Large development teams develop a lot of features. During the lifetime of a repo, the amount of stale branches can grow and snowball. This could be regulated with team rules about what to do with branches after the merge and who should delete them. But as with any manual operation, sometimes someone forgets about it. So once per month or two you should review staled branches and delete them.

My Automation Engineer mind always tries to automate each routine operation like this. So I've configured a cron action that cleans old branches using a pattern.

I’ve used an already existing solution from beatlabs where you can setup the branches to be removed using regexp. Let’s look at the configuration and describe the key moments:

name: CLEAR OLD BRANCHES

on:
  schedule:
    - cron: "0 0 * * 1"
jobs:
  cleaning:
    name: Cleanup old branches
    runs-on: ubuntu-latest
    steps:
      - name: checkout
        uses: actions/checkout@v2
      - name: clean
        uses: beatlabs/[email protected]
        with:
          repo_token: ${{ secrets.GH_TOKEN }}
          date: '2 month ago'
          dry_run: false
          delete_tags: false
          minimum_tags: 5
          extra_protected_branch_regex: master.*|main|develop|^release.*|.*_p$



First of all, let’s set up a trigger when action should be executed. It might be a push, merge, or any other. In my mind, this action is something like general cleaning so I’ve set up its execution by crone once per week every Monday. To configure an appropriate crone for you I can advise a great resource:

https://crontab.guru

on:
  schedule:
    - cron: "0 0 * * 1"

After that, define Cleaning Job with steps:

Checkout is pretty straightforward with actions/checkout@v2 it executes fetch repository. There is no need for any additional configuration.

Clean action has a few important options:


Once you’ve completed setup, enjoy cleaning and forget about routine manual management of staled branches.