在PowerShell提示符中使用posh-git添加远程名称

3
我正在使用posh-git将git信息添加到我的PowerShell提示符中。我想让我的提示符包括远程仓库名称,就像这些示例那样,但是找不到方法来实现。
下面是我的自定义提示符配置文件:
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 >

This is what I want:

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

1
我用以下代码使其正常工作:

$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返回远程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: 我现在接受这个答案,因为我原本期望有其他人回应,但没有人回应。这是我到目前为止找到的唯一解决方案。 编辑: 如果您喜欢此配置文件,请查看我的gist,我会在更改时更新。 https://git.io/vAqYP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接