安装 Git 钩子
Git 版本控制系统允许您配置钩子脚本,这些脚本将在执行某些操作时被调用。(有关完整文档,请参阅 Git 的 自定义 Git 章。)基本思想是,您创建带有知名名称的 shell 脚本,例如 pre-commit、post-update、prepare-commit-msg 等等。如果 Git 客户端在本地 .git/hooks 文件夹中找到这些脚本,它将在执行相应操作时运行这些脚本。
出于安全原因,Git 在您克隆仓库时不会自动安装这些脚本。相反,每个开发者都必须调用一个命令来创建文件并将其设置为可执行文件。Rush 可以为您自动执行此操作!
配置 Rush 以安装 Git 钩子脚本
例如,假设我们发现开发人员在提交时没有提供有意义的工作描述。因此,Git 历史难以理解。为了解决这个问题,您可能希望添加一个 commit-msg
钩子,该钩子要求提交消息满足某些要求。例如,以下是一个简单的 Bash 脚本,它要求至少包含 3 个词的文本
common/git-hooks/commit-msg
#!/bin/sh
#
# This is an example Git hook for use with Rush. To enable this hook, rename this file
# to "commit-msg" and then run "rush install", which will copy it from common/git-hooks
# to the .git/hooks folder.
#
# TO LEARN MORE ABOUT GIT HOOKS
#
# The Git documentation is here: https://git-scm.cn/githooks
# Some helpful resources: https://githooks.com
#
# ABOUT THIS EXAMPLE
#
# The commit-msg hook is called by "git commit" with one argument, the name of the file
# that has the commit message. The hook should exit with non-zero status after issuing
# an appropriate message if it wants to stop the commit. The hook is allowed to edit
# the commit message file.
# This example enforces that commit message should contain a minimum amount of
# description text.
if [ `cat $1 | wc -w` -lt 3 ]; then
echo ""
echo "Invalid commit message: The message must contain at least 3 words."
exit 1
fi
上面显示的示例文件是 rush init
在设置新仓库时生成的模板。您可能可以在自己的仓库中找到一个副本,例如 common/git-hooks/commit-msg.sample。
您可以按如下方式使用它
- 将此文件添加到您的 common/git-hooks 文件夹中,并提交到 Git。
- 当开发者运行
rush install
时,Rush 会将此文件复制到 .git/hooks/commit-msg - 当您运行
git commit
时,Git 会找到该脚本并调用它 - 如果提交消息过短,该脚本将返回非零退出代码;Git 会显示
无效的提交消息
通知并拒绝该操作。
使用 Rush 安装钩子脚本可以避免使用单独的解决方案,例如流行的 Husky 包。请注意,Husky 要求您的仓库具有根级别的 package.json 和 node_modules 文件夹,并且 Husky 为每个 Git 操作(即使是未使用的钩子)运行 shell 命令;使用 Rush 安装钩子可以避免这些限制。
注意:如果您出于某种原因需要卸载钩子,可以安全地删除 .git/hooks/ 文件夹中的文件。
在“git commit”期间调用 Prettier
Prettier 工具确保源文件遵循一致的语法问题约定,例如空格和逗号。通过配置一个 git commit
钩子来自动调用 Prettier,您可以应用这些修复,而无需开发人员做任何努力。
启用 Prettier 文章提供了分步说明。