diff --git a/.github/actions/release-merge/README.md b/.github/actions/release-merge/README.md index f31d8c15..820ca9f0 100644 --- a/.github/actions/release-merge/README.md +++ b/.github/actions/release-merge/README.md @@ -1,8 +1,9 @@ # release-merge Merges a release: the release branch into the base branch, then the base branch back into develop, -through the GitHub API. **The base branch is `main`, or `master` where that is the repository's name -for it**, set with `base-branch`: +through the GitHub API. The two merges are written together or not at all: a conflict in either one +leaves both branches as they were. **The base branch is `main`, or `master` where that is the +repository's name for it**, set with `base-branch`: ```yaml - uses: stellarwp/plugin-toolbox/.github/actions/release-merge@v1 @@ -47,22 +48,65 @@ In this order, stopping at the first failure: the branch's `.puprc` lists holds the version and, when the version is already tagged, that the tag contains the branch: a retry of this release goes on, a tag made from another commit is refused. -3. Merges the release branch into the base branch as a merge commit, `Merge release/… into main` - (or `into master`). When the base already holds the branch, a retry, nothing is merged: the - commit to build is then the one the tag points at when the version is already published, and - otherwise the base's tip, which has to be the commit that merged the branch. A base that has - moved on since, by any commit, is refused. See [Versions it refuses](#versions-it-refuses). -4. Merges the **merged commit** into develop as a merge commit, `Merge main back into develop - (release/…)`. The base branch rather than the release branch, so develop descends from the - base and consecutive releases bring one version bump each instead of divergent copies of the - same generated lines. Skipped when `develop-branch` is empty, for a repository that has no - develop branch. +3. Makes the merge of the release branch into the base branch, a merge commit `Merge release/… into + main` (or `into master`), on a temporary branch: the base is not written yet. When the base + already holds the branch, a retry, nothing is merged: the commit to build is then the one the + tag points at when the version is already published, and otherwise the base's tip. That tip has + to be the commit that merged the branch, or the branch's own tip when the base was + fast-forwarded to it. A base that has moved on since, by any commit, is refused. + See [Versions it refuses](#versions-it-refuses). +4. Makes the merge of that **merged commit** into develop, a merge commit `Merge main back into + develop (release/…)`, on a second temporary branch. The base branch rather than the release + branch, so develop descends from the base and consecutive releases bring one version bump each + instead of divergent copies of the same generated lines. Skipped when `develop-branch` is empty, + for a repository that has no develop branch. +5. Moves the base and develop to their merge commits in one update, then deletes the temporary + branches. See [Both merges or neither](#both-merges-or-neither). The merge commit on the base branch is the `base-sha` output: what the caller checks out and builds from, and what release-publish tags. GitHub makes both merge commits under the identity of `token`, `github-actions[bot]` for the default token, and signs them. The API never fast-forwards, so each release is one merge commit in the history. +## Both merges or neither + +The merge endpoint has no dry run: it writes the merge commit to the branch it is given. Asked for +the base and then for develop, a conflict on develop would leave the release on the base with no +tag and no build, and a hotfix branch cut from the base in that window would ship it. + +So each merge is made on a temporary branch, created at the tip the action read: +`release-merge/-/main` and `release-merge/-/develop`. Only when +both merge commits exist do the branches move, with the GraphQL mutation +[`updateRefs`](https://docs.github.com/en/graphql/reference/git#mutation-updaterefs), which applies +every update or none. Each branch moves from the tip its merge was made on to the merge commit, a +fast-forward. A branch that received a commit in the meantime is no longer at that tip: GitHub +refuses the update, neither branch moves, and the step fails with a message to run it again. + +The merge endpoint takes the temporary branch by name. A commit that someone else pushes to that +branch before the merge would end up under the merge commit, and the update would carry it to the +base. So the step checks that each merge commit was made on the tip the action read: its first +parent is that tip. When it is not, the step fails before it moves a branch, with a message to run +it again. The step fails the same way when GitHub answers that the temporary branch already holds +what is merged: the action only asks for a merge that the tip does not hold, so that answer means +the temporary branch moved. + +GitHub's answer to an update it does not make gives no reason for a branch that moved, so the step +reads the two branches again before it fails, and the message says what it found: + +- A branch received a commit before the update, and neither holds its merge commit. The message + names the branch. Run the step again. +- Both branches are where they were. A rule or the token refused the update, and GitHub's answer + names it, such as a base branch that only takes pull requests. Change that first. +- Both branches hold their merge commits, at their tip or under a commit that reached them since. + The request failed after GitHub applied it: the step warns and goes on. +- One of them could not be read or compared with its merge commit, or holds it while the other + does not. The message says what each one holds, to check by hand. + +The temporary branches are deleted when the step ends, whatever it did. One that could not be deleted +is a warning in the log; a run cancelled in the few seconds they exist can leave them too. Nothing +reads them, and they can be deleted by hand. A repository with a branch named `release-merge` cannot +hold them, since git keeps no branch under the name of another: the step fails before any merge. + The action reads and writes no checkout: it needs none before it, and leaves whatever checkout the job has as it was. Check out `base-sha` after it for the steps that build the release. @@ -71,31 +115,69 @@ job has as it was. Check out `base-sha` after it for the steps that build the re Every step is safe to run again after a late failure, which is what a retry from a release tool does: -- A branch that already holds the other merges as nothing to merge: GitHub answers that the base - already contains the head, and nothing is written. What the caller then builds and publishes is - the commit the tag points at, or the base's tip when there is no tag yet, which has to be the - commit that merged the branch; see [Versions it refuses](#versions-it-refuses). +- A branch that already holds the other has nothing to merge. The action asks GitHub that before it + makes the temporary branch, so a run that finds both branches that way writes nothing: no temporary + branch, no merge, no update. What the caller then builds and publishes is the commit the tag + points at, or the base's tip when there is no tag yet. That tip has to be the commit that merged + the branch, or the branch's own tip; see [Versions it refuses](#versions-it-refuses). - A version already published counts as a retry only when its tag contains the release branch, that is, when it was published from this branch. See [Versions it refuses](#versions-it-refuses). release-publish then skips the release. -- A conflict resolved by hand on the branch, then pushed, is found as an already-merged branch on - the next run, which goes on to the step that had not run. +- A conflict resolved by hand, then pushed, is not found again. The base and develop then hold the + release, and the next run goes on from there. See + [When a merge conflicts](#when-a-merge-conflicts). +- A release that is on the base and not on develop, which a deploy stopped by a conflict left + before the two merges were written together, gets the merge it lacks: only develop moves. -So a run that failed after merging the base, or in a later step of the caller, is rerun as it is; -nothing has to be undone first. +So a run that failed in a later step of the caller is rerun as it is; nothing has to be undone +first. ## When a merge conflicts -GitHub refuses the merge, nothing is written for that branch, and the step fails with the branch -named. The branches already merged stay merged: a conflict merging the base into develop leaves the -release on the base. Resolve the conflict on the branch by hand, push, and run the step again. The -API does not say which files conflict; the merge done by hand shows them. +GitHub refuses the merge and the step fails with the branch named. Neither the base nor develop is +written, whichever merge conflicted: a conflict merging the base into develop does not leave the +release on the base. + +To resolve it, merge the release by hand, in the order of a release that is merged by hand: + +1. Merge the release branch into the base. +2. Merge the base into develop. +3. Resolve the conflict where it shows, and push both branches. +4. If GitHub deleted the release branch after the push, restore it on its pull request. +5. Run the step again. + +The next run finds the release on both branches and merges nothing. It goes on with the release, +and the caller builds and publishes the commit that the merge by hand left on the base. The steps +are the same for a conflict on the base and for a conflict on develop. They are also the same for a +hotfix cut from the base and for a release cut from develop. The API does not say which files +conflict; the merge done by hand shows them. + +The merge into the base can be a merge commit or a fast-forward. A fast-forward is what git does +when the release branch already contains the base: a hotfix cut from the base, or a release cut +from a develop that the base was merged back into. A squash or a rebase does not put the commits +of the release branch on the base, so the next run would merge the branch again. + +If step 2 merged the release branch into develop, not the base, the next run merges the base into +develop itself. + +Step 4 is for a repository that has "Automatically delete head branches" on. The push marks the +pull request of the release branch as merged, and GitHub then deletes the branch. A run that is +started on the release branch, as a deploy from the release dashboard is, has no branch to start +on. Click **Restore branch** on the pull request +([GitHub docs](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/deleting-and-restoring-branches-in-a-pull-request)): +the branch comes back at its last commit. + +Between the push and the next run, the base holds the release with no tag and no build. Run the +step again right after the push. The log carries this line, on one line: ``` -MERGE_CONFLICT: merging main into develop conflicted. Resolve it on develop by hand and push, -then run this step again. Nothing was merged into develop. +MERGE_CONFLICT: merging main into develop conflicted. Merge release/M26.test into main by hand, +then main into develop, resolve the conflict and push both branches. If GitHub then deletes +release/M26.test, because its pull request is marked as merged, restore the branch on the pull +request. Then run this step again: it finds the merges done and goes on with the release. Nothing +was merged: main and develop are as they were. ``` and the `conflict` output names the branch. The [release @@ -104,8 +186,10 @@ marker `MERGE_CONFLICT` at the start of an output line of the job log, every lin runner prefixes with a timestamp. The marker is printed from the script, not written in the workflow, so it is not in the step's echoed inputs and only appears when a merge did conflict. -A merge GitHub refuses for another reason (the base branch moved while the merge was being made) -fails the step without the marker; running the step again is enough. +A failure that is not a conflict has no marker and writes neither branch: a branch that received a +commit while the merges were being made, an update a rule refuses, or a merge GitHub refuses for any +other reason. The message says which, and whether running the step again is enough; see +[Both merges or neither](#both-merges-or-neither). ## Versions it refuses @@ -137,9 +221,10 @@ fails the step without the marker; running the step again is enough. failed after the deploy, then another release or a commit pushed straight to the base, then a retry of this one would build those changes and publish them under this version: a deploy skips the tag it finds on wordpress.org and zips the current trunk, and release-publish tags whatever - commit it is given. So when the version has no tag yet, the base's tip has to be the commit that - merged the branch, the merge commit whose second parent is the branch's tip; a tip that is any - other commit, bump or not, is refused. Finish this release by hand at the commit that merged the + commit it is given. So when the version has no tag yet, the base's tip has to be one of two + commits: the commit that merged the branch (the merge commit whose second parent is the branch's + tip), or the branch's own tip, when the base was fast-forwarded to it. A tip that is any other + commit, bump or not, is refused. Finish this release by hand at the commit that merged the branch into the base, or release another version. A version already published is not refused (the `already-published` output says so, for the caller's own steps): its retry builds the commit the tag points at, what was published, and deploy and publish skip @@ -168,7 +253,7 @@ this; without `head`, the tip at that moment is what merges. | `version` | yes | | The version being released: three or four numeric parts. | | `base-branch` | no | `main` | The branch the release is merged into: `main`, or `master` where that is the repository's name for it. | | `develop-branch` | no | `develop` | The branch the base is merged back into. Empty for a repository without one: only the first merge is made. Write `develop-branch: ''` in the caller itself; a `workflow_dispatch` input left empty takes its default, so the empty value cannot be passed through one. | -| `token` | no | `github.token` | The token for the merges and the reads. Needs `contents: write`. See [The token](#the-token). | +| `token` | no | `github.token` | The token for the merges, the temporary branches and the reads. Needs `contents: write`. See [The token](#the-token). | ## Outputs @@ -177,7 +262,7 @@ this; without `head`, the tip at that moment is what merges. | `version` | The version released. | | `branch` | The release branch merged. | | `base-sha` | The commit on the base branch that holds the release: the merge commit, or the base's tip on a retry that found the merge done. The commit to check out and build from; pass it to release-publish as `target`. | -| `conflict` | The branch a merge conflicted on, or empty. A conflict fails the step, so read it with `continue-on-error` or in a later `if: failure()` step. | +| `conflict` | The branch a merge conflicted on, or empty. A conflict on either branch leaves both as they were. It fails the step, so read it with `continue-on-error` or in a later `if: failure()` step. | | `already-published` | `yes` when the version's GitHub release already existed when the step started (a retry of a published release), `no` otherwise. release-publish skips a published version by itself; read this to skip the steps of your own that write somewhere a retry of an older version must not touch, such as a zip copied to a site or a version written there: `if: steps.merge.outputs.already-published == 'no'`, or `if: steps.merge.outcome == 'success' && steps.merge.outputs.already-published == 'no'` when the merge step runs under `continue-on-error`. Compare with `no`, not with `yes`: `already-published` is among the outputs written last, so a step that failed before them leaves it empty; the `outcome` check covers a failure after them, in the runner's own wrap-up of the step. `conflict` is the one output a failure sets. It says nothing about whether those steps ran: keep them before release-publish, so the release is published only once they are done, and make each one safe to repeat for the same version (the same zip copied again, the same version written again), since a retry after a failed publish runs them again with `no`. | ## One deploy at a time @@ -202,29 +287,35 @@ actionlint 1.7 does not know the key and the plugin repositories lint their work ## The token -The job needs `contents: write`, and the token is used for the two merges and for the branch, tag, -release and file reads. It only ever reaches github-script's client: it is never handed to git, -never on a command line and never in the log. The caller's checkout, when there is one, can use +The job needs `contents: write`, and the token is used for the two merges, the temporary branches +they are made on, the update that moves the base and develop, and the branch, tag, release and file +reads. It only ever reaches github-script's client: it is never handed to git, never on a command +line and never in the log. The caller's checkout, when there is one, can use `persist-credentials: false`. The default `github.token` is enough when the repository's rules allow what the action does: a -merge written straight to the base branch and to develop. The merges are made through the API, not -opened as pull requests, so a base branch that only accepts pull requests refuses the merge, with -any token that is not on the rule's bypass list; a rule that requires signed commits is satisfied, -since GitHub signs the merge commits it makes. GiveWP's rules are the reference shape: the branches -are protected from deletion and non-fast-forward pushes, and `github.token` writes the merges. The -human gate is not the token: the caller puts the job in an environment with required reviewers, and -the release branch reached this step after its review and QA approval. A repository whose rules -still need another actor should pass a GitHub App installation token minted in the run rather than -a personal access token. What the token needs for the tag is in +fast-forward of the base branch and of develop to a merge commit, and branches created and deleted +under `release-merge/`. The merges are made through the API, not opened as pull requests, so a base +branch that only accepts pull requests refuses the update, with any token that is not on the rule's +bypass list, and so does a rule that restricts who creates branches, for the temporary ones; a rule +that requires signed commits is satisfied, since GitHub signs the merge commits it makes. GiveWP's +rules are the reference shape: the branches are protected from deletion and non-fast-forward pushes, +and `github.token` writes the merges. It also writes a release that changes files under +`.github/workflows/`: the temporary branches and the update take them. What `github.token` writes +starts no workflow run. Another token does, so a workflow that runs on every pushed branch would +run on the temporary branches for the seconds they exist; leave `release-merge/**` out of its +branches then. The human gate is not the token: the caller puts the job in an environment with +required reviewers, and the release branch reached this step after its review and QA approval. A +repository whose rules still need another actor should pass a GitHub App installation token minted +in the run rather than a personal access token. What the token needs for the tag is in [release-publish → The token](../release-publish/README.md#the-token). ## How it runs One [actions/github-script](https://github.com/actions/github-script) step runs -[`release-merge.js`](./release-merge.js): the checks and the merges, all through github-script's -Octokit. The inputs reach the script through environment variables, never interpolated into it, so -a crafted value is data rather than part of the program. +[`release-merge.js`](./release-merge.js): the checks, the merges and the update that moves the two +branches, all through github-script's Octokit. The inputs reach the script through environment +variables, never interpolated into it, so a crafted value is data rather than part of the program. The tests, `node --test` from the repository root, run the action against a recorded client and assert the requests it sends and the ones it does not; no git and no network. diff --git a/.github/actions/release-merge/action.yml b/.github/actions/release-merge/action.yml index d595187d..0ff450a2 100644 --- a/.github/actions/release-merge/action.yml +++ b/.github/actions/release-merge/action.yml @@ -4,12 +4,16 @@ # publishing the GitHub release is the release-publish action's, at the commit this one leaves on the # base (`base-sha`). # +# The action writes the two merges together or not at all. It makes each merge on a temporary +# branch, then moves the base and develop to their merge commits in one update. A conflict in +# either merge leaves both branches as they were. +# # The checks and the merges live in release-merge.js, run by actions/github-script, so there is no # dependency to install and nothing to build. Everything goes through the GitHub API: the branch, # tag and release reads, the version-file reads and the merges themselves. No checkout is needed; # the caller checks out `base-sha` afterwards to build from it. name: Release merge -description: Merges the release branch into the base and the base back into develop +description: Merges the release branch into the base and the base back into develop, both or neither inputs: branch: @@ -33,8 +37,8 @@ inputs: whose tag already exists, unless that tag's release was published from this branch, which makes the run a retry. On a retry nothing is merged, and the commit the caller then builds and publishes is the one the tag points at, or, before the tag exists, the base's tip, which has to - be the commit that merged the branch. The release itself is published by release-publish, after - this action. + be the commit that merged the branch or the branch's own tip. The release itself is published + by release-publish, after this action. required: true base-branch: description: 'The branch the release is merged into: `main`, or `master` where that is the name.' @@ -50,9 +54,10 @@ inputs: token: description: >- Token the merges are made with, and the branch, tag, release and file reads. It needs - `contents: write` on the repository, so the job needs that permission too. GitHub makes the - merge commits under its identity and signs them. It only ever reaches github-script's client, - never git or the log. + `contents: write` on the repository, so the job needs that permission too. The repository's + rules also have to let it create and delete the temporary branches under `release-merge/`. + GitHub makes the merge commits under its identity and signs them. It only ever reaches + github-script's client, never git or the log. required: false default: ${{ github.token }} @@ -72,8 +77,8 @@ outputs: conflict: description: >- Which branch a merge conflicted on, `main` or `develop` for the defaults, or empty when the - merges went through. A conflict fails the step, so a caller reads this with `continue-on-error` - or in a later `if: failure()` step. + merges went through. A conflict on either leaves both branches as they were. It fails the step, + so a caller reads this with `continue-on-error` or in a later `if: failure()` step. value: ${{ steps.merge.outputs.conflict }} already-published: description: >- @@ -89,7 +94,7 @@ outputs: runs: using: 'composite' steps: - - name: Merge the release into the base and the base back into develop + - name: Merge the release into the base and the base back into develop, both or neither id: merge uses: actions/github-script@v9 env: @@ -105,7 +110,7 @@ runs: INPUT_BASE_BRANCH: ${{ inputs.base-branch }} INPUT_DEVELOP_BRANCH: ${{ inputs.develop-branch }} with: - # Every read and the merges go through github-script's own client, built from this token. + # Every read and every write go through github-script's own client, built from this token. github-token: ${{ inputs.token }} script: | const { runMerge } = require(`${process.env.ACTION_PATH}/release-merge.js`) diff --git a/.github/actions/release-merge/release-merge.js b/.github/actions/release-merge/release-merge.js index a10b8e58..a8e808c3 100644 --- a/.github/actions/release-merge/release-merge.js +++ b/.github/actions/release-merge/release-merge.js @@ -6,11 +6,16 @@ * after this action and its build, at the commit this one leaves on the base (`base-sha`). * * runMerge checks the inputs and the version against the repository's tags, then asks GitHub for - * the two merges. Everything goes through the Octokit github-script supplies: the action reads and - * writes no checkout, so a test runs it against a recorded client and asserts the requests. + * the two merges. It makes each merge on a temporary branch first. When both merge commits exist, + * it moves the base and develop to them in one update, and GitHub moves both branches or neither. + * A conflict in either merge leaves the base and develop as they were. * - * Every step is safe to run again after a late failure: a branch that already holds the release - * merges as a no-op. + * Everything goes through the Octokit github-script supplies: the action reads and writes no + * checkout, so a test runs it against a recorded client and asserts the requests. + * + * Every step is safe to run again after a late failure. A branch that already holds the release + * has nothing to merge. A run that finds the base and develop in that state writes nothing: it + * creates no temporary branch either. */ const { validateVersion: validateReleaseVersion } = require('../../lib/versions.js') @@ -117,7 +122,7 @@ function mergeMessage(from, into) { * Whether a failed merge request is GitHub reporting a conflict, as opposed to any other refusal. * * The merge endpoint answers 409 for two things: a conflict between the branches, and a base that - * moved while the merge was being made. Only the first is a conflict for the caller to resolve. + * moved while the merge was being made. Only the first is a conflict for a person to resolve. * * @param {Error} error The Octokit error. * @@ -287,7 +292,11 @@ async function assertBranchHoldsVersion({ github, owner, repo, branch, ref, vers } /** - * Whether a commit contains a branch: the tag of a published version, against the release branch. + * Whether one commit contains another. runMerge asks two questions with it: + * + * - Does the tag of a published version contain the release branch? + * - Does the tip of the base, or of develop, already contain the commit that is about to be merged + * into it? * * @param {object} options * @param {object} options.github The Octokit github-script supplies. @@ -341,63 +350,358 @@ async function commitMergesBranch({ github, owner, repo, branch, ref, sha }) { } /** - * Merges one branch, or commit, into another as a merge commit, through the API. + * Creates the temporary branch that a merge is made on. The temporary branch starts at the tip of + * the branch that the merge is for. * - * GitHub makes the merge commit under the token's identity and signs it. A base that already holds - * the head answers 204 and nothing is written, which is what a retry after a late failure finds. A - * conflict prints the MERGE_CONFLICT marker on a line of its own, where the release dashboard looks - * for it, and fails; nothing is written for that branch. + * The merge endpoint has no dry run: it writes the merge commit to the branch that it is given. If + * the action gave it the base and then develop, the base would hold its merge before the merge + * into develop was tried. * * @param {object} options - * @param {object} options.github The Octokit github-script supplies. - * @param {object} options.core The @actions/core toolkit. - * @param {string} options.owner The repository owner. - * @param {string} options.repo The repository name. - * @param {string} options.into The branch merged into, e.g. `main`. - * @param {string} options.head What is merged: a branch name or a commit hash. - * @param {string} options.message The merge commit message. - * @param {string} options.label How to name `head` in the log, e.g. `release/M26.test`. + * @param {object} options.github The Octokit github-script supplies. + * @param {string} options.owner The repository owner. + * @param {string} options.repo The repository name. + * @param {string} options.name The temporary branch to create. + * @param {string} options.sha The commit to create it at. + * @param {string} options.nothingMerged The sentence that closes the error message. It says that + * the base and develop were not written. * - * @throws {Error} When the merge conflicts or GitHub refuses it. + * @throws {Error} When GitHub refuses to create the branch. * - * @returns {Promise<{merged: boolean, sha: string}>} Whether a merge commit was made, and the commit - * `into` points at afterwards: the merge commit, or its tip when there was nothing to merge. + * @returns {Promise} Resolves once the branch exists. */ -async function mergeInto({ github, core, owner, repo, into, head, message, label }) { - let response +async function createTempBranch({ github, owner, repo, name, sha, nothingMerged }) { try { - response = await github.rest.repos.merge({ owner, repo, base: into, head, commit_message: message }) + await github.rest.git.createRef({ owner, repo, ref: `refs/heads/${name}`, sha }) } catch (error) { - if (isConflict(error)) { - // core.info prints a plain line: the marker has to open an output line to count, see the README. - core.setOutput('conflict', into) - core.info( - `MERGE_CONFLICT: merging ${label} into ${into} conflicted. Resolve it on ${into} by hand and ` + - `push, then run this step again. Nothing was merged into ${into}.` - ) + const whatFailed = `Creating the temporary branch ${name} failed (HTTP ${error?.status}): ${error?.message}.` + + // GitHub answers "Reference already exists" when a branch of that name exists. The token and + // the rules are not the cause, so that message does not mention them. GitHub answers + // "Reference update failed" both when a rule restricts who creates branches and when the + // repository has a branch named release-merge. The message for any other answer gives these + // two causes. + if (error?.status === 422 && /already exists/i.test(String(error?.message))) { throw new Error( - `Merging ${label} into ${into} stopped on a conflict. Resolve it on ${into} by hand and push, ` + - `then run this step again: the merges already done are kept. Nothing was merged into ${into}.` + `${whatFailed} A branch of that name is left from another run of this step: delete it, then run this ` + + `step again. ${nothingMerged}` ) } - if (error?.status === 409) { - throw new Error( - `Merging ${label} into ${into} was refused: ${into} moved while the merge was being made ` + - `(${error.message}). Run this step again; the merges already done are kept.` + throw new Error( + `${whatFailed} Each merge is tried on a temporary branch first, so the token and the repository's rules have ` + + `to allow creating and deleting it, and the repository cannot have a branch named release-merge. ${nothingMerged}` + ) + } +} + +/** + * Deletes the temporary branches that the run created, whether the run passed or failed. + * + * If a temporary branch cannot be deleted, the step warns and goes on. By then the release is + * merged, or the run has already failed with its own message. Nothing reads a temporary branch. + * + * @param {object} options + * @param {object} options.github The Octokit github-script supplies. + * @param {object} options.core The @actions/core toolkit. + * @param {string} options.owner The repository owner. + * @param {string} options.repo The repository name. + * @param {string[]} options.names The temporary branches that were created. + * + * @returns {Promise} Resolves once every deletion was tried. + */ +async function deleteTempBranches({ github, core, owner, repo, names }) { + for (const name of names) { + try { + await github.rest.git.deleteRef({ owner, repo, ref: `heads/${name}` }) + } catch (error) { + core.warning( + `The temporary branch ${name} could not be deleted (HTTP ${error?.status}): ${error?.message}. ` + + 'Delete it by hand; nothing reads it.' ) } + } +} + +/** + * A commit hash as a message shows it: its first seven characters. + * + * @param {string} sha The commit hash. + * + * @returns {string} The short hash. + */ +function shortSha(sha) { + return sha.slice(0, 7) +} + +/** + * Makes one merge commit, on a temporary branch that starts at the tip of `into`, the branch that + * the merge is for. This function does not write `into`: moveBranches moves it to the merge commit + * once every merge is made. + * + * GitHub makes the merge commit under the token's identity and signs it. On a conflict, the + * function prints the MERGE_CONFLICT marker on a line of its own, where the release dashboard looks + * for it, and throws. + * + * runMerge checks first whether `tip` already holds `head`, and makes no temporary branch when it + * does. So this function is only called when `tip` does not hold `head`. + * + * The endpoint takes the temporary branch by name, so the merge is made on whatever commit that + * branch points at. The function checks that this commit is `tip`, and throws when it is not. It + * also throws when the endpoint answers 204, which says that the temporary branch already holds + * `head`: `tip` does not, so the branch is no longer at `tip`. + * + * @param {object} options + * @param {object} options.github The Octokit github-script supplies. + * @param {object} options.core The @actions/core toolkit. + * @param {string} options.owner The repository owner. + * @param {string} options.repo The repository name. + * @param {string} options.into The branch the merge is for, e.g. `main`. + * @param {string} options.tempBranch The temporary branch that the merge is made on. It starts + * at `tip`. + * @param {string} options.tip The commit that `into` pointed at when it was read. + * @param {string} options.head What is merged: a commit hash. + * @param {string} options.message The merge commit message. + * @param {string} options.label How to name `head` in the log, e.g. `release/M26.test`. + * @param {string} options.howToResolve The sentences that tell a person how to resolve a + * conflict by hand. They are the same for either merge. + * @param {string} options.nothingMerged The sentence that closes a failure message. It says that + * the base and develop were not written. + * + * @throws {Error} When the merge conflicts, GitHub refuses it, or it was not made on `tip`. + * + * @returns {Promise} The merge commit, which `into` should point at. + */ +async function mergeInto({ github, core, owner, repo, into, tempBranch, tip, head, message, label, howToResolve, nothingMerged }) { + let response + try { + response = await github.rest.repos.merge({ owner, repo, base: tempBranch, head, commit_message: message }) + } catch (error) { + if (isConflict(error)) { + // core.info prints a plain line: the marker has to open an output line to count, see the README. + core.setOutput('conflict', into) + core.info(`MERGE_CONFLICT: merging ${label} into ${into} conflicted. ${howToResolve} ${nothingMerged}`) + throw new Error(`Merging ${label} into ${into} stopped on a conflict. ${howToResolve} ${nothingMerged}`) + } - throw new Error(`Merging ${label} into ${into} failed (HTTP ${error?.status}): ${error?.message}`) + throw new Error(`Merging ${label} into ${into} failed (HTTP ${error?.status}): ${error?.message}. ${nothingMerged}`) } + // Anyone who can push to the repository can push to the temporary branch before the merge. The + // two checks below fail the step when the merge was not made on `tip`. + // + // A 204 says that the temporary branch already holds `head`. `tip` does not, so someone else + // put `head` on the temporary branch. Read as nothing to merge, the 204 would leave `into` out + // of the update at the end while the other branch moves. if (response.status === 204) { - core.info(`${into} already has ${label}: nothing to merge.`) + throw new Error( + `GitHub answered that the temporary branch ${tempBranch} already has ${label}, but ${into} did not have it at ` + + `${shortSha(tip)}, the commit that ${into} was read at: the temporary branch received a commit after this step ` + + `created it. ${nothingMerged} Run this step again.` + ) + } + + // The first parent of the merge commit is the commit that the merge was made on. When it is + // someone else's commit, the merge commit still descends from `tip`, so the update at the end, + // which only checks that `into` is still at `tip`, would move `into` to it and carry their + // commit along. + const madeOn = response.data.parents?.[0]?.sha + if (madeOn === undefined) { + throw new Error( + `GitHub's answer to the merge of ${label} into ${into} does not name the commit that the merge was made on, ` + + `so this step cannot confirm that it was made on ${shortSha(tip)}, the commit that ${into} was read at. ` + + `${nothingMerged} Run this step again.` + ) + } + if (madeOn !== tip) { + throw new Error( + `The merge of ${label} into ${into} was made on ${shortSha(madeOn)}, not on ${shortSha(tip)}, the commit that ` + + `${into} was read at: the temporary branch ${tempBranch} received a commit after this step created it. ` + + `${nothingMerged} Run this step again.` + ) + } + + return response.data.sha +} + +/** + * The mutation that moves several branches at once: GitHub applies every update or none. + * + * The REST API moves one ref per request. With two requests, GitHub could move the base and then + * refuse develop, which is the state that the temporary branches exist to avoid. + */ +const UPDATE_REFS = `mutation ($input: UpdateRefsInput!) { + updateRefs(input: $input) { + clientMutationId + } +}` + +/** + * What GitHub answered to a failed update, on one line. + * + * When GitHub refuses the update, it answers with GraphQL errors, and Octokit joins them with a + * line break before each one. When the request gets no usable answer, the error has a status and a + * message instead. + * + * @param {Error} error The Octokit error. + * + * @returns {string} The answer. + */ +function failureReason(error) { + if (Array.isArray(error?.errors)) { + return error.errors.map(({ message }) => String(message).replace(/\.+$/, '')).join('; ') + } + + return `HTTP ${error?.status}: ${error?.message}` +} + +/** + * After a failed update, reads the tip of each branch and whether the branch holds its merge + * commit. + * + * GitHub's answer does not say what happened. For a branch that moved, GitHub answers "Something + * went wrong", the same text as for a failure on its own side. And GitHub may have applied a + * request that got no answer. + * + * If the tip is neither the commit that the merge was made on nor the merge commit, the function + * compares the tip with the merge commit. If the tip descends from the merge commit, GitHub applied + * the update and the branch received a commit afterwards. Without this comparison, the message + * would say that nothing was merged, for a branch that holds the release. + * + * @param {object} options + * @param {object} options.github The Octokit github-script supplies. + * @param {string} options.owner The repository owner. + * @param {string} options.repo The repository name. + * @param {object[]} options.moves `{branch, from, to}` per branch. + * + * @returns {Promise} Each move, with two more fields. `currentTip` is the branch's tip, + * or null if the tip could not be read. `hasMergeCommit` says whether `currentTip` is the + * merge commit or descends from it, and is null if that could not be checked. + */ +async function readBranchStates({ github, owner, repo, moves }) { + const states = [] + for (const move of moves) { + let currentTip = null + let hasMergeCommit = null + try { + currentTip = (await github.rest.repos.getBranch({ owner, repo, branch: move.branch })).data.commit.sha + hasMergeCommit = + currentTip === move.to || + (currentTip !== move.from && + (await commitContainsBranch({ github, owner, repo, branch: move.branch, ref: move.to, sha: currentTip }))) + } catch { + // The values stay null, and the message says what could not be read or compared. + } + states.push({ ...move, currentTip, hasMergeCommit }) + } + + return states +} + +/** + * Moves the base and develop to their merge commits in one update, so the remote never holds one + * merge without the other. + * + * The update moves each branch from the tip that its merge was made on. If a branch is no longer + * at that tip, GitHub refuses the update and moves no branch. The merge commit descends from the + * tip, so the move is a fast-forward and never needs to be forced. + * + * When the update fails, the function reads the branches again, and the message says what they + * hold. The message states only what was checked, because each case needs a different action from + * the reader. + * + * @param {object} options + * @param {object} options.github The Octokit github-script supplies. + * @param {object} options.core The @actions/core toolkit. + * @param {string} options.owner The repository owner. + * @param {string} options.repo The repository name. + * @param {object[]} options.moves `{branch, from, to}` per branch. `from` is the tip that + * the branch was read at, and `to` is the merge commit made + * on that tip. + * @param {string} options.nothingMerged The sentence that closes a message when the base and + * develop were not written. + * + * @throws {Error} When the repository cannot be read, a branch received a commit while the merges + * were being made, GitHub does not move the branches, or the update failed and what + * the branches hold cannot be confirmed. + * + * @returns {Promise} Resolves once the branches are moved. That includes a request that + * failed while the branches hold their merge commits. + */ +async function moveBranches({ github, core, owner, repo, moves, nothingMerged }) { + let repositoryId + try { + repositoryId = (await github.rest.repos.get({ owner, repo })).data.node_id + } catch (error) { + throw new Error(`Reading ${owner}/${repo} failed (HTTP ${error?.status}): ${error?.message}. ${nothingMerged}`) + } + + const refUpdates = moves.map(({ branch, from, to }) => ({ name: `refs/heads/${branch}`, beforeOid: from, afterOid: to })) + let reason + try { + await github.graphql(UPDATE_REFS, { input: { repositoryId, refUpdates } }) + + return + } catch (error) { + reason = failureReason(error) + } + + const names = moves.map(({ branch }) => branch) + const plural = names.length > 1 + const branchList = names.join(' and ') + const branchListTogether = plural ? `${branchList} together` : branchList + const states = await readBranchStates({ github, owner, repo, moves }) + + // The request failed, and GitHub applied the update: the connection was lost after that. A + // branch that received a commit after the update still holds its merge commit. + if (states.every(({ hasMergeCommit }) => hasMergeCommit === true)) { + core.warning( + `Moving ${branchListTogether} failed (${reason}), but the update was applied: ` + + `${branchList} ${plural ? 'hold their merge commits' : 'holds its merge commit'}.` + ) + + return + } + + // At least one branch could not be read or compared, or one branch holds its merge commit and + // the other does not. + if (states.some(({ hasMergeCommit }) => hasMergeCommit !== false)) { + const descriptions = states.map(({ branch, currentTip, hasMergeCommit }) => { + if (currentTip === null) { + return `${branch} could not be read` + } + if (hasMergeCommit === null) { + return `${branch} is at ${shortSha(currentTip)}, which could not be compared with its merge commit` + } + + return hasMergeCommit ? `${branch} holds its merge commit` : `${branch} is at ${shortSha(currentTip)}` + }) - return { merged: false, sha: await readBranchTip({ github, owner, repo, branch: into }) } + throw new Error( + `Moving ${branchListTogether} failed (${reason}), and what the branches hold now could not be confirmed: ` + + `${descriptions.join(', ')}. Check them before running this step again.` + ) + } + + // From here on, no branch holds its merge commit. The comparison checked that; it is not + // inferred from a tip that changed. + const moved = states.filter(({ currentTip, from }) => currentTip !== from) + if (moved.length > 0) { + const movedList = moved + .map(({ branch, from, currentTip }) => `${branch} (at ${shortSha(currentTip)}, the merge was made on ${shortSha(from)})`) + .join(' and ') + + throw new Error( + `${movedList} received a commit while the merges were being made, so GitHub moved ` + + `${plural ? 'neither branch' : 'nothing'} (${reason}). Nothing was merged. Run this step again.` + ) } - return { merged: true, sha: response.data.sha } + throw new Error( + `GitHub did not move ${branchListTogether}: ${reason}. ${nothingMerged} No commit reached ` + + `${plural ? 'them' : 'it'} while the merges were being made: when the answer names a rule or a ` + + 'permission, change that before running this step again.' + ) } /** @@ -411,6 +715,11 @@ async function mergeInto({ github, core, owner, repo, into, head, message, label * commit in the history. A repository without a develop branch leaves `develop-branch` empty, and * only the first merge is made. * + * The action writes the two merges together or not at all. It makes each merge on a temporary + * branch. Once both merge commits exist, it moves the base and develop to them in one update. If + * the merges were written one after the other, a conflict on develop would leave the release on + * the base with no tag and no build. A hotfix branch cut from the base would then ship that code. + * * Nothing is read from or written to a checkout: the caller checks out `base-sha` afterwards for * the steps that build the release from it. * @@ -420,9 +729,9 @@ async function mergeInto({ github, core, owner, repo, into, head, message, label * @param {object} options.env The environment the action manifest put its inputs in. * * @throws {Error} When an input is wrong, a branch is missing, the tag exists without a release, a - * merge conflicts, or a read or a merge fails. + * merge conflicts, a branch moved while the merges were made, or a read or a write fails. * - * @returns {Promise} Resolves once both merges are made and the outputs are set, + * @returns {Promise} Resolves once both branches hold their merge and the outputs are set, * `already-published` among them: `yes` when the version's release already existed when the step started. */ async function runMerge({ github, core, env }) { @@ -454,9 +763,11 @@ async function runMerge({ github, core, env }) { 'the deploy again on the branch as it is now. Nothing was merged.' ) } - for (const name of develop === null ? [base] : [base, develop]) { - await readBranchTip({ github, owner, repo, branch: name }) - } + + // The tips of the base and develop are read once as well. Each merge is made on the tip that + // was read, and the update moves the branch from that tip to the merge commit, or does not move it. + const baseTip = await readBranchTip({ github, owner, repo, branch: base }) + const developTip = develop === null ? null : await readBranchTip({ github, owner, repo, branch: develop }) await assertBranchHoldsVersion({ github, owner, repo, branch, ref: branchSha, version }) @@ -475,58 +786,123 @@ async function runMerge({ github, core, env }) { core.info(`${version} is already published (${releaseUrl}) from ${branch}: nothing to publish again.`) } - const { merged: mergedBase, sha: mergedSha } = await mergeInto({ - github, - core, - owner, - repo, - into: base, - head: branchSha, - message: mergeMessage(branch, base), - label: branch, - }) - - // base-sha is the commit the release is published at and built from. A merge that was made is - // that merge commit, which holds the version the branch was just checked for. A retry that found - // the merge done gets the base's tip, and that tip is only this release while nothing has been - // merged or pushed since: a publish that failed after the deploy, then another release, then a - // retry would build the later release's code and publish it under this version, since the - // caller's deploy and publish each skip what they find done. So when the version is already - // published, the retry builds the commit the tag was made from, what was published, and the base - // moving on changes nothing; when it is not, the tip has to be the commit that merged the branch. - let baseSha = mergedSha - if (!mergedBase) { - if (tagged) { - baseSha = tagSha - core.info(`${version} builds at ${tagSha}, the commit it was published from.`) - } else if (!(await commitMergesBranch({ github, owner, repo, branch, ref: branchSha, sha: mergedSha }))) { - throw new Error( - `${base} already had ${branch} and has moved on since: its tip ${mergedSha} is not the commit that merged ` + - `${branch}, so a build from it would publish other changes under ${version}. There is nothing left ` + - `to merge for ${version}; finish it by hand at the commit that merged ${branch} into ${base}, or ` + - 'release another version. Nothing was merged.' - ) + // Until the update at the end, the action writes only the temporary branches. Their names carry + // the run id and the attempt, so two runs never share a temporary branch. From here on, a failure + // message closes with this sentence when the base and develop are where they were. + const nothingMerged = `Nothing was merged: ${develop === null ? `${base} is as it was` : `${base} and ${develop} are as they were`}.` + // A conflict is resolved the way a release is merged by hand: the release branch into the base, + // then the base into develop. The instruction is the same for a conflict in either merge, and for + // a hotfix cut from the base as for a release cut from develop. The next run then finds each + // branch holding what would be merged into it. + // + // The merge by hand marks the pull request of the release branch as merged. A repository with + // "Automatically delete head branches" on then deletes the release branch, and a run started on + // that branch has nothing to start on. So the instruction says to restore the branch first. + const restore = + `If GitHub then deletes ${branch}, because its pull request is marked as merged, restore the branch ` + + 'on the pull request.' + const howToResolve = + develop === null + ? `Merge ${branch} into ${base} by hand, resolve the conflict and push. ${restore} Then run this step ` + + 'again: it finds the merge done and goes on with the release.' + : `Merge ${branch} into ${base} by hand, then ${base} into ${develop}, resolve the conflict and push ` + + `both branches. ${restore} Then run this step again: it finds the merges done and goes on with the release.` + const tempPrefix = `release-merge/${env.GITHUB_RUN_ID}-${env.GITHUB_RUN_ATTEMPT}` + const tempBranches = [] + const mergeOnTempBranch = async ({ into, tip, head, message, label, headIsNew = false }) => { + // If the tip already holds the head, there is nothing to merge. A retry after a late failure + // finds that for the base and for develop. The action checks this before it creates the + // temporary branch, so that retry writes nothing. When this run has just made the head, no + // branch holds it yet, so the check is skipped. + if (!headIsNew && (await commitContainsBranch({ github, owner, repo, branch: label, ref: head, sha: tip }))) { + core.info(`${into} already has ${label}: nothing to merge.`) + + return { merged: false, sha: tip } } + + const tempBranch = `${tempPrefix}/${into}` + await createTempBranch({ github, owner, repo, name: tempBranch, sha: tip, nothingMerged }) + tempBranches.push(tempBranch) + + const sha = await mergeInto({ github, core, owner, repo, into, tempBranch, tip, head, message, label, howToResolve, nothingMerged }) + + return { merged: true, sha } } - // The second merge takes that commit, not the base's name, so develop receives exactly what is - // being released even if the base moves on. + let mergedBase let mergedDevelop = null - if (develop === null) { - core.info(`develop-branch is empty: ${base} is not merged back into a develop branch.`) - } else { - mergedDevelop = ( - await mergeInto({ - github, - core, - owner, - repo, + let baseSha + try { + const baseMerge = await mergeOnTempBranch({ + into: base, + tip: baseTip, + head: branchSha, + message: mergeMessage(branch, base), + label: branch, + }) + mergedBase = baseMerge.merged + + // base-sha is the commit the release is published at and built from. A merge that was made is + // that merge commit, which holds the version the branch was just checked for. A retry that found + // the merge done gets the base's tip, and that tip is only this release while nothing has been + // merged or pushed since: a publish that failed after the deploy, then another release, then a + // retry would build the later release's code and publish it under this version, since the + // caller's deploy and publish each skip what they find done. So when the version is already + // published, the retry builds the commit the tag was made from, what was published, and the base + // moving on changes nothing; when it is not, the tip has to be the commit that merged the branch. + // + // A base that was fast-forwarded to the release branch has no merge commit: its tip is the + // branch's tip. A merge by hand leaves that when the branch already contains the base, as a + // hotfix cut from the base does, and a release cut from a develop that the base was merged back + // into. That tip holds nothing but the release, so the retry builds it. + baseSha = baseMerge.sha + if (!mergedBase) { + if (tagged) { + baseSha = tagSha + core.info(`${version} builds at ${tagSha}, the commit it was published from.`) + } else if ( + baseTip !== branchSha && + !(await commitMergesBranch({ github, owner, repo, branch, ref: branchSha, sha: baseTip })) + ) { + throw new Error( + `${base} already had ${branch} and has moved on since: its tip ${baseTip} is not the commit that merged ` + + `${branch}, so a build from it would publish other changes under ${version}. There is nothing left ` + + `to merge for ${version}; finish it by hand at the commit that merged ${branch} into ${base}, or ` + + `release another version. ${nothingMerged}` + ) + } + } + + const moves = mergedBase ? [{ branch: base, from: baseTip, to: baseSha }] : [] + + // The second merge takes that commit, not the base's name, so develop receives exactly what is + // being released even if the base moves on. + if (develop === null) { + core.info(`develop-branch is empty: ${base} is not merged back into a develop branch.`) + } else { + const developMerge = await mergeOnTempBranch({ into: develop, + tip: developTip, head: baseSha, message: `Merge ${base} back into ${develop} (${branch})`, label: base, + headIsNew: mergedBase, }) - ).merged + mergedDevelop = developMerge.merged + if (mergedDevelop) { + moves.push({ branch: develop, from: developTip, to: developMerge.sha }) + } + } + + // Every merge commit exists, so the branches move to them now, in one update. A branch that + // already held its merge is not part of the update. + if (moves.length > 0) { + await moveBranches({ github, core, owner, repo, moves, nothingMerged }) + } + } finally { + // The temporary branches are deleted after the update, not before. Until the update, they are + // the only branches that hold the merge commits. + await deleteTempBranches({ github, core, owner, repo, names: tempBranches }) } // One item of the list the deploy's actions write to the job summary, with each branch as a link. diff --git a/.github/actions/release-prep/release-prep.js b/.github/actions/release-prep/release-prep.js index 2755bd0a..0c5a4cd5 100644 --- a/.github/actions/release-prep/release-prep.js +++ b/.github/actions/release-prep/release-prep.js @@ -15,7 +15,7 @@ const { execFileSync } = require('node:child_process') // The three-or-four-parts pattern lives with the other version rules, shared with release-merge. const { compareVersions, STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js') -const { readRepository, tagExists } = require('../../lib/github.js') +const { readRepository, tagExists, repositoryUrl, branchLink, commitLink } = require('../../lib/github.js') const { runOrFail } = require('../../lib/exec.js') // How pup is resolved, downloaded and run lives with the other actions that run it. const { @@ -612,6 +612,8 @@ async function runCommit({ github, core, exec, env, cwd = process.cwd() }) { const version = readVersion(env.INPUT_VERSION) const message = commitMessage(branch, version) const { owner, repo } = readRepository(env, 'Nothing was committed.') + // The job summary shows the branch and the commit as links, as the deploy's actions do. + const url = repositoryUrl(env, { owner, repo }) await runOrFail(exec, 'git', ['add', '--all'], { cwd }, 'Staging the changes') @@ -630,7 +632,7 @@ async function runCommit({ github, core, exec, env, cwd = process.cwd() }) { core.setOutput('commit', '') core.setOutput('files', '') await core.summary - .addRaw(`Nothing to commit: \`${branch}\` already holds ${version}.`, true) + .addRaw(`Nothing to commit: ${branchLink(url, branch)} already holds ${version}.`, true) .write() return @@ -706,7 +708,7 @@ async function runCommit({ github, core, exec, env, cwd = process.cwd() }) { core.setOutput('files', files.join('\n')) // A Markdown list rather than addList, whose HTML list would show the backticks literally. await core.summary - .addRaw(`Committed \`${commit.sha.slice(0, 7)}\` "${message}" to \`${branch}\`:\n\n`) + .addRaw(`Committed ${commitLink(url, commit.sha)} "${message}" to ${branchLink(url, branch)}:\n\n`) .addRaw(files.map((file) => `- \`${file}\``).join('\n'), true) .write() } diff --git a/README.md b/README.md index c578e292..85e45e17 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ Each phase ends with something people can actually use. - [x] Port `analyze-hooks` from TEC: the actions and filters a release adds, updates, deprecates or removes and the views it adds, changes or removes, as pending changelog entries. The search paths, the views paths and the changelog types are inputs, and a `v` on the release tag is accepted. - [ ] Add `setup-node` for the npm crowd. - [x] Add `release-prep`: version bump, TBD replacement and changelog through pup and the changelogger action, committed to the release branch through the GitHub API. A caller to copy is in `templates/workflows/release-prep.yml`. -- [x] Add `release-merge`: the release branch into the base branch, the base back into develop, each step safe to rerun and a conflict reported with a `MERGE_CONFLICT` line. +- [x] Add `release-merge`: the release branch into the base branch, the base back into develop, both merges written together or not at all, each step safe to rerun and a conflict reported with a `MERGE_CONFLICT` line. - [x] Add `release-publish`: the GitHub release for a version at a commit, with a title, notes from a file and assets uploaded before the release is public, skipped when it already exists. The complete deploy workflow to copy, both actions with the build between them, is `templates/workflows/release.yml`. - [x] Add `zip-name` and `release-zip`: the zip's name before the build, with a pre-release label (`dev`, `alpha`, `beta`, `rc`) and an optional build number, then `pup build`, `check`, `i18n` and `package` for that version. What `stellarwp/github-actions`' `zip.yml` does, as two actions so the bucket can be asked for the name first. The caller to copy, with the S3 check, the upload, the Slack notice and the artifact around them, is `templates/workflows/zip.yml`. - [x] Add `herald-publish`: the build uploaded to Herald and published as a version of a product, with a `ci` API key. A ZIP of another version is refused, and a rerun updates the version instead of creating it twice. `templates/workflows/release.yml` shows the step, commented out, between the build and `release-publish`. diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index eb7925b9..6a052828 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -71,7 +71,8 @@ jobs: exit 1 fi - # The merges go through the GitHub API: no checkout is needed before this step. + # The merges go through the GitHub API: no checkout is needed before this step. The base and + # develop receive their merge together, so a conflict on either leaves both as they were. - uses: stellarwp/plugin-toolbox/.github/actions/release-merge@v1 id: merge with: diff --git a/tests/actions/release-merge/release-merge.test.js b/tests/actions/release-merge/release-merge.test.js index f4804339..abb56d33 100644 --- a/tests/actions/release-merge/release-merge.test.js +++ b/tests/actions/release-merge/release-merge.test.js @@ -28,6 +28,8 @@ function mergeEnv(overrides = {}) { INPUT_BASE_BRANCH: 'main', INPUT_DEVELOP_BRANCH: 'develop', GITHUB_REPOSITORY: 'stellarwp/plugin', + GITHUB_RUN_ID: '77', + GITHUB_RUN_ATTEMPT: '1', ...overrides, } } @@ -49,6 +51,15 @@ const TIP = { develop: 'cccccccccccccccccccccccccccccccccccccccc', } +/** The temporary branches of run 77, first attempt. Each merge is made on one of them before a branch moves. */ +const TEMP = { + main: 'release-merge/77-1/main', + develop: 'release-merge/77-1/develop', +} + +/** The repository's node ID. The mutation that moves the branches takes it to name the repository. */ +const REPOSITORY_ID = 'R_kgDOplugin' + /** The merge commits GitHub answers with: the release on main, then main on develop. */ const MERGED = { main: 'dddddddddddddddddddddddddddddddddddddddd', @@ -72,6 +83,10 @@ const API = { compare: (sha, ref = TIP['release/M26.test']) => `${REPO}/compare/${encodeURIComponent(`${ref}...${sha}`)}`, commit: (sha) => `${REPO}/commits/${sha}`, merges: `${REPO}/merges`, + repository: REPO, + refs: `${REPO}/git/refs`, + ref: (name) => `${REPO}/git/refs/${encodeURIComponent(`heads/${name}`)}`, + graphql: '/graphql', } /** @@ -133,10 +148,23 @@ function files(contents = {}, ref = TIP['release/M26.test']) { })) } +/** + * The body of a merge commit as the merge endpoint answers it. The first parent is the commit that + * the merge was made on, the second is the commit that was merged. + * + * @param {string} sha The merge commit. + * @param {string[]} parents Its parents' hashes. + * + * @returns {object} The body. + */ +function mergeCommit(sha, parents) { + return { sha, parents: parents.map((parent) => ({ sha: parent })) } +} + /** What the merge endpoint answers: a merge commit, nothing to merge, or a refusal. */ const MERGE = { - main: { status: 201, body: { sha: MERGED.main } }, - develop: { status: 201, body: { sha: MERGED.develop } }, + main: { status: 201, body: mergeCommit(MERGED.main, [TIP.main, TIP['release/M26.test']]) }, + develop: { status: 201, body: mergeCommit(MERGED.develop, [TIP.develop, MERGED.main]) }, done: { status: 204 }, conflict: { status: 409, body: { message: 'Merge conflict' } }, moved: { status: 409, body: { message: 'Base branch was modified. Review and try the merge again.' } }, @@ -154,13 +182,91 @@ function merges(responses) { } /** - * The rules of the common case: no tag, three branches, a prepared release branch, both merges made. + * The answers to the mutation that moves the branches. The first three are what GitHub sent to real + * updates: + * + * - `done`: the update was applied. + * - `moved`: a branch is no longer at the tip that it was read at. GitHub names neither the branch + * nor the reason. + * - `protected`: the base only takes pull requests. + * - `unanswered`: the request got no usable answer. + */ +const MOVE = { + done: { body: { data: { updateRefs: { clientMutationId: null } } } }, + moved: { + body: { + errors: [ + { + message: + 'Something went wrong while executing your query on 2026-12-02T22:36:20Z. Please include `0F82:23A134:76FFF:C508E:6B109D62` when reporting this issue.', + }, + ], + }, + }, + protected: { + body: { + data: { updateRefs: null }, + errors: [ + { + type: 'UNPROCESSABLE', + path: ['updateRefs'], + locations: [{ line: 2, column: 3 }], + message: "Branch 'refs/heads/main' is protected: Changes must be made through a pull request..", + }, + ], + }, + }, + unanswered: { status: 502, body: { message: 'Server Error' } }, +} + +/** + * Makes a branch answer differently from its second read on. The second read is the one that the + * action makes after a failed update. + * + * @param {object[]} rules The rules, with one per branch as `branches` builds them. + * @param {object} later Maps a branch name to the tip that the second read returns, or to a whole + * response. + * + * @returns {object[]} The rules, with those branches answering their first read as before. + */ +function readAgain(rules, later) { + return rules.map((rule) => { + const name = Object.keys(later).find((branch) => rule.method === 'GET' && rule.path === API.branch(branch)) + if (name === undefined) { + return rule + } + + const second = typeof later[name] === 'string' ? { body: { name, commit: { sha: later[name] } } } : later[name] + + return { method: rule.method, path: rule.path, responses: [{ body: rule.body }, second] } + }) +} + +/** + * The rule that answers that one commit already holds another. The action asks this before it makes + * a temporary branch, and a retry after a late failure gets this answer for the base and for develop. + * + * @param {string} tip The commit asked about: the tip of the base or of develop. + * @param {string} head The commit that `tip` holds. Defaults to the release branch's tip. + * + * @returns {object} The rule. + */ +function holds(tip, head = TIP['release/M26.test']) { + return { method: 'GET', path: API.compare(tip, head), body: { status: 'ahead' } } +} + +/** + * The rules of the common case: no tag, three branches, a prepared release branch that main does + * not hold yet, both merges made on their temporary branches, and the two branches moved together. * * @param {object} options * @param {object[]} options.tag Rules for the tag and release reads; none for an untagged version. * @param {string[]} options.branches The branches the repository has. * @param {object} options.files Files of the release branch to change from the fixture. * @param {object[]} options.merges What the merge requests are answered with. + * @param {object} options.tempBranch What creating a temporary branch is answered with. + * @param {object} options.cleanup What deleting a temporary branch is answered with. + * @param {object} options.move What the mutation that moves the branches is answered with. * @param {object[]} options.extra Any other rule. * * @returns {object[]} The rules. @@ -170,9 +276,24 @@ function repositoryWith({ branches: names = Object.keys(TIP), files: contents = {}, merges: answers = [MERGE.main, MERGE.develop], + tempBranch = { status: 201, body: {} }, + cleanup = { status: 204 }, + move = MOVE.done, extra = [], } = {}) { - return [...tag, ...branches(names), ...files(contents), merges(answers), ...extra] + return [ + ...tag, + ...branches(names), + ...files(contents), + { method: 'GET', path: API.compare(TIP.main), body: { status: 'diverged' } }, + merges(answers), + { method: 'POST', path: API.refs, ...tempBranch }, + { method: 'DELETE', path: API.ref(TEMP.main), ...cleanup }, + { method: 'DELETE', path: API.ref(TEMP.develop), ...cleanup }, + { method: 'GET', path: API.repository, body: { node_id: REPOSITORY_ID } }, + { method: 'POST', path: API.graphql, ...move }, + ...extra, + ] } /** @@ -197,6 +318,45 @@ function mergesAsked(requests) { return requests.filter((request) => request.method === 'POST' && request.path === API.merges).map((request) => request.body) } +/** + * The branch updates in each mutation that was sent, in order: one entry per mutation. + * + * @param {object[]} requests The requests recordingFetch recorded. + * + * @returns {object[][]} `{name, beforeOid, afterOid}` per branch, per mutation. + */ +function movesAsked(requests) { + return requests + .filter((request) => request.method === 'POST' && request.path === API.graphql) + .map((request) => { + assert.match(request.body.query, /updateRefs\(input: \$input\)/) + assert.strictEqual(request.body.variables.input.repositoryId, REPOSITORY_ID) + + return request.body.variables.input.refUpdates + }) +} + +/** + * The writes to the repository, in order, as `METHOD path`: everything but the reads. + * + * @param {object[]} requests The requests recordingFetch recorded. + * + * @returns {string[]} One line per write. + */ +function written(requests) { + return requested(requests.filter((request) => request.method !== 'GET')) +} + +/** The writes of a run that made both merges and moved nothing: it creates the temporary branches, then deletes them. */ +const TEMP_ONLY = [ + `POST ${API.refs}`, + `POST ${API.merges}`, + `POST ${API.refs}`, + `POST ${API.merges}`, + `DELETE ${API.ref(TEMP.main)}`, + `DELETE ${API.ref(TEMP.develop)}`, +] + describe('release-merge', () => { describe('validateVersion', () => { it('accepts three or four numeric parts, the shape the dashboard publishes', () => { @@ -325,7 +485,7 @@ describe('release-merge', () => { }) describe('runMerge', () => { - it('merges the release into the base, then the merged commit back into develop, as two merge commits', async (t) => { + it('tries both merges on temporary branches, then moves the base and develop together in one update', async (t) => { const { github, requests } = await octokitFor(repositoryWith()) const { core, outputs, summary } = await coreWithOutputs(t) @@ -339,14 +499,44 @@ describe('release-merge', () => { `GET ${API.file('.puprc')}`, `GET ${API.file('plugin.php')}`, `GET ${API.file('readme.txt')}`, + // The action asks GitHub whether main already holds the release branch. It does not ask + // whether develop holds the commit just made for main: no branch holds that commit yet. + `GET ${API.compare(TIP.main)}`, + // Each merge is made on a temporary branch at the tip that was read: nothing reaches main or + // develop until both merges exist. + `POST ${API.refs}`, `POST ${API.merges}`, + `POST ${API.refs}`, `POST ${API.merges}`, + `GET ${API.repository}`, + `POST ${API.graphql}`, + // The temporary branches are deleted last, so the merge commits are still on a branch when + // main and develop move. + `DELETE ${API.ref(TEMP.main)}`, + `DELETE ${API.ref(TEMP.develop)}`, ]) + assert.deepStrictEqual( + requests.filter((request) => request.method === 'POST' && request.path === API.refs).map((request) => request.body), + [ + { ref: `refs/heads/${TEMP.main}`, sha: TIP.main }, + { ref: `refs/heads/${TEMP.develop}`, sha: TIP.develop }, + ] + ) assert.deepStrictEqual(mergesAsked(requests), [ // The tip the version check read, not the branch by name: what was checked is what is merged. - { base: 'main', head: TIP['release/M26.test'], commit_message: 'Merge release/M26.test into main' }, - // The commit just made on main, not main by name: develop gets exactly what is released. - { base: 'develop', head: MERGED.main, commit_message: 'Merge main back into develop (release/M26.test)' }, + // The message names main, the branch that the commit is for, not the temporary branch. + { base: TEMP.main, head: TIP['release/M26.test'], commit_message: 'Merge release/M26.test into main' }, + // The commit just made for main, not main by name: develop gets exactly what is released. + { base: TEMP.develop, head: MERGED.main, commit_message: 'Merge main back into develop (release/M26.test)' }, + ]) + // One mutation moves both branches, each from the tip that its merge was made on to its merge + // commit. GitHub moves both or neither, and refuses the update when a branch is no longer at + // that tip. + assert.deepStrictEqual(movesAsked(requests), [ + [ + { name: 'refs/heads/main', beforeOid: TIP.main, afterOid: MERGED.main }, + { name: 'refs/heads/develop', beforeOid: TIP.develop, afterOid: MERGED.develop }, + ], ]) assert.deepStrictEqual(outputs(), { branch: 'release/M26.test', @@ -402,6 +592,7 @@ describe('release-merge', () => { `GET ${API.file('plugin.php', tip)}`, `GET ${API.file('readme.txt', tip)}`, `GET ${API.compare(TAG_COMMIT, tip)}`, + `GET ${API.compare(TIP.main, tip)}`, ], 'every read names the tip, never the branch' ) @@ -451,6 +642,7 @@ describe('release-merge', () => { assert.ok(!requested(requests).some((line) => line.includes('develop')), requested(requests).join('\n')) assert.strictEqual(mergesAsked(requests).length, 1) + assert.deepStrictEqual(movesAsked(requests), [[{ name: 'refs/heads/main', beforeOid: TIP.main, afterOid: MERGED.main }]]) assert.strictEqual(outputs()['base-sha'], MERGED.main) assert.strictEqual(outputs()['develop-branch'], '') assert.strictEqual(outputs().conflict, '') @@ -458,7 +650,7 @@ describe('release-merge', () => { assert.match(summary(), /^- \*\*Release 4\.17\.0:\*\* merged \[release\/M26\.test\]\(.*\) into \[main\]\(.*\), no develop branch to merge back into\.$/m) }) - it('does nothing on a retry after a late failure: both merges answer already merged', async (t) => { + it('writes nothing on a retry after a late failure: both branches already hold the release', async (t) => { // The publish step tagged the first run's merge commit, so the retry finds the tag with its // release, and main's tip is that commit. const { github, requests } = await octokitFor( @@ -467,15 +659,15 @@ describe('release-merge', () => { { method: 'GET', path: API.tag, body: { ref: 'refs/tags/4.17.0', object: { sha: MERGED.main, type: 'commit' } } }, PUBLISHED[1], ], - merges: [MERGE.done, MERGE.done], - extra: [{ method: 'GET', path: API.compare(MERGED.main), body: { status: 'ahead' } }], + // The tag and main are at the same commit, so one rule answers two questions: the tag + // contains the branch, and main does too. + extra: [holds(MERGED.main), holds(TIP.develop, MERGED.main)], }).map((rule) => (rule.path === API.branch('main') ? { ...rule, body: { name: 'main', commit: { sha: MERGED.main } } } : rule)) ) const { core, outputs, logged } = await coreWithOutputs(t) await runMerge({ github, core, env: mergeEnv() }) - assert.strictEqual(mergesAsked(requests).length, 2) assert.match(logged(), /main already has release\/M26\.test: nothing to merge/) assert.match(logged(), /develop already has main: nothing to merge/) assert.strictEqual(outputs().conflict, '') @@ -483,8 +675,35 @@ describe('release-merge', () => { // published. Nothing else is read about main's tip. assert.strictEqual(outputs()['base-sha'], MERGED.main) assert.ok(!requested(requests).some((line) => line.startsWith(`GET ${API.commit('')}`)), requested(requests).join('\n')) - // The second merge still asks for that commit, which develop already has. - assert.strictEqual(mergesAsked(requests)[1].head, MERGED.main) + // The action asks whether develop holds that commit, and develop does. + assert.ok(requested(requests).includes(`GET ${API.compare(TIP.develop, MERGED.main)}`), requested(requests).join('\n')) + // Neither branch has anything to receive: no temporary branch is made, no merge is asked for + // and nothing is moved. The run only reads. + assert.deepStrictEqual(written(requests), []) + }) + + it('moves only develop on a retry that finds the release on the base and not yet on develop', async (t) => { + // The state that an earlier version of the action left after a conflict on develop: the + // release is on main, published or not, and develop does not have it. + const { github, requests } = await octokitFor( + repositoryWith({ + merges: [MERGE.develop], + extra: [ + holds(MERGED.main), + commit(MERGED.main, [TIP.main, TIP['release/M26.test']]), + { method: 'GET', path: API.compare(TIP.develop, MERGED.main), body: { status: 'diverged' } }, + ], + }).map((rule) => (rule.path === API.branch('main') ? { ...rule, body: { name: 'main', commit: { sha: MERGED.main } } } : rule)) + ) + const { core, outputs, summary } = await coreWithOutputs(t) + + await runMerge({ github, core, env: mergeEnv() }) + + assert.deepStrictEqual(movesAsked(requests), [[{ name: 'refs/heads/develop', beforeOid: TIP.develop, afterOid: MERGED.develop }]]) + // One temporary branch, for the one merge there is to make. + assert.deepStrictEqual(written(requests), [`POST ${API.refs}`, `POST ${API.merges}`, `POST ${API.graphql}`, `DELETE ${API.ref(TEMP.develop)}`]) + assert.strictEqual(outputs()['base-sha'], MERGED.main) + assert.match(summary(), /\[main\]\(.*\) already had \[release\/M26\.test\]\(.*\), merged \[main\]\(.*\) into \[develop\]\(.*\)\.$/m) }) it('goes on with an unpublished retry whose base tip is the commit that merged the branch', async (t) => { @@ -492,25 +711,43 @@ describe('release-merge', () => { // first run's merge commit, whose second parent is the branch's tip: the retry publishes it. const { github, requests } = await octokitFor( repositoryWith({ - merges: [MERGE.done, MERGE.done], - extra: [commit(MERGED.main, [TIP.main, TIP['release/M26.test']])], + extra: [holds(MERGED.main), commit(MERGED.main, [TIP.main, TIP['release/M26.test']]), holds(TIP.develop, MERGED.main)], }).map((rule) => (rule.path === API.branch('main') ? { ...rule, body: { name: 'main', commit: { sha: MERGED.main } } } : rule)) ) const { core, outputs } = await coreWithOutputs(t) await runMerge({ github, core, env: mergeEnv() }) - // The tip is read after the merge answered already merged, by the hash it then read, and - // before the develop merge; no version file is read at the base. - assert.deepStrictEqual(requested(requests).slice(-5), [ - `POST ${API.merges}`, - `GET ${API.branch('main')}`, + // The action finds that main holds the branch, checks that the tip it read is the commit that + // merged the branch, then asks about develop. It does not read main again, and it reads no + // version file at the base. + assert.deepStrictEqual(requested(requests).slice(-3), [ + `GET ${API.compare(MERGED.main)}`, `GET ${API.commit(MERGED.main)}`, - `POST ${API.merges}`, - `GET ${API.branch('develop')}`, + `GET ${API.compare(TIP.develop, MERGED.main)}`, ]) + assert.deepStrictEqual(written(requests), []) assert.strictEqual(outputs()['base-sha'], MERGED.main) - assert.strictEqual(mergesAsked(requests)[1].head, MERGED.main) + }) + + it('goes on with an unpublished retry whose base was fast-forwarded to the release branch', async (t) => { + // What a merge by hand leaves when the branch already contains main, as a hotfix cut from + // main does: git moves main to the branch's tip with no merge commit. That tip holds nothing + // but the release, so the retry builds it, and no commit is read to look for a merge. + const tip = TIP['release/M26.test'] + const { github, requests } = await octokitFor( + repositoryWith({ + extra: [{ method: 'GET', path: API.compare(tip), body: { status: 'identical' } }, holds(TIP.develop)], + }).map((rule) => (rule.path === API.branch('main') ? { ...rule, body: { name: 'main', commit: { sha: tip } } } : rule)) + ) + const { core, outputs, logged } = await coreWithOutputs(t) + + await runMerge({ github, core, env: mergeEnv() }) + + assert.match(logged(), /main already has release\/M26\.test: nothing to merge/) + assert.strictEqual(outputs()['base-sha'], tip) + assert.ok(!requested(requests).some((line) => line.startsWith(`GET ${API.commit('')}`)), requested(requests).join('\n')) + assert.deepStrictEqual(written(requests), []) }) it('refuses an unpublished retry once the base has moved on, bump or not, so other changes are not published under this version', async (t) => { @@ -524,8 +761,7 @@ describe('release-merge', () => { for (const parents of [[MERGED.main, other], [MERGED.main]]) { const { github, requests } = await octokitFor( repositoryWith({ - merges: [MERGE.done, MERGE.done], - extra: [commit(later, parents)], + extra: [holds(later), commit(later, parents)], }).map((rule) => (rule.path === API.branch('main') ? { ...rule, body: { name: 'main', commit: { sha: later } } } : rule)) ) const { core, outputs } = await coreWithOutputs(t) @@ -536,12 +772,45 @@ describe('release-merge', () => { `parents ${parents.length}` ) - // Refused before the develop merge, and the outputs are not set. - assert.strictEqual(mergesAsked(requests).length, 1) + // The run is refused before the action asks about develop. Nothing is written and no + // output is set. + assert.deepStrictEqual(written(requests), []) assert.deepStrictEqual(outputs(), {}) } }) + it('fails with neither branch moved when the merge endpoint answers that a temporary branch already has what is merged', async (t) => { + // The action only asks for a merge after it knows that the tip does not hold the head: the + // comparison said so, or the head is the merge commit that this run has just made. A 204 + // then means that someone else moved the temporary branch to a commit that holds the head. + // Read as nothing to merge, it would leave develop out of the update while main moves. + for (const [into, answers, madeBeforeFailing] of [ + ['main', [MERGE.done], [`POST ${API.refs}`, `POST ${API.merges}`, `DELETE ${API.ref(TEMP.main)}`]], + ['develop', [MERGE.main, MERGE.done], TEMP_ONLY], + ]) { + const { github, requests } = await octokitFor(repositoryWith({ merges: answers })) + const { core, outputs, logged } = await coreWithOutputs(t) + const label = into === 'main' ? 'release/M26\\.test' : 'main' + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + new RegExp( + `GitHub answered that the temporary branch release-merge/77-1/${into} already has ${label}, but ${into} did not have it at ` + + `${TIP[into].slice(0, 7)}, the commit that ${into} was read at: the temporary branch received a commit after this step ` + + 'created it\\. Nothing was merged: main and develop are as they were\\. Run this step again\\.' + ), + into + ) + + // No branch is moved, not even main when its merge was made, and every temporary branch is + // deleted. The log does not say that the branch already had the merge. + assert.deepStrictEqual(movesAsked(requests), [], into) + assert.deepStrictEqual(written(requests), madeBeforeFailing, into) + assert.doesNotMatch(logged(), /nothing to merge/, into) + assert.deepStrictEqual(outputs(), {}, into) + } + }) + it('sets no output when the step fails after the merges, so a caller reading published under continue-on-error skips its writes', async (t) => { // The job summary is the last write before the outputs; a summary that fails fails the step // with every output still empty, so `already-published == 'no'` is false for a caller that kept going. @@ -561,8 +830,7 @@ describe('release-merge', () => { const { github, requests } = await octokitFor( repositoryWith({ tag: PUBLISHED, - merges: [MERGE.done, MERGE.done], - extra: [{ method: 'GET', path: API.compare(TAG_COMMIT), body: { status: 'ahead' } }], + extra: [holds(TAG_COMMIT), holds(later), holds(TIP.develop, TAG_COMMIT)], }).map((rule) => (rule.path === API.branch('main') ? { ...rule, body: { name: 'main', commit: { sha: later } } } : rule)) ) const { core, outputs, logged } = await coreWithOutputs(t) @@ -573,7 +841,8 @@ describe('release-merge', () => { // What a caller reads to skip the writes its deploy would repeat: the site's zip, a version // stored on the site, anything that is not idempotent. assert.strictEqual(outputs()['already-published'], 'yes') - assert.strictEqual(mergesAsked(requests)[1].head, TAG_COMMIT, 'develop is asked for the published commit') + assert.ok(requested(requests).includes(`GET ${API.compare(TIP.develop, TAG_COMMIT)}`), 'develop is asked about the published commit') + assert.deepStrictEqual(written(requests), []) assert.match(logged(), /main already has release\/M26\.test.*4\.17\.0 builds at ffffffffffffffffffffffffffffffffffffffff, the commit it was published from/s) assert.ok(!requested(requests).includes(`GET ${API.commit(later)}`), 'nothing is read about the tip') }) @@ -612,47 +881,385 @@ describe('release-merge', () => { assert.deepStrictEqual(mergesAsked(requests), []) }) - it('prints the MERGE_CONFLICT marker and merges nothing when the release conflicts with the base', async (t) => { + it('prints the MERGE_CONFLICT marker and writes nothing when the release conflicts with the base', async (t) => { const { github, requests } = await octokitFor(repositoryWith({ merges: [MERGE.conflict] })) const { core, outputs, logged } = await coreWithOutputs(t) await assert.rejects( runMerge({ github, core, env: mergeEnv() }), - /release\/M26\.test into main stopped on a conflict.*Nothing was merged into main/s + /release\/M26\.test into main stopped on a conflict\. Merge release\/M26\.test into main by hand, then main into develop, resolve the conflict and push both branches\. If GitHub then deletes release\/M26\.test, because its pull request is marked as merged, restore the branch on the pull request\. Then run this step again: it finds the merges done and goes on with the release\. Nothing was merged: main and develop are as they were\./ ) - // The marker opens a line of its own: that is what the dashboard's detector anchors on. - assert.match(logged(), /^MERGE_CONFLICT: .*release\/M26\.test.*main/m) + // The marker opens a line of its own: that is what the dashboard's detector anchors on. The + // instruction is the order of a release merged by hand: the release branch into main, then + // main into develop. It also says to restore the release branch when GitHub deletes it, which + // a repository that deletes the branch of a merged pull request does after the merge by hand. + assert.match( + logged(), + /^MERGE_CONFLICT: merging release\/M26\.test into main conflicted\. Merge release\/M26\.test into main by hand, then main into develop, resolve the conflict and push both branches\. If GitHub then deletes release\/M26\.test, because its pull request is marked as merged, restore the branch on the pull request\. Then run this step again: it finds the merges done and goes on with the release\. Nothing was merged: main and develop are as they were\.$/m + ) assert.strictEqual(outputs().conflict, 'main') - assert.strictEqual(mergesAsked(requests).length, 1, 'develop was never asked for') + // The merge into develop was never tried, and the one temporary branch was deleted. + assert.deepStrictEqual(written(requests), [`POST ${API.refs}`, `POST ${API.merges}`, `DELETE ${API.ref(TEMP.main)}`]) }) - it('prints the marker and names develop when the merged base conflicts with develop', async (t) => { + it('leaves the base as it was when the merge back into develop conflicts, and names develop', async (t) => { const { github, requests } = await octokitFor(repositoryWith({ merges: [MERGE.main, MERGE.conflict] })) const { core, outputs, logged } = await coreWithOutputs(t) await assert.rejects( runMerge({ github, core, env: mergeEnv() }), - /main into develop stopped on a conflict.*merges already done are kept.*Nothing was merged into develop/s + /main into develop stopped on a conflict\. Merge release\/M26\.test into main by hand, then main into develop, resolve the conflict and push both branches\. If GitHub then deletes release\/M26\.test, because its pull request is marked as merged, restore the branch on the pull request\. Then run this step again: it finds the merges done and goes on with the release\. Nothing was merged: main and develop are as they were\./ ) - assert.match(logged(), /^MERGE_CONFLICT: .*main.*develop/m) + // The instruction is the same as for a conflict on main: the release branch into main first, + // then main into develop. The merge of main into develop shows every conflict, also one with + // a commit that only main has. + assert.match( + logged(), + /^MERGE_CONFLICT: merging main into develop conflicted\. Merge release\/M26\.test into main by hand, then main into develop, resolve the conflict and push both branches\. If GitHub then deletes release\/M26\.test, because its pull request is marked as merged, restore the branch on the pull request\. Then run this step again: it finds the merges done and goes on with the release\. Nothing was merged: main and develop are as they were\.$/m + ) assert.strictEqual(outputs().conflict, 'develop') - // The release did reach the base: a retry finds that merge done and only redoes develop. - assert.deepStrictEqual(mergesAsked(requests).map((merge) => merge.base), ['main', 'develop']) + // The merge for main was made on its temporary branch only. The action never asks GitHub to + // move main, so main does not hold the release while develop waits for a person. + assert.deepStrictEqual(written(requests), TEMP_ONLY) + assert.deepStrictEqual(movesAsked(requests), []) + assert.ok(!requested(requests).includes(`GET ${API.repository}`), requested(requests).join('\n')) + }) + + it('names only the base, in the instruction and as unchanged, when there is no develop branch', async (t) => { + const { github } = await octokitFor(repositoryWith({ branches: ['release/M26.test', 'main'], merges: [MERGE.conflict] })) + const { core, logged } = await coreWithOutputs(t) + + await assert.rejects(runMerge({ github, core, env: mergeEnv({ INPUT_DEVELOP_BRANCH: '' }) }), /Nothing was merged: main is as it was\./) + assert.match( + logged(), + /^MERGE_CONFLICT: merging release\/M26\.test into main conflicted\. Merge release\/M26\.test into main by hand, resolve the conflict and push\. If GitHub then deletes release\/M26\.test, because its pull request is marked as merged, restore the branch on the pull request\. Then run this step again: it finds the merge done and goes on with the release\. Nothing was merged: main is as it was\.$/m + ) + assert.doesNotMatch(logged(), /develop/) }) - it('fails without the marker when GitHub refuses the merge because the base moved', async (t) => { - const { github } = await octokitFor(repositoryWith({ merges: [MERGE.moved] })) + it('fails without the marker when GitHub refuses a merge for any other reason', async (t) => { + const { github, requests } = await octokitFor(repositoryWith({ merges: [MERGE.moved] })) const { core, outputs, logged } = await coreWithOutputs(t) await assert.rejects( runMerge({ github, core, env: mergeEnv() }), - /main moved while the merge was being made.*Base branch was modified.*Run this step again/s + /Merging release\/M26\.test into main failed \(HTTP 409\): Base branch was modified.*Nothing was merged: main and develop are as they were\./s ) assert.doesNotMatch(logged(), /MERGE_CONFLICT/) assert.strictEqual(outputs().conflict, undefined) + assert.deepStrictEqual(written(requests).at(-1), `DELETE ${API.ref(TEMP.main)}`) + }) + + it('fails with neither branch moved when a merge was made on a commit that is not the tip that was read', async (t) => { + // The merge is asked for by the name of the temporary branch. Someone else pushed a commit to + // that branch after the action created it, so GitHub made the merge on their commit. Moving + // the branch to that merge commit would be a fast-forward, and GitHub would accept it. + const intruder = '9999999999999999999999999999999999999999' + const onMain = { status: 201, body: mergeCommit(MERGED.main, [intruder, TIP['release/M26.test']]) } + const onDevelop = { status: 201, body: mergeCommit(MERGED.develop, [intruder, MERGED.main]) } + + for (const [into, answers, madeBeforeFailing] of [ + ['main', [onMain], [`POST ${API.refs}`, `POST ${API.merges}`, `DELETE ${API.ref(TEMP.main)}`]], + ['develop', [MERGE.main, onDevelop], TEMP_ONLY], + ]) { + const { github, requests } = await octokitFor(repositoryWith({ merges: answers })) + const { core, outputs, logged } = await coreWithOutputs(t) + const label = into === 'main' ? 'release/M26\\.test' : 'main' + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + new RegExp( + `The merge of ${label} into ${into} was made on 9999999, not on ${TIP[into].slice(0, 7)}, the commit that ${into} was read at: ` + + `the temporary branch release-merge/77-1/${into} received a commit after this step created it\\. ` + + 'Nothing was merged: main and develop are as they were\\. Run this step again\\.' + ), + into + ) + + // No branch is moved, and every temporary branch is deleted. + assert.deepStrictEqual(movesAsked(requests), [], into) + assert.deepStrictEqual(written(requests), madeBeforeFailing, into) + assert.doesNotMatch(logged(), /MERGE_CONFLICT/, into) + assert.strictEqual(outputs().conflict, undefined, into) + } + }) + + it('fails with neither branch moved when the answer to a merge does not name the commit that it was made on', async (t) => { + const { github, requests } = await octokitFor(repositoryWith({ merges: [{ status: 201, body: { sha: MERGED.main } }] })) + const { core } = await coreWithOutputs(t) + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + /GitHub's answer to the merge of release\/M26\.test into main does not name the commit that the merge was made on, so this step cannot confirm that it was made on bbbbbbb, the commit that main was read at\. Nothing was merged: main and develop are as they were\. Run this step again\./ + ) + + assert.deepStrictEqual(movesAsked(requests), []) + assert.deepStrictEqual(written(requests), [`POST ${API.refs}`, `POST ${API.merges}`, `DELETE ${API.ref(TEMP.main)}`]) + }) + + it('fails with neither branch moved, naming the branch that received a commit, and says to run again', async (t) => { + // A commit reached main after its tip was read. The merge commit was made on the old tip, so + // GitHub refuses the update for main, and the update for develop with it. GitHub's answer + // names no branch and no reason, so the action reads both branches again to say which one moved. + const later = '9999999999999999999999999999999999999999' + const { github, requests } = await octokitFor( + readAgain( + repositoryWith({ + move: MOVE.moved, + // The commit that reached main does not hold the merge commit, which is on the temporary + // branch only: the update was not applied. + extra: [{ method: 'GET', path: API.compare(later, MERGED.main), body: { status: 'diverged' } }], + }), + { main: later } + ) + ) + const { core, outputs, logged } = await coreWithOutputs(t) + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + /^Error: main \(at 9999999, the merge was made on bbbbbbb\) received a commit while the merges were being made, so GitHub moved neither branch \(Something went wrong while executing your query.*when reporting this issue\)\. Nothing was merged\. Run this step again\.$/ + ) + + // Not a conflict for a person to resolve: no marker, so the dashboard shows a failure to retry. + assert.doesNotMatch(logged(), /MERGE_CONFLICT/) + assert.deepStrictEqual(outputs(), {}) + assert.strictEqual(movesAsked(requests).length, 1, 'the update is asked for once, not again') + assert.deepStrictEqual(requested(requests).slice(-6), [ + `POST ${API.graphql}`, + `GET ${API.branch('main')}`, + `GET ${API.compare(later, MERGED.main)}`, + `GET ${API.branch('develop')}`, + `DELETE ${API.ref(TEMP.main)}`, + `DELETE ${API.ref(TEMP.develop)}`, + ]) + }) + + it('says to change the rule, not to run again, when GitHub does not move the branches and neither received a commit', async (t) => { + // The base only takes pull requests. The merges are made on the temporary branches, so the + // rule refuses the update, not the merges. Running the step again would get the same answer. + const { github, requests } = await octokitFor(repositoryWith({ move: MOVE.protected })) + const { core, outputs, logged } = await coreWithOutputs(t) + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + /^Error: GitHub did not move main and develop together: Branch 'refs\/heads\/main' is protected: Changes must be made through a pull request\. Nothing was merged: main and develop are as they were\. No commit reached them while the merges were being made: when the answer names a rule or a permission, change that before running this step again\.$/ + ) + + assert.doesNotMatch(logged(), /MERGE_CONFLICT/) + assert.deepStrictEqual(outputs(), {}) + assert.deepStrictEqual(written(requests).slice(-2), [`DELETE ${API.ref(TEMP.main)}`, `DELETE ${API.ref(TEMP.develop)}`]) + }) + + it('goes on with a warning when the request for the update failed and the branches hold their merge commits', async (t) => { + // The connection dropped after GitHub applied the update. The action reads both branches + // again and finds them at their merge commits: the release is merged, and the caller builds it. + const { github, requests } = await octokitFor( + readAgain(repositoryWith({ move: MOVE.unanswered }), { main: MERGED.main, develop: MERGED.develop }) + ) + const { core, outputs, logged } = await coreWithOutputs(t) + + await runMerge({ github, core, env: mergeEnv() }) + + assert.match( + logged(), + /::warning::Moving main and develop together failed \(HTTP 502: Server Error\), but the update was applied: main and develop hold their merge commits\./ + ) + assert.strictEqual(movesAsked(requests).length, 1) + assert.strictEqual(outputs()['base-sha'], MERGED.main) + assert.strictEqual(outputs().conflict, '') + assert.deepStrictEqual(written(requests).slice(-2), [`DELETE ${API.ref(TEMP.main)}`, `DELETE ${API.ref(TEMP.develop)}`]) + }) + + it('takes the update as applied when the branch received a commit on top of its merge commit', async (t) => { + // The update moved main to its merge commit, the answer was lost, and a commit reached main + // before the action read it again. Main's tip is neither the old tip nor the merge commit, and + // it descends from the merge commit: the release is on main. "Nothing was merged" would be + // false. A retry would then find that main moved on, and ask a person to finish the release + // by hand. + const later = '9999999999999999999999999999999999999999' + const { github, requests } = await octokitFor( + readAgain( + repositoryWith({ + branches: ['release/M26.test', 'main'], + merges: [MERGE.main], + move: MOVE.unanswered, + extra: [holds(later, MERGED.main)], + }), + { main: later } + ) + ) + const { core, outputs, logged } = await coreWithOutputs(t) + + await runMerge({ github, core, env: mergeEnv({ INPUT_DEVELOP_BRANCH: '' }) }) + + assert.match(logged(), /::warning::Moving main failed \(HTTP 502: Server Error\), but the update was applied: main holds its merge commit\./) + // base-sha is the merge commit, not main's tip: the caller builds the release without the + // later commit. + assert.strictEqual(outputs()['base-sha'], MERGED.main) + assert.deepStrictEqual(requested(requests).slice(-4), [ + `POST ${API.graphql}`, + `GET ${API.branch('main')}`, + `GET ${API.compare(later, MERGED.main)}`, + `DELETE ${API.ref(TEMP.main)}`, + ]) + }) + + it('takes the update as applied when both branches received a commit after it', async (t) => { + const later = '9999999999999999999999999999999999999999' + const other = '8888888888888888888888888888888888888888' + const { github } = await octokitFor( + readAgain( + repositoryWith({ move: MOVE.unanswered, extra: [holds(later, MERGED.main), holds(other, MERGED.develop)] }), + { main: later, develop: other } + ) + ) + const { core, outputs, logged } = await coreWithOutputs(t) + + await runMerge({ github, core, env: mergeEnv() }) + + assert.match(logged(), /::warning::Moving main and develop together failed \(HTTP 502: Server Error\), but the update was applied: main and develop hold their merge commits\./) + assert.strictEqual(outputs()['base-sha'], MERGED.main) + }) + + it('does not say nothing was merged when a moved branch cannot be compared with its merge commit', async (t) => { + // The update got no answer, and main is at another commit. The comparison that would tell + // whether that commit holds the merge commit fails, so the update may or may not have been + // applied. + const later = '9999999999999999999999999999999999999999' + const { github } = await octokitFor( + readAgain( + repositoryWith({ + branches: ['release/M26.test', 'main'], + merges: [MERGE.main], + move: MOVE.unanswered, + extra: [{ method: 'GET', path: API.compare(later, MERGED.main), status: 500, body: { message: 'boom' } }], + }), + { main: later } + ) + ) + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects(runMerge({ github, core, env: mergeEnv({ INPUT_DEVELOP_BRANCH: '' }) }), (error) => { + assert.match( + error.message, + /^Moving main failed \(HTTP 502: Server Error\), and what the branches hold now could not be confirmed: main is at 9999999, which could not be compared with its merge commit\. Check them before running this step again\.$/ + ) + assert.doesNotMatch(error.message, /Nothing was merged/) + + return true + }) + assert.deepStrictEqual(outputs(), {}) + }) + + it('says nothing was merged when the request for the update failed and the branch is where it was', async (t) => { + const { github } = await octokitFor( + repositoryWith({ branches: ['release/M26.test', 'main'], merges: [MERGE.main], move: MOVE.unanswered }) + ) + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects( + runMerge({ github, core, env: mergeEnv({ INPUT_DEVELOP_BRANCH: '' }) }), + /^Error: GitHub did not move main: HTTP 502: Server Error\. Nothing was merged: main is as it was\. No commit reached it while the merges were being made/ + ) + assert.deepStrictEqual(outputs(), {}) + }) + + it('says what each branch holds, and not that nothing was merged, when a failed update cannot be confirmed', async (t) => { + // The update got no answer, and develop cannot be read afterwards. Main holds the release, + // and the state of develop is unknown. The message must not say that the release was merged, + // nor that it was not. + const { github } = await octokitFor( + readAgain(repositoryWith({ move: MOVE.unanswered }), { main: MERGED.main, develop: { status: 500, body: { message: 'boom' } } }) + ) + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects(runMerge({ github, core, env: mergeEnv() }), (error) => { + assert.match( + error.message, + /^Moving main and develop together failed \(HTTP 502: Server Error\), and what the branches hold now could not be confirmed: main holds its merge commit, develop could not be read\. Check them before running this step again\.$/ + ) + assert.doesNotMatch(error.message, /Nothing was merged/) + + return true + }) + assert.deepStrictEqual(outputs(), {}) + }) + + it('fails before the update when the repository cannot be read, with both temporary branches deleted', async (t) => { + const { github, requests } = await octokitFor( + repositoryWith().map((rule) => (rule.path === API.repository ? { ...rule, status: 500, body: { message: 'boom' } } : rule)) + ) + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + /Reading stellarwp\/plugin failed \(HTTP 500\): boom\. Nothing was merged: main and develop are as they were\./ + ) + + // Both merges were made on the temporary branches only, and no update is asked for. + assert.deepStrictEqual(written(requests), TEMP_ONLY) + assert.deepStrictEqual(movesAsked(requests), []) + assert.deepStrictEqual(outputs(), {}) + }) + + it('fails before any merge when the temporary branch cannot be created, naming the token, the rules and a branch named release-merge', async (t) => { + // GitHub gives this answer when a ruleset restricts who creates branches, and also when the + // repository has a branch named release-merge. The message gives both causes. + const { github, requests } = await octokitFor( + repositoryWith({ tempBranch: { status: 422, body: { message: 'Reference update failed' } } }) + ) + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects( + runMerge({ github, core, env: mergeEnv() }), + /Creating the temporary branch release-merge\/77-1\/main failed \(HTTP 422\): Reference update failed\. Each merge is tried on a temporary branch first, so the token and the repository's rules have to allow creating and deleting it, and the repository cannot have a branch named release-merge\. Nothing was merged: main and develop are as they were\./ + ) + + // Nothing was created, so there is nothing to merge on and nothing to delete. + assert.deepStrictEqual(written(requests), [`POST ${API.refs}`]) + assert.deepStrictEqual(outputs(), {}) + }) + + it('says to delete the branch, not to change the token, when a temporary branch of that name already exists', async (t) => { + // Another run of this step left a branch with the same run id and attempt. Here GitHub refuses + // the second temporary branch. The first one holds the merge commit for main by then, and the + // action deletes it. + const { github, requests } = await octokitFor( + repositoryWith({ + tempBranch: { responses: [{ status: 201, body: {} }, { status: 422, body: { message: 'Reference already exists' } }] }, + }) + ) + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects(runMerge({ github, core, env: mergeEnv() }), (error) => { + assert.match( + error.message, + /^Creating the temporary branch release-merge\/77-1\/develop failed \(HTTP 422\): Reference already exists\. A branch of that name is left from another run of this step: delete it, then run this step again\. Nothing was merged: main and develop are as they were\.$/ + ) + assert.doesNotMatch(error.message, /token/) + + return true + }) + + assert.deepStrictEqual(written(requests), [`POST ${API.refs}`, `POST ${API.merges}`, `POST ${API.refs}`, `DELETE ${API.ref(TEMP.main)}`]) + assert.deepStrictEqual(movesAsked(requests), []) + assert.deepStrictEqual(outputs(), {}) + }) + + it('warns and still succeeds when a temporary branch cannot be deleted after the branches moved', async (t) => { + const { github, requests } = await octokitFor(repositoryWith({ cleanup: { status: 500, body: { message: 'boom' } } })) + const { core, outputs, logged } = await coreWithOutputs(t) + + await runMerge({ github, core, env: mergeEnv() }) + + // Both deletions are tried, and the release is merged whatever they answer. + assert.match(logged(), /::warning::.*temporary branch release-merge\/77-1\/main.*boom.*Delete it by hand/) + assert.match(logged(), /::warning::.*temporary branch release-merge\/77-1\/develop/) + assert.strictEqual(movesAsked(requests).length, 1) + assert.strictEqual(outputs()['base-sha'], MERGED.main) }) it('refuses a version the branch does not hold, naming the file, before merging anything', async (t) => { diff --git a/tests/actions/release-prep/release-prep.test.js b/tests/actions/release-prep/release-prep.test.js index be49bc95..d6e0587f 100644 --- a/tests/actions/release-prep/release-prep.test.js +++ b/tests/actions/release-prep/release-prep.test.js @@ -1227,7 +1227,15 @@ describe('release-prep', () => { commit: 'commit-new', files: 'bin/tool.sh\nchangelog.txt\nchangelog/entry.yaml\nlogo.png\nplugin.php', }) - assert.match(summary(), /Committed `commit-` "Prepare release\/M26\.jigglypuff \(4\.17\.0\)" to `release\/M26\.jigglypuff`/) + // The commit and the branch are links, as in the summary of the deploy's actions. The files stay + // code spans. + assert.ok( + summary().includes( + 'Committed [commit-](https://github.com/stellarwp/plugin/commit/commit-new) "Prepare release/M26.jigglypuff (4.17.0)" ' + + 'to [release/M26.jigglypuff](https://github.com/stellarwp/plugin/tree/release/M26.jigglypuff):' + ), + summary() + ) assert.match(summary(), /^- `bin\/tool\.sh`\n- `changelog\.txt`\n- `changelog\/entry\.yaml`\n- `logo\.png`\n- `plugin\.php`$/m) assert.equal(git(work, 'rev-parse', 'HEAD'), head, 'the checkout itself stays where it was') }) @@ -1268,7 +1276,7 @@ describe('release-prep', () => { it('neither commits nor calls the API when nothing changed, and still succeeds', async (t) => { // A retry of the same version finds the branch already prepared. - const { core, outputs } = await coreWithOutputs(t) + const { core, outputs, summary } = await coreWithOutputs(t) const { exec } = await recordedRealExec() const { github, requests } = await octokitFor(apiAccepts()) const work = checkoutOn('release/M26.jigglypuff') @@ -1277,6 +1285,12 @@ describe('release-prep', () => { assert.deepEqual(requests, []) assert.deepEqual(outputs(), { commit: '', files: '' }) + assert.ok( + summary().includes( + 'Nothing to commit: [release/M26.jigglypuff](https://github.com/stellarwp/plugin/tree/release/M26.jigglypuff) already holds 4.17.0.' + ), + summary() + ) }) it('fails when the branch moved after the checkout, without forcing the ref', async (t) => {