DEV Community

Cover image for Local Git Branch Prune/Delete Against Remote in Python
Tony Mezzolesta
Tony Mezzolesta

Posted on

Local Git Branch Prune/Delete Against Remote in Python

Automation is a programmer's best friend. Its an investment of time and skill in order to make your life and job easier. Hey, we have all been there. You are working on a project and you are attempting a major change. So you create a new branch off of the master and make your changes. Publish/Commit/Push. Now you have to look into a bug but you don't want to merge your changes in without testing yet. You create a new branch off of the master and resolve your bug there. Tested and merged into master. After weeks of doing this, you realize that your local branches have piled up and are most likely dead (assuming that you delete your branches in remote once they are merged). So you will need to run a command to prune, then run a command to get branches including remote, then run another command to delete old branches...bleh.

So I wrote a python script that will automatically do this for you. You can either setup a task to run every so often or just run it straight from the terminal. I know that this is nothing fancy, but I hope this is useful to someone like me who just got sick of cleaning their local git repo.

Note:

This will DELETE branches that are not in remote. Make sure you publish them if they are not old or marked for clean-up. Also, this will skip over the branch you are sitting on along with the master branch. You can manipulate the script to skip over any other branches you want (development/staging).

Prerequisites:

  • Directory must have git initialized. You can pass the directory in as an argument. See read me in github repo.
  • Must have Python 2.7+ installed.

GitHub logo TonyMezzolesta / Clean_Local_Branches_Python

Python script that will prune branches and delete any local branches that do not exist in origin.

Clean_Local_Branches_Python

Python script that will prune branches and delete any local branches that do not exist in origin.

Command

To initiate, simply run command:

$ python %file_directory%/prune.py

or run with arguments:

$ python %file_directory%/prune.py C:\git\repo

Arguments

  1. arg[0] = File location of script. This is added by default
  2. arg[1] = Directory workspace (optional). Leave blank if script is in local workspace.

Steps

  1. Runs the prune command against origin
  2. Gets list of local branches
  3. Loops through local branches
  4. Checks each local branch against remote to see if it exists
  5. If not exists, run delete on local branch

Exceptions

The script will skip the current branch you are on (*) and the master branch. This can be adjusted per your liking by the if statements in the for loop.




Top comments (0)