From 0f75cd92c048db7e895ca6553ac72190e843dc60 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Tue, 14 Jul 2026 03:01:22 +0900 Subject: [PATCH] Automate and validate the release flow (#998) * improve release flow * limit permission * Test and harden the release workflow * Keep workspace lockfile versions aligned * Run release regression tests in CI --- .github/workflows/finalise-release.yml | 92 ++++++++++++++ .github/workflows/prepare-release.yml | 108 +++++++++++++++++ .github/workflows/release.yml | 33 ++++- .github/workflows/unit-ci.yml | 16 ++- devs.md | 44 +++++++ update-workspaces.mjs | 26 ++++ utils/release-notes.mjs | 147 +++++++++++++++++++++++ utils/release-process.unit.spec.ts | 160 +++++++++++++++++++++++++ version-bump.mjs | 8 +- 9 files changed, 627 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/finalise-release.yml create mode 100644 .github/workflows/prepare-release.yml create mode 100644 utils/release-notes.mjs create mode 100644 utils/release-process.unit.spec.ts diff --git a/.github/workflows/finalise-release.yml b/.github/workflows/finalise-release.yml new file mode 100644 index 00000000..31cad3fa --- /dev/null +++ b/.github/workflows/finalise-release.yml @@ -0,0 +1,92 @@ +name: Finalise Release Tags + +on: + workflow_dispatch: + inputs: + version: + description: Release version, for example 0.25.81 + required: true + type: string + release_branch: + description: Release PR branch. Defaults to the version with dots replaced by underscores. + required: false + type: string + expected_head_sha: + description: Full head commit SHA reviewed in the release PR + required: true + type: string + +jobs: + finalise: + runs-on: ubuntu-latest + environment: release + permissions: + contents: write + steps: + - name: Resolve release branch + id: branch + env: + VERSION: ${{ inputs.version }} + RELEASE_BRANCH_INPUT: ${{ inputs.release_branch }} + run: | + set -euo pipefail + BRANCH="${RELEASE_BRANCH_INPUT}" + if [[ -z "${BRANCH}" ]]; then + BRANCH="${VERSION//./_}" + fi + echo "name=${BRANCH}" >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@v4 + with: + ref: ${{ steps.branch.outputs.name }} + fetch-depth: 0 + submodules: recursive + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: "24.x" + + - name: Validate release head + env: + VERSION: ${{ inputs.version }} + EXPECTED_HEAD_SHA: ${{ inputs.expected_head_sha }} + run: | + set -euo pipefail + ACTUAL_HEAD_SHA="$(git rev-parse HEAD)" + if [[ "${ACTUAL_HEAD_SHA}" != "${EXPECTED_HEAD_SHA}" ]]; then + echo "Release branch head is ${ACTUAL_HEAD_SHA}, expected ${EXPECTED_HEAD_SHA}." >&2 + exit 1 + fi + node utils/release-notes.mjs validate "${VERSION}" + git fetch --tags --force + if git rev-parse --verify --quiet "refs/tags/${VERSION}" >/dev/null; then + echo "Tag already exists: ${VERSION}" >&2 + exit 1 + fi + if git rev-parse --verify --quiet "refs/tags/${VERSION}-cli" >/dev/null; then + echo "Tag already exists: ${VERSION}-cli" >&2 + exit 1 + fi + + - name: Create and push release tags + env: + VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + git tag "${VERSION}" + git tag "${VERSION}-cli" + git push origin "${VERSION}" "${VERSION}-cli" + + - name: Summarise next steps + env: + VERSION: ${{ inputs.version }} + run: | + { + echo "Created tags \`${VERSION}\` and \`${VERSION}-cli\`." + echo "" + echo "The plug-in release workflow is triggered by the \`${VERSION}\` tag and creates a draft release by default." + echo "The CLI Docker workflow is triggered by the \`${VERSION}-cli\` tag and publishes the version, major-minor, latest, and SHA-qualified image tags." + echo "" + echo "To create a pre-release instead of the default draft flow, run \`Release Obsidian Plugin\` manually with \`tag=${VERSION}\`, \`draft=false\`, and \`prerelease=true\`." + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 00000000..aa6a0fdb --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,108 @@ +name: Prepare Release PR + +on: + workflow_dispatch: + inputs: + version: + description: Release version, for example 0.25.81 + required: true + type: string + base_branch: + description: Base branch for the release PR + required: false + type: string + default: main + release_branch: + description: Release branch name. Defaults to the version with dots replaced by underscores. + required: false + type: string + release_date: + description: Release date in ordinal format. Defaults to the current UTC date. + required: false + type: string + allow_empty_updates: + description: Allow an empty Unreleased section + required: false + type: boolean + default: false + +jobs: + prepare: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.base_branch }} + fetch-depth: 0 + submodules: recursive + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: "24.x" + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Prepare release changes + id: prepare + env: + VERSION: ${{ inputs.version }} + RELEASE_BRANCH_INPUT: ${{ inputs.release_branch }} + RELEASE_DATE: ${{ inputs.release_date }} + ALLOW_EMPTY_UPDATES: ${{ inputs.allow_empty_updates }} + run: | + set -euo pipefail + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + BRANCH="${RELEASE_BRANCH_INPUT}" + if [[ -z "${BRANCH}" ]]; then + BRANCH="${VERSION//./_}" + fi + + if git ls-remote --exit-code --heads origin "${BRANCH}" >/dev/null 2>&1; then + echo "Release branch already exists: ${BRANCH}" >&2 + exit 1 + fi + + git switch -c "${BRANCH}" + npm version "${VERSION}" --no-git-tag-version + node utils/release-notes.mjs prepare "${VERSION}" + npm run pretty:json + + git add package.json package-lock.json manifest.json versions.json updates.md src/apps/cli/package.json src/apps/webpeer/package.json src/apps/webapp/package.json + git diff --cached --check + git commit -m "Releasing ${VERSION}" + git push --set-upstream origin "${BRANCH}" + + echo "branch=${BRANCH}" >> "$GITHUB_OUTPUT" + + - name: Create draft release PR + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ inputs.version }} + BASE_BRANCH: ${{ inputs.base_branch }} + RELEASE_BRANCH: ${{ steps.prepare.outputs.branch }} + run: | + cat > /tmp/release-pr-body.md <> $GITHUB_OUTPUT + if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + TAG="${{ inputs.tag }}" + DRAFT="${{ inputs.draft }}" + PRERELEASE="${{ inputs.prerelease }}" + else + TAG="${GITHUB_REF_NAME}" + DRAFT="true" + PRERELEASE="false" + fi + echo "tag=${TAG}" >> $GITHUB_OUTPUT + echo "draft=${DRAFT}" >> $GITHUB_OUTPUT + echo "prerelease=${PRERELEASE}" >> $GITHUB_OUTPUT # Build the plugin - name: Build id: build @@ -58,4 +86,5 @@ jobs: styles.css name: ${{ steps.version.outputs.tag }} tag_name: ${{ steps.version.outputs.tag }} - draft: true \ No newline at end of file + draft: ${{ steps.version.outputs.draft }} + prerelease: ${{ steps.version.outputs.prerelease }} diff --git a/.github/workflows/unit-ci.yml b/.github/workflows/unit-ci.yml index 9b27eede..5d173f33 100644 --- a/.github/workflows/unit-ci.yml +++ b/.github/workflows/unit-ci.yml @@ -17,6 +17,13 @@ on: - 'vitest.config*.ts' - 'esbuild.config.mjs' - 'eslint.config.mjs' + - 'update-workspaces.mjs' + - 'version-bump.mjs' + - 'utils/release-*.mjs' + - 'utils/release-*.unit.spec.ts' + - '.github/workflows/prepare-release.yml' + - '.github/workflows/finalise-release.yml' + - '.github/workflows/release.yml' - '.github/workflows/unit-ci.yml' pull_request: paths: @@ -29,6 +36,13 @@ on: - 'vitest.config*.ts' - 'esbuild.config.mjs' - 'eslint.config.mjs' + - 'update-workspaces.mjs' + - 'version-bump.mjs' + - 'utils/release-*.mjs' + - 'utils/release-*.unit.spec.ts' + - '.github/workflows/prepare-release.yml' + - '.github/workflows/finalise-release.yml' + - '.github/workflows/release.yml' - '.github/workflows/unit-ci.yml' permissions: @@ -113,4 +127,4 @@ jobs: if: always() run: | npm run test:docker-couchdb:stop || true - npm run test:docker-s3:stop || true \ No newline at end of file + npm run test:docker-s3:stop || true diff --git a/devs.md b/devs.md index b31ee71b..cd32c2f6 100644 --- a/devs.md +++ b/devs.md @@ -258,6 +258,50 @@ export class ModuleExample extends AbstractObsidianModule { In short, the situation remains unchanged for me, but it means you all become a little safer. Thank you for your understanding! +## Release Notes + +- Keep the top section of `updates.md` as `## Unreleased` during normal development. +- When opening a feature or fix PR, update `## Unreleased` in the same PR if the change is user-facing. +- Add only user-facing changes that help users understand what they gain, what has changed, or what they may need to do after updating. +- Avoid listing purely internal refactors, maintenance chores, generated-file changes, and dependency updates unless they affect users; group and label them when they are included. +- When preparing a release, replace `## Unreleased` with the target version heading (for example, `## 0.25.81`) and add a fresh empty `## Unreleased` section above it for the next cycle. +- Review and polish the released section in the release PR before tagging, because the content is embedded into the plug-in and may be reused as the GitHub Release notes. + +## Release Workflow + +This workflow is for maintainers. Contributors should update `## Unreleased` for user-facing feature or fix PRs, but do not need to run the release workflows. +The `Finalise Release Tags` and `Release Obsidian Plugin` workflows use the `release` GitHub Environment. Configure Environment protection in the repository settings so tag creation and release publication require maintainer approval. + +- Run the `Prepare Release PR` workflow with the target version. It creates the release branch, updates versions, moves the `## Unreleased` notes to the target version, commits the release preparation, pushes the branch, and opens a draft release PR. +- Do not tag the release branch when the PR is first created. Polish the release PR first, especially `updates.md`. +- Once the release PR head is fixed, run the `Finalise Release Tags` workflow with its full head commit SHA. It validates the release branch and pushes both the plug-in tag (for example, `0.25.81`) and the CLI tag (for example, `0.25.81-cli`) to that commit. +- The plug-in tag triggers the release workflow and creates a draft GitHub Release by default. The CLI tag triggers the Docker workflow and publishes the fixed version tag, the major-minor moving tag (for example, `0.25-cli`), `latest`, and the SHA-qualified tag. +- Merge the release PR with a merge commit after the draft or pre-release has been created. This keeps the tagged release commit in the `main` history. +- If a pre-release is needed, run the `Release Obsidian Plugin` workflow manually with the target tag, `draft=false`, and `prerelease=true`. + +### Release Cheat Sheet + +1. Before starting, add user-facing notes under `## Unreleased` in `updates.md`. +2. Run `Prepare Release PR` from GitHub Actions. + - `version`: the target version, for example `0.25.81`. + - `base_branch`: normally `main`. + - `release_branch`: leave blank to use the default branch name, for example `0_25_81`. + - `release_date`: use an ordinal date such as `14th July, 2026`, or leave blank to use the current UTC date. + - `allow_empty_updates`: leave disabled unless the release intentionally has no user-facing notes. +3. Review the generated draft PR. + - Polish `updates.md`. + - Confirm `package.json`, `manifest.json`, `versions.json`, and workspace package versions. + - Confirm that `manifest.json` has the intended `minAppVersion`. + - Wait for the necessary CI checks. +4. When the PR head is fixed, run `Finalise Release Tags`. + - `version`: the same target version. + - `release_branch`: leave blank unless the release branch used a custom name. + - `expected_head_sha`: the full head commit SHA reviewed in the release PR. +5. Check the generated draft GitHub Release for the plug-in tag. +6. Check the CLI Docker workflow started from the `*-cli` tag. +7. Publish the draft GitHub Release when ready, then merge the release PR into `main` with a merge commit. +8. If the release should be a pre-release instead of a draft release, run `Release Obsidian Plugin` manually with the target `tag`, `draft=false`, and `prerelease=true`. + ## Contribution Guidelines - Follow existing code style and conventions diff --git a/update-workspaces.mjs b/update-workspaces.mjs index 36646123..dfb3bd6b 100644 --- a/update-workspaces.mjs +++ b/update-workspaces.mjs @@ -23,6 +23,23 @@ if (!workspaces || !Array.isArray(workspaces)) { process.exit(1); } +const packageLockPath = resolve('package-lock.json'); +let packageLock; +let packageLockChanged = false; +try { + packageLock = JSON.parse(readFileSync(packageLockPath, 'utf8')); + if (packageLock.version !== mainVersion) { + packageLock.version = mainVersion; + packageLockChanged = true; + } + if (packageLock.packages?.[''] && packageLock.packages[''].version !== mainVersion) { + packageLock.packages[''].version = mainVersion; + packageLockChanged = true; + } +} catch (error) { + console.warn('Could not update package-lock.json:', error.message); +} + // Collect all root dependencies for version matching. const rootDeps = { ...(rootPackage.dependencies || {}), @@ -68,10 +85,15 @@ for (const dir of workspaceDirs) { const workspaceName = basename(dir); const targetVersion = `${mainVersion}-${workspaceName}`; + const lockWorkspace = packageLock?.packages?.[dir.replaceAll('\\', '/')]; console.log(`Updating ${pkg.name || dir}:`); console.log(` Version: ${pkg.version} -> ${targetVersion}`); pkg.version = targetVersion; + if (lockWorkspace && lockWorkspace.version !== targetVersion) { + lockWorkspace.version = targetVersion; + packageLockChanged = true; + } // Synchronise dependencies. if (pkg.dependencies) { @@ -109,3 +131,7 @@ for (const dir of workspaceDirs) { console.error(` Failed to write ${pkgJsonPath}:`, error); } } + +if (packageLockChanged) { + writeFileSync(packageLockPath, JSON.stringify(packageLock, null, 4) + '\n', 'utf8'); +} diff --git a/utils/release-notes.mjs b/utils/release-notes.mjs new file mode 100644 index 00000000..3e4d9857 --- /dev/null +++ b/utils/release-notes.mjs @@ -0,0 +1,147 @@ +import { readFileSync, writeFileSync } from "fs"; + +const updatesPath = "updates.md"; + +// Utility used by the release workflows to rotate and validate `updates.md`. +// It intentionally keeps the Markdown format simple: top-level `##` headings +// are treated as release boundaries, and only one `## Unreleased` section is +// allowed. + +function fail(message) { + console.error(message); + process.exit(1); +} + +function readJson(path) { + return JSON.parse(readFileSync(path, "utf8")); +} + +function assertVersion(version) { + if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) { + fail(`Invalid release version: ${version}`); + } +} + +function formatReleaseDate(date = new Date()) { + const day = date.getUTCDate(); + const suffix = + day % 10 === 1 && day !== 11 + ? "st" + : day % 10 === 2 && day !== 12 + ? "nd" + : day % 10 === 3 && day !== 13 + ? "rd" + : "th"; + const month = new Intl.DateTimeFormat("en-GB", { month: "long", timeZone: "UTC" }).format(date); + const year = date.getUTCFullYear(); + return `${day}${suffix} ${month}, ${year}`; +} + +function headingPattern(heading) { + return new RegExp(`^## ${heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*$`, "m"); +} + +// Return a `##` section body without interpreting lower-level headings. +function findSection(markdown, heading) { + const pattern = headingPattern(heading); + const match = pattern.exec(markdown); + if (!match) return undefined; + + const headingStart = match.index; + const bodyStart = match.index + match[0].length; + const rest = markdown.slice(bodyStart); + const next = /^## .+$/m.exec(rest); + const end = next ? bodyStart + next.index : markdown.length; + + return { + headingStart, + bodyStart, + end, + body: markdown.slice(bodyStart, end), + }; +} + +function assertSingleUnreleased(markdown) { + const matches = markdown.match(/^## Unreleased\s*$/gm) || []; + if (matches.length !== 1) { + fail(`Expected exactly one '## Unreleased' section in ${updatesPath}, found ${matches.length}.`); + } +} + +function prepare(version) { + assertVersion(version); + const markdown = readFileSync(updatesPath, "utf8"); + assertSingleUnreleased(markdown); + + if (headingPattern(version).test(markdown)) { + fail(`Release notes for ${version} already exist in ${updatesPath}.`); + } + + const unreleased = findSection(markdown, "Unreleased"); + if (!unreleased) fail(`Could not find '## Unreleased' in ${updatesPath}.`); + + const allowEmpty = process.env.ALLOW_EMPTY_UPDATES === "true"; + if (!allowEmpty && unreleased.body.trim() === "") { + fail(`The '## Unreleased' section is empty. Set ALLOW_EMPTY_UPDATES=true if this is intentional.`); + } + + // Keep a fresh empty Unreleased section above the newly dated release notes. + const releasedBody = `${unreleased.body.trim()}\n\n`; + const releaseDate = process.env.RELEASE_DATE || formatReleaseDate(); + const replacement = `## Unreleased\n\n## ${version}\n\n${releaseDate}\n\n${releasedBody}`; + const nextMarkdown = markdown.slice(0, unreleased.headingStart) + replacement + markdown.slice(unreleased.end); + writeFileSync(updatesPath, nextMarkdown, "utf8"); +} + +function validate(version) { + assertVersion(version); + + const rootPackage = readJson("package.json"); + const manifest = readJson("manifest.json"); + if (rootPackage.version !== version) { + fail(`package.json version is ${rootPackage.version}, expected ${version}.`); + } + if (manifest.version !== version) { + fail(`manifest.json version is ${manifest.version}, expected ${version}.`); + } + + for (const workspace of ["cli", "webpeer", "webapp"]) { + const workspacePackage = readJson(`src/apps/${workspace}/package.json`); + const expected = `${version}-${workspace}`; + if (workspacePackage.version !== expected) { + fail(`src/apps/${workspace}/package.json version is ${workspacePackage.version}, expected ${expected}.`); + } + } + + const versions = readJson("versions.json"); + if (versions[version] !== manifest.minAppVersion) { + fail(`versions.json does not map ${version} to manifest minAppVersion ${manifest.minAppVersion}.`); + } + + const markdown = readFileSync(updatesPath, "utf8"); + assertSingleUnreleased(markdown); + + const releaseSection = findSection(markdown, version); + if (!releaseSection) { + fail(`Could not find '## ${version}' in ${updatesPath}.`); + } + if (releaseSection.body.trim() === "") { + fail(`The release notes for ${version} are empty.`); + } + if (/\b(?:TODO|WIP)\b/i.test(releaseSection.body)) { + fail(`The release notes for ${version} still contain TODO or WIP markers.`); + } +} + +const [command, version] = process.argv.slice(2); +if (!command || !version) { + fail("Usage: node utils/release-notes.mjs "); +} + +if (command === "prepare") { + prepare(version); +} else if (command === "validate") { + validate(version); +} else { + fail(`Unknown command: ${command}`); +} diff --git a/utils/release-process.unit.spec.ts b/utils/release-process.unit.spec.ts new file mode 100644 index 00000000..940bf88a --- /dev/null +++ b/utils/release-process.unit.spec.ts @@ -0,0 +1,160 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const releaseNotesScript = fileURLToPath(new URL("./release-notes.mjs", import.meta.url)); +const versionBumpScript = + process.env.VERSION_BUMP_SCRIPT || fileURLToPath(new URL("../version-bump.mjs", import.meta.url)); +const workspaceUpdateScript = fileURLToPath(new URL("../update-workspaces.mjs", import.meta.url)); +const temporaryDirectories: string[] = []; + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } +}); + +function makeTemporaryDirectory(): string { + const directory = mkdtempSync(join(tmpdir(), "livesync-release-notes-")); + temporaryDirectories.push(directory); + return directory; +} + +function writeJson(directory: string, path: string, value: unknown): void { + const fullPath = join(directory, path); + mkdirSync(dirname(fullPath), { recursive: true }); + writeFileSync(fullPath, `${JSON.stringify(value, null, 4)}\n`, "utf8"); +} + +function runNode(script: string, args: string[], cwd: string, env: Record = {}) { + return spawnSync(process.execPath, [script, ...args], { + cwd, + encoding: "utf8", + env: { ...process.env, ...env }, + }); +} + +function createReleaseFixture(version = "0.25.81"): string { + const directory = makeTemporaryDirectory(); + writeJson(directory, "package.json", { version }); + writeJson(directory, "manifest.json", { version, minAppVersion: "1.7.2" }); + writeJson(directory, "versions.json", { [version]: "1.7.2" }); + for (const workspace of ["cli", "webpeer", "webapp"]) { + writeJson(directory, `src/apps/${workspace}/package.json`, { version: `${version}-${workspace}` }); + } + writeFileSync( + join(directory, "updates.md"), + "# 0.25\n\n## Unreleased\n\n### Fixed\n\n- Preserved file content.\n\n## 0.25.80\n\n7th July, 2026\n\n- Previous release.\n", + "utf8" + ); + return directory; +} + +describe("release notes", () => { + it("moves Unreleased notes into a dated release and validates the result", () => { + const directory = createReleaseFixture(); + + const prepared = runNode(releaseNotesScript, ["prepare", "0.25.81"], directory, { + RELEASE_DATE: "14th July, 2026", + }); + + expect(prepared.status, prepared.stderr).toBe(0); + expect(readFileSync(join(directory, "updates.md"), "utf8")).toBe( + "# 0.25\n\n## Unreleased\n\n## 0.25.81\n\n14th July, 2026\n\n### Fixed\n\n- Preserved file content.\n\n## 0.25.80\n\n7th July, 2026\n\n- Previous release.\n" + ); + + const validated = runNode(releaseNotesScript, ["validate", "0.25.81"], directory); + expect(validated.status, validated.stderr).toBe(0); + }); + + it("rejects an empty Unreleased section unless explicitly allowed", () => { + const directory = createReleaseFixture(); + writeFileSync( + join(directory, "updates.md"), + "# 0.25\n\n## Unreleased\n\n## 0.25.80\n\nPrevious release.\n", + "utf8" + ); + + const rejected = runNode(releaseNotesScript, ["prepare", "0.25.81"], directory); + expect(rejected.status).toBe(1); + expect(rejected.stderr).toContain("The '## Unreleased' section is empty."); + + const allowed = runNode(releaseNotesScript, ["prepare", "0.25.81"], directory, { + ALLOW_EMPTY_UPDATES: "true", + RELEASE_DATE: "14th July, 2026", + }); + expect(allowed.status, allowed.stderr).toBe(0); + }); + + it("rejects unfinished release notes", () => { + const directory = createReleaseFixture(); + writeFileSync( + join(directory, "updates.md"), + "# 0.25\n\n## Unreleased\n\n## 0.25.81\n\n14th July, 2026\n\n- TODO: finish these notes.\n", + "utf8" + ); + + const result = runNode(releaseNotesScript, ["validate", "0.25.81"], directory); + expect(result.status).toBe(1); + expect(result.stderr).toContain("still contain TODO or WIP markers"); + }); +}); + +describe("version bump", () => { + it("records every release even when its minimum app version is already used", () => { + const directory = makeTemporaryDirectory(); + writeJson(directory, "manifest.json", { version: "0.25.80", minAppVersion: "1.7.2" }); + writeJson(directory, "versions.json", { "0.25.61": "1.7.2" }); + + const result = runNode(versionBumpScript, [], directory, { npm_package_version: "0.25.81" }); + + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(readFileSync(join(directory, "manifest.json"), "utf8"))).toMatchObject({ + version: "0.25.81", + minAppVersion: "1.7.2", + }); + expect(JSON.parse(readFileSync(join(directory, "versions.json"), "utf8"))).toEqual({ + "0.25.61": "1.7.2", + "0.25.81": "1.7.2", + }); + }); +}); + +describe("workspace version update", () => { + it("keeps workspace package and lockfile versions together", () => { + const directory = makeTemporaryDirectory(); + const workspaces = ["src/apps/cli", "src/apps/webpeer", "src/apps/webapp"]; + writeJson(directory, "package.json", { version: "0.25.81", workspaces }); + for (const workspace of ["cli", "webpeer", "webapp"]) { + writeJson(directory, `src/apps/${workspace}/package.json`, { version: `0.25.80-${workspace}` }); + } + writeJson(directory, "package-lock.json", { + name: "obsidian-livesync", + version: "0.25.80", + lockfileVersion: 3, + packages: { + "": { version: "0.25.80", workspaces }, + "src/apps/cli": { version: "0.25.80-cli" }, + "src/apps/webpeer": { version: "0.25.80-webpeer" }, + "src/apps/webapp": { version: "0.25.80-webapp" }, + }, + }); + + const result = runNode(workspaceUpdateScript, [], directory); + + expect(result.status, result.stderr).toBe(0); + for (const workspace of ["cli", "webpeer", "webapp"]) { + const packageJson = JSON.parse(readFileSync(join(directory, `src/apps/${workspace}/package.json`), "utf8")); + expect(packageJson.version).toBe(`0.25.81-${workspace}`); + } + const packageLock = JSON.parse(readFileSync(join(directory, "package-lock.json"), "utf8")); + expect(packageLock.version).toBe("0.25.81"); + expect(packageLock.packages[""].version).toBe("0.25.81"); + expect(packageLock.packages["src/apps/cli"].version).toBe("0.25.81-cli"); + expect(packageLock.packages["src/apps/webpeer"].version).toBe("0.25.81-webpeer"); + expect(packageLock.packages["src/apps/webapp"].version).toBe("0.25.81-webapp"); + }); +}); diff --git a/version-bump.mjs b/version-bump.mjs index 32dcf7e2..1733c0bc 100644 --- a/version-bump.mjs +++ b/version-bump.mjs @@ -10,8 +10,8 @@ writeFileSync("manifest.json", JSON.stringify(manifest, null, 4)); // update versions.json with target version and minAppVersion from manifest.json // but only if the target version is not already in versions.json -const versions = JSON.parse(readFileSync('versions.json', 'utf8')); -if (!Object.values(versions).includes(minAppVersion)) { +const versions = JSON.parse(readFileSync("versions.json", "utf8")); +if (!(targetVersion in versions)) { versions[targetVersion] = minAppVersion; - writeFileSync('versions.json', JSON.stringify(versions, null, 4)); -} \ No newline at end of file + writeFileSync("versions.json", JSON.stringify(versions, null, 4)); +}