Today, I want to show how you can automate removing of old branches when merging child branches in a parent branch. Now, one can say this topic had already been overtaken due to the wide use of CI and services like github/bitbucket. But as the story says: “Github will help only those who help themselves.”
Let’s assume we have a project of the following structure:
To start removing branches, we need to define first what actually needs to be removed.
Returns all branches names that contain current commit. If HEAD is on e, we will get the following output:
To exclude the current branch, as well as a master one, from the output, let’s add the following regex:
If you need to exclude any more branches, ‘develop’ for example, the expression will look like:
To remove detected branches from the remote repository, we run the command:
And here’s how it will look like after being combined with the logic we already have:
Now after we’ve written a code that removes a branch from a remote repository, we need to make sure that local branch copies always end up being removed too. The following instruction will help us so this:
After removing all branches from a ‘remote’, this is how instruction’s output will look like:
As seen from the output, branches now have ‘gone’ status, which allows us to write a regex, find branches, and delete them.
From combining it with the previous expression, we’ll get:
After command execution, we’ll get the following output:
For the sake of convenience, let’s add ‘alias’ for this command into gitconfig, by calling
And adding the following string there:
Now we can remove branches with a single command
There’s only one small problem left: no to forget to run a script that removes unnecessary branches whenever merging is done. But wait, is it a problem at all? We could just use ‘post-merge commit hook’, and that’s it!
To do this, let’s create a .git/hooks/post-merge file, and add one single command to it:
Let’s make sure that file is accessible:
So now, after every merge, all merged branches will be removed automatically.