git pre-commit hook:提交(commit)前自動觸發執行指令

在 git 儲存庫(repository)資料夾中會有 .git 隱藏資料夾,用來儲存 git 需要使用到的版本控制資訊紀錄。在這之中又有 hooks 資料夾,裡面儲存了一堆可以自動觸發和執行的腳本,其中就有今天要介紹的 pre-commit

預設會有 .git/hooks/pre-commit.sample 檔案,這個檔案是內建的範例腳本,想要讓它可以執行的話就把檔名改成 pre-commit 即可(移除 .sample 副檔名)

這裡有一個簡單的 pre-commit 檔案示範:
    
#!/bin/bash

# 檢查是否包含 Console.WriteLine
if git diff --cached | grep "Console.WriteLine"; then
  echo "❌ 禁止 commit:請移除 Console.WriteLine!"
  exit 1
fi

exit 0
    

在 git commit 前會自動執行 pre-commit 檔案,如果退出代號為 0 ,就會繼續 git commit,反之就會終止,無法 commit。

註1:在 windows 中安裝 git 時(Git for Windows),會一併安裝 Git Bash ,所以可以執行上述腳本
註2:在 Linux 中需要確認 .git/hooks/pre-commit 檔案是否可執行,可以使用 chmod +x .git/hooks/pre-commit 賦予檔案執行權限。

如果本次 git commit 需要忽略、不執行 pre-commit ,可以在 commit 時附加 --no-verify 參數。

範例 git commit 指令:
    
git commit -m "訊息" --no-verify
    



文章撰寫中...請稍後...

參考資料:
git - 8.3 Customizing Git - Git Hooks

留言