章节 ▾ 第二版

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

除了 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 Tab 补全功能,并且它有各种提示符“主题”,其中许多都显示版本控制数据。oh-my-zsh 主题示例 只是这个系统可以实现的一个例子。

An example of an oh-my-zsh theme
图 186. oh-my-zsh 主题示例