Skip to content

Instantly share code, notes, and snippets.

@Antaris
Created February 27, 2024 22:13
Show Gist options
  • Save Antaris/7c8c191afcb19ffd1ade289b90c6ee9a to your computer and use it in GitHub Desktop.
Save Antaris/7c8c191afcb19ffd1ade289b90c6ee9a to your computer and use it in GitHub Desktop.
Cleaning up local GIT branches with PowerShell
function GitPruneBranches {
param(
[string[]] $Exclude,
[switch] $Unmerged,
[switch] $Commit
)
$pattern = '^\s*(?!(master|main|develop|\*).*$).*'
if ($Exclude -and $Exclude.Count -gt 0) {
$pattern = '^(?!(master|main|develop|\*|' + (($Exclude -Join '|') -Replace '\*', '.*') + ').*$).*'
}
if ($Unmerged) {
$branches = git branch
} else {
$branches = git branch --merged
}
$set = New-Object System.Collections.Generic.HashSet[string]
$branches | ForEach-Object {
$branch = $_.Trim()
if ($branch -match $pattern) {
$set.Add($branch) | Out-Null
}
}
if ($set.Count -gt 0) {
if (!$commit) {
$set | ForEach-Object { Write-Host "Will delete branch $_" }
Write-Host "Will delete $($set.Count) branch(es)"
} else {
$set | ForEach-Object {
git branch -D $_
}
Write-Host "Deleted $($set.Count) branch(es)"
}
} else {
Write-Host "No branches match the deletion pattern"
}
}
Set-Alias -Name prn -Value GitPruneBranches
@Antaris
Copy link
Author

Antaris commented Feb 27, 2024

I use this nifty little function periodically to clean up my local branches. It is safe-by-default, and doesn't perform any deletion unless you pass the -commit flag.

I also like shorthand commands, so in this case, prn (prune).

Examples:

prn
prn -exclude <pattern>
prn -commit

With the -unmerged flag, it will consider unmerged branches (most likely dangerous). It will also filter out the master, main, develop* branches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment