vscode中使用powershell显示分支名

由于我的电脑打开git bash很慢很慢,在vscode中我想使用默认的powershell,但又想看到分支名称,于是倒腾了一下

vscode中使用powershell显示分支名_第1张图片
windows powershell(或windows terminal)启动前会先执行一个.ps1的配置文件,通过修改此文件可以对powershell做一些预设置。

  1. 打开powershell窗口,输入命令$Profile查看ps1文件位置。
$Profile
C:\Users\hnxyc\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

变量$Profile保存了ps1文件的绝对路径。

  1. ps1文件默认不存在,按路径手动创建文件即可。也可以敲下面的命令快速创建。
New-Item –Path $Profile –Type File –Force
  1. 编辑ps1文件
notepad $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 " ($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
}

$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding

$OutputEncoding是为了支持分支名为中文的情况。

你可能感兴趣的:(vscode,git)