From 628df55ba71e877f47ca65530aa80f76083bb211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= Date: Wed, 11 Nov 2026 13:59:03 +0100 Subject: [PATCH 1/4] chore: initial commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jesus Manuel Piñeiro Cid From 8ec96b033e50aa5365e3f2711635b336640c6511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= Date: Wed, 11 Nov 2026 16:07:42 +0100 Subject: [PATCH 2/4] [cli] Pluggable docs version resolvers: descriptor, github-release, tag-bump Each versioned site now chooses where its docs release version comes from with docouture.versionSource in docs/package.json: descriptor (default, docs/.release-version), github-release (the published Release's tag, with an optional prefix) or tag-bump (latest docs/v* tag plus a bump chosen by the docs/release, docs/release-minor or docs/release-major label). - docouture release resolve: one tested implementation of the version rules, with semver-aware tag ordering and bumps; the release workflow calls it and gates the descriptor bump and the git-flow sync on it - release preview follows the source and installs dependencies only for tag-bump - docouture version-source: show or switch the source - docouture new --version-source, upgrade backfill and CLI skew warning, doctor checks - docs, docouture-docs-versioning skill, v1.4.0 release notes, specs Closes #299 --- .../skills/docouture-docs-versioning/SKILL.md | 13 +- .../reference/releasing.md | 35 ++- .../workflows/docouture-release-preview.yml | 135 ++++++++++-- .github/workflows/docouture-release.yml | 123 +++++------ AGENTS.md | 4 +- code/packages/cli/src/bin.ts | 87 +++++++- code/packages/cli/src/commands/completion.ts | 2 + code/packages/cli/src/commands/doctor.ts | 22 +- code/packages/cli/src/commands/new.spec.ts | 65 ++++++ code/packages/cli/src/commands/new.ts | 136 ++++++++++-- .../packages/cli/src/commands/release.spec.ts | 161 ++++++++++++++ code/packages/cli/src/commands/release.ts | 109 ++++++++++ .../packages/cli/src/commands/upgrade.spec.ts | 79 +++++++ code/packages/cli/src/commands/upgrade.ts | 30 +++ .../cli/src/commands/version-source.spec.ts | 135 ++++++++++++ .../cli/src/commands/version-source.ts | 169 +++++++++++++++ code/packages/cli/src/lib/docs-tags.ts | 20 ++ .../cli/src/lib/doctor-checks.spec.ts | 61 ++++++ code/packages/cli/src/lib/doctor-checks.ts | 91 ++++++++ .../src/lib/package-version-source.spec.ts | 95 ++++++++ .../cli/src/lib/package-version-source.ts | 75 +++++++ code/packages/cli/src/lib/project-cli.spec.ts | 68 ++++++ code/packages/cli/src/lib/project-cli.ts | 65 ++++++ code/packages/cli/src/lib/release-labels.ts | 18 ++ .../cli/src/lib/release-resolve.spec.ts | 204 ++++++++++++++++++ code/packages/cli/src/lib/release-resolve.ts | 193 +++++++++++++++++ code/packages/cli/src/lib/semver.spec.ts | 81 +++++++ code/packages/cli/src/lib/semver.ts | 95 ++++++++ code/packages/cli/src/lib/site-mode.spec.ts | 24 +++ code/packages/cli/src/lib/site-mode.ts | 29 +++ .../cli/templates/agent-support/AGENTS.md | 3 +- .../modules/main/pages/getting-started.adoc | 6 + .../workflows/docouture-release-preview.yml | 131 +++++++++-- .../templates/workflows/docouture-release.yml | 123 +++++------ docs/src/modules/main/nav.adoc | 1 + .../main/pages/guides-branching-model.adoc | 2 +- .../guides-releasing-a-documentation.adoc | 54 ++++- .../main/pages/guides-versioning-modes.adoc | 2 +- .../src/modules/main/pages/reference-cli.adoc | 81 ++++++- .../main/pages/release-notes/1-4-0.adoc | 64 ++++++ .../main/pages/release-notes/index.adoc | 1 + .../.openspec.yaml | 2 + .../design.md | 41 ++++ .../proposal.md | 35 +++ .../docs-release-prerelease-sync/spec.md | 23 ++ .../specs/docs-release-preview/spec.md | 36 ++++ .../specs/docs-release-resolve/spec.md | 85 ++++++++ .../specs/docs-version-source/spec.md | 64 ++++++ .../tasks.md | 35 +++ .../.openspec.yaml | 2 + .../design.md | 29 +++ .../proposal.md | 29 +++ .../specs/docs-release-resolve/spec.md | 56 +++++ .../tasks.md | 17 ++ .../docs-release-prerelease-sync/spec.md | 14 +- openspec/specs/docs-release-preview/spec.md | 28 ++- openspec/specs/docs-release-resolve/spec.md | 116 ++++++++++ openspec/specs/docs-version-source/spec.md | 65 ++++++ skills/docouture-docs-versioning/SKILL.md | 10 +- .../reference/releasing.md | 29 ++- 60 files changed, 3381 insertions(+), 227 deletions(-) create mode 100644 code/packages/cli/src/commands/release.spec.ts create mode 100644 code/packages/cli/src/commands/release.ts create mode 100644 code/packages/cli/src/commands/version-source.spec.ts create mode 100644 code/packages/cli/src/commands/version-source.ts create mode 100644 code/packages/cli/src/lib/docs-tags.ts create mode 100644 code/packages/cli/src/lib/package-version-source.spec.ts create mode 100644 code/packages/cli/src/lib/package-version-source.ts create mode 100644 code/packages/cli/src/lib/project-cli.spec.ts create mode 100644 code/packages/cli/src/lib/project-cli.ts create mode 100644 code/packages/cli/src/lib/release-labels.ts create mode 100644 code/packages/cli/src/lib/release-resolve.spec.ts create mode 100644 code/packages/cli/src/lib/release-resolve.ts create mode 100644 code/packages/cli/src/lib/semver.spec.ts create mode 100644 code/packages/cli/src/lib/semver.ts create mode 100644 code/packages/cli/src/lib/site-mode.spec.ts create mode 100644 code/packages/cli/src/lib/site-mode.ts create mode 100644 docs/src/modules/main/pages/release-notes/1-4-0.adoc create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/design.md create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/proposal.md create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-prerelease-sync/spec.md create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-preview/spec.md create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-resolve/spec.md create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-version-source/spec.md create mode 100644 openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/tasks.md create mode 100644 openspec/changes/archive/2026-11-11-release-resolve-descriptor/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-11-release-resolve-descriptor/design.md create mode 100644 openspec/changes/archive/2026-11-11-release-resolve-descriptor/proposal.md create mode 100644 openspec/changes/archive/2026-11-11-release-resolve-descriptor/specs/docs-release-resolve/spec.md create mode 100644 openspec/changes/archive/2026-11-11-release-resolve-descriptor/tasks.md create mode 100644 openspec/specs/docs-release-resolve/spec.md create mode 100644 openspec/specs/docs-version-source/spec.md diff --git a/.agents/skills/docouture-docs-versioning/SKILL.md b/.agents/skills/docouture-docs-versioning/SKILL.md index 3c8f4cfd..468f4e03 100644 --- a/.agents/skills/docouture-docs-versioning/SKILL.md +++ b/.agents/skills/docouture-docs-versioning/SKILL.md @@ -1,6 +1,6 @@ --- name: docouture-docs-versioning -description: "How to cut a release or a prerelease on a docouture Antora documentation site scaffolded with Versioned (Full History) mode: docouture version, docs/.release-version, and the docouture-release.yml workflow. USE WHEN bumping a version, cutting a release, configuring what a release tag contains, or asking how versioning works on this site. EXAMPLES: 'cut a release', 'bump the docs version', 'what does docs/.release-version do', 'how do I release a new version of the docs'." +description: "How to cut a release or a prerelease on a docouture Antora documentation site scaffolded with Versioned (Full History) mode: docouture version, docs/.release-version and its alternatives (docouture version-source: github-release, tag-bump), and the docouture-release.yml workflow. USE WHEN bumping a version, cutting a release, configuring what a release tag contains, or asking how versioning works on this site. EXAMPLES: 'cut a release', 'bump the docs version', 'what does docs/.release-version do', 'how do I release a new version of the docs'." --- # Docs versioning (Versioned — Full History) @@ -35,3 +35,14 @@ a release tag, and what the release workflow actually does). `docs/.release-version` forward to the next patch version automatically and commits that to `main` — you shouldn't normally need to edit it yourself except to set an intentionally different next target (e.g. jumping to a new minor). +- On a git-flow site the workflow also opens a sync pull request from the release branch + into the prerelease branch (`docs/package.json`'s `docouture.prereleaseBranch`) to carry + that bump over — merge it. +- **Where the version comes from is configurable.** `docouture.versionSource` in + `docs/package.json` is `descriptor` (the default, everything above), `github-release` + (the published GitHub Release's tag, optionally minus `docouture.versionSourcePrefix`) or + `tag-bump` (the latest `docs/v*` tag plus a bump: `docs/release` patch, + `docs/release-minor` minor, `docs/release-major` major). Only `descriptor` uses + `docs/.release-version`, the post-release bump and the git-flow sync. Show or change it + with `docouture version-source [source]`; `docouture new --mode versioned` asks for it. + See `reference/releasing.md`. diff --git a/.agents/skills/docouture-docs-versioning/reference/releasing.md b/.agents/skills/docouture-docs-versioning/reference/releasing.md index c85a919b..76c8720b 100644 --- a/.agents/skills/docouture-docs-versioning/reference/releasing.md +++ b/.agents/skills/docouture-docs-versioning/reference/releasing.md @@ -74,7 +74,34 @@ advanced or touched by this step; its own `docs/src/antora.yml` permanently keep released version, e.g. a docs typo caught after the tag went out) is a deliberate, ordinary act, not something needing a separate flag. -## `docs/.release-version` after a release +## Version sources + +`docs/package.json`'s `docouture.versionSource` picks where the version comes from; +`docouture release resolve` implements all three for both workflows (release and preview). + +| source | version | notes | +| --- | --- | --- | +| `descriptor` (default) | `docs/.release-version` | the post-release bump and the git-flow sync below apply only here | +| `github-release` | tag of the published GitHub Release, minus `docouture.versionSourcePrefix` | a merged `docs/release` PR fails with a clear message; no version file | +| `tag-bump` | highest `docs/v*` tag + bump | `docs/release` patch, `docs/release-minor` minor, `docs/release-major` major (highest wins); semver-aware, prerelease tags included; the first release needs an explicit version via `workflow_dispatch`; no version file | + +`docouture version-source [descriptor|github-release|tag-bump] [--prefix

] [--version ] +[--dry-run]` shows or changes it (refuses standalone sites): `descriptor` creates +`docs/.release-version` seeded with the next patch of the latest tag, the others remove it +(warning if it held a pending value), and `tag-bump` prints the `gh label create` commands +for the two extra labels. Workflows read the source at run time, so none are re-rendered, but +they run the project's installed CLI: bump `@inditextech/docouture-cli` and install first, +then `docouture upgrade` (writes `"versionSource": "descriptor"` where missing), then +optionally `docouture version-source`. `docouture doctor` shows the active source and warns +about a stray or missing `.release-version` and about a CLI without `release resolve`. + +The preview comment follows the source: `descriptor` reads the file (no install), +`github-release` says the docs follow the code release without a version, and `tag-bump` +shows the version released if the PR merged now (it can change if another release lands +first). Under `tag-bump`, a run started by a published GitHub Release has no PR labels, so it +bumps patch; use `workflow_dispatch` with an explicit version for a minor or major bump there. + +## `docs/.release-version` after a release (`descriptor` only) Nothing clears it — it's bumped forward instead, except on a republish. On a genuine forward release (the target tag was new), a final step in the workflow advances the file @@ -84,6 +111,12 @@ on a republish (the target tag already existed): that run's target version was t already superseded by whatever the file currently holds as the next planned target, so bumping forward from the republished version would clobber that already-planned value. +On a **git-flow** site the bump lands on the release branch only, so the workflow's +`sync-prerelease` job opens a pull request into the prerelease branch (named by +`docs/package.json`'s `docouture.prereleaseBranch`) to carry it over — merge that PR. A +failed sync turns the run red but does not block publishing. Needs `pull-requests: write` +on the GitHub App; older sites run `docouture upgrade` once to get the job and field. + ## Why there's no `docouture release` command `docouture-release.yml`'s own steps depend on CI-only concerns a portable local CLI command diff --git a/.github/workflows/docouture-release-preview.yml b/.github/workflows/docouture-release-preview.yml index 84f3903f..27997700 100644 --- a/.github/workflows/docouture-release-preview.yml +++ b/.github/workflows/docouture-release-preview.yml @@ -20,10 +20,17 @@ name: docouture-release-preview # tag before merging, not after. # # Reuses docouture-release.yml's own "Detect mode" (grep antora-playbook.yml's -# content.sources[] tags) and "Resolve version" (stable, or -# docs/.release-version's contents) logic verbatim — see that workflow's own -# comments, and the docs-site-package skill's reference/versioning-modes.md, -# for the full mechanism. +# content.sources[] tags) logic verbatim — see that workflow's own comments, +# and the docs-site-package skill's reference/versioning-modes.md, for the full +# mechanism. +# +# The version depends on the site's `docouture.versionSource` +# (docs/package.json), read here with `node` (preinstalled on the runner): +# `descriptor` (default) reads docs/.release-version in bash and installs +# nothing; `github-release` has no version to show — the docs follow the code +# release — so it posts a fixed message; `tag-bump` installs the project's +# dependencies and asks `docouture release resolve` for the version that would +# be released if the pull request merged now. # # Docouture hardening: pinned actions, no persisted checkout credentials, # no third-party path filter (the pull request's own file list comes from the @@ -53,7 +60,7 @@ jobs: # the workflow a read-only GITHUB_TOKEN whatever `permissions:` asks for, # so every `gh pr comment` below would fail the run. Skipping this job # skips the three comment jobs that need it. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository && (github.event.pull_request.draft == false || contains(github.event.pull_request.labels.*.name, 'docs/release')) }} + if: ${{ github.event.pull_request.head.repo.full_name == github.repository && (github.event.pull_request.draft == false || (contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major'))) }} outputs: detected: ${{ steps.changes.outputs.paths }} steps: @@ -77,7 +84,7 @@ jobs: # With a code release (`release-type/*` without `skip-release`) the job also # runs when the pull request touches no docs, to explain that the docs follow # the code release. - if: ${{ contains(github.event.pull_request.labels.*.name, 'docs/release') && (needs.check-changes-in-paths.outputs.detected == 'true' || (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release'))) }} + if: ${{ (contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && (needs.check-changes-in-paths.outputs.detected == 'true' || (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release'))) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: @@ -118,30 +125,83 @@ jobs: echo "mode=${mode}" >> "$GITHUB_OUTPUT" echo "Detected ${mode} (antora-playbook.yml: ${line})" - # Standalone always targets 'stable'; versioned reads the plain-text - # docs/.release-version this PR is expected to have committed — same - # source docouture-release.yml's pull_request trigger reads (there is no - # workflow_dispatch input to fall back to here, since this workflow - # only ever runs on pull_request). + - name: Read version source + id: source + run: | + source=$(node -p "require('./package.json').docouture?.versionSource ?? 'descriptor'") + + case "$source" in + descriptor | github-release | tag-bump) ;; + *) + echo "::error::docs/package.json declares docouture.versionSource '${source}' — expected descriptor, github-release or tag-bump." + exit 1 + ;; + esac + + echo "source=${source}" >> "$GITHUB_OUTPUT" + echo "Version source: ${source}" + + # Only `tag-bump` needs the project's own CLI here (semver ordering of + # the docs/v* tags); `descriptor` and `github-release` install nothing. + - name: Setup pnpm + uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + with: + package_json_file: docs/package.json + + - name: Setup Node + if: steps.source.outputs.source == 'tag-bump' + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version-file: docs/package.json + package-manager-cache: false + + - name: Install dependencies + if: steps.source.outputs.source == 'tag-bump' + run: pnpm install --frozen-lockfile + + # Standalone always targets 'stable'. Versioned depends on the source: + # `descriptor` reads the plain-text docs/.release-version this PR is + # expected to have committed — same source docouture-release.yml's + # pull_request trigger reads (there is no workflow_dispatch input to fall + # back to here); `github-release` has no version until the code release + # publishes; `tag-bump` asks `docouture release resolve` using the tags + # from the REST API (checkout keeps no credentials, and is shallow). - name: Resolve version id: resolve env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} MODE: ${{ steps.detect.outputs.mode }} + SOURCE: ${{ steps.source.outputs.source }} + LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} run: | - if [ "$MODE" = "versioned" ]; then + error="" + if [ "$MODE" != "versioned" ]; then + version="stable" + tag="docs/stable" + elif [ "$SOURCE" = "github-release" ]; then + version="" + tag="" + elif [ "$SOURCE" = "tag-bump" ]; then + tags=$(gh api --paginate "repos/${REPOSITORY}/git/matching-refs/tags/docs/v" --jq '.[].ref | ltrimstr("refs/tags/")' | paste -sd, -) + resolved=$(npx docouture release resolve --mode versioned --event pull_request --labels "$LABELS" --tags "$tags" --report) + version=$(printf '%s\n' "$resolved" | sed -n 's/^version=//p') + tag=$(printf '%s\n' "$resolved" | sed -n 's/^tag=//p') + error=$(printf '%s\n' "$resolved" | sed -n 's/^error=//p') + else if [ -f .release-version ]; then version=$(tr -d '[:space:]' < .release-version) else version="" fi tag="docs/v${version}" - else - version="stable" - tag="docs/stable" fi - echo "version=${version}" >> "$GITHUB_OUTPUT" - echo "tag=${tag}" >> "$GITHUB_OUTPUT" + { + echo "version=${version}" + echo "tag=${tag}" + echo "error=${error}" + } >> "$GITHUB_OUTPUT" # Asks the REST API rather than `git ls-remote`: checkout keeps no # credentials, and an unauthenticated ls-remote against a private @@ -174,8 +234,10 @@ jobs: REPOSITORY: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }} MODE: ${{ steps.detect.outputs.mode }} + SOURCE: ${{ steps.source.outputs.source }} VERSION: ${{ steps.resolve.outputs.version }} TAG: ${{ steps.resolve.outputs.tag }} + ERROR: ${{ steps.resolve.outputs.error }} EXISTED: ${{ steps.check.outputs.existed }} # A code release is also pending (`release-type/*` without # `skip-release`), so docouture-release.yml defers the docs release to @@ -188,7 +250,28 @@ jobs: FAIL_TIMING="If you merge it as it is, the docs release will fail." fi - if [ "$MODE" = "versioned" ] && [ -z "$VERSION" ]; then + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "github-release" ]; then + gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " + ### :information_source: The docs are released with the code release + This site's docs version source is \`github-release\`: the docs site is published when the code release publishes a GitHub Release, never when a Pull Request merges. No version can be shown here, and the \`docs/release\` label does **not** release the docs on merge. + + - **If the code release publishes a GitHub Release:** nothing else to do. Remove the \`docs/release\` label. + - **If it does not** (the release fails, stays a draft, or is marked pre-release): the docs will not be released. Start \`docouture-release\` manually from the Actions tab with an explicit version." + exit 0 + fi + + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "tag-bump" ] && [ -n "$ERROR" ]; then + gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " + ### :x: Docs release will fail: no version to bump from + This site's docs version source is \`tag-bump\`, but no \`docs/v*\` tag exists yet to bump from. + + ${FAIL_TIMING} + + **Before merging:** release the first version manually with \`docouture-release\` from the Actions tab, giving an explicit version such as \`1.0.0\`." + exit 0 + fi + + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "descriptor" ] && [ -z "$VERSION" ]; then gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " ### :x: Docs release will fail: no target version This site uses versioned docs, so a docs release needs to know which version to publish. This Pull Request has the \`docs/release\` label but no \`docs/.release-version\` file. @@ -206,7 +289,7 @@ jobs: # whole point of a preview: docouture-release.yml checks the same # thing, but only finds out after the PR has already merged. SEMVER_RE='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$' - if [ "$MODE" = "versioned" ] && ! [[ "$VERSION" =~ $SEMVER_RE ]]; then + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "descriptor" ] && ! [[ "$VERSION" =~ $SEMVER_RE ]]; then gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " ### :x: Docs release will fail: invalid version \`docs/.release-version\` contains \`${VERSION}\`, which is not a valid version. Use a SemVer version such as \`1.2.0\` or \`1.2.0-rc.1\`, with no leading \`v\` and no two-part version like \`1.2\`. See https://semver.org. @@ -237,17 +320,23 @@ jobs: ### :warning: This tag already exists \`${TAG}\` has already been published. ${REPLACE_WHEN}" - if [ "$MODE" = "versioned" ]; then + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "descriptor" ]; then MESSAGE="${MESSAGE} If that is not what you want, change the version in \`docs/.release-version\`." fi fi + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "tag-bump" ]; then + MESSAGE="${MESSAGE} + + This is the version released **if this Pull Request merged now**: the latest \`docs/v*\` tag plus the bump its labels select. It can change if another docs release lands first." + fi + gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body "$MESSAGE" release-preview-no-docs-changes: name: Add PR comment with configuration management information needs: check-changes-in-paths - if: ${{ contains(github.event.pull_request.labels.*.name, 'docs/release') && needs.check-changes-in-paths.outputs.detected == 'false' && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} + if: ${{ (contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && needs.check-changes-in-paths.outputs.detected == 'false' && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: @@ -266,7 +355,7 @@ jobs: release-preview-no-release-label: name: Add PR comment with release information needs: check-changes-in-paths - if: ${{ !contains(github.event.pull_request.labels.*.name, 'docs/release') && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} + if: ${{ !(contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: @@ -289,7 +378,7 @@ jobs: release-preview-code-release: name: Add PR comment with code release information needs: check-changes-in-paths - if: ${{ !contains(github.event.pull_request.labels.*.name, 'docs/release') && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} + if: ${{ !(contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: diff --git a/.github/workflows/docouture-release.yml b/.github/workflows/docouture-release.yml index 4c9164cf..4c9f5a20 100644 --- a/.github/workflows/docouture-release.yml +++ b/.github/workflows/docouture-release.yml @@ -55,6 +55,16 @@ name: docouture-release # that other workflow actually finishes. Either way this runs exactly # once per merge, just not always at the same moment. # +# Version source (versioned only): where a release's version comes from is the +# site's `docouture.versionSource` in docs/package.json, resolved by `docouture +# release resolve` — `descriptor` (default: docs/.release-version, as described +# above), `github-release` (the published GitHub Release's tag) or `tag-bump` +# (the latest docs/v* tag plus a bump: `docs/release` patch, +# `docs/release-minor` minor, `docs/release-major` major). Only `descriptor` +# runs the descriptor bump and the git-flow sync below. Under `tag-bump` a +# `release: published` run has no pull request labels to read, so it bumps +# patch; use workflow_dispatch with an explicit version for anything else. +# # Git-flow (versioned only): the descriptor bump below lands on the release # branch, so the `sync-prerelease` job opens a pull request carrying it into # the prerelease branch (name read from docs/package.json's @@ -127,6 +137,7 @@ jobs: prerelease_branch: ${{ steps.flow.outputs.prerelease_branch }} version: ${{ steps.resolve.outputs.version }} bumped: ${{ steps.bump.outputs.bumped }} + uses_descriptor: ${{ steps.resolve.outputs.uses_descriptor }} # `docouture new` scaffolds this site's package.json, antora-playbook.yml, # docs/antora.yml etc. under docs/ (not the repository root) — see the # docs-site-package skill's reference/versioning-modes.md. Every step @@ -153,7 +164,9 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'release' && !github.event.release.prerelease) || (github.event.pull_request.merged == true && - contains(github.event.pull_request.labels.*.name, 'docs/release') && + (contains(github.event.pull_request.labels.*.name, 'docs/release') || + contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || + contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && (contains(github.event.pull_request.labels.*.name, 'skip-release') || !contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type'))) steps: @@ -285,6 +298,38 @@ jobs: echo "mode=${mode}" >> "$GITHUB_OUTPUT" echo "Detected ${mode} (antora-playbook.yml: ${line})" + # Where the target version comes from is decided by `docouture release + # resolve`, which reads the site's `docouture.versionSource` from + # docs/package.json: `descriptor` (default) uses the workflow_dispatch + # input if a person typed one, else the docs/.release-version file the + # merged PR committed; `github-release` uses the published Release's + # tag; `tag-bump` bumps the latest docs/v* tag by the PR's + # `docs/release[-minor|-major]` label. Standalone always targets + # `stable`. The command also validates it (present, SemVer, + # not 'stable') and fails here, before any tag is pushed below — a + # malformed value would otherwise only fail later in "Bump release + # descriptor", after the tag already exists. + - name: Resolve version + id: resolve + env: + MODE: ${{ steps.detect.outputs.mode }} + EVENT: ${{ github.event_name }} + DISPATCH_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ github.event.release.tag_name }} + LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} + run: | + args=(release resolve --mode "$MODE" --event "$EVENT" --labels "$LABELS") + if [ "$EVENT" = "workflow_dispatch" ]; then + args+=(--version "$DISPATCH_VERSION") + fi + if [ -n "$RELEASE_TAG" ]; then + args+=(--release-tag "$RELEASE_TAG") + fi + + resolved=$(npx docouture "${args[@]}") + echo "$resolved" >> "$GITHUB_OUTPUT" + echo "$resolved" + # The flow (trunk-based or git-flow) and, under git-flow, the prerelease # branch name come from docs/package.json's `docouture` block — one # declared source, kept in sync by `docouture new`, `branch-model` and @@ -295,11 +340,12 @@ jobs: id: flow env: MODE: ${{ steps.detect.outputs.mode }} + USES_DESCRIPTOR: ${{ steps.resolve.outputs.uses_descriptor }} run: | branching=$(node -p "require('./package.json').docouture?.branching ?? ''") prerelease=$(node -p "require('./package.json').docouture?.prereleaseBranch ?? ''") - if [ "$branching" = "git-flow" ] && [ -z "$prerelease" ] && [ "$MODE" = "versioned" ]; then + if [ "$branching" = "git-flow" ] && [ -z "$prerelease" ] && [ "$USES_DESCRIPTOR" = "true" ]; then echo "::error::docs/package.json declares docouture.branching 'git-flow' but no docouture.prereleaseBranch — run 'docouture upgrade' to add it (the prerelease branch needs a sync PR carrying the docs/.release-version bump)." exit 1 fi @@ -308,74 +354,6 @@ jobs: echo "prerelease_branch=${prerelease}" >> "$GITHUB_OUTPUT" echo "Detected flow '${branching:-trunk-based}' (prerelease branch '${prerelease}')" - # Where the target version comes from depends on how this run started: - # a person typed it (workflow_dispatch) or the merged PR committed it - # (docs/.release-version). Standalone ignores whatever this resolves to - # either way — it always targets `stable` — but it's still resolved - # uniformly here so later steps don't need to know which trigger fired. - - name: Resolve version - id: resolve - env: - EVENT: ${{ github.event_name }} - DISPATCH_VERSION: ${{ inputs.version }} - run: | - if [ "$EVENT" = "workflow_dispatch" ]; then - version="$DISPATCH_VERSION" - source="workflow_dispatch input" - elif [ -f .release-version ]; then - version=$(tr -d '[:space:]' < .release-version) - source="docs/.release-version" - else - version="" - source="docs/.release-version (missing)" - fi - - echo "version=${version}" >> "$GITHUB_OUTPUT" - echo "Resolved version '${version}' from ${source}" - - - name: Validate version - env: - MODE: ${{ steps.detect.outputs.mode }} - EVENT: ${{ github.event_name }} - VERSION: ${{ steps.resolve.outputs.version }} - run: | - if [ "$MODE" = "versioned" ] && [ -z "$VERSION" ]; then - if [ "$EVENT" = "workflow_dispatch" ]; then - echo "::error::Versioned mode requires a real target version — re-run with a 'version' input other than the default 'stable', e.g. 1.2.0." - else - echo "::error::Versioned mode requires a real target version, and this PR carried no docs/.release-version — add that file with the target version (e.g. 1.2.0) before merging with the docs/release label, or run docouture-release manually via workflow_dispatch instead." - fi - exit 1 - fi - - if [ "$MODE" = "versioned" ] && [ "$VERSION" = "stable" ]; then - echo "::error::'stable' is standalone's target name, not a valid versioned-mode version — use a real version, e.g. 1.2.0." - exit 1 - fi - - # Full SemVer 2.0.0 grammar (semver.org's own regex, rewritten with - # plain groups instead of `(?:...)` — bash's [[ =~ ]] runs glibc - # POSIX ERE, not PCRE, and doesn't understand non-capturing - # groups). Catches a hand-edited docs/.release-version (or a typo'd - # workflow_dispatch input) BEFORE any tag is pushed below — without - # this, a malformed value sails through here, tags and pushes fine - # in "Cut release"/"Push release tag", and only fails later inside - # "Bump release descriptor" (npm's `version patch` rejects - # non-semver input) — by which point the tag already exists but the - # job as a whole reads as failed, so the `publish` job below never - # runs. Prerelease/build-metadata suffixes (1.2.0-beta.1, - # 1.2.0+build) are valid SemVer and accepted; a leading 'v' or a - # bare '1.2' are not. - SEMVER_RE='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$' - if [ "$MODE" = "versioned" ] && [ -n "$VERSION" ] && ! [[ "$VERSION" =~ $SEMVER_RE ]]; then - echo "::error::docs/.release-version (or the 'version' input) must be a valid SemVer version like 1.2.0 — got '${VERSION}'. See https://semver.org — prerelease/build metadata (1.2.0-beta.1, 1.2.0+build) is fine, a leading 'v' or a two-part '1.2' is not." - exit 1 - fi - - if [ "$MODE" = "standalone" ] && [ -n "$VERSION" ] && [ "$VERSION" != "stable" ]; then - echo "::warning::Standalone mode always releases to the 'stable' tag — ignoring provided version '${VERSION}'." - fi - # The release branch's own docs/antora.yml is never touched here — it # permanently says version: prerelease (both modes, trunk-based only # — see the guides-branching-model guide for why this steady-state @@ -474,7 +452,7 @@ jobs: # republish of an already-released version — see "Check for existing # release" above): docs/.release-version needs a sane value again # immediately or the next docs/release merge has nothing to read (see - # "Validate version" above). Rather than clearing it, bump it forward + # "Resolve version" above). Rather than clearing it, bump it forward # one patch version — the same idiom `just bump` uses for this # workspace's own npm packages: let `npm version` do the semver # arithmetic against a throwaway package.json instead of hand-rolling @@ -487,7 +465,7 @@ jobs: # protecting it. - name: Bump release descriptor id: bump - if: steps.detect.outputs.mode == 'versioned' && steps.check.outputs.existed != 'true' + if: steps.resolve.outputs.uses_descriptor == 'true' && steps.check.outputs.existed != 'true' env: VERSION: ${{ steps.resolve.outputs.version }} run: | @@ -517,6 +495,7 @@ jobs: if: >- needs.release.result == 'success' && needs.release.outputs.branching == 'git-flow' && + needs.release.outputs.uses_descriptor == 'true' && needs.release.outputs.bumped == 'true' runs-on: ubuntu-24.04 timeout-minutes: 10 diff --git a/AGENTS.md b/AGENTS.md index 20a398fa..96bfe272 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,7 +108,8 @@ npx skills@latest add InditexTech/docouture --all that must agree, the home-page vs. content-page patterns, and how a site grows beyond its default `ROOT` + `main` modules. - **`docouture-docs-versioning`** — only relevant when this site was scaffolded with - `--mode versioned`: cutting releases, `docouture version`, and `docs/.release-version`. + `--mode versioned`: cutting releases, `docouture version`, `docs/.release-version` and the + alternative version sources (`docouture version-source`). @@ -152,6 +153,7 @@ issue belongs to. | structure.adoc | `code/README.md`, workspace `packages/` layout | current | | guides-branching-model.adoc | `code/packages/cli/templates/workflows/*.yml` | current | | guides-releasing-a-documentation.adoc | `code/packages/cli/templates/workflows/docouture-release.yml`, `docouture-release-preview.yml` | current | +| release-notes/1-4-0.adoc (v1.4.0 entry) | manual (hand-written: version sources, upgrade order, limitations) | current | | release-notes/1-3-2.adoc (v1.3.2 entry) | manual (hand-written: combined-release preview wording and upgrade steps) | current | | release-notes/1-3-1.adoc (v1.3.1 entry) | manual (hand-written: handlebars security floor and upgrade steps) | current | | release-notes/1-3-0.adoc (v1.3.0 entry) | manual (hand-written: check-links removal and upgrade checklist) | current | diff --git a/code/packages/cli/src/bin.ts b/code/packages/cli/src/bin.ts index 0fb448ed..7c185c3d 100644 --- a/code/packages/cli/src/bin.ts +++ b/code/packages/cli/src/bin.ts @@ -7,7 +7,9 @@ 'use strict' import { runNew } from './commands/new.js' +import { runRelease } from './commands/release.js' import { runVersion } from './commands/version.js' +import { runVersionSource } from './commands/version-source.js' import { runDev } from './commands/dev.js' import { runBuild } from './commands/build.js' import { runDoctor } from './commands/doctor.js' @@ -42,6 +44,8 @@ const COMMAND_ORDER = [ 'doctor', 'upgrade', 'branch-model', + 'version-source', + 'release', 'eject', 'teardown', 'completion', @@ -238,6 +242,83 @@ Options: --release-branch Git-flow target only: the release branch --dir Repository root (default: cwd, or its enclosing repo) --dry-run List what would be written without changing anything +`, + }, + 'version-source': { + usageLine: 'version-source [source]', + summary: 'Choose where the docs release version comes from', + help: `Usage: + docouture version-source [descriptor|github-release|tag-bump] [--prefix

] + [--version ] [--dir ] [--dry-run] + +Show or change where a versioned site's docs release version comes from +(docs/package.json's docouture.versionSource). With no argument it prints +the current source. + + descriptor docs/.release-version, committed by the release PR (the + default). Creates the file, seeded with the next patch of + the latest docs/v* tag (or --version), if it is missing. + github-release the tag of the published GitHub Release (--prefix strips a + tag prefix such as docs-site@). Removes docs/.release-version. + tag-bump the latest docs/v* tag plus a bump chosen by the PR's + docs/release, docs/release-minor or docs/release-major + label. Removes docs/.release-version and prints the + 'gh label create' commands for the two extra labels. + +Refuses a standalone site (it always releases docs/stable). Removing +docs/.release-version warns when it held a pending version. Idempotent. +Workflows read the source at run time, so none are re-rendered — but they +run the project's installed CLI, so install a version with 'release resolve' +first. + +Options: + --prefix

github-release only: strip this prefix from the release tag + --version descriptor only: write this version to docs/.release-version + --dir Repository root (default: cwd, or its enclosing repo) + --dry-run List what would change without changing anything +`, + }, + release: { + usageLine: 'release resolve', + summary: 'Resolve the docs version a release targets', + help: `Usage: + docouture release resolve --mode [--version ] + [--event ] [--release-tag ] [--labels ] [--tags ] + [--report] [--dir ] + +Resolve the docs version and tag a release run targets. Used by the +docouture-release and docouture-release-preview workflows. Where the +version comes from depends on docs/package.json's docouture.versionSource +(default 'descriptor'): + + descriptor --version when given (the workflow_dispatch input), else + docs/.release-version + github-release the published release tag (--release-tag), minus + docouture.versionSourcePrefix when set; a docs/release + pull request fails + tag-bump the highest docs/v* tag plus a bump chosen by --labels: + docs/release patch, docs/release-minor minor, + docs/release-major major (highest wins); the first + release needs --version + +--version always wins. Standalone sites always target 'stable'. + +Prints key=value lines (version, tag, source, version_source, +uses_descriptor) to stdout, ready to append to $GITHUB_OUTPUT. +uses_descriptor is true only when the descriptor bump and prerelease sync +apply. A missing or non-SemVer version fails with exit 1. With --report +the failure is printed as error= and error_value= instead, and the exit code stays 0. + +Options: + --mode 'versioned' or 'standalone' (required) + --version Explicit version; takes precedence over every source + --event GitHub event name (workflow_dispatch, pull_request, release) + --release-tag Tag of the published GitHub Release (github-release) + --labels Pull request labels, comma-separated (tag-bump) + --tags Existing tag names instead of listing git tags (tag-bump) + --report Report a version error as output instead of failing + --dir Repository root (default: cwd, or its enclosing repo) `, }, eject: { @@ -294,8 +375,8 @@ Examples: const CLI_SUMMARY = 'Scaffold, build, and publish Antora documentation sites' // Left column width of the command table below, including the 2-space -// indent — wide enough for the longest usageLine ('branch-model '). -const COMMAND_COLUMN_WIDTH = 24 +// indent — wide enough for the longest usageLine ('version-source [source]'). +const COMMAND_COLUMN_WIDTH = 28 const USAGE = `Usage: docouture [options] @@ -326,6 +407,8 @@ const RUNNERS: Record = { doctor: runDoctor, upgrade: runUpgrade, 'branch-model': runBranchModel, + 'version-source': runVersionSource, + release: runRelease, eject: runEject, teardown: runTeardown, completion: async (argv) => runCompletion(argv), diff --git a/code/packages/cli/src/commands/completion.ts b/code/packages/cli/src/commands/completion.ts index d046a54b..4ff2fe4c 100644 --- a/code/packages/cli/src/commands/completion.ts +++ b/code/packages/cli/src/commands/completion.ts @@ -25,6 +25,8 @@ export const COMMANDS = [ 'doctor', 'upgrade', 'branch-model', + 'version-source', + 'release', 'eject', 'teardown', 'completion', diff --git a/code/packages/cli/src/commands/doctor.ts b/code/packages/cli/src/commands/doctor.ts index 2a446c62..749c087c 100644 --- a/code/packages/cli/src/commands/doctor.ts +++ b/code/packages/cli/src/commands/doctor.ts @@ -14,10 +14,15 @@ import { getContext } from '../lib/cli-context.js' import { theme } from '../lib/theme.js' import { readSourceUrl, readStartPageComponent, readStartPath } from '../lib/playbook-yml.js' import { detectBranches, inferBranching } from '../lib/branch-detect.js' +import { readCliInfo } from '../lib/cli-info.js' +import { readProjectCli } from '../lib/project-cli.js' +import { detectSiteMode } from '../lib/site-mode.js' import { checkAgentFilesPresent, checkAntoraAvailable, checkBranchingAgrees, + checkProjectCli, + checkVersionSource, checkGitHasCommit, checkNamesAgree, checkNodeVersion, @@ -30,7 +35,7 @@ interface PackageJson { name?: string engines?: { node?: string } packageManager?: string - docouture?: { branching?: string; prereleaseBranch?: string } + docouture?: { branching?: string; prereleaseBranch?: string; versionSource?: string } } interface JsonCheckResult extends CheckResult { @@ -260,6 +265,21 @@ export async function runDoctor(argv: string[]): Promise { json ) + log('version source') + runCheck( + report, + 'version source', + checkVersionSource({ + mode: await detectSiteMode(siteRoot), + declared: pkg?.docouture?.versionSource ?? null, + descriptorExists: await exists(join(siteRoot, '.release-version')), + }), + 'warn', + json + ) + const { version: runningCli } = await readCliInfo(import.meta.url, 2) + runChecks(report, 'version source', checkProjectCli(runningCli, await readProjectCli(siteRoot, target)), 'warn', json) + if (json) { process.stdout.write(`${JSON.stringify({ status: status === 0 ? 'ok' : 'fail', checks: report }, null, 2)}\n`) } diff --git a/code/packages/cli/src/commands/new.spec.ts b/code/packages/cli/src/commands/new.spec.ts index 0ca5f935..e147955a 100644 --- a/code/packages/cli/src/commands/new.spec.ts +++ b/code/packages/cli/src/commands/new.spec.ts @@ -510,6 +510,64 @@ describe('runNew', () => { expect(playbook).toContain('duplicate_latest_version: true') }) + describe('--version-source', () => { + async function scaffoldVersioned(extra: string[]): Promise<{ code: number; repo: string }> { + const repo = join(base, 'repo') + await initRepo(repo) + const code = await runNew(['my-project-docs', '--dir', repo, '--mode', 'versioned', ...extra]) + return { code, repo } + } + + async function declared(repo: string): Promise | undefined> { + const pkg = JSON.parse(await readFile(join(repo, 'docs', 'package.json'), 'utf8')) as { + docouture?: Record + } + return pkg.docouture + } + + it('defaults to descriptor and lays down docs/.release-version', async () => { + const { code, repo } = await scaffoldVersioned([]) + expect(code).toBe(0) + expect((await declared(repo))?.versionSource).toBe('descriptor') + expect((await readFile(join(repo, 'docs', '.release-version'), 'utf8')).trim()).toBe('0.1.0') + }) + + it.each(['github-release', 'tag-bump'])('%s declares the source and lays down no .release-version', async (source) => { + const { code, repo } = await scaffoldVersioned(['--version-source', source]) + expect(code).toBe(0) + expect((await declared(repo))?.versionSource).toBe(source) + await expect(readFile(join(repo, 'docs', '.release-version'), 'utf8')).rejects.toThrow() + }) + + it('prints the exact label commands for tag-bump', async () => { + await scaffoldVersioned(['--version-source', 'tag-bump']) + const printed = logSpy.mock.calls.flat().join('\n') + expect(printed).toContain('gh label create docs/release-minor') + expect(printed).toContain('gh label create docs/release-major') + }) + + it('rejects an invalid value', async () => { + const { code } = await scaffoldVersioned(['--version-source', 'bogus']) + expect(code).toBe(1) + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("invalid --version-source: 'bogus'")) + }) + + it('rejects a standalone site', async () => { + const repo = join(base, 'repo') + await initRepo(repo) + const code = await runNew(['my-project-docs', '--dir', repo, '--mode', 'standalone', '--version-source', 'tag-bump']) + expect(code).toBe(1) + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('standalone')) + }) + + it('writes no version source for a standalone site', async () => { + const repo = join(base, 'repo') + await initRepo(repo) + await runNew(['my-project-docs', '--dir', repo]) + expect(await declared(repo)).not.toHaveProperty('versionSource') + }) + }) + it('pins @inditextech/docouture-cli and antora to exact versions in the scaffolded package.json', async () => { const repo = join(base, 'repo') await initRepo(repo) @@ -555,6 +613,8 @@ describe('runNew', () => { input.write('\n') // Enter — accept the default (trunk-based) await waitForPrompt('Branch (plays both') input.write('\n') // Enter — accept the default (main) + await waitForPrompt('docs release version come from') + input.write('\n') // Enter — accept the default (descriptor) await waitForPrompt('Package manager') input.write('\n') // Enter — accept the default (npm, or whatever was auto-guessed) @@ -562,6 +622,11 @@ describe('runNew', () => { input.end() expect(code).toBe(0) + const wizardPkg = JSON.parse(await readFile(join(repo, 'docs', 'package.json'), 'utf8')) as { + docouture?: Record + } + expect(wizardPkg.docouture?.versionSource).toBe('descriptor') + const antoraYml = await readFile(join(repo, 'docs', 'src', 'antora.yml'), 'utf8') expect(antoraYml).toContain('name: ROOT') expect(antoraYml).toContain('title: My Wizard Docs') diff --git a/code/packages/cli/src/commands/new.ts b/code/packages/cli/src/commands/new.ts index dee3e434..d377245e 100644 --- a/code/packages/cli/src/commands/new.ts +++ b/code/packages/cli/src/commands/new.ts @@ -25,6 +25,9 @@ import { findRepoRoot } from '../lib/repo-root.js' import { normalizeSiteUrl, siteUrlLine } from '../lib/site-url.js' import { AGENTS_MD_FILENAME, hasManagedSection, mergeAgentsMd } from '../lib/agents-md.js' import { cacheWarmBranchesYaml, type Branching } from '../lib/branch-detect.js' +import { setVersionSource } from '../lib/package-version-source.js' +import { TAG_BUMP_LABEL_COMMANDS } from '../lib/release-labels.js' +import { VERSION_SOURCES, type VersionSource } from '../lib/release-resolve.js' // Matches the rule an npm package name (and, not coincidentally, an Antora // component name — both end up as URL segments) can safely be: this is @@ -208,6 +211,7 @@ interface WizardAnswers { branching: Branching prereleaseBranch: string releaseBranch: string + versionSource: VersionSource | undefined pm: PackageManager } @@ -230,6 +234,7 @@ async function promptWizard( branch?: string prereleaseBranch?: string releaseBranch?: string + versionSource?: VersionSource pm?: PackageManager }, defaults: { pm: PackageManager; siteUrl: string | undefined } @@ -405,6 +410,41 @@ async function promptWizard( releaseBranch = branch } + // Where the docs release version comes from — versioned sites only, + // standalone always targets the rolling 'docs/stable' tag. See + // lib/release-resolve.ts and the docs-version-source spec. + const versionSource = + mode === 'versioned' + ? (initial.versionSource ?? + (await select( + { + message: 'Where does the docs release version come from?\n', + default: 'descriptor' as VersionSource, + choices: [ + { + name: 'descriptor (docs/.release-version)', + value: 'descriptor', + description: + 'A release pull request commits the target version in docs/.release-version; the workflow bumps it to the next patch afterwards.', + }, + { + name: 'github-release (the code release tag)', + value: 'github-release', + description: + 'The docs follow the code: publishing a GitHub Release releases the docs at that release tag. No version file.', + }, + { + name: 'tag-bump (latest docs/v* tag + bump)', + value: 'tag-bump', + description: + "The next version is the latest docs/v* tag plus a bump chosen by the PR's label (docs/release patch, docs/release-minor, docs/release-major). No version file.", + }, + ], + }, + context + ))) + : undefined + const pm = initial.pm ?? (await select( @@ -428,6 +468,7 @@ async function promptWizard( branching, prereleaseBranch, releaseBranch, + versionSource, pm, } } @@ -515,6 +556,18 @@ export async function runNew(argv: string[], io: NewIO = defaultIO()): Promise undefined; not given at all -> derived default. @@ -592,7 +653,7 @@ export async function runNew(argv: string[], io: NewIO = defaultIO()): Promise [--dir ] [--title ] [--site-url <url>] [--url-segment] [--mode standalone|versioned] ' + '[--flow trunk-based|git-flow] [--branch <name>] [--integration-branch <name>] [--release-branch <name>] ' + - '[--pm npm|pnpm]' + '[--version-source descriptor|github-release|tag-bump] [--pm npm|pnpm]' ) return 1 } @@ -650,11 +711,13 @@ export async function runNew(argv: string[], io: NewIO = defaultIO()): Promise<n branching, prereleaseBranch, releaseBranch, + versionSource, pmChoice, }) printNextSteps({ mode, + versionSource, branching, prereleaseBranch, releaseBranch, @@ -748,6 +811,7 @@ async function scaffoldSite(params: { branching: Branching prereleaseBranch: string releaseBranch: string + versionSource: VersionSource | undefined pmChoice: PackageManager }): Promise<PackageManagerPlan> { const { @@ -763,6 +827,7 @@ async function scaffoldSite(params: { branching, prereleaseBranch, releaseBranch, + versionSource, pmChoice, } = params @@ -856,11 +921,17 @@ async function scaffoldSite(params: { join(docsDir, 'antora-playbook.yml'), values ) - await writeTemplateFile( - join(starterDir, 'src', 'release-version.versioned'), - join(docsDir, '.release-version'), - values - ) + const source = versionSource ?? 'descriptor' + await setVersionSource(join(docsDir, 'package.json'), source) + // Only `descriptor` keeps a version file; the other sources read the + // version from the release tag / the existing docs/v* tags. + if (source === 'descriptor') { + await writeTemplateFile( + join(starterDir, 'src', 'release-version.versioned'), + join(docsDir, '.release-version'), + values + ) + } } return pm @@ -872,6 +943,7 @@ async function scaffoldSite(params: { // own banner — see lib/theme.ts for why that's not picocolors directly. function printNextSteps(args: { mode: Mode + versionSource: VersionSource | undefined branching: Branching prereleaseBranch: string releaseBranch: string @@ -881,7 +953,18 @@ function printNextSteps(args: { workflowsDir: string ghPagesUrl: string | undefined }): void { - const { mode, branching, prereleaseBranch, releaseBranch, pm, target, docsDir, workflowsDir, ghPagesUrl } = args + const { + mode, + versionSource, + branching, + prereleaseBranch, + releaseBranch, + pm, + target, + docsDir, + workflowsDir, + ghPagesUrl, + } = args const created = (path: string): string => ` ${theme.success('✓')} ${path}` // Relative to `target` (the repo root), not process.cwd() — cwd may be a @@ -930,14 +1013,37 @@ function printNextSteps(args: { console.log(theme.bold('Versioning: Versioned (Full History)')) console.log(` ${prereleaseBranch} is the prerelease channel.`) console.log('') - console.log(' To cut your first release:') - console.log(" 1. Create the 'docs/release' label (once): gh label create docs/release") - console.log(' 2. Open a PR that sets the target version in docs/.release-version (e.g. "1.0.0")') - console.log(" 3. Label the PR 'docs/release'") - console.log(' 4. Merge it — docouture-release.yml runs automatically and tags docs/vX.Y.Z') - console.log('') - console.log(' (or skip the label/PR entirely: run docouture-release.yml manually via workflow_dispatch') - console.log(' and type the version)') + if (versionSource === 'github-release') { + console.log(' Version source: github-release — the docs follow your code release.') + console.log(' The docs are released, at the release tag, when a GitHub Release is published;') + console.log(' there is no docs/.release-version. If your release tags carry a prefix (e.g. docs-site@),') + console.log(' run: docouture version-source github-release --prefix <prefix>') + console.log('') + console.log(' To cut your first release: publish a GitHub Release (or run docouture-release.yml') + console.log(' manually via workflow_dispatch and type the version).') + } else if (versionSource === 'tag-bump') { + console.log(' Version source: tag-bump — the next version is the latest docs/vX.Y.Z tag plus a bump.') + console.log(' There is no docs/.release-version.') + console.log('') + console.log(' To cut your first release (there is no tag to bump from yet):') + console.log(' run docouture-release.yml manually via workflow_dispatch and type the version (e.g. 1.0.0).') + console.log('') + console.log(' After that, label a merged PR to release: patch with docs/release, minor with') + console.log(' docs/release-minor, major with docs/release-major. Create the labels once:') + console.log(' gh label create docs/release') + for (const command of TAG_BUMP_LABEL_COMMANDS) console.log(` ${command}`) + } else { + console.log(' Version source: descriptor — the target version is docs/.release-version.') + console.log('') + console.log(' To cut your first release:') + console.log(" 1. Create the 'docs/release' label (once): gh label create docs/release") + console.log(' 2. Open a PR that sets the target version in docs/.release-version (e.g. "1.0.0")') + console.log(" 3. Label the PR 'docs/release'") + console.log(' 4. Merge it — docouture-release.yml runs automatically and tags docs/vX.Y.Z') + console.log('') + console.log(' (or skip the label/PR entirely: run docouture-release.yml manually via workflow_dispatch') + console.log(' and type the version)') + } console.log('') console.log( ' See the docouture-docs-versioning skill (npx skills add InditexTech/docouture) for the full mechanism.' diff --git a/code/packages/cli/src/commands/release.spec.ts b/code/packages/cli/src/commands/release.spec.ts new file mode 100644 index 00000000..22441fab --- /dev/null +++ b/code/packages/cli/src/commands/release.spec.ts @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { execFileSync } from 'node:child_process' +import { mkdir, mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { runRelease } from './release.js' + +let dir: string +let errorSpy: ReturnType<typeof vi.spyOn> +let logSpy: ReturnType<typeof vi.spyOn> + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'docouture-cli-release-')) + await mkdir(join(dir, 'docs'), { recursive: true }) + errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) +}) + +afterEach(() => { + errorSpy.mockRestore() + logSpy.mockRestore() +}) + +const out = () => logSpy.mock.calls.map((c: unknown[]) => String(c[0])) + +describe('runRelease resolve', () => { + it('prints key=value lines from the descriptor', async () => { + await writeFile(join(dir, 'docs', '.release-version'), '1.2.0\n') + expect(await runRelease(['resolve', '--mode', 'versioned', '--dir', dir])).toBe(0) + expect(out()).toEqual([ + 'version=1.2.0', + 'tag=docs/v1.2.0', + 'source=docs/.release-version', + 'version_source=descriptor', + 'uses_descriptor=true', + ]) + }) + + it('prefers --version', async () => { + await writeFile(join(dir, 'docs', '.release-version'), '1.2.0\n') + expect(await runRelease(['resolve', '--mode', 'versioned', '--version', '2.0.0', '--dir', dir])).toBe(0) + expect(out()[0]).toBe('version=2.0.0') + }) + + it('reports stable for standalone', async () => { + expect(await runRelease(['resolve', '--mode', 'standalone', '--dir', dir])).toBe(0) + expect(out()).toContain('tag=docs/stable') + expect(out()).toContain('uses_descriptor=false') + }) + + it('warns and ignores a mismatched standalone version', async () => { + expect(await runRelease(['resolve', '--mode', 'standalone', '--version', '1.2.3', '--dir', dir])).toBe(0) + expect(errorSpy.mock.calls.flat().join('\n')).toContain('ignoring provided version') + expect(out()).toContain('version=stable') + }) + + it('fails on a missing file', async () => { + expect(await runRelease(['resolve', '--mode', 'versioned', '--dir', dir])).toBe(1) + expect(errorSpy.mock.calls.flat().join('\n')).toContain('missing') + expect(out()).toEqual([]) + }) + + it('fails on an invalid version', async () => { + await writeFile(join(dir, 'docs', '.release-version'), 'v1.2\n') + expect(await runRelease(['resolve', '--mode', 'versioned', '--dir', dir])).toBe(1) + }) + + it('--report exits 0 with the error kind and value', async () => { + await writeFile(join(dir, 'docs', '.release-version'), '1.2\n') + expect(await runRelease(['resolve', '--mode', 'versioned', '--report', '--dir', dir])).toBe(0) + expect(out()).toContain('error=invalid') + expect(out()).toContain('error_value=1.2') + }) + + it('--report on a missing file reports missing', async () => { + expect(await runRelease(['resolve', '--mode', 'versioned', '--report', '--dir', dir])).toBe(0) + expect(out()).toContain('error=missing') + }) + + it('rejects a bad mode and an unknown subcommand', async () => { + expect(await runRelease(['resolve', '--mode', 'x'])).toBe(1) + expect(await runRelease(['nope'])).toBe(1) + }) + + describe('version sources', () => { + async function writeSource(docouture: Record<string, unknown>): Promise<void> { + await writeFile(join(dir, 'docs', 'package.json'), JSON.stringify({ name: 'docs', docouture })) + } + + function git(...args: string[]): void { + execFileSync('git', args, { cwd: dir, stdio: 'ignore' }) // NOSONAR + } + + it('fails naming the valid values on an unknown source', async () => { + await writeSource({ versionSource: 'tag_bump' }) + expect(await runRelease(['resolve', '--mode', 'versioned', '--dir', dir])).toBe(1) + const message = errorSpy.mock.calls.flat().join('\n') + expect(message).toContain('tag_bump') + expect(message).toContain('descriptor, github-release, tag-bump') + }) + + it('resolves github-release from the release tag, stripping the prefix', async () => { + await writeSource({ versionSource: 'github-release', versionSourcePrefix: 'docs-site@' }) + const argv = ['resolve', '--mode', 'versioned', '--event', 'release', '--release-tag', 'docs-site@1.4.0', '--dir', dir] + expect(await runRelease(argv)).toBe(0) + expect(out()).toContain('version=1.4.0') + expect(out()).toContain('version_source=github-release') + expect(out()).toContain('uses_descriptor=false') + }) + + it('fails a docs/release pull request under github-release', async () => { + await writeSource({ versionSource: 'github-release' }) + const argv = ['resolve', '--mode', 'versioned', '--event', 'pull_request', '--labels', 'docs/release', '--dir', dir] + expect(await runRelease(argv)).toBe(1) + expect(errorSpy.mock.calls.flat().join('\n')).toContain('github-release') + }) + + it('bumps tag-bump from real git tags and the label list', async () => { + await writeSource({ versionSource: 'tag-bump' }) + git('init', '-q') + git('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '--allow-empty', '-qm', 'x') + for (const tag of ['docs/v1.2.3', 'docs/v1.1.0', 'docs/stable']) git('tag', tag) + const argv = ['resolve', '--mode', 'versioned', '--labels', 'docs/release, docs/release-minor', '--dir', dir] + expect(await runRelease(argv)).toBe(0) + expect(out()).toContain('version=1.3.0') + expect(out()).toContain('tag=docs/v1.3.0') + expect(out()).toContain('version_source=tag-bump') + expect(out()).toContain('uses_descriptor=false') + }) + + it('uses injected --tags instead of listing git tags', async () => { + await writeSource({ versionSource: 'tag-bump' }) + const argv = ['resolve', '--mode', 'versioned', '--tags', 'docs/v2.0.0,docs/v1.9.0\ndocs/stable', '--dir', dir] + expect(await runRelease(argv)).toBe(0) + expect(out()).toContain('version=2.0.1') + }) + + it('fails the first tag-bump release without a version', async () => { + await writeSource({ versionSource: 'tag-bump' }) + git('init', '-q') + expect(await runRelease(['resolve', '--mode', 'versioned', '--dir', dir])).toBe(1) + expect(errorSpy.mock.calls.flat().join('\n')).toContain('explicit version') + }) + + it('does not read the descriptor under tag-bump', async () => { + await writeSource({ versionSource: 'tag-bump' }) + await writeFile(join(dir, 'docs', '.release-version'), '9.9.9\n') + git('init', '-q') + expect(await runRelease(['resolve', '--mode', 'versioned', '--version', '2.0.0', '--dir', dir])).toBe(0) + expect(out()).toContain('version=2.0.0') + }) + }) +}) diff --git a/code/packages/cli/src/commands/release.ts b/code/packages/cli/src/commands/release.ts new file mode 100644 index 00000000..69a6d298 --- /dev/null +++ b/code/packages/cli/src/commands/release.ts @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { readFile } from 'node:fs/promises' +import { join, resolve } from 'node:path' + +import { parseArgs } from '../lib/args.js' +import { exists } from '../lib/copy-template.js' +import { listDocsTags } from '../lib/docs-tags.js' +import { findRepoRoot } from '../lib/repo-root.js' +import { readVersionSourceDeclaration } from '../lib/package-version-source.js' +import { type ReleaseMode, resolveRelease, VERSION_SOURCES } from '../lib/release-resolve.js' + +const USAGE = + 'usage: docouture release resolve --mode <versioned|standalone> [--version <v>] [--event <name>] [--release-tag <tag>] [--labels <a,b>] [--tags <a,b>] [--report] [--dir <path>]' + +async function runResolve(argv: string[]): Promise<number> { + const { flags } = parseArgs(argv) + + const mode = flags.mode + if (mode !== 'versioned' && mode !== 'standalone') { + console.error(USAGE) + console.error(`invalid --mode: '${typeof mode === 'string' ? mode : ''}' — expected 'versioned' or 'standalone'`) + return 1 + } + + const explicit = typeof flags.version === 'string' ? flags.version : undefined + const report = flags.report === true + const startDir = typeof flags.dir === 'string' ? resolve(flags.dir) : resolve(process.cwd()) + const repoRoot = await findRepoRoot(startDir) + const descriptorFile = join(repoRoot, 'docs', '.release-version') + const descriptor = (await exists(descriptorFile)) ? await readFile(descriptorFile, 'utf8') : null + + const packageJsonFile = join(repoRoot, 'docs', 'package.json') + const declaration = (await exists(packageJsonFile)) + ? await readVersionSourceDeclaration(packageJsonFile) + : { raw: null, source: 'descriptor' as const, prefix: null } + if (declaration.source === null) { + console.error( + `::error::docs/package.json declares docouture.versionSource '${declaration.raw}' — expected one of: ${VERSION_SOURCES.join(', ')}` + ) + return 1 + } + const source = declaration.source + const event = typeof flags.event === 'string' ? flags.event : undefined + const releaseTag = typeof flags['release-tag'] === 'string' ? flags['release-tag'] : undefined + const labels = + typeof flags.labels === 'string' + ? flags.labels + .split(',') + .map((label) => label.trim()) + .filter((label) => label !== '') + : [] + // --tags injects the tag names (comma- or newline-separated) for callers with + // no local tags to list, such as a shallow checkout without credentials. + const injectedTags = + typeof flags.tags === 'string' + ? flags.tags + .split(/[,\n]/) + .map((tag) => tag.trim()) + .filter((tag) => tag !== '') + : undefined + const tags = source === 'tag-bump' && mode === 'versioned' ? (injectedTags ?? (await listDocsTags(repoRoot))) : [] + + if (mode === 'standalone' && explicit !== undefined && explicit !== 'stable') { + console.error( + `::warning::Standalone mode always releases to the 'stable' tag — ignoring provided version '${explicit}'.` + ) + } + + const result = resolveRelease({ + mode: mode as ReleaseMode, + explicit, + descriptor, + source, + event, + releaseTag, + prefix: declaration.prefix ?? undefined, + labels, + tags, + }) + + if (result.error && !report) { + console.error(`::error::${result.error.message}`) + return 1 + } + + console.log(`version=${result.version}`) + console.log(`tag=${result.tag}`) + console.log(`source=${result.source}`) + console.log(`version_source=${mode === 'standalone' ? 'standalone' : source}`) + console.log(`uses_descriptor=${result.usesDescriptor === true}`) + if (result.error) { + console.log(`error=${result.error.kind}`) + console.log(`error_value=${result.error.value}`) + } + return 0 +} + +export async function runRelease(argv: string[]): Promise<number> { + const [sub, ...rest] = argv + if (sub === 'resolve') return runResolve(rest) + console.error(USAGE) + console.error(`unknown release subcommand: '${sub ?? ''}' — expected 'resolve'`) + return 1 +} diff --git a/code/packages/cli/src/commands/upgrade.spec.ts b/code/packages/cli/src/commands/upgrade.spec.ts index 96ae282b..ae9c48d7 100644 --- a/code/packages/cli/src/commands/upgrade.spec.ts +++ b/code/packages/cli/src/commands/upgrade.spec.ts @@ -95,6 +95,85 @@ describe('runUpgrade', () => { expect(await readFile(pkgPath, 'utf8')).toBe(before) }) + describe('docouture.versionSource backfill', () => { + async function legacyVersionedSite(): Promise<{ repo: string; pkgPath: string }> { + const repo = join(base, 'repo') + await initRepo(repo) + await runNew(['my-docs', '--dir', repo, '--yes', '--mode', 'versioned']) + const pkgPath = join(repo, 'docs', 'package.json') + const pkg = JSON.parse(await readFile(pkgPath, 'utf8')) + delete pkg.docouture.versionSource + await writeFile(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8') + return { repo, pkgPath } + } + + it('writes descriptor on a versioned site that lacks it and points at version-source', async () => { + const { repo, pkgPath } = await legacyVersionedSite() + expect(await runUpgrade(['--dir', repo])).toBe(0) + expect(JSON.parse(await readFile(pkgPath, 'utf8')).docouture.versionSource).toBe('descriptor') + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("docouture.versionSource 'descriptor'")) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('docouture')) + }) + + it('is idempotent', async () => { + const { repo, pkgPath } = await legacyVersionedSite() + await runUpgrade(['--dir', repo]) + const first = await readFile(pkgPath, 'utf8') + logSpy.mockClear() + await runUpgrade(['--dir', repo]) + expect(await readFile(pkgPath, 'utf8')).toBe(first) + expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("docouture.versionSource 'descriptor'")) + }) + + it('never changes an existing value', async () => { + const repo = join(base, 'repo') + await initRepo(repo) + await runNew(['my-docs', '--dir', repo, '--yes', '--mode', 'versioned', '--version-source', 'tag-bump']) + await runUpgrade(['--dir', repo]) + const pkg = JSON.parse(await readFile(join(repo, 'docs', 'package.json'), 'utf8')) + expect(pkg.docouture.versionSource).toBe('tag-bump') + }) + + it('leaves a standalone site alone', async () => { + const repo = join(base, 'repo') + await initRepo(repo) + await runNew(['my-docs', '--dir', repo, '--yes']) + await runUpgrade(['--dir', repo]) + const pkg = JSON.parse(await readFile(join(repo, 'docs', 'package.json'), 'utf8')) + expect(pkg.docouture).not.toHaveProperty('versionSource') + }) + + it('--dry-run reports it without writing', async () => { + const { repo, pkgPath } = await legacyVersionedSite() + const before = await readFile(pkgPath, 'utf8') + await runUpgrade(['--dir', repo, '--dry-run']) + expect(await readFile(pkgPath, 'utf8')).toBe(before) + expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("would set docouture.versionSource to 'descriptor'")) + }) + }) + + describe('CLI skew warning', () => { + it("warns when the project's pinned CLI differs from the running one", async () => { + const repo = join(base, 'repo') + await initRepo(repo) + await runNew(['my-docs', '--dir', repo, '--yes']) + const pkgPath = join(repo, 'docs', 'package.json') + const pkg = JSON.parse(await readFile(pkgPath, 'utf8')) + pkg.devDependencies['@inditextech/docouture-cli'] = '0.0.1' + await writeFile(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8') + await runUpgrade(['--dir', repo]) + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('0.0.1')) + }) + + it('does not warn on a fresh scaffold', async () => { + const repo = join(base, 'repo') + await initRepo(repo) + await runNew(['my-docs', '--dir', repo, '--yes']) + await runUpgrade(['--dir', repo]) + expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining('differs from the project')) + }) + }) + it('refuses to run when --dir is not inside a git repository', async () => { const notARepo = join(base, 'not-a-repo') await mkdir(notARepo, { recursive: true }) diff --git a/code/packages/cli/src/commands/upgrade.ts b/code/packages/cli/src/commands/upgrade.ts index c7472e8d..9fd20bb0 100644 --- a/code/packages/cli/src/commands/upgrade.ts +++ b/code/packages/cli/src/commands/upgrade.ts @@ -17,6 +17,9 @@ import { resolveConfig } from '../lib/config-resolver.js' import { findRepoRoot } from '../lib/repo-root.js' import { AGENTS_MD_FILENAME, mergeAgentsMd } from '../lib/agents-md.js' import { setBranching } from '../lib/package-branching.js' +import { readVersionSourceDeclaration, setVersionSource } from '../lib/package-version-source.js' +import { cliSkewMessage, readProjectCli } from '../lib/project-cli.js' +import { detectSiteMode } from '../lib/site-mode.js' import { removeCheckLinks } from '../lib/check-links-removal.js' import { setFailureLevel } from '../lib/playbook-yml.js' import { cacheWarmBranchesYaml, detectBranches } from '../lib/branch-detect.js' @@ -228,6 +231,14 @@ export async function runUpgrade(argv: string[]): Promise<number> { const pkgText = (await exists(siteRootPackageJson)) ? await readFile(siteRootPackageJson, 'utf8') : null const pkgRemoval = pkgText === null ? null : removeCheckLinks(pkgText) + // Versioned sites that predate `docouture.versionSource` get the explicit + // default written back (no behavior change). Never touches an existing + // value, a standalone site, or a site with no docs/package.json. + const needsVersionSource = + pkgText !== null && + (await detectSiteMode(siteRoot)) === 'versioned' && + (await readVersionSourceDeclaration(siteRootPackageJson)).raw === null + if (dryRun) { const plannedWorkflows = await copyTemplate(workflowsTemplateDir, workflowsDir, values, { dryRun: true }) @@ -235,6 +246,9 @@ export async function runUpgrade(argv: string[]): Promise<number> { for (const path of [...plannedWorkflows, agentsMdFile, ...strictPlans.map((p) => p.file)]) { console.log(` ${relative(target, path)}`) } + if (needsVersionSource) { + console.log(`would set docouture.versionSource to 'descriptor' in ${relative(target, siteRootPackageJson)}`) + } if (hasScript || pkgRemoval?.changed) { console.log('would remove (check-links is no longer part of docouture):') if (hasScript) console.log(` ${relative(target, checkLinksScript)}`) @@ -289,6 +303,11 @@ export async function runUpgrade(argv: string[]): Promise<number> { updatedPackageJson = await setBranching(packageJsonFile, 'git-flow', detected.prerelease) } + if (needsVersionSource) { + // After the check-links cleanup above has rewritten docs/package.json. + await setVersionSource(siteRootPackageJson, 'descriptor') + } + for (const plan of strictPlans) { await writeFile(plan.file, plan.content, 'utf8') console.log( @@ -312,6 +331,17 @@ export async function runUpgrade(argv: string[]): Promise<number> { ) } console.log(`updated ${relative(target, agentsMdFile)}`) + if (needsVersionSource) { + console.log(`updated ${relative(target, siteRootPackageJson)} (docouture.versionSource 'descriptor')`) + console.log("note: the docs version still comes from docs/.release-version. To change that, run 'docouture") + console.log(" version-source <descriptor|github-release|tag-bump>' — see 'docouture version-source --help'.") + } + + // The workflows just written run the project's own installed CLI, not this + // one: say so when they differ, since a stale CLI lacks newer commands. + const projectCli = await readProjectCli(siteRoot, target) + const skew = cliSkewMessage(cliVersion, projectCli) + if (skew !== null) console.warn(`warning: ${skew}`) return 0 } diff --git a/code/packages/cli/src/commands/version-source.spec.ts b/code/packages/cli/src/commands/version-source.spec.ts new file mode 100644 index 00000000..168aba52 --- /dev/null +++ b/code/packages/cli/src/commands/version-source.spec.ts @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { execFileSync } from 'node:child_process' +import { mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { exists } from '../lib/copy-template.js' +import { runVersionSource } from './version-source.js' + +let dir: string +let errorSpy: ReturnType<typeof vi.spyOn> +let warnSpy: ReturnType<typeof vi.spyOn> +let logSpy: ReturnType<typeof vi.spyOn> + +function git(...args: string[]): void { + execFileSync('git', args, { cwd: dir, stdio: 'ignore' }) // NOSONAR +} + +async function scaffold(options: { mode?: 'versioned' | 'standalone'; docouture?: Record<string, unknown>; descriptor?: string } = {}) { + const { mode = 'versioned', docouture = { branching: 'trunk-based' }, descriptor } = options + await mkdir(join(dir, 'docs'), { recursive: true }) + await writeFile( + join(dir, 'docs', 'antora-playbook.yml'), + `content:\n sources:\n - tags: ['${mode === 'versioned' ? 'docs/v*' : 'docs/stable'}']\n` + ) + await writeFile(join(dir, 'docs', 'package.json'), `${JSON.stringify({ name: 'docs', docouture }, null, 2)}\n`) + if (descriptor !== undefined) await writeFile(join(dir, 'docs', '.release-version'), `${descriptor}\n`) +} + +async function pkg(): Promise<{ docouture: Record<string, unknown> }> { + return JSON.parse(await readFile(join(dir, 'docs', 'package.json'), 'utf8')) +} + +const output = (spy: ReturnType<typeof vi.spyOn>): string => spy.mock.calls.flat().join('\n') + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'docouture-cli-version-source-')) + git('init', '-q') + git('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '--allow-empty', '-qm', 'x') + errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) +}) + +afterEach(() => { + errorSpy.mockRestore() + warnSpy.mockRestore() + logSpy.mockRestore() +}) + +describe('runVersionSource', () => { + it('prints the current source when given no argument', async () => { + await scaffold({ docouture: { branching: 'trunk-based', versionSource: 'tag-bump' } }) + expect(await runVersionSource(['--dir', dir])).toBe(0) + expect(output(logSpy)).toContain('version source: tag-bump') + }) + + it('refuses a standalone site', async () => { + await scaffold({ mode: 'standalone' }) + expect(await runVersionSource(['tag-bump', '--dir', dir])).toBe(1) + expect(output(errorSpy)).toContain('standalone') + expect((await pkg()).docouture).not.toHaveProperty('versionSource') + }) + + it('rejects an unknown source and a bad --version', async () => { + await scaffold() + expect(await runVersionSource(['tag_bump', '--dir', dir])).toBe(1) + expect(await runVersionSource(['descriptor', '--version', 'v1', '--dir', dir])).toBe(1) + }) + + it('switches to tag-bump: removes the file, warns about the pending version, prints the labels', async () => { + await scaffold({ descriptor: '1.3.0' }) + expect(await runVersionSource(['tag-bump', '--dir', dir])).toBe(0) + expect((await pkg()).docouture.versionSource).toBe('tag-bump') + expect(await exists(join(dir, 'docs', '.release-version'))).toBe(false) + expect(output(warnSpy)).toContain("pending version '1.3.0'") + expect(output(logSpy)).toContain('gh label create docs/release-minor') + expect(output(logSpy)).toContain('gh label create docs/release-major') + }) + + it('does not warn when the removed file is empty', async () => { + await scaffold({ descriptor: '' }) + await runVersionSource(['github-release', '--dir', dir]) + expect(output(warnSpy)).toBe('') + }) + + it('switches back to descriptor, seeding the next patch of the latest tag', async () => { + await scaffold({ docouture: { branching: 'trunk-based', versionSource: 'tag-bump' } }) + git('tag', 'docs/v1.2.4') + git('tag', 'docs/v1.2.0') + expect(await runVersionSource(['descriptor', '--dir', dir])).toBe(0) + expect((await readFile(join(dir, 'docs', '.release-version'), 'utf8')).trim()).toBe('1.2.5') + }) + + it('seeds 0.1.0 with no tags and honours --version', async () => { + await scaffold({ docouture: { branching: 'trunk-based', versionSource: 'tag-bump' } }) + await runVersionSource(['descriptor', '--dir', dir]) + expect((await readFile(join(dir, 'docs', '.release-version'), 'utf8')).trim()).toBe('0.1.0') + await runVersionSource(['descriptor', '--version', '4.0.0', '--dir', dir]) + expect((await readFile(join(dir, 'docs', '.release-version'), 'utf8')).trim()).toBe('4.0.0') + }) + + it('sets the github-release prefix and only for that source', async () => { + await scaffold() + expect(await runVersionSource(['github-release', '--prefix', 'docs-site@', '--dir', dir])).toBe(0) + expect((await pkg()).docouture).toMatchObject({ versionSource: 'github-release', versionSourcePrefix: 'docs-site@' }) + expect(await runVersionSource(['tag-bump', '--prefix', 'x', '--dir', dir])).toBe(1) + }) + + it('--dry-run writes nothing and lists the plan', async () => { + await scaffold({ descriptor: '1.3.0' }) + expect(await runVersionSource(['tag-bump', '--dry-run', '--dir', dir])).toBe(0) + expect(output(logSpy)).toContain('would:') + expect(output(logSpy)).toContain('remove docs/.release-version') + expect((await pkg()).docouture).not.toHaveProperty('versionSource') + expect(await exists(join(dir, 'docs', '.release-version'))).toBe(true) + }) + + it('is idempotent', async () => { + await scaffold({ docouture: { branching: 'trunk-based', versionSource: 'descriptor' }, descriptor: '1.0.0' }) + expect(await runVersionSource(['descriptor', '--dir', dir])).toBe(0) + expect(output(logSpy)).toContain('nothing to do') + await runVersionSource(['tag-bump', '--dir', dir]) + logSpy.mockClear() + expect(await runVersionSource(['tag-bump', '--dir', dir])).toBe(0) + expect(output(logSpy)).toContain('nothing to do') + }) +}) diff --git a/code/packages/cli/src/commands/version-source.ts b/code/packages/cli/src/commands/version-source.ts new file mode 100644 index 00000000..53a983bb --- /dev/null +++ b/code/packages/cli/src/commands/version-source.ts @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { execFileSync } from 'node:child_process' +import { readFile, rm, writeFile } from 'node:fs/promises' +import { join, relative, resolve } from 'node:path' + +import { parseArgs } from '../lib/args.js' +import { exists } from '../lib/copy-template.js' +import { listDocsTags } from '../lib/docs-tags.js' +import { readVersionSourceDeclaration, setVersionSource } from '../lib/package-version-source.js' +import { printTagBumpLabelCommands } from '../lib/release-labels.js' +import { parseVersionSource, SEMVER_RE, TAG_PREFIX, VERSION_SOURCES } from '../lib/release-resolve.js' +import { findRepoRoot } from '../lib/repo-root.js' +import { bumpVersion, highestSemver } from '../lib/semver.js' +import { detectSiteMode } from '../lib/site-mode.js' + +const USAGE = + 'usage: docouture version-source [descriptor|github-release|tag-bump] [--prefix <p>] [--version <X.Y.Z>] [--dir <path>] [--dry-run]' + +// Seed used when a `descriptor` site has no docs/v* tag to bump from — the +// same value `docouture new` lays down for a fresh versioned site. +const FIRST_VERSION = '0.1.0' + +function isInsideGitWorkTree(dir: string): boolean { + try { + // Resolves 'git' off PATH, same as any shell script would — same + // reasoning as branch-model.ts's own copy of this function. + execFileSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: dir, stdio: 'ignore' }) // NOSONAR + return true + } catch { + return false + } +} + +async function seedVersion(repoRoot: string, explicit: string | undefined): Promise<string> { + if (explicit !== undefined) return explicit + const tags = await listDocsTags(repoRoot) + const latest = highestSemver( + tags.filter((tag) => tag.startsWith(TAG_PREFIX)).map((tag) => tag.slice(TAG_PREFIX.length)) + ) + return latest === null ? FIRST_VERSION : bumpVersion(latest, 'patch') +} + +export async function runVersionSource(argv: string[]): Promise<number> { + const { positional, flags } = parseArgs(argv) + + const dryRun = flags['dry-run'] === true + const explicitVersion = typeof flags.version === 'string' ? flags.version : undefined + const prefix = typeof flags.prefix === 'string' ? flags.prefix : undefined + const startDir = typeof flags.dir === 'string' ? resolve(flags.dir) : resolve(process.cwd()) + + const targetArg = positional[0] + const target = targetArg === undefined ? null : parseVersionSource(targetArg) + if (targetArg !== undefined && target === null) { + console.error(USAGE) + console.error(`invalid source: '${targetArg}' — expected one of: ${VERSION_SOURCES.join(', ')}`) + return 1 + } + + if (explicitVersion !== undefined && !SEMVER_RE.test(explicitVersion)) { + console.error(`--version '${explicitVersion}' is not a valid SemVer version like 1.2.0`) + return 1 + } + + if (!isInsideGitWorkTree(startDir)) { + console.error(`'${startDir}' is not inside a git repository`) + console.error( + 'docouture version-source re-configures an already-scaffolded repository — run it from your repo root, or pass --dir <path> to one' + ) + return 1 + } + + const repoRoot = await findRepoRoot(startDir) + const siteRoot = join(repoRoot, 'docs') + const packageJsonFile = join(siteRoot, 'package.json') + if (!(await exists(packageJsonFile))) { + console.error(`no site found at '${siteRoot}'`) + console.error('pass --dir <path> to a component root (the parent of docs/), or run docouture new first') + return 1 + } + + const mode = await detectSiteMode(siteRoot) + if (mode === 'standalone') { + console.error('this is a standalone (Stable + Prerelease) site — it has no docs version source') + console.error("standalone releases always target the 'docs/stable' tag; only versioned sites choose a source") + return 1 + } + if (mode === null) { + console.error("could not tell whether this site is versioned or standalone from docs/antora-playbook.yml's tags") + console.error('is this a docouture-scaffolded site? (run docouture new first, or check --dir)') + return 1 + } + + const declaration = await readVersionSourceDeclaration(packageJsonFile) + if (target === null) { + console.log(`version source: ${declaration.source ?? `${declaration.raw} (invalid)`}`) + if (declaration.prefix) console.log(`prefix: ${declaration.prefix}`) + return 0 + } + + if (prefix !== undefined && target !== 'github-release') { + console.error('--prefix only applies to the github-release source') + return 1 + } + + const descriptorFile = join(siteRoot, '.release-version') + const descriptorExists = await exists(descriptorFile) + const rel = (path: string): string => relative(repoRoot, path) + + const plan: string[] = [] + const warnings: string[] = [] + let seed: string | null = null + + if (target === 'descriptor') { + if (explicitVersion !== undefined || !descriptorExists) { + seed = await seedVersion(repoRoot, explicitVersion) + plan.push(`${descriptorExists ? 'overwrite' : 'create'} ${rel(descriptorFile)} with ${seed}`) + } + } else if (descriptorExists) { + const pending = (await readFile(descriptorFile, 'utf8')).trim() + if (pending !== '') { + warnings.push(`${rel(descriptorFile)} held the pending version '${pending}', which is discarded`) + } + plan.push(`remove ${rel(descriptorFile)}`) + } + + const prefixChange = target === 'github-release' && prefix !== undefined && prefix !== declaration.prefix + if (declaration.source !== target || declaration.raw === null || prefixChange) { + plan.unshift(`set docouture.versionSource to '${target}' in ${rel(packageJsonFile)}`) + } + + if (plan.length === 0) { + console.log(`already '${target}' — nothing to do`) + return 0 + } + + if (dryRun) { + console.log('would:') + for (const line of plan) console.log(` ${line}`) + for (const warning of warnings) console.log(`warning: ${warning}`) + return 0 + } + + await setVersionSource(packageJsonFile, target, prefix) + if (seed !== null) await writeFile(descriptorFile, `${seed}\n`, 'utf8') + else if (target !== 'descriptor' && descriptorExists) await rm(descriptorFile) + + console.log(`version source is now '${target}'`) + for (const line of plan.slice(1)) console.log(` ${line}`) + for (const warning of warnings) console.warn(`warning: ${warning}`) + + console.log('') + console.log('The release workflows read the source at run time — no workflow files need re-rendering,') + console.log('but they run the project\u2019s installed CLI: make sure it is a version with `release resolve`.') + if (target === 'tag-bump') { + console.log('') + printTagBumpLabelCommands() + } + if (target === 'github-release') { + console.log('') + console.log("Docs are now released when your code release publishes a GitHub Release — a merged 'docs/release'") + console.log('pull request fails. Use --prefix <p> if your release tags carry a prefix (e.g. docs-site@).') + } + return 0 +} diff --git a/code/packages/cli/src/lib/docs-tags.ts b/code/packages/cli/src/lib/docs-tags.ts new file mode 100644 index 00000000..ad4b4b8f --- /dev/null +++ b/code/packages/cli/src/lib/docs-tags.ts @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { execFile } from 'node:child_process' + +import { TAG_PREFIX } from './release-resolve.js' + +// Existing docs/v* tag names, from the local clone — callers fetch tags first. +export function listDocsTags(repoRoot: string): Promise<string[]> { + return new Promise((resolvePromise) => { + // Resolves 'git' off PATH, same as the other commands that shell out to it. + execFile('git', ['tag', '-l', `${TAG_PREFIX}*`], { cwd: repoRoot }, (err, stdout) => { + // NOSONAR + resolvePromise(err ? [] : stdout.split('\n').filter((line) => line.trim() !== '')) + }) + }) +} diff --git a/code/packages/cli/src/lib/doctor-checks.spec.ts b/code/packages/cli/src/lib/doctor-checks.spec.ts index d10c9972..fa77d076 100644 --- a/code/packages/cli/src/lib/doctor-checks.spec.ts +++ b/code/packages/cli/src/lib/doctor-checks.spec.ts @@ -19,7 +19,9 @@ import { checkNamesAgree, checkNodeVersion, checkPackageManagerAvailable, + checkProjectCli, checkReleaseLabelExists, + checkVersionSource, } from './doctor-checks.js' describe('checkNodeVersion', () => { @@ -292,3 +294,62 @@ describe('checkBranchingAgrees', () => { expect(result.detail).toContain('docouture branch-model') }) }) + +describe('checkVersionSource', () => { + it('skips a standalone site', () => { + expect(checkVersionSource({ mode: 'standalone', declared: null, descriptorExists: false }).ok).toBe(true) + }) + + it('skips when the mode cannot be told', () => { + expect(checkVersionSource({ mode: null, declared: null, descriptorExists: false }).ok).toBe(true) + }) + + it('shows the active source when everything agrees', () => { + const result = checkVersionSource({ mode: 'versioned', declared: 'tag-bump', descriptorExists: false }) + expect(result).toMatchObject({ ok: true, message: "version source 'tag-bump'" }) + }) + + it('treats an absent declaration as descriptor', () => { + const result = checkVersionSource({ mode: 'versioned', declared: null, descriptorExists: true }) + expect(result.ok).toBe(true) + expect(result.message).toContain("'descriptor'") + }) + + it('warns when descriptor has no file', () => { + const result = checkVersionSource({ mode: 'versioned', declared: 'descriptor', descriptorExists: false }) + expect(result.ok).toBe(false) + expect(result.detail).toContain('docouture version-source descriptor') + }) + + it.each(['github-release', 'tag-bump'])('warns when %s still has a .release-version', (declared) => { + const result = checkVersionSource({ mode: 'versioned', declared, descriptorExists: true }) + expect(result.ok).toBe(false) + expect(result.detail).toContain(`docouture version-source ${declared}`) + }) + + it('warns on an unknown value', () => { + const result = checkVersionSource({ mode: 'versioned', declared: 'tag_bump', descriptorExists: false }) + expect(result.ok).toBe(false) + expect(result.detail).toContain('descriptor, github-release, tag-bump') + }) +}) + +describe('checkProjectCli', () => { + it('is clean when the project CLI matches and supports release resolve', () => { + const results = checkProjectCli('1.4.0', { version: '1.4.0', hasReleaseResolve: true, from: 'installed' }) + expect(results).toHaveLength(1) + expect(results[0]?.ok).toBe(true) + }) + + it('warns on skew and on a CLI without release resolve', () => { + const results = checkProjectCli('1.4.0', { version: '1.3.2', hasReleaseResolve: false, from: 'installed' }) + expect(results.map((r) => r.ok)).toEqual([false, false]) + expect(results[1]?.message).toContain("does not support 'release resolve'") + }) + + it('skips when the project CLI cannot be found', () => { + const results = checkProjectCli('1.4.0', { version: null, hasReleaseResolve: null, from: null }) + expect(results).toHaveLength(1) + expect(results[0]?.ok).toBe(true) + }) +}) diff --git a/code/packages/cli/src/lib/doctor-checks.ts b/code/packages/cli/src/lib/doctor-checks.ts index 932dc8af..0b6ec04e 100644 --- a/code/packages/cli/src/lib/doctor-checks.ts +++ b/code/packages/cli/src/lib/doctor-checks.ts @@ -9,6 +9,8 @@ import { existsSync } from 'node:fs' import { join } from 'node:path' import type { Branching } from './branch-detect.js' +import { cliSkewMessage, type ProjectCli } from './project-cli.js' +import { parseVersionSource, VERSION_SOURCES } from './release-resolve.js' // Each check here is a plain function returning a result rather than // printing directly — `commands/doctor.ts` owns all output formatting, so @@ -432,3 +434,92 @@ export function checkBranchingAgrees(input: BranchingInput): CheckResult { "run 'docouture branch-model <trunk-based|git-flow>' to re-sync everything, or fix docs/package.json's docouture.branching by hand if it's simply stale", } } + +export interface VersionSourceInput { + /** From antora-playbook.yml's `tags:` line; null when it could not be told. */ + mode: 'versioned' | 'standalone' | null + /** `docs/package.json` -> `docouture.versionSource`, or null if absent. */ + declared: string | null + /** Whether `docs/.release-version` exists. */ + descriptorExists: boolean +} + +/** + * Which resolver this site uses, and whether the files on disk agree with + * it. Advisory, same as the other release checks: a standalone site (which + * has no version source) or an unreadable mode is `ok: true`. + */ +export function checkVersionSource(input: VersionSourceInput): CheckResult { + const label = 'version source' + if (input.mode === 'standalone') { + return { ok: true, label, message: 'standalone site — releases always target docs/stable, no version source' } + } + if (input.mode === null) { + return { ok: true, label, message: 'could not tell the versioning mode from antora-playbook.yml — skipping' } + } + + const source = input.declared === null ? 'descriptor' : parseVersionSource(input.declared) + if (source === null) { + return { + ok: false, + label, + message: `docouture.versionSource '${input.declared}' is not a known source`, + detail: `expected one of: ${VERSION_SOURCES.join(', ')} — run 'docouture version-source <source>' to fix it`, + } + } + + const declaredNote = input.declared === null ? ' (default; not declared in docs/package.json)' : '' + if (source === 'descriptor' && !input.descriptorExists) { + return { + ok: false, + label, + message: `version source 'descriptor'${declaredNote} but docs/.release-version does not exist`, + detail: "run 'docouture version-source descriptor' to create it, or switch to another source", + } + } + if (source !== 'descriptor' && input.descriptorExists) { + return { + ok: false, + label, + message: `version source '${source}' but docs/.release-version still exists`, + detail: `the file is ignored under '${source}' — run 'docouture version-source ${source}' to remove it`, + } + } + return { ok: true, label, message: `version source '${source}'${declaredNote}` } +} + +/** + * The generated workflows run the project's own installed CLI. Warns when it + * differs from the running one, and when it predates `release resolve`. + * Nothing to report when the project's CLI cannot be located. + */ +export function checkProjectCli(running: string, project: ProjectCli): CheckResult[] { + const results: CheckResult[] = [] + const skew = cliSkewMessage(running, project) + results.push( + skew === null + ? { + ok: true, + label: 'CLI version', + message: + project.version === null + ? 'project CLI not found — skipping' + : `project CLI ${project.version} matches the running CLI`, + } + : { + ok: false, + label: 'CLI version', + message: skew, + detail: "update @inditextech/docouture-cli in docs/package.json, install, then run 'docouture upgrade'", + } + ) + if (project.hasReleaseResolve === false) { + results.push({ + ok: false, + label: 'release resolve', + message: `the project's installed CLI ${project.version} does not support 'release resolve'`, + detail: 'the docs release workflows call it — update @inditextech/docouture-cli and install before running them', + }) + } + return results +} diff --git a/code/packages/cli/src/lib/package-version-source.spec.ts b/code/packages/cli/src/lib/package-version-source.spec.ts new file mode 100644 index 00000000..852892e8 --- /dev/null +++ b/code/packages/cli/src/lib/package-version-source.spec.ts @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { mkdtemp, readFile, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { beforeEach, describe, expect, it } from 'vitest' + +import { readVersionSourceDeclaration, setVersionSource } from './package-version-source.js' + +let file: string + +async function write(docouture: Record<string, unknown> | undefined): Promise<void> { + const pkg: Record<string, unknown> = { name: 'docs', version: '1.0.0' } + if (docouture) pkg.docouture = docouture + pkg.scripts = { build: 'x' } + await writeFile(file, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8') +} + +async function read(): Promise<{ docouture?: Record<string, unknown>; scripts?: unknown }> { + return JSON.parse(await readFile(file, 'utf8')) +} + +beforeEach(async () => { + file = join(await mkdtemp(join(tmpdir(), 'docouture-version-source-')), 'package.json') +}) + +describe('readVersionSourceDeclaration', () => { + it('treats an absent value as descriptor', async () => { + await write({ branching: 'trunk-based' }) + expect(await readVersionSourceDeclaration(file)).toEqual({ raw: null, source: 'descriptor', prefix: null }) + }) + + it('reads a valid source and prefix', async () => { + await write({ versionSource: 'github-release', versionSourcePrefix: 'v' }) + expect(await readVersionSourceDeclaration(file)).toEqual({ + raw: 'github-release', + source: 'github-release', + prefix: 'v', + }) + }) + + it('flags an unknown value', async () => { + await write({ versionSource: 'tag_bump' }) + expect(await readVersionSourceDeclaration(file)).toEqual({ raw: 'tag_bump', source: null, prefix: null }) + }) + + it('handles a missing docouture block', async () => { + await write(undefined) + expect((await readVersionSourceDeclaration(file)).source).toBe('descriptor') + }) +}) + +describe('setVersionSource', () => { + it('places the key after branching and prereleaseBranch, keeping other keys in order', async () => { + await write({ branching: 'git-flow', prereleaseBranch: 'develop', other: 1 }) + expect(await setVersionSource(file, 'tag-bump')).toBe(true) + const pkg = await read() + expect(Object.keys(pkg.docouture!)).toEqual(['branching', 'prereleaseBranch', 'versionSource', 'other']) + expect(pkg.docouture!.versionSource).toBe('tag-bump') + expect(Object.keys(pkg)).toEqual(['name', 'version', 'docouture', 'scripts']) + }) + + it('adds the key to an empty block and creates the block when absent', async () => { + await write(undefined) + await setVersionSource(file, 'descriptor') + expect((await read()).docouture).toEqual({ versionSource: 'descriptor' }) + }) + + it('is idempotent', async () => { + await write({ branching: 'trunk-based' }) + expect(await setVersionSource(file, 'descriptor')).toBe(true) + expect(await setVersionSource(file, 'descriptor')).toBe(false) + }) + + it('writes the prefix only for github-release', async () => { + await write({ branching: 'trunk-based' }) + await setVersionSource(file, 'github-release', 'docs-site@') + expect((await read()).docouture).toMatchObject({ + versionSource: 'github-release', + versionSourcePrefix: 'docs-site@', + }) + await setVersionSource(file, 'tag-bump') + expect((await read()).docouture).not.toHaveProperty('versionSourcePrefix') + }) + + it('keeps an existing prefix when switching to github-release again', async () => { + await write({ versionSource: 'github-release', versionSourcePrefix: 'v' }) + expect(await setVersionSource(file, 'github-release')).toBe(false) + }) +}) diff --git a/code/packages/cli/src/lib/package-version-source.ts b/code/packages/cli/src/lib/package-version-source.ts new file mode 100644 index 00000000..2e2852a6 --- /dev/null +++ b/code/packages/cli/src/lib/package-version-source.ts @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +// Shared reader/writer for the `docouture.versionSource` (and optional +// `docouture.versionSourcePrefix`) declaration in docs/package.json — where +// the docs release version comes from. Same shape as package-branching.ts: +// every other key keeps its value and order, and the keys are placed directly +// after `branching`/`prereleaseBranch`. + +import { readFile, writeFile } from 'node:fs/promises' + +import { parseVersionSource, type VersionSource } from './release-resolve.js' + +type Docouture = Record<string, unknown> + +export interface VersionSourceDeclaration { + // The raw declared value, or null when absent. Not validated here so + // callers can report an unknown value with its text. + raw: string | null + // The declared source when valid; 'descriptor' when absent; null when the + // declared value is not one of the three. + source: VersionSource | null + prefix: string | null +} + +export async function readVersionSourceDeclaration(packageJsonFile: string): Promise<VersionSourceDeclaration> { + const pkg = JSON.parse(await readFile(packageJsonFile, 'utf8')) as { docouture?: Docouture } + const { versionSource, versionSourcePrefix } = pkg.docouture ?? {} + const raw = typeof versionSource === 'string' ? versionSource : null + return { + raw, + source: raw === null ? 'descriptor' : parseVersionSource(raw), + prefix: typeof versionSourcePrefix === 'string' ? versionSourcePrefix : null, + } +} + +/** + * Read-modify-write of the `docouture` block. `prefix` is only kept for + * `github-release`. Returns true when the file content changed. + */ +export async function setVersionSource( + packageJsonFile: string, + source: VersionSource, + prefix?: string +): Promise<boolean> { + const original = await readFile(packageJsonFile, 'utf8') + const pkg = JSON.parse(original) as { docouture?: Docouture } + const entries = Object.entries(pkg.docouture ?? {}).filter( + ([key]) => key !== 'versionSource' && key !== 'versionSourcePrefix' + ) + + const additions: [string, unknown][] = [['versionSource', source]] + const keepPrefix = source === 'github-release' ? (prefix ?? readExistingPrefix(pkg)) : undefined + if (keepPrefix) additions.push(['versionSourcePrefix', keepPrefix]) + + let insertAt = 0 + entries.forEach(([key], index) => { + if (key === 'branching' || key === 'prereleaseBranch') insertAt = index + 1 + }) + entries.splice(insertAt, 0, ...additions) + + pkg.docouture = Object.fromEntries(entries) + const out = `${JSON.stringify(pkg, null, 2)}\n` + if (out === original) return false + await writeFile(packageJsonFile, out, 'utf8') + return true +} + +function readExistingPrefix(pkg: { docouture?: Docouture }): string | undefined { + const value = pkg.docouture?.versionSourcePrefix + return typeof value === 'string' && value !== '' ? value : undefined +} diff --git a/code/packages/cli/src/lib/project-cli.spec.ts b/code/packages/cli/src/lib/project-cli.spec.ts new file mode 100644 index 00000000..cff057cd --- /dev/null +++ b/code/packages/cli/src/lib/project-cli.spec.ts @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { mkdir, mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { beforeEach, describe, expect, it } from 'vitest' + +import { cliSkewMessage, readProjectCli } from './project-cli.js' + +let root: string +let site: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'docouture-project-cli-')) + site = join(root, 'docs') + await mkdir(site, { recursive: true }) +}) + +async function install(version: string, withRelease: boolean): Promise<void> { + const dir = join(site, 'node_modules', '@inditextech', 'docouture-cli') + await mkdir(join(dir, 'build', 'commands'), { recursive: true }) + await writeFile(join(dir, 'package.json'), JSON.stringify({ version })) + if (withRelease) await writeFile(join(dir, 'build', 'commands', 'release.js'), '') +} + +describe('readProjectCli', () => { + it('reads the installed version and release resolve support', async () => { + await install('1.4.0', true) + expect(await readProjectCli(site, root)).toEqual({ version: '1.4.0', hasReleaseResolve: true, from: 'installed' }) + }) + + it('reports an installed CLI without release resolve', async () => { + await install('1.3.2', false) + expect(await readProjectCli(site, root)).toMatchObject({ version: '1.3.2', hasReleaseResolve: false }) + }) + + it('falls back to an exact pin in package.json', async () => { + await writeFile(join(site, 'package.json'), JSON.stringify({ devDependencies: { '@inditextech/docouture-cli': '1.3.2' } })) + expect(await readProjectCli(site, root)).toEqual({ version: '1.3.2', hasReleaseResolve: null, from: 'declared' }) + }) + + it('ignores a range it cannot compare', async () => { + await writeFile(join(site, 'package.json'), JSON.stringify({ devDependencies: { '@inditextech/docouture-cli': '^1.3.2' } })) + expect((await readProjectCli(site, root)).version).toBeNull() + }) + + it('returns nothing when the CLI is not a dependency', async () => { + expect(await readProjectCli(site, root)).toEqual({ version: null, hasReleaseResolve: null, from: null }) + }) +}) + +describe('cliSkewMessage', () => { + it('is null when versions match or nothing is known', () => { + expect(cliSkewMessage('1.4.0', { version: '1.4.0', hasReleaseResolve: true, from: 'installed' })).toBeNull() + expect(cliSkewMessage('1.4.0', { version: null, hasReleaseResolve: null, from: null })).toBeNull() + }) + + it('names both versions on a skew', () => { + const message = cliSkewMessage('1.4.0', { version: '1.3.2', hasReleaseResolve: false, from: 'installed' }) + expect(message).toContain('1.4.0') + expect(message).toContain('1.3.2') + }) +}) diff --git a/code/packages/cli/src/lib/project-cli.ts b/code/packages/cli/src/lib/project-cli.ts new file mode 100644 index 00000000..78976058 --- /dev/null +++ b/code/packages/cli/src/lib/project-cli.ts @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +// The generated workflows run the CLI the project itself installed +// (`npx docouture ...` under docs/), not whichever one is running now. This +// reads back what that is, so `upgrade` and `doctor` can warn about a skew. + +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' + +import { exists } from './copy-template.js' + +const CLI_PACKAGE = '@inditextech/docouture-cli' + +export interface ProjectCli { + // Version of the CLI the project resolves, or null when it cannot be told. + version: string | null + // Whether the project's installed CLI ships `release resolve`; null when + // the CLI is not installed (so there is nothing to probe). + hasReleaseResolve: boolean | null + // 'installed' (read from node_modules) or 'declared' (from package.json). + from: 'installed' | 'declared' | null +} + +async function readJson<T>(file: string): Promise<T | null> { + try { + return JSON.parse(await readFile(file, 'utf8')) as T + } catch { + return null + } +} + +export async function readProjectCli(siteRoot: string, repoRoot: string): Promise<ProjectCli> { + for (const base of [siteRoot, repoRoot]) { + const dir = join(base, 'node_modules', ...CLI_PACKAGE.split('/')) + const pkg = await readJson<{ version?: string }>(join(dir, 'package.json')) + if (pkg?.version) { + return { + version: pkg.version, + hasReleaseResolve: await exists(join(dir, 'build', 'commands', 'release.js')), + from: 'installed', + } + } + } + + const sitePkg = await readJson<{ devDependencies?: Record<string, string>; dependencies?: Record<string, string> }>( + join(siteRoot, 'package.json') + ) + const declared = sitePkg?.devDependencies?.[CLI_PACKAGE] ?? sitePkg?.dependencies?.[CLI_PACKAGE] + if (declared && /^\d/.test(declared)) return { version: declared, hasReleaseResolve: null, from: 'declared' } + return { version: null, hasReleaseResolve: null, from: null } +} + +// The one-line warning shared by upgrade and doctor; null when there is no +// skew (or nothing to compare). +export function cliSkewMessage(running: string, project: ProjectCli): string | null { + if (project.version === null || project.version === running) return null + return ( + `running CLI ${running} differs from the project's ${project.from === 'declared' ? 'declared' : 'installed'} ` + + `@inditextech/docouture-cli ${project.version} — the workflows use the project's, so update it in docs/package.json and install first` + ) +} diff --git a/code/packages/cli/src/lib/release-labels.ts b/code/packages/cli/src/lib/release-labels.ts new file mode 100644 index 00000000..9609508c --- /dev/null +++ b/code/packages/cli/src/lib/release-labels.ts @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +// The CLI never calls the GitHub API: like `docs/release` today, the extra +// labels a `tag-bump` site uses are only printed as commands to run. +export const TAG_BUMP_LABEL_COMMANDS = [ + "gh label create docs/release-minor --description 'Release the docs with a minor version bump'", + "gh label create docs/release-major --description 'Release the docs with a major version bump'", +] as const + +export function printTagBumpLabelCommands(log: (line: string) => void = console.log): void { + log("A 'tag-bump' site bumps patch on 'docs/release', minor on 'docs/release-minor' and major on") + log("'docs/release-major'. Create the two extra labels once:") + for (const command of TAG_BUMP_LABEL_COMMANDS) log(` ${command}`) +} diff --git a/code/packages/cli/src/lib/release-resolve.spec.ts b/code/packages/cli/src/lib/release-resolve.spec.ts new file mode 100644 index 00000000..42def5df --- /dev/null +++ b/code/packages/cli/src/lib/release-resolve.spec.ts @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { describe, expect, it } from 'vitest' + +import { parseVersionSource, resolveDescriptor, resolveRelease, SEMVER_RE } from './release-resolve.js' + +describe('resolveDescriptor', () => { + it('reads the descriptor in versioned mode', () => { + const r = resolveDescriptor({ mode: 'versioned', descriptor: '1.2.0\n' }) + expect(r).toEqual({ version: '1.2.0', tag: 'docs/v1.2.0', source: 'docs/.release-version' }) + }) + + it('prefers an explicit version over the descriptor', () => { + const r = resolveDescriptor({ mode: 'versioned', explicit: '2.0.0', descriptor: '1.2.0' }) + expect(r.version).toBe('2.0.0') + expect(r.source).toBe('version input') + expect(r.error).toBeUndefined() + }) + + it('targets stable in standalone mode regardless of inputs', () => { + const r = resolveDescriptor({ mode: 'standalone', explicit: '9.9.9', descriptor: 'junk' }) + expect(r).toEqual({ version: 'stable', tag: 'docs/stable', source: 'standalone' }) + }) + + it('accepts prerelease and build metadata', () => { + expect(resolveDescriptor({ mode: 'versioned', descriptor: '1.2.0-rc.1' }).tag).toBe('docs/v1.2.0-rc.1') + expect(resolveDescriptor({ mode: 'versioned', descriptor: '1.2.0+build.5' }).error).toBeUndefined() + }) + + it.each(['v1.2.0', '1.2', '01.2.3', '1.2.3-', 'abc'])('rejects %s as invalid', (value) => { + const r = resolveDescriptor({ mode: 'versioned', descriptor: value }) + expect(r.error?.kind).toBe('invalid') + expect(r.error?.value).toBe(value) + }) + + it('reports a missing file', () => { + const r = resolveDescriptor({ mode: 'versioned', descriptor: null }) + expect(r.error?.kind).toBe('missing') + expect(r.error?.message).toContain('missing') + }) + + it('reports an empty file as missing', () => { + expect(resolveDescriptor({ mode: 'versioned', descriptor: ' \n' }).error?.kind).toBe('missing') + }) + + it('rejects stable as a versioned version', () => { + expect(resolveDescriptor({ mode: 'versioned', explicit: 'stable', descriptor: null }).error?.kind).toBe('reserved') + }) +}) + +// The preview workflow has no Node/install steps, so it keeps its own bash +// copy of the SemVer grammar. Guard it against drifting from the CLI's. +describe('preview workflow SemVer parity', () => { + const template = join( + dirname(fileURLToPath(import.meta.url)), + '..', + '..', + 'templates', + 'workflows', + 'docouture-release-preview.yml' + ) + const source = /SEMVER_RE='([^']+)'/.exec(readFileSync(template, 'utf8'))?.[1] + + it('finds the regex in the template', () => { + expect(source).toBeDefined() + }) + + it.each([ + '1.2.0', + '0.0.0', + '1.2.0-rc.1', + '1.2.0-0', + '1.2.0+build.5', + '1.2.0-beta+exp.sha.5114f85', + 'v1.2.0', + '1.2', + '01.2.3', + '1.2.3-', + '1.2.3-01', + '', + 'stable', + ])('agrees on %j', (value) => { + const bashRe = new RegExp(source ?? '(?!)') + expect(bashRe.test(value)).toBe(SEMVER_RE.test(value)) + }) +}) + +describe('parseVersionSource', () => { + it('accepts the three sources and rejects others', () => { + expect(parseVersionSource('descriptor')).toBe('descriptor') + expect(parseVersionSource('github-release')).toBe('github-release') + expect(parseVersionSource('tag-bump')).toBe('tag-bump') + expect(parseVersionSource('tag_bump')).toBeNull() + expect(parseVersionSource(undefined)).toBeNull() + }) +}) + +describe('resolveRelease', () => { + it('defaults to descriptor and flags the descriptor steps', () => { + const r = resolveRelease({ mode: 'versioned', descriptor: '1.2.0' }) + expect(r).toMatchObject({ version: '1.2.0', tag: 'docs/v1.2.0', usesDescriptor: true }) + }) + + it('standalone never uses the descriptor, whatever the source', () => { + const r = resolveRelease({ mode: 'standalone', source: 'tag-bump', descriptor: null }) + expect(r).toMatchObject({ version: 'stable', tag: 'docs/stable', usesDescriptor: false }) + }) + + describe('github-release', () => { + const base = { mode: 'versioned', source: 'github-release', descriptor: '9.9.9' } as const + + it('uses a plain release tag, ignoring the descriptor', () => { + const r = resolveRelease({ ...base, event: 'release', releaseTag: '1.4.0' }) + expect(r).toMatchObject({ version: '1.4.0', tag: 'docs/v1.4.0', usesDescriptor: false }) + expect(r.error).toBeUndefined() + }) + + it('strips the configured prefix', () => { + const r = resolveRelease({ ...base, event: 'release', releaseTag: 'docs-site@1.4.0', prefix: 'docs-site@' }) + expect(r.version).toBe('1.4.0') + }) + + it('fails on a tag without the prefix', () => { + const r = resolveRelease({ ...base, event: 'release', releaseTag: 'other@1.4.0', prefix: 'docs-site@' }) + expect(r.error?.kind).toBe('prefix') + }) + + it('rejects a v-prefixed tag as invalid SemVer', () => { + const r = resolveRelease({ ...base, event: 'release', releaseTag: 'v1.4.0' }) + expect(r.error?.kind).toBe('invalid') + }) + + it('fails a docs/release pull request', () => { + const r = resolveRelease({ ...base, event: 'pull_request', labels: ['docs/release'] }) + expect(r.error?.kind).toBe('unsupported') + expect(r.error?.message).toContain('github-release') + }) + + it('lets an explicit version win, even for a labelled pull request', () => { + const r = resolveRelease({ ...base, event: 'workflow_dispatch', explicit: '2.0.0', releaseTag: '1.0.0' }) + expect(r.version).toBe('2.0.0') + expect(r.source).toBe('version input') + }) + + it('reports a missing tag', () => { + expect(resolveRelease({ ...base, event: 'release' }).error?.kind).toBe('missing') + }) + }) + + describe('tag-bump', () => { + const base = { mode: 'versioned', source: 'tag-bump', descriptor: null } as const + const tags = ['docs/v1.2.3', 'docs/v1.1.0', 'docs/stable', 'something'] + + it('bumps patch on docs/release', () => { + const r = resolveRelease({ ...base, tags, labels: ['docs/release'] }) + expect(r).toMatchObject({ version: '1.2.4', tag: 'docs/v1.2.4', usesDescriptor: false }) + }) + + it('bumps patch when there are no labels (release event)', () => { + expect(resolveRelease({ ...base, tags }).version).toBe('1.2.4') + }) + + it('bumps minor and major', () => { + expect(resolveRelease({ ...base, tags, labels: ['docs/release-minor'] }).version).toBe('1.3.0') + expect(resolveRelease({ ...base, tags, labels: ['docs/release-major'] }).version).toBe('2.0.0') + }) + + it('takes the highest bump when several labels are present', () => { + const labels = ['docs/release', 'docs/release-minor', 'docs/release-major'] + expect(resolveRelease({ ...base, tags, labels }).version).toBe('2.0.0') + }) + + it('orders prereleases and bumps from the highest', () => { + const r = resolveRelease({ ...base, tags: ['docs/v1.2.0-rc.1', 'docs/v1.1.9'] }) + expect(r.version).toBe('1.2.0') + }) + + it('lets an explicit version win without bumping', () => { + expect(resolveRelease({ ...base, tags, explicit: '3.0.0' }).version).toBe('3.0.0') + }) + + it('validates an explicit version', () => { + expect(resolveRelease({ ...base, tags, explicit: 'v3' }).error?.kind).toBe('invalid') + }) + + it('fails the first release without a version', () => { + const r = resolveRelease({ ...base, tags: ['docs/stable'] }) + expect(r.error?.kind).toBe('missing') + expect(r.error?.message).toContain('explicit version') + }) + + it('allows the first release with an explicit version', () => { + expect(resolveRelease({ ...base, tags: [], explicit: '1.0.0' }).version).toBe('1.0.0') + }) + }) +}) diff --git a/code/packages/cli/src/lib/release-resolve.ts b/code/packages/cli/src/lib/release-resolve.ts new file mode 100644 index 00000000..0614bd8a --- /dev/null +++ b/code/packages/cli/src/lib/release-resolve.ts @@ -0,0 +1,193 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { bumpVersion, highestSemver, SEMVER_RE } from './semver.js' + +export type ReleaseMode = 'versioned' | 'standalone' + +export type ReleaseErrorKind = 'missing' | 'invalid' | 'reserved' | 'prefix' | 'unsupported' + +export interface ReleaseResolution { + version: string + tag: string + source: string + // True only when the descriptor bump and the prerelease sync apply: versioned + // mode under the `descriptor` version source. + usesDescriptor?: boolean + error?: { kind: ReleaseErrorKind; value: string; message: string } +} + +export const DESCRIPTOR_SOURCE = 'docs/.release-version' +export const INPUT_SOURCE = 'version input' + +export { SEMVER_RE } + +export type VersionSource = 'descriptor' | 'github-release' | 'tag-bump' + +export const VERSION_SOURCES: readonly VersionSource[] = ['descriptor', 'github-release', 'tag-bump'] + +export function parseVersionSource(value: unknown): VersionSource | null { + return typeof value === 'string' && (VERSION_SOURCES as readonly string[]).includes(value) + ? (value as VersionSource) + : null +} + +export const RELEASE_LABEL = 'docs/release' +export const RELEASE_MINOR_LABEL = 'docs/release-minor' +export const RELEASE_MAJOR_LABEL = 'docs/release-major' +export const TAG_PREFIX = 'docs/v' + +export interface ResolveInput { + mode: ReleaseMode + // An explicit version (the workflow_dispatch input), if any. + explicit?: string + // Contents of docs/.release-version, or null when the file does not exist. + descriptor: string | null + // Active version source; absent means `descriptor`. + source?: VersionSource + // GitHub event name (workflow_dispatch, pull_request, release, ...). + event?: string + // Tag of the published GitHub Release (github-release). + releaseTag?: string + // `docouture.versionSourcePrefix`, stripped from releaseTag (github-release). + prefix?: string + // Labels on the merged pull request (tag-bump, and the github-release guard). + labels?: string[] + // Existing git tag names, e.g. 'docs/v1.2.3' (tag-bump). Others are ignored. + tags?: string[] +} + +type ReleaseError = NonNullable<ReleaseResolution['error']> + +// Shared validation of a resolved versioned-mode version: present, not the +// standalone name 'stable', and valid SemVer. +function checkVersion(version: string, source: string): ReleaseError | undefined { + if (version === '') { + return { kind: 'missing', value: '', message: 'versioned mode requires a real target version, e.g. 1.2.0' } + } + if (version === 'stable') { + return { + kind: 'reserved', + value: version, + message: + "'stable' is standalone's target name, not a valid versioned-mode version — use a real version, e.g. 1.2.0", + } + } + if (!SEMVER_RE.test(version)) { + return { + kind: 'invalid', + value: version, + message: `${source} must be a valid SemVer version like 1.2.0 — got '${version}'. Prerelease/build metadata (1.2.0-beta.1, 1.2.0+build) is fine; a leading 'v' or a two-part '1.2' is not`, + } + } + return undefined +} + +function finish(version: string, source: string, usesDescriptor: boolean, error?: ReleaseError): ReleaseResolution { + const result: ReleaseResolution = { version, tag: `${TAG_PREFIX}${version}`, source, usesDescriptor } + if (error) result.error = error + return result +} + +// The `descriptor` resolver: explicit input wins, else docs/.release-version. +// Standalone always targets 'stable'. Pure: the command does the file IO. +export function resolveDescriptor(input: ResolveInput): ReleaseResolution { + if (input.mode === 'standalone') { + return { version: 'stable', tag: 'docs/stable', source: 'standalone' } + } + + const explicit = input.explicit?.trim() ?? '' + const fromInput = explicit.length > 0 + const source = fromInput ? INPUT_SOURCE : DESCRIPTOR_SOURCE + const version = fromInput ? explicit : (input.descriptor?.replace(/\s+/g, '') ?? '') + + if (version === '' && !fromInput) { + const message = `versioned mode requires a target version, and ${DESCRIPTOR_SOURCE} is ${input.descriptor === null ? 'missing' : 'empty'} — add it with the version to release (e.g. 1.2.0)` + return { version, tag: `${TAG_PREFIX}${version}`, source, error: { kind: 'missing', value: '', message } } + } + + const error = checkVersion(version, source) + const result: ReleaseResolution = { version, tag: `${TAG_PREFIX}${version}`, source } + if (error) result.error = error + return result +} + +// `github-release`: the docs follow the code release, so the version is the +// published release tag minus an optional prefix. +function resolveGithubRelease(input: ResolveInput, explicit: string): ReleaseResolution { + const sourceLabel = explicit ? INPUT_SOURCE : 'release tag' + if (!explicit && input.event === 'pull_request' && (input.labels ?? []).includes(RELEASE_LABEL)) { + return finish('', 'github-release', false, { + kind: 'unsupported', + value: RELEASE_LABEL, + message: `this site's docs version source is 'github-release': docs are released when the code release publishes a GitHub Release, not when a '${RELEASE_LABEL}' pull request merges — remove the label or switch source with 'docouture version-source'`, + }) + } + + let version = explicit + if (!explicit) { + const tag = input.releaseTag?.trim() ?? '' + if (tag === '') { + return finish('', sourceLabel, false, { + kind: 'missing', + value: '', + message: + "version source 'github-release' reads the published GitHub Release tag, and none was given — run it from a release event or pass an explicit version", + }) + } + const prefix = input.prefix ?? '' + if (prefix !== '' && !tag.startsWith(prefix)) { + return finish(tag, sourceLabel, false, { + kind: 'prefix', + value: tag, + message: `release tag '${tag}' does not start with the configured docouture.versionSourcePrefix '${prefix}'`, + }) + } + version = tag.slice(prefix.length) + } + return finish(version, sourceLabel, false, checkVersion(version, sourceLabel)) +} + +function bumpFromLabels(labels: string[]): 'patch' | 'minor' | 'major' { + if (labels.includes(RELEASE_MAJOR_LABEL)) return 'major' + if (labels.includes(RELEASE_MINOR_LABEL)) return 'minor' + return 'patch' +} + +// `tag-bump`: the latest docs/v* tag plus a bump the PR labels choose. +function resolveTagBump(input: ResolveInput, explicit: string): ReleaseResolution { + if (explicit) return finish(explicit, INPUT_SOURCE, false, checkVersion(explicit, INPUT_SOURCE)) + + const versions = (input.tags ?? []).filter((t) => t.startsWith(TAG_PREFIX)).map((t) => t.slice(TAG_PREFIX.length)) + const latest = highestSemver(versions) + if (latest === null) { + return finish('', 'docs/v* tags', false, { + kind: 'missing', + value: '', + message: + "version source 'tag-bump' needs an existing docs/v* tag to bump from, and none exists — pass an explicit version for the first release (for example through workflow_dispatch)", + }) + } + const version = bumpVersion(latest, bumpFromLabels(input.labels ?? [])) + return finish(version, `docs/v${latest} + bump`, false) +} + +// Resolves the docs version for the configured source. Standalone always +// targets 'stable'. Pure: the command gathers every input. +export function resolveRelease(input: ResolveInput): ReleaseResolution { + if (input.mode === 'standalone') { + return { version: 'stable', tag: 'docs/stable', source: 'standalone', usesDescriptor: false } + } + const explicit = input.explicit?.trim() ?? '' + switch (input.source ?? 'descriptor') { + case 'github-release': + return resolveGithubRelease(input, explicit) + case 'tag-bump': + return resolveTagBump(input, explicit) + default: + return { ...resolveDescriptor(input), usesDescriptor: true } + } +} diff --git a/code/packages/cli/src/lib/semver.spec.ts b/code/packages/cli/src/lib/semver.spec.ts new file mode 100644 index 00000000..595d7423 --- /dev/null +++ b/code/packages/cli/src/lib/semver.spec.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { describe, expect, it } from 'vitest' + +import { bumpVersion, compareSemver, highestSemver, parseSemver } from './semver.js' + +describe('compareSemver', () => { + // The ordering example from semver.org section 11, in ascending order. + const ascending = [ + '1.0.0-alpha', + '1.0.0-alpha.1', + '1.0.0-alpha.beta', + '1.0.0-beta', + '1.0.0-beta.2', + '1.0.0-beta.11', + '1.0.0-rc.1', + '1.0.0', + '1.0.1', + '1.1.0', + '2.0.0', + '10.0.0', + ] + + it('orders the SemVer spec example ascending', () => { + for (let i = 0; i < ascending.length - 1; i++) { + expect(compareSemver(ascending[i]!, ascending[i + 1]!)).toBe(-1) + expect(compareSemver(ascending[i + 1]!, ascending[i]!)).toBe(1) + } + }) + + it('ignores build metadata', () => { + expect(compareSemver('1.2.3+a', '1.2.3+b')).toBe(0) + }) + + it('throws on invalid input', () => { + expect(() => compareSemver('v1.2.3', '1.2.3')).toThrow() + }) +}) + +describe('highestSemver', () => { + it('picks the highest, ignoring invalid entries', () => { + expect(highestSemver(['1.2.0-rc.1', '1.1.9', 'junk', '1.2.0-beta'])).toBe('1.2.0-rc.1') + }) + + it('returns null when nothing valid', () => { + expect(highestSemver([])).toBeNull() + expect(highestSemver(['x'])).toBeNull() + }) +}) + +describe('bumpVersion', () => { + // Expected values are semver.inc's own results. + it.each([ + ['1.2.3', 'patch', '1.2.4'], + ['1.2.3', 'minor', '1.3.0'], + ['1.2.3', 'major', '2.0.0'], + ['1.2.0-rc.1', 'patch', '1.2.0'], + ['1.2.3-rc.1', 'patch', '1.2.3'], + ['1.2.0-rc.1', 'minor', '1.2.0'], + ['1.2.3-rc.1', 'minor', '1.3.0'], + ['2.0.0-rc.1', 'major', '2.0.0'], + ['2.1.0-rc.1', 'major', '3.0.0'], + ['1.2.3+build.5', 'patch', '1.2.4'], + ] as const)('%s %s -> %s', (version, level, expected) => { + expect(bumpVersion(version, level)).toBe(expected) + }) + + it('throws on invalid input', () => { + expect(() => bumpVersion('1.2', 'patch')).toThrow() + }) +}) + +describe('parseSemver', () => { + it('parses prerelease identifiers', () => { + expect(parseSemver('1.2.3-beta.2+x')).toEqual({ major: 1, minor: 2, patch: 3, prerelease: ['beta', '2'] }) + }) +}) diff --git a/code/packages/cli/src/lib/semver.ts b/code/packages/cli/src/lib/semver.ts new file mode 100644 index 00000000..77b00579 --- /dev/null +++ b/code/packages/cli/src/lib/semver.ts @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +// Just enough SemVer 2.0.0 for docs version resolution: precedence ordering +// and the three bump levels, matching `semver.inc` for stable and prerelease +// inputs. Not a dependency: this is one small, well-specified function pair. + +// Full SemVer 2.0.0 grammar (semver.org's own regex). Prerelease and build +// metadata suffixes are valid; a leading 'v' or a two-part '1.2' is not. +export const SEMVER_RE = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/ + +export type BumpLevel = 'patch' | 'minor' | 'major' + +export interface ParsedVersion { + major: number + minor: number + patch: number + prerelease: string[] +} + +export function parseSemver(version: string): ParsedVersion | null { + if (!SEMVER_RE.test(version)) return null + const [core = '', ...rest] = version.split('+')[0]!.split('-') + const [major = '0', minor = '0', patch = '0'] = core.split('.') + const prerelease = rest.length > 0 ? rest.join('-').split('.') : [] + return { major: Number(major), minor: Number(minor), patch: Number(patch), prerelease } +} + +function comparePrereleaseIdentifier(a: string, b: string): number { + const aNumeric = /^\d+$/.test(a) + const bNumeric = /^\d+$/.test(b) + if (aNumeric && bNumeric) return Math.sign(Number(a) - Number(b)) + if (aNumeric) return -1 + if (bNumeric) return 1 + if (a === b) return 0 + return a < b ? -1 : 1 +} + +// SemVer 2.0.0 precedence: build metadata is ignored, a version with a +// prerelease sorts below the same version without one. +export function compareSemver(a: string, b: string): number { + const pa = parseSemver(a) + const pb = parseSemver(b) + if (!pa || !pb) throw new Error(`cannot compare invalid SemVer: '${pa ? b : a}'`) + for (const key of ['major', 'minor', 'patch'] as const) { + if (pa[key] !== pb[key]) return Math.sign(pa[key] - pb[key]) + } + if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0 + if (pa.prerelease.length === 0) return 1 + if (pb.prerelease.length === 0) return -1 + const length = Math.max(pa.prerelease.length, pb.prerelease.length) + for (let i = 0; i < length; i++) { + const x = pa.prerelease[i] + const y = pb.prerelease[i] + if (x === undefined) return -1 + if (y === undefined) return 1 + const result = comparePrereleaseIdentifier(x, y) + if (result !== 0) return result + } + return 0 +} + +export function highestSemver(versions: string[]): string | null { + let best: string | null = null + for (const version of versions) { + if (!parseSemver(version)) continue + if (best === null || compareSemver(version, best) > 0) best = version + } + return best +} + +// Same rules as `semver.inc(version, level)`: a bump from a prerelease whose +// lower components are already zero only drops the prerelease; build metadata +// is discarded. +export function bumpVersion(version: string, level: BumpLevel): string { + const parsed = parseSemver(version) + if (!parsed) throw new Error(`cannot bump invalid SemVer: '${version}'`) + const { major, minor, patch, prerelease } = parsed + const isPrerelease = prerelease.length > 0 + + if (level === 'major') { + if (isPrerelease && minor === 0 && patch === 0) return `${major}.0.0` + return `${major + 1}.0.0` + } + if (level === 'minor') { + if (isPrerelease && patch === 0) return `${major}.${minor}.0` + return `${major}.${minor + 1}.0` + } + if (isPrerelease) return `${major}.${minor}.${patch}` + return `${major}.${minor}.${patch + 1}` +} diff --git a/code/packages/cli/src/lib/site-mode.spec.ts b/code/packages/cli/src/lib/site-mode.spec.ts new file mode 100644 index 00000000..e48a1bdb --- /dev/null +++ b/code/packages/cli/src/lib/site-mode.spec.ts @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { describe, expect, it } from 'vitest' + +import { detectModeFromPlaybook } from './site-mode.js' + +describe('detectModeFromPlaybook', () => { + it('detects versioned from docs/v*', () => { + expect(detectModeFromPlaybook("content:\n sources:\n - tags: ['docs/v*']\n")).toBe('versioned') + }) + + it('detects standalone from docs/stable', () => { + expect(detectModeFromPlaybook(" tags: ['docs/stable']\n")).toBe('standalone') + }) + + it('returns null for anything else', () => { + expect(detectModeFromPlaybook(" tags: ['other']\n")).toBeNull() + expect(detectModeFromPlaybook('no tags here')).toBeNull() + }) +}) diff --git a/code/packages/cli/src/lib/site-mode.ts b/code/packages/cli/src/lib/site-mode.ts new file mode 100644 index 00000000..649f7594 --- /dev/null +++ b/code/packages/cli/src/lib/site-mode.ts @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +'use strict' + +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' + +export type SiteMode = 'versioned' | 'standalone' + +// Same signal docouture-release.yml's "Detect mode" step reads: the first +// `tags:` line of antora-playbook.yml says `docs/v*` (versioned) or +// `docs/stable` (standalone). Derived live, never stored. +export function detectModeFromPlaybook(content: string): SiteMode | null { + const line = content.split('\n').find((candidate) => candidate.includes('tags:')) + if (line === undefined) return null + if (line.includes('v*')) return 'versioned' + if (line.includes('stable')) return 'standalone' + return null +} + +export async function detectSiteMode(siteRoot: string): Promise<SiteMode | null> { + try { + return detectModeFromPlaybook(await readFile(join(siteRoot, 'antora-playbook.yml'), 'utf8')) + } catch { + return null + } +} diff --git a/code/packages/cli/templates/agent-support/AGENTS.md b/code/packages/cli/templates/agent-support/AGENTS.md index f30525a0..c0c18859 100644 --- a/code/packages/cli/templates/agent-support/AGENTS.md +++ b/code/packages/cli/templates/agent-support/AGENTS.md @@ -78,7 +78,8 @@ npx skills@latest add InditexTech/docouture --all that must agree, the home-page vs. content-page patterns, and how a site grows beyond its default `ROOT` + `main` modules. - **`docouture-docs-versioning`** — only relevant when this site was scaffolded with - `--mode versioned`: cutting releases, `docouture version`, and `docs/.release-version`. + `--mode versioned`: cutting releases, `docouture version`, `docs/.release-version` and the + alternative version sources (`docouture version-source`). <!-- docouture:end --> diff --git a/code/packages/cli/templates/starter/src/modules/main/pages/getting-started.adoc b/code/packages/cli/templates/starter/src/modules/main/pages/getting-started.adoc index 5374981d..cd3b4773 100644 --- a/code/packages/cli/templates/starter/src/modules/main/pages/getting-started.adoc +++ b/code/packages/cli/templates/starter/src/modules/main/pages/getting-started.adoc @@ -88,6 +88,12 @@ type the version into its `version` input.) *Standalone* mode has no such file — every release always targets the same `docs/stable` tag, so there is nothing to set beforehand. +This is the default `descriptor` version source. A versioned site can instead take the version +from the published GitHub Release's tag (`github-release`) or from the latest `docs/v*` tag plus a +bump chosen by the pull request's label (`tag-bump`) — neither keeps a `docs/.release-version`. +Show or change it with `docouture version-source` (see its `--help`); the reference page for the +release workflow explains each source. + `docouture version <value>` is a different, narrower tool: it directly rewrites `docs/antora.yml`'s `version:`/`prerelease:` fields in place and leaves everything else in this directory untouched. It is what diff --git a/code/packages/cli/templates/workflows/docouture-release-preview.yml b/code/packages/cli/templates/workflows/docouture-release-preview.yml index e29a4a00..55f9abea 100644 --- a/code/packages/cli/templates/workflows/docouture-release-preview.yml +++ b/code/packages/cli/templates/workflows/docouture-release-preview.yml @@ -20,10 +20,17 @@ name: docouture-release-preview # tag before merging, not after. # # Reuses docouture-release.yml's own "Detect mode" (grep antora-playbook.yml's -# content.sources[] tags) and "Resolve version" (stable, or -# docs/.release-version's contents) logic verbatim — see that workflow's own -# comments, and the docs-site-package skill's reference/versioning-modes.md, -# for the full mechanism. +# content.sources[] tags) logic verbatim — see that workflow's own comments, +# and the docs-site-package skill's reference/versioning-modes.md, for the full +# mechanism. +# +# The version depends on the site's `docouture.versionSource` +# (docs/package.json), read here with `node` (preinstalled on the runner): +# `descriptor` (default) reads docs/.release-version in bash and installs +# nothing; `github-release` has no version to show — the docs follow the code +# release — so it posts a fixed message; `tag-bump` installs the project's +# dependencies and asks `docouture release resolve` for the version that would +# be released if the pull request merged now. # # Docouture hardening: pinned actions, no persisted checkout credentials, # no third-party path filter (the pull request's own file list comes from the @@ -53,7 +60,7 @@ jobs: # the workflow a read-only GITHUB_TOKEN whatever `permissions:` asks for, # so every `gh pr comment` below would fail the run. Skipping this job # skips the three comment jobs that need it. - if: ${{ github.event.pull_request.head.repo.full_name == github.repository && (github.event.pull_request.draft == false || contains(github.event.pull_request.labels.*.name, 'docs/release')) }} + if: ${{ github.event.pull_request.head.repo.full_name == github.repository && (github.event.pull_request.draft == false || (contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major'))) }} outputs: detected: ${{ steps.changes.outputs.paths }} steps: @@ -77,7 +84,7 @@ jobs: # With a code release (`release-type/*` without `skip-release`) the job also # runs when the pull request touches no docs, to explain that the docs follow # the code release. - if: ${{ contains(github.event.pull_request.labels.*.name, 'docs/release') && (needs.check-changes-in-paths.outputs.detected == 'true' || (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release'))) }} + if: ${{ (contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && (needs.check-changes-in-paths.outputs.detected == 'true' || (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release'))) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: @@ -118,30 +125,79 @@ jobs: echo "mode=${mode}" >> "$GITHUB_OUTPUT" echo "Detected ${mode} (antora-playbook.yml: ${line})" - # Standalone always targets 'stable'; versioned reads the plain-text - # docs/.release-version this PR is expected to have committed — same - # source docouture-release.yml's pull_request trigger reads (there is no - # workflow_dispatch input to fall back to here, since this workflow - # only ever runs on pull_request). + - name: Read version source + id: source + run: | + source=$(node -p "require('./package.json').docouture?.versionSource ?? 'descriptor'") + + case "$source" in + descriptor | github-release | tag-bump) ;; + *) + echo "::error::docs/package.json declares docouture.versionSource '${source}' — expected descriptor, github-release or tag-bump." + exit 1 + ;; + esac + + echo "source=${source}" >> "$GITHUB_OUTPUT" + echo "Version source: ${source}" + + # Only `tag-bump` needs the project's own CLI here (semver ordering of + # the docs/v* tags); `descriptor` and `github-release` install nothing. + # __DOCOUTURE_PM_SETUP_STEP__ + - name: Setup Node + if: steps.source.outputs.source == 'tag-bump' + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version-file: docs/package.json + package-manager-cache: false + + - name: Install dependencies + if: steps.source.outputs.source == 'tag-bump' + run: __DOCOUTURE_INSTALL_CI__ + + # Standalone always targets 'stable'. Versioned depends on the source: + # `descriptor` reads the plain-text docs/.release-version this PR is + # expected to have committed — same source docouture-release.yml's + # pull_request trigger reads (there is no workflow_dispatch input to fall + # back to here); `github-release` has no version until the code release + # publishes; `tag-bump` asks `docouture release resolve` using the tags + # from the REST API (checkout keeps no credentials, and is shallow). - name: Resolve version id: resolve env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} MODE: ${{ steps.detect.outputs.mode }} + SOURCE: ${{ steps.source.outputs.source }} + LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} run: | - if [ "$MODE" = "versioned" ]; then + error="" + if [ "$MODE" != "versioned" ]; then + version="stable" + tag="docs/stable" + elif [ "$SOURCE" = "github-release" ]; then + version="" + tag="" + elif [ "$SOURCE" = "tag-bump" ]; then + tags=$(gh api --paginate "repos/${REPOSITORY}/git/matching-refs/tags/docs/v" --jq '.[].ref | ltrimstr("refs/tags/")' | paste -sd, -) + resolved=$(npx docouture release resolve --mode versioned --event pull_request --labels "$LABELS" --tags "$tags" --report) + version=$(printf '%s\n' "$resolved" | sed -n 's/^version=//p') + tag=$(printf '%s\n' "$resolved" | sed -n 's/^tag=//p') + error=$(printf '%s\n' "$resolved" | sed -n 's/^error=//p') + else if [ -f .release-version ]; then version=$(tr -d '[:space:]' < .release-version) else version="" fi tag="docs/v${version}" - else - version="stable" - tag="docs/stable" fi - echo "version=${version}" >> "$GITHUB_OUTPUT" - echo "tag=${tag}" >> "$GITHUB_OUTPUT" + { + echo "version=${version}" + echo "tag=${tag}" + echo "error=${error}" + } >> "$GITHUB_OUTPUT" # Asks the REST API rather than `git ls-remote`: checkout keeps no # credentials, and an unauthenticated ls-remote against a private @@ -174,8 +230,10 @@ jobs: REPOSITORY: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }} MODE: ${{ steps.detect.outputs.mode }} + SOURCE: ${{ steps.source.outputs.source }} VERSION: ${{ steps.resolve.outputs.version }} TAG: ${{ steps.resolve.outputs.tag }} + ERROR: ${{ steps.resolve.outputs.error }} EXISTED: ${{ steps.check.outputs.existed }} # A code release is also pending (`release-type/*` without # `skip-release`), so docouture-release.yml defers the docs release to @@ -188,7 +246,28 @@ jobs: FAIL_TIMING="If you merge it as it is, the docs release will fail." fi - if [ "$MODE" = "versioned" ] && [ -z "$VERSION" ]; then + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "github-release" ]; then + gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " + ### :information_source: The docs are released with the code release + This site's docs version source is \`github-release\`: the docs site is published when the code release publishes a GitHub Release, never when a Pull Request merges. No version can be shown here, and the \`docs/release\` label does **not** release the docs on merge. + + - **If the code release publishes a GitHub Release:** nothing else to do. Remove the \`docs/release\` label. + - **If it does not** (the release fails, stays a draft, or is marked pre-release): the docs will not be released. Start \`docouture-release\` manually from the Actions tab with an explicit version." + exit 0 + fi + + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "tag-bump" ] && [ -n "$ERROR" ]; then + gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " + ### :x: Docs release will fail: no version to bump from + This site's docs version source is \`tag-bump\`, but no \`docs/v*\` tag exists yet to bump from. + + ${FAIL_TIMING} + + **Before merging:** release the first version manually with \`docouture-release\` from the Actions tab, giving an explicit version such as \`1.0.0\`." + exit 0 + fi + + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "descriptor" ] && [ -z "$VERSION" ]; then gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " ### :x: Docs release will fail: no target version This site uses versioned docs, so a docs release needs to know which version to publish. This Pull Request has the \`docs/release\` label but no \`docs/.release-version\` file. @@ -206,7 +285,7 @@ jobs: # whole point of a preview: docouture-release.yml checks the same # thing, but only finds out after the PR has already merged. SEMVER_RE='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$' - if [ "$MODE" = "versioned" ] && ! [[ "$VERSION" =~ $SEMVER_RE ]]; then + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "descriptor" ] && ! [[ "$VERSION" =~ $SEMVER_RE ]]; then gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body " ### :x: Docs release will fail: invalid version \`docs/.release-version\` contains \`${VERSION}\`, which is not a valid version. Use a SemVer version such as \`1.2.0\` or \`1.2.0-rc.1\`, with no leading \`v\` and no two-part version like \`1.2\`. See https://semver.org. @@ -237,17 +316,23 @@ jobs: ### :warning: This tag already exists \`${TAG}\` has already been published. ${REPLACE_WHEN}" - if [ "$MODE" = "versioned" ]; then + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "descriptor" ]; then MESSAGE="${MESSAGE} If that is not what you want, change the version in \`docs/.release-version\`." fi fi + if [ "$MODE" = "versioned" ] && [ "$SOURCE" = "tag-bump" ]; then + MESSAGE="${MESSAGE} + + This is the version released **if this Pull Request merged now**: the latest \`docs/v*\` tag plus the bump its labels select. It can change if another docs release lands first." + fi + gh pr comment "$PR_NUMBER" --repo "$REPOSITORY" --body "$MESSAGE" release-preview-no-docs-changes: name: Add PR comment with configuration management information needs: check-changes-in-paths - if: ${{ contains(github.event.pull_request.labels.*.name, 'docs/release') && needs.check-changes-in-paths.outputs.detected == 'false' && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} + if: ${{ (contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && needs.check-changes-in-paths.outputs.detected == 'false' && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: @@ -266,7 +351,7 @@ jobs: release-preview-no-release-label: name: Add PR comment with release information needs: check-changes-in-paths - if: ${{ !contains(github.event.pull_request.labels.*.name, 'docs/release') && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} + if: ${{ !(contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && !(contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: @@ -289,7 +374,7 @@ jobs: release-preview-code-release: name: Add PR comment with code release information needs: check-changes-in-paths - if: ${{ !contains(github.event.pull_request.labels.*.name, 'docs/release') && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} + if: ${{ !(contains(github.event.pull_request.labels.*.name, 'docs/release') || contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && needs.check-changes-in-paths.outputs.detected == 'true' && github.event.pull_request.draft == false && (contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type/') && !contains(github.event.pull_request.labels.*.name, 'skip-release')) }} runs-on: ubuntu-24.04 timeout-minutes: 5 permissions: diff --git a/code/packages/cli/templates/workflows/docouture-release.yml b/code/packages/cli/templates/workflows/docouture-release.yml index e0b5b9f6..da9a335f 100644 --- a/code/packages/cli/templates/workflows/docouture-release.yml +++ b/code/packages/cli/templates/workflows/docouture-release.yml @@ -55,6 +55,16 @@ name: docouture-release # that other workflow actually finishes. Either way this runs exactly # once per merge, just not always at the same moment. # +# Version source (versioned only): where a release's version comes from is the +# site's `docouture.versionSource` in docs/package.json, resolved by `docouture +# release resolve` — `descriptor` (default: docs/.release-version, as described +# above), `github-release` (the published GitHub Release's tag) or `tag-bump` +# (the latest docs/v* tag plus a bump: `docs/release` patch, +# `docs/release-minor` minor, `docs/release-major` major). Only `descriptor` +# runs the descriptor bump and the git-flow sync below. Under `tag-bump` a +# `release: published` run has no pull request labels to read, so it bumps +# patch; use workflow_dispatch with an explicit version for anything else. +# # Git-flow (versioned only): the descriptor bump below lands on the release # branch, so the `sync-prerelease` job opens a pull request carrying it into # the prerelease branch (name read from docs/package.json's @@ -127,6 +137,7 @@ jobs: prerelease_branch: ${{ steps.flow.outputs.prerelease_branch }} version: ${{ steps.resolve.outputs.version }} bumped: ${{ steps.bump.outputs.bumped }} + uses_descriptor: ${{ steps.resolve.outputs.uses_descriptor }} # `docouture new` scaffolds this site's package.json, antora-playbook.yml, # docs/antora.yml etc. under docs/ (not the repository root) — see the # docs-site-package skill's reference/versioning-modes.md. Every step @@ -153,7 +164,9 @@ jobs: github.event_name == 'workflow_dispatch' || (github.event_name == 'release' && !github.event.release.prerelease) || (github.event.pull_request.merged == true && - contains(github.event.pull_request.labels.*.name, 'docs/release') && + (contains(github.event.pull_request.labels.*.name, 'docs/release') || + contains(github.event.pull_request.labels.*.name, 'docs/release-minor') || + contains(github.event.pull_request.labels.*.name, 'docs/release-major')) && (contains(github.event.pull_request.labels.*.name, 'skip-release') || !contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type'))) steps: @@ -281,6 +294,38 @@ jobs: echo "mode=${mode}" >> "$GITHUB_OUTPUT" echo "Detected ${mode} (antora-playbook.yml: ${line})" + # Where the target version comes from is decided by `docouture release + # resolve`, which reads the site's `docouture.versionSource` from + # docs/package.json: `descriptor` (default) uses the workflow_dispatch + # input if a person typed one, else the docs/.release-version file the + # merged PR committed; `github-release` uses the published Release's + # tag; `tag-bump` bumps the latest docs/v* tag by the PR's + # `docs/release[-minor|-major]` label. Standalone always targets + # `stable`. The command also validates it (present, SemVer, + # not 'stable') and fails here, before any tag is pushed below — a + # malformed value would otherwise only fail later in "Bump release + # descriptor", after the tag already exists. + - name: Resolve version + id: resolve + env: + MODE: ${{ steps.detect.outputs.mode }} + EVENT: ${{ github.event_name }} + DISPATCH_VERSION: ${{ inputs.version }} + RELEASE_TAG: ${{ github.event.release.tag_name }} + LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} + run: | + args=(release resolve --mode "$MODE" --event "$EVENT" --labels "$LABELS") + if [ "$EVENT" = "workflow_dispatch" ]; then + args+=(--version "$DISPATCH_VERSION") + fi + if [ -n "$RELEASE_TAG" ]; then + args+=(--release-tag "$RELEASE_TAG") + fi + + resolved=$(npx docouture "${args[@]}") + echo "$resolved" >> "$GITHUB_OUTPUT" + echo "$resolved" + # The flow (trunk-based or git-flow) and, under git-flow, the prerelease # branch name come from docs/package.json's `docouture` block — one # declared source, kept in sync by `docouture new`, `branch-model` and @@ -291,11 +336,12 @@ jobs: id: flow env: MODE: ${{ steps.detect.outputs.mode }} + USES_DESCRIPTOR: ${{ steps.resolve.outputs.uses_descriptor }} run: | branching=$(node -p "require('./package.json').docouture?.branching ?? ''") prerelease=$(node -p "require('./package.json').docouture?.prereleaseBranch ?? ''") - if [ "$branching" = "git-flow" ] && [ -z "$prerelease" ] && [ "$MODE" = "versioned" ]; then + if [ "$branching" = "git-flow" ] && [ -z "$prerelease" ] && [ "$USES_DESCRIPTOR" = "true" ]; then echo "::error::docs/package.json declares docouture.branching 'git-flow' but no docouture.prereleaseBranch — run 'docouture upgrade' to add it (the prerelease branch needs a sync PR carrying the docs/.release-version bump)." exit 1 fi @@ -304,74 +350,6 @@ jobs: echo "prerelease_branch=${prerelease}" >> "$GITHUB_OUTPUT" echo "Detected flow '${branching:-trunk-based}' (prerelease branch '${prerelease}')" - # Where the target version comes from depends on how this run started: - # a person typed it (workflow_dispatch) or the merged PR committed it - # (docs/.release-version). Standalone ignores whatever this resolves to - # either way — it always targets `stable` — but it's still resolved - # uniformly here so later steps don't need to know which trigger fired. - - name: Resolve version - id: resolve - env: - EVENT: ${{ github.event_name }} - DISPATCH_VERSION: ${{ inputs.version }} - run: | - if [ "$EVENT" = "workflow_dispatch" ]; then - version="$DISPATCH_VERSION" - source="workflow_dispatch input" - elif [ -f .release-version ]; then - version=$(tr -d '[:space:]' < .release-version) - source="docs/.release-version" - else - version="" - source="docs/.release-version (missing)" - fi - - echo "version=${version}" >> "$GITHUB_OUTPUT" - echo "Resolved version '${version}' from ${source}" - - - name: Validate version - env: - MODE: ${{ steps.detect.outputs.mode }} - EVENT: ${{ github.event_name }} - VERSION: ${{ steps.resolve.outputs.version }} - run: | - if [ "$MODE" = "versioned" ] && [ -z "$VERSION" ]; then - if [ "$EVENT" = "workflow_dispatch" ]; then - echo "::error::Versioned mode requires a real target version — re-run with a 'version' input other than the default 'stable', e.g. 1.2.0." - else - echo "::error::Versioned mode requires a real target version, and this PR carried no docs/.release-version — add that file with the target version (e.g. 1.2.0) before merging with the docs/release label, or run docouture-release manually via workflow_dispatch instead." - fi - exit 1 - fi - - if [ "$MODE" = "versioned" ] && [ "$VERSION" = "stable" ]; then - echo "::error::'stable' is standalone's target name, not a valid versioned-mode version — use a real version, e.g. 1.2.0." - exit 1 - fi - - # Full SemVer 2.0.0 grammar (semver.org's own regex, rewritten with - # plain groups instead of `(?:...)` — bash's [[ =~ ]] runs glibc - # POSIX ERE, not PCRE, and doesn't understand non-capturing - # groups). Catches a hand-edited docs/.release-version (or a typo'd - # workflow_dispatch input) BEFORE any tag is pushed below — without - # this, a malformed value sails through here, tags and pushes fine - # in "Cut release"/"Push release tag", and only fails later inside - # "Bump release descriptor" (npm's `version patch` rejects - # non-semver input) — by which point the tag already exists but the - # job as a whole reads as failed, so the `publish` job below never - # runs. Prerelease/build-metadata suffixes (1.2.0-beta.1, - # 1.2.0+build) are valid SemVer and accepted; a leading 'v' or a - # bare '1.2' are not. - SEMVER_RE='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$' - if [ "$MODE" = "versioned" ] && [ -n "$VERSION" ] && ! [[ "$VERSION" =~ $SEMVER_RE ]]; then - echo "::error::docs/.release-version (or the 'version' input) must be a valid SemVer version like 1.2.0 — got '${VERSION}'. See https://semver.org — prerelease/build metadata (1.2.0-beta.1, 1.2.0+build) is fine, a leading 'v' or a two-part '1.2' is not." - exit 1 - fi - - if [ "$MODE" = "standalone" ] && [ -n "$VERSION" ] && [ "$VERSION" != "stable" ]; then - echo "::warning::Standalone mode always releases to the 'stable' tag — ignoring provided version '${VERSION}'." - fi - # The release branch's own docs/antora.yml is never touched here — it # permanently says version: prerelease (both modes, trunk-based only # — see the guides-branching-model guide for why this steady-state @@ -470,7 +448,7 @@ jobs: # republish of an already-released version — see "Check for existing # release" above): docs/.release-version needs a sane value again # immediately or the next docs/release merge has nothing to read (see - # "Validate version" above). Rather than clearing it, bump it forward + # "Resolve version" above). Rather than clearing it, bump it forward # one patch version — the same idiom `just bump` uses for this # workspace's own npm packages: let `npm version` do the semver # arithmetic against a throwaway package.json instead of hand-rolling @@ -483,7 +461,7 @@ jobs: # protecting it. - name: Bump release descriptor id: bump - if: steps.detect.outputs.mode == 'versioned' && steps.check.outputs.existed != 'true' + if: steps.resolve.outputs.uses_descriptor == 'true' && steps.check.outputs.existed != 'true' env: VERSION: ${{ steps.resolve.outputs.version }} run: | @@ -513,6 +491,7 @@ jobs: if: >- needs.release.result == 'success' && needs.release.outputs.branching == 'git-flow' && + needs.release.outputs.uses_descriptor == 'true' && needs.release.outputs.bumped == 'true' runs-on: ubuntu-24.04 timeout-minutes: 10 diff --git a/docs/src/modules/main/nav.adoc b/docs/src/modules/main/nav.adoc index 059dd4e0..c9c92720 100644 --- a/docs/src/modules/main/nav.adoc +++ b/docs/src/modules/main/nav.adoc @@ -38,6 +38,7 @@ * xref:main:additional-information-overview.adoc[Overview] * xref:main:changelog/index.adoc[Changelog] * xref:main:release-notes/index.adoc[Release notes] +** xref:main:release-notes/1-4-0.adoc[v1.4.0] ** xref:main:release-notes/1-3-2.adoc[v1.3.2] ** xref:main:release-notes/1-3-1.adoc[v1.3.1] ** xref:main:release-notes/1-3-0.adoc[v1.3.0] diff --git a/docs/src/modules/main/pages/guides-branching-model.adoc b/docs/src/modules/main/pages/guides-branching-model.adoc index 45eb0f36..61a93785 100644 --- a/docs/src/modules/main/pages/guides-branching-model.adoc +++ b/docs/src/modules/main/pages/guides-branching-model.adoc @@ -73,7 +73,7 @@ green. `main`), posting a preview comment. On merge, `docouture-release.yml` cuts the release (checks out `main`, tags it, pushes the tag) and calls `docouture-publish.yml` to build and publish. - A versioned release also bumps `docs/.release-version` on `main`; its + Under the default `descriptor` version source, a versioned release also bumps `docs/.release-version` on `main`; its `sync-prerelease` job then opens a pull request into `develop` carrying that bump (branch `automated/sync-docs-release-<version>-to-develop`) — merge it so `develop` doesn't go stale. It runs before the publish, which doesn't wait on its result: a diff --git a/docs/src/modules/main/pages/guides-releasing-a-documentation.adoc b/docs/src/modules/main/pages/guides-releasing-a-documentation.adoc index 69926b95..6b400f65 100644 --- a/docs/src/modules/main/pages/guides-releasing-a-documentation.adoc +++ b/docs/src/modules/main/pages/guides-releasing-a-documentation.adoc @@ -24,8 +24,9 @@ Under the hood: `docouture version <value>` patches `docs/src/antora.yml` on a o commit built on the release branch's current tip, `git tag docs/v<value>` is created there, and the tag is pushed — the release branch itself is never advanced. -Before any of that: `docs/.release-version` (or the `workflow_dispatch` version input, -in versioned mode) is validated against full SemVer 2.0.0 — a leading `v`, a bare `1.2`, +Before any of that: the resolved version (`docs/.release-version`, or the +`workflow_dispatch` version input, in versioned mode; see <<version-sources>> for the +other sources) is validated against full SemVer 2.0.0 — a leading `v`, a bare `1.2`, or any other malformed value fails the workflow immediately with a clear error, instead of tagging first and only failing later inside the version-bump step. `docouture-release-preview.yml` runs the same check earlier, as a PR comment, before the @@ -53,8 +54,53 @@ triggered by a labelled PR merge: version directly — its form field is what a versioned-mode release actually requires there, unlike standalone's, where the default is fine.) +[#version-sources] +=== Where the version comes from + +By default the version comes from `docs/.release-version`, as above. That file duplicates +the `docs/v*` tags, and it needs the post-release bump push (and, under git-flow, the sync +pull request below). A versioned site can instead choose another source with +`docouture.versionSource` in `docs/package.json`: + +[cols="1,3"] +|=== +|Source |The version comes from + +|`descriptor` (default) +|`docs/.release-version`, committed by the release pull request. The forward-bump and the git-flow sync described here apply only to this source. + +|`github-release` +|The tag of the published GitHub Release, minus the optional `docouture.versionSourcePrefix` (for example `docs-site@`). The docs follow the code release. A merged `docs/release` pull request fails with a message saying so. + +|`tag-bump` +|The highest existing `docs/v*` tag plus a bump: `docs/release` bumps patch, `docs/release-minor` minor and `docs/release-major` major (the highest wins when several are present). The first release has no tag to bump from, so run `docouture-release` manually with an explicit version. +|=== + +Change the source with `docouture version-source <source>` (see xref:main:reference-cli.adoc[]); +`docouture new --mode versioned` asks for it. Switching to `github-release` or `tag-bump` +removes `docs/.release-version`; for `tag-bump` it also prints the `gh label create` +commands for the two extra labels, which you create once. `docouture release resolve` +implements the rules for both workflows. + +* The preview comment follows the source: `descriptor` reads the file (no dependency + install), `github-release` says the docs follow the code release without naming a + version, and `tag-bump` shows the version released *if the pull request merged now*, which + can change if another release lands first. +* Under `tag-bump`, a run started by a published GitHub Release has no pull request + labels to read, so it bumps patch. Use `workflow_dispatch` with an explicit version for + a minor or major bump in that case. +* The workflows run the CLI your project installed. Update `@inditextech/docouture-cli` + and install it first, then run `docouture upgrade` (which writes + `"versionSource": "descriptor"` on a site that lacks it, with no behavior change), then + optionally `docouture version-source`. `docouture doctor` shows the active source and + warns about a stray or missing `docs/.release-version` and about a project CLI that + predates `release resolve`. + === Under git-flow: the sync pull request +This applies to the `descriptor` source only; the other sources have no bump to carry over +and skip the job. + The forward-bump is committed on the release branch only. On a git-flow site the workflow's `sync-prerelease` job then opens a pull request from `automated/sync-docs-release-<version>-to-<prerelease>` into the prerelease branch, so @@ -123,8 +169,8 @@ The docs release depends on the code release publishing a Release. They are not docs tag; * your code release does not publish a GitHub Release at all. -In versioned mode there is one more case. If `docs/.release-version` is missing or -invalid, the docs release fails when the Release is published, after the code release has +In versioned mode under the `descriptor` source there is one more case. If +`docs/.release-version` is missing or invalid, the docs release fails when the Release is published, after the code release has already gone out. The preview flags this on a pull request with `docs/release`; with `release-type/*` alone it does not check the file, which is normally present because every release bumps it forward. diff --git a/docs/src/modules/main/pages/guides-versioning-modes.adoc b/docs/src/modules/main/pages/guides-versioning-modes.adoc index 0eb526c6..ca152ed4 100644 --- a/docs/src/modules/main/pages/guides-versioning-modes.adoc +++ b/docs/src/modules/main/pages/guides-versioning-modes.adoc @@ -37,7 +37,7 @@ content: tags: ['docs/v*'] ---- -A versioned-mode site additionally gets `docs/.release-version` — a plain-text file +Under the default `descriptor` version source, a versioned-mode site additionally gets `docs/.release-version` — a plain-text file holding the *next* release's target version, read by `docouture-release.yml` instead of a workflow input. diff --git a/docs/src/modules/main/pages/reference-cli.adoc b/docs/src/modules/main/pages/reference-cli.adoc index 3fc8a5f7..0ed027e3 100644 --- a/docs/src/modules/main/pages/reference-cli.adoc +++ b/docs/src/modules/main/pages/reference-cli.adoc @@ -36,6 +36,8 @@ xref:main:guides-branching-model.adoc[] |`--branch <name>` |Trunk-based only: the one branch (default: `main`) |`--integration-branch <name>` |Git-flow only: the prerelease branch (default: `develop`) |`--release-branch <name>` |Git-flow only: the release branch (default: `main`) +|`--version-source <source>` |Versioned mode only: where the docs release version comes from — `descriptor` (default, `docs/.release-version`), +`github-release` or `tag-bump`; see xref:main:guides-releasing-a-documentation.adoc#version-sources[]. `tag-bump` prints the `gh label create` commands for `docs/release-minor` and `docs/release-major`. Rejected for a standalone site |`--pm <pm>` |`npm` or `pnpm` (default: auto-detected) |`--yes` |Skip the interactive wizard |=== @@ -107,7 +109,10 @@ Antora is installed, and (advisory only) whether `AGENTS.md` is still present, w (`docs/package.json`'s `docouture.branching`, plus `docouture.prereleaseBranch` under git-flow) agrees with what `antora-playbook.yml`/`docouture-release.yml` actually say — see -xref:main:guides-branching-model.adoc[]. Does not check for the agent skills — see +xref:main:guides-branching-model.adoc[]. On a versioned site it also shows the active +version source and warns about a stray or missing `docs/.release-version`, a project CLI that +differs from the running one, and a project CLI that predates `release resolve` — see +xref:main:guides-releasing-a-documentation.adoc#version-sources[]. Does not check for the agent skills — see xref:main:reference-ai-first-approach.adoc[], those are a separate, self-serve install this CLI never scaffolds or verifies. @@ -127,6 +132,10 @@ page a site owner has written — is never touched, with one exception: on a git it writes or corrects `docouture.branching` and `docouture.prereleaseBranch` in `docs/package.json` (derived from `antora-playbook.yml`), which `docouture-release.yml` reads to open the prerelease sync PR. This also backfills sites scaffolded before that field existed. +On a versioned site without `docouture.versionSource` it writes `"versionSource": "descriptor"` (the +current behavior, so nothing changes) and points at `docouture version-source`; it never changes an +existing value, never prompts and never touches a standalone site. It warns when the project's +installed `@inditextech/docouture-cli` differs from the running one, since the workflows use the project's. It also sets `runtime.log.failure_level` to `error` in `docs/antora-playbook*.yml`, replacing any other value and printing each file it changed: builds then fail on errors such as a broken `xref:` or a missing include, so run `docouture build` and fix what it reports before @@ -180,6 +189,76 @@ stay manual steps, printed as a reminder after every real run. |`--dry-run` |Lists what would be written without writing it |=== +== `docouture version-source [source]` + +Show or change where a versioned site's docs release version comes from +(`docs/package.json`'s `docouture.versionSource`). With no argument it prints the current +source. See xref:main:guides-releasing-a-documentation.adoc#version-sources[] for what each +source means. + +Refuses a standalone site, which always releases `docs/stable`. Per target: + +* `descriptor` creates `docs/.release-version` if it is missing, seeded with the next patch + of the latest `docs/v*` tag (or `--version`; `0.1.0` with no tag). +* `github-release` removes `docs/.release-version`. +* `tag-bump` removes `docs/.release-version` and prints the `gh label create` commands for + `docs/release-minor` and `docs/release-major`. + +Removing the file warns when it held a pending version. The command is idempotent. No +workflow is re-rendered: the workflows read the source at run time, but they run the +project's installed CLI, so install a version with `release resolve` first. + +[cols="1,2"] +|=== +|Argument/Flag |Effect + +|`[source]` |`descriptor`, `github-release` or `tag-bump`; omit to show the current one +|`--prefix <p>` |`github-release` only: strip this prefix from the release tag (`docouture.versionSourcePrefix`) +|`--version <X.Y.Z>` |`descriptor` only: write this version to `docs/.release-version` +|`--dry-run` |Lists what would change without changing anything +|=== + +== `docouture release resolve` + +Resolve the docs version and tag a release run targets. The `docouture-release` and +`docouture-release-preview` workflows call it so the version rules live in one place. + +Where the version comes from depends on `docouture.versionSource` in `docs/package.json` +(`descriptor` when absent): + +[cols="1,3"] +|=== +|Source |Version + +|`descriptor` |`--version` when given (the `workflow_dispatch` input), otherwise `docs/.release-version` +|`github-release` |The published release tag (`--release-tag`) minus `docouture.versionSourcePrefix`, when set. A merged `docs/release` pull request fails. +|`tag-bump` |The highest `docs/v*` tag plus a bump chosen by `--labels`: `docs/release` patch, `docs/release-minor` minor, `docs/release-major` major (the highest wins). The first release needs `--version`. +|=== + +`--version` always takes precedence. A standalone site always targets `stable`. A versioned +version must be present, valid SemVer and not `stable`; otherwise the command fails with +exit code 1. + +Prints `version`, `tag`, `source`, `version_source` and `uses_descriptor` as `key=value` +lines on stdout, ready to append to `$GITHUB_OUTPUT`. `uses_descriptor` is `true` only when +the descriptor bump and the prerelease sync apply. With `--report`, a version error is printed +as `error` (`missing`, `invalid`, `reserved`, `prefix` or `unsupported`) and `error_value` +instead, and the exit code stays 0. + +[cols="1,2"] +|=== +|Argument/Flag |Effect + +|`--mode <mode>` |Required: `versioned` or `standalone` +|`--version <v>` |Explicit version; takes precedence over every source +|`--event <name>` |GitHub event name (`workflow_dispatch`, `pull_request`, `release`) +|`--release-tag <tag>` |Tag of the published GitHub Release (`github-release`) +|`--labels <a,b>` |Pull request labels, comma-separated (`tag-bump`) +|`--tags <a,b>` |Existing tag names instead of listing git tags (`tag-bump`) +|`--report` |Report a version error as output instead of failing +|`--dir <path>` |Repository root (default: cwd, or its enclosing repo) +|=== + == `docouture eject <target>` Copy a bundled default file out into `docs/` for local customization. Refuses to diff --git a/docs/src/modules/main/pages/release-notes/1-4-0.adoc b/docs/src/modules/main/pages/release-notes/1-4-0.adoc new file mode 100644 index 00000000..01dc28a8 --- /dev/null +++ b/docs/src/modules/main/pages/release-notes/1-4-0.adoc @@ -0,0 +1,64 @@ += v1.4.0 + +[.lead] +A versioned site can now choose where its docs release version comes from. The default is +unchanged, so nothing breaks, but the release workflows now call a new CLI command, so the +CLI must be updated first. Existing sites get the new workflows by running +`docouture upgrade`. + +== Do this + +. Update every `@inditextech/docouture-*` package, and the CLI if you install it, to + `1.4.0`, and install. In a scaffolded site these are pinned in `docs/package.json`. + Do this before the next step: the generated workflows run the CLI your project installed, + and `docouture-release.yml` now calls `docouture release resolve`, which older CLIs do + not have. +. Run `docouture upgrade`, review the diff, and commit `.github/workflows/` and + `docs/package.json`. On a versioned site it writes `"versionSource": "descriptor"`, which + keeps today's behavior. It warns when the CLI you ran differs from the one your project + installed. See xref:main:reference-cli.adoc[]. +. Optional: run `docouture version-source` to see, or `docouture version-source <source>` to + change, where the docs version comes from. Run `docouture doctor` afterwards. It shows the + active source and warns about a stray or missing `docs/.release-version`. + +A standalone site needs only the first two steps and has nothing to choose: it always +releases `docs/stable`. + +== What changed + +* *New: three version sources.* A versioned site sets `docouture.versionSource` in + `docs/package.json`: +** `descriptor` (the default) reads `docs/.release-version`, exactly as before, including + the forward bump after each release and the git-flow sync pull request. +** `github-release` takes the version from the tag of the published GitHub Release, minus an + optional `docouture.versionSourcePrefix`. The docs follow the code release. +** `tag-bump` takes the latest `docs/v*` tag and bumps it: `docs/release` bumps patch, + `docs/release-minor` minor and `docs/release-major` major. Create the two extra labels + once; `docouture new` and `docouture version-source` print the `gh label create` + commands. ++ +Under `github-release` and `tag-bump` there is no `docs/.release-version`, no post-release +bump push and no sync pull request, so the release no longer needs to push to the protected +release branch. See xref:main:guides-releasing-a-documentation.adoc#version-sources[]. +* *New: `docouture version-source`.* Shows or changes the source, creating or removing + `docs/.release-version` for you. `--dry-run` previews it. Refuses a standalone site. +* *New: `docouture release resolve`.* The release and preview workflows share one tested + implementation of the version rules, including SemVer validation. +* *New: `docouture new --version-source`.* Versioned mode asks which source to use. +* *Changed: `docouture upgrade` and `docouture doctor`.* `upgrade` backfills the default and + warns on a CLI mismatch. `doctor` shows the active source and warns when the project's + installed CLI differs from yours or predates `release resolve`. +* *Changed: the release preview follows the source.* `descriptor` is unchanged and still + installs nothing. `github-release` says the docs follow the code release and names no + version. `tag-bump` shows the version released *if the pull request merged now*, which can + change if another release lands first. The job runs your package manager's install only + for `tag-bump`. + +== Limitations + +* Under `tag-bump`, a release started by a published GitHub Release has no pull request + labels to read, so it bumps patch. Use `workflow_dispatch` with an explicit version for a + minor or major bump, and for the first release, when there is no tag to bump from. +* Under `github-release`, a merged pull request with `docs/release` fails the release + workflow with a message saying so. The preview comments that suggest adding `docs/release` + to a pull request without it still say so under `github-release`. diff --git a/docs/src/modules/main/pages/release-notes/index.adoc b/docs/src/modules/main/pages/release-notes/index.adoc index dd4d6582..30dfb89b 100644 --- a/docs/src/modules/main/pages/release-notes/index.adoc +++ b/docs/src/modules/main/pages/release-notes/index.adoc @@ -5,6 +5,7 @@ xref:main:changelog/index.adoc[Changelog], the unabridged commit-level record. == Versions +* xref:main:release-notes/1-4-0.adoc[v1.4.0] * xref:main:release-notes/1-3-2.adoc[v1.3.2] * xref:main:release-notes/1-3-1.adoc[v1.3.1] * xref:main:release-notes/1-3-0.adoc[v1.3.0] diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/.openspec.yaml b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/.openspec.yaml new file mode 100644 index 00000000..2a7773d6 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-11 diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/design.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/design.md new file mode 100644 index 00000000..e282c35f --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/design.md @@ -0,0 +1,41 @@ +# Design + +## Context + +See proposal.md. After `release-resolve-descriptor`, `docouture release resolve` implements only the `descriptor` resolver (`src/lib/release-resolve.ts`, a pure function plus file IO in `src/commands/release.ts`), and the release workflow's "Resolve version" step calls it. The preview workflow (`docouture-release-preview.yml`) still resolves in bash and has no Node, package-manager or install steps; a parity test guards its SemVer regex. + +The release workflow gates itself on `docs/release` in its job `if:`, runs the descriptor bump on the release branch, and runs `sync-prerelease` under git-flow when the bump happened. `docs/package.json`'s `docouture` block is written by `src/lib/package-branching.ts` (`setBranching`), and `new`, `branch-model` and `upgrade` already maintain it. + +## Goals / Non-Goals + +**Goals:** +- Per-site choice of version source, with `descriptor` as an unchanged default. +- One tested resolver implementation for all three sources, used by both workflows where a version must be computed. +- The descriptor-only machinery (bump push, sync job, `.release-version`) is cleanly skipped for the other sources. + +**Non-Goals:** +- Custom script or npm resolvers, automatic migration during `upgrade`, standalone mode, and any GitHub API call from the CLI. + +## Decisions + +- **`versionSource` lives in `docs/package.json`'s `docouture` block**, read by workflows through `release resolve` (and by the preview with `node -p`). Alternative: a repo variable or workflow input; rejected because the declaration must travel with the site, like `branching`, and be checked by `doctor`. A shared writer `package-version-source.ts` mirrors `package-branching.ts`, keeping key order and idempotency. +- **Pure resolvers with injected inputs.** `resolveRelease({ mode, source, explicit, descriptor, event, releaseTag, labels, tags, prefix })` returns the existing `ReleaseResolution` plus `usesDescriptor`. The command gathers the inputs (reads `.release-version`, runs `git tag -l 'docs/v*'`, parses `--event`, `--release-tag`, `--labels`) and prints `key=value` lines. This keeps every rule unit-testable without git or GitHub. +- **Hand-written SemVer comparison** in a lib module (precedence including prerelease identifiers, build metadata ignored), plus a `bumpVersion(version, level)` that matches `semver.inc` for patch/minor/major on stable and prerelease inputs. Alternative: depend on `semver`; rejected for one small, well-specified function, and revisited if the test corpus gets awkward. +- **Bump selection from labels.** `docs/release` is patch, `docs/release-minor` minor, `docs/release-major` major, highest wins. A `workflow_dispatch` run has no labels, so under `tag-bump` it needs an explicit version (the same override covers republish and the first release). +- **Descriptor-only steps gate on `uses_descriptor`.** The "Resolve version" step writes `uses_descriptor` to `$GITHUB_OUTPUT`; "Bump release descriptor" and the `sync-prerelease` condition test it. The git-flow check that demands `prereleaseBranch` runs only when it is true. +- **Trigger conditions** in the release workflow's job `if:` and the preview's job conditions also match `docs/release-minor` and `docs/release-major`. These labels are harmless under other sources because `resolve` fails or ignores them as the specs state. +- **Preview stays cheap for `descriptor`.** A first step reads `versionSource` with `node -p` (Node is preinstalled on runners). `descriptor` keeps the existing bash path with no install; `github-release` posts a fixed message; `tag-bump` runs the same setup-node, package-manager and install steps as the release workflow (same template placeholders), fetches tags, and calls `release resolve`. Alternative: always install; rejected on cost for the common case. This reverses change 1's "preview never calls the CLI" decision only for `tag-bump`, where the logic cannot reasonably stay in bash. +- **Wizard and flags.** `new` adds one `select` prompt after the versioning-mode and branching questions, versioned only, plus `--version-source`. `upgrade` backfills `descriptor` without prompting. `version-source` mirrors `branch-model`'s structure: argument parsing, `--dry-run`, `--dir`, shared `package-version-source.ts`, and re-uses nothing from workflow re-rendering (workflows read the source at run time, so no re-render is needed). +- **CLI skew warning.** `upgrade` and `doctor` compare the running CLI version with the one resolved by the project's `docs/package.json`/lockfile and warn on a mismatch, since workflows use the project's installed CLI. `doctor` also warns when the project's CLI lacks `release resolve` (probed through the resolved package's version). + +## Risks / Trade-offs + +- [Workflow upgraded before the CLI] → the documented order is bump CLI, install, `docouture upgrade`, then optionally `version-source`; `upgrade` and `doctor` warn on skew. +- [Concurrent releases under `tag-bump`] → the preview says "if merged now"; the release workflow's existing concurrency group serializes runs and the tag is recomputed at run time. +- [Race between the code release and the docs release under `github-release`] → the existing `release: published` trigger fires the docs release; `workflow_dispatch` with an explicit version remains the repair path. +- [Switching sources by hand] → `version-source` makes the file and label side effects explicit and supports `--dry-run`; `doctor` catches a stray or missing `.release-version`. +- [A larger change than the first half] → tasks are ordered resolver library first, then command inputs, workflows, commands and docs, with each group landing its own tests. + +## Migration Plan + +Existing sites need no action: an absent `versionSource` means `descriptor`, and `upgrade` writes it explicitly. A site moves to another source with `docouture version-source <source>`, after upgrading its CLI. diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/proposal.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/proposal.md new file mode 100644 index 00000000..b485cbdd --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/proposal.md @@ -0,0 +1,35 @@ +## Why + +In versioned (Full History) mode every release version comes from `docs/.release-version`, which duplicates the `docs/v*` tags Antora already treats as the source of truth. Maintaining it is costly: a post-release bump pushed to the protected release branch (needing an App token with ruleset bypass, #298), a `sync-prerelease` job under git-flow that exists only to carry that bump, a hard failure when a `docs/release` PR did not commit the file, and a `release: published` trigger that ignores `release.tag_name`. docouture is code-agnostic, so the fix cannot be "read the version from the code's manifest": each site must choose where its docs version comes from. This is the second half of #299; the first half (`release-resolve-descriptor`, archived) moved descriptor resolution and SemVer validation into `docouture release resolve`. + +## What Changes + +- Add `docouture.versionSource` to `docs/package.json` (next to `branching`/`prereleaseBranch`) with three built-in resolvers: `descriptor` (default, today's behavior), `github-release` (`release.tag_name`, optionally stripping `docouture.versionSourcePrefix`) and `tag-bump` (latest `docs/v*` tag plus a bump). An absent value means `descriptor`. +- `tag-bump` bumps patch on `docs/release`, minor on `docs/release-minor`, major on `docs/release-major` (highest wins when several are set). Ordering is semver-aware, including prerelease tags, and a bump from a prerelease tag follows `semver.inc` (`1.2.0-rc.1` patch becomes `1.2.0`). With no existing `docs/v*` tag it requires an explicit version through `workflow_dispatch`. +- Extend `docouture release resolve` with the new resolvers and inputs (event, release tag, PR labels, tags) and a machine-readable signal telling the workflow whether the descriptor bump and prerelease sync apply. +- Release workflow: the bump step and the `sync-prerelease` job run only under `descriptor`. Trigger conditions also match `docs/release-minor` and `docs/release-major`. Under `github-release`, a merged `docs/release` PR fails with a clear message. +- Preview workflow: reads `versionSource` with `node`. `descriptor` stays on bash with no install, `github-release` posts a fixed "docs follow the code release" message, and `tag-bump` installs dependencies and calls `release resolve` to show the version "if merged now". +- `docouture new` (versioned mode only): wizard prompt and `--version-source` flag, default `descriptor`, each option explained. For `tag-bump` it prints the `gh label create` commands for `docs/release-minor` and `docs/release-major`. Standalone sites are unaffected. +- `docouture upgrade`: on a versioned site without `versionSource`, write `"versionSource": "descriptor"` (idempotent, no behavior change) and print a pointer to the new command; no prompt. `upgrade` and `doctor` warn when the running CLI differs from the project's resolved dependency. +- New command `docouture version-source [descriptor|github-release|tag-bump] [--dry-run] [--version X.Y.Z]`, modeled on `branch-model`. It refuses standalone sites, sets `versionSource`, creates `docs/.release-version` (seeded with the next patch of the latest tag, or `--version`) for `descriptor`, and removes it for the others (warning if it held a pending value), printing the label commands for `tag-bump`. +- `docouture doctor`: show the active resolver; warn when `github-release`/`tag-bump` still has `.release-version`, when `descriptor` has no file, and when the installed CLI lacks `release resolve`. +- Docs, the `docouture-docs-versioning` skill, the scaffolded `AGENTS.md` and `getting-started` page, and release notes. + +Non-goals: custom (script) or npm-package resolvers; automatic migration between resolvers during `upgrade`; standalone mode. + +## Capabilities + +### New Capabilities +- `docs-version-source`: the `versionSource` declaration in `docs/package.json` and how `new`, `upgrade`, `doctor` and `version-source` scaffold, backfill, check and switch it. + +### Modified Capabilities +- `docs-release-resolve`: the `github-release` and `tag-bump` resolvers, their inputs, bump semantics, tag ordering, and the signal for descriptor-only steps. +- `docs-release-preview`: version and comment behavior under each source, and release-label handling for `docs/release-minor` and `docs/release-major`. +- `docs-release-prerelease-sync`: the bump and sync apply only under `descriptor`; the sync is skipped otherwise. + +## Impact + +- `code/packages/cli`: `src/commands/{release,new,upgrade,doctor}.ts`, new `src/commands/version-source.ts`, `src/lib/{release-resolve,doctor-checks}.ts` plus a new `package-version-source.ts`, `bin.ts`, `completion.ts`, the workflow templates (`docouture-release.yml`, `docouture-release-preview.yml`), starter `getting-started.adoc`, `agent-support/AGENTS.md`. +- `.github/workflows/docouture-release*.yml` (this repo's own copies). +- `docs/src/modules/main/pages/` (CLI reference, releasing and branching guides, release notes) and `skills/docouture-docs-versioning`. +- Existing sites keep working unchanged on `descriptor`. Sites must install the new CLI before upgrading workflows, since workflows run the project's installed CLI. diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-prerelease-sync/spec.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-prerelease-sync/spec.md new file mode 100644 index 00000000..df7d6f4f --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-prerelease-sync/spec.md @@ -0,0 +1,23 @@ +## MODIFIED Requirements + +### Requirement: Flow detection from package.json +The release workflow SHALL read `docouture.branching` and `prereleaseBranch` from `docs/package.json`. An absent `branching` SHALL be treated as trunk-based. `git-flow` without `prereleaseBranch` SHALL fail in versioned mode under the `descriptor` version source with a message pointing at `docouture upgrade`. Under other version sources it SHALL NOT fail, since no sync pull request is opened. + +#### Scenario: Missing prerelease name +- **WHEN** `branching` is `git-flow`, the source is `descriptor` and `prereleaseBranch` is absent +- **THEN** the run fails naming `docouture upgrade` + +#### Scenario: Missing prerelease name, other source +- **WHEN** `branching` is `git-flow`, the source is `tag-bump` and `prereleaseBranch` is absent +- **THEN** the run does not fail on that account + +### Requirement: Skip conditions +The sync SHALL be skipped for trunk-based sites, standalone mode, a version source other than `descriptor`, republishes (tag already existed), a missing prerelease branch, or when the prerelease branch already contains the release branch. The descriptor bump SHALL likewise run only under `descriptor`. + +#### Scenario: Trunk-based +- **WHEN** `branching` is `trunk-based` +- **THEN** the sync job is skipped + +#### Scenario: Other source +- **WHEN** the version source is `github-release` or `tag-bump` +- **THEN** neither the descriptor bump nor the sync job runs diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-preview/spec.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-preview/spec.md new file mode 100644 index 00000000..37278988 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-preview/spec.md @@ -0,0 +1,36 @@ +## MODIFIED Requirements + +### Requirement: Version errors +Under the `descriptor` version source in versioned mode, when `docs/.release-version` is missing or not valid SemVer, the preview SHALL post an error instead of the release preview and SHALL say that the docs release will fail. For a pull request with T, it SHALL say the failure happens when the code release publishes a GitHub Release, after the code release has gone out, not on merge. + +#### Scenario: Missing version, docs only +- **WHEN** a versioned-mode `descriptor` pull request has `docs/release`, no T and no `docs/.release-version` +- **THEN** the comment says the docs release will fail and asks to add the file before merging + +#### Scenario: Invalid version with a code release +- **WHEN** a versioned-mode `descriptor` pull request has `docs/release`, T and an invalid `docs/.release-version` +- **THEN** the comment says the docs release will fail when the code Release is published, not on merge + +## ADDED Requirements + +### Requirement: Preview by version source +The preview SHALL read the version source from `docs/package.json`. Under `descriptor` it SHALL NOT install dependencies. Under `github-release` it SHALL state that the docs are released when the code release publishes a GitHub Release, with no version, and that a `docs/release` label does not release them on merge. Under `tag-bump` it SHALL compute the version with `docouture release resolve` and state it as the version released if the pull request merged now, noting the version can change if another release lands first. + +#### Scenario: github-release +- **WHEN** a `github-release` pull request has `docs/release` +- **THEN** the comment says the docs follow the code release and names no version + +#### Scenario: tag-bump +- **WHEN** a `tag-bump` pull request has `docs/release-minor` and the latest tag is `docs/v1.2.3` +- **THEN** the comment says merging now releases `docs/v1.3.0`, and that the version can change if another release merges first + +#### Scenario: Descriptor stays cheap +- **WHEN** the version source is `descriptor` +- **THEN** the job runs no install step + +### Requirement: Bump labels trigger the preview +Under `tag-bump`, a pull request with `docs/release-minor` or `docs/release-major` SHALL be previewed like one with `docs/release`. + +#### Scenario: Minor label only +- **WHEN** a `tag-bump` pull request has `docs/release-minor` and no `docs/release` +- **THEN** the release preview is posted diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-resolve/spec.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-resolve/spec.md new file mode 100644 index 00000000..1cb00b5d --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-release-resolve/spec.md @@ -0,0 +1,85 @@ +## RENAMED Requirements + +- FROM: `### Requirement: Descriptor is the only resolver` +- TO: `### Requirement: Descriptor is the default resolver` + +## MODIFIED Requirements + +### Requirement: Resolve command interface +`docouture release resolve` SHALL accept the site mode (`versioned` or `standalone`), an optional explicit version, the repository root (default: cwd, or its enclosing repo), the event name, the published release tag and the pull request labels, and SHALL print the resolved version, the release tag, the source the version came from and the active version source. It SHALL expose these as `key=value` lines suitable for appending to `$GITHUB_OUTPUT`. It SHALL read the active version source from `docs/package.json`, defaulting to `descriptor`, and SHALL print whether the descriptor bump and prerelease sync apply. + +#### Scenario: Versioned, version from the descriptor +- **WHEN** it runs in `versioned` mode with source `descriptor`, without an explicit version, and `docs/.release-version` contains `1.2.0` +- **THEN** it reports version `1.2.0`, tag `docs/v1.2.0` and source `docs/.release-version`, says the descriptor steps apply, and exits 0 + +#### Scenario: Standalone +- **WHEN** it runs in `standalone` mode +- **THEN** it reports version `stable` and tag `docs/stable` regardless of any file, version source or explicit version, says the descriptor steps do not apply, and exits 0 + +### Requirement: Descriptor is the default resolver +When `docs/package.json` declares no `versionSource`, or declares `descriptor`, the command SHALL resolve versions only from the explicit input or `docs/.release-version`, SHALL NOT read the GitHub Release tag, and SHALL say the descriptor bump and prerelease sync apply. A `release: published` run under `descriptor` therefore keeps reading `docs/.release-version`. + +#### Scenario: Release event +- **WHEN** a workflow runs the command for a `release: published` event, source `descriptor`, with no explicit version +- **THEN** the version comes from `docs/.release-version` + +## ADDED Requirements + +### Requirement: Unknown version source +The command SHALL fail with exit 1, naming the valid values, when `versionSource` is not `descriptor`, `github-release` or `tag-bump`. + +#### Scenario: Typo +- **WHEN** `versionSource` is `tag_bump` +- **THEN** it exits non-zero and lists `descriptor`, `github-release` and `tag-bump` + +### Requirement: github-release resolver +Under `github-release` the version SHALL be the published release tag with `versionSourcePrefix` stripped when declared, and SHALL be validated as SemVer. A tag that does not start with the declared prefix SHALL fail. An explicit version SHALL still take precedence. A pull request event carrying `docs/release` SHALL fail with a message that explains the docs follow the code release and names the configured source. The descriptor steps SHALL NOT apply. + +#### Scenario: Plain tag +- **WHEN** the release tag is `1.4.0` and no prefix is declared +- **THEN** it reports version `1.4.0` and tag `docs/v1.4.0` + +#### Scenario: Prefixed tag +- **WHEN** the release tag is `docs-site@1.4.0` and the prefix is `docs-site@` +- **THEN** it reports version `1.4.0` + +#### Scenario: Wrong prefix +- **WHEN** the release tag is `other@1.4.0` and the prefix is `docs-site@` +- **THEN** it exits non-zero and says the tag does not start with the prefix + +#### Scenario: Release label on a merged PR +- **WHEN** a pull request event has `docs/release` and the source is `github-release` +- **THEN** it exits non-zero and says the docs release follows the code release + +### Requirement: tag-bump resolver +Under `tag-bump` the version SHALL be the highest existing `docs/v*` tag, by SemVer ordering including prerelease precedence, incremented by the bump the pull request labels select: `docs/release` patch, `docs/release-minor` minor and `docs/release-major` major, the highest bump winning when several labels are present. A bump from a prerelease tag SHALL follow `semver.inc`. An explicit version SHALL take precedence over any bump. The descriptor steps SHALL NOT apply. + +#### Scenario: Implicit patch +- **WHEN** the latest tag is `docs/v1.2.3` and only `docs/release` is present +- **THEN** it reports version `1.2.4` + +#### Scenario: Minor and major labels +- **WHEN** both `docs/release-minor` and `docs/release-major` are present on top of `docs/v1.2.3` +- **THEN** it reports version `2.0.0` + +#### Scenario: Prerelease ordering +- **WHEN** the tags are `docs/v1.2.0-rc.1` and `docs/v1.1.9` +- **THEN** the latest is `1.2.0-rc.1` and a patch bump reports `1.2.0` + +#### Scenario: Explicit version +- **WHEN** `--version 3.0.0` is passed on top of `docs/v1.2.3` +- **THEN** it reports version `3.0.0` without bumping + +### Requirement: tag-bump without a tag +Under `tag-bump` with no existing `docs/v*` tag and no explicit version, the command SHALL fail saying an explicit version is needed for the first release, for example through `workflow_dispatch`. + +#### Scenario: First release +- **WHEN** no `docs/v*` tag exists and no version is given +- **THEN** it exits non-zero and asks for an explicit version + +### Requirement: Descriptor-only steps signal +The command SHALL print `uses_descriptor=true` only when the mode is versioned and the source is `descriptor`, so a workflow runs the descriptor bump and the prerelease sync only then. + +#### Scenario: tag-bump +- **WHEN** the source is `tag-bump` +- **THEN** it prints `uses_descriptor=false` diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-version-source/spec.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-version-source/spec.md new file mode 100644 index 00000000..f8061c5e --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/specs/docs-version-source/spec.md @@ -0,0 +1,64 @@ +## Purpose + +Defines how a versioned docouture site declares where its docs release version comes from, and how the CLI scaffolds, backfills, checks and switches that declaration. + +## ADDED Requirements + +### Requirement: Version source declaration +The `docouture` block of `docs/package.json` SHALL be able to declare `versionSource` as `descriptor`, `github-release` or `tag-bump`. An absent `versionSource` SHALL mean `descriptor`. When `versionSource` is `github-release` the block MAY declare `versionSourcePrefix`, a string stripped from the start of a release tag. `versionSource` SHALL be placed after `branching` and `prereleaseBranch` and other keys SHALL keep their order. + +#### Scenario: Absent value +- **WHEN** `docs/package.json` has no `versionSource` +- **THEN** the site is treated as `descriptor` + +#### Scenario: Unknown value +- **WHEN** `versionSource` is any other string +- **THEN** commands that read it fail naming the three valid values + +### Requirement: new scaffolds the source +In versioned mode `docouture new` SHALL ask which version source to use, with each option explained and `descriptor` as the default, and SHALL accept `--version-source <source>` to skip the prompt. It SHALL write the choice to `docs/package.json` and create `docs/.release-version` only for `descriptor`. For `tag-bump` it SHALL print the exact `gh label create` commands for `docs/release-minor` and `docs/release-major` and SHALL NOT call the GitHub API. In standalone mode it SHALL neither prompt for nor accept a version source. + +#### Scenario: Default +- **WHEN** a versioned site is scaffolded without choosing a source +- **THEN** `versionSource` is `descriptor` and `docs/.release-version` exists + +#### Scenario: tag-bump +- **WHEN** a versioned site is scaffolded with `--version-source tag-bump` +- **THEN** no `docs/.release-version` is created and the label commands are printed + +#### Scenario: Standalone +- **WHEN** `--version-source` is passed for a standalone site +- **THEN** the command fails saying standalone sites have no version source + +### Requirement: upgrade backfills the source +`docouture upgrade` on a versioned site without `versionSource` SHALL write `"versionSource": "descriptor"`, print what it changed and point at `docouture version-source`, without prompting. It SHALL be idempotent, SHALL NOT change an existing `versionSource` and SHALL NOT touch standalone sites. When the running CLI version differs from the version resolved by the project it SHALL warn. + +#### Scenario: Legacy versioned site +- **WHEN** a versioned site's `package.json` lacks `versionSource` +- **THEN** upgrade writes `descriptor` and reports it + +#### Scenario: Second run +- **WHEN** upgrade runs again +- **THEN** `package.json` is unchanged + +### Requirement: version-source command +`docouture version-source [descriptor|github-release|tag-bump]` SHALL refuse a standalone site, set `versionSource`, and per target: for `descriptor` create `docs/.release-version` seeded with the next patch of the latest `docs/v*` tag, or with `--version`; for `github-release` and `tag-bump` remove `docs/.release-version`, warning when it held a pending value, and for `tag-bump` print the `gh label create` commands. `--dry-run` SHALL report what would change without writing. It SHALL be idempotent. + +#### Scenario: Switch to tag-bump +- **WHEN** a `descriptor` site holding `1.3.0` in `.release-version` is switched to `tag-bump` +- **THEN** the file is removed, a warning names the pending `1.3.0`, and the label commands are printed + +#### Scenario: Switch back +- **WHEN** a `tag-bump` site is switched to `descriptor` and the latest tag is `docs/v1.2.4` +- **THEN** `.release-version` is created containing `1.2.5` + +#### Scenario: Dry run +- **WHEN** `--dry-run` is passed +- **THEN** nothing is written and the planned changes are listed + +### Requirement: doctor reports the source +`docouture doctor` SHALL show the active version source and SHALL warn when `github-release` or `tag-bump` still has `docs/.release-version`, when `descriptor` has no such file, and when the installed CLI does not support `release resolve`, each with the fix. + +#### Scenario: Stray descriptor +- **WHEN** `versionSource` is `tag-bump` and `docs/.release-version` exists +- **THEN** doctor warns and suggests `docouture version-source tag-bump` diff --git a/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/tasks.md b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/tasks.md new file mode 100644 index 00000000..7194a729 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-pluggable-docs-version-resolvers/tasks.md @@ -0,0 +1,35 @@ +# Tasks + +## 1. Resolver library + +- [x] 1.1 Add SemVer precedence comparison and a `bumpVersion` helper in a lib module; verify unit tests cover stable, prerelease ordering, build metadata ignored, and `semver.inc` parity for patch/minor/major (including `1.2.0-rc.1` patch becomes `1.2.0`) +- [x] 1.2 Extend `resolveRelease` with the `github-release` resolver (prefix stripping, wrong-prefix and `docs/release` PR failures) and the `tag-bump` resolver (label precedence, no-tag failure, explicit override); verify unit tests cover every scenario in `docs-release-resolve` +- [x] 1.3 Add `usesDescriptor` to the resolution and reject unknown sources; verify tests for standalone, each source and the typo case + +## 2. `release resolve` command + +- [x] 2.1 Add `--event`, `--release-tag`, `--labels` inputs, read `versionSource`/`versionSourcePrefix` from `docs/package.json`, list `docs/v*` tags with git, and print `source` and `uses_descriptor`; verify `release.spec.ts` asserts the new output lines and exit codes against a temp git repo with tags +- [x] 2.2 Update the command's help text and `docs/.../reference-cli.adoc`; verify the help and completion specs pass and the docs build passes + +## 3. Declaration writer + +- [x] 3.1 Add `package-version-source.ts` (read, validate, write after `branching`/`prereleaseBranch`, idempotent, key order preserved); verify unit tests for absent, valid, invalid, rewrite and idempotent cases + +## 4. Workflows + +- [x] 4.1 In `docouture-release.yml` gate the bump step, the `prereleaseBranch` requirement and `sync-prerelease` on `uses_descriptor`, and extend the job `if:` with `docs/release-minor` and `docs/release-major`; verify `actionlint` passes and the template-render tests pass +- [x] 4.2 In `docouture-release-preview.yml` read the source with `node -p`, keep the bash path for `descriptor`, post the fixed message for `github-release`, and for `tag-bump` add setup, install, tag fetch and `release resolve`; extend the job conditions with the bump labels; verify `actionlint` passes and the SemVer parity test still passes +- [x] 4.3 Mirror both workflow edits in `.github/workflows/docouture-release*.yml`; verify the diff matches the templates apart from placeholders + +## 5. CLI commands + +- [x] 5.1 Add the `version-source` command (target argument, `--dry-run`, `--version`, `--dir`, standalone refusal, descriptor seeding from the latest tag, file removal with pending-value warning, label commands for `tag-bump`); verify its spec covers each scenario in `docs-version-source` +- [x] 5.2 Register `version-source` in `bin.ts` and `completion.ts`; verify completion and help specs pass +- [x] 5.3 Add the wizard prompt and `--version-source` to `new` (versioned only, label commands for `tag-bump`, `.release-version` only for `descriptor`); verify `new.spec.ts` covers default, each source and the standalone rejection +- [x] 5.4 Backfill `versionSource: descriptor` in `upgrade` (idempotent, versioned only, no prompt, pointer message) and add the CLI skew warning; verify `upgrade.spec.ts` covers legacy, second-run and standalone cases +- [x] 5.5 Add the doctor checks (active source, stray or missing `.release-version`, CLI lacks `release resolve`, skew); verify `doctor-checks.spec.ts` covers each warning and the clean case + +## 6. Documentation + +- [x] 6.1 Document the sources in the releasing and branching guides and the CLI reference, update the `docouture-docs-versioning` skill, the starter `getting-started.adoc` and `agent-support/AGENTS.md`, and the AGENTS.md documentation-state ledger; verify the docs build passes and the skills sync check passes +- [x] 6.2 Add the release-notes entry with the upgrade order (bump and install the CLI, `docouture upgrade`, optionally `docouture version-source`); verify the docs build passes diff --git a/openspec/changes/archive/2026-11-11-release-resolve-descriptor/.openspec.yaml b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/.openspec.yaml new file mode 100644 index 00000000..2a7773d6 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-11 diff --git a/openspec/changes/archive/2026-11-11-release-resolve-descriptor/design.md b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/design.md new file mode 100644 index 00000000..5a1e5253 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/design.md @@ -0,0 +1,29 @@ +# Design + +## Context + +See proposal.md. The release workflow runs from `docs/` (working-directory) and already detects mode via the playbook `tags:` line. The release workflow resolves from `workflow_dispatch` input or `.release-version`; the preview resolves from `.release-version` only and has no Node setup. The release workflow calls the project's installed CLI (`npx docouture ...`). + +## Goals / Non-Goals + +**Goals:** +- One tested implementation of resolve plus SemVer validation, shared by both workflows. +- Identical observable behavior (tags, messages, comments) to today. + +**Non-Goals:** +- New resolvers, `versionSource` config, mode detection in the CLI (workflows keep passing `--mode`). + +## Decisions + +- **Command shape: `docouture release resolve --mode <versioned|standalone> [--version <v>] [--report] [--dir <path>]`.** `release` is a command group so `version-source`-adjacent subcommands can follow. Alternative: a flat `release-resolve` command; rejected because change 2 and later work extend the group naturally. +- **Output as `key=value` lines** (`version`, `tag`, `source`, `error`, `error_value`) on stdout, appended to `$GITHUB_OUTPUT` by the workflow. Alternative: JSON; rejected because shell consumers need no `jq`. +- **`--report` mode** exits 0 and emits `error=missing|invalid` so a caller that wants to comment instead of fail can (no workflow uses it yet, since the preview stays on bash); without it, errors go to stderr with exit 1 (release workflow). One validator, two reporting modes. +- **SemVer regex moved to a lib module** with unit tests; the bash copies are deleted. +- **The preview does not call the CLI.** It has no Node, package-manager or install steps, and only posts a comment. Adding them would slow every docs-label PR. Alternative: install and call `release resolve --report` there; rejected on cost. The duplicated SemVer regex is guarded by a parity test that extracts it from the template and runs it against the same corpus as the CLI's. +- **Mode stays a workflow input.** Detection from the playbook stays in bash for now; moving it in would widen scope. + +## Risks / Trade-offs + +- [Workflow template upgraded before the CLI] → the `docouture upgrade` ordering is documented in release notes; `doctor` support for this lands in change 2. +- [Preview's bash SemVer regex drifts from the CLI's] → parity test in `release-resolve.spec.ts`. +- [Repo copies of workflows diverge from templates] → update both in the same task group. diff --git a/openspec/changes/archive/2026-11-11-release-resolve-descriptor/proposal.md b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/proposal.md new file mode 100644 index 00000000..377b9128 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/proposal.md @@ -0,0 +1,29 @@ +## Why + +The docs version is resolved by bash duplicated in `docouture-release.yml` and `docouture-release-preview.yml` (resolve source, SemVer validation, error wording). The logic is untested and the two copies can drift. This is step one of #299 (pluggable version resolvers): put resolution in one tested CLI command, with no behavior change, so the later `github-release` and `tag-bump` resolvers (change 2) have a single place to land. + +## What Changes + +- Add `docouture release resolve`: given the trigger context (event, dispatch version, mode), it prints the resolved version, its source, and validation errors, using the `descriptor` resolver only (`workflow_dispatch` input, else `docs/.release-version`). +- Move SemVer validation and the "missing / invalid version" decisions into the command. Exit non-zero with a message on failure. +- Replace the inline "Resolve version" and "Validate version" bash in `docouture-release.yml` (template and the repo's own copy) with a call to the command. +- The preview workflow keeps its own bash resolve and SemVer check, since it has no Node or install steps and only posts a comment. A parity test fails if its regex diverges from the CLI's. +- Keep the `release: published` trigger reading `docs/.release-version` under `descriptor` (decision A of #299). Behavior is unchanged. +- No new config key: `docouture.versionSource` is introduced in change 2. Absence means `descriptor`. + +Non-goals: the `github-release` and `tag-bump` resolvers, the `version-source` command, `new`/`upgrade`/`doctor` changes (all change 2). + +## Capabilities + +### New Capabilities +- `docs-release-resolve`: contract of `docouture release resolve` (inputs, outputs, validation, exit codes) for the `descriptor` resolver. + +### Modified Capabilities +None. The preview's observable behavior is unchanged. + +## Impact + +- `code/packages/cli`: new `src/commands/release.ts` (plus spec, `bin.ts` COMMAND_INFO, completion), workflow templates. +- `.github/workflows/docouture-release.yml`: the repo's own copy. +- Sites need the new CLI installed before their workflows are upgraded (workflows run the project's installed CLI). `docs/reference-cli.adoc` and release notes updated. +- `docs-release-prerelease-sync` is untouched here (the bump and sync job stay). diff --git a/openspec/changes/archive/2026-11-11-release-resolve-descriptor/specs/docs-release-resolve/spec.md b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/specs/docs-release-resolve/spec.md new file mode 100644 index 00000000..9fbf55f5 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/specs/docs-release-resolve/spec.md @@ -0,0 +1,56 @@ +## Purpose + +Defines how `docouture release resolve` decides which docs version a release run targets, so the release and preview workflows share one validated source of truth instead of duplicated shell. + +## ADDED Requirements + +### Requirement: Resolve command interface +`docouture release resolve` SHALL accept the site mode (`versioned` or `standalone`), an optional explicit version, and the repository root (default: cwd, or its enclosing repo), and SHALL print the resolved version, the release tag and the source the version came from. It SHALL expose these as `key=value` lines suitable for appending to `$GITHUB_OUTPUT`. + +#### Scenario: Versioned, version from the descriptor +- **WHEN** it runs in `versioned` mode without an explicit version and `docs/.release-version` contains `1.2.0` +- **THEN** it reports version `1.2.0`, tag `docs/v1.2.0` and source `docs/.release-version`, and exits 0 + +#### Scenario: Standalone +- **WHEN** it runs in `standalone` mode +- **THEN** it reports version `stable` and tag `docs/stable` regardless of any file or explicit version, and exits 0 + +### Requirement: Explicit version takes precedence +When an explicit version is supplied (the `workflow_dispatch` input), the command SHALL use it instead of `docs/.release-version`, and SHALL report its source as the explicit input. + +#### Scenario: Dispatch version +- **WHEN** it runs in `versioned` mode with explicit version `2.0.0` and `docs/.release-version` contains `1.2.0` +- **THEN** it reports version `2.0.0` + +### Requirement: Version validation +In `versioned` mode the command SHALL fail with a non-zero exit and a message naming the source when the resolved version is missing, equals `stable`, or is not valid SemVer 2.0.0. Prerelease and build-metadata suffixes SHALL be accepted; a leading `v` and a two-part version SHALL be rejected. + +#### Scenario: Missing file +- **WHEN** it runs in `versioned` mode with no explicit version and no `docs/.release-version` +- **THEN** it exits non-zero and says the file is missing + +#### Scenario: Invalid SemVer +- **WHEN** the resolved version is `v1.2` or `1.2` +- **THEN** it exits non-zero and says the version is not valid SemVer + +#### Scenario: Prerelease suffix +- **WHEN** the resolved version is `1.2.0-rc.1` +- **THEN** it exits 0 and reports tag `docs/v1.2.0-rc.1` + +#### Scenario: Reserved name +- **WHEN** versioned mode resolves the version `stable` +- **THEN** it exits non-zero and says `stable` is not a valid versioned version + +### Requirement: Descriptor is the only resolver +Until a different resolver is configured, the command SHALL resolve versions only from the explicit input or `docs/.release-version`, and SHALL NOT read the GitHub Release tag. A `release: published` run therefore keeps reading `docs/.release-version`. + +#### Scenario: Release event +- **WHEN** a workflow runs the command for a `release: published` event with no explicit version +- **THEN** the version comes from `docs/.release-version` + +### Requirement: Validation-only reporting +The command SHALL provide a mode that reports a validation failure as output (an error kind: missing or invalid) with exit 0, so the preview workflow can post a comment instead of failing the job. + +#### Scenario: Preview with a bad version +- **WHEN** the command runs in report mode with an invalid `docs/.release-version` +- **THEN** it exits 0 and reports the error kind `invalid` and the offending value diff --git a/openspec/changes/archive/2026-11-11-release-resolve-descriptor/tasks.md b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/tasks.md new file mode 100644 index 00000000..ce810018 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-release-resolve-descriptor/tasks.md @@ -0,0 +1,17 @@ +# Tasks + +## 1. Resolver library + +- [x] 1.1 Add a lib module with the descriptor resolver and SemVer 2.0.0 validation; verify unit tests cover valid, prerelease, `v1.2`, `1.2`, `stable`, missing file, explicit-over-file and standalone cases +- [x] 1.2 Add the `release resolve` command (`src/commands/release.ts`) with `--mode`, `--version`, `--report`, `--dir`; verify its spec asserts `key=value` output, exit codes and report mode + +## 2. CLI wiring and docs + +- [x] 2.1 Register `release` in `bin.ts` (COMMAND_INFO, command map) and `completion.ts`; verify the completion and help specs pass +- [x] 2.2 Document the command in `docs/.../reference-cli.adoc` and update the AGENTS.md documentation-state row; verify the docs build passes + +## 3. Workflows + +- [x] 3.1 Replace "Resolve version" and "Validate version" in `templates/workflows/docouture-release.yml` with `npx docouture release resolve`; verify `actionlint` or the template copy tests pass and outputs keep the same names +- [x] 3.2 Add a parity test that extracts the SemVer regex from `docouture-release-preview.yml` and checks it agrees with the CLI's on the same corpus; verify it passes +- [x] 3.3 Apply the same edit to the repo's own `.github/workflows/docouture-release.yml`; verify the diff matches the templates apart from placeholders diff --git a/openspec/specs/docs-release-prerelease-sync/spec.md b/openspec/specs/docs-release-prerelease-sync/spec.md index 2cd83f13..ef9d6ead 100644 --- a/openspec/specs/docs-release-prerelease-sync/spec.md +++ b/openspec/specs/docs-release-prerelease-sync/spec.md @@ -6,12 +6,16 @@ Defines how the docs release workflow detects the branching model and, under git ## Requirements ### Requirement: Flow detection from package.json -The release workflow SHALL read `docouture.branching` and `prereleaseBranch` from `docs/package.json`. An absent `branching` SHALL be treated as trunk-based. `git-flow` without `prereleaseBranch` SHALL fail in versioned mode with a message pointing at `docouture upgrade`. +The release workflow SHALL read `docouture.branching` and `prereleaseBranch` from `docs/package.json`. An absent `branching` SHALL be treated as trunk-based. `git-flow` without `prereleaseBranch` SHALL fail in versioned mode under the `descriptor` version source with a message pointing at `docouture upgrade`. Under other version sources it SHALL NOT fail, since no sync pull request is opened. #### Scenario: Missing prerelease name -- **WHEN** `branching` is `git-flow` and `prereleaseBranch` is absent +- **WHEN** `branching` is `git-flow`, the source is `descriptor` and `prereleaseBranch` is absent - **THEN** the run fails naming `docouture upgrade` +#### Scenario: Missing prerelease name, other source +- **WHEN** `branching` is `git-flow`, the source is `tag-bump` and `prereleaseBranch` is absent +- **THEN** the run does not fail on that account + ### Requirement: Sync PR to the prerelease branch After a versioned release that bumped `docs/.release-version`, under git-flow the workflow SHALL open a pull request from `automated/sync-docs-release-<version>-to-<prerelease>` into the prerelease branch, containing the release branch state. It SHALL reuse an existing open PR, force-update the branch with lease, retry creation up to 3 times on 5xx after re-checking for an existing PR, and label it `kind/internal` when that label exists. @@ -24,12 +28,16 @@ After a versioned release that bumped `docs/.release-version`, under git-flow th - **THEN** no second PR is created ### Requirement: Skip conditions -The sync SHALL be skipped for trunk-based sites, standalone mode, republishes (tag already existed), a missing prerelease branch, or when the prerelease branch already contains the release branch. +The sync SHALL be skipped for trunk-based sites, standalone mode, a version source other than `descriptor`, republishes (tag already existed), a missing prerelease branch, or when the prerelease branch already contains the release branch. The descriptor bump SHALL likewise run only under `descriptor`. #### Scenario: Trunk-based - **WHEN** `branching` is `trunk-based` - **THEN** the sync job is skipped +#### Scenario: Other source +- **WHEN** the version source is `github-release` or `tag-bump` +- **THEN** neither the descriptor bump nor the sync job runs + ### Requirement: Publish is not blocked by sync The `sync-prerelease` job SHALL run before `publish`, and `publish` SHALL run whenever `release` succeeded, regardless of the sync result. A sync failure SHALL leave the run failed and SHALL comment on the merged `docs/release` PR with the run link when one exists. diff --git a/openspec/specs/docs-release-preview/spec.md b/openspec/specs/docs-release-preview/spec.md index 42f77e1e..e46140a3 100644 --- a/openspec/specs/docs-release-preview/spec.md +++ b/openspec/specs/docs-release-preview/spec.md @@ -28,14 +28,14 @@ For a pull request with `docs/release` and no code release (T), the preview SHAL - **THEN** the comment says nothing new will be released ### Requirement: Version errors -In versioned mode, when `docs/.release-version` is missing or not valid SemVer, the preview SHALL post an error instead of the release preview and SHALL say that the docs release will fail. For a pull request with T, it SHALL say the failure happens when the code release publishes a GitHub Release, after the code release has gone out, not on merge. +Under the `descriptor` version source in versioned mode, when `docs/.release-version` is missing or not valid SemVer, the preview SHALL post an error instead of the release preview and SHALL say that the docs release will fail. For a pull request with T, it SHALL say the failure happens when the code release publishes a GitHub Release, after the code release has gone out, not on merge. #### Scenario: Missing version, docs only -- **WHEN** a versioned-mode pull request has `docs/release`, no T and no `docs/.release-version` +- **WHEN** a versioned-mode `descriptor` pull request has `docs/release`, no T and no `docs/.release-version` - **THEN** the comment says the docs release will fail and asks to add the file before merging #### Scenario: Invalid version with a code release -- **WHEN** a versioned-mode pull request has `docs/release`, T and an invalid `docs/.release-version` +- **WHEN** a versioned-mode `descriptor` pull request has `docs/release`, T and an invalid `docs/.release-version` - **THEN** the comment says the docs release will fail when the code Release is published, not on merge ### Requirement: Combined code and docs release @@ -81,3 +81,25 @@ The preview SHALL post no comment on pull requests from forks, and on draft pull #### Scenario: Draft without label - **WHEN** a draft pull request has no `docs/release` label - **THEN** no comment is posted + +### Requirement: Preview by version source +The preview SHALL read the version source from `docs/package.json`. Under `descriptor` it SHALL NOT install dependencies. Under `github-release` it SHALL state that the docs are released when the code release publishes a GitHub Release, with no version, and that a `docs/release` label does not release them on merge. Under `tag-bump` it SHALL compute the version with `docouture release resolve` and state it as the version released if the pull request merged now, noting the version can change if another release lands first. + +#### Scenario: github-release +- **WHEN** a `github-release` pull request has `docs/release` +- **THEN** the comment says the docs follow the code release and names no version + +#### Scenario: tag-bump +- **WHEN** a `tag-bump` pull request has `docs/release-minor` and the latest tag is `docs/v1.2.3` +- **THEN** the comment says merging now releases `docs/v1.3.0`, and that the version can change if another release merges first + +#### Scenario: Descriptor stays cheap +- **WHEN** the version source is `descriptor` +- **THEN** the job runs no install step + +### Requirement: Bump labels trigger the preview +Under `tag-bump`, a pull request with `docs/release-minor` or `docs/release-major` SHALL be previewed like one with `docs/release`. + +#### Scenario: Minor label only +- **WHEN** a `tag-bump` pull request has `docs/release-minor` and no `docs/release` +- **THEN** the release preview is posted diff --git a/openspec/specs/docs-release-resolve/spec.md b/openspec/specs/docs-release-resolve/spec.md new file mode 100644 index 00000000..390410ed --- /dev/null +++ b/openspec/specs/docs-release-resolve/spec.md @@ -0,0 +1,116 @@ +# docs-release-resolve Specification + +## Purpose +Defines how `docouture release resolve` decides which docs version a release run targets, so the release and preview workflows share one validated source of truth instead of duplicated shell. + +## Requirements + +### Requirement: Resolve command interface +`docouture release resolve` SHALL accept the site mode (`versioned` or `standalone`), an optional explicit version, the repository root (default: cwd, or its enclosing repo), the event name, the published release tag and the pull request labels, and SHALL print the resolved version, the release tag, the source the version came from and the active version source. It SHALL expose these as `key=value` lines suitable for appending to `$GITHUB_OUTPUT`. It SHALL read the active version source from `docs/package.json`, defaulting to `descriptor`, and SHALL print whether the descriptor bump and prerelease sync apply. + +#### Scenario: Versioned, version from the descriptor +- **WHEN** it runs in `versioned` mode with source `descriptor`, without an explicit version, and `docs/.release-version` contains `1.2.0` +- **THEN** it reports version `1.2.0`, tag `docs/v1.2.0` and source `docs/.release-version`, says the descriptor steps apply, and exits 0 + +#### Scenario: Standalone +- **WHEN** it runs in `standalone` mode +- **THEN** it reports version `stable` and tag `docs/stable` regardless of any file, version source or explicit version, says the descriptor steps do not apply, and exits 0 + +### Requirement: Explicit version takes precedence +When an explicit version is supplied (the `workflow_dispatch` input), the command SHALL use it instead of `docs/.release-version`, and SHALL report its source as the explicit input. + +#### Scenario: Dispatch version +- **WHEN** it runs in `versioned` mode with explicit version `2.0.0` and `docs/.release-version` contains `1.2.0` +- **THEN** it reports version `2.0.0` + +### Requirement: Version validation +In `versioned` mode the command SHALL fail with a non-zero exit and a message naming the source when the resolved version is missing, equals `stable`, or is not valid SemVer 2.0.0. Prerelease and build-metadata suffixes SHALL be accepted; a leading `v` and a two-part version SHALL be rejected. + +#### Scenario: Missing file +- **WHEN** it runs in `versioned` mode with no explicit version and no `docs/.release-version` +- **THEN** it exits non-zero and says the file is missing + +#### Scenario: Invalid SemVer +- **WHEN** the resolved version is `v1.2` or `1.2` +- **THEN** it exits non-zero and says the version is not valid SemVer + +#### Scenario: Prerelease suffix +- **WHEN** the resolved version is `1.2.0-rc.1` +- **THEN** it exits 0 and reports tag `docs/v1.2.0-rc.1` + +#### Scenario: Reserved name +- **WHEN** versioned mode resolves the version `stable` +- **THEN** it exits non-zero and says `stable` is not a valid versioned version + +### Requirement: Descriptor is the default resolver +When `docs/package.json` declares no `versionSource`, or declares `descriptor`, the command SHALL resolve versions only from the explicit input or `docs/.release-version`, SHALL NOT read the GitHub Release tag, and SHALL say the descriptor bump and prerelease sync apply. A `release: published` run under `descriptor` therefore keeps reading `docs/.release-version`. + +#### Scenario: Release event +- **WHEN** a workflow runs the command for a `release: published` event, source `descriptor`, with no explicit version +- **THEN** the version comes from `docs/.release-version` + +### Requirement: Validation-only reporting +The command SHALL provide a mode that reports a validation failure as output (an error kind: missing or invalid) with exit 0, so the preview workflow can post a comment instead of failing the job. + +#### Scenario: Preview with a bad version +- **WHEN** the command runs in report mode with an invalid `docs/.release-version` +- **THEN** it exits 0 and reports the error kind `invalid` and the offending value + +### Requirement: Unknown version source +The command SHALL fail with exit 1, naming the valid values, when `versionSource` is not `descriptor`, `github-release` or `tag-bump`. + +#### Scenario: Typo +- **WHEN** `versionSource` is `tag_bump` +- **THEN** it exits non-zero and lists `descriptor`, `github-release` and `tag-bump` + +### Requirement: github-release resolver +Under `github-release` the version SHALL be the published release tag with `versionSourcePrefix` stripped when declared, and SHALL be validated as SemVer. A tag that does not start with the declared prefix SHALL fail. An explicit version SHALL still take precedence. A pull request event carrying `docs/release` SHALL fail with a message that explains the docs follow the code release and names the configured source. The descriptor steps SHALL NOT apply. + +#### Scenario: Plain tag +- **WHEN** the release tag is `1.4.0` and no prefix is declared +- **THEN** it reports version `1.4.0` and tag `docs/v1.4.0` + +#### Scenario: Prefixed tag +- **WHEN** the release tag is `docs-site@1.4.0` and the prefix is `docs-site@` +- **THEN** it reports version `1.4.0` + +#### Scenario: Wrong prefix +- **WHEN** the release tag is `other@1.4.0` and the prefix is `docs-site@` +- **THEN** it exits non-zero and says the tag does not start with the prefix + +#### Scenario: Release label on a merged PR +- **WHEN** a pull request event has `docs/release` and the source is `github-release` +- **THEN** it exits non-zero and says the docs release follows the code release + +### Requirement: tag-bump resolver +Under `tag-bump` the version SHALL be the highest existing `docs/v*` tag, by SemVer ordering including prerelease precedence, incremented by the bump the pull request labels select: `docs/release` patch, `docs/release-minor` minor and `docs/release-major` major, the highest bump winning when several labels are present. A bump from a prerelease tag SHALL follow `semver.inc`. An explicit version SHALL take precedence over any bump. The descriptor steps SHALL NOT apply. + +#### Scenario: Implicit patch +- **WHEN** the latest tag is `docs/v1.2.3` and only `docs/release` is present +- **THEN** it reports version `1.2.4` + +#### Scenario: Minor and major labels +- **WHEN** both `docs/release-minor` and `docs/release-major` are present on top of `docs/v1.2.3` +- **THEN** it reports version `2.0.0` + +#### Scenario: Prerelease ordering +- **WHEN** the tags are `docs/v1.2.0-rc.1` and `docs/v1.1.9` +- **THEN** the latest is `1.2.0-rc.1` and a patch bump reports `1.2.0` + +#### Scenario: Explicit version +- **WHEN** `--version 3.0.0` is passed on top of `docs/v1.2.3` +- **THEN** it reports version `3.0.0` without bumping + +### Requirement: tag-bump without a tag +Under `tag-bump` with no existing `docs/v*` tag and no explicit version, the command SHALL fail saying an explicit version is needed for the first release, for example through `workflow_dispatch`. + +#### Scenario: First release +- **WHEN** no `docs/v*` tag exists and no version is given +- **THEN** it exits non-zero and asks for an explicit version + +### Requirement: Descriptor-only steps signal +The command SHALL print `uses_descriptor=true` only when the mode is versioned and the source is `descriptor`, so a workflow runs the descriptor bump and the prerelease sync only then. + +#### Scenario: tag-bump +- **WHEN** the source is `tag-bump` +- **THEN** it prints `uses_descriptor=false` diff --git a/openspec/specs/docs-version-source/spec.md b/openspec/specs/docs-version-source/spec.md new file mode 100644 index 00000000..f5d90fee --- /dev/null +++ b/openspec/specs/docs-version-source/spec.md @@ -0,0 +1,65 @@ +# docs-version-source Specification + +## Purpose +Defines how a versioned docouture site declares where its docs release version comes from, and how the CLI scaffolds, backfills, checks and switches that declaration. + +## Requirements + +### Requirement: Version source declaration +The `docouture` block of `docs/package.json` SHALL be able to declare `versionSource` as `descriptor`, `github-release` or `tag-bump`. An absent `versionSource` SHALL mean `descriptor`. When `versionSource` is `github-release` the block MAY declare `versionSourcePrefix`, a string stripped from the start of a release tag. `versionSource` SHALL be placed after `branching` and `prereleaseBranch` and other keys SHALL keep their order. + +#### Scenario: Absent value +- **WHEN** `docs/package.json` has no `versionSource` +- **THEN** the site is treated as `descriptor` + +#### Scenario: Unknown value +- **WHEN** `versionSource` is any other string +- **THEN** commands that read it fail naming the three valid values + +### Requirement: new scaffolds the source +In versioned mode `docouture new` SHALL ask which version source to use, with each option explained and `descriptor` as the default, and SHALL accept `--version-source <source>` to skip the prompt. It SHALL write the choice to `docs/package.json` and create `docs/.release-version` only for `descriptor`. For `tag-bump` it SHALL print the exact `gh label create` commands for `docs/release-minor` and `docs/release-major` and SHALL NOT call the GitHub API. In standalone mode it SHALL neither prompt for nor accept a version source. + +#### Scenario: Default +- **WHEN** a versioned site is scaffolded without choosing a source +- **THEN** `versionSource` is `descriptor` and `docs/.release-version` exists + +#### Scenario: tag-bump +- **WHEN** a versioned site is scaffolded with `--version-source tag-bump` +- **THEN** no `docs/.release-version` is created and the label commands are printed + +#### Scenario: Standalone +- **WHEN** `--version-source` is passed for a standalone site +- **THEN** the command fails saying standalone sites have no version source + +### Requirement: upgrade backfills the source +`docouture upgrade` on a versioned site without `versionSource` SHALL write `"versionSource": "descriptor"`, print what it changed and point at `docouture version-source`, without prompting. It SHALL be idempotent, SHALL NOT change an existing `versionSource` and SHALL NOT touch standalone sites. When the running CLI version differs from the version resolved by the project it SHALL warn. + +#### Scenario: Legacy versioned site +- **WHEN** a versioned site's `package.json` lacks `versionSource` +- **THEN** upgrade writes `descriptor` and reports it + +#### Scenario: Second run +- **WHEN** upgrade runs again +- **THEN** `package.json` is unchanged + +### Requirement: version-source command +`docouture version-source [descriptor|github-release|tag-bump]` SHALL refuse a standalone site, set `versionSource`, and per target: for `descriptor` create `docs/.release-version` seeded with the next patch of the latest `docs/v*` tag, or with `--version`; for `github-release` and `tag-bump` remove `docs/.release-version`, warning when it held a pending value, and for `tag-bump` print the `gh label create` commands. `--dry-run` SHALL report what would change without writing. It SHALL be idempotent. + +#### Scenario: Switch to tag-bump +- **WHEN** a `descriptor` site holding `1.3.0` in `.release-version` is switched to `tag-bump` +- **THEN** the file is removed, a warning names the pending `1.3.0`, and the label commands are printed + +#### Scenario: Switch back +- **WHEN** a `tag-bump` site is switched to `descriptor` and the latest tag is `docs/v1.2.4` +- **THEN** `.release-version` is created containing `1.2.5` + +#### Scenario: Dry run +- **WHEN** `--dry-run` is passed +- **THEN** nothing is written and the planned changes are listed + +### Requirement: doctor reports the source +`docouture doctor` SHALL show the active version source and SHALL warn when `github-release` or `tag-bump` still has `docs/.release-version`, when `descriptor` has no such file, and when the installed CLI does not support `release resolve`, each with the fix. + +#### Scenario: Stray descriptor +- **WHEN** `versionSource` is `tag-bump` and `docs/.release-version` exists +- **THEN** doctor warns and suggests `docouture version-source tag-bump` diff --git a/skills/docouture-docs-versioning/SKILL.md b/skills/docouture-docs-versioning/SKILL.md index a1c80734..468f4e03 100644 --- a/skills/docouture-docs-versioning/SKILL.md +++ b/skills/docouture-docs-versioning/SKILL.md @@ -1,6 +1,6 @@ --- name: docouture-docs-versioning -description: "How to cut a release or a prerelease on a docouture Antora documentation site scaffolded with Versioned (Full History) mode: docouture version, docs/.release-version, and the docouture-release.yml workflow. USE WHEN bumping a version, cutting a release, configuring what a release tag contains, or asking how versioning works on this site. EXAMPLES: 'cut a release', 'bump the docs version', 'what does docs/.release-version do', 'how do I release a new version of the docs'." +description: "How to cut a release or a prerelease on a docouture Antora documentation site scaffolded with Versioned (Full History) mode: docouture version, docs/.release-version and its alternatives (docouture version-source: github-release, tag-bump), and the docouture-release.yml workflow. USE WHEN bumping a version, cutting a release, configuring what a release tag contains, or asking how versioning works on this site. EXAMPLES: 'cut a release', 'bump the docs version', 'what does docs/.release-version do', 'how do I release a new version of the docs'." --- # Docs versioning (Versioned — Full History) @@ -38,3 +38,11 @@ a release tag, and what the release workflow actually does). - On a git-flow site the workflow also opens a sync pull request from the release branch into the prerelease branch (`docs/package.json`'s `docouture.prereleaseBranch`) to carry that bump over — merge it. +- **Where the version comes from is configurable.** `docouture.versionSource` in + `docs/package.json` is `descriptor` (the default, everything above), `github-release` + (the published GitHub Release's tag, optionally minus `docouture.versionSourcePrefix`) or + `tag-bump` (the latest `docs/v*` tag plus a bump: `docs/release` patch, + `docs/release-minor` minor, `docs/release-major` major). Only `descriptor` uses + `docs/.release-version`, the post-release bump and the git-flow sync. Show or change it + with `docouture version-source [source]`; `docouture new --mode versioned` asks for it. + See `reference/releasing.md`. diff --git a/skills/docouture-docs-versioning/reference/releasing.md b/skills/docouture-docs-versioning/reference/releasing.md index 2af90bd7..76c8720b 100644 --- a/skills/docouture-docs-versioning/reference/releasing.md +++ b/skills/docouture-docs-versioning/reference/releasing.md @@ -74,7 +74,34 @@ advanced or touched by this step; its own `docs/src/antora.yml` permanently keep released version, e.g. a docs typo caught after the tag went out) is a deliberate, ordinary act, not something needing a separate flag. -## `docs/.release-version` after a release +## Version sources + +`docs/package.json`'s `docouture.versionSource` picks where the version comes from; +`docouture release resolve` implements all three for both workflows (release and preview). + +| source | version | notes | +| --- | --- | --- | +| `descriptor` (default) | `docs/.release-version` | the post-release bump and the git-flow sync below apply only here | +| `github-release` | tag of the published GitHub Release, minus `docouture.versionSourcePrefix` | a merged `docs/release` PR fails with a clear message; no version file | +| `tag-bump` | highest `docs/v*` tag + bump | `docs/release` patch, `docs/release-minor` minor, `docs/release-major` major (highest wins); semver-aware, prerelease tags included; the first release needs an explicit version via `workflow_dispatch`; no version file | + +`docouture version-source [descriptor|github-release|tag-bump] [--prefix <p>] [--version <v>] +[--dry-run]` shows or changes it (refuses standalone sites): `descriptor` creates +`docs/.release-version` seeded with the next patch of the latest tag, the others remove it +(warning if it held a pending value), and `tag-bump` prints the `gh label create` commands +for the two extra labels. Workflows read the source at run time, so none are re-rendered, but +they run the project's installed CLI: bump `@inditextech/docouture-cli` and install first, +then `docouture upgrade` (writes `"versionSource": "descriptor"` where missing), then +optionally `docouture version-source`. `docouture doctor` shows the active source and warns +about a stray or missing `.release-version` and about a CLI without `release resolve`. + +The preview comment follows the source: `descriptor` reads the file (no install), +`github-release` says the docs follow the code release without a version, and `tag-bump` +shows the version released if the PR merged now (it can change if another release lands +first). Under `tag-bump`, a run started by a published GitHub Release has no PR labels, so it +bumps patch; use `workflow_dispatch` with an explicit version for a minor or major bump there. + +## `docs/.release-version` after a release (`descriptor` only) Nothing clears it — it's bumped forward instead, except on a republish. On a genuine forward release (the target tag was new), a final step in the workflow advances the file From 2244ec9e2972cb9af14537661eddac885de582dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= <jesusmpc@inditex.com> Date: Wed, 11 Nov 2026 16:10:41 +0100 Subject: [PATCH 3/4] [cli] Format the new spec files with prettier --- code/packages/cli/src/commands/new.spec.ts | 25 +++++++++++++------ .../packages/cli/src/commands/release.spec.ts | 24 ++++++++++++++++-- .../cli/src/commands/version-source.spec.ts | 9 +++++-- code/packages/cli/src/lib/project-cli.spec.ts | 10 ++++++-- 4 files changed, 55 insertions(+), 13 deletions(-) diff --git a/code/packages/cli/src/commands/new.spec.ts b/code/packages/cli/src/commands/new.spec.ts index e147955a..a48a51ed 100644 --- a/code/packages/cli/src/commands/new.spec.ts +++ b/code/packages/cli/src/commands/new.spec.ts @@ -532,12 +532,15 @@ describe('runNew', () => { expect((await readFile(join(repo, 'docs', '.release-version'), 'utf8')).trim()).toBe('0.1.0') }) - it.each(['github-release', 'tag-bump'])('%s declares the source and lays down no .release-version', async (source) => { - const { code, repo } = await scaffoldVersioned(['--version-source', source]) - expect(code).toBe(0) - expect((await declared(repo))?.versionSource).toBe(source) - await expect(readFile(join(repo, 'docs', '.release-version'), 'utf8')).rejects.toThrow() - }) + it.each(['github-release', 'tag-bump'])( + '%s declares the source and lays down no .release-version', + async (source) => { + const { code, repo } = await scaffoldVersioned(['--version-source', source]) + expect(code).toBe(0) + expect((await declared(repo))?.versionSource).toBe(source) + await expect(readFile(join(repo, 'docs', '.release-version'), 'utf8')).rejects.toThrow() + } + ) it('prints the exact label commands for tag-bump', async () => { await scaffoldVersioned(['--version-source', 'tag-bump']) @@ -555,7 +558,15 @@ describe('runNew', () => { it('rejects a standalone site', async () => { const repo = join(base, 'repo') await initRepo(repo) - const code = await runNew(['my-project-docs', '--dir', repo, '--mode', 'standalone', '--version-source', 'tag-bump']) + const code = await runNew([ + 'my-project-docs', + '--dir', + repo, + '--mode', + 'standalone', + '--version-source', + 'tag-bump', + ]) expect(code).toBe(1) expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('standalone')) }) diff --git a/code/packages/cli/src/commands/release.spec.ts b/code/packages/cli/src/commands/release.spec.ts index 22441fab..e195f79c 100644 --- a/code/packages/cli/src/commands/release.spec.ts +++ b/code/packages/cli/src/commands/release.spec.ts @@ -109,7 +109,17 @@ describe('runRelease resolve', () => { it('resolves github-release from the release tag, stripping the prefix', async () => { await writeSource({ versionSource: 'github-release', versionSourcePrefix: 'docs-site@' }) - const argv = ['resolve', '--mode', 'versioned', '--event', 'release', '--release-tag', 'docs-site@1.4.0', '--dir', dir] + const argv = [ + 'resolve', + '--mode', + 'versioned', + '--event', + 'release', + '--release-tag', + 'docs-site@1.4.0', + '--dir', + dir, + ] expect(await runRelease(argv)).toBe(0) expect(out()).toContain('version=1.4.0') expect(out()).toContain('version_source=github-release') @@ -118,7 +128,17 @@ describe('runRelease resolve', () => { it('fails a docs/release pull request under github-release', async () => { await writeSource({ versionSource: 'github-release' }) - const argv = ['resolve', '--mode', 'versioned', '--event', 'pull_request', '--labels', 'docs/release', '--dir', dir] + const argv = [ + 'resolve', + '--mode', + 'versioned', + '--event', + 'pull_request', + '--labels', + 'docs/release', + '--dir', + dir, + ] expect(await runRelease(argv)).toBe(1) expect(errorSpy.mock.calls.flat().join('\n')).toContain('github-release') }) diff --git a/code/packages/cli/src/commands/version-source.spec.ts b/code/packages/cli/src/commands/version-source.spec.ts index 168aba52..23a428cb 100644 --- a/code/packages/cli/src/commands/version-source.spec.ts +++ b/code/packages/cli/src/commands/version-source.spec.ts @@ -23,7 +23,9 @@ function git(...args: string[]): void { execFileSync('git', args, { cwd: dir, stdio: 'ignore' }) // NOSONAR } -async function scaffold(options: { mode?: 'versioned' | 'standalone'; docouture?: Record<string, unknown>; descriptor?: string } = {}) { +async function scaffold( + options: { mode?: 'versioned' | 'standalone'; docouture?: Record<string, unknown>; descriptor?: string } = {} +) { const { mode = 'versioned', docouture = { branching: 'trunk-based' }, descriptor } = options await mkdir(join(dir, 'docs'), { recursive: true }) await writeFile( @@ -110,7 +112,10 @@ describe('runVersionSource', () => { it('sets the github-release prefix and only for that source', async () => { await scaffold() expect(await runVersionSource(['github-release', '--prefix', 'docs-site@', '--dir', dir])).toBe(0) - expect((await pkg()).docouture).toMatchObject({ versionSource: 'github-release', versionSourcePrefix: 'docs-site@' }) + expect((await pkg()).docouture).toMatchObject({ + versionSource: 'github-release', + versionSourcePrefix: 'docs-site@', + }) expect(await runVersionSource(['tag-bump', '--prefix', 'x', '--dir', dir])).toBe(1) }) diff --git a/code/packages/cli/src/lib/project-cli.spec.ts b/code/packages/cli/src/lib/project-cli.spec.ts index cff057cd..983c6bc2 100644 --- a/code/packages/cli/src/lib/project-cli.spec.ts +++ b/code/packages/cli/src/lib/project-cli.spec.ts @@ -40,12 +40,18 @@ describe('readProjectCli', () => { }) it('falls back to an exact pin in package.json', async () => { - await writeFile(join(site, 'package.json'), JSON.stringify({ devDependencies: { '@inditextech/docouture-cli': '1.3.2' } })) + await writeFile( + join(site, 'package.json'), + JSON.stringify({ devDependencies: { '@inditextech/docouture-cli': '1.3.2' } }) + ) expect(await readProjectCli(site, root)).toEqual({ version: '1.3.2', hasReleaseResolve: null, from: 'declared' }) }) it('ignores a range it cannot compare', async () => { - await writeFile(join(site, 'package.json'), JSON.stringify({ devDependencies: { '@inditextech/docouture-cli': '^1.3.2' } })) + await writeFile( + join(site, 'package.json'), + JSON.stringify({ devDependencies: { '@inditextech/docouture-cli': '^1.3.2' } }) + ) expect((await readProjectCli(site, root)).version).toBeNull() }) From 92b996a9650bb156d01d724d63d56cfda04eecbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= <jesusmpc@inditex.com> Date: Wed, 11 Nov 2026 16:36:45 +0100 Subject: [PATCH 4/4] [cli] Fix SonarCloud findings and reduce complexity in the new commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Keep the NOSONAR for S4036 on the execFile call line in docs-tags.ts - Split release resolve, version-source and new into small helpers - Replace the long SemVer regex with an isSemver parser, and simplify compareSemver - Read the installed CLI candidates in parallel in project-cli.ts - version-source with no argument now fails on an unknown declared source Signed-off-by: Jesus Manuel Piñeiro Cid <jesusmpc@inditex.com> --- code/packages/cli/src/commands/new.ts | 87 +++--- code/packages/cli/src/commands/release.ts | 130 +++++---- .../cli/src/commands/version-source.spec.ts | 6 + .../cli/src/commands/version-source.ts | 251 ++++++++++++------ code/packages/cli/src/lib/docs-tags.ts | 8 +- code/packages/cli/src/lib/project-cli.ts | 27 +- .../cli/src/lib/release-resolve.spec.ts | 11 +- code/packages/cli/src/lib/release-resolve.ts | 6 +- code/packages/cli/src/lib/semver.spec.ts | 41 ++- code/packages/cli/src/lib/semver.ts | 107 +++++--- 10 files changed, 447 insertions(+), 227 deletions(-) diff --git a/code/packages/cli/src/commands/new.ts b/code/packages/cli/src/commands/new.ts index d377245e..6dcbb968 100644 --- a/code/packages/cli/src/commands/new.ts +++ b/code/packages/cli/src/commands/new.ts @@ -516,6 +516,51 @@ function parseEnumFlag<T extends string>( return { value: raw as T, error: null } } +interface EnumFlags { + mode: Mode | undefined + branching: Branching | undefined + versionSource: VersionSource | undefined + pmChoice: PackageManager | undefined + error: string | null +} + +// The four enum-valued flags (--mode, --flow, --version-source, --pm), each +// either absent, a valid member, or an error to print verbatim. +function parseEnumFlags(flags: Record<string, string | boolean>): EnumFlags { + const mode = parseEnumFlag(flags, 'mode', MODES, "'standalone' or 'versioned'") + const flow = parseEnumFlag(flags, 'flow', BRANCH_MODELS, "'trunk-based' or 'git-flow'") + const versionSource = parseEnumFlag( + flags, + 'version-source', + VERSION_SOURCES, + "'descriptor', 'github-release' or 'tag-bump'" + ) + const pm = parseEnumFlag(flags, 'pm', PACKAGE_MANAGERS, "'npm' or 'pnpm'") + return { + mode: mode.value, + branching: flow.value, + versionSource: versionSource.value, + pmChoice: pm.value, + error: mode.error ?? flow.error ?? versionSource.error ?? pm.error, + } +} + +// A version source only exists for versioned sites: standalone rejects one, +// versioned defaults to `descriptor`. +function resolveVersionSource( + mode: Mode, + versionSource: VersionSource | undefined +): { value: VersionSource | undefined; error: string | null } { + if (mode === 'standalone') { + const error = + versionSource === undefined + ? null + : "--version-source only applies to versioned sites: a standalone site has no docs version source\n(standalone releases always target the 'docs/stable' tag)" + return { value: undefined, error } + } + return { value: versionSource ?? 'descriptor', error: null } +} + export async function runNew(argv: string[], io: NewIO = defaultIO()): Promise<number> { const { positional, flags } = parseArgs(argv) @@ -542,38 +587,12 @@ export async function runNew(argv: string[], io: NewIO = defaultIO()): Promise<n const integrationBranchFlag = stringFlag(flags, 'integration-branch') const releaseBranchFlag = stringFlag(flags, 'release-branch') - const modeFlag = parseEnumFlag(flags, 'mode', MODES, "'standalone' or 'versioned'") - if (modeFlag.error) { - console.error(modeFlag.error) - return 1 - } - let mode = modeFlag.value - - const flowFlag = parseEnumFlag(flags, 'flow', BRANCH_MODELS, "'trunk-based' or 'git-flow'") - if (flowFlag.error) { - console.error(flowFlag.error) - return 1 - } - let branching = flowFlag.value - - const versionSourceFlag = parseEnumFlag( - flags, - 'version-source', - VERSION_SOURCES, - "'descriptor', 'github-release' or 'tag-bump'" - ) - if (versionSourceFlag.error) { - console.error(versionSourceFlag.error) - return 1 - } - let versionSource = versionSourceFlag.value - - const pmFlag = parseEnumFlag(flags, 'pm', PACKAGE_MANAGERS, "'npm' or 'pnpm'") - if (pmFlag.error) { - console.error(pmFlag.error) + const enumFlags = parseEnumFlags(flags) + if (enumFlags.error) { + console.error(enumFlags.error) return 1 } - let pmChoice = pmFlag.value + let { mode, branching, versionSource, pmChoice } = enumFlags // Best-effort guess for the wizard's own default (an existing // packageManager field/lockfile at --dir/cwd, or how docouture itself was @@ -625,12 +644,12 @@ export async function runNew(argv: string[], io: NewIO = defaultIO()): Promise<n mode = mode ?? 'standalone' branching = branching ?? 'trunk-based' - if (mode === 'standalone' && versionSource !== undefined) { - console.error('--version-source only applies to versioned sites: a standalone site has no docs version source') - console.error("(standalone releases always target the 'docs/stable' tag)") + const versionSourceChoice = resolveVersionSource(mode, versionSource) + if (versionSourceChoice.error) { + console.error(versionSourceChoice.error) return 1 } - if (mode === 'versioned') versionSource = versionSource ?? 'descriptor' + versionSource = versionSourceChoice.value pmChoice = pmChoice ?? pmGuess urlSegment = urlSegment ?? false // '' (explicitly skipped) -> undefined; not given at all -> derived default. diff --git a/code/packages/cli/src/commands/release.ts b/code/packages/cli/src/commands/release.ts index 69a6d298..a3dda466 100644 --- a/code/packages/cli/src/commands/release.ts +++ b/code/packages/cli/src/commands/release.ts @@ -11,12 +11,77 @@ import { parseArgs } from '../lib/args.js' import { exists } from '../lib/copy-template.js' import { listDocsTags } from '../lib/docs-tags.js' import { findRepoRoot } from '../lib/repo-root.js' -import { readVersionSourceDeclaration } from '../lib/package-version-source.js' -import { type ReleaseMode, resolveRelease, VERSION_SOURCES } from '../lib/release-resolve.js' +import { readVersionSourceDeclaration, type VersionSourceDeclaration } from '../lib/package-version-source.js' +import { + type ReleaseMode, + type ReleaseResolution, + resolveRelease, + VERSION_SOURCES, + type VersionSource, +} from '../lib/release-resolve.js' const USAGE = 'usage: docouture release resolve --mode <versioned|standalone> [--version <v>] [--event <name>] [--release-tag <tag>] [--labels <a,b>] [--tags <a,b>] [--report] [--dir <path>]' +type Flags = Record<string, string | boolean> + +function stringFlag(flags: Flags, name: string): string | undefined { + const value = flags[name] + return typeof value === 'string' ? value : undefined +} + +// A comma- (or, with `newlines`, newline-) separated flag value as a clean list. +function listFlag(value: string | undefined, separator: RegExp): string[] | undefined { + if (value === undefined) return undefined + return value + .split(separator) + .map((item) => item.trim()) + .filter((item) => item !== '') +} + +async function readDescriptor(repoRoot: string): Promise<string | null> { + const file = join(repoRoot, 'docs', '.release-version') + return (await exists(file)) ? await readFile(file, 'utf8') : null +} + +async function readDeclaration(repoRoot: string): Promise<VersionSourceDeclaration> { + const file = join(repoRoot, 'docs', 'package.json') + if (!(await exists(file))) return { raw: null, source: 'descriptor', prefix: null } + return readVersionSourceDeclaration(file) +} + +function warnIgnoredStandaloneVersion(mode: ReleaseMode, explicit: string | undefined): void { + if (mode !== 'standalone' || explicit === undefined || explicit === 'stable') return + console.error( + `::warning::Standalone mode always releases to the 'stable' tag — ignoring provided version '${explicit}'.` + ) +} + +// Only a versioned `tag-bump` run reads tags. --tags injects the names (comma- +// or newline-separated) for callers with no local tags to list, such as a +// shallow checkout without credentials. +async function resolveTags( + mode: ReleaseMode, + source: VersionSource, + injected: string[] | undefined, + repoRoot: string +): Promise<string[]> { + if (mode !== 'versioned' || source !== 'tag-bump') return [] + return injected ?? (await listDocsTags(repoRoot)) +} + +function printResult(result: ReleaseResolution, mode: ReleaseMode, source: VersionSource): void { + console.log(`version=${result.version}`) + console.log(`tag=${result.tag}`) + console.log(`source=${result.source}`) + console.log(`version_source=${mode === 'standalone' ? 'standalone' : source}`) + console.log(`uses_descriptor=${result.usesDescriptor === true}`) + if (result.error) { + console.log(`error=${result.error.kind}`) + console.log(`error_value=${result.error.value}`) + } +} + async function runResolve(argv: string[]): Promise<number> { const { flags } = parseArgs(argv) @@ -27,17 +92,11 @@ async function runResolve(argv: string[]): Promise<number> { return 1 } - const explicit = typeof flags.version === 'string' ? flags.version : undefined - const report = flags.report === true + const explicit = stringFlag(flags, 'version') const startDir = typeof flags.dir === 'string' ? resolve(flags.dir) : resolve(process.cwd()) const repoRoot = await findRepoRoot(startDir) - const descriptorFile = join(repoRoot, 'docs', '.release-version') - const descriptor = (await exists(descriptorFile)) ? await readFile(descriptorFile, 'utf8') : null - const packageJsonFile = join(repoRoot, 'docs', 'package.json') - const declaration = (await exists(packageJsonFile)) - ? await readVersionSourceDeclaration(packageJsonFile) - : { raw: null, source: 'descriptor' as const, prefix: null } + const declaration = await readDeclaration(repoRoot) if (declaration.source === null) { console.error( `::error::docs/package.json declares docouture.versionSource '${declaration.raw}' — expected one of: ${VERSION_SOURCES.join(', ')}` @@ -45,58 +104,27 @@ async function runResolve(argv: string[]): Promise<number> { return 1 } const source = declaration.source - const event = typeof flags.event === 'string' ? flags.event : undefined - const releaseTag = typeof flags['release-tag'] === 'string' ? flags['release-tag'] : undefined - const labels = - typeof flags.labels === 'string' - ? flags.labels - .split(',') - .map((label) => label.trim()) - .filter((label) => label !== '') - : [] - // --tags injects the tag names (comma- or newline-separated) for callers with - // no local tags to list, such as a shallow checkout without credentials. - const injectedTags = - typeof flags.tags === 'string' - ? flags.tags - .split(/[,\n]/) - .map((tag) => tag.trim()) - .filter((tag) => tag !== '') - : undefined - const tags = source === 'tag-bump' && mode === 'versioned' ? (injectedTags ?? (await listDocsTags(repoRoot))) : [] - - if (mode === 'standalone' && explicit !== undefined && explicit !== 'stable') { - console.error( - `::warning::Standalone mode always releases to the 'stable' tag — ignoring provided version '${explicit}'.` - ) - } + + warnIgnoredStandaloneVersion(mode, explicit) const result = resolveRelease({ - mode: mode as ReleaseMode, + mode, explicit, - descriptor, + descriptor: await readDescriptor(repoRoot), source, - event, - releaseTag, + event: stringFlag(flags, 'event'), + releaseTag: stringFlag(flags, 'release-tag'), prefix: declaration.prefix ?? undefined, - labels, - tags, + labels: listFlag(stringFlag(flags, 'labels'), /,/) ?? [], + tags: await resolveTags(mode, source, listFlag(stringFlag(flags, 'tags'), /[,\n]/), repoRoot), }) - if (result.error && !report) { + if (result.error && flags.report !== true) { console.error(`::error::${result.error.message}`) return 1 } - console.log(`version=${result.version}`) - console.log(`tag=${result.tag}`) - console.log(`source=${result.source}`) - console.log(`version_source=${mode === 'standalone' ? 'standalone' : source}`) - console.log(`uses_descriptor=${result.usesDescriptor === true}`) - if (result.error) { - console.log(`error=${result.error.kind}`) - console.log(`error_value=${result.error.value}`) - } + printResult(result, mode, source) return 0 } diff --git a/code/packages/cli/src/commands/version-source.spec.ts b/code/packages/cli/src/commands/version-source.spec.ts index 23a428cb..571e8073 100644 --- a/code/packages/cli/src/commands/version-source.spec.ts +++ b/code/packages/cli/src/commands/version-source.spec.ts @@ -64,6 +64,12 @@ describe('runVersionSource', () => { expect(output(logSpy)).toContain('version source: tag-bump') }) + it('fails naming the valid values when the declared source is unknown', async () => { + await scaffold({ docouture: { branching: 'trunk-based', versionSource: 'tag_bump' } }) + expect(await runVersionSource(['--dir', dir])).toBe(1) + expect(output(errorSpy)).toContain('descriptor, github-release, tag-bump') + }) + it('refuses a standalone site', async () => { await scaffold({ mode: 'standalone' }) expect(await runVersionSource(['tag-bump', '--dir', dir])).toBe(1) diff --git a/code/packages/cli/src/commands/version-source.ts b/code/packages/cli/src/commands/version-source.ts index 53a983bb..46e281c4 100644 --- a/code/packages/cli/src/commands/version-source.ts +++ b/code/packages/cli/src/commands/version-source.ts @@ -11,11 +11,15 @@ import { join, relative, resolve } from 'node:path' import { parseArgs } from '../lib/args.js' import { exists } from '../lib/copy-template.js' import { listDocsTags } from '../lib/docs-tags.js' -import { readVersionSourceDeclaration, setVersionSource } from '../lib/package-version-source.js' +import { + readVersionSourceDeclaration, + setVersionSource, + type VersionSourceDeclaration, +} from '../lib/package-version-source.js' import { printTagBumpLabelCommands } from '../lib/release-labels.js' -import { parseVersionSource, SEMVER_RE, TAG_PREFIX, VERSION_SOURCES } from '../lib/release-resolve.js' +import { parseVersionSource, TAG_PREFIX, VERSION_SOURCES, type VersionSource } from '../lib/release-resolve.js' import { findRepoRoot } from '../lib/repo-root.js' -import { bumpVersion, highestSemver } from '../lib/semver.js' +import { bumpVersion, highestSemver, isSemver } from '../lib/semver.js' import { detectSiteMode } from '../lib/site-mode.js' const USAGE = @@ -45,125 +49,212 @@ async function seedVersion(repoRoot: string, explicit: string | undefined): Prom return latest === null ? FIRST_VERSION : bumpVersion(latest, 'patch') } -export async function runVersionSource(argv: string[]): Promise<number> { - const { positional, flags } = parseArgs(argv) +interface Invocation { + target: VersionSource | null + dryRun: boolean + explicitVersion: string | undefined + prefix: string | undefined + startDir: string +} - const dryRun = flags['dry-run'] === true +type Parsed = { ok: true; invocation: Invocation } | { ok: false; errors: string[] } + +function parseInvocation(argv: string[]): Parsed { + const { positional, flags } = parseArgs(argv) const explicitVersion = typeof flags.version === 'string' ? flags.version : undefined const prefix = typeof flags.prefix === 'string' ? flags.prefix : undefined - const startDir = typeof flags.dir === 'string' ? resolve(flags.dir) : resolve(process.cwd()) - const targetArg = positional[0] const target = targetArg === undefined ? null : parseVersionSource(targetArg) + if (targetArg !== undefined && target === null) { - console.error(USAGE) - console.error(`invalid source: '${targetArg}' — expected one of: ${VERSION_SOURCES.join(', ')}`) - return 1 + return { + ok: false, + errors: [USAGE, `invalid source: '${targetArg}' — expected one of: ${VERSION_SOURCES.join(', ')}`], + } } - - if (explicitVersion !== undefined && !SEMVER_RE.test(explicitVersion)) { - console.error(`--version '${explicitVersion}' is not a valid SemVer version like 1.2.0`) - return 1 + if (explicitVersion !== undefined && !isSemver(explicitVersion)) { + return { ok: false, errors: [`--version '${explicitVersion}' is not a valid SemVer version like 1.2.0`] } } + if (prefix !== undefined && target !== 'github-release') { + return { ok: false, errors: ['--prefix only applies to the github-release source'] } + } + const startDir = typeof flags.dir === 'string' ? resolve(flags.dir) : resolve(process.cwd()) + return { ok: true, invocation: { target, dryRun: flags['dry-run'] === true, explicitVersion, prefix, startDir } } +} + +interface Site { + repoRoot: string + siteRoot: string + packageJsonFile: string +} +type Located = { ok: true; site: Site } | { ok: false; errors: string[] } + +// Finds the repository and its versioned site; every other outcome is an +// error naming what is wrong (not a git repo, no site, standalone, unknown). +async function locateSite(startDir: string): Promise<Located> { if (!isInsideGitWorkTree(startDir)) { - console.error(`'${startDir}' is not inside a git repository`) - console.error( - 'docouture version-source re-configures an already-scaffolded repository — run it from your repo root, or pass --dir <path> to one' - ) - return 1 + return { + ok: false, + errors: [ + `'${startDir}' is not inside a git repository`, + 'docouture version-source re-configures an already-scaffolded repository — run it from your repo root, or pass --dir <path> to one', + ], + } } - const repoRoot = await findRepoRoot(startDir) const siteRoot = join(repoRoot, 'docs') const packageJsonFile = join(siteRoot, 'package.json') if (!(await exists(packageJsonFile))) { - console.error(`no site found at '${siteRoot}'`) - console.error('pass --dir <path> to a component root (the parent of docs/), or run docouture new first') - return 1 + return { + ok: false, + errors: [ + `no site found at '${siteRoot}'`, + 'pass --dir <path> to a component root (the parent of docs/), or run docouture new first', + ], + } } - const mode = await detectSiteMode(siteRoot) if (mode === 'standalone') { - console.error('this is a standalone (Stable + Prerelease) site — it has no docs version source') - console.error("standalone releases always target the 'docs/stable' tag; only versioned sites choose a source") - return 1 + return { + ok: false, + errors: [ + 'this is a standalone (Stable + Prerelease) site — it has no docs version source', + "standalone releases always target the 'docs/stable' tag; only versioned sites choose a source", + ], + } } if (mode === null) { - console.error("could not tell whether this site is versioned or standalone from docs/antora-playbook.yml's tags") - console.error('is this a docouture-scaffolded site? (run docouture new first, or check --dir)') - return 1 + return { + ok: false, + errors: [ + "could not tell whether this site is versioned or standalone from docs/antora-playbook.yml's tags", + 'is this a docouture-scaffolded site? (run docouture new first, or check --dir)', + ], + } } + return { ok: true, site: { repoRoot, siteRoot, packageJsonFile } } +} - const declaration = await readVersionSourceDeclaration(packageJsonFile) - if (target === null) { - console.log(`version source: ${declaration.source ?? `${declaration.raw} (invalid)`}`) - if (declaration.prefix) console.log(`prefix: ${declaration.prefix}`) - return 0 +interface Plan { + steps: string[] + warnings: string[] + // Version to write to docs/.release-version, when it is to be (re)written. + seed: string | null + removeDescriptor: boolean +} + +async function planDescriptor(site: Site, invocation: Invocation, descriptorExists: boolean): Promise<Plan> { + const { explicitVersion } = invocation + if (!descriptorExists || explicitVersion !== undefined) { + const seed = await seedVersion(site.repoRoot, explicitVersion) + const verb = descriptorExists ? 'overwrite' : 'create' + return { + steps: [`${verb} ${relative(site.repoRoot, join(site.siteRoot, '.release-version'))} with ${seed}`], + warnings: [], + seed, + removeDescriptor: false, + } } + return { steps: [], warnings: [], seed: null, removeDescriptor: false } +} - if (prefix !== undefined && target !== 'github-release') { - console.error('--prefix only applies to the github-release source') - return 1 +async function planRemoval(site: Site, descriptorExists: boolean): Promise<Plan> { + if (!descriptorExists) return { steps: [], warnings: [], seed: null, removeDescriptor: false } + const file = join(site.siteRoot, '.release-version') + const rel = relative(site.repoRoot, file) + const pending = (await readFile(file, 'utf8')).trim() + return { + steps: [`remove ${rel}`], + warnings: pending === '' ? [] : [`${rel} held the pending version '${pending}', which is discarded`], + seed: null, + removeDescriptor: true, } +} - const descriptorFile = join(siteRoot, '.release-version') - const descriptorExists = await exists(descriptorFile) - const rel = (path: string): string => relative(repoRoot, path) +function needsDeclarationChange(declaration: VersionSourceDeclaration, invocation: Invocation): boolean { + const { target, prefix } = invocation + if (declaration.source !== target || declaration.raw === null) return true + return target === 'github-release' && prefix !== undefined && prefix !== declaration.prefix +} - const plan: string[] = [] - const warnings: string[] = [] - let seed: string | null = null +async function buildPlan(site: Site, invocation: Invocation, declaration: VersionSourceDeclaration): Promise<Plan> { + const descriptorExists = await exists(join(site.siteRoot, '.release-version')) + const files = + invocation.target === 'descriptor' + ? await planDescriptor(site, invocation, descriptorExists) + : await planRemoval(site, descriptorExists) + if (!needsDeclarationChange(declaration, invocation)) return files + const declare = `set docouture.versionSource to '${invocation.target}' in ${relative(site.repoRoot, site.packageJsonFile)}` + return { ...files, steps: [declare, ...files.steps] } +} - if (target === 'descriptor') { - if (explicitVersion !== undefined || !descriptorExists) { - seed = await seedVersion(repoRoot, explicitVersion) - plan.push(`${descriptorExists ? 'overwrite' : 'create'} ${rel(descriptorFile)} with ${seed}`) - } - } else if (descriptorExists) { - const pending = (await readFile(descriptorFile, 'utf8')).trim() - if (pending !== '') { - warnings.push(`${rel(descriptorFile)} held the pending version '${pending}', which is discarded`) - } - plan.push(`remove ${rel(descriptorFile)}`) +function printNotes(target: VersionSource): void { + console.log('') + console.log('The release workflows read the source at run time — no workflow files need re-rendering,') + console.log('but they run the project\u2019s installed CLI: make sure it is a version with `release resolve`.') + if (target === 'tag-bump') { + console.log('') + printTagBumpLabelCommands() } + if (target === 'github-release') { + console.log('') + console.log("Docs are now released when your code release publishes a GitHub Release — a merged 'docs/release'") + console.log('pull request fails. Use --prefix <p> if your release tags carry a prefix (e.g. docs-site@).') + } +} - const prefixChange = target === 'github-release' && prefix !== undefined && prefix !== declaration.prefix - if (declaration.source !== target || declaration.raw === null || prefixChange) { - plan.unshift(`set docouture.versionSource to '${target}' in ${rel(packageJsonFile)}`) +function printCurrent(declaration: VersionSourceDeclaration): number { + if (declaration.source === null) { + console.error( + `docouture.versionSource '${declaration.raw}' is not a known source — expected one of: ${VERSION_SOURCES.join(', ')}` + ) + return 1 } + console.log(`version source: ${declaration.source}`) + if (declaration.prefix) console.log(`prefix: ${declaration.prefix}`) + return 0 +} + +function fail(errors: string[]): number { + for (const line of errors) console.error(line) + return 1 +} + +export async function runVersionSource(argv: string[]): Promise<number> { + const parsed = parseInvocation(argv) + if (!parsed.ok) return fail(parsed.errors) + const { invocation } = parsed + const { target, dryRun, prefix } = invocation - if (plan.length === 0) { + const located = await locateSite(invocation.startDir) + if (!located.ok) return fail(located.errors) + const { site } = located + + const declaration = await readVersionSourceDeclaration(site.packageJsonFile) + if (target === null) return printCurrent(declaration) + + const plan = await buildPlan(site, invocation, declaration) + if (plan.steps.length === 0) { console.log(`already '${target}' — nothing to do`) return 0 } if (dryRun) { console.log('would:') - for (const line of plan) console.log(` ${line}`) - for (const warning of warnings) console.log(`warning: ${warning}`) + for (const step of plan.steps) console.log(` ${step}`) + for (const warning of plan.warnings) console.log(`warning: ${warning}`) return 0 } - await setVersionSource(packageJsonFile, target, prefix) - if (seed !== null) await writeFile(descriptorFile, `${seed}\n`, 'utf8') - else if (target !== 'descriptor' && descriptorExists) await rm(descriptorFile) + const descriptorFile = join(site.siteRoot, '.release-version') + await setVersionSource(site.packageJsonFile, target, prefix) + if (plan.seed !== null) await writeFile(descriptorFile, `${plan.seed}\n`, 'utf8') + if (plan.removeDescriptor) await rm(descriptorFile) console.log(`version source is now '${target}'`) - for (const line of plan.slice(1)) console.log(` ${line}`) - for (const warning of warnings) console.warn(`warning: ${warning}`) - - console.log('') - console.log('The release workflows read the source at run time — no workflow files need re-rendering,') - console.log('but they run the project\u2019s installed CLI: make sure it is a version with `release resolve`.') - if (target === 'tag-bump') { - console.log('') - printTagBumpLabelCommands() - } - if (target === 'github-release') { - console.log('') - console.log("Docs are now released when your code release publishes a GitHub Release — a merged 'docs/release'") - console.log('pull request fails. Use --prefix <p> if your release tags carry a prefix (e.g. docs-site@).') - } + for (const step of plan.steps) console.log(` ${step}`) + for (const warning of plan.warnings) console.warn(`warning: ${warning}`) + printNotes(target) return 0 } diff --git a/code/packages/cli/src/lib/docs-tags.ts b/code/packages/cli/src/lib/docs-tags.ts index ad4b4b8f..9dd3b1c8 100644 --- a/code/packages/cli/src/lib/docs-tags.ts +++ b/code/packages/cli/src/lib/docs-tags.ts @@ -11,10 +11,10 @@ import { TAG_PREFIX } from './release-resolve.js' // Existing docs/v* tag names, from the local clone — callers fetch tags first. export function listDocsTags(repoRoot: string): Promise<string[]> { return new Promise((resolvePromise) => { - // Resolves 'git' off PATH, same as the other commands that shell out to it. - execFile('git', ['tag', '-l', `${TAG_PREFIX}*`], { cwd: repoRoot }, (err, stdout) => { - // NOSONAR + const onDone = (err: Error | null, stdout: string): void => { resolvePromise(err ? [] : stdout.split('\n').filter((line) => line.trim() !== '')) - }) + } + // Resolves 'git' off PATH, same as the other commands that shell out to it. + execFile('git', ['tag', '-l', `${TAG_PREFIX}*`], { cwd: repoRoot }, onDone) // NOSONAR }) } diff --git a/code/packages/cli/src/lib/project-cli.ts b/code/packages/cli/src/lib/project-cli.ts index 78976058..b995e769 100644 --- a/code/packages/cli/src/lib/project-cli.ts +++ b/code/packages/cli/src/lib/project-cli.ts @@ -33,18 +33,23 @@ async function readJson<T>(file: string): Promise<T | null> { } } +interface InstalledCli { + version: string + hasReleaseResolve: boolean +} + +async function readInstalledCli(base: string): Promise<InstalledCli | null> { + const dir = join(base, 'node_modules', ...CLI_PACKAGE.split('/')) + const pkg = await readJson<{ version?: string }>(join(dir, 'package.json')) + if (!pkg?.version) return null + return { version: pkg.version, hasReleaseResolve: await exists(join(dir, 'build', 'commands', 'release.js')) } +} + export async function readProjectCli(siteRoot: string, repoRoot: string): Promise<ProjectCli> { - for (const base of [siteRoot, repoRoot]) { - const dir = join(base, 'node_modules', ...CLI_PACKAGE.split('/')) - const pkg = await readJson<{ version?: string }>(join(dir, 'package.json')) - if (pkg?.version) { - return { - version: pkg.version, - hasReleaseResolve: await exists(join(dir, 'build', 'commands', 'release.js')), - from: 'installed', - } - } - } + // The site's own node_modules wins over the repository root's. + const candidates = await Promise.all([siteRoot, repoRoot].map(readInstalledCli)) + const installed = candidates.find((candidate) => candidate !== null) + if (installed) return { ...installed, from: 'installed' } const sitePkg = await readJson<{ devDependencies?: Record<string, string>; dependencies?: Record<string, string> }>( join(siteRoot, 'package.json') diff --git a/code/packages/cli/src/lib/release-resolve.spec.ts b/code/packages/cli/src/lib/release-resolve.spec.ts index 42def5df..fe6002a6 100644 --- a/code/packages/cli/src/lib/release-resolve.spec.ts +++ b/code/packages/cli/src/lib/release-resolve.spec.ts @@ -10,7 +10,8 @@ import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' -import { parseVersionSource, resolveDescriptor, resolveRelease, SEMVER_RE } from './release-resolve.js' +import { parseVersionSource, resolveDescriptor, resolveRelease } from './release-resolve.js' +import { isSemver } from './semver.js' describe('resolveDescriptor', () => { it('reads the descriptor in versioned mode', () => { @@ -82,14 +83,20 @@ describe('preview workflow SemVer parity', () => { '1.2.0-beta+exp.sha.5114f85', 'v1.2.0', '1.2', + '1.2.3.4', '01.2.3', + '1.02.3', '1.2.3-', '1.2.3-01', + '1.2.3-a..b', + '1.2.3+', + '1.0.0-x-y-z.-', + '1.0.0+21AF26D3----117B344092BD', '', 'stable', ])('agrees on %j', (value) => { const bashRe = new RegExp(source ?? '(?!)') - expect(bashRe.test(value)).toBe(SEMVER_RE.test(value)) + expect(bashRe.test(value)).toBe(isSemver(value)) }) }) diff --git a/code/packages/cli/src/lib/release-resolve.ts b/code/packages/cli/src/lib/release-resolve.ts index 0614bd8a..9fb9e132 100644 --- a/code/packages/cli/src/lib/release-resolve.ts +++ b/code/packages/cli/src/lib/release-resolve.ts @@ -4,7 +4,7 @@ 'use strict' -import { bumpVersion, highestSemver, SEMVER_RE } from './semver.js' +import { bumpVersion, highestSemver, isSemver } from './semver.js' export type ReleaseMode = 'versioned' | 'standalone' @@ -23,8 +23,6 @@ export interface ReleaseResolution { export const DESCRIPTOR_SOURCE = 'docs/.release-version' export const INPUT_SOURCE = 'version input' -export { SEMVER_RE } - export type VersionSource = 'descriptor' | 'github-release' | 'tag-bump' export const VERSION_SOURCES: readonly VersionSource[] = ['descriptor', 'github-release', 'tag-bump'] @@ -76,7 +74,7 @@ function checkVersion(version: string, source: string): ReleaseError | undefined "'stable' is standalone's target name, not a valid versioned-mode version — use a real version, e.g. 1.2.0", } } - if (!SEMVER_RE.test(version)) { + if (!isSemver(version)) { return { kind: 'invalid', value: version, diff --git a/code/packages/cli/src/lib/semver.spec.ts b/code/packages/cli/src/lib/semver.spec.ts index 595d7423..c6557d51 100644 --- a/code/packages/cli/src/lib/semver.spec.ts +++ b/code/packages/cli/src/lib/semver.spec.ts @@ -6,7 +6,7 @@ import { describe, expect, it } from 'vitest' -import { bumpVersion, compareSemver, highestSemver, parseSemver } from './semver.js' +import { bumpVersion, compareSemver, highestSemver, isSemver, parseSemver } from './semver.js' describe('compareSemver', () => { // The ordering example from semver.org section 11, in ascending order. @@ -79,3 +79,42 @@ describe('parseSemver', () => { expect(parseSemver('1.2.3-beta.2+x')).toEqual({ major: 1, minor: 2, patch: 3, prerelease: ['beta', '2'] }) }) }) + +describe('isSemver', () => { + it.each([ + '0.0.0', + '1.2.3', + '10.20.30', + '1.0.0-alpha', + '1.0.0-alpha.1', + '1.0.0-0.3.7', + '1.0.0-x.7.z.92', + '1.0.0-x-y-z.-', + '1.0.0+20130313144700', + '1.0.0-beta+exp.sha.5114f85', + '1.0.0+21AF26D3----117B344092BD', + ])('accepts %s', (value) => { + expect(isSemver(value)).toBe(true) + }) + + it.each([ + '', + '1', + '1.2', + '1.2.3.4', + 'v1.2.3', + '01.2.3', + '1.02.3', + '1.2.03', + '1.2.3-', + '1.2.3-01', + '1.2.3-a..b', + '1.2.3+', + '1.2.3+a..b', + '1.2.3-be$ta', + '-1.2.3', + 'stable', + ])('rejects %j', (value) => { + expect(isSemver(value)).toBe(false) + }) +}) diff --git a/code/packages/cli/src/lib/semver.ts b/code/packages/cli/src/lib/semver.ts index 77b00579..9e579b2d 100644 --- a/code/packages/cli/src/lib/semver.ts +++ b/code/packages/cli/src/lib/semver.ts @@ -4,14 +4,10 @@ 'use strict' -// Just enough SemVer 2.0.0 for docs version resolution: precedence ordering -// and the three bump levels, matching `semver.inc` for stable and prerelease -// inputs. Not a dependency: this is one small, well-specified function pair. - -// Full SemVer 2.0.0 grammar (semver.org's own regex). Prerelease and build -// metadata suffixes are valid; a leading 'v' or a two-part '1.2' is not. -export const SEMVER_RE = - /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/ +// Just enough SemVer 2.0.0 for docs version resolution: validation, +// precedence ordering and the three bump levels, matching `semver.inc` for +// stable and prerelease inputs. Not a dependency: this is one small, +// well-specified function set. export type BumpLevel = 'patch' | 'minor' | 'major' @@ -22,17 +18,50 @@ export interface ParsedVersion { prerelease: string[] } +const NUMERIC_IDENTIFIER = /^(0|[1-9]\d*)$/ +const ALPHANUMERIC_IDENTIFIER = /^[0-9A-Za-z-]+$/ +const DIGITS_ONLY = /^\d+$/ + +// A prerelease identifier is alphanumeric; when it is all digits it must not +// have a leading zero. +function isPrereleaseIdentifier(identifier: string): boolean { + if (!ALPHANUMERIC_IDENTIFIER.test(identifier)) return false + return !DIGITS_ONLY.test(identifier) || NUMERIC_IDENTIFIER.test(identifier) +} + +function splitVersion(version: string): { core: string; prerelease: string | null; build: string | null } { + const plus = version.indexOf('+') + const build = plus === -1 ? null : version.slice(plus + 1) + const withoutBuild = plus === -1 ? version : version.slice(0, plus) + const dash = withoutBuild.indexOf('-') + return { + core: dash === -1 ? withoutBuild : withoutBuild.slice(0, dash), + prerelease: dash === -1 ? null : withoutBuild.slice(dash + 1), + build, + } +} + +// Full SemVer 2.0.0 grammar: MAJOR.MINOR.PATCH with no leading zeros, an +// optional -prerelease and an optional +build. A leading 'v' and a two-part +// '1.2' are not valid. +export function isSemver(version: string): boolean { + const { core, prerelease, build } = splitVersion(version) + const numbers = core.split('.') + if (numbers.length !== 3 || !numbers.every((part) => NUMERIC_IDENTIFIER.test(part))) return false + if (prerelease !== null && !prerelease.split('.').every(isPrereleaseIdentifier)) return false + return build === null || build.split('.').every((part) => ALPHANUMERIC_IDENTIFIER.test(part)) +} + export function parseSemver(version: string): ParsedVersion | null { - if (!SEMVER_RE.test(version)) return null - const [core = '', ...rest] = version.split('+')[0]!.split('-') - const [major = '0', minor = '0', patch = '0'] = core.split('.') - const prerelease = rest.length > 0 ? rest.join('-').split('.') : [] - return { major: Number(major), minor: Number(minor), patch: Number(patch), prerelease } + if (!isSemver(version)) return null + const { core, prerelease } = splitVersion(version) + const [major = 0, minor = 0, patch = 0] = core.split('.').map(Number) + return { major, minor, patch, prerelease: prerelease === null ? [] : prerelease.split('.') } } function comparePrereleaseIdentifier(a: string, b: string): number { - const aNumeric = /^\d+$/.test(a) - const bNumeric = /^\d+$/.test(b) + const aNumeric = DIGITS_ONLY.test(a) + const bNumeric = DIGITS_ONLY.test(b) if (aNumeric && bNumeric) return Math.sign(Number(a) - Number(b)) if (aNumeric) return -1 if (bNumeric) return 1 @@ -40,34 +69,35 @@ function comparePrereleaseIdentifier(a: string, b: string): number { return a < b ? -1 : 1 } -// SemVer 2.0.0 precedence: build metadata is ignored, a version with a -// prerelease sorts below the same version without one. +// A version with a prerelease sorts below the same version without one; two +// prereleases compare identifier by identifier, and a shorter list loses when +// all shared identifiers are equal. +function comparePrerelease(a: string[], b: string[]): number { + if (a.length === 0 || b.length === 0) return Math.sign(b.length - a.length) + for (let i = 0; i < Math.min(a.length, b.length); i++) { + const result = comparePrereleaseIdentifier(a[i]!, b[i]!) + if (result !== 0) return result + } + return Math.sign(a.length - b.length) +} + +// SemVer 2.0.0 precedence: build metadata is ignored. export function compareSemver(a: string, b: string): number { const pa = parseSemver(a) const pb = parseSemver(b) if (!pa || !pb) throw new Error(`cannot compare invalid SemVer: '${pa ? b : a}'`) - for (const key of ['major', 'minor', 'patch'] as const) { - if (pa[key] !== pb[key]) return Math.sign(pa[key] - pb[key]) - } - if (pa.prerelease.length === 0 && pb.prerelease.length === 0) return 0 - if (pa.prerelease.length === 0) return 1 - if (pb.prerelease.length === 0) return -1 - const length = Math.max(pa.prerelease.length, pb.prerelease.length) - for (let i = 0; i < length; i++) { - const x = pa.prerelease[i] - const y = pb.prerelease[i] - if (x === undefined) return -1 - if (y === undefined) return 1 - const result = comparePrereleaseIdentifier(x, y) - if (result !== 0) return result - } - return 0 + return ( + Math.sign(pa.major - pb.major) || + Math.sign(pa.minor - pb.minor) || + Math.sign(pa.patch - pb.patch) || + comparePrerelease(pa.prerelease, pb.prerelease) + ) } export function highestSemver(versions: string[]): string | null { let best: string | null = null for (const version of versions) { - if (!parseSemver(version)) continue + if (!isSemver(version)) continue if (best === null || compareSemver(version, best) > 0) best = version } return best @@ -83,13 +113,10 @@ export function bumpVersion(version: string, level: BumpLevel): string { const isPrerelease = prerelease.length > 0 if (level === 'major') { - if (isPrerelease && minor === 0 && patch === 0) return `${major}.0.0` - return `${major + 1}.0.0` + return isPrerelease && minor === 0 && patch === 0 ? `${major}.0.0` : `${major + 1}.0.0` } if (level === 'minor') { - if (isPrerelease && patch === 0) return `${major}.${minor}.0` - return `${major}.${minor + 1}.0` + return isPrerelease && patch === 0 ? `${major}.${minor}.0` : `${major}.${minor + 1}.0` } - if (isPrerelease) return `${major}.${minor}.${patch}` - return `${major}.${minor}.${patch + 1}` + return isPrerelease ? `${major}.${minor}.${patch}` : `${major}.${minor}.${patch + 1}` }