diff --git a/.github/workflows/__shared-ci.yml b/.github/workflows/__shared-ci.yml index 5973e5a..d0e051a 100644 --- a/.github/workflows/__shared-ci.yml +++ b/.github/workflows/__shared-ci.yml @@ -49,6 +49,16 @@ jobs: contents: read uses: $/.github/workflows/__test-action-matrix-outputs.yml + test-action-create-and-merge-pull-request: + needs: lint + permissions: + contents: read + id-token: write + packages: read + pull-requests: write + security-events: write + uses: $/.github/workflows/__test-action-create-and-merge-pull-request.yml + test-action-lint-pull-request-title: needs: lint permissions: @@ -135,6 +145,7 @@ jobs: - test-action-distributions - test-action-test-action-distribution - test-action-lint-pull-request-title + - test-action-create-and-merge-pull-request - test-action-parse-ci-reports - test-action-need-fix-to-issue if: always() diff --git a/.github/workflows/__test-action-create-and-merge-pull-request.yml b/.github/workflows/__test-action-create-and-merge-pull-request.yml new file mode 100644 index 0000000..120e1cc --- /dev/null +++ b/.github/workflows/__test-action-create-and-merge-pull-request.yml @@ -0,0 +1,22 @@ +name: Internal - Tests for create-and-merge-pull-request action + +on: + workflow_call: + +permissions: {} + +jobs: + continuous-integration: + uses: hoverkraft-tech/ci-github-nodejs/.github/workflows/continuous-integration.yml@98d91b1cc347efc64cd5fb20bc0ebc076acad114 # 3.1.0 + permissions: + contents: read + id-token: write + packages: read + pull-requests: write + security-events: write + with: + working-directory: ./actions/create-and-merge-pull-request + build: "" + lint: "" + code-ql: '{"languages":"typescript","config-file":".github/codeql/config.yml"}' + test: '{"comment":false,"report-group":"test-action-create-and-merge-pull-request"}' diff --git a/actions/create-and-merge-pull-request/README.md b/actions/create-and-merge-pull-request/README.md index 8325aed..77636e1 100644 --- a/actions/create-and-merge-pull-request/README.md +++ b/actions/create-and-merge-pull-request/README.md @@ -30,7 +30,11 @@ ## Overview Action to create and merge Pull Request. -Opinionated, set GitHub Actions bot as author, then merge with the configured strategy. +Set GitHub Actions bot as author, then merge the created commit with the configured strategy. +Run generation and validation before calling this action. It attempts the merge immediately; +it does not wait for the pull request's CI or enable GitHub's optional auto-merge feature. +Administrator bypass is enabled by default. Set bypass-branch-protection to false to request a normal merge. +A pull request head change after creation prevents the merge. For this action to work you must explicitly allow GitHub Actions to create pull requests. See . @@ -42,7 +46,7 @@ See . | | | -| **`branch`** | The pull request branch name | **true** | - | -| **`title`** | The pull request title and, for merge/squash merges, the merged commit title | **true** | - | -| **`body`** | The pull request body | **true** | - | -| **`commit-message`** | The commit message for the pull request and, for merge/squash merges, the merged commit body | **true** | - | -| **`merge-method`** | Merge strategy for the created pull request. | **false** | `rebase` | -| | Valid values: `merge`, `rebase`, `squash`. | | | +| **Input** | **Description** | **Required** | **Default** | +| ------------------------------ | --------------------------------------------------------------------------------------------------------------- | ------------ | --------------------- | +| **`github-token`** | GitHub token for creating and merging pull request (permissions contents: write and pull-requests: write). | **false** | `${{ github.token }}` | +| | See . | | | +| **`branch`** | The pull request branch name | **true** | - | +| **`title`** | The pull request title and, for merge/squash merges, the merged commit title | **true** | - | +| **`body`** | The pull request body | **true** | - | +| **`commit-message`** | The commit message for the pull request and, for merge/squash merges, the merged commit body | **true** | - | +| **`add-paths`** | Newline-separated paths to include in the commit, forwarded to peter-evans/create-pull-request. | **false** | - | +| | Empty includes all changes. Use this to restrict generated updates to their intended files. | | | +| **`bypass-branch-protection`** | Request administrator merge privileges with --admin. Requires a token allowed to bypass the repository's rules. | **false** | `true` | +| | This can bypass required reviews, status checks and merge queues. The expected PR head is still checked. | | | +| **`merge-method`** | Merge strategy for the created pull request. | **false** | `rebase` | +| | Valid values: `merge`, `rebase`, `squash`. | | | diff --git a/actions/create-and-merge-pull-request/action.yml b/actions/create-and-merge-pull-request/action.yml index 50f0b87..2b253bc 100644 --- a/actions/create-and-merge-pull-request/action.yml +++ b/actions/create-and-merge-pull-request/action.yml @@ -3,7 +3,11 @@ name: "Create and merge Pull Request" description: | Action to create and merge Pull Request. - Opinionated, set GitHub Actions bot as author, then merge with the configured strategy. + Set GitHub Actions bot as author, then merge the created commit with the configured strategy. + Run generation and validation before calling this action. It attempts the merge immediately; + it does not wait for the pull request's CI or enable GitHub's optional auto-merge feature. + Administrator bypass is enabled by default. Set bypass-branch-protection to false to request a normal merge. + A pull request head change after creation prevents the merge. author: hoverkraft branding: icon: git-pull-request @@ -28,6 +32,17 @@ inputs: commit-message: description: "The commit message for the pull request and, for merge/squash merges, the merged commit body" required: true + add-paths: + description: | + Newline-separated paths to include in the commit, forwarded to peter-evans/create-pull-request. + Empty includes all changes. Use this to restrict generated updates to their intended files. + required: false + bypass-branch-protection: + description: | + Request administrator merge privileges with --admin. Requires a token allowed to bypass the repository's rules. + This can bypass required reviews, status checks and merge queues. The expected PR head is still checked. + default: "true" + required: false merge-method: description: | Merge strategy for the created pull request. @@ -61,6 +76,7 @@ runs: title: ${{ inputs.title }} body: ${{ inputs.body }} commit-message: ${{ inputs.commit-message }} + add-paths: ${{ inputs.add-paths }} author: ${{ steps.github-actions-bot-user.outputs.name }} <${{ steps.github-actions-bot-user.outputs.email }}> committer: ${{ steps.github-actions-bot-user.outputs.name }} <${{ steps.github-actions-bot-user.outputs.email }}> @@ -69,170 +85,19 @@ runs: if: steps.create-pull-request.outputs.pull-request-number && steps.create-pull-request.outputs.pull-request-operation != 'closed' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: + ACTION_PATH: ${{ github.action_path }} GH_TOKEN: ${{ inputs.github-token }} PULL_REQUEST_NUMBER: ${{ steps.create-pull-request.outputs.pull-request-number }} + PULL_REQUEST_HEAD_SHA: ${{ steps.create-pull-request.outputs.pull-request-head-sha }} + BYPASS_BRANCH_PROTECTION: ${{ inputs.bypass-branch-protection }} MERGE_METHOD: ${{ inputs.merge-method }} PULL_REQUEST_TITLE: ${{ inputs.title }} PULL_REQUEST_COMMIT_MESSAGE: ${{ inputs.commit-message }} with: github-token: ${{ inputs.github-token }} script: | - const maxAttempts = 10; - const requiredWorkflowsError = 'Required workflow'; - const repository = `${context.repo.owner}/${context.repo.repo}`; - const mergeMethod = (process.env.MERGE_METHOD ?? 'rebase').trim(); - const mergeCommitTitle = (process.env.PULL_REQUEST_TITLE ?? '').trim(); - const mergeCommitMessage = process.env.PULL_REQUEST_COMMIT_MESSAGE ?? ''; - const mergeMethodFlags = { - merge: '--merge', - rebase: '--rebase', - squash: '--squash', - }; - const getRetryDelayMs = attempt => Math.min(1000 * (2 ** attempt), 10000); - - const sleep = delayMs => new Promise(resolve => setTimeout(resolve, delayMs)); - - if (!(mergeMethod in mergeMethodFlags)) { - throw new Error( - `Invalid merge method: ${mergeMethod}. Expected one of: ${Object.keys(mergeMethodFlags).join(', ')}`, - ); - } - - const waitFor = async ({ - run, - isComplete, - shouldRetry = () => true, - onAttempt = () => {}, - getRetryMessage, - getFailureMessage, - getTimeoutMessage, - }) => { - for (let attempt = 0; attempt < maxAttempts; attempt++) { - const result = await run(); - - onAttempt(result); - - if (isComplete(result)) { - return result; - } - - if (!shouldRetry(result)) { - throw new Error(getFailureMessage(result)); - } - - const retryDelayMs = getRetryDelayMs(attempt); - core.debug(getRetryMessage(result, retryDelayMs)); - await sleep(retryDelayMs); - } - - throw new Error(getTimeoutMessage()); - }; - - const parsePullRequestNumber = pullNumberRaw => { - if (!/^[0-9]+$/.test(pullNumberRaw)) { - throw new Error(`Invalid pull request number: ${pullNumberRaw}`); - } - - return Number.parseInt(pullNumberRaw, 10); - }; - - const getPullRequest = async pullNumber => { - const { data: pullRequest } = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: pullNumber, - }); - - return pullRequest; - }; - - const waitForMergeablePullRequest = pullNumber => - waitFor({ - run: () => getPullRequest(pullNumber), - isComplete: pullRequest => pullRequest.mergeable === true, - onAttempt: pullRequest => { - if (pullRequest.mergeable !== true) { - core.debug(`Pull request is not mergeable, mergeable_state: ${pullRequest.mergeable_state}`); - } - }, - getRetryMessage: (_pullRequest, retryDelayMs) => `Retrying mergeability check in ${retryDelayMs}ms...`, - getFailureMessage: () => `Pull request #${pullNumber} cannot be retried because it is not mergeable.`, - getTimeoutMessage: () => `Pull request #${pullNumber} is not mergeable after ${maxAttempts} attempts`, - }); - - const getMergeArguments = pullNumber => { - const args = [ - 'pr', - 'merge', - '-R', - repository, - mergeMethodFlags[mergeMethod], - '--admin', - String(pullNumber), - ]; - - if (mergeMethod !== 'rebase' && mergeCommitTitle) { - args.push('--subject', mergeCommitTitle); - } - - if (mergeMethod !== 'rebase' && mergeCommitMessage.trim()) { - args.push('--body', mergeCommitMessage); - } - - return args; - }; - - const mergePullRequest = async pullNumber => { - core.debug(`Merging pull request #${pullNumber} for repository ${repository} with method ${mergeMethod}...`); - - const { exitCode, stdout, stderr } = await exec.getExecOutput( - 'gh', - getMergeArguments(pullNumber), - { - env: process.env, - ignoreReturnCode: true, - silent: true, - }, - ); - - return { - mergeExitCode: exitCode, - mergeOutputs: [stdout, stderr].filter(Boolean).join('\n').trim(), - }; - }; - - const verifyMergedPullRequest = async (pullNumber, mergeOutputs) => { - const pullRequest = await waitFor({ - run: () => getPullRequest(pullNumber), - isComplete: currentPullRequest => Boolean( - currentPullRequest.merged - && currentPullRequest.base.ref - && currentPullRequest.merge_commit_sha, - ), - getRetryMessage: (_pullRequest, retryDelayMs) => `Pull request merge has not been reflected by the REST API yet, retrying in ${retryDelayMs}ms...`, - getFailureMessage: () => `Pull request merge verification stopped before completion: ${mergeOutputs}`, - getTimeoutMessage: () => `Pull request merge succeeded but timed out while waiting for REST API verification: ${mergeOutputs}`, - }); - - core.setOutput('merged-ref', `refs/heads/${pullRequest.base.ref}`); - core.setOutput('merged-sha', pullRequest.merge_commit_sha); - }; - - const pullNumber = parsePullRequestNumber(process.env.PULL_REQUEST_NUMBER ?? ''); - - await waitForMergeablePullRequest(pullNumber); - - const { mergeOutputs } = await waitFor({ - run: () => mergePullRequest(pullNumber), - isComplete: ({ mergeExitCode }) => mergeExitCode === 0, - shouldRetry: ({ mergeOutputs }) => mergeOutputs.includes(requiredWorkflowsError), - onAttempt: ({ mergeExitCode, mergeOutputs }) => { - core.debug(`Merge outputs: ${mergeOutputs}`); - core.debug(`Merge exit code: ${mergeExitCode}`); - }, - getRetryMessage: (_result, retryDelayMs) => `Pull request is not mergeable yet because some of required workflow check issues, retrying in ${retryDelayMs}ms...`, - getFailureMessage: ({ mergeOutputs }) => `Failed to merge pull request: ${mergeOutputs}`, - getTimeoutMessage: () => `Failed to merge pull request after ${maxAttempts} attempts`, - }); - - await verifyMergedPullRequest(pullNumber, mergeOutputs); + const { pathToFileURL } = require('node:url'); + const { join } = require('node:path'); + const moduleUrl = pathToFileURL(join(process.env.ACTION_PATH, 'src', 'index.js')); + const { run } = await import(moduleUrl.href); + await run({ core, context, github, exec }); diff --git a/actions/create-and-merge-pull-request/package-lock.json b/actions/create-and-merge-pull-request/package-lock.json new file mode 100644 index 0000000..dacfdcc --- /dev/null +++ b/actions/create-and-merge-pull-request/package-lock.json @@ -0,0 +1,16 @@ +{ + "name": "create-and-merge-pull-request", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "create-and-merge-pull-request", + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=24.0.0" + } + } + } +} diff --git a/actions/create-and-merge-pull-request/package.json b/actions/create-and-merge-pull-request/package.json new file mode 100644 index 0000000..84657b4 --- /dev/null +++ b/actions/create-and-merge-pull-request/package.json @@ -0,0 +1,17 @@ +{ + "name": "create-and-merge-pull-request", + "version": "1.0.0", + "private": true, + "description": "Create scoped pull requests and merge the expected commit", + "type": "module", + "scripts": { + "test": "node --test", + "pretest:ci": "node -e \"require('node:fs').mkdirSync('coverage', { recursive: true })\"", + "test:ci": "node --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=coverage/junit.xml --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test" + }, + "author": "hoverkraft", + "license": "MIT", + "engines": { + "node": ">=24.0.0" + } +} diff --git a/actions/create-and-merge-pull-request/src/index.js b/actions/create-and-merge-pull-request/src/index.js new file mode 100644 index 0000000..7da8eb4 --- /dev/null +++ b/actions/create-and-merge-pull-request/src/index.js @@ -0,0 +1,205 @@ +export async function run({ + github, + context, + core, + exec, + env = process.env, + sleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)), +}) { + const maxAttempts = 10; + const requiredWorkflowsError = "Required workflow"; + const repository = `${context.repo.owner}/${context.repo.repo}`; + const mergeMethod = (env.MERGE_METHOD ?? "rebase").trim(); + const mergeCommitTitle = (env.PULL_REQUEST_TITLE ?? "").trim(); + const mergeCommitMessage = env.PULL_REQUEST_COMMIT_MESSAGE ?? ""; + const expectedHeadSha = (env.PULL_REQUEST_HEAD_SHA ?? "").trim(); + const bypassBranchProtection = env.BYPASS_BRANCH_PROTECTION ?? "true"; + const mergeMethodFlags = { + merge: "--merge", + rebase: "--rebase", + squash: "--squash", + }; + const getRetryDelayMs = (attempt) => Math.min(1000 * 2 ** attempt, 10000); + + if (!(mergeMethod in mergeMethodFlags)) { + throw new Error( + `Invalid merge method: ${mergeMethod}. Expected one of: ${Object.keys(mergeMethodFlags).join(", ")}`, + ); + } + + if (!/^[a-f0-9]{40}$/.test(expectedHeadSha)) { + throw new Error( + "A valid pull request head SHA from the creation step is required.", + ); + } + if (!["true", "false"].includes(bypassBranchProtection)) { + throw new Error("bypass-branch-protection must be true or false."); + } + + const waitFor = async ({ + run, + isComplete, + shouldRetry = () => true, + onAttempt = () => {}, + getRetryMessage, + getFailureMessage, + getTimeoutMessage, + }) => { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const result = await run(); + + onAttempt(result); + + if (isComplete(result)) { + return result; + } + + if (!shouldRetry(result)) { + throw new Error(getFailureMessage(result)); + } + + const retryDelayMs = getRetryDelayMs(attempt); + core.debug(getRetryMessage(result, retryDelayMs)); + await sleep(retryDelayMs); + } + + throw new Error(getTimeoutMessage()); + }; + + const parsePullRequestNumber = (pullNumberRaw) => { + if (!/^[0-9]+$/.test(pullNumberRaw)) { + throw new Error(`Invalid pull request number: ${pullNumberRaw}`); + } + + return Number.parseInt(pullNumberRaw, 10); + }; + + const getPullRequest = async (pullNumber) => { + const { data: pullRequest } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + }); + + return pullRequest; + }; + + const waitForMergeablePullRequest = (pullNumber) => + waitFor({ + run: async () => { + const pullRequest = await getPullRequest(pullNumber); + if (pullRequest.head?.sha !== expectedHeadSha) { + throw new Error( + `Pull request #${pullNumber} head changed after creation; refusing to merge.`, + ); + } + return pullRequest; + }, + isComplete: (pullRequest) => pullRequest.mergeable === true, + onAttempt: (pullRequest) => { + if (pullRequest.mergeable !== true) { + core.debug( + `Pull request is not mergeable, mergeable_state: ${pullRequest.mergeable_state}`, + ); + } + }, + getRetryMessage: (_pullRequest, retryDelayMs) => + `Retrying mergeability check in ${retryDelayMs}ms...`, + getFailureMessage: () => + `Pull request #${pullNumber} cannot be retried because it is not mergeable.`, + getTimeoutMessage: () => + `Pull request #${pullNumber} is not mergeable after ${maxAttempts} attempts`, + }); + + const getMergeArguments = (pullNumber) => { + const args = [ + "pr", + "merge", + "-R", + repository, + mergeMethodFlags[mergeMethod], + "--match-head-commit", + expectedHeadSha, + String(pullNumber), + ]; + + if (bypassBranchProtection === "true") { + args.push("--admin"); + } + + if (mergeMethod !== "rebase" && mergeCommitTitle) { + args.push("--subject", mergeCommitTitle); + } + + if (mergeMethod !== "rebase" && mergeCommitMessage.trim()) { + args.push("--body", mergeCommitMessage); + } + + return args; + }; + + const mergePullRequest = async (pullNumber) => { + core.debug( + `Merging pull request #${pullNumber} for repository ${repository} with method ${mergeMethod}...`, + ); + + const { exitCode, stdout, stderr } = await exec.getExecOutput( + "gh", + getMergeArguments(pullNumber), + { + env: env, + ignoreReturnCode: true, + silent: true, + }, + ); + + return { + mergeExitCode: exitCode, + mergeOutputs: [stdout, stderr].filter(Boolean).join("\n").trim(), + }; + }; + + const verifyMergedPullRequest = async (pullNumber, mergeOutputs) => { + const pullRequest = await waitFor({ + run: () => getPullRequest(pullNumber), + isComplete: (currentPullRequest) => + Boolean( + currentPullRequest.merged && + currentPullRequest.base.ref && + currentPullRequest.merge_commit_sha, + ), + getRetryMessage: (_pullRequest, retryDelayMs) => + `Pull request merge has not been reflected by the REST API yet, retrying in ${retryDelayMs}ms...`, + getFailureMessage: () => + `Pull request merge verification stopped before completion: ${mergeOutputs}`, + getTimeoutMessage: () => + `Pull request merge succeeded but timed out while waiting for REST API verification: ${mergeOutputs}`, + }); + + core.setOutput("merged-ref", `refs/heads/${pullRequest.base.ref}`); + core.setOutput("merged-sha", pullRequest.merge_commit_sha); + }; + + const pullNumber = parsePullRequestNumber(env.PULL_REQUEST_NUMBER ?? ""); + + await waitForMergeablePullRequest(pullNumber); + + const { mergeOutputs } = await waitFor({ + run: () => mergePullRequest(pullNumber), + isComplete: ({ mergeExitCode }) => mergeExitCode === 0, + shouldRetry: ({ mergeOutputs }) => + mergeOutputs.includes(requiredWorkflowsError), + onAttempt: ({ mergeExitCode, mergeOutputs }) => { + core.debug(`Merge outputs: ${mergeOutputs}`); + core.debug(`Merge exit code: ${mergeExitCode}`); + }, + getRetryMessage: (_result, retryDelayMs) => + `Pull request is not mergeable yet because some of required workflow check issues, retrying in ${retryDelayMs}ms...`, + getFailureMessage: ({ mergeOutputs }) => + `Failed to merge pull request: ${mergeOutputs}`, + getTimeoutMessage: () => + `Failed to merge pull request after ${maxAttempts} attempts`, + }); + + await verifyMergedPullRequest(pullNumber, mergeOutputs); +} diff --git a/actions/create-and-merge-pull-request/src/index.test.js b/actions/create-and-merge-pull-request/src/index.test.js new file mode 100644 index 0000000..7f2103a --- /dev/null +++ b/actions/create-and-merge-pull-request/src/index.test.js @@ -0,0 +1,185 @@ +import assert from "node:assert/strict"; +import { mock, test } from "node:test"; +import { run } from "./index.js"; + +const headSha = "a".repeat(40); +const mergedSha = "b".repeat(40); + +function scenario({ env = {}, mergeResult, pullRequest } = {}) { + let merged = false; + const outputs = {}; + const get = mock.fn(async () => ({ + data: { + mergeable: true, + head: { sha: headSha }, + merged, + base: { ref: "main" }, + merge_commit_sha: merged ? mergedSha : null, + ...pullRequest, + }, + })); + const getExecOutput = mock.fn(async () => { + if (mergeResult) return mergeResult; + merged = true; + return { exitCode: 0, stdout: "Merged", stderr: "" }; + }); + const parameters = { + github: { rest: { pulls: { get } } }, + context: { repo: { owner: "example", repo: "repository" } }, + core: { + debug: mock.fn(), + setOutput: (key, value) => { + outputs[key] = value; + }, + }, + exec: { getExecOutput }, + sleep: mock.fn(async () => {}), + env: { PULL_REQUEST_NUMBER: "123", PULL_REQUEST_HEAD_SHA: headSha, ...env }, + }; + return { parameters, outputs, get, getExecOutput }; +} + +test("disabling bypass uses a normal merge and returns the verified merge outputs", async () => { + const setup = scenario({ env: { BYPASS_BRANCH_PROTECTION: "false" } }); + await run(setup.parameters); + const [command, args] = setup.getExecOutput.mock.calls[0].arguments; + assert.equal(command, "gh"); + assert.deepEqual(args, [ + "pr", + "merge", + "-R", + "example/repository", + "--rebase", + "--match-head-commit", + headSha, + "123", + ]); + assert.deepEqual(setup.outputs, { + "merged-ref": "refs/heads/main", + "merged-sha": mergedSha, + }); +}); + +test("branch protection failures never escalate to administrator merge", async () => { + const setup = scenario({ env: { BYPASS_BRANCH_PROTECTION: "false" } }); + setup.getExecOutput.mock.mockImplementation(async (_command, args) => { + if (args.includes("--admin")) + return { exitCode: 0, stdout: "Bypassed protection", stderr: "" }; + return { exitCode: 1, stdout: "", stderr: "Required reviews are missing" }; + }); + await assert.rejects(run(setup.parameters), /Required reviews are missing/); + assert.equal(setup.getExecOutput.mock.callCount(), 1); + assert.deepEqual(setup.outputs, {}); +}); + +for (const bypass of [undefined, "true"]) { + test(`preserves administrator merge with ${bypass === undefined ? "the default" : "explicit bypass"} and checks the expected head`, async () => { + const setup = scenario({ env: { BYPASS_BRANCH_PROTECTION: bypass } }); + await run(setup.parameters); + const args = setup.getExecOutput.mock.calls[0].arguments[1]; + assert.ok(args.includes("--admin")); + assert.equal(args[args.indexOf("--match-head-commit") + 1], headSha); + }); +} + +test("refuses a head change before invoking the merge command", async () => { + const setup = scenario({ pullRequest: { head: { sha: "c".repeat(40) } } }); + await assert.rejects(run(setup.parameters), /head changed/); + assert.equal(setup.getExecOutput.mock.callCount(), 0); + assert.deepEqual(setup.outputs, {}); +}); + +test("a head change during the merge command fails without retrying", async () => { + const setup = scenario(); + setup.getExecOutput.mock.mockImplementation(async (_command, args) => { + assert.equal(args[args.indexOf("--match-head-commit") + 1], headSha); + return { exitCode: 1, stdout: "", stderr: "Head commit does not match" }; + }); + await assert.rejects(run(setup.parameters), /Head commit does not match/); + assert.equal(setup.getExecOutput.mock.callCount(), 1); + assert.deepEqual(setup.outputs, {}); +}); + +for (const [env, error] of [ + [{ BYPASS_BRANCH_PROTECTION: "yes" }, /bypass-branch-protection/], + [{ PULL_REQUEST_HEAD_SHA: "" }, /head SHA/], + [{ PULL_REQUEST_HEAD_SHA: "not-a-commit" }, /head SHA/], + [{ PULL_REQUEST_NUMBER: "--admin" }, /pull request number/], + [{ MERGE_METHOD: "unsupported" }, /Invalid merge method/], +]) { + test(`invalid merge input is rejected: ${JSON.stringify(env)}`, async () => { + const setup = scenario({ env }); + await assert.rejects(run(setup.parameters), error); + assert.equal(setup.get.mock.callCount(), 0); + assert.equal(setup.getExecOutput.mock.callCount(), 0); + }); +} + +for (const method of ["merge", "squash"]) { + test(`${method} preserves the supplied title and multiline message as arguments`, async () => { + const title = "docs: update references"; + const body = "Generated files\n\nLiteral $(not-a-shell-command)"; + const setup = scenario({ + env: { + MERGE_METHOD: method, + PULL_REQUEST_TITLE: title, + PULL_REQUEST_COMMIT_MESSAGE: body, + }, + }); + await run(setup.parameters); + const args = setup.getExecOutput.mock.calls[0].arguments[1]; + assert.ok(args.includes(`--${method}`)); + assert.equal(args[args.indexOf("--subject") + 1], title); + assert.equal(args[args.indexOf("--body") + 1], body); + }); +} + +test("waits for mergeability without changing the expected head", async () => { + const setup = scenario(); + setup.get.mock.mockImplementationOnce(async () => ({ + data: { mergeable: null, head: { sha: headSha } }, + })); + await run(setup.parameters); + assert.deepEqual( + setup.parameters.sleep.mock.calls.map((call) => call.arguments[0]), + [1000], + ); + assert.equal(setup.getExecOutput.mock.callCount(), 1); +}); + +test("retries a transient required-workflow error with the same merge guard", async () => { + const setup = scenario({ env: { BYPASS_BRANCH_PROTECTION: "false" } }); + setup.getExecOutput.mock.mockImplementationOnce(async () => ({ + exitCode: 1, + stdout: "", + stderr: "Required workflow is pending", + })); + await run(setup.parameters); + assert.equal(setup.getExecOutput.mock.callCount(), 2); + for (const call of setup.getExecOutput.mock.calls) { + const args = call.arguments[1]; + assert.equal(args[args.indexOf("--match-head-commit") + 1], headSha); + assert.ok(!args.includes("--admin")); + } +}); + +test("mergeability polling terminates without a merge when conflicts remain", async () => { + const setup = scenario({ pullRequest: { mergeable: false } }); + await assert.rejects( + run(setup.parameters), + /not mergeable after 10 attempts/, + ); + assert.equal(setup.get.mock.callCount(), 10); + assert.equal(setup.getExecOutput.mock.callCount(), 0); +}); + +test("a successful command is not reported as a completed merge until GitHub confirms it", async () => { + const setup = scenario({ + mergeResult: { exitCode: 0, stdout: "Queued", stderr: "" }, + }); + await assert.rejects( + run(setup.parameters), + /timed out.*merge verification|timed out.*verification/, + ); + assert.deepEqual(setup.outputs, {}); +});