Cleanup Abandoned Git Branches

      No Comments on Cleanup Abandoned Git Branches

Often we create branches in a Git repo to do a proof-of-concept or do work on a bug or enhancement that never get merged into master. The longer those branches go unmerged, they may be handled elsewhere or are no longer valuable or applicable. This adds clutter repo when browsing in your Git client or Bitbucket web interface. This process can allow you remove the branches while still being able to retrieve the commits if the need should ever arise.

Step-by-step guide

Deleting branches does not delete the related commits. In order to still understand their original intent while keeping things tidy, we can use tags. This can be done even without checking out the original branches. And just like branches, you can use slashes to mimic a folder structure. In this case, we use “archive”.

git tag archive/example-old-branch origin/example-old-branch
git push origin archive/example-old-branch

You can now safely delete the original branch on the remote origin.

git push origin –delete example-old-branch

Bash Script

You can automate this process with a script that receives one or more parameters.

branch=$1
tag=""
if [ $2 ]; then
  tag="archive/$2"
else
  tag="archive/feature/$branch"
fi
 
if [[ $tag =~ \/$ ]]; then
    tag="$tag$branch"
fi
 
cmd1="git tag $tag origin/$branch"
echo $cmd1
$cmd1
 
cmd2="git push origin $tag"
echo $cmd2
$cmd2
 
cmd3="git push origin --delete $branch"
echo $cmd3
$cmd3

This handles three scenarios:

One Parameter

$ git-archive example-old-branch
git tag archive/feature/example-old-branch origin/example-old-branch
git push origin archive/feature/example-old-branch
git push origin --delete example-old-branch

This assumes the tag will have the same name as the original branch. A prefix of “archive/feature/” is added by default.

Two Parameters

$ git-archive example-old-branch misc/old-branch
git tag archive/misc/old-branch origin/example-old-branch
git push origin archive/misc/old-branch
git push origin --delete example-old-branch

This takes the second parameter as a more specific tag name. Only “archive/” is added so all archive tags are grouped together.

Two Parameters, Second with Trailing Slash

$ git-archive example-old-branch misc/
git tag archive/misc/example-old-branch origin/example-old-branch
git push origin archive/misc/example-old-branch
git push origin --delete example-old-branch

The second parameter is understood as a folder so it’s added between the “archive/” prefix and the original branch name.

Conclusion

It’s always good to tidy up a repo every so often. Perhaps after a major release or every few months when you’re between projects. Now you can focus on the actual code you’re writing!

Leave a Reply