Keep your development workspace tidy

A big issue I find when working in today's modern development environment is the ever increasing number of git repositories we now have to maintain. With each repository comes a number of branches that we create, push and pull as we progress the development of each service and over time they just start to build up like driftwood on a beach; not the pretty driftwood of photos and art-pieces but junk useless wood that have long served their purpose. Just recently I counted that in the space of a couple of months I had pulled in over 40 repositories and most of those repositories had multiple branches and in one extreme case I had over 30 branches, all of the branches had either been merged back to master or I had abandoned e.g. spikes.

Now I could have done the simplest thing and just removed each one individually as I went along or just devote sometime every so often and do the same but en-masse. Instead I decided to do neither and instead I wrote a script that I could execute from a bash shell and later refined it into an alias.

alias -p bfg='for d in */; { echo $d; cd $d; { git checkout -q master; git branch | egrep -v "(^\*)|(^\s+(master|dev|hotfix|qa))" | xargs --no-run-if-empty git branch -D ; }; cd ..; };'  

I call it BFG because it shows no mercy and I only run it when I just want to tidyblow things up.

Let me describe how it works (and I am doing this as much for my sake as for yours.)

  • For each subfolder under the current folder
  • switch to the master branch
    e.g. git checkout -q master
  • list all the available branches
    e.g. git branch ...
  • filter out those in the 'keep' list
    e.g. ... | egrep -v "(^\*)|(^\s+(master|dev|hotfix|qa))" ...
  • if any extra branches found delete them
    e.g. ... | xargs --no-run-if-empty git branch -D ;

I now try to run this at least once a month, especially when we have delivered on a number of features, and I know that it is safe to do so. If I am feeling nervous about running the script I substitute the -D for -d when executing git branch as this will not remove a branch if it has not yet been merged with its upstream.

Any questions or suggestions for improvements please post below.