章節 ▾ 第二版

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

Zsh 中的 Git

Zsh 也自帶一個用於 Git 的 Tab 補全庫。要使用它,只需在你的 .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 補全不僅僅是列出;它們有有用的描述,你可以透過重複按 Tab 鍵圖形化地導航列表。這適用於 Git 命令、它們的引數、倉庫內部事物的名稱(如 refs 和 remotes),以及檔名和所有其他 Zsh 知道如何 Tab 補全的內容。

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 Tab 補全功能,並擁有各種提示符“主題”,其中許多主題會顯示版本控制資料。oh-my-zsh 主題的一個示例只是使用此係統可以實現的一個例子。

An example of an oh-my-zsh theme
圖 186. oh-my-zsh 主題的一個示例
scroll-to-top