Git.psm1

function Add-GitTag {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string] $Version
    )

    $tagName = "$Version"
    $sha = Start-NativeExecution git rev-parse HEAD
    $shortSha = $shortSha = $sha.Substring(0, 8)
    $commitMessage = "Added tag $tagName for changeset $shortSha"

    Log info $commitMessage
    Start-NativeExecution git tag -a $tagName -m $commitMessage
}

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 agt Add-GitTag
New-Alias cgb Clear-GitBranches
New-Alias gk Invoke-Gitk
New-Alias gka Invoke-GitkAll