DEV Community

Fernando Muller Junior
Fernando Muller Junior

Posted on

Automatizing Git Branches Cleanup: Streamlining Your Workflow

Introduction

Managing Git branches efficiently is essential for maintaining a clean and organized codebase. As your project grows, so does the number of branches, making it crucial to automate the cleanup process. In this article, we’ll explore best practices and a Python script to automate Git branch cleanup.
Best Practices for Branch Cleanup

Image description

Before diving into automation, let’s establish some best practices:

  • Regular Review: Schedule regular reviews to identify stale or obsolete branches.
  • Merge and Delete: After merging a feature or bug fix, promptly delete the associated branch.
  • Automate: Automate the process to ensure consistency and save time.

Automating Git Branch Cleanup with Python

The Python Script

Below is a simple Python script that automates Git branch cleanup. Save it as cleanup_branches.py:

import subprocess

def cleanup_branches():
    try:
        # Fetch all remote branches
        subprocess.run(["git", "fetch", "--all", "--prune"])

        # Get a list of merged branches
        merged_branches = subprocess.check_output(["git", "branch", "--merged"]).decode("utf-8").splitlines()

        # Exclude main/master branch
        merged_branches = [branch.strip() for branch in merged_branches if branch.strip() != "main"]

        # Delete merged branches
        for branch in merged_branches:
            subprocess.run(["git", "branch", "-d", branch])
            print(f"Deleted branch: {branch}")

        print("Branch cleanup completed successfully!")
    except Exception as e:
        print(f"Error during cleanup: {e}")

if __name__ == "__main__":
    cleanup_branches()
Enter fullscreen mode Exit fullscreen mode

Success Stories

Many development teams have benefited from automating branch cleanup. By implementing similar scripts, they’ve:

  • Reduced clutter in their repositories.
  • Improved collaboration by maintaining a cleaner workspace.
  • Enhanced overall code quality.

Conclusion

Automating Git branch cleanup is a smart move for any development team. By following best practices and using tools like the Python script above, you’ll keep your repository tidy and your workflow efficient.


More info

Ready to streamline your Git branches? Dive deeper into DevOps and SRE practices by visiting the DevOps Mind blog for more insights and exclusive resources.
https://devopsmind.com.br/en/git-en-us/git-branch-cleanup-automate/

Remember, a clean repository leads to happier developers! 🚀

Top comments (5)

Collapse
 
ozair0 profile image
Ozair

Is it worth it? I mean we faced an issue with a merge from a long time ago or 1 year ago and the leftover branches which were merged at that time helped us find the mistake we made and revert it.

Collapse
 
fernandomullerjr profile image
Fernando Muller Junior

In this post I bring a simpler and more practical approach, for everyday uses:
devopsmind.com.br/en/git-en-us/git...

Collapse
 
fernandomullerjr profile image
Fernando Muller Junior

Sometimes yes, depending on the flow and whether there is a need for add-ons, such as alerts/notifications via Slack or some extra action

Collapse
 
jagedn profile image
Jorge

nice post but little over engineering, why not a simple bash ?

Collapse
 
fernandomullerjr profile image
Fernando Muller Junior

In this post I bring a simpler and more practical approach, for everyday uses:
devopsmind.com.br/en/git-en-us/git...

In the dev.to post I tried to bring this option, because sometimes depending on the flow and whether there is a need for add-ons, such as alerts/notifications via Slack or some extra action, maybe Python fits better.