Skip to content

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.

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.

  1. Create version-file-plugin.ts at 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.scopes maps the name of each scope the plugin is registered for to the scope, and context.fs reads files of the project. Phases return their results as maps keyed by scope name.

  2. Create the VERSION file with the current version:

    Terminal window
    echo "1.0.1" > 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:

version-file-plugin.ts
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;
},
};
};

Replace the npm plugin with yours in unirelman.config.ts:

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:

Terminal window
npx unirelman changesets create --scopes my-package --level minor --message "add a feature"
Terminal window
npx unirelman version --dry-run --verbose

The summary shows my-package: 1.0.1 → 1.1.0, and the logs show Would write VERSION.

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:

version-file-plugin.ts
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:

Terminal window
npx unirelman version-file show

The command prompts for the scope, then ends with my-package: 1.0.1. With --json, it prints the result as a JSON document instead:

Terminal window
npx unirelman version-file show --scope my-package --json
{
"scope": "my-package",
"version": "1.0.1"
}

Phases and commands report a failure by throwing an error, and the CLI prints it.

  1. Add an error class for an empty VERSION file:

    version-file-plugin.ts
    export class VersionFileEmptyError extends Error {
    constructor(scopeName: string) {
    super(`VERSION file of scope ${scopeName} is empty`);
    this.name = "VersionFileEmptyError";
    }
    }
  2. Throw it in getCurrentVersion:

    version-file-plugin.ts
    const content = await context.fs.read(filePath);
    if (content.trim() === "") {
    throw new VersionFileEmptyError(scopeName);
    }
  3. Empty the file and run the pipeline:

    Terminal window
    echo "" > VERSION
    Terminal window
    npx unirelman version --dry-run

    The 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
  4. 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.