Skip to content

Instantly share code, notes, and snippets.

@tkirill
Created July 1, 2015 18:14
Show Gist options
  • Save tkirill/0f0f1902beb0c0723582 to your computer and use it in GitHub Desktop.
Save tkirill/0f0f1902beb0c0723582 to your computer and use it in GitHub Desktop.
Remove local git branches
# For http://stackoverflow.com/q/31026942/458723
# Removes local branches that not exist on any remote
function IsNot-CurrentLocalBranch($branch)
{
return $branch -notmatch "^\*"
}
function IsNot-MasterOrDevelop($branch)
{
return $branch -notmatch "master|develop"
}
function Get-LocalBranches
{
git branch `
| where {IsNot-CurrentLocalBranch $_ -and IsNot-MasterOrDevelop} `
| foreach {$_.Trim()} `
| where {$_} `
| foreach {write $_}
}
function IsNot-CurrentRemoteBranch($branch)
{
$branch -match "->"
}
function Remove-RemoteName($branch)
{
$pattern = "^.+?/(.+)$"
if ($branch -match $pattern) {
write $branch -replace $pattern, '$2'
}
}
function Get-RemoteBranches
{
git branch --remote `
| where {IsNot-CurrentRemoteBranch $_ -and IsNot-MasterOrDevelop} `
| Remove-RemoteName `
| where {$_} `
| foreach {$_.Trim()} `
| foreach {write $_}
}
function Remove-LocalBranch($branch)
{
Write-Host "Removing branch $branch"
git branch -D $branch
}
function Run-Main
{
$remoteBranches = Get-RemoteBranches
Get-LocalBranches `
| where {$_ -notin $remoteBranches} `
| foreach {Remove-LocalBranch $_}
}
Run-Main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment