From 4fa4422bc7874ad794be682b308de078e7809919 Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Thu, 12 Nov 2026 15:53:27 +0100 Subject: [PATCH] Add Changesets mode to create-release-branch Select the mode with --changesets or with "mode": "changesets" in release.config.json. The release spec lists the packages of the pending Changesets with the version specifiers that the Changesets give. The maintainer can leave packages out, but cannot change their versions. Before the Initialize Release commit, the mode checks that the .changeset directory has no uncommitted changes, so that this commit does not take in a Changeset by mistake. The functional tests load the real @metamask/changesets-changelog module from its source. --- packages/create-release-branch/CHANGELOG.md | 1 + packages/create-release-branch/README.md | 2 + packages/create-release-branch/docs/setup.md | 39 + .../src/cli/command-line-arguments.ts | 7 + .../src/cli/initial-parameters.test.ts | 104 +++ .../src/cli/initial-parameters.ts | 13 +- .../src/cli/select.test.ts | 23 + .../create-release-branch/src/cli/select.ts | 4 + .../create-release-branch/src/core/mode.ts | 2 +- .../editor/release-specification.test.ts | 123 +++ .../frontends/editor/release-specification.ts | 86 ++- .../src/functional.test.ts | 699 ++++++++++++++++++ .../modes/changesets/changesets-mode.test.ts | 203 +++++ .../src/modes/changesets/changesets-mode.ts | 89 +++ .../src/project/release-config.test.ts | 30 +- .../functional/helpers/local-monorepo.ts | 91 ++- .../helpers/monorepo-environment.ts | 7 +- 17 files changed, 1501 insertions(+), 22 deletions(-) create mode 100644 packages/create-release-branch/src/modes/changesets/changesets-mode.test.ts create mode 100644 packages/create-release-branch/src/modes/changesets/changesets-mode.ts diff --git a/packages/create-release-branch/CHANGELOG.md b/packages/create-release-branch/CHANGELOG.md index 80ddd003..244223c7 100644 --- a/packages/create-release-branch/CHANGELOG.md +++ b/packages/create-release-branch/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Add Changesets mode: the pending Changesets set the packages and versions in the release spec, and `@metamask/changesets-changelog` writes the changelogs. Choose it with `--changesets` or with `"mode": "changesets"` in `release.config.json` ([#170](https://github.com/MetaMask/release-tools/pull/170)) - Read the release mode from an optional `mode` property in `release.config.json` ([#165](https://github.com/MetaMask/release-tools/pull/165)) ### Changed diff --git a/packages/create-release-branch/README.md b/packages/create-release-branch/README.md index 6472a132..62e6a325 100644 --- a/packages/create-release-branch/README.md +++ b/packages/create-release-branch/README.md @@ -23,6 +23,8 @@ npm install @metamask/create-release-branch --save-dev For more on how to use this tool, please see the [documentation](./docs). +The tool can also release a monorepo with [Changesets](https://github.com/changesets/changesets). See [Changesets mode](./docs/setup.md#changesets-mode). + ## Contributing This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/release-tools#readme). diff --git a/packages/create-release-branch/docs/setup.md b/packages/create-release-branch/docs/setup.md index 95c58cca..e80023d4 100644 --- a/packages/create-release-branch/docs/setup.md +++ b/packages/create-release-branch/docs/setup.md @@ -49,3 +49,42 @@ Combined with the changes above, this might look like: "versioningStrategy": "independent" } ``` + +## Changesets mode + +By default, the tool reads the Git history to write the changelogs. A monorepo with independent versions can use [Changesets](https://github.com/changesets/changesets) instead. In Changesets mode: + +- The pending Changesets in the `.changeset` directory set the packages to release and their new versions. +- The release spec lists these packages, with their version specifiers already filled in. Do not change a specifier. If a specifier gives another version than the Changesets, the tool stops with an error. To keep the Changesets of a package for a later release, remove the package from the release spec. +- The tool writes the changelogs from the Changesets. Then it deletes the Changesets that the release uses. +- The tool does not release the entries in the "Unreleased" section of a changelog. A package without Changesets is not released, even if it has such entries. If a package in the release has such entries, the tool stops with an error. Move the entries into Changesets and commit them, or remove the entries. You can also release them in legacy mode before you use Changesets mode. + +To use Changesets mode, set `mode` to `"changesets"` in `release.config.json`: + +``` +# release.config.json +{ + "versioningStrategy": "independent", + "mode": "changesets" +} +``` + +You can also run the tool with the `--changesets` flag. The flag selects Changesets mode for one run, whatever `mode` is set to. + +Changesets mode has these requirements: + +- The project must have a `.changeset/config.json` file that uses the `@metamask/changesets-changelog` changelog module. Give the module the GitHub repository of the project: + + ```json + { + "changelog": [ + "@metamask/changesets-changelog", + { "repository": "/" } + ] + } + ``` + +- Each Changeset summary must have one category heading and one entry, such as `## Added` followed by `- Add a feature`. If the subject of the commit that adds a Changeset ends with a pull request number, such as `Add a feature (#123)`, the changelog entry links to this pull request. If the subject has no pull request number, for example for a Changeset that you commit on the release branch, the entry has no link. Add the link by hand. +- Changesets pre mode must be off. To exit pre mode, run `changeset pre exit`. +- The `.changeset` directory must not have uncommitted changes. The tool checks this before it makes the first commit of the release, and again before it writes the release. +- The interactive UI (`--interactive`) does not support Changesets mode yet. Edit the release spec in your editor instead. diff --git a/packages/create-release-branch/src/cli/command-line-arguments.ts b/packages/create-release-branch/src/cli/command-line-arguments.ts index e83b712b..9f642dd2 100644 --- a/packages/create-release-branch/src/cli/command-line-arguments.ts +++ b/packages/create-release-branch/src/cli/command-line-arguments.ts @@ -8,6 +8,7 @@ export type CommandLineArguments = { backport: boolean; defaultBranch: string; interactive: boolean; + changesets: boolean; port: number; formatter: string; }; @@ -61,6 +62,12 @@ export async function readCommandLineArguments( type: 'boolean', default: false, }) + .option('changesets', { + describe: + 'Release with Changesets: the pending Changesets set the packages and versions, and write the changelogs. Overrides the "mode" in release.config.json.', + type: 'boolean', + default: false, + }) .option('port', { describe: 'Port to run the interactive web UI server (only used with --interactive)', diff --git a/packages/create-release-branch/src/cli/initial-parameters.test.ts b/packages/create-release-branch/src/cli/initial-parameters.test.ts index f2cae355..42d7d0fa 100644 --- a/packages/create-release-branch/src/cli/initial-parameters.test.ts +++ b/packages/create-release-branch/src/cli/initial-parameters.test.ts @@ -41,6 +41,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -82,6 +83,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -111,6 +113,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -142,6 +145,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -173,6 +177,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -202,6 +207,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -231,6 +237,7 @@ describe('initial-parameters', () => { backport: true, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -260,6 +267,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -289,6 +297,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: true, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -318,6 +327,7 @@ describe('initial-parameters', () => { backport: false, defaultBranch: 'main', interactive: false, + changesets: false, port: 3000, formatter: 'prettier', }); @@ -335,5 +345,99 @@ describe('initial-parameters', () => { expect(initialParameters.frontEndName).toBe('editor'); }); + + describe('when choosing the mode', () => { + /** + * Mocks the command-line arguments and the project. + * + * @param overrides - The arguments that differ from the defaults. + * @param overrides.changesets - Whether `--changesets` is given. + * @param overrides.interactive - Whether `--interactive` is given. + */ + function mockInputs(overrides: { + changesets: boolean; + interactive: boolean; + }): void { + vi.when( + vi.spyOn(commandLineArgumentsModule, 'readCommandLineArguments'), + ) + .calledWith(['arg1', 'arg2']) + .thenResolve({ + projectDirectory: '/path/to/project', + tempDirectory: '/path/to/temp', + reset: false, + backport: false, + defaultBranch: 'main', + port: 3000, + formatter: 'prettier', + ...overrides, + }); + vi.spyOn(envModule, 'getEnvironmentVariables').mockReturnValue({ + EDITOR: undefined, + }); + vi.spyOn(projectModule, 'readProject').mockResolvedValue( + buildMockProject(), + ); + } + + it('uses the mode of the release config', async () => { + mockInputs({ changesets: false, interactive: false }); + vi.when(vi.spyOn(releaseConfigModule, 'readReleaseConfig')) + .calledWith('/path/to/project') + .thenResolve({ mode: 'changesets' }); + + const initialParameters = await determineInitialParameters({ + argv: ['arg1', 'arg2'], + cwd: '/path/to/somewhere', + }); + + expect(initialParameters.modeName).toBe('changesets'); + }); + + it('uses Changesets mode if --changesets is given, without reading the release config', async () => { + mockInputs({ changesets: true, interactive: false }); + const readReleaseConfigSpy = vi.spyOn( + releaseConfigModule, + 'readReleaseConfig', + ); + + const initialParameters = await determineInitialParameters({ + argv: ['arg1', 'arg2'], + cwd: '/path/to/somewhere', + }); + + expect(initialParameters.modeName).toBe('changesets'); + expect(readReleaseConfigSpy).not.toHaveBeenCalled(); + }); + + it('throws if --interactive is given with --changesets', async () => { + mockInputs({ changesets: true, interactive: true }); + + await expect( + determineInitialParameters({ + argv: ['arg1', 'arg2'], + cwd: '/path/to/somewhere', + }), + ).rejects.toThrow( + 'The interactive UI does not support Changesets mode yet.', + ); + }); + + it('throws if --interactive is given and the release config uses Changesets mode', async () => { + mockInputs({ changesets: false, interactive: true }); + vi.spyOn(releaseConfigModule, 'readReleaseConfig').mockResolvedValue({ + mode: 'changesets', + }); + + await expect( + determineInitialParameters({ + argv: ['arg1', 'arg2'], + cwd: '/path/to/somewhere', + }), + ).rejects.toThrow( + 'The interactive UI does not support Changesets mode yet.\nRun this tool without --interactive to edit the release spec in your editor.', + ); + }); + }); }); }); diff --git a/packages/create-release-branch/src/cli/initial-parameters.ts b/packages/create-release-branch/src/cli/initial-parameters.ts index 7aabec1c..616ef0d6 100644 --- a/packages/create-release-branch/src/cli/initial-parameters.ts +++ b/packages/create-release-branch/src/cli/initial-parameters.ts @@ -28,6 +28,7 @@ type InitialParameters = { * @param args.argv - The arguments to this executable. * @param args.cwd - The directory in which this executable was run. * @returns The initial parameters. + * @throws If the interactive UI is asked for in Changesets mode. */ export async function determineInitialParameters({ argv, @@ -40,7 +41,17 @@ export async function determineInitialParameters({ const projectDirectoryPath = path.resolve(cwd, args.projectDirectory); const project = await readProject(projectDirectoryPath); - const { mode: modeName } = await readReleaseConfig(projectDirectoryPath); + const modeName: ModeName = args.changesets + ? 'changesets' + : (await readReleaseConfig(projectDirectoryPath)).mode; + if (modeName === 'changesets' && args.interactive) { + throw new Error( + [ + 'The interactive UI does not support Changesets mode yet.', + 'Run this tool without --interactive to edit the release spec in your editor.', + ].join('\n'), + ); + } const tempDirectoryPath = args.tempDirectory === undefined ? path.join( diff --git a/packages/create-release-branch/src/cli/select.test.ts b/packages/create-release-branch/src/cli/select.test.ts index 18c1ac6b..70f552b6 100644 --- a/packages/create-release-branch/src/cli/select.test.ts +++ b/packages/create-release-branch/src/cli/select.test.ts @@ -5,11 +5,13 @@ import type { FrontEnd } from '../core/front-end.js'; import type { Mode } from '../core/mode.js'; import * as editorFrontEndModule from '../frontends/editor/editor-front-end.js'; import * as uiFrontEndModule from '../frontends/ui/server.js'; +import * as changesetsModeModule from '../modes/changesets/changesets-mode.js'; import * as legacyModeModule from '../modes/legacy/legacy-mode.js'; import { selectFrontEnd, selectMode } from './select.js'; vi.mock('../frontends/editor/editor-front-end'); vi.mock('../frontends/ui/server'); +vi.mock('../modes/changesets/changesets-mode'); vi.mock('../modes/legacy/legacy-mode'); describe('select', () => { @@ -34,6 +36,27 @@ describe('select', () => { }); expect(mode).toBe(legacyMode); }); + + it('selectMode returns the Changesets mode', () => { + const project = buildMockProject(); + const changesetsMode = { name: 'changesets' } as Mode; + const createChangesetsModeSpy = vi + .spyOn(changesetsModeModule, 'createChangesetsMode') + .mockReturnValue(changesetsMode); + + const mode = selectMode('changesets', { + project, + defaultBranch: 'main', + formatter: 'prettier', + }); + + expect(createChangesetsModeSpy).toHaveBeenCalledWith({ + project, + defaultBranch: 'main', + formatter: 'prettier', + }); + expect(mode).toBe(changesetsMode); + }); }); describe('selectFrontEnd', () => { diff --git a/packages/create-release-branch/src/cli/select.ts b/packages/create-release-branch/src/cli/select.ts index 759100ae..d128c8d6 100644 --- a/packages/create-release-branch/src/cli/select.ts +++ b/packages/create-release-branch/src/cli/select.ts @@ -5,6 +5,7 @@ import type { Mode, ModeName } from '../core/mode.js'; import type { Formatter } from '../core/types.js'; import { createEditorFrontEnd } from '../frontends/editor/editor-front-end.js'; import { createUIFrontEnd } from '../frontends/ui/server.js'; +import { createChangesetsMode } from '../modes/changesets/changesets-mode.js'; import { createLegacyMode } from '../modes/legacy/legacy-mode.js'; import type { Project } from '../project/project.js'; @@ -30,6 +31,9 @@ export function selectMode( case 'legacy': return createLegacyMode(options); + case 'changesets': + return createChangesetsMode(options); + default: return assertExhaustive(name); } diff --git a/packages/create-release-branch/src/core/mode.ts b/packages/create-release-branch/src/core/mode.ts index 144c8b7b..5d72d6df 100644 --- a/packages/create-release-branch/src/core/mode.ts +++ b/packages/create-release-branch/src/core/mode.ts @@ -5,7 +5,7 @@ import type { ReleaseChoiceError, ReleaseChoices } from './release-rules.js'; /** * The names of the release modes. */ -export const MODE_NAMES = ['legacy'] as const; +export const MODE_NAMES = ['legacy', 'changesets'] as const; /** * The name of a release mode. diff --git a/packages/create-release-branch/src/frontends/editor/release-specification.test.ts b/packages/create-release-branch/src/frontends/editor/release-specification.test.ts index 2bd71fc7..ecccb735 100644 --- a/packages/create-release-branch/src/frontends/editor/release-specification.test.ts +++ b/packages/create-release-branch/src/frontends/editor/release-specification.test.ts @@ -195,6 +195,129 @@ packages: }); }); + describe('generateReleaseSpecificationTemplateForMonorepo in Changesets mode', () => { + const CHANGESETS_INSTRUCTIONS = ` +# This file (called the "release spec") allows you to specify which packages you +# want to include in this release along with the new versions they should +# receive. +# +# The packages below have pending Changesets, or are bumped because a package +# they depend on is released. The value after each package is the version +# specifier that the Changesets give, and the comment after it shows the new +# version. Do not change the value. In Changesets mode, the Changesets set the +# version of each package. +# +# To leave a package out of this release, remove it from this list. Its +# Changesets are kept for a later release. +#`.trim(); + + it('sets each package to the bump that the Changesets give, and describes it in a comment', async () => { + const template = await generateReleaseSpecificationTemplateForMonorepo({ + modeName: 'changesets', + candidates: [ + { + name: '@scope/a', + currentVersion: '1.4.0', + plannedVersion: '2.0.0', + kind: 'changes', + changeCount: 3, + }, + { + name: '@scope/b', + currentVersion: '0.1.0', + plannedVersion: '0.2.0', + kind: 'changes', + changeCount: 1, + }, + { + name: '@scope/c', + currentVersion: '1.4.0', + plannedVersion: '1.4.1', + kind: 'dependency', + }, + ], + isEditorAvailable: true, + }); + + expect(template).toBe( + `${CHANGESETS_INSTRUCTIONS} +# When you're finished, save this file and close it. The tool will update the +# versions of the packages you've listed, write their changelogs from the +# Changesets, and delete the Changesets that the release uses. + +packages: + "@scope/a": major # 1.4.0 -> 2.0.0, 3 changesets + "@scope/b": minor # 0.1.0 -> 0.2.0, 1 changeset + "@scope/c": patch # 1.4.0 -> 1.4.1 +`, + ); + expect(YAML.parse(template)).toStrictEqual({ + packages: { + '@scope/a': 'major', + '@scope/b': 'minor', + '@scope/c': 'patch', + }, + }); + }); + + it('sets a package to its planned version if no bump type gives it', async () => { + const template = await generateReleaseSpecificationTemplateForMonorepo({ + modeName: 'changesets', + candidates: [ + { + name: '@scope/a', + currentVersion: '1.0.0', + plannedVersion: '2.5.0', + kind: 'dependency', + }, + ], + isEditorAvailable: true, + }); + + expect(template).toContain(' "@scope/a": 2.5.0 # 1.0.0 -> 2.5.0\n'); + }); + + it('adjusts the instructions slightly if an editor is not available', async () => { + const template = await generateReleaseSpecificationTemplateForMonorepo({ + modeName: 'changesets', + candidates: [ + { + name: '@scope/a', + currentVersion: '1.0.0', + plannedVersion: '1.1.0', + kind: 'changes', + changeCount: 2, + }, + ], + isEditorAvailable: false, + }); + + expect(template).toBe( + `${CHANGESETS_INSTRUCTIONS} +# When you're finished, save this file and then run create-release-branch again. +# The tool will update the versions of the packages you've listed, write their +# changelogs from the Changesets, and delete the Changesets that the release +# uses. + +packages: + "@scope/a": minor # 1.0.0 -> 1.1.0, 2 changesets +`, + ); + }); + + it('throws if there is no package to release', async () => { + await expect( + generateReleaseSpecificationTemplateForMonorepo({ + modeName: 'changesets', + candidates: [], + isEditorAvailable: true, + }), + ).rejects.toThrow( + 'Could not generate release specification: There are no pending Changesets.', + ); + }); + }); + describe('waitForUserToEditReleaseSpecification', () => { it('waits for the given editor command to complete successfully', async () => { const releaseSpecificationPath = '/path/to/release-spec'; diff --git a/packages/create-release-branch/src/frontends/editor/release-specification.ts b/packages/create-release-branch/src/frontends/editor/release-specification.ts index 7636e8dc..4a4f7963 100644 --- a/packages/create-release-branch/src/frontends/editor/release-specification.ts +++ b/packages/create-release-branch/src/frontends/editor/release-specification.ts @@ -1,4 +1,4 @@ -import YAML, { YAMLParseError } from 'yaml'; +import YAML, { YAMLMap, YAMLParseError } from 'yaml'; import type { Candidate } from '../../core/candidates.js'; import type { CliOutput } from '../../core/cli-output.js'; @@ -17,6 +17,7 @@ import { isObject, runCommand, } from '../../utils/misc-utils.js'; +import { semver, SemVer } from '../../utils/semver.js'; import { Editor } from './editor.js'; /** @@ -76,8 +77,72 @@ const TEMPLATE_TEXT_BY_MODE: Record = { noCandidatesMessage: 'Could not generate release specification: There are no packages that have changed since their latest release.', }, + changesets: { + instructions: ` +# This file (called the "release spec") allows you to specify which packages you +# want to include in this release along with the new versions they should +# receive. +# +# The packages below have pending Changesets, or are bumped because a package +# they depend on is released. The value after each package is the version +# specifier that the Changesets give, and the comment after it shows the new +# version. Do not change the value. In Changesets mode, the Changesets set the +# version of each package. +# +# To leave a package out of this release, remove it from this list. Its +# Changesets are kept for a later release. +#`.trim(), + afterEditingWithEditor: ` +# When you're finished, save this file and close it. The tool will update the +# versions of the packages you've listed, write their changelogs from the +# Changesets, and delete the Changesets that the release uses.`.trim(), + afterEditingWithoutEditor: ` +# When you're finished, save this file and then run create-release-branch again. +# The tool will update the versions of the packages you've listed, write their +# changelogs from the Changesets, and delete the Changesets that the release +# uses.`.trim(), + noCandidatesMessage: + 'Could not generate release specification: There are no pending Changesets.', + }, }; +/** + * Proposes the version specifier of a candidate: the bump type that gives its + * planned version, or else the planned version. + * + * @param candidate - The candidate. + * @returns The version specifier, or `null` if no version is planned. + */ +function proposeVersionSpecifier(candidate: Candidate): string | null { + const { currentVersion, plannedVersion } = candidate; + if (plannedVersion === undefined) { + return SKIP_PACKAGE_DIRECTIVE; + } + const bump = semver.diff(currentVersion, plannedVersion); + return (bump === 'major' || bump === 'minor' || bump === 'patch') && + new SemVer(currentVersion).inc(bump).version === plannedVersion + ? bump + : plannedVersion; +} + +/** + * Describes a candidate in the comment after its line in the release spec. + * + * @param candidate - The candidate. + * @returns The comment, or undefined if there is nothing to say. + */ +function describeCandidate(candidate: Candidate): string | undefined { + const { currentVersion, plannedVersion, changeCount } = candidate; + if (plannedVersion === undefined) { + return undefined; + } + const versions = `${currentVersion} -> ${plannedVersion}`; + if (changeCount === undefined) { + return versions; + } + return `${versions}, ${changeCount} ${changeCount === 1 ? 'changeset' : 'changesets'}`; +} + /** * A problem in the release spec. * @@ -167,7 +232,8 @@ export class ReleaseSpecificationError extends UserFacingError { * @param args - The set of arguments to this function. * @param args.modeName - The name of the release mode, which picks the * instructions and the error message when there are no packages. - * @param args.candidates - The packages to list in the release spec. + * @param args.candidates - The packages to list in the release spec, with + * their proposed version specifiers. * @param args.isEditorAvailable - Whether or not an executable can be found on * the user's computer to edit the release spec once it is generated. * @returns The release specification template. @@ -194,11 +260,19 @@ export async function generateReleaseSpecificationTemplateForMonorepo({ throw new Error(templateText.noCandidatesMessage); } - const packages = candidates.reduce((obj, candidate) => { - return { ...obj, [candidate.name]: SKIP_PACKAGE_DIRECTIVE }; - }, {}); + const document = new YAML.Document({}); + const packages = new YAMLMap(); + for (const candidate of candidates) { + const value = document.createNode(proposeVersionSpecifier(candidate)); + const comment = describeCandidate(candidate); + if (comment !== undefined) { + value.comment = ` ${comment}`; + } + packages.add(document.createPair(candidate.name, value)); + } + document.set('packages', packages); - return [instructions, YAML.stringify({ packages })].join('\n\n'); + return [instructions, document.toString()].join('\n\n'); } /** diff --git a/packages/create-release-branch/src/functional.test.ts b/packages/create-release-branch/src/functional.test.ts index eb93ad41..fc1aabb7 100644 --- a/packages/create-release-branch/src/functional.test.ts +++ b/packages/create-release-branch/src/functional.test.ts @@ -1,8 +1,265 @@ import { describe, expect, it } from 'vitest'; +import type { ChangesetSpecification } from '../tests/functional/helpers/local-monorepo.js'; +import type MonorepoEnvironment from '../tests/functional/helpers/monorepo-environment.js'; import { withMonorepoProjectEnvironment } from '../tests/functional/helpers/with.js'; import { buildChangelog } from '../tests/helpers.js'; +type ChangesetsPackageNickname = 'a' | 'b' | 'c' | 'd' | 'l'; + +const REPOSITORY_URL = 'https://github.com/example-org/example-repo'; + +/** + * The pull request of the commit that adds the Changesets, which their + * changelog entries link to. + */ +const SETUP_PULL_REQUEST = 20; + +/** + * Builds a link to a pull request of the repository of the functional tests. + * + * @param pullRequest - The number of the pull request. + * @returns The Markdown link. + */ +function pullRequestLink(pullRequest: number): string { + return `[#${pullRequest}](${REPOSITORY_URL}/pull/${pullRequest})`; +} + +/** + * Builds the lockfile of the Changesets monorepo. + * + * @param rangeOfB - The range of `@scope/b` that `@scope/c` depends on. + * @returns The content of `yarn.lock`. + */ +function buildChangesetsMonorepoLockfile(rangeOfB: string): string { + const workspaceEntry = ( + name: string, + directoryPath: string, + extraLines: string[] = [], + ): string[] => [ + ` version: 0.0.0-use.local`, + ` resolution: "${name}@workspace:${directoryPath}"`, + ...extraLines, + ' languageName: unknown', + ' linkType: soft', + ]; + return [ + '# This file is generated by running "yarn install" inside your project.', + '# Manual changes might be lost - proceed with caution!', + '', + '__metadata:', + ' version: 6', + '', + '"@scope/a@workspace:packages/a":', + ...workspaceEntry('@scope/a', 'packages/a'), + '', + `"@scope/b@${rangeOfB}, @scope/b@workspace:packages/b":`, + ...workspaceEntry('@scope/b', 'packages/b'), + '', + '"@scope/c@workspace:packages/c":', + ...workspaceEntry('@scope/c', 'packages/c', [ + ' dependencies:', + ` "@scope/b": ${rangeOfB}`, + ]), + '', + '"@scope/d@workspace:packages/d":', + ...workspaceEntry('@scope/d', 'packages/d'), + '', + '"@scope/l@workspace:packages/l":', + ...workspaceEntry('@scope/l', 'packages/l'), + '', + '"@scope/monorepo@workspace:.":', + ...workspaceEntry('@scope/monorepo', '.'), + '', + ].join('\n'); +} + +/** + * The Changeset that releases `@scope/a` and `@scope/d`. + */ +const SHARED_CHANGESET: ChangesetSpecification = { + id: 'eager-owls-fly', + releases: { '@scope/a': 'patch', '@scope/d': 'minor' }, + summary: '## Fixed\n\n- Fix a and extend d', +}; + +/** + * Builds a monorepo that uses Changesets and commits all of its files, then + * calls the given function with it. The monorepo has: + * + * - `a`, released by a minor Changeset, with an empty `Unreleased` section; + * - `b`, released by a major Changeset, without a changelog; + * - `c`, which depends on `b`, with an empty `Unreleased` section; + * - `d`, released with `a` by a shared Changeset; + * - `l`, which only has hand-written `Unreleased` entries. + * + * @param options - The options. + * @param options.changesets - Changesets to add to the default ones. + * @param options.files - Other files to write, by path relative to the root. + * @param callback - The function to call with the environment. + * @returns Whatever the callback returns. + */ +async function withChangesetsMonorepo( + { + changesets = [], + files = {}, + }: { + changesets?: ChangesetSpecification[]; + files?: Record; + }, + callback: ( + environment: MonorepoEnvironment, + ) => Promise, +): Promise { + return await withMonorepoProjectEnvironment( + { + packages: { + $root$: { + name: '@scope/monorepo', + version: '1.0.0', + directoryPath: '.', + }, + a: { name: '@scope/a', version: '1.0.0', directoryPath: 'packages/a' }, + b: { name: '@scope/b', version: '1.0.0', directoryPath: 'packages/b' }, + c: { name: '@scope/c', version: '1.0.0', directoryPath: 'packages/c' }, + d: { name: '@scope/d', version: '0.1.0', directoryPath: 'packages/d' }, + l: { name: '@scope/l', version: '1.0.0', directoryPath: 'packages/l' }, + }, + workspaces: { + '.': ['packages/*'], + }, + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor' }, + summary: '## Added\n\n- Add a feature to a', + }, + { + id: 'calm-dogs-run', + releases: { '@scope/b': 'major' }, + summary: '## Removed\n\n- Remove the old API of b', + }, + SHARED_CHANGESET, + ...changesets, + ], + createInitialCommit: false, + }, + async (environment) => { + await environment.writeFileWithinPackage( + 'a', + 'CHANGELOG.md', + buildChangelog(` + ## [Unreleased] + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [Unreleased]: ${REPOSITORY_URL}/compare/@scope/a@1.0.0...HEAD + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/a@1.0.0 + `), + ); + await environment.updateJsonFileWithinPackage('c', 'package.json', { + dependencies: { '@scope/b': '^1.0.0' }, + }); + await environment.writeFileWithinPackage( + 'c', + 'CHANGELOG.md', + buildChangelog(` + ## [Unreleased] + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [Unreleased]: ${REPOSITORY_URL}/compare/@scope/c@1.0.0...HEAD + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/c@1.0.0 + `), + ); + await environment.writeFileWithinPackage( + 'l', + 'CHANGELOG.md', + buildChangelog(` + ## [Unreleased] + + ### Fixed + + - Fix a legacy bug in l (${pullRequestLink(2)}) + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [Unreleased]: ${REPOSITORY_URL}/compare/@scope/l@1.0.0...HEAD + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/l@1.0.0 + `), + ); + await environment.writeFile( + 'yarn.lock', + buildChangesetsMonorepoLockfile('^1.0.0'), + ); + for (const [filePath, content] of Object.entries(files)) { + await environment.writeFile(filePath, content); + } + await environment.createCommit( + `Set up the monorepo (#${SETUP_PULL_REQUEST})`, + ); + return await callback(environment); + }, + ); +} + +/** + * Reads the subjects of the latest commits, newest first. + * + * @param environment - The environment. + * @param count - The number of commits to read. + * @returns The subjects. + */ +async function readLatestCommitSubjects( + environment: MonorepoEnvironment, + count: number, +): Promise { + const { stdout } = await environment.runCommand('git', [ + 'log', + '--pretty=%s', + `--max-count=${count}`, + ]); + return stdout.split('\n'); +} + +/** + * Lists the files in the `.changeset` directory. + * + * @param environment - The environment. + * @returns The file names, sorted. + */ +async function listChangesetDirectory( + environment: MonorepoEnvironment, +): Promise { + const { stdout } = await environment.runCommand('ls', ['.changeset']); + return stdout.split('\n'); +} + +/** + * Reads the status of the working tree. + * + * @param environment - The environment. + * @returns The output of `git status --porcelain`. + */ +async function readStatus( + environment: MonorepoEnvironment, +): Promise { + return (await environment.runCommand('git', ['status', '--porcelain'])) + .stdout; +} + describe('create-release-branch (functional)', () => { describe('against a monorepo with independent versions', () => { it('bumps the ordinary part of the root package and updates the versions of the specified packages according to the release spec', async () => { @@ -1065,4 +1322,446 @@ __metadata: ); }); }); + + describe('against a monorepo using Changesets', () => { + it('releases every pending Changeset, then commits the release', async () => { + await withChangesetsMonorepo({}, async (environment) => { + const rootChangelogBefore = await environment.readFile('CHANGELOG.md'); + const changelogOfLBefore = await environment.readFileWithinPackage( + 'l', + 'CHANGELOG.md', + ); + + await environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { + a: 'minor', + b: 'major', + c: 'patch', + d: 'minor', + }, + }, + }); + + expect(await environment.readJsonFile('package.json')).toMatchObject({ + name: '@scope/monorepo', + version: '2.0.0', + }); + expect(await environment.readFile('CHANGELOG.md')).toBe( + rootChangelogBefore, + ); + expect( + await environment.readJsonFileWithinPackage('a', 'package.json'), + ).toStrictEqual({ name: '@scope/a', version: '1.1.0' }); + expect( + await environment.readJsonFileWithinPackage('b', 'package.json'), + ).toStrictEqual({ name: '@scope/b', version: '2.0.0' }); + expect( + await environment.readJsonFileWithinPackage('c', 'package.json'), + ).toStrictEqual({ + name: '@scope/c', + version: '1.0.1', + dependencies: { '@scope/b': '^2.0.0' }, + }); + expect( + await environment.readJsonFileWithinPackage('d', 'package.json'), + ).toStrictEqual({ name: '@scope/d', version: '0.2.0' }); + expect( + await environment.readJsonFileWithinPackage('l', 'package.json'), + ).toStrictEqual({ name: '@scope/l', version: '1.0.0' }); + + expect( + await environment.readFileWithinPackage('a', 'CHANGELOG.md'), + ).toStrictEqual( + buildChangelog(` + ## [1.1.0] + + ### Added + + - Add a feature to a (${pullRequestLink(SETUP_PULL_REQUEST)}) + + ### Fixed + + - Fix a and extend d (${pullRequestLink(SETUP_PULL_REQUEST)}) + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [1.1.0]: ${REPOSITORY_URL}/compare/@scope/a@1.0.0...@scope/a@1.1.0 + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/a@1.0.0 + `), + ); + expect( + await environment.readFileWithinPackage('b', 'CHANGELOG.md'), + ).toStrictEqual( + buildChangelog(` + ## [2.0.0] + + ### Removed + + - **BREAKING:** Remove the old API of b (${pullRequestLink(SETUP_PULL_REQUEST)}) + + [2.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/b@2.0.0 + `), + ); + expect( + await environment.readFileWithinPackage('c', 'CHANGELOG.md'), + ).toStrictEqual( + buildChangelog(` + ## [1.0.1] + + ### Changed + + - Bump \`@scope/b\` from \`1.0.0\` to \`2.0.0\` + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [1.0.1]: ${REPOSITORY_URL}/compare/@scope/c@1.0.0...@scope/c@1.0.1 + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/c@1.0.0 + `), + ); + expect( + await environment.readFileWithinPackage('l', 'CHANGELOG.md'), + ).toBe(changelogOfLBefore); + + expect(await listChangesetDirectory(environment)).toStrictEqual([ + 'config.json', + ]); + expect(await environment.readFile('yarn.lock')).toStrictEqual( + buildChangesetsMonorepoLockfile('^2.0.0'), + ); + expect(await readLatestCommitSubjects(environment, 2)).toStrictEqual([ + 'Update Release 2.0.0', + 'Initialize Release 2.0.0', + ]); + expect( + ( + await environment.runCommand('git', [ + 'rev-parse', + '--abbrev-ref', + 'HEAD', + ]) + ).stdout, + ).toBe('release/2.0.0'); + expect(await readStatus(environment)).toBe(''); + }); + }); + + it('keeps the Changesets of a package that the release spec leaves out', async () => { + await withChangesetsMonorepo({}, async (environment) => { + await environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { + a: 'minor', + b: 'major', + c: 'patch', + }, + }, + }); + + expect( + await environment.readJsonFileWithinPackage('a', 'package.json'), + ).toStrictEqual({ name: '@scope/a', version: '1.1.0' }); + expect( + await environment.readJsonFileWithinPackage('d', 'package.json'), + ).toStrictEqual({ name: '@scope/d', version: '0.1.0' }); + expect( + await environment.readJsonFileWithinPackage('l', 'package.json'), + ).toStrictEqual({ name: '@scope/l', version: '1.0.0' }); + expect(await listChangesetDirectory(environment)).toStrictEqual([ + 'config.json', + 'eager-owls-fly.md', + ]); + expect(await environment.readFile('.changeset/eager-owls-fly.md')).toBe( + `---\n"@scope/d": minor\n---\n${SHARED_CHANGESET.summary}`, + ); + expect(await readStatus(environment)).toBe(''); + }); + }); + + it('stops if the release spec changes the version that the Changesets give, and changes no package', async () => { + await withChangesetsMonorepo({}, async (environment) => { + const changesetsBefore = await listChangesetDirectory(environment); + + const promise = environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { + a: 'major', + b: 'major', + c: 'patch', + d: 'minor', + }, + }, + }); + + await expect(promise).rejects.toThrow( + /is set to major, but the Changesets release it as 1\.1\.0/u, + ); + expect( + await environment.readJsonFileWithinPackage('a', 'package.json'), + ).toStrictEqual({ name: '@scope/a', version: '1.0.0' }); + expect(await listChangesetDirectory(environment)).toStrictEqual( + changesetsBefore, + ); + }); + }); + + it('stops if a released package has entries in Unreleased, and changes no package', async () => { + const changelogOfA = buildChangelog(` + ## [Unreleased] + + ### Added + + - Add a legacy feature to a (${pullRequestLink(1)}) + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [Unreleased]: ${REPOSITORY_URL}/compare/@scope/a@1.0.0...HEAD + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/a@1.0.0 + `); + await withChangesetsMonorepo( + { files: { 'packages/a/CHANGELOG.md': changelogOfA } }, + async (environment) => { + const changesetsBefore = await listChangesetDirectory(environment); + + const promise = environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { + a: 'minor', + b: 'major', + c: 'patch', + d: 'minor', + }, + }, + }); + + await expect(promise).rejects.toThrow( + /1 changelog has entries in Unreleased:/u, + ); + expect( + await environment.readJsonFileWithinPackage('a', 'package.json'), + ).toStrictEqual({ name: '@scope/a', version: '1.0.0' }); + expect( + await environment.readFileWithinPackage('a', 'CHANGELOG.md'), + ).toBe(changelogOfA); + expect(await listChangesetDirectory(environment)).toStrictEqual( + changesetsBefore, + ); + }, + ); + }); + + it('stops before the first commit of the release if the .changeset directory has uncommitted changes', async () => { + await withChangesetsMonorepo({}, async (environment) => { + await environment.writeFile( + '.changeset/quiet-foxes-hide.md', + '---\n"@scope/a": patch\n---\n\n## Fixed\n\n- Fix a again\n', + ); + + const promise = environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { a: 'minor', b: 'major', c: 'patch', d: 'minor' }, + }, + }); + + await expect(promise).rejects.toThrow( + /The \.changeset directory has uncommitted changes\./u, + ); + expect(await readLatestCommitSubjects(environment, 1)).toStrictEqual([ + `Set up the monorepo (#${SETUP_PULL_REQUEST})`, + ]); + expect(await readStatus(environment)).toBe( + '?? .changeset/quiet-foxes-hide.md', + ); + }); + }); + + it('releases a committed Changeset whose commit has no pull request number, without a link', async () => { + await withChangesetsMonorepo({}, async (environment) => { + await environment.writeFile( + '.changeset/quiet-foxes-hide.md', + '---\n"@scope/a": patch\n---\n\n## Fixed\n\n- Fix a again\n', + ); + await environment.createCommit('Add a Changeset for a'); + + await environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { a: 'minor', b: 'major', c: 'patch', d: 'minor' }, + }, + }); + + expect( + await environment.readFileWithinPackage('a', 'CHANGELOG.md'), + ).toContain('- Fix a again\n'); + expect(await listChangesetDirectory(environment)).toStrictEqual([ + 'config.json', + ]); + }); + }); + + it('uses Changesets mode if release.config.json asks for it', async () => { + await withChangesetsMonorepo( + { files: { 'release.config.json': '{ "mode": "changesets" }\n' } }, + async (environment) => { + await environment.runTool({ + releaseSpecification: { + packages: { + a: 'minor', + b: 'major', + c: 'patch', + d: 'minor', + }, + }, + }); + + expect( + await environment.readJsonFileWithinPackage('b', 'package.json'), + ).toStrictEqual({ name: '@scope/b', version: '2.0.0' }); + expect(await listChangesetDirectory(environment)).toStrictEqual([ + 'config.json', + ]); + }, + ); + }); + + it('stops with the recovery command if the release cannot be applied, and changes no file', async () => { + await withChangesetsMonorepo( + { + changesets: [ + { + id: 'sharp-bees-buzz', + releases: { '@scope/a': 'patch' }, + summary: 'A summary without a category', + }, + ], + }, + async (environment) => { + const changesetsBefore = await listChangesetDirectory(environment); + + const promise = environment.runTool({ + args: ['--changesets'], + releaseSpecification: { + packages: { + a: 'minor', + b: 'major', + c: 'patch', + d: 'minor', + }, + }, + }); + + await expect(promise).rejects.toThrow( + /The release could not be applied\./u, + ); + await expect(promise).rejects.toThrow( + /git stash --include-untracked/u, + ); + expect(await listChangesetDirectory(environment)).toStrictEqual( + changesetsBefore, + ); + expect( + await environment.readJsonFileWithinPackage('a', 'package.json'), + ).toStrictEqual({ name: '@scope/a', version: '1.0.0' }); + // The temporary directory keeps the release spec for the next run. + expect(await readStatus(environment)).toBe('?? tmp/'); + }, + ); + }); + + it('follows the legacy workflow if Changesets mode is not chosen', async () => { + await withChangesetsMonorepo({}, async (environment) => { + const changesetsBefore = await listChangesetDirectory(environment); + + await environment.runTool({ + releaseSpecification: { + packages: { + a: 'minor', + l: 'patch', + }, + }, + }); + + expect( + await environment.readJsonFileWithinPackage('a', 'package.json'), + ).toStrictEqual({ name: '@scope/a', version: '1.1.0' }); + expect( + await environment.readJsonFileWithinPackage('b', 'package.json'), + ).toStrictEqual({ name: '@scope/b', version: '1.0.0' }); + expect( + await environment.readFileWithinPackage('a', 'CHANGELOG.md'), + ).toStrictEqual( + buildChangelog(` + ## [Unreleased] + + ## [1.1.0] + + ### Uncategorized + + - Set up the monorepo (${pullRequestLink(20)}) + + ## [1.0.0] + + ### Added + + - Initial release (${pullRequestLink(0)}) + + [Unreleased]: ${REPOSITORY_URL}/compare/@scope/a@1.1.0...HEAD + [1.1.0]: ${REPOSITORY_URL}/compare/@scope/a@1.0.0...@scope/a@1.1.0 + [1.0.0]: ${REPOSITORY_URL}/releases/tag/@scope/a@1.0.0 + `), + ); + expect(await listChangesetDirectory(environment)).toStrictEqual( + changesetsBefore, + ); + }); + }); + + it('fails without changing the working tree if --interactive is given', async () => { + await withChangesetsMonorepo({}, async (environment) => { + const headBefore = ( + await environment.runCommand('git', ['rev-parse', 'HEAD']) + ).stdout; + + await expect( + environment.runTool({ + args: ['--changesets', '--interactive'], + releaseSpecification: { packages: {} }, + }), + ).rejects.toThrow( + /The interactive UI does not support Changesets mode yet\./u, + ); + + expect( + (await environment.runCommand('git', ['rev-parse', 'HEAD'])).stdout, + ).toBe(headBefore); + expect( + ( + await environment.runCommand('git', [ + 'rev-parse', + '--abbrev-ref', + 'HEAD', + ]) + ).stdout, + ).toBe('main'); + expect(await readStatus(environment)).toBe(''); + }); + }); + }); }); diff --git a/packages/create-release-branch/src/modes/changesets/changesets-mode.test.ts b/packages/create-release-branch/src/modes/changesets/changesets-mode.test.ts new file mode 100644 index 00000000..afe8d110 --- /dev/null +++ b/packages/create-release-branch/src/modes/changesets/changesets-mode.test.ts @@ -0,0 +1,203 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + buildMockChangesetsState, + buildMockPackage, + buildMockProject, +} from '../../../tests/unit/helpers.js'; +import type { Candidate } from '../../core/candidates.js'; +import type { ModePlan, ModePlanResult } from '../../core/mode.js'; +import { readFile } from '../../utils/fs.js'; +import { applyChangesetsRelease, checkChangesetDirectory } from './apply.js'; +import { listChangesetsCandidates } from './candidates.js'; +import { createChangesetsMode } from './changesets-mode.js'; +import { loadChangesets } from './load.js'; +import { planChangesetsRelease } from './plan.js'; +import type { ChangesetsPlanData } from './plan.js'; + +vi.mock('../../utils/fs'); +vi.mock('./apply'); +vi.mock('./candidates'); +vi.mock('./load'); +vi.mock('./plan'); + +const PROJECT = buildMockProject({ + isMonorepo: true, + workspacePackages: { + a: buildMockPackage('a', '1.0.0'), + }, +}); + +const STATE = buildMockChangesetsState(); + +const CANDIDATES: Candidate[] = [ + { + name: 'a', + currentVersion: '1.0.0', + plannedVersion: '1.1.0', + kind: 'changes', + changeCount: 1, + }, +]; + +const PLAN: ModePlan = { + releases: [{ name: 'a', newVersion: '1.1.0' }], + data: { + state: STATE, + filteredPlan: STATE.fullPlan, + selectedChangesets: [], + }, +}; + +/** + * Mocks the Changesets state of the project and its candidates. + */ +function mockState(): void { + vi.when(vi.mocked(loadChangesets)) + .calledWith(PROJECT.directoryPath) + .thenResolve(STATE); + vi.when(vi.mocked(listChangesetsCandidates)) + .calledWith(PROJECT, STATE) + .thenReturn(CANDIDATES); +} + +describe('changesets-mode', () => { + describe('createChangesetsMode', () => { + it('is named "changesets"', () => { + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(mode.name).toBe('changesets'); + }); + + it('checks the .changeset directory when it prepares the release, and returns no notice', async () => { + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(mode.prepare).toMatchObject({ + title: 'Checking the .changeset directory', + result: 'The .changeset directory has no uncommitted changes', + }); + expect(await mode.prepare.run()).toStrictEqual([]); + expect(checkChangesetDirectory).toHaveBeenCalledWith(PROJECT); + }); + + it('lists the candidates of the pending Changesets', async () => { + mockState(); + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(await mode.listCandidates()).toStrictEqual(CANDIDATES); + }); + + it('ignores the choices when it lists the candidates', async () => { + mockState(); + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(await mode.listCandidates({ a: 'major' })).toStrictEqual( + CANDIDATES, + ); + }); + + it('reads the Changesets again every time it lists the candidates', async () => { + mockState(); + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + await mode.listCandidates(); + await mode.listCandidates(); + + expect(loadChangesets).toHaveBeenCalledTimes(2); + }); + + it('plans the release from the choices, with the Changesets that it reads if it did not list the candidates', async () => { + mockState(); + const result: ModePlanResult = { plan: PLAN }; + vi.when(vi.mocked(planChangesetsRelease)) + .calledWith({ + project: PROJECT, + state: STATE, + candidates: CANDIDATES, + choices: { a: 'minor' }, + }) + .thenReturn(result); + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(await mode.plan({ a: 'minor' })).toBe(result); + expect(loadChangesets).toHaveBeenCalledTimes(1); + }); + + it('plans the release with the Changesets that the last candidates call read', async () => { + const oldState = buildMockChangesetsState({ + fullPlan: { + changesets: [{ id: 'old-changeset', summary: '', releases: [] }], + releases: [], + preState: undefined, + }, + }); + vi.mocked(loadChangesets) + .mockResolvedValueOnce(oldState) + .mockResolvedValueOnce(STATE); + vi.when(vi.mocked(listChangesetsCandidates)) + .calledWith(PROJECT, STATE) + .thenReturn(CANDIDATES); + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + await mode.listCandidates(); + await mode.listCandidates(); + await mode.plan({ a: 'minor' }); + + expect(loadChangesets).toHaveBeenCalledTimes(2); + expect(planChangesetsRelease).toHaveBeenCalledWith({ + project: PROJECT, + state: STATE, + candidates: CANDIDATES, + choices: { a: 'minor' }, + }); + }); + + it('applies the planned release, and returns no notice', async () => { + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(await mode.apply(PLAN, '2.0.0')).toStrictEqual([]); + expect(applyChangesetsRelease).toHaveBeenCalledWith({ + project: PROJECT, + data: PLAN.data, + newRootVersion: '2.0.0', + formatter: 'prettier', + }); + }); + + it('returns the changelog of a package as its release notes', async () => { + vi.when(vi.mocked(readFile)) + .calledWith(PROJECT.workspacePackages.a.changelogPath) + .thenResolve('changelog of a'); + const mode = createChangesetsMode({ + project: PROJECT, + formatter: 'prettier', + }); + + expect(await mode.getReleaseNotes('a')).toBe('changelog of a'); + }); + }); +}); diff --git a/packages/create-release-branch/src/modes/changesets/changesets-mode.ts b/packages/create-release-branch/src/modes/changesets/changesets-mode.ts new file mode 100644 index 00000000..6df94df6 --- /dev/null +++ b/packages/create-release-branch/src/modes/changesets/changesets-mode.ts @@ -0,0 +1,89 @@ +import type { Candidate } from '../../core/candidates.js'; +import type { Mode } from '../../core/mode.js'; +import type { Formatter } from '../../core/types.js'; +import type { Project } from '../../project/project.js'; +import { readFile } from '../../utils/fs.js'; +import { applyChangesetsRelease, checkChangesetDirectory } from './apply.js'; +import { listChangesetsCandidates } from './candidates.js'; +import { loadChangesets } from './load.js'; +import type { ChangesetsState } from './load.js'; +import { planChangesetsRelease } from './plan.js'; +import type { ChangesetsPlanData } from './plan.js'; + +/** + * The Changesets state of the project, and the candidates that it gives. + */ +type LoadedChangesets = { + state: ChangesetsState; + candidates: Candidate[]; +}; + +/** + * Creates the release mode in which the pending Changesets set the packages + * and versions to release. The maintainer only chooses which packages go in + * the release. Before the first commit of the release, the mode checks that + * the `.changeset` directory has no uncommitted changes, so that this commit + * does not take in a Changeset by mistake. Every call to `listCandidates` + * reads the Changesets again. + * `plan` uses the Changesets that the last `listCandidates` call read, and + * reads them only if there was no such call. + * + * @param args - The arguments. + * @param args.project - Information about the project. + * @param args.formatter - The formatter to use for formatting the changelogs. + * @returns The Changesets mode. + */ +export function createChangesetsMode({ + project, + formatter, +}: { + project: Project; + formatter: Formatter; +}): Mode { + let lastLoad: LoadedChangesets | undefined; + + const load = async (): Promise => { + const state = await loadChangesets(project.directoryPath); + lastLoad = { state, candidates: listChangesetsCandidates(project, state) }; + return lastLoad; + }; + + return { + name: 'changesets', + + prepare: { + title: 'Checking the .changeset directory', + result: 'The .changeset directory has no uncommitted changes', + run: async () => { + await checkChangesetDirectory(project); + return []; + }, + }, + + async listCandidates() { + const { candidates } = await load(); + return candidates; + }, + + async plan(choices) { + const { state, candidates } = lastLoad ?? (await load()); + return planChangesetsRelease({ project, state, candidates, choices }); + }, + + async apply({ data }, newRootVersion) { + await applyChangesetsRelease({ + project, + data, + newRootVersion, + formatter, + }); + return []; + }, + + async getReleaseNotes(packageName) { + return await readFile( + project.workspacePackages[packageName].changelogPath, + ); + }, + }; +} diff --git a/packages/create-release-branch/src/project/release-config.test.ts b/packages/create-release-branch/src/project/release-config.test.ts index 453485c6..907dc279 100644 --- a/packages/create-release-branch/src/project/release-config.test.ts +++ b/packages/create-release-branch/src/project/release-config.test.ts @@ -28,18 +28,21 @@ describe('release-config', () => { }); }); - it('reads the mode from the config file', async () => { - await withSandbox(async ({ directoryPath }) => { - await fs.promises.writeFile( - path.join(directoryPath, 'release.config.json'), - JSON.stringify({ mode: 'legacy' }), - ); + it.each(['legacy', 'changesets'])( + 'reads the mode %j from the config file', + async (mode) => { + await withSandbox(async ({ directoryPath }) => { + await fs.promises.writeFile( + path.join(directoryPath, 'release.config.json'), + JSON.stringify({ mode }), + ); - expect(await readReleaseConfig(directoryPath)).toStrictEqual({ - mode: 'legacy', + expect(await readReleaseConfig(directoryPath)).toStrictEqual({ + mode, + }); }); - }); - }); + }, + ); it.each(['unknown', 1, null])('rejects the mode %j', async (mode) => { await withSandbox(async ({ directoryPath }) => { @@ -65,12 +68,15 @@ describe('release-config', () => { }), ).toStrictEqual({ title: 'The "mode" in is not valid: "unknown"', - lines: ['Use one of: "legacy".', '(/path/to/release.config.json)'], + lines: [ + 'Use one of: "legacy", "changesets".', + '(/path/to/release.config.json)', + ], }); expect(error.message).toBe( [ 'The "mode" in release.config.json is not valid: "unknown"', - 'Use one of: "legacy".', + 'Use one of: "legacy", "changesets".', '/path/to/release.config.json', ].join('\n'), ); diff --git a/packages/create-release-branch/tests/functional/helpers/local-monorepo.ts b/packages/create-release-branch/tests/functional/helpers/local-monorepo.ts index 71e29283..eb6797d7 100644 --- a/packages/create-release-branch/tests/functional/helpers/local-monorepo.ts +++ b/packages/create-release-branch/tests/functional/helpers/local-monorepo.ts @@ -1,9 +1,32 @@ import path from 'path'; +import { pathToFileURL } from 'url'; import { PackageSpecification } from './environment.js'; import LocalRepo, { LocalRepoOptions } from './local-repo.js'; import { knownKeysOf } from './utils.js'; +/** + * A Changeset file. + * + * @property id - The name of the file, without `.md`. + * @property releases - The bump type for each package that it releases. + * @property summary - The text after the front matter. + */ +export type ChangesetSpecification = { + id: string; + releases: Record; + summary: string; +}; + +/** + * The source of `@metamask/changesets-changelog`, which `tsx` can load + * without a build. + */ +const CHANGELOG_MODULE_SOURCE_PATH = path.resolve( + import.meta.dirname, + '../../../../changesets-changelog/src/index.ts', +); + /** * A set of configuration options for a {@link LocalMonorepo}. In addition * to the options listed in {@link LocalRepoOptions}, these include: @@ -11,10 +34,14 @@ import { knownKeysOf } from './utils.js'; * @property packages - The known packages within this repo (including the * root). * @property workspaces - The known workspaces within this repo. + * @property changesets - If given, the repo uses Changesets: it gets a + * `.changeset/config.json` that uses `@metamask/changesets-changelog`, and + * these Changeset files. */ export type LocalMonorepoOptions = { packages: Record; workspaces: Record; + changesets?: ChangesetSpecification[] | undefined; } & LocalRepoOptions; /** @@ -37,12 +64,19 @@ export default class LocalMonorepo< */ readonly #workspaces: LocalMonorepoOptions['workspaces']; + /** + * The Changeset files within this repo, if it uses Changesets. + */ + readonly #changesets: LocalMonorepoOptions['changesets']; + constructor({ packages, workspaces, + changesets, ...rest }: LocalMonorepoOptions) { super(rest); + this.#changesets = changesets; this.#packages = { $root$: { name: 'monorepo', @@ -158,7 +192,8 @@ export default class LocalMonorepo< /** * Writes an initial package.json for the root package as well as any - * workspace packages (if specified). + * workspace packages (if specified), and the Changesets files (if + * specified). */ protected async afterCreate(): Promise { await super.afterCreate(); @@ -187,9 +222,63 @@ export default class LocalMonorepo< }), ); + if (this.#changesets !== undefined) { + await this.#writeChangesetsFiles(this.#changesets); + } + await this.runCommand('yarn', ['plugin', 'import', 'constraints']); } + /** + * Writes the Changesets configuration, the Changeset files, and a package + * that points `@metamask/changesets-changelog` to its source. Formatting is + * disabled so that the result does not depend on formatters found above + * the repo. + * + * @param changesets - The Changeset files. + */ + async #writeChangesetsFiles( + changesets: ChangesetSpecification[], + ): Promise { + await this.writeJsonFile('.changeset/config.json', { + changelog: [ + '@metamask/changesets-changelog', + { repository: 'example-org/example-repo' }, + ], + commit: false, + fixed: [], + linked: [], + access: 'restricted', + baseBranch: 'main', + updateInternalDependencies: 'patch', + ignore: [], + format: false, + }); + for (const { id, releases, summary } of changesets) { + const frontMatter = Object.entries(releases) + .map(([name, type]) => `${JSON.stringify(name)}: ${type}`) + .join('\n'); + await this.writeFile( + `.changeset/${id}.md`, + `---\n${frontMatter}\n---\n\n${summary}\n`, + ); + } + + await this.writeFile('.gitignore', 'node_modules/\n'); + await this.writeJsonFile( + 'node_modules/@metamask/changesets-changelog/package.json', + { + name: '@metamask/changesets-changelog', + type: 'module', + exports: './index.js', + }, + ); + await this.writeFile( + 'node_modules/@metamask/changesets-changelog/index.js', + `export { default } from '${pathToFileURL(CHANGELOG_MODULE_SOURCE_PATH).href}';\n`, + ); + } + /** * Gets the name of the primary package that this project represents. * diff --git a/packages/create-release-branch/tests/functional/helpers/monorepo-environment.ts b/packages/create-release-branch/tests/functional/helpers/monorepo-environment.ts index df68d7b0..805e2b7f 100644 --- a/packages/create-release-branch/tests/functional/helpers/monorepo-environment.ts +++ b/packages/create-release-branch/tests/functional/helpers/monorepo-environment.ts @@ -8,7 +8,7 @@ import Environment, { EnvironmentOptions, PackageSpecification, } from './environment.js'; -import LocalMonorepo from './local-monorepo.js'; +import LocalMonorepo, { LocalMonorepoOptions } from './local-monorepo.js'; import { debug, knownKeysOf } from './utils.js'; /** @@ -18,12 +18,15 @@ import { debug, knownKeysOf } from './utils.js'; * @property packages - The known packages within this repo (including the * root). * @property workspaces - The known workspaces within this repo. + * @property changesets - If given, the repo uses Changesets with these + * Changeset files. See {@link LocalMonorepoOptions}. */ export type MonorepoEnvironmentOptions< WorkspacePackageNickname extends string, > = { packages: Record; workspaces: Record; + changesets?: LocalMonorepoOptions['changesets']; } & EnvironmentOptions; /** @@ -153,6 +156,7 @@ cat "${releaseSpecificationPath}" > "$1" protected buildLocalRepo({ packages, workspaces, + changesets, createInitialCommit = true, }: MonorepoEnvironmentOptions): LocalMonorepo { return new LocalMonorepo({ @@ -160,6 +164,7 @@ cat "${releaseSpecificationPath}" > "$1" remoteRepoDirectoryPath: this.remoteRepo.getWorkingDirectoryPath(), packages, workspaces, + changesets, createInitialCommit, }); }