Tuesday, January 14, 2025

Command to cleanup branches

Give me a git command such that when I run that it should do clean up in the branches.

Below are the few constraints while implementing that:

  1. should delete all the local branches which are deleted on the remote branch.
  2. if any merged pull requests, it should delete the branches both remote and local.
  3. The command you share should work on windows powershell.

Here's a Git command that addresses your requirements and should work in Windows PowerShell:




git fetch -p ; git branch -vv | Select-String -Pattern ": gone]" | ForEach-Object { $_.ToString().Trim().Split(" ")[0] } | ForEach-Object { git branch -D $_ } ; git for-each-ref --format '%(refname:short) %(upstream:track)' refs/heads | Where-Object { $_ -match '\[gone\]$' } | ForEach-Object { $_.Split(' ')[0] } | ForEach-Object { git push origin --delete $_ }

This command does the following:

  1. Deletes local branches that have been deleted on the remote:

    • git fetch -p updates the local repository with remote changes and prunes deleted remote branches.
    • git branch -vv | Select-String -Pattern ": gone]" finds local branches whose remote tracking branches are gone.
    • The branches are then deleted using git branch -D.
  2. Deletes both local and remote branches for merged pull requests:

    • git for-each-ref lists all local branches with their upstream tracking status.
    • Branches with [gone] status (indicating they've been merged and deleted on remote) are identified.
    • These branches are then deleted both locally (git branch -D) and remotely (git push origin --delete).
  3. This command is formatted to work in Windows PowerShell.

Please note:

  • This command will perform deletions without confirmation, so use it carefully.
  • Make sure you have the necessary permissions to delete remote branches.
  • It's always a good idea to backup your repository before running cleanup commands.
  • This command assumes that merged branches have been deleted on the remote. If your workflow keeps merged branches on the remote, you might need to adjust the command.

For safety, you might want to run parts of this command separately and review the output before proceeding with deletions.

No comments:

Post a Comment