From 8549a7cc58b7ca9f728ed28e36022cfbadf76c8d Mon Sep 17 00:00:00 2001 From: Guillaume Roux Date: Thu, 12 Nov 2026 14:16:39 +0100 Subject: [PATCH] Plan a Changesets release from the release choices Add planChangesetsRelease, which checks the release choices against the Changesets release plan and builds the plan to apply. The choices select the packages, and the Changesets set their versions. A choice that gives another version than the Changesets is an error. Select the Changesets with filterChangesets from changesets-utils. It now keeps the none releases of a kept Changeset, and keeps the Changesets that have only none releases. --- README.md | 1 + packages/changesets-utils/CHANGELOG.md | 3 +- .../src/filter-changesets.test.ts | 45 + .../changesets-utils/src/filter-changesets.ts | 17 +- packages/create-release-branch/package.json | 2 + .../src/core/release-rules.ts | 2 +- .../src/modes/changesets/plan.test.ts | 834 ++++++++++++++++++ .../src/modes/changesets/plan.ts | 241 +++++ .../create-release-branch/tsconfig.build.json | 5 +- packages/create-release-branch/tsconfig.json | 5 +- .../create-release-branch/tsconfig.lint.json | 5 +- yarn.lock | 2 + 12 files changed, 1154 insertions(+), 8 deletions(-) create mode 100644 packages/create-release-branch/src/modes/changesets/plan.test.ts create mode 100644 packages/create-release-branch/src/modes/changesets/plan.ts diff --git a/README.md b/README.md index 5f3b4a7c..081482df 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,7 @@ linkStyle default opacity:0.5 changesets_lint --> auto_changelog; changesets_utils --> auto_changelog; create_release_branch --> auto_changelog; + create_release_branch --> changesets_utils; ``` diff --git a/packages/changesets-utils/CHANGELOG.md b/packages/changesets-utils/CHANGELOG.md index 19797b5c..e9b168c4 100644 --- a/packages/changesets-utils/CHANGELOG.md +++ b/packages/changesets-utils/CHANGELOG.md @@ -11,8 +11,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Add `parseChangesetSummary` for parsing categorized Changeset summaries, and `GrammarError` for structured parse failures ([#41](https://github.com/MetaMask/release-tools/pull/41)) - Summaries contain one entry: a level-two `## ` heading followed by exactly one top-level bullet. Heading categories match case-insensitively and are returned in canonical spelling as `Added`, `Changed`, `Removed`, `Fixed`, `Security`, or `Deprecated` for plugin use. -- Add `filterChangesets` for filtering changesets down to selected package releases ([#76](https://github.com/MetaMask/release-tools/pull/76)) +- Add `filterChangesets` for filtering changesets down to selected package releases ([#76](https://github.com/MetaMask/release-tools/pull/76), [#168](https://github.com/MetaMask/release-tools/pull/168)) - Returns new changeset and release objects, preserves summaries and metadata, drops changesets with no selected releases, and does not mutate its inputs. + - Keeps the `none` releases of a kept changeset, and keeps changesets with only `none` releases, so that a release consumes them. - Add `restoreResidualChangesets` for rewriting Changeset files after a partial release ([#78](https://github.com/MetaMask/release-tools/pull/78)) - Writes back only the releases for packages that were not released, preserves the original summary and bump types, leaves fully consumed Changeset files deleted, and is safe to run more than once. - Export the supported changeset categories for changelog plugins ([#87](https://github.com/MetaMask/release-tools/pull/87)). diff --git a/packages/changesets-utils/src/filter-changesets.test.ts b/packages/changesets-utils/src/filter-changesets.test.ts index 196b5231..eec1bbcf 100644 --- a/packages/changesets-utils/src/filter-changesets.test.ts +++ b/packages/changesets-utils/src/filter-changesets.test.ts @@ -39,6 +39,51 @@ describe('filterChangesets', () => { expect(filterChangesets([changeset], ['@scope/two'])).toStrictEqual([]); }); + it('keeps the none releases of a kept changeset', () => { + const changeset: NewChangesetWithCommit = { + id: 'entry-one', + summary: 'Summary', + releases: [ + { name: '@scope/one', type: 'minor' }, + { name: '@scope/two', type: 'none' }, + { name: '@scope/three', type: 'patch' }, + ], + }; + + expect(filterChangesets([changeset], ['@scope/one'])).toStrictEqual([ + { + ...changeset, + releases: [ + { name: '@scope/one', type: 'minor' }, + { name: '@scope/two', type: 'none' }, + ], + }, + ]); + }); + + it('keeps a changeset with only none releases', () => { + const changeset: NewChangesetWithCommit = { + id: 'entry-one', + summary: 'Summary', + releases: [{ name: '@scope/one', type: 'none' }], + }; + + expect(filterChangesets([changeset], [])).toStrictEqual([changeset]); + }); + + it('drops a changeset without selected releases, with its none releases', () => { + const changeset: NewChangesetWithCommit = { + id: 'entry-one', + summary: 'Summary', + releases: [ + { name: '@scope/one', type: 'major' }, + { name: '@scope/two', type: 'none' }, + ], + }; + + expect(filterChangesets([changeset], ['@scope/three'])).toStrictEqual([]); + }); + it('preserves metadata and clones returned objects', () => { const changeset: NewChangesetWithCommit = { id: 'entry-one', diff --git a/packages/changesets-utils/src/filter-changesets.ts b/packages/changesets-utils/src/filter-changesets.ts index 24371fd1..7bcbb72b 100644 --- a/packages/changesets-utils/src/filter-changesets.ts +++ b/packages/changesets-utils/src/filter-changesets.ts @@ -3,12 +3,16 @@ import type { NewChangesetWithCommit } from '@changesets/types'; /** * Returns changesets with releases limited to the selected package names. * + * A kept changeset also keeps its `none` releases, and a changeset with only + * `none` releases is always kept, so that a release consumes them. + * * The returned changesets and releases are shallow clones. The input values * are not modified. * * @param changesets - Changesets to filter. * @param selected - Package names to keep. - * @returns Changesets that retain at least one selected release. + * @returns Changesets that retain at least one selected release, and + * changesets with only `none` releases. */ export function filterChangesets( changesets: readonly NewChangesetWithCommit[], @@ -17,10 +21,17 @@ export function filterChangesets( const selectedNames = new Set(selected); return changesets.flatMap((changeset) => { + const isKept = + changeset.releases.every(({ type }) => type === 'none') || + changeset.releases.some(({ name }) => selectedNames.has(name)); + if (!isKept) { + return []; + } + const releases = changeset.releases - .filter(({ name }) => selectedNames.has(name)) + .filter(({ name, type }) => type === 'none' || selectedNames.has(name)) .map((release) => ({ ...release })); - return releases.length > 0 ? [{ ...changeset, releases }] : []; + return [{ ...changeset, releases }]; }); } diff --git a/packages/create-release-branch/package.json b/packages/create-release-branch/package.json index e6ac9729..b706d642 100644 --- a/packages/create-release-branch/package.json +++ b/packages/create-release-branch/package.json @@ -44,6 +44,7 @@ "test:watch": "vitest --watch" }, "dependencies": { + "@changesets/assemble-release-plan": "^7.0.0", "@changesets/config": "^4.0.1", "@changesets/get-release-plan": "^5.0.2", "@changesets/types": "^7.0.0", @@ -51,6 +52,7 @@ "@manypkg/get-packages": "^3.1.0", "@metamask/action-utils": "^2.0.0", "@metamask/auto-changelog": "^7.1.0", + "@metamask/changesets-utils": "^0.0.0", "@metamask/utils": "^11.12.0", "debug": "^4.3.4", "execa": "^8.0.1", diff --git a/packages/create-release-branch/src/core/release-rules.ts b/packages/create-release-branch/src/core/release-rules.ts index 539439ae..df586541 100644 --- a/packages/create-release-branch/src/core/release-rules.ts +++ b/packages/create-release-branch/src/core/release-rules.ts @@ -20,7 +20,7 @@ export type IncrementableVersionPart = (typeof IncrementableVersionParts)[keyof typeof IncrementableVersionParts]; export const SKIP_PACKAGE_DIRECTIVE = null; -const INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE = 'intentionally-skip'; +export const INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE = 'intentionally-skip'; /** * The maintainer's choice for each package, as given: a bump type, an exact diff --git a/packages/create-release-branch/src/modes/changesets/plan.test.ts b/packages/create-release-branch/src/modes/changesets/plan.test.ts new file mode 100644 index 00000000..a1fdc2fe --- /dev/null +++ b/packages/create-release-branch/src/modes/changesets/plan.test.ts @@ -0,0 +1,834 @@ +import { assembleReleasePlan } from '@changesets/assemble-release-plan'; +import { defaultConfig } from '@changesets/config'; +import type { + Config, + NewChangeset, + Packages, + VersionType, +} from '@changesets/types'; +import { describe, expect, it } 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 type { ReleaseChoices } from '../../core/release-rules.js'; +import type { Project } from '../../project/project.js'; +import { compareNames, listChangesetsCandidates } from './candidates.js'; +import type { ChangesetsState } from './load.js'; +import { planChangesetsRelease } from './plan.js'; +import type { ChangesetsPlanData } from './plan.js'; + +/** + * A workspace package of a fixture. + */ +type FixturePackage = { + name: string; + version: string; + dependencies?: Record; + peerDependencies?: Record; + optionalDependencies?: Record; +}; + +/** + * A pending Changeset of a fixture. + */ +type FixtureChangeset = { + id: string; + releases: Record; + summary: string; +}; + +/** + * The workspace packages, the pending Changesets, and the Changesets + * configuration of a fixture. + */ +type FixtureOptions = { + packages: FixturePackage[]; + changesets?: FixtureChangeset[]; + config?: Partial; +}; + +const FIXTURE: FixtureOptions = { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/b', version: '1.0.0' }, + { + name: '@scope/c', + version: '1.0.0', + dependencies: { '@scope/b': '^1.0.0' }, + }, + { name: '@scope/d', version: '0.1.0' }, + { name: '@scope/f', version: '1.0.0' }, + { + name: '@scope/h', + version: '1.0.0', + dependencies: { '@scope/c': '1.0.0' }, + }, + { name: '@scope/n', version: '1.0.0' }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor' }, + summary: 'Add a feature to a', + }, + { + id: 'eager-owls-fly', + releases: { '@scope/a': 'patch', '@scope/d': 'minor' }, + summary: 'Fix a and add a feature to d', + }, + { + id: 'calm-dogs-run', + releases: { '@scope/b': 'major' }, + summary: 'Break b', + }, + { + id: 'quiet-fish-nap', + releases: { '@scope/f': 'none' }, + summary: 'Touch f without releasing it', + }, + ], +}; + +/** + * The choices that keep the bumps that the Changesets give for `FIXTURE`. + */ +const PROPOSED_CHOICES: ReleaseChoices = { + '@scope/a': 'minor', + '@scope/b': 'major', + '@scope/d': 'minor', + '@scope/c': 'patch', + '@scope/h': 'patch', +}; + +/** + * Builds the project and the Changesets state of a fixture, and lists its + * candidates. The Changesets are sorted by id, as Changesets reads them. + * + * @param options - The fixture. + * @returns The project, the state, and the candidates. + */ +function loadFixture(options: FixtureOptions): { + project: Project; + state: ChangesetsState; + candidates: Candidate[]; +} { + const { packages, changesets = [], config = {} } = options; + const project = buildMockProject({ + workspacePackages: Object.fromEntries( + packages.map(({ name, version }) => [ + name, + buildMockPackage(name, version), + ]), + ), + }); + + const changesetsPackages: Packages = { + rootDir: project.directoryPath, + rootPackage: { + dir: project.directoryPath, + packageJson: { name: 'root', version: '0.0.0', private: true }, + }, + packages: packages.map((packageJson) => ({ + dir: project.workspacePackages[packageJson.name].directoryPath, + packageJson, + })), + tool: { type: 'yarn' }, + }; + const fullConfig: Config = { ...defaultConfig, ...config }; + const pendingChangesets = changesets + .map( + ({ id, releases, summary }): NewChangeset => ({ + id, + summary, + releases: Object.entries(releases).map(([name, type]) => ({ + name, + type, + })), + }), + ) + .sort((left, right) => compareNames(left.id, right.id)); + const state = buildMockChangesetsState({ + packages: changesetsPackages, + config: fullConfig, + fullPlan: assembleReleasePlan( + pendingChangesets, + changesetsPackages, + fullConfig, + undefined, + ), + }); + + return { + project, + state, + candidates: listChangesetsCandidates(project, state), + }; +} + +/** + * Plans a release of a fixture with the given choices. + * + * @param choices - The release choices. + * @param options - The fixture. + * @returns The state and the result. + */ +function planFixture( + choices: ReleaseChoices, + options: FixtureOptions = FIXTURE, +): { + state: ChangesetsState; + result: ModePlanResult; +} { + const input = loadFixture(options); + return { + state: input.state, + result: planChangesetsRelease({ ...input, choices }), + }; +} + +/** + * Plans a release with the given choices, and returns the state and the plan. + * + * @param choices - The release choices. + * @param options - The description of the fixture. + * @returns The state and the plan. + * @throws If the result has errors instead of a plan. + */ +function planFixturePlan( + choices: ReleaseChoices, + options: FixtureOptions = FIXTURE, +): { state: ChangesetsState; plan: ModePlan } { + const { state, result } = planFixture(choices, options); + if (!('plan' in result)) { + throw new Error(`Expected a plan, got: ${JSON.stringify(result.errors)}`); + } + return { state, plan: result.plan }; +} + +/** + * Plans a release with the given choices, and returns the plan data. + * + * @param choices - The release choices. + * @param options - The description of the fixture. + * @returns The plan data. + */ +function planFixtureData( + choices: ReleaseChoices, + options: FixtureOptions = FIXTURE, +): ChangesetsPlanData { + return planFixturePlan(choices, options).plan.data; +} + +/** + * Plans a release with the given choices, and returns the errors. + * + * @param choices - The release choices. + * @param options - The description of the fixture. + * @returns The errors. + */ +function planFixtureErrors( + choices: ReleaseChoices, + options: FixtureOptions = FIXTURE, +): unknown { + const { result } = planFixture(choices, options); + return 'errors' in result ? result.errors : result; +} + +/** + * Picks the name and the new version of each release of the filtered plan. + * + * @param data - The plan data. + * @returns The names and new versions, sorted by name. + */ +function summarizeVersions( + data: ChangesetsPlanData, +): [string, string | undefined][] { + return data.filteredPlan.releases + .map(({ name, newVersion }): [string, string | undefined] => [ + name, + newVersion, + ]) + .sort(([left], [right]) => compareNames(left, right)); +} + +/** + * Picks the id and the releases of each Changeset. + * + * @param changesets - The Changesets. + * @returns The ids and releases. + */ +function summarizeChangesets( + changesets: ChangesetsPlanData['selectedChangesets'], +): { id: string; releases: unknown }[] { + return changesets.map(({ id, releases }) => ({ id, releases })); +} + +/** + * Builds the error for a choice that does not give the version that the + * Changesets give. + * + * @param args - The arguments. + * @param args.packageName - The name of the package. + * @param args.entryIndex - The index of the choice in the release spec. + * @param args.choice - The choice. + * @param args.newVersion - The version that the Changesets give. + * @param args.proposed - The value that gives this version. + * @returns The error. + */ +function buildChangedVersionError({ + packageName, + entryIndex, + choice, + newVersion, + proposed, +}: { + packageName: string; + entryIndex: number; + choice: string; + newVersion: string; + proposed: string; +}): unknown { + return { + packageName, + entryIndex, + problem: `is set to ${choice}, but the Changesets release it as ${newVersion}`, + hint: `Set it to ${proposed}. You cannot change the version of a package in Changesets mode.`, + }; +} + +const UNLISTED_HINT = + 'Add it with a version specifier, or set it to intentionally-skip.'; + +const NOTHING_TO_RELEASE = { + problem: + 'has nothing to release: no selected Changeset and no dependency bump', + hint: 'Remove it, set it to intentionally-skip, or add a Changeset for it.', +}; + +describe('plan', () => { + describe('planChangesetsRelease', () => { + it('plans the full release when the choices keep the proposed bumps', () => { + const { state, plan } = planFixturePlan(PROPOSED_CHOICES); + + expect(plan.releases).toStrictEqual([ + { name: '@scope/a', newVersion: '1.1.0' }, + { name: '@scope/b', newVersion: '2.0.0' }, + { name: '@scope/c', newVersion: '1.0.1' }, + { name: '@scope/d', newVersion: '0.2.0' }, + { name: '@scope/h', newVersion: '1.0.1' }, + ]); + expect(plan.data.state).toBe(state); + expect(plan.data.filteredPlan.releases).toStrictEqual( + state.fullPlan.releases, + ); + }); + + it.each([ + ['@scope/b', '2.0.0'], + ['@scope/c', '1.0.1'], + ])( + 'accepts the exact version that the Changesets give to %s', + (packageName, newVersion) => { + const { plan } = planFixturePlan({ + ...PROPOSED_CHOICES, + [packageName]: newVersion, + }); + + expect(plan.releases).toContainEqual({ name: packageName, newVersion }); + }, + ); + + it.each([ + { packageName: '@scope/a', choice: 'major', entryIndex: 0 }, + { packageName: '@scope/a', choice: 'patch', entryIndex: 0 }, + { packageName: '@scope/a', choice: '1.2.0', entryIndex: 0 }, + ])( + 'reports a package with changes set to $choice instead of the version that its Changesets give', + ({ packageName, choice, entryIndex }) => { + const errors = planFixtureErrors({ + ...PROPOSED_CHOICES, + [packageName]: choice, + }); + + expect(errors).toStrictEqual([ + buildChangedVersionError({ + packageName, + entryIndex, + choice, + newVersion: '1.1.0', + proposed: 'minor', + }), + ]); + }, + ); + + it('reports a dependency bump set to another version than the one that the Changesets give', () => { + const errors = planFixtureErrors({ + ...PROPOSED_CHOICES, + '@scope/c': 'minor', + }); + + expect(errors).toStrictEqual([ + buildChangedVersionError({ + packageName: '@scope/c', + entryIndex: 3, + choice: 'minor', + newVersion: '1.0.1', + proposed: 'patch', + }), + ]); + }); + + it('drops the releases of a package left out, and keeps the other releases of a Changeset that it shares', () => { + const { '@scope/a': _leftOut, ...choices } = PROPOSED_CHOICES; + + const data = planFixtureData(choices); + + expect(data.filteredPlan.releases.map(({ name }) => name)).not.toContain( + '@scope/a', + ); + const expectedChangesets = [ + { + id: 'calm-dogs-run', + releases: [{ name: '@scope/b', type: 'major' }], + }, + { + id: 'eager-owls-fly', + releases: [{ name: '@scope/d', type: 'minor' }], + }, + { + id: 'quiet-fish-nap', + releases: [{ name: '@scope/f', type: 'none' }], + }, + ]; + expect(summarizeChangesets(data.selectedChangesets)).toStrictEqual( + expectedChangesets, + ); + expect(summarizeChangesets(data.filteredPlan.changesets)).toStrictEqual( + expectedChangesets, + ); + }); + + it('does not change the state', () => { + const { project, state, candidates } = loadFixture(FIXTURE); + const fullPlan = structuredClone(state.fullPlan); + + planChangesetsRelease({ + project, + state, + candidates, + choices: { ...PROPOSED_CHOICES, '@scope/a': null }, + }); + + expect(state.fullPlan).toStrictEqual(fullPlan); + }); + + it.each([null, 'intentionally-skip'])( + 'leaves out a package with changes whose choice is %s', + (choice) => { + const data = planFixtureData({ + ...PROPOSED_CHOICES, + '@scope/a': choice, + }); + + expect( + data.filteredPlan.releases.map(({ name }) => name), + ).not.toContain('@scope/a'); + }, + ); + + it('keeps a Changeset that only has none releases', () => { + const data = planFixtureData(PROPOSED_CHOICES); + + expect( + data.filteredPlan.changesets.find(({ id }) => id === 'quiet-fish-nap'), + ).toMatchObject({ releases: [{ name: '@scope/f', type: 'none' }] }); + }); + + it('keeps the none releases of a kept Changeset', () => { + const data = planFixtureData( + { '@scope/a': 'minor' }, + { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/f', version: '1.0.0' }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor', '@scope/f': 'none' }, + summary: 'Add a feature to a', + }, + ], + }, + ); + + expect(summarizeChangesets(data.filteredPlan.changesets)).toStrictEqual([ + { + id: 'brave-cats-sing', + releases: [ + { name: '@scope/a', type: 'minor' }, + { name: '@scope/f', type: 'none' }, + ], + }, + ]); + }); + + it('drops a Changeset of a package left out with its none releases', () => { + const data = planFixtureData( + { '@scope/a': 'minor', '@scope/b': null }, + { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/b', version: '1.0.0' }, + { name: '@scope/f', version: '1.0.0' }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor' }, + summary: 'Add a feature to a', + }, + { + id: 'calm-dogs-run', + releases: { '@scope/b': 'major', '@scope/f': 'none' }, + summary: 'Break b', + }, + ], + }, + ); + + expect(data.filteredPlan.changesets.map(({ id }) => id)).toStrictEqual([ + 'brave-cats-sing', + ]); + }); + + it('leaves out dependency bumps set to intentionally-skip', () => { + const data = planFixtureData({ + ...PROPOSED_CHOICES, + '@scope/c': 'intentionally-skip', + '@scope/h': 'intentionally-skip', + }); + + expect(data.filteredPlan.releases.map(({ name }) => name)).not.toContain( + '@scope/c', + ); + expect(data.filteredPlan.releases.map(({ name }) => name)).not.toContain( + '@scope/h', + ); + }); + + it('reports the chosen packages that have nothing to release', () => { + const { '@scope/b': _leftOut, ...choices } = PROPOSED_CHOICES; + + const errors = planFixtureErrors(choices); + + expect(errors).toStrictEqual([ + { packageName: '@scope/c', entryIndex: 2, ...NOTHING_TO_RELEASE }, + { packageName: '@scope/h', entryIndex: 3, ...NOTHING_TO_RELEASE }, + ]); + }); + + it('reports a dependency bump that is not in the choices', () => { + const { '@scope/c': _leftOut, ...choices } = PROPOSED_CHOICES; + + const errors = planFixtureErrors(choices); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/c', + problem: + 'is released because dependency @scope/b is released as major, but it is not in the release spec', + hint: UNLISTED_HINT, + }, + ]); + }); + + it('reports a peer dependent that is not in the choices', () => { + const errors = planFixtureErrors( + { '@scope/a': 'major' }, + { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { + name: '@scope/p', + version: '1.0.0', + peerDependencies: { '@scope/a': '^1.0.0' }, + }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'major' }, + summary: 'Break a', + }, + ], + }, + ); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/p', + problem: + 'is released because peer dependency @scope/a is released as major, but it is not in the release spec', + hint: UNLISTED_HINT, + }, + ]); + }); + + it('explains a dependency bump that an optional dependency causes', () => { + const errors = planFixtureErrors( + { '@scope/b': 'major' }, + { + packages: [ + { name: '@scope/b', version: '1.0.0' }, + { + name: '@scope/c', + version: '1.0.0', + optionalDependencies: { '@scope/b': '^1.0.0' }, + }, + ], + changesets: [ + { + id: 'calm-dogs-run', + releases: { '@scope/b': 'major' }, + summary: 'Break b', + }, + ], + }, + ); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/c', + problem: + 'is released because dependency @scope/b is released as major, but it is not in the release spec', + hint: UNLISTED_HINT, + }, + ]); + }); + + it('names the first released dependency by name', () => { + const errors = planFixtureErrors( + { '@scope/b': 'major', '@scope/a': 'major' }, + { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/b', version: '1.0.0' }, + { + name: '@scope/c', + version: '1.0.0', + dependencies: { '@scope/b': '^1.0.0', '@scope/a': '^1.0.0' }, + }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'major', '@scope/b': 'major' }, + summary: 'Break a and b', + }, + ], + }, + ); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/c', + problem: + 'is released because dependency @scope/a is released as major, but it is not in the release spec', + hint: UNLISTED_HINT, + }, + ]); + }); + + it('reports a release that is not in the choices and that no dependency explains', () => { + const errors = planFixtureErrors( + { '@scope/a': 'minor' }, + { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/n', version: '1.0.0' }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor' }, + summary: 'Add a feature to a', + }, + ], + config: { fixed: [['@scope/a', '@scope/n']] }, + }, + ); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/n', + problem: + 'is released by the Changesets release plan, but it is not in the release spec', + hint: UNLISTED_HINT, + }, + ]); + }); + + it('releases a package of a fixed group that is in the choices', () => { + const data = planFixtureData( + { '@scope/a': 'minor', '@scope/n': 'minor' }, + { + packages: [ + { name: '@scope/a', version: '1.0.0' }, + { name: '@scope/n', version: '1.0.0' }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor' }, + summary: 'Add a feature to a', + }, + ], + config: { fixed: [['@scope/a', '@scope/n']] }, + }, + ); + + expect(summarizeVersions(data)).toStrictEqual([ + ['@scope/a', '1.1.0'], + ['@scope/n', '1.1.0'], + ]); + }); + + describe('with a linked group', () => { + const LINKED_FIXTURE: FixtureOptions = { + packages: [ + { name: '@scope/a', version: '2.0.0' }, + { name: '@scope/n', version: '1.0.0' }, + ], + changesets: [ + { + id: 'brave-cats-sing', + releases: { '@scope/a': 'minor' }, + summary: 'Add a feature to a', + }, + { + id: 'calm-dogs-run', + releases: { '@scope/n': 'patch' }, + summary: 'Fix n', + }, + ], + config: { linked: [['@scope/a', '@scope/n']] }, + }; + + it('gives a package the higher version of its group', () => { + const data = planFixtureData( + { '@scope/a': 'minor', '@scope/n': '2.1.0' }, + LINKED_FIXTURE, + ); + + expect(summarizeVersions(data)).toStrictEqual([ + ['@scope/a', '2.1.0'], + ['@scope/n', '2.1.0'], + ]); + }); + + it.each(['patch', 'minor'])( + 'reports a package set to %s, and gives the exact version in the hint because no bump type gives it', + (choice) => { + const errors = planFixtureErrors( + { '@scope/a': 'minor', '@scope/n': choice }, + LINKED_FIXTURE, + ); + + expect(errors).toStrictEqual([ + buildChangedVersionError({ + packageName: '@scope/n', + entryIndex: 1, + choice, + newVersion: '2.1.0', + proposed: '2.1.0', + }), + ]); + }, + ); + }); + + it('reports a dependency bump that only packages set to intentionally-skip cause', () => { + const errors = planFixtureErrors({ + ...PROPOSED_CHOICES, + '@scope/c': 'intentionally-skip', + }); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/h', + entryIndex: 4, + problem: + 'is released only because of packages set to intentionally-skip', + hint: 'Set it to intentionally-skip too.', + }, + ]); + }); + + it('reports a dependency bump that only packages set to intentionally-skip cause, when it is not in the choices', () => { + const { '@scope/h': _leftOut, ...choices } = PROPOSED_CHOICES; + + const errors = planFixtureErrors({ + ...choices, + '@scope/c': 'intentionally-skip', + }); + + expect(errors).toStrictEqual([ + { + packageName: '@scope/h', + problem: + 'is released only because of packages set to intentionally-skip', + hint: 'Set it to intentionally-skip too.', + }, + ]); + }); + + it('reports choices that release no package', () => { + const errors = planFixtureErrors({ + '@scope/a': null, + '@scope/b': null, + '@scope/d': null, + }); + + expect(errors).toStrictEqual([ + { + problem: 'does not release any package', + hint: 'Set a version specifier for at least one package.', + }, + ]); + }); + + it('reports every problem at once', () => { + const errors = planFixtureErrors({ + ...PROPOSED_CHOICES, + '@scope/a': 'major', + '@scope/c': 'intentionally-skip', + '@scope/n': 'patch', + }); + + expect(errors).toStrictEqual([ + buildChangedVersionError({ + packageName: '@scope/a', + entryIndex: 0, + choice: 'major', + newVersion: '1.1.0', + proposed: 'minor', + }), + { + packageName: '@scope/h', + entryIndex: 4, + problem: + 'is released only because of packages set to intentionally-skip', + hint: 'Set it to intentionally-skip too.', + }, + { packageName: '@scope/n', entryIndex: 5, ...NOTHING_TO_RELEASE }, + ]); + }); + }); +}); diff --git a/packages/create-release-branch/src/modes/changesets/plan.ts b/packages/create-release-branch/src/modes/changesets/plan.ts new file mode 100644 index 00000000..b34e7315 --- /dev/null +++ b/packages/create-release-branch/src/modes/changesets/plan.ts @@ -0,0 +1,241 @@ +import { assembleReleasePlan } from '@changesets/assemble-release-plan'; +import type { + ComprehensiveRelease, + NewChangeset, + Packages, + ReleasePlan, +} from '@changesets/types'; +import { filterChangesets } from '@metamask/changesets-utils'; + +import type { Candidate } from '../../core/candidates.js'; +import type { ModePlanResult } from '../../core/mode.js'; +import { + INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE, + normalizeReleaseChoices, +} from '../../core/release-rules.js'; +import type { + ReleaseChoiceError, + ReleaseChoices, +} from '../../core/release-rules.js'; +import type { VersionSpecifiers } from '../../core/types.js'; +import type { Project } from '../../project/project.js'; +import { semver, SemVer } from '../../utils/semver.js'; +import { compareNames, isBumpingRelease } from './candidates.js'; +import type { BumpingRelease } from './candidates.js'; +import type { ChangesetsState } from './load.js'; + +/** + * What Changesets mode needs to apply a release. + * + * @property filteredPlan - The release plan of the selected Changesets. + * @property selectedChangesets - The Changesets that the release consumes, + * with only the releases that it keeps. + */ +export type ChangesetsPlanData = { + state: ChangesetsState; + filteredPlan: ReleasePlan; + selectedChangesets: NewChangeset[]; +}; + +/** + * Indexes the releases that bump a version by package name. + * + * @param releases - The releases. + * @returns The bumping releases, by package name. + */ +function indexBumpingReleases( + releases: ComprehensiveRelease[], +): Map { + return new Map( + releases.filter(isBumpingRelease).map((release) => [release.name, release]), + ); +} + +/** + * Explains why the plan bumps a package that no selected Changeset names. + * + * @param packageName - The name of the package. + * @param packages - The workspace packages. + * @param releasesByName - The bumping releases, by package name. + * @returns The reason, or undefined if no released dependency explains it. + */ +function getPropagationReason( + packageName: string, + packages: Packages, + releasesByName: ReadonlyMap, +): string | undefined { + // Every release of the plan is for one of the packages. + const { packageJson: manifest } = packages.packages.find( + ({ packageJson }) => packageJson.name === packageName, + ) as Packages['packages'][number]; + const withLabel = ( + ranges: Record | undefined, + label: string, + ): { name: string; range: string; label: string }[] => + Object.entries(ranges ?? {}).map(([name, range]) => ({ + name, + range, + label, + })); + const dependencies = [ + ...withLabel(manifest.dependencies, 'dependency'), + ...withLabel(manifest.optionalDependencies, 'dependency'), + ...withLabel(manifest.peerDependencies, 'peer dependency'), + ].sort((left, right) => compareNames(left.name, right.name)); + + for (const { name, range, label } of dependencies) { + const release = releasesByName.get(name); + if (release !== undefined && !semver.satisfies(release.newVersion, range)) { + return `released because ${label} ${name} is released as ${release.type}`; + } + } + return undefined; +} + +/** + * Gives the version that a version specifier sets. + * + * @param currentVersion - The current version of the package. + * @param specifier - The version specifier. + * @returns The new version. + */ +function getSpecifiedVersion( + currentVersion: string, + specifier: VersionSpecifiers[string], +): string { + return specifier instanceof SemVer + ? specifier.version + : new SemVer(currentVersion).inc(specifier).version; +} + +/** + * What the planning function takes. The choices must have passed the shared + * rules. + */ +type PlanningInput = { + project: Project; + state: ChangesetsState; + candidates: Candidate[]; + choices: ReleaseChoices; +}; + +/** + * Plans a Changesets release from the release choices. The Changesets set the + * version of each package, and the choices only select the packages. + * + * @param input - The planning input. + * @returns The plan, or every problem that prevents it. + */ +export function planChangesetsRelease( + input: PlanningInput, +): ModePlanResult { + const { project, state, candidates, choices } = input; + const specifiers = normalizeReleaseChoices(choices); + const selected = new Set( + candidates + .filter( + ({ name, kind }) => + kind === 'changes' && specifiers[name] !== undefined, + ) + .map(({ name }) => name), + ); + const selectedChangesets = filterChangesets(state.fullPlan.changesets, [ + ...selected, + ]); + const assembledPlan = assembleReleasePlan( + selectedChangesets, + state.packages, + state.config, + state.fullPlan.preState, + ); + const releases = assembledPlan.releases.filter( + ({ name, type }) => + type === 'none' || choices[name] !== INTENTIONALLY_SKIP_PACKAGE_DIRECTIVE, + ); + + const choiceNames = Object.keys(choices); + const getEntryIndex = (packageName: string): { entryIndex?: number } => { + const entryIndex = choiceNames.indexOf(packageName); + return entryIndex === -1 ? {} : { entryIndex }; + }; + + const assembledReleases = indexBumpingReleases(assembledPlan.releases); + const finalReleases = indexBumpingReleases(releases); + const errors: ReleaseChoiceError[] = []; + + for (const { name, type, newVersion } of [...finalReleases.values()].sort( + (left, right) => compareNames(left.name, right.name), + )) { + const specifier = specifiers[name]; + const currentVersion = + project.workspacePackages[name].validatedManifest.version.version; + if ( + !selected.has(name) && + getPropagationReason(name, state.packages, finalReleases) === undefined && + getPropagationReason(name, state.packages, assembledReleases) !== + undefined + ) { + errors.push({ + packageName: name, + ...getEntryIndex(name), + problem: + 'is released only because of packages set to intentionally-skip', + hint: 'Set it to intentionally-skip too.', + }); + } else if (specifier === undefined) { + const reason = getPropagationReason(name, state.packages, finalReleases); + errors.push({ + packageName: name, + problem: `is ${reason ?? 'released by the Changesets release plan'}, but it is not in the release spec`, + hint: 'Add it with a version specifier, or set it to intentionally-skip.', + }); + } else if (getSpecifiedVersion(currentVersion, specifier) !== newVersion) { + const proposed = + getSpecifiedVersion(currentVersion, type) === newVersion + ? type + : newVersion; + errors.push({ + packageName: name, + ...getEntryIndex(name), + problem: `is set to ${String(specifier)}, but the Changesets release it as ${newVersion}`, + hint: `Set it to ${proposed}. You cannot change the version of a package in Changesets mode.`, + }); + } + } + + choiceNames.forEach((name, entryIndex) => { + if (specifiers[name] !== undefined && !finalReleases.has(name)) { + errors.push({ + packageName: name, + entryIndex, + problem: + 'has nothing to release: no selected Changeset and no dependency bump', + hint: 'Remove it, set it to intentionally-skip, or add a Changeset for it.', + }); + } + }); + + if (finalReleases.size === 0) { + errors.push({ + problem: 'does not release any package', + hint: 'Set a version specifier for at least one package.', + }); + } + + if (errors.length > 0) { + return { errors }; + } + + return { + plan: { + releases: [...finalReleases.values()] + .map(({ name, newVersion }) => ({ name, newVersion })) + .sort((left, right) => compareNames(left.name, right.name)), + data: { + state, + filteredPlan: { ...assembledPlan, releases }, + selectedChangesets, + }, + }, + }; +} diff --git a/packages/create-release-branch/tsconfig.build.json b/packages/create-release-branch/tsconfig.build.json index ab7dfe1f..2148bf36 100644 --- a/packages/create-release-branch/tsconfig.build.json +++ b/packages/create-release-branch/tsconfig.build.json @@ -6,7 +6,10 @@ "lib": ["ES2023", "DOM", "DOM.Iterable"], "types": ["node"] }, - "references": [{ "path": "../auto-changelog/tsconfig.build.json" }], + "references": [ + { "path": "../auto-changelog/tsconfig.build.json" }, + { "path": "../changesets-utils/tsconfig.build.json" } + ], "include": ["./src"], "exclude": ["**/*.test.ts", "./src/ui/**"] } diff --git a/packages/create-release-branch/tsconfig.json b/packages/create-release-branch/tsconfig.json index 035ac023..7543b023 100644 --- a/packages/create-release-branch/tsconfig.json +++ b/packages/create-release-branch/tsconfig.json @@ -10,6 +10,9 @@ "lib": ["ES2023", "DOM", "DOM.Iterable"], "types": ["node", "react", "react-dom", "vite/client"] }, - "references": [{ "path": "../auto-changelog" }], + "references": [ + { "path": "../auto-changelog" }, + { "path": "../changesets-utils" } + ], "include": ["./src", "./tests"] } diff --git a/packages/create-release-branch/tsconfig.lint.json b/packages/create-release-branch/tsconfig.lint.json index 64057f99..09f3ae82 100644 --- a/packages/create-release-branch/tsconfig.lint.json +++ b/packages/create-release-branch/tsconfig.lint.json @@ -4,5 +4,8 @@ "outDir": "./.tsc-lint-cache", "tsBuildInfoFile": "./.tsc-lint-cache/tsconfig.tsbuildinfo" }, - "references": [{ "path": "../auto-changelog/tsconfig.lint.json" }] + "references": [ + { "path": "../auto-changelog/tsconfig.lint.json" }, + { "path": "../changesets-utils/tsconfig.lint.json" } + ] } diff --git a/yarn.lock b/yarn.lock index 0cbf36ff..4d0bc1d4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1083,6 +1083,7 @@ __metadata: version: 0.0.0-use.local resolution: "@metamask/create-release-branch@workspace:packages/create-release-branch" dependencies: + "@changesets/assemble-release-plan": "npm:^7.0.0" "@changesets/config": "npm:^4.0.1" "@changesets/get-release-plan": "npm:^5.0.2" "@changesets/types": "npm:^7.0.0" @@ -1090,6 +1091,7 @@ __metadata: "@manypkg/get-packages": "npm:^3.1.0" "@metamask/action-utils": "npm:^2.0.0" "@metamask/auto-changelog": "npm:^7.1.0" + "@metamask/changesets-utils": "npm:^0.0.0" "@metamask/utils": "npm:^11.12.0" "@tailwindcss/vite": "npm:^4.0.9" "@types/debug": "npm:^4.1.7"