Created
February 27, 2024 22:13
-
-
Save Antaris/7c8c191afcb19ffd1ade289b90c6ee9a to your computer and use it in GitHub Desktop.
Cleaning up local GIT branches with PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
With the
-unmerged
flag, it will consider unmerged branches (most likely dangerous). It will also filter out themaster
,main
,develop*
branches.