When you create a pull request in GitHub, you start building commits on top of a branch that is called the base branch. That new branch that contains your new code is called the head branch. Your goal is to merge the head branch into the base branch.

The base branch is stored inside the target repository. But where’s the head branch? It could be either in the target repository or in a fork of that repository, depending on the user workflow and permissions.

If the head branch is in a fork, it’s the pull request author problem to keep its fork clean. However, if the head branch is located in the target repository itself, it’s good to keep that one tidy and remove merged branches.

Cleaning Up Head Branch

Once a pull request is merged, the pull request author will see such a button at the bottom of the pull request page:

If the pull request author clicks that button, the head branch of the pull request will be deleted — a safe operation since it’s been merged.

Deleting merged branches is something a lot of repository maintainers likes to do to keep their repository easy to browse.

Though you know that nobody at Mergify likes to click on buttons, so let’s see how to automate that!

Automatic Branch Clean Up

When a pull request is created with a head branch from the same repository where Mergify’s running, Mergify can delete the branch automatically for you. No need to click any button!

Here’s a rule that would do that for you:

pull_request_rules:
  - name: delete head branch on merged pull requests
    conditions:
      - merged
    actions:
      delete_head_branch:

As soon as a pull request is merged, the head branch is deleted.

You could also mean to delete the head branch if the pull request is just closed and not merged. Just use the following snippet:

pull_request_rules:
  - name: delete head branch on closed pull requests
    conditions:
      - closed
    actions:
      delete_head_branch:

Be aware that this rule will remove the head branch when the code is not merged — so while it keeps your code clean, it’ll also delete code that has not been merged anywhere, which means potential data loss. Beware! :)

If you have any other fun idea around this workflow, please leave a comment below!