DEV Community

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 on.

Why we built Safe Branch Cleanup

So we built Safe Branch Cleanup, a small GitHub Action that checks each branch first.

It deletes a branch only when:

  • it had a merged pull request, and
  • its latest commit is already in your base branch (squash and rebase merges included).

It never touches your default or base branch, protected branches, a keep list you choose, branches with an open pull request, work in progress, or pull requests closed without merging.

Anything deleted can be restored from its pull request page.

Setup

Add one step to a workflow:

- uses: manthrix/safe-branch-cleanup@v1.0.0
  with:
    keep-branches: staging, develop

Run it once in dry-run mode to see exactly what it would delete. On our own repo it took us from 72 branches to 2 - safely.

Links

There are a few "good first issue" tasks if you'd like to contribute. Feedback welcome - especially edge cases we haven't thought of.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.