章节 ▾ 第二版

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 主题示例