Build your first plugin
In this tutorial, you write a plugin that stores the version of a scope in a plain VERSION file, then add a command that prints it. You use it in the project from Release your first package, in place of the npm plugin.
Prerequisites
Section titled “Prerequisites”- The project from Release your first package, at version
1.0.1.
Read the current version
Section titled “Read the current version”A plugin is an object with a name and one function per phase it takes part in. The getCurrentVersion phase returns the current version of each scope.
-
Create
version-file-plugin.tsat the root of the project:version-file-plugin.ts import type { Plugin, ScopeVersionMap, Version } from "@unirelman/core";import { join } from "node:path";const VERSION_FILE_NAME = "VERSION";export const createVersionFilePlugin = (): Plugin => {return {name: "version-file",getCurrentVersion: async (context): Promise<ScopeVersionMap> => {const versions = new Map<string, Version>();for (const [scopeName, scope] of context.scopes) {const filePath = join(scope.path, VERSION_FILE_NAME);const content = await context.fs.read(filePath);versions.set(scopeName, { version: content.trim(), meta: {} });}return versions;},};};context.scopesmaps the name of each scope the plugin is registered for to the scope, andcontext.fsreads files of the project. Phases return their results as maps keyed by scope name. -
Create the
VERSIONfile with the current version:Terminal window echo "1.0.1" > VERSION
Write the next version
Section titled “Write the next version”The generateFileOperations phase returns the file operations of the release. Core applies them, so the plugin describes the file and core writes it.
Add the phase to the plugin:
import type { FileOperation, Plugin, ScopeFileOperationsMap, ScopeVersionMap } from "@unirelman/core";
// ...
export const createVersionFilePlugin = (): Plugin => { return { name: "version-file", getCurrentVersion: async (context): Promise<ScopeVersionMap> => { // ... }, generateFileOperations: async (context, state): Promise<ScopeFileOperationsMap> => { const fileOperations = new Map<string, FileOperation[]>();
for (const [scopeName, scope] of context.scopes) { const nextVersion = state.nextVersions.get(scopeName);
if (nextVersion === undefined) { continue; }
fileOperations.set(scopeName, [ { type: "version-file", path: join(scope.path, VERSION_FILE_NAME), action: "write", content: `${nextVersion.version}\n`, meta: {}, }, ]); }
return fileOperations; }, };};Register the plugin
Section titled “Register the plugin”Replace the npm plugin with yours in unirelman.config.ts:
import { defineConfig } from "@unirelman/cli";import { createChangelogPlugin } from "@unirelman/plugin-changelog";import { createChangesetsPlugin } from "@unirelman/plugin-changesets";import { createGitPlugin } from "@unirelman/plugin-git";import { createNpmPlugin } from "@unirelman/plugin-npm";import { createSemverPlugin } from "@unirelman/plugin-semver";import { createVersionFilePlugin } from "./version-file-plugin.ts";
export default defineConfig({ scopes: { "my-package": "./", }, plugins: [ createChangesetsPlugin(), createChangelogPlugin(), createNpmPlugin({ publish: false }), createVersionFilePlugin(), createGitPlugin(), createSemverPlugin(), ],});Check the plugin with a change and a dry run:
npx unirelman changesets create --scopes my-package --level minor --message "add a feature"pnpm unirelman changesets create --scopes my-package --level minor --message "add a feature"yarn unirelman changesets create --scopes my-package --level minor --message "add a feature"bunx unirelman changesets create --scopes my-package --level minor --message "add a feature"npx unirelman version --dry-run --verbosepnpm unirelman version --dry-run --verboseyarn unirelman version --dry-run --verbosebunx unirelman version --dry-run --verboseThe summary shows my-package: 1.0.1 → 1.1.0, and the logs show Would write VERSION.
Add a command
Section titled “Add a command”A plugin with commands is a CLIPlugin, from @unirelman/cli. Its commands are declared with defineCommand, and the CLI renders their messages and result.
Add a show command that prints the version of a scope:
import type { CLIPlugin } from "@unirelman/cli";
import { defineCommand } from "@unirelman/cli";// ...
export const createVersionFilePlugin = (): CLIPlugin => { return { name: "version-file", commandDescription: "Manage VERSION files", commands: (context) => ({ show: defineCommand({ meta: { name: "show", description: "Print the version of a scope" }, title: "Show version", options: { scope: { type: "string", description: "Scope to show" }, }, run: async ({ options, ui }) => { const scopeName = options.scope ?? (await ui.select({ message: "Select a scope", option: "--scope", options: [...context.scopes.keys()].map((value) => ({ value, label: value })), })); const scope = context.scopes.get(scopeName);
if (scope === undefined) { throw new Error(`Failed to show the version: unknown scope ${scopeName}.`); }
const filePath = join(scope.path, VERSION_FILE_NAME);
return { scope: scopeName, version: (await context.fs.read(filePath)).trim() }; }, success: (result) => ({ summary: [], message: `${result.scope}: ${result.version}` }), }), }), // ... };};Run it:
npx unirelman version-file showpnpm unirelman version-file showyarn unirelman version-file showbunx unirelman version-file showThe command prompts for the scope, then ends with my-package: 1.0.1. With --json, it prints the result as a JSON document instead:
npx unirelman version-file show --scope my-package --jsonpnpm unirelman version-file show --scope my-package --jsonyarn unirelman version-file show --scope my-package --jsonbunx unirelman version-file show --scope my-package --json{ "scope": "my-package", "version": "1.0.1"}Report an error
Section titled “Report an error”Phases and commands report a failure by throwing an error, and the CLI prints it.
-
Add an error class for an empty
VERSIONfile:version-file-plugin.ts export class VersionFileEmptyError extends Error {constructor(scopeName: string) {super(`VERSION file of scope ${scopeName} is empty`);this.name = "VersionFileEmptyError";}} -
Throw it in
getCurrentVersion:version-file-plugin.ts const content = await context.fs.read(filePath);if (content.trim() === "") {throw new VersionFileEmptyError(scopeName);} -
Empty the file and run the pipeline:
Terminal window echo "" > VERSIONTerminal window npx unirelman version --dry-runTerminal window pnpm unirelman version --dry-runTerminal window yarn unirelman version --dry-runTerminal window bunx unirelman version --dry-runThe command fails with the error, prefixed by the plugin and the phase:
Plugin "version-file" failed in the getCurrentVersion phase: VERSION file of scope my-package is empty -
Restore the version:
Terminal window echo "1.0.1" > VERSION
You built a plugin that reads and writes versions, adds a command, and reports errors.