章节 ▾ 第二版

A1.8 附录 A:其他环境中的 Git - Git in PowerShell

Git in PowerShell

Windows 上旧的命令行终端 (cmd.exe) 实际上并不支持定制化的 Git 体验,但如果你在使用 PowerShell,那你就走运了。在 Linux 或 macOS 上运行 PowerShell Core 同样适用。一个名为 posh-git (https://github.com/dahlbyk/posh-git) 的包提供了强大的 Tab 自动补全功能,以及增强的提示符,帮助你随时了解仓库状态。它看起来是这样的:

PowerShell with Posh-git
图 187. 带有 Posh-git 的 PowerShell

安装

先决条件 (仅限 Windows)

在你可以在机器上运行 PowerShell 脚本之前,需要将本地的 ExecutionPolicy 设置为 RemoteSigned (基本上,除了 UndefinedRestricted 之外都可以)。如果你选择 AllSigned 而不是 RemoteSigned,那么本地脚本 (你自己写的) 也需要进行数字签名才能执行。使用 RemoteSigned 时,只有 ZoneIdentifier 设置为 Internet (从网上下载的) 的脚本才需要签名,其他不需要。如果你是管理员,并希望为该机器上的所有用户设置,请使用 -Scope LocalMachine。如果你是普通用户,没有管理员权限,可以使用 -Scope CurrentUser 只为你自己设置。

更多关于 PowerShell 执行策略 (ExecutionPolicy) 的信息:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy

要为所有用户将 ExecutionPolicy 的值设置为 RemoteSigned,请使用以下命令:

> Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned -Force

如果你至少有 PowerShell 5,或者有安装了 PackageManagement 的 PowerShell 4,你就可以使用包管理器为你安装 posh-git。

关于 PowerShell Gallery 的更多信息:https://learn.microsoft.com/en-us/powershell/scripting/gallery/overview

> Install-Module posh-git -Scope CurrentUser -Force
> Install-Module posh-git -Scope CurrentUser -AllowPrerelease -Force # Newer beta version with PowerShell Core support

如果你想为所有用户安装 posh-git,请使用 -Scope AllUsers,并从提升的 PowerShell 控制台执行该命令。如果第二个命令失败并出现类似 Module 'PowerShellGet' was not installed by using Install-Module 的错误,你需要先运行另一个命令:

> Install-Module PowerShellGet -Force -SkipPublisherCheck

然后你就可以回去重试了。这发生的原因是 Windows PowerShell 自带的模块是用不同的发布者证书签名的。

更新 PowerShell 提示符

要在你的提示符中包含 Git 信息,需要导入 posh-git 模块。要让 posh-git 在每次 PowerShell 启动时都导入,请执行 Add-PoshGitToProfile 命令,它会将导入语句添加到你的 $profile 脚本中。这个脚本会在你每次打开新的 PowerShell 控制台时执行。请记住,有多个 $profile 脚本。例如,一个用于控制台,另一个用于 ISE。

> Import-Module posh-git
> Add-PoshGitToProfile -AllHosts

从源码安装

只需从 https://github.com/dahlbyk/posh-git/releases 下载 posh-git 的一个发布版本,然后解压缩。接着使用 posh-git.psd1 文件的完整路径导入模块:

> Import-Module <path-to-uncompress-folder>\src\posh-git.psd1
> Add-PoshGitToProfile -AllHosts

这将向你的 profile.ps1 文件添加正确的行,下次打开 PowerShell 时,posh-git 就会生效。

关于提示符中显示的 Git 状态摘要信息的说明,请参阅:https://github.com/dahlbyk/posh-git/blob/master/README.md#git-status-summary-information。关于如何自定义 posh-git 提示符的更多细节,请参阅:https://github.com/dahlbyk/posh-git/blob/master/README.md#customization-variables