Skip to content

About

Merges a pull request, or marks a draft ready for review, once all the conditions you list hold, such as a label, a passing check or approvals

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Use this GitHub action with your project
Add this Action to an existing workflow or create a new one
View on Marketplace

Repository files navigation

merge-when

GitHub Release CI

Merges a pull request, marks a draft ready for review, rewrites its branch without merge commits, or rebases it when it has fallen behind its base, once conditions you list all hold, without relying on GitHub's own auto-merge or branch protection. merge-when-green is this action with the conditions for "labelled, green and discussed" filled in.

When to use this

  • A private repository on the Free plan, where GitHub offers neither auto-merge nor required status checks.
  • A repository where auto-merge is switched off, by a repository or organisation setting you can't or won't change.
  • Merge rules kept in a workflow rather than in settings: wait for one aggregate check on the exact head commit, for every review thread to be resolved, for approvals, or for a particular author, whichever plan the repository is on.
  • A setup with no personal access token to hand out: a GitHub App or a deploy key can do the merge instead.

Where GitHub's native auto-merge with required checks is available and does what you need, use that. Nothing here stops anyone merging by hand; the action only saves waiting.

Use

The action has no triggers of its own, so a workflow supplies them. Run it when CI finishes, and again when the label is added or the pull request leaves draft, so a pull request that already meets the conditions merges at once.

name: Merge when

on:
  workflow_run:
    workflows: [CI]
    types: [completed]
  pull_request_target:
    types: [labeled, ready_for_review]

concurrency:
  group: merge-when-${{ github.event.workflow_run.head_sha || github.event.pull_request.head.sha }}
  cancel-in-progress: false

permissions:
  contents: read
  pull-requests: read
  checks: read

