Rush Stack商店部落格活動
跳至主要內容

安裝 Git 鉤子

Git 版本控制系統允許您設定鉤子指令碼,這些指令碼會在執行特定動作時被調用。(如需完整文件,請參閱 Git 的「自訂 Git」章節。)基本概念是,您可以使用 pre-commitpost-updateprepare-commit-msg 等知名名稱建立 shell 指令碼。如果 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.dev.org.tw/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

您會按如下方式使用它

  1. 將此檔案加入您的 common/git-hooks 資料夾中,並提交至 Git。
  2. 當開發人員執行 rush install 時,Rush 會將此檔案複製到 .git/hooks/commit-msg
  3. 當您執行 git commit 時,Git 會找到該指令碼並調用它
  4. 如果提交訊息太短,指令碼會傳回非零結束代碼;Git 會顯示 Invalid commit message 通知並拒絕該操作。

使用 Rush 安裝鉤子指令碼可以避免需要單獨的解決方案,例如廣受歡迎的 Husky 套件。請注意,Husky 預期您的儲存庫具有根層級的 package.jsonnode_modules 資料夾,而且 Husky 會為每個 Git 操作執行 shell 指令(即使是未使用的鉤子);使用 Rush 安裝鉤子可以避免這些限制。

注意: 如果您因為某些原因需要解除安裝這些鉤子,可以安全地刪除您 .git/hooks/ 資料夾中的檔案。

在「git commit」期間調用 Prettier

Prettier 工具確保原始程式檔遵循一致的語法慣例,例如空格和逗號。透過設定 git commit 鉤子以自動調用 Prettier,您可以套用這些修正,而無需開發人員付出任何努力。

啟用 Prettier」文章提供了逐步說明。