Skip to content

Instantly share code, notes, and snippets.

@pizycki
Created September 6, 2019 16:56
Show Gist options
  • Select an option

  • Save pizycki/6ac319b35ff75ffc995fe1e74a51a70b to your computer and use it in GitHub Desktop.

Select an option

Save pizycki/6ac319b35ff75ffc995fe1e74a51a70b to your computer and use it in GitHub Desktop.
Get old branches
param (
[Parameter(Mandatory = $true)] $RepositoryPath,
[Parameter(Mandatory = $true)] $Days
)
function Get-BranchesInRepository([string]$path){
Push-Location
try {
Set-Location $path
$branches = git for-each-ref --sort='-committerdate:iso8601' --format='%(committerdate:iso8601)|%(refname:short)|%(committeremail)|%(committername)' refs/remotes/
}
finally {
Pop-Location
}
return $branches
}
function Get-MergedBranchesInRepository([string]$path) {
Push-Location
try {
Set-Location $path
$branches = git branch --remote --merged
}
finally {
Pop-Location
}
return $branches
}
function Parse-BranchRow([string]$row) {
$segments = $row.Split('|')
[pscustomobject]@{
Branch = $segments[1]
LastCommitDate = $segments[0]
AuthorEmail = $segments[2]
AuthorName = $segments[3]
}
}
function Was-NotUpdateFor($branch, [TimeSpan] $time){
[DateTime] $lastUpdate = [DateTime]::Parse($branch.LastCommitDate)
return $lastUpdate.Add($time).Ticks -lt [DateTime]::Now.Date.Ticks
}
function Is-NameRestricted($branch, [string[]]$restrictedNames) {
[string[]] $segments = $branch.Branch.Split("/")
foreach($seg in $segments){
foreach($rn in $restrictedNames){
if($seg -eq $rn){
return $true
}
}
}
}
### Main ###
$restricted = @("master", "develop", "release", "HEAD")
$time = [TimeSpan]::FromDays($Days)
$mergedBranches = Get-MergedBranchesInRepository $RepositoryPath
$staleBranches = `
Get-BranchesInRepository $RepositoryPath `
| %{ Parse-BranchRow $_ } `
| ?{ Was-NotUpdateFor $_ $time } `
| ?{ !(Is-NameRestricted $_ $restricted) }
Write-Host $staleBranches.Length
$staleBranches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment