Skip to content

Instantly share code, notes, and snippets.

@BoresXP
Created December 2, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoresXP/cfba7e51a1a429c1b48711ed58c07eaf to your computer and use it in GitHub Desktop.
Save BoresXP/cfba7e51a1a429c1b48711ed58c07eaf to your computer and use it in GitHub Desktop.
Script to clear git branches without upstream
<#
.SYNOPSIS
Used to clean branches in git repo.
.DESCRIPTION
Script to clean branches without upstream in git repo. Uses git commands to work with repo.
.PARAMETER dryRun
Prevent script from doing any real actions.
.PARAMETER force
Remove branches without upstream even if they are not merged. Use with care!
.PARAMETER noPruneOrigin
Do not prune origins before cleaning local branches.
.PARAMETER noFetch
Do not fetch all before cleaning local branches.
#>
param(
[switch]$dryRun,
[switch]$force,
[switch]$noPruneOrigin,
[switch]$noFetch
)
git status | Out-Null
if ($LASTEXITCODE -ne 0)
{
Write-Host -ForegroundColor Red "Failed to execute git command. Not a git repository?"
return 1
}
if (!$noFetch)
{
git fetch --all | Out-Null
}
$remotes = git remote
if ($remotes -is [array])
{
Write-Host -ForegroundColor Yellow "Found $($remotes.Length) remotes, expected 1. Exiting."
return 2
}
$originName = $remotes
if (-not $noPruneOrigin)
{
git remote prune $originName | Out-Null
}
$localBranches = git branch | %{ $_.Trim() } | %{ if ($_.StartsWith('* ')) { $_.Substring(2) } else { $_ } }
if ($localBranches.Length -eq 0)
{
Write-Host -ForegroundColor Yellow "No local branches found. Exiting. "
return 3
}
$remoteBranches = git branch -r | %{ $_.Trim() } | %{ if ($_.IndexOf('/') -gt 0) { $_.Substring($_.IndexOf('/') + 1) } else { $_ } }
$mergedBranches = git branch --merged dev | %{ $_.Trim() }
$orphaned = 0
$notMerged = 0
$removed = 0
foreach ($branch in $localBranches)
{
$remoteBranch = $remoteBranches | ?{ $_ -ieq $branch }
if (!$remoteBranch)
{
$mergedBranch = $mergedBranches | ?{ $_ -ieq $branch }
if (!$mergedBranch)
{
$notMerged++
}
if ($dryRun)
{
if ($mergedBranch)
{
Write-Host $branch
}
elseif (!$force)
{
Write-Host -NoNewline $branch
Write-Host -ForegroundColor Red ' Not merged!'
}
}
else
{
$isRemoved = $false
if ($force)
{
if ($mergedBranch)
{
git branch -d $branch | Out-Null
$isRemoved = $true
}
}
else
{
git branch -D $branch | Out-Null
$isRemoved = $true
}
if ($isRemoved)
{
Write-Host "Removed branch $($branch)"
$removed++
}
}
if (!$force -or $mergedBranch)
{
$orphaned++
}
}
}
if ($dryRun)
{
Write-Host -NoNewline "Orphaned branches total: $($orphaned)"
if (!$force)
{
Write-Host -NoNewline ", not merged: $($notMerged)"
}
Write-Host ''
}
else
{
Write-Host "Total branches removed: $($removed)"
}
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment