diff --git a/README.md b/README.md index 081482df..3c437eb3 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ linkStyle default opacity:0.5 changesets_lint --> changesets_utils; changesets_lint --> auto_changelog; changesets_utils --> auto_changelog; + create_release_branch --> apply_release_plan; create_release_branch --> auto_changelog; create_release_branch --> changesets_utils; ``` diff --git a/packages/changesets-changelog/CHANGELOG.md b/packages/changesets-changelog/CHANGELOG.md index 09865778..d0998ed4 100644 --- a/packages/changesets-changelog/CHANGELOG.md +++ b/packages/changesets-changelog/CHANGELOG.md @@ -13,5 +13,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Add Keep a Changelog categories and repository option validation ([#87](https://github.com/MetaMask/release-tools/pull/87)) - Generate categorized changelog entries ([#88](https://github.com/MetaMask/release-tools/pull/88)) - Generate Keep a Changelog version headings ([#90](https://github.com/MetaMask/release-tools/pull/90)) +- Write a changelog entry without a pull request link if the commit subject of its changeset has no pull request number ([#169](https://github.com/MetaMask/release-tools/pull/169)) [Unreleased]: https://github.com/MetaMask/release-tools/ diff --git a/packages/changesets-changelog/src/changelog-functions.test.ts b/packages/changesets-changelog/src/changelog-functions.test.ts index b6285e52..afd96df0 100644 --- a/packages/changesets-changelog/src/changelog-functions.test.ts +++ b/packages/changesets-changelog/src/changelog-functions.test.ts @@ -46,6 +46,14 @@ describe('getReleaseLine', () => { '- **BREAKING:** Add a feature ([#1234](https://github.com/MetaMask/core/pull/1234))\n - Preserve this detail', ); }); + + it('leaves out the pull request link if the commit has no pull request number', async () => { + mockedGetPullRequestLink.mockResolvedValue(undefined); + + expect(await getReleaseLine(changeset, 'minor', options)).toBe( + '- Add a feature\n - Preserve this detail', + ); + }); }); describe('categorizeReleaseLine', () => { diff --git a/packages/changesets-changelog/src/changelog-functions.ts b/packages/changesets-changelog/src/changelog-functions.ts index 6434a09f..c206719e 100644 --- a/packages/changesets-changelog/src/changelog-functions.ts +++ b/packages/changesets-changelog/src/changelog-functions.ts @@ -10,7 +10,9 @@ import { getGitHubRepository } from './options.js'; import { getPullRequestLink } from './resolve-pull-request.js'; /** - * Formats one categorized changeset as a Markdown changelog line. + * Formats one categorized changeset as a Markdown changelog line. The line + * has no pull request link if the commit of the changeset has no pull request + * number in its subject. * * @param changeset - The changeset to format. * @param type - The release's version bump type. @@ -29,9 +31,11 @@ export const getReleaseLine: GetReleaseLine = async ( ); const [firstLine, ...remainingLines] = description.split('\n'); const breakingPrefix = type === 'major' ? '**BREAKING:** ' : ''; + const linkSuffix = + pullRequestLink === undefined ? '' : ` (${pullRequestLink})`; return [ - `- ${breakingPrefix}${firstLine} (${pullRequestLink})`, + `- ${breakingPrefix}${firstLine}${linkSuffix}`, ...remainingLines, ].join('\n'); }; diff --git a/packages/changesets-changelog/src/resolve-pull-request.test.ts b/packages/changesets-changelog/src/resolve-pull-request.test.ts index 53365b3b..3bec1826 100644 --- a/packages/changesets-changelog/src/resolve-pull-request.test.ts +++ b/packages/changesets-changelog/src/resolve-pull-request.test.ts @@ -31,10 +31,8 @@ describe('extractPullRequestNumber', () => { ).toBe('1234'); }); - it('throws when a subject has no pull request number', () => { - expect(() => extractPullRequestNumber('Add a feature')).toThrow( - 'does not contain a pull request number', - ); + it('returns undefined when a subject has no pull request number', () => { + expect(extractPullRequestNumber('Add a feature')).toBeUndefined(); }); }); @@ -57,6 +55,14 @@ describe('getPullRequestLink', () => { ]); }); + it('returns undefined when the commit subject has no pull request number', async () => { + mockedExeca.mockResolvedValue({ stdout: 'Add a feature' } as never); + + expect( + await getPullRequestLink(changeset, 'MetaMask/core'), + ).toBeUndefined(); + }); + it('throws when the changeset has no commit', async () => { const withoutCommit = { ...changeset }; delete withoutCommit.commit; diff --git a/packages/changesets-changelog/src/resolve-pull-request.ts b/packages/changesets-changelog/src/resolve-pull-request.ts index 139c9ba4..db3cfda0 100644 --- a/packages/changesets-changelog/src/resolve-pull-request.ts +++ b/packages/changesets-changelog/src/resolve-pull-request.ts @@ -8,20 +8,14 @@ const MERGE_COMMIT_PR_PATTERN = /Merge pull request #(\d+) from/iu; * Extracts a pull request number from a Git commit subject. * * @param subject - The Git commit subject. - * @returns The pull request number. + * @returns The pull request number, or undefined if the subject has none. */ -export function extractPullRequestNumber(subject: string): string { +export function extractPullRequestNumber(subject: string): string | undefined { const match = subject.match(SQUASH_MERGE_PR_PATTERN) ?? subject.match(MERGE_COMMIT_PR_PATTERN); - if (!match) { - throw new Error( - `Commit subject does not contain a pull request number: ${subject}`, - ); - } - - return match[1]; + return match?.[1]; } /** @@ -29,12 +23,13 @@ export function extractPullRequestNumber(subject: string): string { * * @param changeset - The changeset whose commit should be inspected. * @param repository - The GitHub repository in `owner/repo` form. - * @returns The Markdown pull request link. + * @returns The Markdown pull request link, or undefined if the commit subject + * has no pull request number. */ export async function getPullRequestLink( changeset: NewChangesetWithCommit, repository: string, -): Promise { +): Promise { if (!changeset.commit) { throw new Error(`Changeset ${changeset.id} has no commit`); } @@ -61,5 +56,7 @@ export async function getPullRequestLink( } const pullRequestNumber = extractPullRequestNumber(subject.trim()); - return `[#${pullRequestNumber}](https://github.com/${repository}/pull/${pullRequestNumber})`; + return pullRequestNumber === undefined + ? undefined + : `[#${pullRequestNumber}](https://github.com/${repository}/pull/${pullRequestNumber})`; } diff --git a/packages/create-release-branch/package.json b/packages/create-release-branch/package.json index b706d642..0ab31799 100644 --- a/packages/create-release-branch/package.json +++ b/packages/create-release-branch/package.json @@ -51,6 +51,7 @@ "@clack/prompts": "^1.8.1", "@manypkg/get-packages": "^3.1.0", "@metamask/action-utils": "^2.0.0", + "@metamask/apply-release-plan": "^0.0.0", "@metamask/auto-changelog": "^7.1.0", "@metamask/changesets-utils": "^0.0.0", "@metamask/utils": "^11.12.0", diff --git a/packages/create-release-branch/src/core/repo.test.ts b/packages/create-release-branch/src/core/repo.test.ts index 20e8b1fc..f406be8d 100644 --- a/packages/create-release-branch/src/core/repo.test.ts +++ b/packages/create-release-branch/src/core/repo.test.ts @@ -7,6 +7,7 @@ import { hasChangesInDirectorySinceGitTag, getCurrentBranchName, branchExists, + hasUncommittedChanges, restoreFiles, } from './repo.js'; @@ -220,6 +221,32 @@ describe('repo', () => { }); }); + describe('hasUncommittedChanges', () => { + it('returns true when git status lists a change under the path', async () => { + vi.when(vi.spyOn(miscUtils, 'getLinesFromCommand')) + .calledWith('git', ['status', '--porcelain', '--', '.changeset'], { + cwd: '/path/to/repo', + }) + .thenResolve(['?? .changeset/brave-cats-sing.md']); + + expect(await hasUncommittedChanges('/path/to/repo', '.changeset')).toBe( + true, + ); + }); + + it('returns false when git status lists no change under the path', async () => { + vi.when(vi.spyOn(miscUtils, 'getLinesFromCommand')) + .calledWith('git', ['status', '--porcelain', '--', '.changeset'], { + cwd: '/path/to/repo', + }) + .thenResolve([]); + + expect(await hasUncommittedChanges('/path/to/repo', '.changeset')).toBe( + false, + ); + }); + }); + describe('restoreFiles', () => { it('should call runCommand with the correct arguments', async () => { const getStdoutFromCommandSpy = vi.spyOn( diff --git a/packages/create-release-branch/src/core/repo.ts b/packages/create-release-branch/src/core/repo.ts index 34a974c3..24e41a3c 100644 --- a/packages/create-release-branch/src/core/repo.ts +++ b/packages/create-release-branch/src/core/repo.ts @@ -214,6 +214,26 @@ export async function branchExists( return branchNames.length > 0; } +/** + * Checks whether a path in the given repository has uncommitted changes, + * including untracked files. + * + * @param repositoryDirectoryPath - The path to the repository directory. + * @param pathspec - The path to check, relative to the repository directory. + * @returns Whether `git status` reports any change under the path. + */ +export async function hasUncommittedChanges( + repositoryDirectoryPath: string, + pathspec: string, +): Promise { + const statusLines = await getLinesFromGitCommandWithin( + repositoryDirectoryPath, + 'status', + ['--porcelain', '--', pathspec], + ); + return statusLines.length > 0; +} + /** * Retrieves the names of the tags in the given repo, sorted by ascending * semantic version order. As this fetches tags from the remote first, you are diff --git a/packages/create-release-branch/src/modes/changesets/apply.test.ts b/packages/create-release-branch/src/modes/changesets/apply.test.ts new file mode 100644 index 00000000..984ccb37 --- /dev/null +++ b/packages/create-release-branch/src/modes/changesets/apply.test.ts @@ -0,0 +1,495 @@ +import type { NewChangeset } from '@changesets/types'; +import { applyReleasePlan } from '@metamask/apply-release-plan'; +import { oxfmt } from '@metamask/auto-changelog'; +import { restoreResidualChangesets } from '@metamask/changesets-utils'; +import { describe, expect, it, vi } from 'vitest'; + +import { buildChangelog } from '../../../tests/helpers.js'; +import { + buildMockChangesetsState, + buildMockPackage, + buildMockProject, +} from '../../../tests/unit/helpers.js'; +import { hasUncommittedChanges } from '../../core/repo.js'; +import { getFormatter } from '../../project/package.js'; +import { + fileExists, + readFile, + readJsonObjectFile, + writeFile, + writeJsonFile, +} from '../../utils/fs.js'; +import { + applyChangesetsRelease, + ChangesetsApplyError, + RECOVERY_COMMAND, +} from './apply.js'; +import { ChangesetsSetupError } from './load.js'; +import type { ChangesetsPlanData } from './plan.js'; + +vi.mock('@metamask/apply-release-plan'); +vi.mock('@metamask/changesets-utils'); +vi.mock('../../core/repo'); +vi.mock('../../project/package'); +vi.mock('../../utils/fs'); + +const PROJECT = buildMockProject({ + isMonorepo: true, + rootPackage: buildMockPackage('root', '1.0.0'), + workspacePackages: { + a: buildMockPackage('a', '1.0.0'), + b: buildMockPackage('b', '1.0.0'), + c: buildMockPackage('c', '1.0.0'), + }, +}); + +/** + * A Changeset that releases `a`, which the release keeps, and `b`, which it + * leaves out. + */ +const SHARED_CHANGESET: NewChangeset = { + id: 'eager-owls-fly', + summary: '## Fixed\n\n- Fix a and extend b', + releases: [ + { name: 'a', type: 'patch' }, + { name: 'b', type: 'minor' }, + ], +}; + +const SELECTED_CHANGESET: NewChangeset = { + ...SHARED_CHANGESET, + releases: [{ name: 'a', type: 'patch' }], +}; + +const UNRELEASED_CHANGELOG = buildChangelog(` + ## [Unreleased] + + [Unreleased]: https://repo.url/ +`); + +/** + * Builds the data of a plan that releases `a` from a shared Changeset, and + * keeps `c` unchanged. + * + * @returns The plan data. + */ +function buildPlanData(): ChangesetsPlanData { + return { + state: buildMockChangesetsState({ + fullPlan: { + changesets: [SHARED_CHANGESET], + releases: [], + preState: undefined, + }, + }), + filteredPlan: { + changesets: [SELECTED_CHANGESET], + releases: [ + { + name: 'a', + type: 'patch', + oldVersion: '1.0.0', + newVersion: '1.0.1', + changesets: [SHARED_CHANGESET.id], + }, + { + name: 'c', + type: 'none', + oldVersion: '1.0.0', + newVersion: '1.0.0', + changesets: [], + }, + ], + preState: undefined, + }, + selectedChangesets: [SELECTED_CHANGESET], + }; +} + +/** + * Builds the data of a plan that releases `a` and `b`. + * + * @returns The plan data. + */ +function buildTwoReleasesPlanData(): ChangesetsPlanData { + const data = buildPlanData(); + return { + ...data, + filteredPlan: { + ...data.filteredPlan, + releases: [ + ...data.filteredPlan.releases, + { + name: 'b', + type: 'minor', + oldVersion: '1.0.0', + newVersion: '1.1.0', + changesets: [SHARED_CHANGESET.id], + }, + ], + }, + }; +} + +/** + * Mocks the changelogs of the given packages. + * + * @param changelogs - The content of each changelog, by package name. + */ +function mockChangelogs(changelogs: Record): void { + for (const [name, content] of Object.entries(changelogs)) { + const { changelogPath } = PROJECT.workspacePackages[name]; + vi.when(vi.mocked(fileExists)).calledWith(changelogPath).thenResolve(true); + vi.when(vi.mocked(readFile)).calledWith(changelogPath).thenResolve(content); + } +} + +/** + * Applies a release of the mock project. + * + * @param data - The plan data. + */ +async function applyRelease( + data: ChangesetsPlanData = buildPlanData(), +): Promise { + await applyChangesetsRelease({ + project: PROJECT, + data, + newRootVersion: '2.0.0', + formatter: 'oxfmt', + }); +} + +describe('apply', () => { + describe('applyChangesetsRelease', () => { + it('applies the filtered plan with Changesets', async () => { + const data = buildPlanData(); + + await applyRelease(data); + + expect(applyReleasePlan).toHaveBeenCalledWith( + data.filteredPlan, + data.state.packages, + data.state.config, + ); + }); + + it('rewrites the changelog of each bumped package, with the link of its new release section and no empty Unreleased section', async () => { + mockChangelogs({ + a: buildChangelog(` + ## [Unreleased] + + ## [1.0.1] + + ### Fixed + + - Fix a and extend b ([#20](https://repo.url/pull/20)) + + ## [1.0.0] + + ### Added + + - Initial release + + [Unreleased]: https://repo.url/compare/a@1.0.0...HEAD + [1.0.0]: https://repo.url/releases/tag/a@1.0.0 + `), + }); + vi.when(vi.mocked(getFormatter)).calledWith('oxfmt').thenReturn(oxfmt); + + await applyRelease(); + + expect(writeFile).toHaveBeenCalledTimes(1); + expect(writeFile).toHaveBeenCalledWith( + PROJECT.workspacePackages.a.changelogPath, + buildChangelog(` + ## [1.0.1] + + ### Fixed + + - Fix a and extend b ([#20](https://repo.url/pull/20)) + + ## [1.0.0] + + ### Added + + - Initial release + + [1.0.1]: https://repo.url/compare/a@1.0.0...a@1.0.1 + [1.0.0]: https://repo.url/releases/tag/a@1.0.0 + `), + ); + }); + + it('does not write a changelog for a bumped package that has none', async () => { + await applyRelease(); + + expect(writeFile).not.toHaveBeenCalled(); + }); + + it('bumps the root version in the manifest on disk', async () => { + const { manifestPath } = PROJECT.rootPackage; + vi.when(vi.mocked(readJsonObjectFile)) + .calledWith(manifestPath) + .thenResolve({ + name: 'root', + version: '1.0.0', + dependencies: { a: '^1.0.1' }, + }); + + await applyRelease(); + + expect(writeJsonFile).toHaveBeenCalledTimes(1); + expect(writeJsonFile).toHaveBeenCalledWith(manifestPath, { + name: 'root', + version: '2.0.0', + dependencies: { a: '^1.0.1' }, + }); + }); + + it('restores the releases that a shared Changeset leaves out', async () => { + await applyRelease(); + + expect(restoreResidualChangesets).toHaveBeenCalledWith({ + changesetDir: '/path/to/project/.changeset', + changesets: [SHARED_CHANGESET], + releasedPackageNames: ['a'], + }); + }); + + it('fails before changing any file if the .changeset directory has uncommitted changes', async () => { + vi.when(vi.mocked(hasUncommittedChanges)) + .calledWith(PROJECT.directoryPath, '.changeset') + .thenResolve(true); + + await expect(applyRelease()).rejects.toThrow( + new ChangesetsSetupError({ + problem: 'The .changeset directory has uncommitted changes.', + details: ['Commit or remove them, then run this tool again.'], + filePath: '/path/to/project/.changeset', + }), + ); + expect(applyReleasePlan).not.toHaveBeenCalled(); + }); + + it('fails before changing any file if the changelog of a released package cannot be parsed', async () => { + mockChangelogs({ + a: buildChangelog(` + ## [1.0.0] + + ### Unknown + + - Initial release + + [1.0.0]: https://repo.url/releases/tag/a@1.0.0 + `), + }); + + await expect(applyRelease()).rejects.toThrow( + new ChangesetsSetupError({ + problem: 'The changelog of a could not be parsed.', + details: [ + "Invalid change category: 'Unknown'", + 'Fix the changelog, then run this tool again.', + ], + filePath: PROJECT.workspacePackages.a.changelogPath, + }), + ); + expect(applyReleasePlan).not.toHaveBeenCalled(); + }); + + it('fails before changing any file if the changelogs of released packages have entries in Unreleased', async () => { + const changelogWithUnreleasedEntries = buildChangelog(` + ## [Unreleased] + + ### Changed + + - Bump \`c\` from \`^1.0.0\` to \`^2.0.0\` ([#30](https://repo.url/pull/30)) + + ## [1.0.0] + + ### Added + + - Initial release + + [Unreleased]: https://repo.url/compare/a@1.0.0...HEAD + [1.0.0]: https://repo.url/releases/tag/a@1.0.0 + `); + mockChangelogs({ + a: changelogWithUnreleasedEntries, + b: changelogWithUnreleasedEntries.replaceAll('a@', 'b@'), + }); + + await expect(applyRelease(buildTwoReleasesPlanData())).rejects.toThrow( + new ChangesetsSetupError({ + problem: '2 changelogs have entries in Unreleased:', + details: [ + `a ${PROJECT.workspacePackages.a.changelogPath}`, + `b ${PROJECT.workspacePackages.b.changelogPath}`, + 'Changesets mode does not release entries in Unreleased. Move each entry into a Changeset and commit it, or remove the entry. Then run this tool again.', + ], + }), + ); + expect(applyReleasePlan).not.toHaveBeenCalled(); + }); + + it('names a single changelog that has entries in Unreleased', async () => { + mockChangelogs({ + a: buildChangelog(` + ## [Unreleased] + + ### Fixed + + - Fix a bug ([#30](https://repo.url/pull/30)) + + ## [1.0.0] + + ### Added + + - Initial release + + [Unreleased]: https://repo.url/compare/a@1.0.0...HEAD + [1.0.0]: https://repo.url/releases/tag/a@1.0.0 + `), + }); + + await expect(applyRelease()).rejects.toThrow( + '1 changelog has entries in Unreleased:', + ); + }); + + it('fails before changing any file if changelogs with no release have link reference definitions', async () => { + mockChangelogs({ + a: UNRELEASED_CHANGELOG, + b: UNRELEASED_CHANGELOG, + }); + + await expect(applyRelease(buildTwoReleasesPlanData())).rejects.toThrow( + [ + '2 changelogs cannot take the new release section:', + `a ${PROJECT.workspacePackages.a.changelogPath}`, + `b ${PROJECT.workspacePackages.b.changelogPath}`, + 'A changelog with no release yet must not have link reference definitions, such as "[Unreleased]: ...". Remove them, then run this tool again.', + ].join('\n'), + ); + expect(applyReleasePlan).not.toHaveBeenCalled(); + }); + + it('names a single changelog that cannot take the new release section', async () => { + mockChangelogs({ a: UNRELEASED_CHANGELOG }); + + await expect(applyRelease()).rejects.toThrow( + '1 changelog cannot take the new release section:', + ); + }); + + it('accepts a changelog that already has a release', async () => { + mockChangelogs({ + a: buildChangelog(` + ## [Unreleased] + + ## [1.0.0] + + ### Added + + - Initial release + + [Unreleased]: https://repo.url/compare/a@1.0.0...HEAD + [1.0.0]: https://repo.url/releases/tag/a@1.0.0 + `), + }); + + await applyRelease(); + + expect(applyReleasePlan).toHaveBeenCalled(); + }); + + it('explains how to recover if a step fails after the checks', async () => { + const cause = new Error('Could not write the file'); + vi.mocked(applyReleasePlan).mockRejectedValue(cause); + + const promise = applyRelease(); + + await expect(promise).rejects.toThrow(ChangesetsApplyError); + await expect(promise).rejects.toHaveProperty('cause', cause); + }); + + it('does not let applyReleasePlan write errors to the console', async () => { + const consoleError = vi.spyOn(console, 'error'); + vi.mocked(applyReleasePlan).mockImplementation(async () => { + console.error('An error was encountered'); + throw new Error('Could not write the file'); + }); + + await expect(applyRelease()).rejects.toThrow(ChangesetsApplyError); + expect(consoleError).not.toHaveBeenCalled(); + expect(console.error).toBe(consoleError); + }); + }); + + describe('ChangesetsApplyError', () => { + it('describes the cause and the recovery command', () => { + const error = new ChangesetsApplyError({ + cause: new Error('Could not write the file', { + cause: new Error('Disk full'), + }), + }); + + expect( + error.describe({ + name: (text) => `<${text}>`, + dim: (text) => `[${text}]`, + }), + ).toStrictEqual({ + title: 'The release could not be applied.', + lines: [ + 'Could not write the file', + 'Caused by: Disk full', + '', + 'The project may now have part of the release. Put the changes aside with this command, then run this tool again:', + ` ${RECOVERY_COMMAND}`, + ], + }); + }); + + it('describes a cause that describes itself', () => { + const error = new ChangesetsApplyError({ + cause: new ChangesetsSetupError({ + problem: 'The changelog of a could not be parsed.', + details: ['Fix the changelog, then run this tool again.'], + filePath: '/a/CHANGELOG.md', + }), + }); + + expect( + error.describe({ + name: (text) => `<${text}>`, + dim: (text) => `[${text}]`, + }).lines, + ).toStrictEqual([ + 'The changelog of a could not be parsed.', + 'Fix the changelog, then run this tool again.', + '[/a/CHANGELOG.md]', + '', + 'The project may now have part of the release. Put the changes aside with this command, then run this tool again:', + ` ${RECOVERY_COMMAND}`, + ]); + }); + + it('has a plain message', () => { + const error = new ChangesetsApplyError({ + cause: new Error('Could not write the file'), + }); + + expect(error.message).toBe( + [ + 'The release could not be applied.', + 'Could not write the file', + '', + 'The project may now have part of the release. Put the changes aside with this command, then run this tool again:', + ` ${RECOVERY_COMMAND}`, + ].join('\n'), + ); + }); + }); +}); diff --git a/packages/create-release-branch/src/modes/changesets/apply.ts b/packages/create-release-branch/src/modes/changesets/apply.ts new file mode 100644 index 00000000..42856148 --- /dev/null +++ b/packages/create-release-branch/src/modes/changesets/apply.ts @@ -0,0 +1,320 @@ +import { applyReleasePlan } from '@metamask/apply-release-plan'; +import { parseChangelog } from '@metamask/auto-changelog'; +import type { Changelog } from '@metamask/auto-changelog'; +import { restoreResidualChangesets } from '@metamask/changesets-utils'; +import { getErrorMessage } from '@metamask/utils'; +import path from 'path'; + +import type { CliOutput } from '../../core/cli-output.js'; +import { hasUncommittedChanges } from '../../core/repo.js'; +import type { Formatter } from '../../core/types.js'; +import type { ErrorDescription } from '../../core/user-facing-error.js'; +import { + describeError, + UserFacingError, +} from '../../core/user-facing-error.js'; +import { getFormatter } from '../../project/package.js'; +import type { Project } from '../../project/project.js'; +import { + fileExists, + readFile, + readJsonObjectFile, + writeFile, + writeJsonFile, +} from '../../utils/fs.js'; +import { isBumpingRelease } from './candidates.js'; +import { ChangesetsSetupError } from './load.js'; +import type { ChangesetsPlanData } from './plan.js'; + +/** + * The command that puts aside the changes of a release that could not be + * applied, including the files that it created. + */ +export const RECOVERY_COMMAND = 'git stash --include-untracked'; + +/** + * The headings before which `applyReleasePlan` inserts a new release section. + * In a changelog without them, it adds the section at the end, after any link + * reference definition, where the changelog can no longer be parsed. + */ +const VERSION_HEADING_PATTERN = /^#{1,6}\s+.*\d+\.\d+/mu; + +const LINK_REFERENCE_DEFINITION_PATTERN = /^\[[^\]]+\]:/mu; + +/** + * A release that failed after the tool started to write it. + */ +export class ChangesetsApplyError extends UserFacingError { + /** + * Creates the error. + * + * @param options - The options. + * @param options.cause - The error that stopped the release. + */ + constructor(options: { cause: unknown }) { + super(undefined, options); + const plain = (text: string): string => text; + const { title, lines } = this.describe({ name: plain, dim: plain }); + this.message = [title, ...lines].join('\n'); + } + + describe(format: CliOutput['format']): ErrorDescription { + const cause = describeError(this.cause, format, { debug: false }); + return { + title: 'The release could not be applied.', + lines: [ + cause.title, + ...cause.lines, + '', + 'The project may now have part of the release. Put the changes aside with this command, then run this tool again:', + ` ${RECOVERY_COMMAND}`, + ], + }; + } +} + +/** + * Checks that the `.changeset` directory has no uncommitted changes, including + * untracked files. + * + * @param project - The project. + * @throws A `ChangesetsSetupError` if the directory has uncommitted changes. + */ +export async function checkChangesetDirectory(project: Project): Promise { + if (await hasUncommittedChanges(project.directoryPath, '.changeset')) { + throw new ChangesetsSetupError({ + problem: 'The .changeset directory has uncommitted changes.', + details: ['Commit or remove them, then run this tool again.'], + filePath: path.join(project.directoryPath, '.changeset'), + }); + } +} + +/** + * Checks that the changelog of every released package can be parsed, has no + * entries in `Unreleased`, and can take its release section. + * + * @param project - The project. + * @param data - The plan data. + * @throws A `ChangesetsSetupError` if a changelog does not pass. + */ +async function checkChangelogs( + project: Project, + data: ChangesetsPlanData, +): Promise { + const changelogsWithUnreleasedEntries: string[] = []; + const unfitChangelogs: string[] = []; + + for (const { name } of data.filteredPlan.releases.filter(isBumpingRelease)) { + const pkg = project.workspacePackages[name]; + if (!(await fileExists(pkg.changelogPath))) { + continue; + } + const changelogContent = await readFile(pkg.changelogPath); + let changelog: Changelog; + try { + changelog = parseChangelog({ + changelogContent, + repoUrl: project.repositoryUrl, + tagPrefix: `${name}@`, + allowMissingUnreleasedSection: true, + }); + } catch (error) { + throw new ChangesetsSetupError( + { + problem: `The changelog of ${name} could not be parsed.`, + details: [ + getErrorMessage(error), + 'Fix the changelog, then run this tool again.', + ], + filePath: pkg.changelogPath, + }, + { cause: error }, + ); + } + if (Object.values(changelog.getUnreleasedChanges()).flat().length > 0) { + changelogsWithUnreleasedEntries.push(`${name} ${pkg.changelogPath}`); + } + if ( + !VERSION_HEADING_PATTERN.test(changelogContent) && + LINK_REFERENCE_DEFINITION_PATTERN.test(changelogContent) + ) { + unfitChangelogs.push(`${name} ${pkg.changelogPath}`); + } + } + + if (changelogsWithUnreleasedEntries.length > 0) { + throw new ChangesetsSetupError({ + problem: + changelogsWithUnreleasedEntries.length === 1 + ? '1 changelog has entries in Unreleased:' + : `${changelogsWithUnreleasedEntries.length} changelogs have entries in Unreleased:`, + details: [ + ...changelogsWithUnreleasedEntries, + 'Changesets mode does not release entries in Unreleased. Move each entry into a Changeset and commit it, or remove the entry. Then run this tool again.', + ], + }); + } + + if (unfitChangelogs.length > 0) { + throw new ChangesetsSetupError({ + problem: + unfitChangelogs.length === 1 + ? '1 changelog cannot take the new release section:' + : `${unfitChangelogs.length} changelogs cannot take the new release section:`, + details: [ + ...unfitChangelogs, + 'A changelog with no release yet must not have link reference definitions, such as "[Unreleased]: ...". Remove them, then run this tool again.', + ], + }); + } +} + +/** + * Writes the new version of the root package to its manifest. The manifest is + * read from disk, to keep the ranges that `applyReleasePlan` wrote to it. + * + * @param args - The arguments. + * @param args.project - The project. + * @param args.newRootVersion - The new version of the root package. + */ +async function bumpRootVersion({ + project, + newRootVersion, +}: { + project: Project; + newRootVersion: string; +}): Promise { + const { manifestPath } = project.rootPackage; + await writeJsonFile(manifestPath, { + ...(await readJsonObjectFile(manifestPath)), + version: newRootVersion, + }); +} + +/** + * Rewrites the changelog of a released package with auto-changelog. The + * changelog then has a link reference definition for the release section that + * `applyReleasePlan` added, and no empty `Unreleased` section. + * + * @param args - The arguments. + * @param args.project - The project. + * @param args.packageName - The name of the package. + * @param args.formatter - The formatter to use for formatting the changelog. + */ +async function rewriteChangelog({ + project, + packageName, + formatter, +}: { + project: Project; + packageName: string; + formatter: Formatter; +}): Promise { + const { changelogPath } = project.workspacePackages[packageName]; + if (!(await fileExists(changelogPath))) { + return; + } + const changelog = parseChangelog({ + changelogContent: await readFile(changelogPath), + repoUrl: project.repositoryUrl, + tagPrefix: `${packageName}@`, + formatter: getFormatter(formatter), + allowMissingUnreleasedSection: true, + removeEmptyUnreleasedSection: true, + }); + await writeFile(changelogPath, await changelog.toString()); +} + +/** + * Runs `applyReleasePlan` without the lines that it writes to the console when + * it fails. The error that it throws describes the failure. + * + * @param args - The arguments of `applyReleasePlan`. + */ +async function applyReleasePlanQuietly( + ...args: Parameters +): Promise { + const { error } = console; + console.error = (): void => { + // Drop the message. + }; + try { + await applyReleasePlan(...args); + } finally { + console.error = error; + } +} + +/** + * Writes the release to the project. + * + * @param args - The arguments. + * @param args.project - The project. + * @param args.data - The plan data. + * @param args.newRootVersion - The new version of the root package. + * @param args.formatter - The formatter to use for formatting the changelogs. + */ +async function writeRelease({ + project, + data, + newRootVersion, + formatter, +}: { + project: Project; + data: ChangesetsPlanData; + newRootVersion: string; + formatter: Formatter; +}): Promise { + const { state, filteredPlan, selectedChangesets } = data; + await applyReleasePlanQuietly(filteredPlan, state.packages, state.config); + + for (const { name } of filteredPlan.releases.filter(isBumpingRelease)) { + await rewriteChangelog({ project, packageName: name, formatter }); + } + + await bumpRootVersion({ project, newRootVersion }); + + for (const { id, releases } of selectedChangesets) { + await restoreResidualChangesets({ + changesetDir: path.join(project.directoryPath, '.changeset'), + changesets: state.fullPlan.changesets.filter( + (changeset) => changeset.id === id, + ), + releasedPackageNames: releases.map(({ name }) => name), + }); + } +} + +/** + * Applies a Changesets release to the project. The Changesets that the + * release only partly consumes are restored with the releases it leaves out. + * + * @param args - The arguments. + * @param args.project - The project. + * @param args.data - The plan data. + * @param args.newRootVersion - The new version of the root package. + * @param args.formatter - The formatter to use for formatting the changelogs. + * @throws A `ChangesetsSetupError` if a check fails before any file changes. + * @throws A `ChangesetsApplyError` if a later step fails. + */ +export async function applyChangesetsRelease({ + project, + data, + newRootVersion, + formatter, +}: { + project: Project; + data: ChangesetsPlanData; + newRootVersion: string; + formatter: Formatter; +}): Promise { + await checkChangesetDirectory(project); + await checkChangelogs(project, data); + + try { + await writeRelease({ project, data, newRootVersion, formatter }); + } catch (error) { + throw new ChangesetsApplyError({ cause: error }); + } +} diff --git a/packages/create-release-branch/tsconfig.build.json b/packages/create-release-branch/tsconfig.build.json index 2148bf36..aa5970c7 100644 --- a/packages/create-release-branch/tsconfig.build.json +++ b/packages/create-release-branch/tsconfig.build.json @@ -7,6 +7,7 @@ "types": ["node"] }, "references": [ + { "path": "../apply-release-plan/tsconfig.build.json" }, { "path": "../auto-changelog/tsconfig.build.json" }, { "path": "../changesets-utils/tsconfig.build.json" } ], diff --git a/packages/create-release-branch/tsconfig.json b/packages/create-release-branch/tsconfig.json index 7543b023..4e6a4b15 100644 --- a/packages/create-release-branch/tsconfig.json +++ b/packages/create-release-branch/tsconfig.json @@ -11,6 +11,7 @@ "types": ["node", "react", "react-dom", "vite/client"] }, "references": [ + { "path": "../apply-release-plan" }, { "path": "../auto-changelog" }, { "path": "../changesets-utils" } ], diff --git a/packages/create-release-branch/tsconfig.lint.json b/packages/create-release-branch/tsconfig.lint.json index 09f3ae82..aa81294a 100644 --- a/packages/create-release-branch/tsconfig.lint.json +++ b/packages/create-release-branch/tsconfig.lint.json @@ -5,6 +5,7 @@ "tsBuildInfoFile": "./.tsc-lint-cache/tsconfig.tsbuildinfo" }, "references": [ + { "path": "../apply-release-plan/tsconfig.lint.json" }, { "path": "../auto-changelog/tsconfig.lint.json" }, { "path": "../changesets-utils/tsconfig.lint.json" } ] diff --git a/yarn.lock b/yarn.lock index 4d0bc1d4..c044c1a5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -946,7 +946,7 @@ __metadata: languageName: node linkType: hard -"@metamask/apply-release-plan@workspace:packages/apply-release-plan": +"@metamask/apply-release-plan@npm:^0.0.0, @metamask/apply-release-plan@workspace:packages/apply-release-plan": version: 0.0.0-use.local resolution: "@metamask/apply-release-plan@workspace:packages/apply-release-plan" dependencies: @@ -1090,6 +1090,7 @@ __metadata: "@clack/prompts": "npm:^1.8.1" "@manypkg/get-packages": "npm:^3.1.0" "@metamask/action-utils": "npm:^2.0.0" + "@metamask/apply-release-plan": "npm:^0.0.0" "@metamask/auto-changelog": "npm:^7.1.0" "@metamask/changesets-utils": "npm:^0.0.0" "@metamask/utils": "npm:^11.12.0"