章節 ▾ 第二版

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