diff --git a/merged-packages/auto-changelog/CHANGELOG.md b/merged-packages/auto-changelog/CHANGELOG.md index ebe33669..f98bb001 100644 --- a/merged-packages/auto-changelog/CHANGELOG.md +++ b/merged-packages/auto-changelog/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **BREAKING:** Drop CommonJS support ([#100](https://github.com/MetaMask/release-tools/pull/100)) + - This package is now ESM-only, but can still be used in CommonJS projects via `require(esm)` in modern Node.js versions (22+), or dynamic imports in older Node.js versions. - This package was migrated from [`MetaMask/auto-changelog`](https://github.com/MetaMask/auto-changelog). See [the original changelog](https://github.com/MetaMask/auto-changelog/blob/v6.2.1/CHANGELOG.md) for changes prior to the migration. [Unreleased]: https://github.com/MetaMask/release-tools/ diff --git a/merged-packages/auto-changelog/jest.config.js b/merged-packages/auto-changelog/jest.config.js deleted file mode 100644 index 9dd60370..00000000 --- a/merged-packages/auto-changelog/jest.config.js +++ /dev/null @@ -1,28 +0,0 @@ -module.exports = { - collectCoverage: true, - collectCoverageFrom: ['./src/**.ts'], - // Jest (i.e. istanbul) identifies every export in index.ts as a distinct - // function, which tanks our function coverage. - coveragePathIgnorePatterns: ['index.ts'], - coverageReporters: ['text', 'html'], - coverageThreshold: { - global: { - branches: 66, - functions: 77, - lines: 74, - statements: 74, - }, - }, - moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'], - preset: 'ts-jest', - // "resetMocks" resets all mocks, including mocked modules, to jest.fn(), - // between each test case. - resetMocks: true, - // "restoreMocks" restores all mocks created using jest.spyOn to their - // original implementations, between each test. It does not affect mocked - // modules. - restoreMocks: true, - testEnvironment: 'node', - testRegex: ['\\.test\\.(ts|js)$'], - testTimeout: 2500, -}; diff --git a/merged-packages/auto-changelog/package.json b/merged-packages/auto-changelog/package.json index 45177832..e8497859 100644 --- a/merged-packages/auto-changelog/package.json +++ b/merged-packages/auto-changelog/package.json @@ -6,91 +6,68 @@ "Ethereum", "MetaMask" ], - "homepage": "https://github.com/MetaMask/auto-changelog#readme", + "homepage": "https://github.com/MetaMask/release-tools/tree/main/packages/auto-changelog#readme", "bugs": { - "url": "https://github.com/MetaMask/auto-changelog/issues" + "url": "https://github.com/MetaMask/release-tools/issues" }, + "license": "(MIT OR Apache-2.0)", "repository": { "type": "git", - "url": "https://github.com/MetaMask/auto-changelog.git" + "url": "https://github.com/MetaMask/release-tools.git" }, - "license": "(MIT OR Apache-2.0)", + "bin": "dist/cli.js", + "files": [ + "dist/" + ], + "type": "module", "sideEffects": false, "exports": { ".": { - "import": { - "types": "./dist/index.d.mts", - "default": "./dist/index.mjs" - }, - "require": { - "types": "./dist/index.d.cts", - "default": "./dist/index.cjs" - } + "types": "./dist/index.d.ts", + "default": "./dist/index.js" }, "./package.json": "./package.json" }, - "main": "./dist/index.cjs", - "module": "./dist/index.mjs", - "types": "./dist/index.d.cts", - "bin": "dist/cli.mjs", - "files": [ - "dist" - ], - "scripts": { - "build": "ts-bridge --project tsconfig.build.json --clean", - "changelog": "node dist/cli.mjs", - "lint": "yarn lint:eslint && yarn lint:misc --check", - "lint:eslint": "eslint . --cache --ext js,ts", - "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", - "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore", - "prepack": "./scripts/prepack.sh", - "test": "jest && attw --pack", - "test:watch": "jest --watch" + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" }, - "resolutions": { - "fflate": "0.8.2" + "scripts": { + "build": "tsc --project tsconfig.build.json", + "build:all": "tsc --build tsconfig.build.json --verbose", + "build:clean": "yarn build:only-clean && yarn build", + "build:docs": "typedoc", + "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'", + "changelog:update": "../../scripts/update-changelog.sh @metamask/auto-changelog", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/auto-changelog", + "since-latest-release": "../../scripts/since-latest-release.sh", + "test": "vitest", + "test:clean": "vitest --clearCache", + "test:package": "attw --pack", + "test:verbose": "vitest --reporter=verbose", + "test:watch": "vitest --watch" }, "dependencies": { "@octokit/rest": "^20.0.0", "diff": "^5.0.0", - "execa": "^5.1.1", - "semver": "^7.3.5", - "yargs": "^17.0.1" + "execa": "^8.0.1", + "semver": "^7.8.5", + "yargs": "^17.7.2" }, "devDependencies": { "@arethetypeswrong/cli": "^0.15.3", - "@lavamoat/allow-scripts": "^2.1.0", - "@vitest/coverage-istanbul": "^5.0.1", - "@metamask/eslint-config": "^11.1.0", - "@metamask/eslint-config-jest": "^11.1.0", - "@metamask/eslint-config-nodejs": "^11.1.0", - "@metamask/eslint-config-typescript": "^11.1.0", - "@ts-bridge/cli": "^0.6.3", - "@types/cross-spawn": "^6.0.2", "@types/diff": "^5.0.0", - "@types/jest": "^26.0.23", "@types/node": "^22.18.0", - "@types/semver": "^7.3.6", - "@types/yargs": "^16.0.1", - "@typescript-eslint/eslint-plugin": "^5.42.1", - "@typescript-eslint/parser": "^5.42.1", - "eslint": "^8.40.0", - "eslint-config-prettier": "^9.1.0", - "eslint-plugin-import": "^2.26.0", - "eslint-plugin-jest": "^27.1.5", - "eslint-plugin-jsdoc": "^39.6.2", - "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^5.2.1", - "jest": "^29.7.0", + "@types/semver": "^7", + "@types/yargs": "^17.0.33", + "@vitest/coverage-istanbul": "^5.0.1", "nock": "^14.0.17", "outdent": "^0.8.0", "oxfmt": "^0.45.0", "prettier": "^3.3.3", - "prettier-plugin-packagejson": "^2.5.2", - "rimraf": "^3.0.2", - "ts-jest": "^29.2.5", + "rimraf": "^5.0.5", "typedoc": "^0.25.13", - "typescript": "~4.8.4", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vitest": "^5.0.1" }, "peerDependencies": { @@ -105,17 +82,7 @@ "optional": true } }, - "packageManager": "yarn@4.16.0", "engines": { - "node": "^18.20 || ^20.17 || >=22" - }, - "publishConfig": { - "access": "public", - "registry": "https://registry.npmjs.org/" - }, - "lavamoat": { - "allowScripts": { - "@lavamoat/preinstall-always-fail": false - } + "node": "^22.16.0 || ^24" } } diff --git a/merged-packages/auto-changelog/src/changelog.test.ts b/merged-packages/auto-changelog/src/changelog.test.ts index efa96ead..2d6171a9 100644 --- a/merged-packages/auto-changelog/src/changelog.test.ts +++ b/merged-packages/auto-changelog/src/changelog.test.ts @@ -1,9 +1,10 @@ -import _outdent from 'outdent'; +import { outdent as outdentFactory } from 'outdent'; +import { describe, expect, it } from 'vitest'; -import Changelog from './changelog'; -import { ChangeCategory } from './constants'; +import Changelog from './changelog.js'; +import { ChangeCategory } from './constants.js'; -const outdent = _outdent({ trimTrailingNewline: false }); +const outdent = outdentFactory({ trimTrailingNewline: false }); const emptyChangelog = `# Changelog All notable changes to this project will be documented in this file. diff --git a/merged-packages/auto-changelog/src/changelog.ts b/merged-packages/auto-changelog/src/changelog.ts index 2853dae3..28981727 100644 --- a/merged-packages/auto-changelog/src/changelog.ts +++ b/merged-packages/auto-changelog/src/changelog.ts @@ -5,9 +5,9 @@ import { orderedChangeCategories, unreleased, Version, -} from './constants'; -import * as formatters from './formatters'; -import { PackageRename } from './shared-types'; +} from './constants.js'; +import * as formatters from './formatters.js'; +import { PackageRename } from './shared-types.js'; /** * The name of the formatter to use when formatting the changelog string. @@ -44,7 +44,7 @@ export async function format( * derived from the object itself. */ export function getKnownPropertyNames( - object: Partial>, + object: Partial>, ): Key[] { return Object.getOwnPropertyNames(object) as Key[]; } @@ -137,7 +137,7 @@ function stringifyCategory( changes: Change[], repoUrl: string, useShortPrLink = false, -) { +): string { const categoryHeader = `### ${category}`; if (changes.length === 0) { return categoryHeader; @@ -180,7 +180,7 @@ function stringifyRelease( repoUrl: string, useShortPrLink = false, { date, status }: Partial = {}, -) { +): string { const releaseHeader = `## [${version}]${date ? ` - ${date}` : ''}${ status ? ` [${status}]` : '' }`; @@ -211,7 +211,7 @@ function stringifyReleases( changes: ChangelogChanges, repoUrl: string, useShortPrLink = false, -) { +): string { const stringifiedUnreleased = stringifyRelease( unreleased, changes[unreleased], @@ -221,8 +221,8 @@ function stringifyReleases( const stringifiedReleases = releases.map(({ version, date, status }) => { const categories = changes[version]; return stringifyRelease(version, categories, repoUrl, useShortPrLink, { - date, - status, + ...(date !== undefined && { date }), + ...(status !== undefined && { status }), }); }); @@ -236,7 +236,7 @@ function stringifyReleases( * @param url - The URL string. * @returns The URL string with a trailing slash. */ -function withTrailingSlash(url: string) { +function withTrailingSlash(url: string): string { return url.endsWith('/') ? url : `${url}/`; } @@ -248,7 +248,11 @@ function withTrailingSlash(url: string) { * @param secondRef - A reference (e.g., commit hash, tag, etc.) to the second commit to compare. * @returns The comparison URL for the two given commits. */ -function getCompareUrl(repoUrl: string, firstRef: string, secondRef: string) { +function getCompareUrl( + repoUrl: string, + firstRef: string, + secondRef: string, +): string { return `${withTrailingSlash(repoUrl)}compare/${firstRef}...${secondRef}`; } @@ -259,7 +263,7 @@ function getCompareUrl(repoUrl: string, firstRef: string, secondRef: string) { * @param tag - The tag name. * @returns The URL for the given tag. */ -function getTagUrl(repoUrl: string, tag: string) { +function getTagUrl(repoUrl: string, tag: string): string { return `${withTrailingSlash(repoUrl)}releases/tag/${tag}`; } @@ -280,7 +284,7 @@ function stringifyLinkReferenceDefinitions( tagPrefix: string, releases: ReleaseMetadata[], packageRename?: PackageRename, -) { +): string { const unreleasedLinkReferenceDefinition = getUnreleasedLinkReferenceDefinition( repoUrl, @@ -337,7 +341,9 @@ function getUnreleasedLinkReferenceDefinition( // if there is a package renamed, the tag prefix before the rename will be considered for compare // [Unreleased]: https://github.com/ExampleUsernameOrOrganization/ExampleRepository/compare/test@0.0.2...HEAD const tagPrefixToCompare = - packageRename && packageRename.versionBeforeRename === latestSemverVersion + // oxlint-disable-next-line typescript/prefer-optional-chain -- Optional chaining makes two absent values compare equal. + packageRename !== undefined && + packageRename.versionBeforeRename === latestSemverVersion ? packageRename.tagPrefixBeforeRename : tagPrefix; @@ -376,7 +382,7 @@ function getReleaseLinkReferenceDefinitions( const releaseLinkReferenceDefinitions = releases.map(({ version }) => { let diffUrl; // once the version matches with versionBeforeRename, rest of the lines in changelog will be assumed as migrated tags - if (packageRename && packageRename.versionBeforeRename === version) { + if (packageRename?.versionBeforeRename === version) { tagPrefixToCompare = packageRename.tagPrefixBeforeRename; } @@ -391,10 +397,7 @@ function getReleaseLinkReferenceDefinitions( }); if (previousVersion) { - if ( - packageRename && - packageRename.versionBeforeRename === previousVersion - ) { + if (packageRename?.versionBeforeRename === previousVersion) { // The package was renamed at this version // (the tag prefix holds the new name). diffUrl = getCompareUrl( @@ -494,7 +497,7 @@ export default class Changelog { readonly #tagPrefix: string; - #formatter: Formatter; + readonly #formatter: Formatter; readonly #packageRename: PackageRename | undefined; @@ -511,7 +514,7 @@ export default class Changelog { constructor({ repoUrl, tagPrefix = 'v', - formatter = (changelog) => changelog, + formatter = (changelog): string => changelog, packageRename, }: { repoUrl: string; @@ -542,7 +545,12 @@ export default class Changelog { * @param options.version - The version of the current release, which should * be a [SemVer](https://semver.org/spec/v2.0.0.html)-compatible version. */ - addRelease({ addToStart = true, date, status, version }: AddReleaseOptions) { + addRelease({ + addToStart = true, + date, + status, + version, + }: AddReleaseOptions): void { if (!version) { throw new Error('Version required'); } else if (semver.valid(version) === null) { @@ -552,7 +560,11 @@ export default class Changelog { } this.#changes[version] = {}; - const newRelease = { version, date, status }; + const newRelease = { + version, + ...(date !== undefined && { date }), + ...(status !== undefined && { status }), + }; if (addToStart) { this.#releases.unshift(newRelease); } else { @@ -580,7 +592,7 @@ export default class Changelog { * provided and no description is given, the description is auto-generated * from the bump data. */ - addChange(options: AddChangeOptions) { + addChange(options: AddChangeOptions): void { const { addToStart = true, category, @@ -639,7 +651,7 @@ export default class Changelog { * @param options.prNumbers - New PR numbers (optional). * @param options.dependencyBump - New dependency bump data (optional). */ - updateChange(options: UpdateChangeOptions) { + updateChange(options: UpdateChangeOptions): void { const { version, category, entryIndex, prNumbers } = options; const release = version @@ -697,7 +709,7 @@ export default class Changelog { * * @param version - The release version to migrate unreleased changes to. */ - migrateUnreleasedChangesToRelease(version: Version) { + migrateUnreleasedChangesToRelease(version: Version): void { const releaseChanges = this.#changes[version]; if (!releaseChanges) { throw new Error(`Specified release version does not exist: '${version}'`); @@ -711,7 +723,7 @@ export default class Changelog { ...(unreleasedChanges[category] ?? []), ...(releaseChanges[category] ?? []), ]; - } else { + } else if (unreleasedChanges[category]) { releaseChanges[category] = unreleasedChanges[category]; } } @@ -723,7 +735,7 @@ export default class Changelog { * * @returns The metadata for each release. */ - getReleases() { + getReleases(): ReleaseMetadata[] { return this.#releases; } @@ -733,7 +745,7 @@ export default class Changelog { * @param version - The version of the release to retrieve. * @returns The specified release, or undefined if no such release exists. */ - getRelease(version: Version) { + getRelease(version: Version): ReleaseMetadata | undefined { return this.getReleases().find( ({ version: _version }) => _version === version, ); @@ -747,7 +759,7 @@ export default class Changelog { * @param useShortPrLink - Whether to use short PR links in the changelog entries. * @returns The stringified release, as it appears in the changelog. */ - getStringifiedRelease(version: Version, useShortPrLink = false) { + getStringifiedRelease(version: Version, useShortPrLink = false): string { const release = this.getRelease(version); if (!release) { throw new Error(`Specified release version does not exist: '${version}'`); @@ -768,7 +780,7 @@ export default class Changelog { * @param version - The version of the release being retrieved. * @returns The changes included in the given released. */ - getReleaseChanges(version: Version) { + getReleaseChanges(version: Version): ReleaseChanges { return this.#changes[version]; } @@ -777,7 +789,7 @@ export default class Changelog { * * @returns The changes that have not yet been released. */ - getUnreleasedChanges() { + getUnreleasedChanges(): ReleaseChanges { return this.#changes[unreleased]; } diff --git a/merged-packages/auto-changelog/src/cli.ts b/merged-packages/auto-changelog/src/cli.ts index 6858919b..a983fda6 100644 --- a/merged-packages/auto-changelog/src/cli.ts +++ b/merged-packages/auto-changelog/src/cli.ts @@ -1,4 +1,5 @@ #!/usr/bin/env node +/* oxlint-disable n/hashbang -- TypeScript preserves this shebang in the built CLI. */ import { promises as fs, constants as fsConstants } from 'fs'; import path from 'path'; @@ -7,14 +8,16 @@ import type { Argv } from 'yargs'; import { hideBin } from 'yargs/helpers'; import yargs from 'yargs/yargs'; -import { format, Formatter, FormatterName } from './changelog'; -import { unreleased, Version } from './constants'; -import { readFile, writeFile } from './fs'; -import { createEmptyChangelog } from './init'; -import { findNearestPackageJson, getRepositoryUrl } from './repo'; -import { PackageRename } from './shared-types'; -import { updateChangelog } from './update-changelog'; -import { error, validate } from './validate-command'; +import { format } from './changelog.js'; +import type { Formatter, FormatterName } from './changelog.js'; +import { unreleased } from './constants.js'; +import type { Version } from './constants.js'; +import { readFile, writeFile } from './fs.js'; +import { createEmptyChangelog } from './init.js'; +import { findNearestPackageJson, getRepositoryUrl } from './repo.js'; +import type { PackageRename } from './shared-types.js'; +import { updateChangelog } from './update-changelog.js'; +import { error, validate } from './validate-command/index.js'; const updateEpilog = `New commits will be added to the "${unreleased}" section (or \ to the section for the current release if the '--rc' flag is used) in reverse \ @@ -34,7 +37,7 @@ formatting is correct. Verification of the contents is left for manual review.`; * @param proposedUrl - The URL to validate. * @returns True if the URL is valid, false otherwise. */ -function isValidUrl(proposedUrl: string) { +function isValidUrl(proposedUrl: string): boolean { try { // eslint-disable-next-line no-new new URL(proposedUrl); @@ -128,18 +131,18 @@ async function update({ excludeChoreWithoutChangelogEntry, preventBackfill, verbose, -}: UpdateOptions) { +}: UpdateOptions): Promise { const changelogContent = await readFile(changelogPath); const newChangelogContent = await updateChangelog({ changelogContent, - currentVersion, + ...(currentVersion !== undefined && { currentVersion }), repoUrl, isReleaseCandidate, - projectRootDirectory, + ...(projectRootDirectory !== undefined && { projectRootDirectory }), tagPrefixes: [tagPrefix], formatter, - packageRename, + ...(packageRename !== undefined && { packageRename }), autoCategorize, useChangelogEntry, useShortPrLink, @@ -185,7 +188,11 @@ type InitOptions = { * @param options.repoUrl - The GitHub repository URL for the current project. * @param options.tagPrefix - The prefix used in tags before the version number. */ -async function init({ changelogPath, repoUrl, tagPrefix }: InitOptions) { +async function init({ + changelogPath, + repoUrl, + tagPrefix, +}: InitOptions): Promise { const changelogContent = await createEmptyChangelog({ repoUrl, tagPrefix }); await writeFile(changelogPath, changelogContent); } @@ -201,7 +208,7 @@ the current working directory), and where the changelog path is resolved from \ * @param _yargs - The yargs instance to configure. * @returns A Yargs instance configured with all common commands. */ -function configureCommonCommandOptions(_yargs: Argv) { +function configureCommonCommandOptions(_yargs: Argv): Argv { return _yargs .option('file', { default: 'CHANGELOG.md', @@ -238,11 +245,48 @@ function configureCommonCommandOptions(_yargs: Argv) { }); } +/** + * The parsed command-line arguments for all auto-changelog commands. + */ +type CliArguments = { + file: string; + repo: string; + root?: string; + tagPrefix: string; + versionBeforePackageRename?: string; + tagPrefixBeforePackageRename?: string; + autoCategorize: boolean; + rc: boolean; + currentVersion?: string; + prettier?: boolean; + formatter: string; + useChangelogEntry: boolean; + useShortPrLink: boolean; + requirePrNumbers: boolean; + normalizeToPastTense: boolean; + excludeChoreWithoutChangelogEntry: boolean; + preventBackfill: boolean; + verbose: boolean; + fix: boolean; + prLinks: boolean; + checkDeps: boolean; + fromRef?: string; + toRef: string; + remote: string; + baseBranch?: string; + currentPr?: string; + _: (string | number)[]; + $0: string; +}; + /** * The entrypoint for the auto-changelog CLI. + * + * @returns A promise that resolves when the selected command completes. */ -async function main() { - const { argv } = yargs(hideBin(process.argv)) +async function main(): Promise { + // Yargs cannot infer subcommand option types from a shared `argv`. + const argv = (await yargs(hideBin(process.argv)) .command( 'update', 'Update CHANGELOG.md with any changes made since the most recent release.\nUsage: $0 update [options]', @@ -398,7 +442,8 @@ async function main() { .help('help') .usage( `Utilities for validating and updating "Keep a Changelog" formatted changelogs.\nUsage: $0 [command] [options]`, - ); + ) + .parse()) as CliArguments; const { file: changelogFilename, @@ -458,7 +503,7 @@ async function main() { } const command = argv._[0]; - const formatter = async (changelog: string) => { + const formatter = async (changelog: string): Promise => { // If the deprecated `--prettier` flag is used, it takes precedence over the // `--formatter` option. Otherwise, use the specified formatter, unless it's // "none". @@ -488,7 +533,7 @@ async function main() { if (!currentVersion) { try { const manifestText = await readFile(manifestPath); - const manifest = JSON.parse(manifestText); + const manifest = JSON.parse(manifestText) as { version: string }; currentVersion = manifest.version; } catch (caughtError) { if (hasErrorCode(caughtError)) { @@ -562,13 +607,13 @@ async function main() { } await update({ changelogPath, - currentVersion, + ...(currentVersion !== undefined && { currentVersion }), isReleaseCandidate, repoUrl, - projectRootDirectory, + ...(projectRootDirectory !== undefined && { projectRootDirectory }), tagPrefix, formatter, - packageRename, + ...(packageRename !== undefined && { packageRename }), autoCategorize, useChangelogEntry: Boolean(useChangelogEntry), useShortPrLink: Boolean(useShortPrLink), @@ -597,21 +642,21 @@ async function main() { await validate({ changelogPath, - currentVersion, + ...(currentVersion !== undefined && { currentVersion }), isReleaseCandidate, repoUrl, tagPrefix, fix, formatter, - packageRename, + ...(packageRename !== undefined && { packageRename }), ensureValidPrLinksPresent: prLinks, checkDeps, manifestPath, - fromRef, + ...(fromRef !== undefined && { fromRef }), toRef, remote, - baseBranch, - currentPr, + ...(baseBranch !== undefined && { baseBranch }), + ...(currentPr !== undefined && { currentPr }), }); } else if (command === 'init') { await init({ @@ -620,9 +665,10 @@ async function main() { tagPrefix, }); } - return undefined; } -main().catch((caughtError) => { - error(caughtError); +main().catch((caughtError: unknown) => { + error( + caughtError instanceof Error ? caughtError.message : String(caughtError), + ); }); diff --git a/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.test.ts b/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.test.ts index 24b812e0..4c38f744 100644 --- a/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.test.ts +++ b/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.test.ts @@ -1,7 +1,9 @@ +import { describe, expect, it } from 'vitest'; + /* eslint-disable @typescript-eslint/naming-convention */ -import type { Change, DependencyBump } from './changelog'; -import { ChangeCategory } from './constants'; -import { findDependencyBumpChangelogEntry } from './find-dependency-bump-changelog-entry'; +import type { Change, DependencyBump } from './changelog.js'; +import { ChangeCategory } from './constants.js'; +import { findDependencyBumpChangelogEntry } from './find-dependency-bump-changelog-entry.js'; describe('find-dependency-bump-changelog-entry', () => { describe('findDependencyBumpChangelogEntry', () => { @@ -15,7 +17,7 @@ describe('find-dependency-bump-changelog-entry', () => { ({ description, dependencyBump }) => ({ description, prNumbers: [], - dependencyBump, + ...(dependencyBump !== undefined && { dependencyBump }), }), ), }); diff --git a/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.ts b/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.ts index 20b064cd..066f5fcf 100644 --- a/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.ts +++ b/merged-packages/auto-changelog/src/find-dependency-bump-changelog-entry.ts @@ -1,5 +1,5 @@ -import type { Change, DependencyBump, ReleaseChanges } from './changelog'; -import { ChangeCategory } from './constants'; +import type { Change, DependencyBump, ReleaseChanges } from './changelog.js'; +import { ChangeCategory } from './constants.js'; /** * Result of checking for a changelog entry. diff --git a/merged-packages/auto-changelog/src/formatters.test.ts b/merged-packages/auto-changelog/src/formatters.test.ts index 648fd781..10ded9e7 100644 --- a/merged-packages/auto-changelog/src/formatters.test.ts +++ b/merged-packages/auto-changelog/src/formatters.test.ts @@ -1,4 +1,6 @@ -import { prettier } from './formatters'; +import { describe, expect, it } from 'vitest'; + +import { prettier } from './formatters.js'; describe('oxfmt', () => { // Oxfmt is ESM-only, and Jest doesn't work well with ESM. We'll want to diff --git a/merged-packages/auto-changelog/src/fs.test.ts b/merged-packages/auto-changelog/src/fs.test.ts index 60318131..53ba9577 100644 --- a/merged-packages/auto-changelog/src/fs.test.ts +++ b/merged-packages/auto-changelog/src/fs.test.ts @@ -1,8 +1,9 @@ import { promises as fs } from 'fs'; import os from 'os'; import path from 'path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { readFile, writeFile } from './fs'; +import { readFile, writeFile } from './fs.js'; describe('fs', () => { describe('readFile', () => { diff --git a/merged-packages/auto-changelog/src/generate-diff.test.ts b/merged-packages/auto-changelog/src/generate-diff.test.ts index 6ea17646..e02b23cd 100644 --- a/merged-packages/auto-changelog/src/generate-diff.test.ts +++ b/merged-packages/auto-changelog/src/generate-diff.test.ts @@ -1,8 +1,9 @@ -import _outdent from 'outdent'; +import { outdent as outdentFactory } from 'outdent'; +import { describe, expect, it } from 'vitest'; -import { generateDiff } from './generate-diff'; +import { generateDiff } from './generate-diff.js'; -const outdent = _outdent({ trimTrailingNewline: false }); +const outdent = outdentFactory({ trimTrailingNewline: false }); const testCases = [ { diff --git a/merged-packages/auto-changelog/src/get-dependency-changes.test.ts b/merged-packages/auto-changelog/src/get-dependency-changes.test.ts index 3d6db65c..b2a300f7 100644 --- a/merged-packages/auto-changelog/src/get-dependency-changes.test.ts +++ b/merged-packages/auto-changelog/src/get-dependency-changes.test.ts @@ -1,21 +1,25 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import execa from 'execa'; +import { execa } from 'execa'; +import { describe, expect, it, vi } from 'vitest'; +import type { MockedFunction } from 'vitest'; -import { getDependencyChanges } from './get-dependency-changes'; +import { getDependencyChanges } from './get-dependency-changes.js'; -jest.mock('execa'); +vi.mock('execa'); -const execaMock = execa as jest.MockedFunction; +const execaMock = execa as MockedFunction; /** * Helper to build a mock for execa calls. Enqueues responses in order. * * @param responses - The mock responses to enqueue. */ -function mockExecaResponses(...responses: ({ stdout: string } | Error)[]) { +function mockExecaResponses( + ...responses: ({ stdout: string } | Error)[] +): void { for (const response of responses) { if (response instanceof Error) { - execaMock.mockRejectedValueOnce(response as never); + execaMock.mockRejectedValueOnce(response); } else { execaMock.mockResolvedValueOnce(response as never); } diff --git a/merged-packages/auto-changelog/src/get-dependency-changes.ts b/merged-packages/auto-changelog/src/get-dependency-changes.ts index 0dee24b0..d1acdb22 100644 --- a/merged-packages/auto-changelog/src/get-dependency-changes.ts +++ b/merged-packages/auto-changelog/src/get-dependency-changes.ts @@ -1,7 +1,7 @@ import path from 'path'; -import type { DependencyBump } from './changelog'; -import { runCommand } from './run-command'; +import type { DependencyBump } from './changelog.js'; +import { runCommand } from './run-command.js'; /** * Thrown when the base ref cannot be auto-detected, typically because @@ -256,14 +256,14 @@ export async function getDependencyChanges({ let oldPkg: PackageJson; let newPkg: PackageJson; try { - oldPkg = JSON.parse(oldContent); + oldPkg = JSON.parse(oldContent) as PackageJson; } catch { throw new Error( `Could not parse ${relativePath} at ref ${actualFromRef} as JSON`, ); } try { - newPkg = JSON.parse(newContent); + newPkg = JSON.parse(newContent) as PackageJson; } catch { throw new Error(`Could not parse ${relativePath} at ref ${toRef} as JSON`); } diff --git a/merged-packages/auto-changelog/src/get-new-changes.test.ts b/merged-packages/auto-changelog/src/get-new-changes.test.ts index 04227847..75646e17 100644 --- a/merged-packages/auto-changelog/src/get-new-changes.test.ts +++ b/merged-packages/auto-changelog/src/get-new-changes.test.ts @@ -1,12 +1,23 @@ import nock from 'nock'; - -import { getNewChangeEntries } from './get-new-changes'; -import { runCommand, runCommandAndSplit } from './run-command'; - -jest.mock('./run-command'); - -const mockRunCommand = runCommand as jest.MockedFunction; -const mockRunCommandAndSplit = runCommandAndSplit as jest.MockedFunction< +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + vi, +} from 'vitest'; +import type { MockedFunction } from 'vitest'; + +import { getNewChangeEntries } from './get-new-changes.js'; +import { runCommand, runCommandAndSplit } from './run-command.js'; + +vi.mock('./run-command'); + +const mockRunCommand = runCommand as MockedFunction; +const mockRunCommandAndSplit = runCommandAndSplit as MockedFunction< typeof runCommandAndSplit >; @@ -18,7 +29,7 @@ const repoUrl = 'https://github.com/MetaMask/metamask-mobile'; * @param labels - The label names to return. * @returns The Nock scope for the mocked endpoint. */ -function mockPrLabels(labels: string[] = []) { +function mockPrLabels(labels: string[] = []): ReturnType { return nock('https://api.github.com') .persist() .get(/\/repos\/MetaMask\/metamask-mobile\/pulls\/\d+/u) @@ -77,7 +88,7 @@ describe('getNewChangeEntries', () => { it('logs commit decisions when verbose is enabled', async () => { mockRunCommandAndSplit.mockResolvedValueOnce(['commit1']); mockRunCommand.mockResolvedValueOnce('add feature (#12345)'); - const errorSpy = jest + const errorSpy = vi .spyOn(console, 'error') .mockImplementation(() => undefined); @@ -103,7 +114,7 @@ describe('getNewChangeEntries', () => { it('does not log commit decisions by default', async () => { mockRunCommandAndSplit.mockResolvedValueOnce(['commit1']); mockRunCommand.mockResolvedValueOnce('add feature (#12345)'); - const errorSpy = jest + const errorSpy = vi .spyOn(console, 'error') .mockImplementation(() => undefined); @@ -228,7 +239,7 @@ describe('getNewChangeEntries', () => { mockRunCommand.mockResolvedValueOnce( 'fix: resolve a historical issue (#12345)', ); - const errorSpy = jest + const errorSpy = vi .spyOn(console, 'error') .mockImplementation(() => undefined); @@ -417,7 +428,7 @@ describe('getNewChangeEntries', () => { originalSubject: string, cherryPickSubject: string, entry: string, - ) { + ): ReturnType { mockRunCommandAndSplit.mockResolvedValueOnce(['original', 'cherrypick']); mockRunCommand .mockResolvedValueOnce(originalSubject) // original %s @@ -910,7 +921,10 @@ describe('getNewChangeEntries', () => { * @param body - The commit body (`git show %b`). * @returns The resulting change entries. */ - async function runWithEntry(subject: string, body: string) { + async function runWithEntry( + subject: string, + body: string, + ): ReturnType { mockRunCommandAndSplit.mockResolvedValueOnce(['commit1']); mockRunCommand .mockResolvedValueOnce(subject) // %s @@ -1856,7 +1870,7 @@ describe('getNewChangeEntries', () => { * * @returns The resulting change entries. */ - async function run() { + async function run(): ReturnType { mockRunCommandAndSplit.mockResolvedValueOnce(['commit1']); return getNewChangeEntries({ mostRecentTag: 'v1.0.0', diff --git a/merged-packages/auto-changelog/src/get-new-changes.ts b/merged-packages/auto-changelog/src/get-new-changes.ts index 30f128e2..c02de0a9 100644 --- a/merged-packages/auto-changelog/src/get-new-changes.ts +++ b/merged-packages/auto-changelog/src/get-new-changes.ts @@ -3,9 +3,9 @@ import { Octokit } from '@octokit/rest'; import { ConventionalCommitType, LEADING_VERB_TO_PAST_TENSE, -} from './constants'; -import { getOwnerAndRepoFromUrl } from './repo'; -import { runCommand, runCommandAndSplit } from './run-command'; +} from './constants.js'; +import { getOwnerAndRepoFromUrl } from './repo.js'; +import { runCommand, runCommandAndSplit } from './run-command.js'; let github: Octokit; @@ -24,6 +24,12 @@ export type AddNewCommitsOptions = { verbose?: boolean; }; +export type NewChangeEntry = { + description: string; + subject: string; + hasChangelogEntry: boolean; +}; + // Get array of all ConventionalCommitType values const conventionalCommitTypes = Object.values(ConventionalCommitType); @@ -40,7 +46,7 @@ const typesWithPipe = conventionalCommitTypes.join('|'); async function getCommitHashesInRange( commitRange: string, rootDirectory?: string, -) { +): Promise { const revListArgs = ['rev-list', commitRange]; if (rootDirectory) { revListArgs.push(rootDirectory); @@ -136,7 +142,7 @@ function isCherryPickSubject(subject: string): boolean { * @param message - The changelog entry message. * @returns The message without outer backticks. */ -function removeOuterBackticksIfPresent(message: string) { +function removeOuterBackticksIfPresent(message: string): string { return message.replace(/^`(.*)`$/u, '$1'); } @@ -146,7 +152,7 @@ function removeOuterBackticksIfPresent(message: string) { * @param message - The changelog entry message. * @returns The message without Conventional Commit prefix. */ -function removeConventionalCommitPrefixIfPresent(message: string) { +function removeConventionalCommitPrefixIfPresent(message: string): string { const regex = new RegExp(`^(${typesWithPipe})(\\([^)]*\\))?:\\s*`, 'iu'); return message.replace(regex, ''); } @@ -784,16 +790,24 @@ async function getCommits( } } + const cherryPickOriginalSubject = getCherryPickOriginalSubject(subject); + commits.push({ hash: commitHash, - prNumber, + ...(prNumber !== undefined && { prNumber }), subject, description: description.trim(), isMergeCommit, isCherryPick: isCherryPickSubject(subject), - cherryPickOriginalSubject: getCherryPickOriginalSubject(subject), - cherryPickOriginalPrNumber, - changelogEntry: rawChangelogEntry, + ...(cherryPickOriginalSubject !== undefined && { + cherryPickOriginalSubject, + }), + ...(cherryPickOriginalPrNumber !== undefined && { + cherryPickOriginalPrNumber, + }), + ...(rawChangelogEntry !== undefined && { + changelogEntry: rawChangelogEntry, + }), }); if (verbose) { console.error( @@ -811,7 +825,9 @@ async function getCommits( * @param prNumbers - PR numbers in the target changelog section. * @returns A mapping of PR numbers to their matching commit hashes. */ -async function getCommitsForPrNumbers(prNumbers: string[]) { +async function getCommitsForPrNumbers( + prNumbers: string[], +): Promise> { const commitsByPrNumber = new Map(); const targetPrNumbers = new Set(prNumbers); const prNumberPattern = prNumbers.join('|'); @@ -856,7 +872,7 @@ async function preventBackfillCommits( commits: Commit[], targetSectionPrNumbers: string[], verbose: boolean, -) { +): Promise { const commitsByPrNumber = await getCommitsForPrNumbers( targetSectionPrNumbers, ); @@ -1096,7 +1112,7 @@ export async function getNewChangeEntries({ normalizeToPastTense, preventBackfill = false, verbose = false, -}: AddNewCommitsOptions) { +}: AddNewCommitsOptions): Promise { const shouldNormalizeToPastTense = normalizeToPastTense ?? true; const commitRange = mostRecentTag === null ? 'HEAD' : `${mostRecentTag}..HEAD`; @@ -1136,7 +1152,7 @@ export async function getNewChangeEntries({ // line and joins the values, so a well-formed entry never contains the // label. This strip remains only as a safety net for descriptions that // reach here by another path (e.g. merge-commit body lines). - let newDescription = description?.replace(/CHANGELOG entry: /gu, ''); + let newDescription = description.replace(/CHANGELOG entry: /gu, ''); // Strip HTML comments that may come from PR templates to prevent broken markdown if (newDescription) { @@ -1229,7 +1245,7 @@ async function resolveGithubToken(): Promise { /** * Initialize the Octokit GitHub client with authentication token. */ -async function initOctoKit() { +async function initOctoKit(): Promise { const githubToken = await resolveGithubToken(); github = new Octokit({ auth: githubToken }); @@ -1265,8 +1281,7 @@ async function getPrLabels( }); if (pullRequest) { - const labels = pullRequest.labels.map((label: any) => label.name); - return labels; + return pullRequest.labels.map((label) => label.name); } } catch (error: unknown) { // If PR doesn't exist (404), return empty labels instead of throwing diff --git a/merged-packages/auto-changelog/src/index.ts b/merged-packages/auto-changelog/src/index.ts index 10248709..729cf10f 100644 --- a/merged-packages/auto-changelog/src/index.ts +++ b/merged-packages/auto-changelog/src/index.ts @@ -2,18 +2,18 @@ export { default as Changelog, type DependencyBump, type ReleaseChanges, -} from './changelog'; -export { oxfmt, prettier } from './formatters'; +} from './changelog.js'; +export { oxfmt, prettier } from './formatters.js'; export { BaseRefNotFoundError, getDependencyChanges, type DependencyCheckResult, -} from './get-dependency-changes'; -export { createEmptyChangelog } from './init'; -export { parseChangelog } from './parse-changelog'; -export { updateChangelog } from './update-changelog'; +} from './get-dependency-changes.js'; +export { createEmptyChangelog } from './init.js'; +export { parseChangelog } from './parse-changelog.js'; +export { updateChangelog } from './update-changelog.js'; export { ChangelogFormattingError, MissingDependencyEntriesError, validateChangelog, -} from './validate-changelog'; +} from './validate-changelog.js'; diff --git a/merged-packages/auto-changelog/src/init.test.ts b/merged-packages/auto-changelog/src/init.test.ts index 410ab4c9..f3049351 100644 --- a/merged-packages/auto-changelog/src/init.test.ts +++ b/merged-packages/auto-changelog/src/init.test.ts @@ -1,4 +1,6 @@ -import { createEmptyChangelog } from './init'; +import { describe, expect, it } from 'vitest'; + +import { createEmptyChangelog } from './init.js'; const exampleRepoUrl = 'https://github.com/ExampleUsernameOrOrganization/ExampleRepository/'; diff --git a/merged-packages/auto-changelog/src/init.ts b/merged-packages/auto-changelog/src/init.ts index 7b707e88..c6eb5ebd 100644 --- a/merged-packages/auto-changelog/src/init.ts +++ b/merged-packages/auto-changelog/src/init.ts @@ -1,4 +1,4 @@ -import Changelog from './changelog'; +import Changelog from './changelog.js'; /** * Creates a new empty changelog. @@ -14,7 +14,7 @@ export async function createEmptyChangelog({ }: { repoUrl: string; tagPrefix?: string; -}) { +}): Promise { const changelog = new Changelog({ repoUrl, tagPrefix }); return await changelog.toString(); } diff --git a/merged-packages/auto-changelog/src/parse-changelog.test.ts b/merged-packages/auto-changelog/src/parse-changelog.test.ts index 7f74f2d3..0f0a5641 100644 --- a/merged-packages/auto-changelog/src/parse-changelog.test.ts +++ b/merged-packages/auto-changelog/src/parse-changelog.test.ts @@ -1,8 +1,9 @@ -import _outdent from 'outdent'; +import { outdent as outdentFactory } from 'outdent'; +import { describe, expect, it } from 'vitest'; -import { parseChangelog } from './parse-changelog'; +import { parseChangelog } from './parse-changelog.js'; -const outdent = _outdent({ trimTrailingNewline: false }); +const outdent = outdentFactory({ trimTrailingNewline: false }); const repoUrl = 'https://github.com/ExampleUsernameOrOrganization/ExampleRepository'; @@ -156,9 +157,9 @@ describe('parseChangelog', () => { }); expect(changelog.getReleases()).toStrictEqual([ - { date: '2020-01-01', status: undefined, version: '1.0.0' }, - { date: '2020-01-01', status: undefined, version: '0.0.2' }, - { date: '2020-01-01', status: undefined, version: '0.0.1' }, + { date: '2020-01-01', version: '1.0.0' }, + { date: '2020-01-01', version: '0.0.2' }, + { date: '2020-01-01', version: '0.0.1' }, ]); expect(changelog.getReleaseChanges('1.0.0')).toStrictEqual({ @@ -190,7 +191,6 @@ describe('parseChangelog', () => { expect(changelog.getRelease('1.0.0')).toStrictEqual({ date: '2020-01-01', - status: undefined, version: '1.0.0', }); @@ -234,9 +234,9 @@ describe('parseChangelog', () => { }); expect(changelog.getReleases()).toStrictEqual([ - { date: '2020-01-01', status: undefined, version: '1.0.0' }, - { date: '2020-01-01', status: undefined, version: '0.0.2' }, - { date: '2020-01-01', status: undefined, version: '0.0.1' }, + { date: '2020-01-01', version: '1.0.0' }, + { date: '2020-01-01', version: '0.0.2' }, + { date: '2020-01-01', version: '0.0.1' }, ]); expect(changelog.getReleaseChanges('1.0.0')).toStrictEqual({ @@ -300,9 +300,9 @@ describe('parseChangelog', () => { }); expect(changelog.getReleases()).toStrictEqual([ - { date: '2020-01-01', status: undefined, version: '1.0.0-rc.1' }, - { date: '2020-01-01', status: undefined, version: '0.0.2-beta.1' }, - { date: '2020-01-01', status: undefined, version: '0.0.1-alpha.1' }, + { date: '2020-01-01', version: '1.0.0-rc.1' }, + { date: '2020-01-01', version: '0.0.2-beta.1' }, + { date: '2020-01-01', version: '0.0.1-alpha.1' }, ]); }); @@ -538,7 +538,7 @@ describe('parseChangelog', () => { }); expect(changelog.getReleases()).toStrictEqual([ - { date: '2020-01-01', status: undefined, version: '1.0.0' }, + { date: '2020-01-01', version: '1.0.0' }, ]); expect(changelog.getReleaseChanges('1.0.0')).toStrictEqual({ @@ -871,9 +871,9 @@ describe('parseChangelog', () => { }); expect(changelog.getReleases()).toStrictEqual([ - { date: '2020-01-01', status: undefined, version: '1.0.0' }, - { date: '2020-01-01', status: undefined, version: '0.0.2' }, - { date: '2020-01-01', status: undefined, version: '0.0.1' }, + { date: '2020-01-01', version: '1.0.0' }, + { date: '2020-01-01', version: '0.0.2' }, + { date: '2020-01-01', version: '0.0.1' }, ]); expect(changelog.getReleaseChanges('1.0.0')).toStrictEqual({ @@ -905,7 +905,6 @@ describe('parseChangelog', () => { expect(changelog.getRelease('1.0.0')).toStrictEqual({ date: '2020-01-01', - status: undefined, version: '1.0.0', }); diff --git a/merged-packages/auto-changelog/src/parse-changelog.ts b/merged-packages/auto-changelog/src/parse-changelog.ts index 76fc391e..87e56e20 100644 --- a/merged-packages/auto-changelog/src/parse-changelog.ts +++ b/merged-packages/auto-changelog/src/parse-changelog.ts @@ -1,18 +1,21 @@ import semver from 'semver'; -import Changelog, { DependencyBump, Formatter } from './changelog'; -import { ChangeCategory, unreleased } from './constants'; -import { PackageRename } from './shared-types'; +import Changelog from './changelog.js'; +import type { DependencyBump, Formatter } from './changelog.js'; +import { ChangeCategory, unreleased } from './constants.js'; +import type { PackageRename } from './shared-types.js'; /** * Parse a dependency bump description into structured data. * * Detects the following patterns (case-insensitive verb): - * - `[**BREAKING:** ]Bump \`dep\` from \`old\` to \`new\`` - * - `[**BREAKING:** ]Update \`dep\` from \`old\` to \`new\`` - * - `[**BREAKING:** ]Upgrade \`dep\` from \`old\` to \`new\`` - * - `[**BREAKING:** ]Update \`dep\` to \`new\`` (oldVersion omitted) - * - `[**BREAKING:** ]Upgrade \`dep\` to \`new\`` (oldVersion omitted) + * - `[**BREAKING:** ]Bump from to ` + * - `[**BREAKING:** ]Update from to ` + * - `[**BREAKING:** ]Upgrade from to ` + * - `[**BREAKING:** ]Update to ` (oldVersion omitted) + * - `[**BREAKING:** ]Upgrade to ` (oldVersion omitted) + * + * Dependency names and versions are wrapped in backticks in the description. * * Note: The dependency type is inferred heuristically from the description: * entries with `**BREAKING:**` prefix are classified as `peerDependencies`, @@ -62,7 +65,7 @@ function parsePossibleDependencyBumpDescription( * @param line - The string to truncate. * @returns The truncated string. */ -function truncated(line: string) { +function truncated(line: string): string { return line.length > 80 ? `${line.slice(0, 80)}...` : line; } @@ -106,7 +109,7 @@ export function parseChangelog({ changelogContent, repoUrl, tagPrefix = 'v', - formatter = undefined, + formatter, packageRename, shouldExtractPrLinks = false, }: { @@ -116,13 +119,13 @@ export function parseChangelog({ formatter?: Formatter; packageRename?: PackageRename; shouldExtractPrLinks?: boolean; -}) { +}): Changelog { const changelogLines = changelogContent.split(/(?:\r)?\n/u); // Split on either Windows or Unix line endings const changelog = new Changelog({ repoUrl, tagPrefix, - formatter, - packageRename, + ...(formatter !== undefined && { formatter }), + ...(packageRename !== undefined && { packageRename }), }); const repoName = extractRepoName(repoUrl); @@ -159,7 +162,7 @@ export function parseChangelog({ removeTrailingNewline = false, }: { removeTrailingNewline?: boolean; - } = {}) { + } = {}): void { if (!currentChangeEntry) { return; } diff --git a/merged-packages/auto-changelog/src/repo.test.ts b/merged-packages/auto-changelog/src/repo.test.ts index ed15cd35..5ceca8e9 100644 --- a/merged-packages/auto-changelog/src/repo.test.ts +++ b/merged-packages/auto-changelog/src/repo.test.ts @@ -1,8 +1,9 @@ /* eslint-disable node/no-process-env */ import path from 'path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; -import { findNearestPackageJson, getRepositoryUrl } from './repo'; +import { findNearestPackageJson, getRepositoryUrl } from './repo.js'; describe('getRepositoryUrl', () => { const originalNpmPackageRepositoryUrl = @@ -42,10 +43,10 @@ describe('getRepositoryUrl', () => { it('reads the repository URL from the package.json', () => { process.env.npm_package_repository_url = ''; - process.env.PROJECT_CWD = path.resolve(__dirname, '..'); + process.env.PROJECT_CWD = path.resolve(import.meta.dirname, '..'); expect(getRepositoryUrl()).toBe( - 'https://github.com/MetaMask/auto-changelog', + 'https://github.com/MetaMask/release-tools', ); }); @@ -53,10 +54,12 @@ describe('getRepositoryUrl', () => { delete process.env.npm_package_repository_url; delete process.env.PROJECT_CWD; // The auto-changelog project root, which has a `repository` field. - jest.spyOn(process, 'cwd').mockReturnValue(path.resolve(__dirname, '..')); + vi.spyOn(process, 'cwd').mockReturnValue( + path.resolve(import.meta.dirname, '..'), + ); expect(getRepositoryUrl()).toBe( - 'https://github.com/MetaMask/auto-changelog', + 'https://github.com/MetaMask/release-tools', ); }); @@ -65,16 +68,16 @@ describe('getRepositoryUrl', () => { delete process.env.PROJECT_CWD; // A nested directory that has no package.json of its own; the search must // walk up to the project root. - jest.spyOn(process, 'cwd').mockReturnValue(__dirname); + vi.spyOn(process, 'cwd').mockReturnValue(import.meta.dirname); expect(getRepositoryUrl()).toBe( - 'https://github.com/MetaMask/auto-changelog', + 'https://github.com/MetaMask/release-tools', ); }); }); describe('findNearestPackageJson', () => { - const projectRoot = path.resolve(__dirname, '..'); + const projectRoot = path.resolve(import.meta.dirname, '..'); it('finds the package.json in the given directory', () => { expect(findNearestPackageJson(projectRoot)).toBe( @@ -83,14 +86,14 @@ describe('findNearestPackageJson', () => { }); it('walks up to the nearest package.json from a nested directory', () => { - // `__dirname` (the `src` directory) has no package.json of its own. - expect(findNearestPackageJson(__dirname)).toBe( + // `import.meta.dirname` (the `src` directory) has no package.json of its own. + expect(findNearestPackageJson(import.meta.dirname)).toBe( path.join(projectRoot, 'package.json'), ); }); it('defaults to the current working directory', () => { - jest.spyOn(process, 'cwd').mockReturnValue(__dirname); + vi.spyOn(process, 'cwd').mockReturnValue(import.meta.dirname); expect(findNearestPackageJson()).toBe( path.join(projectRoot, 'package.json'), diff --git a/merged-packages/auto-changelog/src/run-command.ts b/merged-packages/auto-changelog/src/run-command.ts index afa0272b..d88af35c 100644 --- a/merged-packages/auto-changelog/src/run-command.ts +++ b/merged-packages/auto-changelog/src/run-command.ts @@ -1,4 +1,5 @@ -import execa from 'execa'; +import { execa } from 'execa'; +import type { Options } from 'execa'; /** * Executes a shell command in a child process and returns what it wrote to @@ -12,7 +13,7 @@ import execa from 'execa'; export async function runCommand( command: string, args: string[], - options?: execa.Options, + options?: Options, ): Promise { return (await execa(command, [...args], options)).stdout; } @@ -30,7 +31,7 @@ export async function runCommand( export async function runCommandAndSplit( command: string, args: string[], - options?: execa.Options, + options?: Options, ): Promise { return (await execa(command, [...args], options)).stdout .trim() diff --git a/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.test.ts b/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.test.ts index e41132e9..495d6a0b 100644 --- a/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.test.ts +++ b/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.test.ts @@ -1,16 +1,17 @@ import { promises as fs } from 'fs'; import os from 'os'; -import _outdent from 'outdent'; +import { outdent as outdentFactory } from 'outdent'; import path from 'path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import type { DependencyBump } from './changelog'; -import { readFile, writeFile } from './fs'; -import { updateChangelogWithDependencyBumps } from './update-changelog-with-dependency-bumps'; +import type { DependencyBump } from './changelog.js'; +import { readFile, writeFile } from './fs.js'; +import { updateChangelogWithDependencyBumps } from './update-changelog-with-dependency-bumps.js'; -const outdent = _outdent({ trimTrailingNewline: false }); +const outdent = outdentFactory({ trimTrailingNewline: false }); const TEST_REPO_URL = 'https://github.com/example-org/example-repo'; -const formatter = async (content: string) => content; +const formatter = async (content: string): Promise => content; /** * Builds a changelog by filling in the header automatically. @@ -697,7 +698,7 @@ describe('updateChangelogWithDependencyBumps', () => { `); await writeFile(changelogPath, initialContent); - const { parseChangelog } = await import('./parse-changelog'); + const { parseChangelog } = await import('./parse-changelog.js'); const parsedChangelog = parseChangelog({ changelogContent: initialContent, repoUrl: TEST_REPO_URL, @@ -744,7 +745,7 @@ describe('updateChangelogWithDependencyBumps', () => { `); await writeFile(changelogPath, initialContent); - const { parseChangelog } = await import('./parse-changelog'); + const { parseChangelog } = await import('./parse-changelog.js'); const parsedChangelog = parseChangelog({ changelogContent: initialContent, repoUrl: TEST_REPO_URL, diff --git a/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.ts b/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.ts index 17f22e60..3fdbaa0f 100644 --- a/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.ts +++ b/merged-packages/auto-changelog/src/update-changelog-with-dependency-bumps.ts @@ -1,9 +1,9 @@ -import type Changelog from './changelog'; -import type { Change, DependencyBump, Formatter } from './changelog'; -import { ChangeCategory } from './constants'; -import { findDependencyBumpChangelogEntry } from './find-dependency-bump-changelog-entry'; -import { readFile, writeFile } from './fs'; -import { parseChangelog } from './parse-changelog'; +import type Changelog from './changelog.js'; +import type { Change, DependencyBump, Formatter } from './changelog.js'; +import { ChangeCategory } from './constants.js'; +import { findDependencyBumpChangelogEntry } from './find-dependency-bump-changelog-entry.js'; +import { readFile, writeFile } from './fs.js'; +import { parseChangelog } from './parse-changelog.js'; /** * Extracts PR numbers from a change entry's description text. @@ -141,7 +141,7 @@ export async function updateChangelogWithDependencyBumps({ const existingOldVersion = entryCheck.existingEntry.dependencyBump?.oldVersion; changelog.updateChange({ - version: currentVersion, + ...(currentVersion !== undefined && { version: currentVersion }), category: ChangeCategory.Changed, entryIndex: entryCheck.entryIndex, dependencyBump: { diff --git a/merged-packages/auto-changelog/src/update-changelog.test.ts b/merged-packages/auto-changelog/src/update-changelog.test.ts index 06b8e05d..dd6dfcba 100644 --- a/merged-packages/auto-changelog/src/update-changelog.test.ts +++ b/merged-packages/auto-changelog/src/update-changelog.test.ts @@ -1,7 +1,9 @@ -import { ChangeCategory } from './constants'; -import * as ChangeLogUtils from './get-new-changes'; -import * as ChangeLogManager from './update-changelog'; -import { getCategory } from './update-changelog'; +import { describe, expect, it, vi } from 'vitest'; + +import { ChangeCategory } from './constants.js'; +import * as ChangeLogUtils from './get-new-changes.js'; +import * as ChangeLogManager from './update-changelog.js'; +import { getCategory } from './update-changelog.js'; const emptyChangelog = `# Changelog All notable changes to this project will be documented in this file. @@ -61,9 +63,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 describe('updateChangelog', () => { it('should contain conventional support mappings categorization when autoCategorize is true', async () => { - jest - .spyOn(ChangeLogUtils, 'getNewChangeEntries') - .mockResolvedValue(getNewChangeEntriesMockData); + vi.spyOn(ChangeLogUtils, 'getNewChangeEntries').mockResolvedValue( + getNewChangeEntriesMockData, + ); const result = await ChangeLogManager.updateChangelog({ ...changelogData, @@ -76,9 +78,9 @@ describe('updateChangelog', () => { }); it('should not contain conventional support mappings categorization when autoCategorize is false', async () => { - jest - .spyOn(ChangeLogUtils, 'getNewChangeEntries') - .mockResolvedValue(getNewChangeEntriesMockData); + vi.spyOn(ChangeLogUtils, 'getNewChangeEntries').mockResolvedValue( + getNewChangeEntriesMockData, + ); const result = await ChangeLogManager.updateChangelog({ ...changelogData, @@ -91,9 +93,9 @@ describe('updateChangelog', () => { }); it('should support useChangelogEntry=true', async () => { - jest - .spyOn(ChangeLogUtils, 'getNewChangeEntries') - .mockResolvedValue(getNewChangeEntriesMockData); + vi.spyOn(ChangeLogUtils, 'getNewChangeEntries').mockResolvedValue( + getNewChangeEntriesMockData, + ); const result = await ChangeLogManager.updateChangelog({ ...changelogData, @@ -105,14 +107,17 @@ describe('updateChangelog', () => { }); it('should have default values for useChangelogEntry and useShortPrLink', async () => { - jest - .spyOn(ChangeLogUtils, 'getNewChangeEntries') - .mockResolvedValue(getNewChangeEntriesMockData); + vi.spyOn(ChangeLogUtils, 'getNewChangeEntries').mockResolvedValue( + getNewChangeEntriesMockData, + ); + // Omit useChangelogEntry and useShortPrLink so their defaults apply. const result = await ChangeLogManager.updateChangelog({ - ...changelogData, - useChangelogEntry: undefined, - useShortPrLink: undefined, + changelogContent: changelogData.changelogContent, + currentVersion: changelogData.currentVersion, + repoUrl: changelogData.repoUrl, + isReleaseCandidate: changelogData.isReleaseCandidate, + autoCategorize: changelogData.autoCategorize, }); expect(result).toContain('### Added\n- New cool feature (#124)'); @@ -120,10 +125,10 @@ describe('updateChangelog', () => { }); it('logs emitted changelog entries when verbose is enabled', async () => { - jest - .spyOn(ChangeLogUtils, 'getNewChangeEntries') - .mockResolvedValue(getNewChangeEntriesMockData); - const errorSpy = jest + vi.spyOn(ChangeLogUtils, 'getNewChangeEntries').mockResolvedValue( + getNewChangeEntriesMockData, + ); + const errorSpy = vi .spyOn(console, 'error') .mockImplementation(() => undefined); @@ -139,7 +144,7 @@ describe('updateChangelog', () => { }); it('passes only target release PRs to the backfill guard', async () => { - const getNewChangeEntriesSpy = jest + const getNewChangeEntriesSpy = vi .spyOn(ChangeLogUtils, 'getNewChangeEntries') .mockResolvedValue([]); diff --git a/merged-packages/auto-changelog/src/update-changelog.ts b/merged-packages/auto-changelog/src/update-changelog.ts index bd9c2a2b..8bae01ad 100644 --- a/merged-packages/auto-changelog/src/update-changelog.ts +++ b/merged-packages/auto-changelog/src/update-changelog.ts @@ -1,16 +1,17 @@ -import type Changelog from './changelog'; -import { Formatter, getKnownPropertyNames } from './changelog'; +import type Changelog from './changelog.js'; +import { getKnownPropertyNames } from './changelog.js'; +import type { Change, Formatter } from './changelog.js'; import { ChangeCategory, ConventionalCommitType, - Version, CHANGELOG_VERB_TO_CATEGORY, keywordsToIndicateExcluded, -} from './constants'; -import { getNewChangeEntries } from './get-new-changes'; -import { parseChangelog } from './parse-changelog'; -import { runCommandAndSplit } from './run-command'; -import { PackageRename } from './shared-types'; +} from './constants.js'; +import type { Version } from './constants.js'; +import { getNewChangeEntries } from './get-new-changes.js'; +import { parseChangelog } from './parse-changelog.js'; +import { runCommandAndSplit } from './run-command.js'; +import type { PackageRename } from './shared-types.js'; /** * Get the most recent tag for a project. @@ -24,7 +25,7 @@ async function getMostRecentTag({ tagPrefixes, }: { tagPrefixes: [string, ...string[]]; -}) { +}): Promise { // Ensure we have all tags on remote (overwrite if necessary) await runCommandAndSplit('git', ['fetch', '--tags', '--force']); @@ -60,7 +61,7 @@ async function getMostRecentTag({ * @param changelog - The changelog. * @returns All commit descriptions included in the given changelog. */ -function getAllChanges(changelog: Changelog) { +function getAllChanges(changelog: Changelog): Change[] { const releases = changelog.getReleases(); const changes = Object.values(changelog.getUnreleasedChanges()).flat(); for (const release of releases) { @@ -77,7 +78,7 @@ function getAllChanges(changelog: Changelog) { * @param changelog - The changelog. * @returns All pull request numbers included in the given changelog. */ -function getAllLoggedPrNumbers(changelog: Changelog) { +function getAllLoggedPrNumbers(changelog: Changelog): string[] { return getAllChanges(changelog).flatMap((change) => change.prNumbers); } @@ -88,7 +89,7 @@ function getAllLoggedPrNumbers(changelog: Changelog) { * @param changelog - The changelog. * @returns All change descriptions included in the given changelog, trimmed. */ -function getAllLoggedDescriptions(changelog: Changelog) { +function getAllLoggedDescriptions(changelog: Changelog): string[] { return getAllChanges(changelog).map((change) => change.description.trim()); } @@ -191,8 +192,8 @@ export async function updateChangelog({ changelogContent, repoUrl, tagPrefix: tagPrefixes[0], - formatter, - packageRename, + ...(formatter !== undefined && { formatter }), + ...(packageRename !== undefined && { packageRename }), shouldExtractPrLinks: true, // By setting this to true, we ensure we don't re-add a PR to the changelog if it was already added in previous releases }); @@ -241,7 +242,7 @@ export async function updateChangelog({ loggedPrNumbers: getAllLoggedPrNumbers(changelog), loggedDescriptions: getAllLoggedDescriptions(changelog), targetSectionPrNumbers, - projectRootDirectory, + ...(projectRootDirectory !== undefined && { projectRootDirectory }), useChangelogEntry, useShortPrLink, requirePrNumbers, @@ -261,7 +262,9 @@ export async function updateChangelog({ if (category !== ChangeCategory.Excluded) { changelog.addChange({ - version: isReleaseCandidate ? currentVersion : undefined, + ...(isReleaseCandidate && currentVersion !== undefined + ? { version: currentVersion } + : {}), category, description: entry.description, }); diff --git a/merged-packages/auto-changelog/src/validate-changelog.test.ts b/merged-packages/auto-changelog/src/validate-changelog.test.ts index 1d25c9ed..39da2a62 100644 --- a/merged-packages/auto-changelog/src/validate-changelog.test.ts +++ b/merged-packages/auto-changelog/src/validate-changelog.test.ts @@ -1,11 +1,11 @@ +import { outdent as outdentFactory } from 'outdent'; /* eslint-disable jest/no-restricted-matchers */ +import { describe, expect, it } from 'vitest'; -import _outdent from 'outdent'; +import { format } from './changelog.js'; +import { validateChangelog } from './validate-changelog.js'; -import { format } from './changelog'; -import { validateChangelog } from './validate-changelog'; - -const outdent = _outdent({ trimTrailingNewline: false }); +const outdent = outdentFactory({ trimTrailingNewline: false }); const emptyChangelog = `# Changelog All notable changes to this project will be documented in this file. diff --git a/merged-packages/auto-changelog/src/validate-changelog.ts b/merged-packages/auto-changelog/src/validate-changelog.ts index 353ef077..7db7ca2f 100644 --- a/merged-packages/auto-changelog/src/validate-changelog.ts +++ b/merged-packages/auto-changelog/src/validate-changelog.ts @@ -1,9 +1,11 @@ -import Changelog, { Change, type DependencyBump, Formatter } from './changelog'; -import { Version, ChangeCategory } from './constants'; -import { findDependencyBumpChangelogEntry } from './find-dependency-bump-changelog-entry'; -import type { DependencyCheckResult } from './get-dependency-changes'; -import { parseChangelog } from './parse-changelog'; -import { PackageRename } from './shared-types'; +import Changelog from './changelog.js'; +import type { Change, DependencyBump, Formatter } from './changelog.js'; +import { ChangeCategory } from './constants.js'; +import type { Version } from './constants.js'; +import { findDependencyBumpChangelogEntry } from './find-dependency-bump-changelog-entry.js'; +import type { DependencyCheckResult } from './get-dependency-changes.js'; +import { parseChangelog } from './parse-changelog.js'; +import type { PackageRename } from './shared-types.js'; /** * Indicates that the changelog is invalid. @@ -201,19 +203,21 @@ export async function validateChangelog({ repoUrl, isReleaseCandidate, tagPrefix = 'v', - formatter = undefined, + formatter, packageRename, ensureValidPrLinksPresent, dependencyCheckResult, -}: ValidateChangelogOptions) { +}: ValidateChangelogOptions): Promise { const normalizedChangelogContent = normalizeLineEndings(changelogContent); const changelog = parseChangelog({ changelogContent: normalizedChangelogContent, repoUrl, tagPrefix, - formatter, - packageRename, - shouldExtractPrLinks: ensureValidPrLinksPresent, + ...(formatter !== undefined && { formatter }), + ...(packageRename !== undefined && { packageRename }), + ...(ensureValidPrLinksPresent !== undefined && { + shouldExtractPrLinks: ensureValidPrLinksPresent, + }), }); validateReleaseCandidateState(changelog, isReleaseCandidate, currentVersion); @@ -243,7 +247,7 @@ function validateReleaseCandidateState( changelog: Changelog, isReleaseCandidate: boolean, currentVersion: Version | undefined, -) { +): void { if (!isReleaseCandidate) { return; } @@ -282,7 +286,7 @@ function validateReleaseCandidateState( * * @param changelog - The parsed changelog. */ -function validatePrLinks(changelog: Changelog) { +function validatePrLinks(changelog: Changelog): void { for (const release of changelog.getReleases()) { const releaseChangesForVersion = changelog.getReleaseChanges( release.version, @@ -309,7 +313,7 @@ function validateDependencyBumps( changelog: Changelog, dependencyCheckResult: DependencyCheckResult, currentVersion: Version | undefined, -) { +): void { const { dependencyChanges } = dependencyCheckResult; if (!dependencyChanges || dependencyChanges.length === 0) { return; @@ -383,7 +387,7 @@ function validateDependencyBumps( async function validateFormatting( changelog: Changelog, normalizedContent: string, -) { +): Promise { const validChangelog = await changelog.toString(); if (normalizeLineEndings(validChangelog) !== normalizedContent) { throw new ChangelogFormattingError({ @@ -398,7 +402,7 @@ async function validateFormatting( * * @param changelog - The parsed changelog. */ -function validateNonEmptyReleases(changelog: Changelog) { +function validateNonEmptyReleases(changelog: Changelog): void { for (const release of changelog.getReleases()) { const releaseChangesForVersion = changelog.getReleaseChanges( release.version, diff --git a/merged-packages/auto-changelog/src/validate-command/cli-utils.ts b/merged-packages/auto-changelog/src/validate-command/cli-utils.ts index a84c4256..857ee0ca 100644 --- a/merged-packages/auto-changelog/src/validate-command/cli-utils.ts +++ b/merged-packages/auto-changelog/src/validate-command/cli-utils.ts @@ -3,7 +3,7 @@ * * @param errorMessage - The error message to log. */ -export function error(errorMessage: string) { +export function error(errorMessage: string): void { console.error(errorMessage); process.exitCode = 1; } diff --git a/merged-packages/auto-changelog/src/validate-command/index.ts b/merged-packages/auto-changelog/src/validate-command/index.ts index 002ad189..94907e46 100644 --- a/merged-packages/auto-changelog/src/validate-command/index.ts +++ b/merged-packages/auto-changelog/src/validate-command/index.ts @@ -1,2 +1,2 @@ -export { validate, type ValidateOptions } from './validate'; -export { error } from './cli-utils'; +export { validate, type ValidateOptions } from './validate.js'; +export { error } from './cli-utils.js'; diff --git a/merged-packages/auto-changelog/src/validate-command/validate.test.ts b/merged-packages/auto-changelog/src/validate-command/validate.test.ts index ff240fde..eb603ef9 100644 --- a/merged-packages/auto-changelog/src/validate-command/validate.test.ts +++ b/merged-packages/auto-changelog/src/validate-command/validate.test.ts @@ -1,28 +1,28 @@ import { promises as fs } from 'fs'; import os from 'os'; -import _outdent from 'outdent'; +import { outdent as outdentFactory } from 'outdent'; import path from 'path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { BaseRefNotFoundError, getDependencyChanges, -} from '../get-dependency-changes'; -import { validate } from './validate'; +} from '../get-dependency-changes.js'; +import { validate } from './validate.js'; +import type { ValidateOptions } from './validate.js'; -const outdent = _outdent({ trimTrailingNewline: false }); +const outdent = outdentFactory({ trimTrailingNewline: false }); // Only mock the getDependencyChanges function — keep BaseRefNotFoundError real. -jest.mock('../get-dependency-changes', () => { - const actual = jest.requireActual('../get-dependency-changes'); +vi.mock(import('../get-dependency-changes.js'), async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, - getDependencyChanges: jest.fn(), + getDependencyChanges: vi.fn(), }; }); -const getDependencyChangesMock = getDependencyChanges as jest.MockedFunction< - typeof getDependencyChanges ->; +const getDependencyChangesMock = vi.mocked(getDependencyChanges); const repoUrl = 'https://github.com/Org/Repo'; @@ -47,7 +47,7 @@ describe('validate', () => { * * @param content - The changelog content. */ - async function writeChangelog(content: string) { + async function writeChangelog(content: string): Promise { await fs.writeFile(changelogPath, content, 'utf-8'); } @@ -74,7 +74,7 @@ describe('validate', () => { * * @returns Default validate options. */ - function defaultOptions() { + function defaultOptions(): ValidateOptions { return { changelogPath, currentVersion: '1.0.0' as const, @@ -82,7 +82,7 @@ describe('validate', () => { repoUrl, tagPrefix: 'v', fix: false, - formatter: async (input: string) => input, + formatter: async (input: string): Promise => input, ensureValidPrLinksPresent: false, manifestPath: '/repo/package.json', }; @@ -122,7 +122,7 @@ describe('validate', () => { getDependencyChangesMock.mockRejectedValue( new BaseRefNotFoundError('on base branch'), ); - const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => { // Do nothing }); @@ -209,7 +209,7 @@ describe('validate', () => { it('prints diff and sets exitCode=1 when fix=false', async () => { await writeChangelog(poorlyFormattedChangelog); - const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => { // Do nothing }); @@ -243,13 +243,15 @@ describe('validate', () => { prNumbers: ['100'], versionChanged: false, }); - const logSpy = jest.spyOn(console, 'log').mockImplementation(() => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => { // Do nothing }); + // Omit currentVersion to exercise the no-version path. + const { currentVersion, ...optionsWithoutVersion } = defaultOptions(); + await validate({ - ...defaultOptions(), - currentVersion: undefined, + ...optionsWithoutVersion, checkDeps: true, fix: true, currentPr: '200', @@ -270,7 +272,7 @@ describe('validate', () => { prNumbers: ['100'], versionChanged: false, }); - const logSpy = jest.spyOn(console, 'log').mockImplementation(() => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => { // Do nothing }); @@ -299,7 +301,7 @@ describe('validate', () => { prNumbers: ['100'], versionChanged: true, }); - const logSpy = jest.spyOn(console, 'log').mockImplementation(() => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => { // Do nothing }); @@ -329,13 +331,15 @@ describe('validate', () => { prNumbers: [], versionChanged: false, }); - const logSpy = jest.spyOn(console, 'log').mockImplementation(() => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => { // Do nothing }); + // Omit currentVersion to exercise the no-version path. + const { currentVersion, ...optionsWithoutVersion } = defaultOptions(); + await validate({ - ...defaultOptions(), - currentVersion: undefined, + ...optionsWithoutVersion, checkDeps: true, fix: true, currentPr: '200', @@ -353,7 +357,7 @@ describe('validate', () => { prNumbers: [], versionChanged: false, }); - const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => { // Do nothing }); @@ -380,7 +384,7 @@ describe('validate', () => { prNumbers: [], versionChanged: false, }); - const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => { // Do nothing }); @@ -417,7 +421,7 @@ describe('validate', () => { [1.0.0]: ${repoUrl}/releases/tag/v1.0.0 `; await writeChangelog(changelogWithUnreleasedAndRelease); - const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => { // Do nothing }); diff --git a/merged-packages/auto-changelog/src/validate-command/validate.ts b/merged-packages/auto-changelog/src/validate-command/validate.ts index 894c7720..f6ab72d3 100644 --- a/merged-packages/auto-changelog/src/validate-command/validate.ts +++ b/merged-packages/auto-changelog/src/validate-command/validate.ts @@ -1,21 +1,21 @@ -import { Formatter } from '../changelog'; -import { Version } from '../constants'; -import { readFile, writeFile } from '../fs'; -import { generateDiff } from '../generate-diff'; +import type { Formatter } from '../changelog.js'; +import type { Version } from '../constants.js'; +import { readFile, writeFile } from '../fs.js'; +import { generateDiff } from '../generate-diff.js'; import { BaseRefNotFoundError, getDependencyChanges, - type DependencyCheckResult, -} from '../get-dependency-changes'; -import { PackageRename } from '../shared-types'; -import { updateChangelogWithDependencyBumps } from '../update-changelog-with-dependency-bumps'; +} from '../get-dependency-changes.js'; +import type { DependencyCheckResult } from '../get-dependency-changes.js'; +import type { PackageRename } from '../shared-types.js'; +import { updateChangelogWithDependencyBumps } from '../update-changelog-with-dependency-bumps.js'; import { ChangelogFormattingError, InvalidChangelogError, MissingDependencyEntriesError, validateChangelog, -} from '../validate-changelog'; -import { error } from './cli-utils'; +} from '../validate-changelog.js'; +import { error } from './cli-utils.js'; /** * Options for validating a changelog. @@ -89,25 +89,28 @@ export type ValidateOptions = { * @param options.remote - Remote name for auto-detection. * @param options.baseBranch - Base branch for auto-detection. * @param options.currentPr - PR number to use when fixing missing entries. + * @returns A promise that resolves to nothing once the changelog is validated, or + * rejects with an error if the changelog is invalid. */ -export async function validate({ - changelogPath, - currentVersion, - isReleaseCandidate, - repoUrl, - tagPrefix, - fix, - formatter, - packageRename, - ensureValidPrLinksPresent, - checkDeps, - manifestPath, - fromRef, - toRef, - remote, - baseBranch, - currentPr, -}: ValidateOptions) { +export async function validate(options: ValidateOptions): Promise { + const { + changelogPath, + currentVersion, + isReleaseCandidate, + repoUrl, + tagPrefix, + fix, + formatter, + packageRename, + ensureValidPrLinksPresent, + checkDeps, + manifestPath, + fromRef, + toRef, + remote, + baseBranch, + currentPr, + } = options; const changelogContent = await readFile(changelogPath); let dependencyCheckResult: DependencyCheckResult | undefined; @@ -115,10 +118,10 @@ export async function validate({ try { dependencyCheckResult = await getDependencyChanges({ manifestPath, - fromRef, - toRef, - remote, - baseBranch, + ...(fromRef !== undefined && { fromRef }), + ...(toRef !== undefined && { toRef }), + ...(remote !== undefined && { remote }), + ...(baseBranch !== undefined && { baseBranch }), }); } catch (caughtError) { if (caughtError instanceof BaseRefNotFoundError) { @@ -133,22 +136,21 @@ export async function validate({ try { await validateChangelog({ changelogContent, - currentVersion, + ...(currentVersion !== undefined && { currentVersion }), repoUrl, isReleaseCandidate, tagPrefix, formatter, - packageRename, + ...(packageRename !== undefined && { packageRename }), ensureValidPrLinksPresent, - dependencyCheckResult, + ...(dependencyCheckResult !== undefined && { dependencyCheckResult }), }); - return undefined; } catch (caughtError) { if (caughtError instanceof ChangelogFormattingError) { const { validChangelog, invalidChangelog } = caughtError.data; if (fix) { await writeFile(changelogPath, validChangelog); - return undefined; + return; } const diff = generateDiff(validChangelog, invalidChangelog); @@ -169,22 +171,21 @@ export async function validate({ await updateChangelogWithDependencyBumps({ changelogPath, dependencyBumps: caughtError.missingEntries, - currentVersion: - dependencyCheckResult?.versionChanged && hasReleaseHeader - ? currentVersion - : undefined, + ...(dependencyCheckResult?.versionChanged && + hasReleaseHeader && + currentVersion !== undefined && { currentVersion }), prNumbers, repoUrl, formatter, tagPrefix, - packageRename, + ...(packageRename !== undefined && { packageRename }), changelog: caughtError.changelog, }); const count = caughtError.missingEntries.length; console.log( `Fixed ${count} dependency changelog ${count === 1 ? 'entry' : 'entries'} (added or updated).`, ); - return undefined; + return; } const deps = caughtError.missingEntries .map((entry) => entry.dependency)