Published on

Git Repository Clean Up

Authors

    After you have been developing a project for some time your local git repo becomes detached from the repository on 'origin'. Having loads of local branches that are not needs because they have been merged in already. Or all of the remote branches that are no longer on the remote. There are a few commands you can run to clean things up a bit when you feel things are getting cluttered.

    The first one is supper simple we want to remove all the remove references that are no longer on the remote, this can be done by executing our first clean up command.

    git fetch --prune

    Lastly we can remove any of the old branches that have already been merged. For that we can use the below command.

    git --no-pager branch --merged | grep -Ev 'master|^\*' | xargs git branch -d

    The first bit is getting listing all the branches that have already been merged.

    git --no-pageer branch --merged

    Next we need to remove the branches we want to keep. This is being done with a reverse regex grep anything separated by the | is a or. The first one is the master branch we obviously don't want to remove that. The next one is the branch starting that a * or in our case this is the branch you are currently on. Feel free to add any other branch names in here, when I do it I may add a development branch that is a working branch we sometimes use.

    grep -Ev 'master|^\*'

    Lastly we want to delete all the branches that are being printed out. This bit is simple we can just use the git branch -d command and run it with xargs so we can pipe to the command. You may want to leave this last bit off on the first run so you can see what branches will be deleted as there is no --dry-run flag for this delete command.

    xargs git branch -d