Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GitHub Actions to check if branch is up to date with main

How can I add something to my GitHub Actions script to make sure the branch is up to date with the current main branch, i.e., has main as an ancestor?

I know GitHub's repo settings page has a "Require branches to be up to date before merging" option. But it'd still be useful to have the GitHub Actions script fail quickly if the branch isn't up to date, instead of spending 5-10 minutes setting up our testing environment.

like image 600
Josh Avatar asked Sep 15 '25 22:09

Josh


1 Answers

Here's a sample section of a GitHub Actions script to:

  1. Run when a pull request is opened, reopened, or has new commits pushed to it, if that pull request has main as its target branch
  2. Check that the current commit has main as an ancestor, and fail if it doesn't
  3. Don't start the next job/check until the first check has finished
name: Pull Request Checks

on:
  pull_request:
    branches: main

jobs:
  check_if_branch_is_ahead_of_main:
    runs-on: ubuntu-latest
    steps:
      - name: Git checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Check if branch is ahead of main
        run: |
          if ! git merge-base --is-ancestor origin/main ${{ github.event.pull_request.head.sha }};
          then echo "This branch is not up to date with main";
          exit 1; fi

  next_job:
    needs: check_if_branch_is_ahead_of_main
    ...

Note: by default, a GitHub Action running on the pull_request trigger thinks the current commit is a fictional commit that would be produced by merging your pull request into the target branch. ${{ github.event.pull_request.head.sha }} means use the actual commit at the HEAD of the pull request's branch instead.

like image 164
Josh Avatar answered Sep 18 '25 14:09

Josh