Delete merged Git branches automatically - without risking the ones you need
Branches pile up. Ours went from a handful to 72 in a few weeks, most of them already merged. GitHub has a built-in fix: "Automatically delete head branches". But it deletes a branch the moment its pull request merges. On repositories without branch protection, that includes long-lived branches like staging or develop after a release PR — and it never touches branches merged before you turned it…
Branches accumulate rapidly within projects. In a few weeks, a project went from a few branches to 72, many of which were already merged. GitHub offers a built-in feature: "Automatically delete head branches". However, this feature deletes a branch immediately after its pull request merges. On repositories without branch protection, this includes long-lived branches like staging or develop after a release pull request.
Importantly, it does not delete branches merged before the feature was activated. To address this issue, a team developed Safe Branch Cleanup, a GitHub Action. This tool checks each branch before deleting it. It only deletes a branch if it has a merged pull request and its latest commit is already in the base branch (including squash and rebase merges).
It never touches the default or base branch, protected branches, branches on a keep list, branches with open pull requests, work in progress, or pull requests closed without merging. Any deleted branches can be restored from their pull request page. To set up the tool, add one step to a workflow: use the manthrix/safe-branch-cleanup version 1.0.0, specifying the branches to keep.
Running the tool in dry-run mode allows you to see exactly what it would delete. After implementing it, the number of branches was reduced from 72 to 2. The tool is available on GitHub Marketplace and has a few "good first issue" tasks for contributors. Feedback is welcomed, particularly for edge cases that may have been overlooked.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to