Add tab completion for Git branches in Powershell

GitPowershellAutocomplete

Git Problem Overview


When inside a Git repository, is it possible to add tab completion for branches to Powershell? For example:

PS> git checkout maTAB

would result in

PS> git checkout master

Git Solutions


Solution 1 - Git

For that to be possible, a git provider for PowerShell would need to exist.

After a quick search, something similar apparently exists, the bizarre but aptly named posh-git:

http://github.com/dahlbyk/posh-git

> A set of PowerShell scripts which > provide Git/PowerShell integration > > - Prompt for Git repositories: The prompt within Git repositories can > show the current branch and the state > of files (additions, modifications,
> deletions) within. > - Tab completion: Provides tab completion for common commands when > using git. E.g. git ch<tab> --> > git checkout > > Usage > ----- > > See profile.example.ps1 as to how you > can integrate the tab completion > and/or git prompt into your own > profile. You can also choose whether > advanced git commands are shown in the > tab expansion or only simple/common > commands. Default is simple.

Solution 2 - Git

I wrote this little PS "gem", if posh-git is too much.
Just put it in your PowerShell profile to be able to type co  (with a space) and hit Tab to trigger completion and cycle through the list of branches:

function co
{
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [ArgumentCompleter({
            param($pCmd, $pParam, $pWord, $pAst, $pFakes)

            $branchList = (git branch --format='%(refname:short)')

            if ([string]::IsNullOrWhiteSpace($pWord)) {
                return $branchList;
            }

            $branchList | Select-String "$pWord"
        })]
        [string] $branch
    )

    git checkout $branch;
}

UPDATE: refactored to return a list of branches when tab-completion invoked after space and no partial string can be matched. Will return "master" if this is only one branch

As a bonus, did you know you can call TortoiseGit from shell?

function dif
{
    TortoiseGitProc.exe /command:repostatus
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGabe MoothartView Question on Stackoverflow
Solution 1 - GitfletcherView Answer on Stackoverflow
Solution 2 - GitYuriy GettyaView Answer on Stackoverflow