Git.psm1

function Clear-GitBranches() {
    $branches = Start-NativeExecution git branch --merged
    try {
        $filteredBranches = $branches | Where-Object { $_ -notmatch '\* master' } | Where-Object { $_ -notmatch 'master' } | Where-Object { $_ -notmatch '\* *' } | ForEach-Object { $_.Trim() }
    } catch {
        $branches | Log error
        return
    }

    if (-not $filteredBranches) {
        Log info 'No merged branches detected'
        return
    }

    $filteredBranches | Log info

    $title = 'Delete merged branches'
    $message = 'Do you want to delete the already-merged local branches displayed above?'
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes', 'Delete the remote branches listed.'
    $no = New-Object System.Management.Automation.Host.ChoiceDescription '&No', 'Leave the branches alone.'
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

    $result = $Host.UI.PromptForChoice($title, $message, $options, 1)
    if ($result -eq 1) {
        return
    }

    $filteredBranches | ForEach-Object { Start-NativeExecution git branch -d "$_" | Log info }
}

function Invoke-GitkAll() {
    Invoke-Gitk -All @args
}

function Invoke-Gitk([switch] $All) {
    $command = 'gitk'
    [string[]] $arguments = @()

    if ($All) {
        $arguments += '--all'
    }

    $arguments += $args
    Start-NativeExecution $command @arguments
}

New-Alias cgb Clear-GitBranches
New-Alias gk Invoke-Gitk
New-Alias gka Invoke-GitkAll