星期日, 10月 04, 2026

pre-commit

在使用 Claude 時,Claude 建議我使用這工具搭配 gitleaks,可以在提交代碼前檢查是否有機敏資料會被提交到 git repository。

Claude 都這麼建議了,就試試吧。

在 Ubuntu 24.04 ,gitleaks 跟 pre-commit 都已經可以使用 apt 安裝。

sudo apt install gitleaks pre-commit

接下來就是配置。

目前我是先在一個 repository 測試,所以要先撰寫 .pre-commit-config.yaml

# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v3.2.0
    hooks:
    -   id: trailing-whitespace
    -   id: end-of-file-fixer
    -   id: check-yaml
    -   id: check-added-large-files
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.24.2
    hooks:
      - id: gitleaks

在這裡,我使用 pre-commit 所提供的範例,剛好也是我常會用的

  • 檢查行末空白
  • 末行的EOF
  • yaml 格式
  • 避免加入過大的檔案

再來是 gitleaks 的部份,這邊我有點猶豫的是語法,不確定我已經用 apt 安裝 gitleaks 了,是否還要加上 repo。後來想,先加上去再說,錯了再處理就好。但結果看起來是可以使用。

在編寫完成以後,執行以下指令安裝

pre-commit install

然後就收工了。

pre-commit install 會把腳本寫到 .git/hooks/pre-commit ,讓 git commit 時,可以執行此腳本來檢查。


沒有留言: