Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Update workflow: catch up skipped workflow files, refuse an unclear starting point
Claude6b7d2c1e0883
diff --git a/.github/workflows/update-signudoc.yml b/.github/workflows/update-signudoc.ymlindex 6dc07c1..f154f19 100644--- a/.github/workflows/update-signudoc.yml+++ b/.github/workflows/update-signudoc.yml@@ -39,6 +39,10 @@ on:description: "Release to update to, such as v0.2.0. Leave empty for the latest."required: falsedefault: ""+ based_on:+ description: "Only when a run asks for it: the SignuDoc release or commit this copy started from, such as v0.1.0."+ required: false+ default: ""merge:description: "Merge straight into the production branch instead of opening a pull request (only when nothing clashes)."type: boolean@@ -65,6 +69,7 @@ jobs:GH_TOKEN: ${{ secrets.SIGNUDOC_UPDATE_TOKEN || github.token }}HAS_UPDATE_TOKEN: ${{ secrets.SIGNUDOC_UPDATE_TOKEN != '' }}REQUESTED_VERSION: ${{ inputs.version }}+ BASED_ON: ${{ inputs.based_on }}MERGE_NOW: ${{ inputs.merge == true || vars.SIGNUDOC_AUTO_MERGE == '1' }}BASE_BRANCH: ${{ github.event.repository.default_branch }}steps:@@ -120,11 +125,26 @@ jobs:# - a commit both histories share (a fork, or a manual merge),# - the commit the Deploy button copied, found by its files.candidates=()- while read -r sha; do- if git cat-file -e "$sha^{commit}" 2> /dev/null; then candidates+=("$sha"); fi- done < <(git log --max-count=200 --format=%B HEAD |- sed -n 's/^SignuDoc-Commit: \([0-9a-f]\{40\}\)[[:space:]]*$/\1/p')- if shared=$(git merge-base HEAD "$target" 2> /dev/null); then+ if [ -n "${BASED_ON:-}" ]; then+ [[ "$BASED_ON" =~ ^[0-9A-Za-z._-]{1,100}$ ]] ||+ stop "\"$BASED_ON\" is not a SignuDoc release or commit."+ based_on="$BASED_ON"+ if [[ "$based_on" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]]; then based_on="v$based_on"; fi+ base=$(git rev-parse -q --verify "refs/signudoc/tags/$based_on^{commit}" ||+ git rev-parse -q --verify "$based_on^{commit}") ||+ stop "SignuDoc has no release or commit \"$BASED_ON\"."+ git merge-base --is-ancestor "$base" refs/signudoc/main ||+ git merge-base --is-ancestor "$base" "$target" ||+ stop "\"$BASED_ON\" is not a SignuDoc release or commit."+ candidates+=("$base")+ fi+ if [ -z "${BASED_ON:-}" ]; then+ while read -r sha; do+ if git cat-file -e "$sha^{commit}" 2> /dev/null; then candidates+=("$sha"); fi+ done < <(git log --max-count=200 --format=%B HEAD |+ sed -n 's/^SignuDoc-Commit: \([0-9a-f]\{40\}\)[[:space:]]*$/\1/p')+ fi+ if [ -z "${BASED_ON:-}" ] && shared=$(git merge-base HEAD "$target" 2> /dev/null); thencandidates+=("$shared")fiif [ "${#candidates[@]}" -eq 0 ]; then@@ -136,17 +156,25 @@ jobs:awk -v tree="$root_tree" '$2 == tree { print $1; exit }' || true)if [ -z "$copied" ]; then# The first commit was changed before it was pushed. Take the- # SignuDoc commit with the fewest differing files.+ # SignuDoc commit with the fewest differing lines, and only+ # when exactly one commit is that close.fewest=""+ tied=0while read -r sha; do- count=$(git diff --no-renames --name-only "${roots[0]}" "$sha" | wc -l)+ count=$(git diff --no-renames --numstat "${roots[0]}" "$sha" |+ awk '{ total += ($1 == "-" ? 1 : $1 + $2) } END { print total + 0 }')if [ -z "$fewest" ] || [ "$count" -lt "$fewest" ]; thencopied="$sha"fewest="$count"+ tied=0+ elif [ "$count" -eq "$fewest" ]; then+ tied=1fi- [ "$count" -eq 0 ] && breakdone < <(git rev-list --max-count=500 refs/signudoc/main "$target")- summary "Your first commit matches no SignuDoc commit exactly. Using the closest one, ${copied:0:7}, which differs in $fewest files."+ if [ "$tied" -eq 1 ]; then+ stop "Your first commit matches no SignuDoc commit exactly, and several are equally close. Run this workflow again with \"based on\" set to the SignuDoc release you deployed, such as v0.1.0."+ fi+ summary "Your first commit matches no SignuDoc commit exactly. Using the closest one, ${copied:0:7}, which differs in $fewest lines. If that is not the version you deployed, run again with \"based on\" set to it."ficandidates+=("$copied")fi@@ -155,13 +183,39 @@ jobs:if git merge-base --is-ancestor "$base" "$sha"; then base="$sha"; fidone- if git merge-base --is-ancestor "$target" "$base"; then+ # Without the token, a run leaves workflow files as they were and+ # records how far they lag in SignuDoc-Workflows-Commit, so a later+ # run with the token can still bring them in.+ wf_base="$base"+ latest_update=$(git log -1 --format=%H --grep='^SignuDoc-Commit: ' HEAD)+ if [ -z "${BASED_ON:-}" ] && [ -n "$latest_update" ]; then+ message=$(git log -1 --format=%B "$latest_update")+ recorded=$(sed -n 's/^SignuDoc-Commit: \([0-9a-f]\{40\}\)[[:space:]]*$/\1/p' <<< "$message" | head -n 1)+ recorded_wf=$(sed -n 's/^SignuDoc-Workflows-Commit: \([0-9a-f]\{40\}\)[[:space:]]*$/\1/p' <<< "$message" | head -n 1)+ if [ "$recorded" = "$base" ] && [ -n "$recorded_wf" ] &&+ git cat-file -e "$recorded_wf^{commit}" 2> /dev/null; then+ wf_base="$recorded_wf"+ fi+ fi++ needs_code=true+ git merge-base --is-ancestor "$target" "$base" && needs_code=false+ needs_workflows=false+ if [ "$HAS_UPDATE_TOKEN" = "true" ] && ! git merge-base --is-ancestor "$target" "$wf_base"; then+ needs_workflows=true+ fi++ if [ "$needs_code" = "false" ] && [ "$needs_workflows" = "false" ]; thensummary "Already up to date with SignuDoc $tag."+ if ! git merge-base --is-ancestor "$target" "$wf_base"; then+ summary "" "Files in \`.github/workflows\` were left as they were by an earlier update. Add a \`SIGNUDOC_UPDATE_TOKEN\` secret (docs/self-hosting.md) and run this again to bring them in."+ fiecho "Already up to date with SignuDoc $tag."exit 0fibranch="signudoc-update/$tag"+ if [ "$needs_code" = "false" ]; then branch="signudoc-update/$tag-workflows"; fiif git ls-remote --exit-code --heads origin "$branch" > /dev/null; thenopen_pr=$(gh pr list --head "$branch" --state open --json url --jq '.[0].url // ""')if [ -n "$open_pr" ]; then@@ -174,28 +228,36 @@ jobs:# Three-way merge: what SignuDoc changed since $base, applied on# top of this repository, keeping this repository's own changes.- set +e- merge_output=$(git merge-tree --write-tree --name-only --no-messages \- --merge-base="$base" HEAD "$target")- merge_status=$?- set -e- if [ "$merge_status" -eq 1 ]; then- summary "## SignuDoc $tag clashes with changes in this repository" "" \- "These files were changed both here and in SignuDoc, in the same places:" ""- tail -n +2 <<< "$merge_output" | sed '/^$/d; s/^/- `/; s/$/`/' >> "$GITHUB_STEP_SUMMARY"- summary "" "To update by hand, see \"Keep your install up to date\" in docs/self-hosting.md. Use \`${base}\` as the SignuDoc commit this repository is based on."- stop "SignuDoc $tag clashes with this repository's own changes. See the run summary."- elif [ "$merge_status" -ne 0 ]; then- stop "git could not merge SignuDoc $tag."+ merged_tree=$(git rev-parse "HEAD^{tree}")+ if [ "$needs_code" = "true" ]; then+ set +e+ merge_output=$(git merge-tree --write-tree --name-only --no-messages \+ --merge-base="$base" HEAD "$target")+ merge_status=$?+ set -e+ if [ "$merge_status" -eq 1 ]; then+ summary "## SignuDoc $tag clashes with changes in this repository" "" \+ "These files were changed both here and in SignuDoc, in the same places:" ""+ tail -n +2 <<< "$merge_output" | sed '/^$/d; s/^/- `/; s/$/`/' >> "$GITHUB_STEP_SUMMARY"+ summary "" "To update by hand, see \"Keep your install up to date\" in docs/self-hosting.md. Use \`${base}\` as the SignuDoc commit this repository is based on."+ stop "SignuDoc $tag clashes with this repository's own changes. See the run summary."+ elif [ "$merge_status" -ne 0 ]; then+ stop "git could not merge SignuDoc $tag."+ fi+ merged_tree=$(head -n 1 <<< "$merge_output")fi- merged_tree=$(head -n 1 <<< "$merge_output")git checkout --quiet -b "$branch"git read-tree -u --reset "$merged_tree"# GitHub refuses a push that changes workflow files unless the# token may change workflows, which a workflow's own token may not.+ new_wf_base="$target"if [ "$HAS_UPDATE_TOKEN" != "true" ]; then+ # Behind only if SignuDoc changed them since they were last taken.+ if ! git diff --quiet "$wf_base" "$target" -- .github/workflows; then+ new_wf_base="$wf_base"+ fiwhile IFS=$'\t' read -r change path; do[ -n "$path" ] || continueif [ "$change" = "A" ]; then@@ -204,6 +266,26 @@ jobs:git checkout HEAD -- "$path"fidone < <(git diff --cached --no-renames --name-status HEAD -- .github/workflows)+ elif [ "$wf_base" != "$base" ]; then+ # An earlier run left the workflow files behind: merge them from+ # where they were left, and only them.+ set +e+ wf_output=$(git merge-tree --write-tree --name-only --no-messages \+ --merge-base="$wf_base" HEAD "$target")+ wf_status=$?+ set -e+ [ "$wf_status" -le 1 ] || stop "git could not merge the workflow files of SignuDoc $tag."+ wf_clashes=$(tail -n +2 <<< "$wf_output" | grep '^\.github/workflows/' || true)+ if [ -n "$wf_clashes" ]; then+ summary "## Workflow files in SignuDoc $tag clash with changes in this repository" ""+ sed 's/^/- `/; s/$/`/' <<< "$wf_clashes" >> "$GITHUB_STEP_SUMMARY"+ stop "Workflow files in SignuDoc $tag clash with this repository's own changes. See the run summary."+ fi+ wf_tree=$(head -n 1 <<< "$wf_output")+ git rm -r --quiet --force --ignore-unmatch -- .github/workflows+ if git cat-file -e "$wf_tree:.github/workflows" 2> /dev/null; then+ git checkout "$wf_tree" -- .github/workflows+ fifiif git diff --cached --quiet HEAD; then@@ -215,6 +297,8 @@ jobs:if [ "$HAS_UPDATE_TOKEN" != "true" ]; thenkept_workflows=$(git diff --no-renames --name-only "$target" -- .github/workflows)fi+ new_base="$target"+ [ "$needs_code" = "true" ] || new_base="$base"new_migrations=$(git diff --cached --no-renames --name-only --diff-filter=A HEAD -- db/migrations)git commit --quiet --file - << MESSAGE@@ -223,7 +307,8 @@ jobs:Brings in SignuDoc $tag ($release_url).SignuDoc-Version: $tag- SignuDoc-Commit: $target+ SignuDoc-Commit: $new_base+ SignuDoc-Workflows-Commit: $new_wf_baseMESSAGE{@@ -258,7 +343,8 @@ jobs:echo "Opened by the Update SignuDoc workflow."echoecho "SignuDoc-Version: $tag"- echo "SignuDoc-Commit: $target"+ echo "SignuDoc-Commit: $new_base"+ echo "SignuDoc-Workflows-Commit: $new_wf_base"} > "$RUNNER_TEMP/pr-body.md"{diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 53fba6c..c26078e 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -79,6 +79,7 @@ Using it costs nothing: a run takes well under a minute, and private repositorieWhat the workflow does and does not do:- **Your changes are kept.** It does a three-way merge between the SignuDoc version your copy is based on, your copy, and the new release, so code you changed stays changed. Where you and SignuDoc changed the same lines, it stops without touching anything and lists the files in the run's summary. Then update by hand, below.+- **It works out which SignuDoc version your copy started from** by comparing its first commit with this project's history. If the first commit was edited and two versions fit equally well, the run stops and asks you to run it again with **Based on** set to the release you deployed, such as `v0.1.0`.- **It never force-pushes** and never changes your production branch unless you ask it to (below). Everything arrives as a pull request.- **Database changes wait for the merge.** Preview builds do not touch the database (they share it with production unless you set `MIGRATE_ON_PREVIEW=1`), so a preview of an update that changes the database may show errors on pages that need the change. The pull request says when an update changes the database. Merging applies it during the production build. A database change stays if you later roll the site back to an older deployment, so do not roll back across an update that changed the database.- **Files in `.github/workflows` are left alone.** GitHub does not let a workflow's own token change workflow files. When a release changes one, the pull request lists it, and you can copy it from the release by hand. To have the workflow update them too, add the token below.@@ -86,7 +87,7 @@ What the workflow does and does not do:Two optional settings in your repository on GitHub:- **Let the workflow open the pull request.** In Settings, Actions, General, under Workflow permissions, tick **Allow GitHub Actions to create and approve pull requests**. Without it the workflow pushes the branch and its summary links to the page where you open the pull request with one click.-- **`SIGNUDOC_UPDATE_TOKEN`**, a repository secret (Settings, Secrets and variables, Actions). Make a [fine-grained personal access token](https://github.com/settings/personal-access-tokens/new) for your copy only, with read and write access to Contents, Pull requests and Workflows. The workflow uses it instead of its own token, so it can update workflow files and does not need the setting above.+- **`SIGNUDOC_UPDATE_TOKEN`**, a repository secret (Settings, Secrets and variables, Actions). Make a [fine-grained personal access token](https://github.com/settings/personal-access-tokens/new) for your copy only, with read and write access to Contents, Pull requests and Workflows. The workflow uses it instead of its own token, so it can update workflow files and does not need the setting above. Added after an update left workflow files behind, the next run brings them in with a pull request of their own.To skip the pull request, run the workflow with **Merge straight into the production branch** ticked, or set the repository variable `SIGNUDOC_AUTO_MERGE` to `1` to have the weekly run do that. It only does so when the release merges cleanly. Vercel then deploys the update without anyone looking at it first.diff --git a/src/lib/update-workflow.test.ts b/src/lib/update-workflow.test.tsindex ccf9715..5e4ee7f 100644--- a/src/lib/update-workflow.test.ts+++ b/src/lib/update-workflow.test.ts@@ -200,7 +200,12 @@ type RunResult = {function runUpdate(dir: string,upstream: string,- options: { hasToken?: boolean; mergeNow?: boolean; version?: string } = {},+ options: {+ basedOn?: string;+ hasToken?: boolean;+ mergeNow?: boolean;+ version?: string;+ } = {},): RunResult & { gh: string; prBody: string } {const gh = makeGhStub(upstream);const temp = mkdtempSync(path.join(scratch, "runner-"));@@ -213,6 +218,7 @@ function runUpdate(const env = {...gitEnv,BASE_BRANCH: "main",+ BASED_ON: options.basedOn ?? "",GITHUB_OUTPUT: outputFile,GITHUB_REPOSITORY: "acme/signudoc",GITHUB_SERVER_URL: "https://github.com",@@ -403,30 +409,98 @@ test("a clash stops the run and names the files", () => {assert.equal(git(origin, "branch", "--list", "signudoc-update/*"), "");});+/** Merges the pull request the way GitHub's squash button does. */+function squashMerge(origin: string, branch: string) {+ const dir = checkout(origin);+ const message = git(dir, "log", "-1", "--format=%B", `origin/${branch}`);++ git(dir, "merge", "--quiet", "--squash", `origin/${branch}`);+ git(dir, "commit", "--quiet", "-m", `Update SignuDoc (#1)\n\n* ${message}`);+ git(dir, "push", "--quiet", "origin", "main");+ // GitHub keeps the branch unless the repository deletes merged branches.+}+test("once the pull request is merged, the next run is up to date", () => {const upstream = makeUpstream();const { origin } = makeCopy(upstream);assert.equal(runUpdate(checkout(origin), upstream).status, 0);- // Merged the way GitHub's squash button does: a new commit, same files.- const dir = checkout(origin);-- git(dir, "merge", "--quiet", "--squash", "origin/signudoc-update/v0.2.0");- git(- dir,- "commit",- "--quiet",- "-m",- `Update SignuDoc to v0.2.0 (#1)\n\nSignuDoc-Commit: ${git(upstream, "rev-parse", "v0.2.0")}`,- );- git(dir, "push", "--quiet", "origin", "main");- git(dir, "push", "--quiet", "origin", "--delete", "signudoc-update/v0.2.0");+ squashMerge(origin, "signudoc-update/v0.2.0");const again = runUpdate(checkout(origin), upstream);assert.equal(again.status, 0, again.stderr);assert.equal(again.output.branch, undefined);assert.match(again.summary, /Already up to date with SignuDoc v0\.2\.0/);+ // The workflow file it left alone is still pointed out.+ assert.match(again.summary, /SIGNUDOC_UPDATE_TOKEN/);+});++test("adding the token later brings in the workflow files that were left", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);++ assert.equal(runUpdate(checkout(origin), upstream).status, 0);+ squashMerge(origin, "signudoc-update/v0.2.0");++ const withToken = runUpdate(checkout(origin), upstream, { hasToken: true });++ assert.equal(withToken.status, 0, withToken.stderr);+ assert.equal(withToken.output.branch, "signudoc-update/v0.2.0-workflows");+ const branch = "signudoc-update/v0.2.0-workflows";++ assert.equal(+ show(origin, branch, ".github/workflows/ci.yml"),+ "name: CI\non: push",+ );+ assert.equal(+ git(origin, "diff", "--name-only", "main", branch),+ ".github/workflows/ci.yml",+ );++ squashMerge(origin, branch);+ const after = runUpdate(checkout(origin), upstream, { hasToken: true });++ assert.equal(after.status, 0, after.stderr);+ assert.match(after.summary, /Already up to date/);+ assert.doesNotMatch(after.summary, /SIGNUDOC_UPDATE_TOKEN/);+});++test("an unclear starting point stops, and based_on settles it", () => {+ // Two SignuDoc commits equally far from the copy's edited first commit.+ const upstream = path.join(scratch, `upstream-${String((counter += 1))}`);++ mkdirSync(upstream);+ git(upstream, "init", "--quiet", "--initial-branch=main");+ write(upstream, "src/app.ts", "export const b = 1;\n");+ git(upstream, "add", ".");+ git(upstream, "commit", "--quiet", "-m", "One");+ git(upstream, "tag", "v0.1.0");+ write(upstream, "src/app.ts", "export const b = 2;\n");+ git(upstream, "commit", "--quiet", "-am", "Two");+ write(upstream, "src/new.ts", "export const n = 1;\n");+ git(upstream, "add", ".");+ git(upstream, "commit", "--quiet", "-m", "Three");+ git(upstream, "tag", "v0.2.0");++ const { origin } = makeCopy(upstream, undefined, (dir) => {+ write(dir, "src/app.ts", "export const b = 9;\n");+ });+ const unclear = runUpdate(checkout(origin), upstream);++ assert.equal(unclear.status, 1);+ assert.match(unclear.summary, /equally close/);++ const settled = runUpdate(checkout(origin), upstream, { basedOn: "0.1.0" });++ assert.equal(settled.status, 1);+ // From v0.1.0, SignuDoc changed the line this copy changed too.+ assert.match(settled.summary, /- `src\/app\.ts`/);++ const wrong = runUpdate(checkout(origin), upstream, { basedOn: "v9.9.9" });++ assert.equal(wrong.status, 1);+ assert.match(wrong.summary, /has no release or commit/);});test("a copy that is already on the latest release is up to date", () => {