Periodically Update A Branch

How to keep a branch up-to-date by nightly merging the default branch using GitHub Action

Imaging you have a repo with default branch main and another branch X. You want to have X always up-to-date, maybe it is deployed to the staging environment nightly. Here is how to update the branch X automatically using a GitHub Action.

🎁 This example is available at bahmutov/self-update-branch.

GitHub Action

I am using a GH Action workflow to update the branch X nightly or when manually triggered. See the file update-branch.yml

.github/workflows/update-branch.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# https://glebbahmutov.com/blog/trying-github-actions/
name: update-branch
on:
# update the branch X every night
schedule:
- cron: '0 3 * * *'
# or update the branch X manually
workflow_dispatch:

jobs:
update:
runs-on: ubuntu-20.04
steps:
- name: Checkout 🛎
# https://github.com/actions/checkout
uses: actions/checkout@v3
with:
# check out all branches
fetch-depth: 0
# use a personal access token to commit
# the merged code and trigger CI actions
token: ${{ secrets.GH_PAT }}
- name: Update Git branch X
run: |
git config user.name "Update branch"
git config user.email [email protected]
git checkout X
git merge main --no-edit -m "Merged main branch on $(date +%F)"
- name: Push the updated branch X
run: |
git push origin X

I need to use the GitHub personal access token in order for the update commit to trigger other CI services.

Example

You can find a pull request #1 that automatically gets the new updates from the main branch. A merged commit into the branch X triggers the CI runs. In the screenshot below, the merge commit triggers another GitHub workflow test-branch-x and a CircleCI workflow.

The pull request from the branch X updated automatically

See also

One use case for keeping a branch evergreen using the approach described in this blog post is deploying an instrumented version of the application for testing to collect the code coverage information. Read the blog post Code Coverage For Nextjs Application.