Powershell not showing git branch name in all directories

Viewed 183

This is my powershell profile:

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 " git:($branch)" -NoNewline -ForegroundColor "red"
        }
        else {
            # we're on an actual branch, so print it
            Write-Host " git:($branch)" -NoNewline -ForegroundColor "magenta"
        }
    } catch {
        # we'll end up here if we're in a newly initiated git repo
        Write-Host " (no branches yet)" -NoNewline -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 "cyan" 
        Write-BranchName
    }
    else {
        # we're not in a repo so don't bother displaying branch name/sha
        Write-Host $path -NoNewline -ForegroundColor "cyan"
    }

    return $userPrompt 
}

And this is my project directory:

|
|--API
|--Application
|--client-app
|--Domain
|--Infrastructure
|--Persistence
|--Reactivities.sln

Currently git branch is showed perfectly as RefreshTokens

PS Reactivities git:(RefreshTokens) >>

But when I change directory to API directory for example, git branch is NOT showed!?

PS Reactivities\API >>
1 Answers

Write-BranchName is called if (Test-Path .git). There is no .git in API apparently.

Try git rev-parse --show-toplevel to test if the current path is inside a git repository and get the repository's path.

I don't know about Powershell script, but I think you could call Write-BranchName without if..else.... If the current path is not inside a git repository, git rev-parse --abbrev-ref HEAD would raise an error or an exception.

Related