Functions/Remove-GitBranch.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
function Remove-GitBranch {
    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([LibGit2Sharp.Branch])]
    param(
        # Specifies which git repository to check. Defaults to the current directory.
        [string] $RepoRoot = (Get-Location).ProviderPath,

        # The name of the branch. Supports wildcards.
        [Parameter(Position = 0, ValueFromPipelineByPropertyName)]
        [Alias('CanonicalName')]
        [string] $Name
    )

    begin {
        Set-StrictMode -Version 'Latest'

        $repo = Find-GitRepository -Path $RepoRoot -Verify
        if (-not $repo) {
            return
        }
    }

    process {
        $branch = $repo.Branches[$Name]
        if ($null -eq $branch) {
            Write-Error "Branch '$Name' not found."
            return
        }

        $shouldProcessCaption = "Removing git branch"
        $shouldProcessDescription = "Removing the branch `e[1m$Name`e[0m in the repository $RepoRoot."
        $shouldProcessWarning = "Do you want to remove the branch `e[1m$Name`e[0m in the repository $($RepoRoot)?"
        if ($PSCmdlet.ShouldProcess($shouldProcessDescription, $shouldProcessWarning, $shouldProcessCaption)) {
            try {
                $repo.Branches.Remove($branch)
                Write-Information "Deleted branch `e[1m$Name`e[0m"
            } catch {
                Write-Error -ErrorRecord $_
            }
        }
    }
}