使用 posh-git 将远程名称添加到 PowerShell 提示符

Add remote name to PowerShell prompt with posh-git

我正在使用 posh-git 将 git 信息添加到我的 PowerShell 提示符中。我想让我的提示包含像 the examples 这样的远程存储库名称,但找不到这样做的方法。

下面是我的个人资料和我的自定义提示:

function prompt {
    $origLastExitCode = $LASTEXITCODE

    $curPath = $ExecutionContext.SessionState.Path.CurrentLocation.Path
    if ($curPath.ToLower().StartsWith($Home.ToLower())) {
        $curPath = "~" + $curPath.SubString($Home.Length)
    }

    Write-Host "$env:UserName" -NoNewline -ForegroundColor Cyan
    Write-Host "@" -NoNewline -ForegroundColor Yellow
    Write-Host "$(hostname)" -NoNewline
    Write-VcsStatus
    Write-Host "`n$curPath" -NoNewline

    $LASTEXITCODE = $origLastExitCode

    " $('>' * ($nestedPromptLevel + 1)) "
}

Import-Module posh-git

$global:GitPromptSettings.BeforeText = " ("
$global:GitPromptSettings.AfterText = ")"
$global:GitPromptSettings.EnableWindowTitle = "posh-git ~"
$global:GitPromptSettings.EnableStashStatus = $true
$global:GitPromptSettings.BeforeStashText = " {"
$global:GitPromptSettings.AfterStashText = "}"
$global:GitPromptSettings.BeforeStashForegroundColor = "Yellow"
$global:GitPromptSettings.AfterStashForegroundColor = "Yellow"
$global:GitPromptSettings.BranchUntrackedSymbol = "::"
$global:GitPromptSettings.BranchGoneStatusSymbol = "~~"
$global:GitPromptSettings.BranchIdenticalStatusToSymbol = "=="
$global:GitPromptSettings.BranchAheadStatusSymbol = "<<"
$global:GitPromptSettings.BranchBehindStatusSymbol = ">>"
$global:GitPromptSettings.BranchBehindAndAheadStatusSymbol = "><"

这是结果:

spike@Jacob-Laptop (master == +0 ~1 -0 !)
~\Documents\Projects\GUI Utilities\batch-media-file-converter >

这就是我想要的:

spike@Jacob-Laptop [spikespaz/batch-media-file-converter] (master == +0 ~1 -0 !)
~\Documents\Projects\GUI Utilities\batch-media-file-converter >

我用下面的代码得到它:

$remoteName = (git remote get-url origin).Split("/")

Write-Host $remoteName[-2] -NoNewline -ForegroundColor Cyan
Write-Host "/" -NoNewline -ForegroundColor Yellow
Write-Host $remoteName[-1] -NoNewline
Write-Host "]" -NoNewline -ForegroundColor Yellow

只有当前目录是git目录时才需要执行。使用 Test-Path ".git".

检查

命令git remote get-url origin returns 远程URL 例如https://github.com/spikespaz/batch-media-file-converter。这可以在 / 个字符处拆分,其中最后两个索引是 (user, repo).

我还通过使用正则表达式 (([^\/]*)\/([^\/]*)$) 提取用户和存储库名称使其工作,但我认为拆分速度更快。

我看到的唯一问题是从命令返回的 URL 结尾可能有 .git 或其他内容。它也可以是 SSH 地址。我不使用这两种类型的 git 地址,所以如果有人发现这有问题请告诉我。

$remoteName = [regex]::match((git remote get-url origin), "([^\/]*)\/([^\/]*)$").Groups

Write-Host $remoteName[1] -NoNewline -ForegroundColor Cyan
Write-Host "/" -NoNewline -ForegroundColor Yellow
Write-Host $remoteName[2] -NoNewline
Write-Host "]" -NoNewline -ForegroundColor Yellow

这是完整代码: 参见编辑。

function Prompt() {
    <...>
}

Import-Module posh-git

我仍然想知道示例中它是如何完成的,而且我相信不管怎样完成它都会更干净,所以我不会接受这个作为答案,而是将它留在这里作为解决方法。 编辑 2: 我现在接受这个作为答案,因为我曾期望其他人会回应,但没有人回应。这是迄今为止我找到的唯一解决方案。

编辑: 如果您喜欢这个配置文件配置,我已经做了一个要点,每当我更改它时我都会更新它。 https://git.io/vAqYP