name: Catalog Sync on: pull_request: # Base-branch filter only. The head-branch filter (this job is for the # changesets release PR, not every PR into main) lives on the job's `if:` # because `pull_request` has no head-branch filter. branches: [main] types: [opened, synchronize, reopened] workflow_dispatch: inputs: open-pr: description: Open an auto-merging PR instead of committing directly to main type: boolean default: false concurrency: group: catalog-sync-${{ github.ref }} cancel-in-progress: true permissions: contents: read # The reported check run below is written with GITHUB_TOKEN rather than the App # token, so the App's grants do not have to change for this job to report. checks: write jobs: catalog-sync: # A `pull_request` from a FORK gets no secrets, so the App-token step below # cannot mint a token and the job dies at step 1 with an opaque credential # error — before it has looked at the catalog at all. Skipping is both # honester and safer: this job's remediation path commits straight to `main`, # which is not something a fork PR should ever be able to reach for, and a # skipped job reports as skipped rather than as a spurious red check. # # This is the only workflow here that runs on `pull_request` AND depends on # `secrets`, which is why the guard lives here and not in a shared place. # # The head-branch check narrows the `pull_request` trigger to the release PR # changesets opens from `changeset-release/main`: that is the only PR whose # manifests carry the next release versions the catalog is synced against. if: >- github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.repository && github.head_ref == 'changeset-release/main') runs-on: ubuntu-latest steps: - name: Generate App Token id: app-token # Scoped down twice: to this repository, and to the two permissions the job # actually uses — createCommitOnBranch and the ref write need contents, the # PR open and auto-merge need pull-requests. uses: actions/create-github-app-token@v3 with: client-id: ${{ vars.APP_CLIENT_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} owner: spencerbeggs repositories: effected permission-contents: write permission-pull-requests: write - name: Checkout uses: actions/checkout@v7 with: ref: main fetch-depth: 0 token: ${{ steps.app-token.outputs.token }} # Do not leave the App token in .git/config for later steps to reuse. Every # write this job makes goes through the API with an explicit token; the only # git commands here are local reads and staging. persist-credentials: false - name: Setup Runtime id: runtime uses: savvy-web/silk-runtime-action@v1 - name: Check the catalog id: catalog-check # The GATE, and it has to run before `catalog:sync` mutates anything — # afterwards the catalog is in sync by construction and a check would # always pass, which is how this job came to report success on a branch # whose catalog was wrong. `catalog:check` is read-only and exits non-zero # on drift; `continue-on-error` keeps that exit code as a signal # (`steps.catalog-check.outcome`) instead of ending the job here, because # the sync below is the remediation and should still run. continue-on-error: true run: pnpm catalog:check - name: Sync the catalog # Resolves each catalogued package's next release version from the local # workspace, rewrites the catalog literal in place, and writes the # fixed-name changeset when anything moved. The script imports kit packages # through their source, over the workspace links, so it needs no build. run: pnpm catalog:sync - name: Format the rewrite # Scope Biome to the only file the sync rewrites, so an unrelated # unfixable lint diagnostic elsewhere in the repo cannot abort this job. run: pnpm exec biome check --write packages/pnpm-plugin-effected/lib/build/pnpm-config.plugin.ts - name: Check for changes id: changes # `git status --porcelain`, not `git diff --quiet` — do not "simplify" this # back. The precedent workflow can use `git diff` because a separate step # writes its changeset; here `catalog:sync` writes both the rewrite and # `.changeset/catalog-sync.md`, which is untracked on a first sync. `git diff` # cannot see an untracked file, so it would report changed=false on exactly # the run that had a changeset to propose — a check that reports success # while doing nothing, which is the failure class this whole design exists # to eliminate. run: | # The quoted glob is git's pathspec, not the shell's, so a floor file the # sync deleted still counts as a change. if [ -z "$(git status --porcelain -- packages/pnpm-plugin-effected/lib/build/pnpm-config.plugin.ts .changeset/catalog-sync.md '.changeset/breaking-floor-*.md')" ]; then echo "changed=false" >> "$GITHUB_OUTPUT" else echo "changed=true" >> "$GITHUB_OUTPUT" fi - name: Build and test if: steps.changes.outputs.changed == 'true' run: | pnpm build --filter @effected/pnpm-plugin-effected # The catalog tests are the guard on the exclusion that makes this loop # terminate, so they run against the rewrite before it is proposed. # Coverage is disabled: this repo's vitest config enforces global # thresholds a single-package subset run cannot meet, which would abort # the job. pnpm vitest run packages/pnpm-plugin-effected --coverage.enabled=false - name: Commit the sync id: commit if: steps.changes.outputs.changed == 'true' env: GH_TOKEN: ${{ steps.app-token.outputs.token }} REPO: ${{ github.repository }} # Automated runs commit straight back to main; only a manual dispatch # with open-pr=true goes through the branch + auto-merging-PR flow. # (inputs.* is empty on non-dispatch events, so this resolves false.) OPEN_PR: ${{ inputs.open-pr == true }} BRANCH: chore/catalog-sync BASE_BRANCH: main # Fallback only. `catalog:sync` writes COMMIT_MESSAGE_PATH naming every # package that moved and both of its ranges; this is what gets used if # that file is somehow absent, so a missing message degrades to the old # generic headline rather than failing the commit. HEADLINE: "chore(pnpm-plugin-effected): sync the effected catalog" COMMIT_MESSAGE_PATH: .changeset/catalog-sync.commit.txt # DCO only requires a well-formed trailer; keep the exact identity the # previous `git commit --signoff` produced under this App. SIGNOFF: "Signed-off-by: ${{ steps.app-token.outputs.app-slug }}[bot] <${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com>" run: | set -euo pipefail # The commit is created through the GraphQL API, not `git commit` plus # `git push`: GitHub signs commits it creates on the caller's behalf, so # the bot's commits land verified. Locally made ones are unsigned (#159). # Stage exactly the paths this job owns, then read the staged status back: # that picks up the untracked changeset files alongside the rewritten # catalog, and normalizes them into a path list. `.changeset/` is staged # whole because the breaking-floor changesets have per-package names and a # pathspec that matches nothing fails `git add`; the checkout is fresh, so # every change under it is one `catalog:sync` wrote (the commit-message # file is gitignored). `-A` stages a floor file the sync deleted. git add -A -- packages/pnpm-plugin-effected/lib/build/pnpm-config.plugin.ts .changeset additions='[]' while IFS= read -r -d '' path; do additions=$(jq -c --arg path "$path" --arg contents "$(base64 -w0 <"$path")" \ '. + [{path: $path, contents: $contents}]' <<<"$additions") done < <(git diff --cached --name-only -z --diff-filter=d) deletions='[]' while IFS= read -r -d '' path; do deletions=$(jq -c --arg path "$path" '. + [{path: $path}]' <<<"$deletions") done < <(git diff --cached --name-only -z --diff-filter=D) if [ "$additions" = '[]' ] && [ "$deletions" = '[]' ]; then echo "::notice::Nothing staged for $BRANCH" exit 0 fi # The message names the moves, and only the sync knows them. First line is # the headline, the rest is the body; the signoff is appended last so the # DCO trailer stays the final line. if [ -s "$COMMIT_MESSAGE_PATH" ]; then headline=$(head -n 1 "$COMMIT_MESSAGE_PATH") message_body=$(tail -n +2 "$COMMIT_MESSAGE_PATH") body="${message_body}"$'\n'"$SIGNOFF" else echo "::warning::$COMMIT_MESSAGE_PATH is missing; falling back to the generic headline" headline="$HEADLINE" body="$SIGNOFF" fi base_oid=$(gh api "repos/$REPO/git/ref/heads/$BASE_BRANCH" --jq '.object.sha') if [ "$OPEN_PR" = "true" ]; then # createCommitOnBranch cannot force-push, so reset the branch pointer to # the current base tip first — the old `git push --force` semantics of one # fresh commit on top of main. Moving a ref creates no commit, so nothing # unsigned enters history. if gh api "repos/$REPO/git/ref/heads/$BRANCH" >/dev/null 2>&1; then gh api -X PATCH "repos/$REPO/git/refs/heads/$BRANCH" \ -f sha="$base_oid" -F force=true >/dev/null else gh api -X POST "repos/$REPO/git/refs" \ -f ref="refs/heads/$BRANCH" -f sha="$base_oid" >/dev/null fi target_branch="$BRANCH" else # Default path: commit the signed sync directly onto main. The # expectedHeadOid guard makes the mutation fail cleanly if main moved # between the read above and the commit, instead of clobbering it. target_branch="$BASE_BRANCH" fi jq -n \ --arg repo "$REPO" \ --arg branch "$target_branch" \ --arg oid "$base_oid" \ --arg headline "$headline" \ --arg body "$body" \ --argjson additions "$additions" \ --argjson deletions "$deletions" \ '{ query: "mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid url } } }", variables: { input: { branch: { repositoryNameWithOwner: $repo, branchName: $branch }, message: { headline: $headline, body: $body }, expectedHeadOid: $oid, fileChanges: { additions: $additions, deletions: $deletions } } } }' \ > /tmp/commit-mutation.json commit_url=$(gh api graphql --input /tmp/commit-mutation.json \ --jq '.data.createCommitOnBranch.commit.url') echo "$commit_url" echo "commit-url=$commit_url" >> "$GITHUB_OUTPUT" if [ "$OPEN_PR" = "true" ]; then gh pr create \ --base "$BASE_BRANCH" \ --head "$BRANCH" \ --title "$headline" \ --body "Automated sync of the \`effected\` catalog to the next release versions resolved from this repo's manifests and pending changesets." \ || echo "::notice::PR already open for $BRANCH" gh pr merge "$BRANCH" --auto --squash fi - name: Report the catalog check run # `always()`, and ONE call that both creates and concludes the run. The # create-early-then-complete-late shape is what leaves a check run stuck # `in_progress` forever when a job is cancelled or dies before its closing # step — a hung check is indistinguishable from a slow one, and nothing # times it out. A run that is only ever written once, with a conclusion # already in hand, cannot hang. if: always() env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPO: ${{ github.repository }} # The PR's HEAD sha, not `github.sha`. On a `pull_request` event # `github.sha` is the ephemeral MERGE commit; a check run posted there is # invisible to the PR's own status list and to any branch-protection rule # keyed on this check, so the gate silently never applies. HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} JOB_STATUS: ${{ job.status }} # `outcome` is the step's own result BEFORE continue-on-error masks it; # `conclusion` would read `success` on exactly the drift runs this gate # exists to catch. CATALOG_CHECK: ${{ steps.catalog-check.outcome }} CHANGED: ${{ steps.changes.outputs.changed }} COMMIT_URL: ${{ steps.commit.outputs.commit-url }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail if [ "$CATALOG_CHECK" = "success" ]; then conclusion=success title="Catalog is up to date" summary="\`catalog:check\` found no drift: every catalogued package's next release version already matches the \`effected\` catalog literal." elif [ "$JOB_STATUS" != "success" ]; then conclusion=failure title="Catalog is out of date and the sync did not complete" summary="\`catalog:check\` reported drift and the job then ended \`$JOB_STATUS\`, so the catalog is still wrong and nothing has been committed. See the run log." elif [ -n "${COMMIT_URL:-}" ]; then # The catalog WAS wrong. It has been repaired, and that is worth # saying out loud rather than swallowing: a run that silently fixes # drift teaches nobody that the drift happened. conclusion=failure title="Catalog was out of date — synced" summary="\`catalog:check\` reported drift, so the catalog literal was rewritten and committed: $COMMIT_URL"$'\n\n'"This check reports failure because the catalog was wrong at this ref, not because the repair failed. Re-run once the sync commit is in the branch and it goes green." elif [ "$CHANGED" != "true" ]; then # Drift reported but the rewrite produced nothing to commit — the two # halves disagree, which means one of them is broken. conclusion=failure title="Catalog check and sync disagree" summary="\`catalog:check\` reported drift but \`catalog:sync\` rewrote nothing, so no commit was produced. One of the two is wrong; do not treat this as a clean catalog." else conclusion=failure title="Catalog is out of date and was not synced" summary="\`catalog:sync\` rewrote the catalog literal but no commit was produced, so the drift is still unresolved on the branch." fi # The run link goes in the SUMMARY, not `details_url`. GitHub silently # ignores `details_url` on a check run created with the Actions # `GITHUB_TOKEN` and substitutes the check run's own URL, so passing it # produced a check with no route back to the log that explains it # (community#26757). summary="$summary"$'\n\n'"[Run log]($RUN_URL)" gh api "repos/$REPO/check-runs" \ -f name='Catalog Sync' \ -f head_sha="$HEAD_SHA" \ -f status=completed \ -f conclusion="$conclusion" \ -f output[title]="$title" \ -f output[summary]="$summary" >/dev/null echo "::notice::Catalog Sync check run: $conclusion — $title" # Fail the job too, so the outcome is visible whether the consumer keys # on the reported check run or on this job's own status. [ "$conclusion" = "success" ]