Public/Branch/Remove-StaleBranches.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<#
.SYNOPSIS
    Short description
.DESCRIPTION
    Long description
.EXAMPLE
    Example of how to use this cmdlet
.EXAMPLE
    Another example of how to use this cmdlet
.INPUTS
    Inputs to this cmdlet (if any)
.OUTPUTS
    Output from this cmdlet (if any)
.NOTES
    General notes
.COMPONENT
    The component this cmdlet belongs to
.ROLE
    The role this cmdlet belongs to
.FUNCTIONALITY
    The functionality that best describes this cmdlet
#>

function Remove-StaleBranches {
    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
    [Alias()]
    [OutputType([String])]
    Param (
        # If set all found branches are going to be deleted
        [Parameter()]
        [switch]
        $Auto
    )
    
    begin {
    }
    
    end {
        ForEach-GitRepository -Callback {
            Invoke-ExpressionAndThrowIfFailed -command "git fetch --all --prune"

            $localBranchesWithoutRemoteBranch = @(  
                $matches = git branch -vv | Select-string -Pattern "\[origin/(?<branchName>.*):\sgone" -AllMatches  
                $matches.Matches.Groups | Where-Object { 
                    $_.GetType().ToString() -eq "System.Text.RegularExpressions.Group" -and $_.Name -eq "branchName" 
                } | Select-Object -ExpandProperty value
            )

            if ($localBranchesWithoutRemoteBranch.Count -gt 0) {
                Write-Host "[$($_.Name)] Found stale branches" -ForegroundColor Magenta
                $localBranchesWithoutRemoteBranch | ForEach-Object {

                    # Todo: Move to private menu function in case we need below code in another function
                    $yes = "y"
                    $allowedAnswers = $yes, "n"
                    $answer = $yes
                    if (!$Auto) {
                        do {
                            $answer = (Read-Host -Prompt "Shall delete $_ ? ($($allowedAnswers -join "/"))").ToLower()
                        } until ($allowedAnswers -contains $answer)
                    }

                    if ($answer -eq $yes) {
                        Write-Host "`t Deleting branch $_" -ForegroundColor Magenta
                        # Delete the found branch
                        Invoke-ExpressionAndThrowIfFailed -command "git branch -D $_"
                    }
                }
            }
        }
    }
}