How can I display my current git branch name in my PowerShell prompt?

前端 未结 7 2110
暗喜
暗喜 2020-11-30 20:18

Basically I\'m after this but for PowerShell instead of bash.

I use git on windows through PowerShell. If possible, I\'d like my current branch name to displayed as

7条回答
  •  情书的邮戳
    2020-11-30 21:00

    Here's my take on it. I've edited the colours a bit to make it more readable.

    Microsoft.PowerShell_profile.ps1

    function Write-BranchName () {
        try {
            $branch = git rev-parse --abbrev-ref HEAD
    
            if ($branch -eq "HEAD") {
                # we're probably in detached HEAD state, so print the SHA
                $branch = git rev-parse --short HEAD
                Write-Host " ($branch)" -ForegroundColor "red"
            }
            else {
                # we're on an actual branch, so print it
                Write-Host " ($branch)" -ForegroundColor "blue"
            }
        } catch {
            # we'll end up here if we're in a newly initiated git repo
            Write-Host " (no branches yet)" -ForegroundColor "yellow"
        }
    }
    
    function prompt {
        $base = "PS "
        $path = "$($executionContext.SessionState.Path.CurrentLocation)"
        $userPrompt = "$('>' * ($nestedPromptLevel + 1)) "
    
        Write-Host "`n$base" -NoNewline
    
        if (Test-Path .git) {
            Write-Host $path -NoNewline -ForegroundColor "green"
            Write-BranchName
        }
        else {
            # we're not in a repo so don't bother displaying branch name/sha
            Write-Host $path -ForegroundColor "green"
        }
    
        return $userPrompt
    }
    

    Example 1:

    Example 2:

提交回复
热议问题