jobs:
  merge:
    if: >-
      (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success')
      || (github.event_name == 'pull_request_target' && contains(github.event.pull_request.labels.*.name, 'automerge'))
    runs-on: ubuntu-latest
    steps:
      - uses: ExaDev/merge-when@v1
        with:
          merge-token: ${{ secrets.MERGE_TOKEN }}
          when: |
            label: automerge
            check: Required checks
            not-draft
            threads-resolved

Do not add a checkout step that fetches pull request code. Running no pull request code is what makes the pull_request_target trigger safe.

A pull request is considered only when it still has the commit that triggered the run at its head, and the merge is pinned to that commit, so a push made after the conditions held is never merged unseen.

Conditions

when lists one condition per line, and every line must hold. Blank lines and lines starting with # are ignored. An unknown condition, or a value given to a condition that takes none or missing from one that needs it, fails the run before any pull request is touched, so a typo can't silently drop a safeguard. The checking is done by when-core, shared by the when actions.

Condition Holds when
label: <name> the pull request carries the label
check: <name> a check run of that name succeeded on the head commit. Point it at one aggregate job that needs every other job and runs with if: always(), so it passes only when they all did
threads-resolved no review thread is unresolved (more than 100 threads counts as unresolved)
not-draft the pull request is ready for review
approvals: <n> at least n reviewers' latest review is an approval and none requests changes
author: <a>, <b> the author's login is one of those listed, such as dependabot[bot]
base: <branch> the pull request targets that branch
behind the base branch has commits the pull request's head lacks

Marking drafts ready

With then: ready, a draft whose conditions all hold is marked ready for review instead of merged. Run it beside a merge workflow so that agents or people can open pull requests as drafts and leave them to become reviewable, and then mergeable, once CI is green:

name: Ready when

on:
  workflow_run:
    workflows: [CI]
    types: [completed]

concurrency:
  group: ready-when-${{ github.event.workflow_run.head_sha }}
  cancel-in-progress: false

permissions:
  contents: read
  pull-requests: read
  checks: read

jobs:
  ready:
    if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    steps:
      - uses: ExaDev/merge-when@v1
        with:
          then: ready
          merge-token: ${{ secrets.MERGE_TOKEN }}
          when: |
            label: automerge
            check: Required checks
            threads-resolved
  • CI has to run on drafts. The aggregate check must report on a draft's head commit, so don't skip CI jobs with if: github.event.pull_request.draft == false or leave ready_for_review as the only trigger; GitHub's default pull_request types already include drafts.
  • The token must not be GITHUB_TOKEN. GitHub starts no workflow from an event that token caused, so a pull request it marked ready would never trigger the ready_for_review run of the merge workflow. Give merge-token, or app-id and app-private-key; the action refuses to run without one.
  • then: ready takes no merge settings. not-draft (which a draft can never meet), merge-method, ssh-key, update-behind and allow-merge-commits are each rejected before any pull request is touched.
  • It is reversible but not pinned. gh pr ready has no head-commit pin, so a push landing between the check and the call is readied with it. A pull request readied wrongly goes back with gh pr ready <number> --undo.

Linearising a branch

With then: linearise, a pull request whose branch holds merge commits is rebased onto its base and the result is pushed to its branch with a lease on the head commit that was checked, so CI runs on the new head. A rebase drops the merge commits and replays the rest, which loses any conflict resolved inside one, so the branch is rewritten only when the rebased tree is the tree that merging the head into the base gives. Otherwise nothing is pushed and the run says the branch needs rebasing by hand. A pull request with no merge commits, or from a fork, is left alone. It needs merge-token, app-id or ssh-key, never GITHUB_TOKEN, whose push would start no CI run, and takes no merge-method or update-behind.

Run it when a pull request is opened or pushed to, under the same pull_request_target caution as the merge: nothing here checks out or runs pull request code, since the rebase happens in a fresh repository holding only the fetched commits.

on:
  pull_request_target:
    types: [opened, synchronize, reopened]

jobs:
  linearise:
    runs-on: ubuntu-latest
    steps:
      - uses: ExaDev/merge-when@v1
        with:
          then: linearise
          ssh-key: ${{ secrets.MERGE_DEPLOY_KEY }}
          when: |
            not-draft

A fast-forward merge refuses a pull request that still has merge commits, because its push would put them on the base branch, unless allow-merge-commits: true says they belong there (a subtree merge, whose merge commit is the content a rebase would drop). With update-behind, such a pull request that has fallen behind its base is brought up to date by merging the base into it, a push that only adds commits, since a rebase would drop its merge commits.

Rebasing a branch

then: rebase brings a pull request that has fallen behind its base up to date: its commits are replayed onto the base and pushed to its branch with a lease on the head that was read, so CI runs on the new head and a later run can merge it. It is a different effect from linearise, which removes merge commits: a branch that is both behind and holds merge commits is left alone by rebase, which says to linearise it first, since a rebase would drop those merge commits and any conflict resolved inside one. A pull request whose head already contains its base is left alone, whatever the conditions say. A rebase that conflicts pushes nothing and the run says the branch needs updating by hand. A fork's pull request is left alone, and the credential rules are those of linearise: merge-token, app-id or ssh-key, never GITHUB_TOKEN, with no merge-method or update-behind.

What triggers it is a push to the base branch, which moves every open pull request's base and changes no pull request's head, so unlike the other effects it does not look for the pull requests that have the triggering commit at their head. It considers every open pull request, each at the head it has now, and the when lines decide which are rebased. behind is the condition that makes the run a no-op for those already up to date; label keeps it to the pull requests that opted in, and a not-draft line leaves drafts alone.

on:
  push:
    branches: [main]

concurrency:
  group: rebase-when
  cancel-in-progress: false

jobs:
  rebase:
    runs-on: ubuntu-latest
    steps:
      - uses: ExaDev/merge-when@v1
        with:
          then: rebase
          ssh-key: ${{ secrets.MERGE_DEPLOY_KEY }}
          when: |
            label: automerge
            behind

Re-running jobs lost to the runner

A job on a self-hosted runner that restarts mid-job ends failed or cancelled, the aggregate check fails and nothing is merged until someone re-runs the failed jobs. With rerun-lost-runners: <n> (default 0, which does nothing), a workflow_run that did not succeed has the check-run annotations of every job that did not succeed (anything but success, skipped, neutral or still running) read, and its failed jobs are re-run when every one of them carries a runner-loss annotation (its message starts The self-hosted runner lost communication with the server). A job that failed with a test or build error, or was cancelled by its own timeout (its message starts The job has exceeded the maximum execution time), is never re-run, and one such job stops the re-run of the others. The run's attempt number bounds it: a run past attempt n is left alone, so n re-runs at most. A job is classified by its annotation and never by its conclusion, except that a timed_out job without a runner-loss annotation counts as a timeout: a job lost to its runner can show as failed with its running step left without a conclusion, and one stopped by its timeout shows as cancelled. Each job is written to the step summary as re-run or left alone with the reason.

The workflow that runs the action must be triggered by workflow_run and let the job start when the run did not succeed, and the token that re-runs the run is read-token (github.token by default), which needs actions: write. A run that did succeed is merged as usual. It is only used with then: merge.

permissions:
  contents: read
  pull-requests: read
  checks: read
  actions: write

jobs:
  merge:
    if: github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: ExaDev/merge-when@v1
        with:
          merge-token: ${{ secrets.MERGE_TOKEN }}
          rerun-lost-runners: 2
          when: |
            label: automerge
            check: Required checks

Credentials

How the merge is made decides which credential you give. At most one of merge-token, app-id and ssh-key.

Method Credential
rebase, squash, merge (through the API) merge-token, a personal access token or a GitHub App installation token, or app-id with app-private-key, which mints an installation token for the repository (the app needs read and write on contents and pull requests)
fast-forward any of the above, pushing over HTTPS, or ssh-key, a write deploy key, pushing over SSH

A deploy key is an SSH key and cannot call the API, so it only works with fast-forward. Use a credential other than GITHUB_TOKEN when the merge should start workflows (a release on main), because GitHub does not start workflows from pushes made with GITHUB_TOKEN. A protected base branch needs the credential's identity to be a bypass actor.

fast-forward fetches the pull request's head and pushes that exact commit to the base branch, which GitHub records as the pull request being merged. Because it is a push of existing commits, a pull request that is behind its base is not merged (the push is rejected) and is left for its author to update, unless update-behind: true: the action then rebases the head branch onto the base and pushes it back with a lease on the head it saw, so CI runs on the new head and a later run merges it. Fork pull requests and rebases that conflict are left alone. A pull request counts as behind only when the base, fetched again after the rejected push, is not contained in its head; any other failed push fails the run with git's error. A fetch or push whose connection fails is tried up to three times in all, for every effect that uses git.

Inputs

Input Default Meaning
when required The conditions, above
then merge merge, ready to mark a draft ready for review, linearise or rebase
merge-method rebase rebase, squash, merge or fast-forward, for then: merge
merge-token An API token
app-id, app-private-key A GitHub App to mint a token from
ssh-key A write deploy key, for fast-forward, linearise and rebase
update-behind false For fast-forward, rebase a behind pull request instead of leaving it
allow-merge-commits false For fast-forward, merge a pull request that holds merge commits
rerun-lost-runners 0 For then: merge, how often a run lost to its runner is re-run, above
read-token github.token Token used to read pull requests, checks and review threads; re-runs runs
head-sha event's head commit Commit to act on

Development

npm test runs the bats suite for merge.sh against fake gh and git executables and the unit tests for the release plugins, and npm run shellcheck lints the script. CI also runs the composite action itself from the checkout, so its when-core step is exercised against the published v1, and commitlint, actionlint, typecheck, lint and format checks, aggregated into one Required Checks job.

This repository merges its own labelled pull requests with the action, using fast-forward and the release deploy key (.github/workflows/merge-when.yml).

Releases are made by semantic-release from conventional commits on main: it tags the version, publishes the GitHub Release with the changelog entry and a full changelog link, and moves the major tag (v1) that consumers pin to, with a release of that name carrying the changelog for the whole major version.

About

Merges a pull request, or marks a draft ready for review, once all the conditions you list hold, such as a label, a passing check or approvals

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages