章节 ▾ 第二版

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 命令、它们的参数、仓库内的名称(如引用和远程仓库),以及文件名和 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

除了 vcs_info,你可能更喜欢 Git 自带的提示符自定义脚本,即 git-prompt.sh;详情请参阅 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 主题示例