章節 ▾ 第二版

A1.7 附錄 A:其他環境中的 Git - Zsh 中的 Git

Zsh 中的 Git

Zsh 也自帶了一個用於 Git 的選項卡補全庫。要使用它,只需在你的 .zshrc 檔案中執行 autoload -Uz compinit && compinit。Zsh 的介面比 Bash 的要強大一些

$ git che<tab>
check-attr        -- display gitattributes information
check-ref-format  -- ensure that a reference name is well formed
checkout          -- checkout branch or paths to working tree
checkout-index    -- copy files from index to working directory
cherry            -- find commits not merged upstream
cherry-pick       -- apply changes introduced by some existing commits

模稜兩可的選項卡補全不僅會被列出;它們還附有說明,你可以透過反覆按 Tab 鍵來圖形化地導航列表。這適用於 Git 命令、它們的引數以及儲存庫中事物的名稱(如 refs 和 remotes),以及 Zsh 知道如何選項卡補全的所有其他內容,例如檔名。

Zsh 自帶了一個用於從版本控制系統中獲取資訊的框架,稱為 vcs_info。要在右側的提示符中包含分支名稱,請將以下幾行新增到你的 ~/.zshrc 檔案中

autoload -Uz vcs_info
precmd_vcs_info() { vcs_info }
precmd_functions+=( precmd_vcs_info )
setopt prompt_subst
RPROMPT='${vcs_info_msg_0_}'
# PROMPT='${vcs_info_msg_0_}%# '
zstyle ':vcs_info:git:*' formats '%b'

這將在你的 shell 位於 Git 儲存庫中時,在終端視窗的右側顯示當前分支。左側當然也支援;只需取消註釋 PROMPT 的賦值。它看起來大致如下

Customized `zsh` prompt
圖 185. 自定義 zsh 提示符

有關 vcs_info 的更多資訊,請檢視 zshcontrib(1) 手冊頁中的文件,或線上訪問 https://zsh.sourceforge.io/Doc/Release/User-Contributions.html#Version-Control-Information

你可能更喜歡 Git 自帶的提示符自定義指令碼 git-prompt.sh,而不是 vcs_info;有關詳細資訊,請參閱 https://github.com/git/git/blob/master/contrib/completion/git-prompt.shgit-prompt.sh 與 Bash 和 Zsh 都相容。

Zsh 足夠強大,以至於有專門的框架來使其更好。其中一個稱為“oh-my-zsh”,它可以在 https://github.com/ohmyzsh/ohmyzsh 找到。oh-my-zsh 的外掛系統帶有強大的 Git 選項卡補全功能,並且它有各種各樣的提示符“主題”,其中許多都顯示版本控制資料。 oh-my-zsh 主題示例只是這個系統可以做什麼的一個例子。

An example of an oh-my-zsh theme
圖 186. oh-my-zsh 主題示例