Git tidy-up

Why do I need to tidy?

Put simply, when working with Git Flow and pull requests, it’s very easy to end up with orphaned branches held locally. There’s nothing to stop you from having them there, but sometimes it’s nice to not have branches locally that have long since been made redundant.

How did I end up messy?

At work we use a Git Flow-based setup, with our repositories stored in Azure DevOps’ Git. It works well. Since moving from our legacy git server (BonoboGit, hosted on our local network), one of the main benefits has been the introduction of Pull Requests into our process.

When you start off, everything goes pretty much as you’d expect. Let’s imagine you do the following:

me@local:~ git flow feature start create-build-pipeline
me@local:~ touch azure-pipelines.yml
me@local:~ git add azure-pipelines.yml
me@local:~ git commit -m "Added pipeline"
me@local:~ git push -u origin feature/create-build-pipeline

At this point the next step is to raise a PR to get this reviewed and, ultimately, merged back into the develop branch. Most of our development team use the same settings when completing the PR – squash the commit, and delete the source branch.

So, all things being well, once the PR has been approved and completed the change from the create-build-pipeline feature branch is now in develop, but the branch itself has been removed from the main repository. However, it’s still on your local machine.

How to tidy up

Fortunately, all of the commands you need to do this are already available in Git.

me@local:~ git checkout develop
me@local:~ git pull
me@local:~ git fetch --prune
me@local:~ git branch -vv
me@local:~ git branch -D feature/create-build-pipeline

The first two commands shouldn’t need an explanation.
The git fetch --prune command is the key command here as it will:

…connect to a shared remote repository remote and fetch all remote branch refs. It will then delete remote refs that are no longer in use on the remote repository.

Atlassian Git Prune documentation

This latter part is the key to tidying up the local branches, as it ensures that your local copy of the repository knows which branches have been removed.
The git branch -vv command is more of a sanity-check than anything else. It will display the local branches and compare them to the remote ones. In this example, the feature/create-build-pipeline branch should display as “gone”.
The final command forces the removal of the now-redundant branch.