Git フックと自動化: 自動品質ゲート
I Gitフック これらは、イベントに応じて Git が自動的に実行するスクリプトです (コミット、プッシュ、マージ)。これらを使用すると、検証、リンティング、テスト、検証を自動化できます。 作成する 高品質のゲート リポジトリに到達する前に問題を防止します リモート。 Husky や lint-staged などのツールを使用すると、フックのセットアップが簡単かつ効果的になります。
🎯 何を学ぶか
- Git フックとは何ですか、いつ実行されますか
- リンティングとフォーマットのための事前コミットフック
- 従来のコミット用の commit-msg フック
- フックを簡単に扱えるよう、ハスキーで糸くずのあるステージを施しています。
Git フックとは
Git フックは、次の場所に保存されるスクリプトです。 .git/hooks/ Git が自動的に行うこと
ワークフローの特定の瞬間に。任意の実行可能言語で記述できます
(bash、Python、Node.js など)。
📋 メインフック
- 事前コミット: コミットを作成する前(lint、テスト)
- 準備コミットメッセージ: コミットメッセージ(テンプレート)を用意する
- コミットメッセージ: コミットメッセージの検証(従来のコミット)
- コミット後: コミット作成後(通知)
- プリプッシュ: プッシュ前 (完全なテストスイート)
- リベース前: リベース前
コミット前フック: リンティングとフォーマット
Il 事前コミット フックが一番よく使われます。コミットする前にコードを確認してください。
#!/bin/bash
# Esegui ESLint su file staged
npm run lint
if [ $? -ne 0 ]; then
echo "❌ Linting failed. Fix errors before committing."
exit 1
fi
# Esegui test
npm test
if [ $? -ne 0 ]; then
echo "❌ Tests failed. Fix tests before committing."
exit 1
fi
echo "✅ All checks passed!"
exit 0
chmod +x .git/hooks/pre-commit
問題: 非共有フック
のフック .git/hooks/ 彼らはコミットされていない (「.git」は git 無視されます)。
各開発者はそれらを手動で構成する必要があります。解決: ハスキー.
Husky: フック管理の簡素化
ハスキー でフックを定義できます package.json そしてそれらを共有してください
Git 経由でチームと連携します。
# Installa Husky
npm install --save-dev husky
# Inizializza Husky
npx husky init
# Crea .husky/ directory con hooks condivisibili
# Crea pre-commit hook
npx husky add .husky/pre-commit "npm run lint && npm test"
# File creato: .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run lint && npm test
{{ '{' }}
"scripts": {{ '{' }}
"lint": "eslint . --ext .ts,.tsx",
"format": "prettier --write .",
"test": "jest",
"prepare": "husky install"
{{ '}' }},
"devDependencies": {{ '{' }}
"husky": "^8.0.0"
{{ '}' }}
{{ '}' }}
lint ステージング: lint ステージングされた変更されたファイルのみ
リントステージングされた ファイル全体ではなく、ステージングされたファイルに対してのみリンティング/フォーマットを実行します。 プロジェクト。はるかに速くなりました!
npm install --save-dev lint-staged
{{ '{' }}
"lint-staged": {{ '{' }}
"*.{{ '{' }}ts,tsx{{ '}' }}": [
"eslint --fix",
"prettier --write"
],
"*.{{ '{' }}js,jsx{{ '}' }}": [
"eslint --fix",
"prettier --write"
],
"*.css": [
"prettier --write"
]
{{ '}' }},
"scripts": {{ '{' }}
"prepare": "husky install"
{{ '}' }}
{{ '}' }}
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged
Commit-Msg フック: 従来のコミット
Forza 従来のコミット (feat:、fix:、docs: など) 自動変更ログ:
npm install --save-dev @commitlint/cli @commitlint/config-conventional
module.exports = {{ '{' }}
extends: ['@commitlint/config-conventional'],
rules: {{ '{' }}
'type-enum': [2, 'always', [
'feat', // Nuova feature
'fix', // Bug fix
'docs', // Documentazione
'style', // Formatting
'refactor', // Refactoring
'test', // Test
'chore' // Manutenzione
]]
{{ '}' }}
{{ '}' }};
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no-install commitlint --edit "$1"
# ✅ Valido
git commit -m "feat: add user authentication"
git commit -m "fix: resolve payment bug"
# ❌ Invalido (manca tipo)
git commit -m "add feature"
# ⧗ input: add feature
# ✖ subject may not be empty [subject-empty]
# ✖ type may not be empty [type-empty]
プリプッシュフック: 完全なテストスイート
プッシュする前に包括的なテストを実行して、CI 上のビルドの破損を防ぎます。
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# Esegui test suite completa
npm test
# Verifica build di produzione
npm run build
# Se uno fallisce, push viene bloccato
exit $?
完全な例: プロフェッショナルなセットアップ
Husky、lint ステージング、commitlint、およびプレプッシュ テストを使用してセットアップを完了します。
{{ '{' }}
"name": "my-project",
"scripts": {{ '{' }}
"lint": "eslint . --ext .ts,.tsx",
"format": "prettier --write .",
"test": "jest",
"test:ci": "jest --coverage",
"build": "tsc && vite build",
"prepare": "husky install"
{{ '}' }},
"lint-staged": {{ '{' }}
"*.{{ '{' }}ts,tsx{{ '}' }}": [
"eslint --fix",
"prettier --write",
"jest --bail --findRelatedTests"
],
"*.{{ '{' }}css,scss{{ '}' }}": [
"prettier --write"
]
{{ '}' }},
"devDependencies": {{ '{' }}
"husky": "^8.0.0",
"lint-staged": "^13.0.0",
"@commitlint/cli": "^17.0.0",
"@commitlint/config-conventional": "^17.0.0",
"eslint": "^8.0.0",
"prettier": "^2.8.0",
"jest": "^29.0.0"
{{ '}' }}
{{ '}' }}
my-project/
├── .husky/
│ ├── pre-commit # Lint-staged
│ ├── commit-msg # Commitlint
│ └── pre-push # Full tests + build
├── commitlint.config.js
├── .eslintrc.js
├── .prettierrc
├── package.json
└── src/
バイパスフック (注意)
場合によっては、フックをスキップする必要があります (WIP コミットなど)。
# Bypass tutti gli hooks
git commit --no-verify -m "WIP: incomplete feature"
git push --no-verify
# Abbreviazione
git commit -n -m "WIP"
# ⚠️ Usa solo quando assolutamente necessario!
CI/CDの統合
ローカルフックだけでは十分ではありません (バイパスできます)。 CI で同じチェックを再現します。
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
# Stesse verifiche dei hooks locali
- run: npm ci
- run: npm run lint
- run: npm run format -- --check
- run: npm run test:ci
- run: npm run build
# Verifica conventional commits
- uses: wagoid/commitlint-github-action@v5
ベストプラクティス
✅ やるべきこと
- アメリカ合衆国 ハスキー チームとフックを共有するため
- アメリカ合衆国 リントステージングされた 速度向上のため(ステージングされたファイルのみ)
- コミットをチェックする コミットリント
- フックを保持する 速い (10秒未満)
- CI/CD でテストを再生する
- README のドキュメント フックの設定
❌ してはいけないこと
- フックの作成が遅すぎないようにします (開発者をイライラさせます)
- フックのみに依存しないでください (フックはバイパスされる可能性があります)
- プリコミットでは完全なビルドを実行しないでください (プリプッシュを使用します)。
- 忘れないで
"prepare": "husky install"package.json内
高度なフック
#!/usr/bin/env sh
# .husky/prepare-commit-msg
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
# Se è un nuovo commit (non merge/amend)
if [ -z "$COMMIT_SOURCE" ]; then
# Aggiungi template con branch name
BRANCH_NAME=$(git symbolic-ref --short HEAD)
echo "[$BRANCH_NAME] " > "$COMMIT_MSG_FILE"
fi
#!/usr/bin/env sh
# .husky/post-commit
COMMIT_MSG=$(git log -1 --pretty=%B)
AUTHOR=$(git log -1 --pretty=%an)
# Invia notifica a Slack
curl -X POST https://hooks.slack.com/services/YOUR/WEBHOOK/URL \
-H 'Content-Type: application/json' \
-d "{{ '{' }}\"text\":\"New commit by $AUTHOR: $COMMIT_MSG\"{{ '}' }}"
トラブルシューティング
# Hook non eseguibile
chmod +x .husky/pre-commit
# Husky non installato
npm run prepare
# Hook eseguito due volte
# Rimuovi hook duplicati in .git/hooks/
# Lint-staged non trova file
# Verifica pattern in package.json
# Commitlint non funziona
# Controlla commitlint.config.js esista
結論
Git フックは品質ゲートを自動化し、壊れたコード、失敗したテスト、不正なコミットを防ぎます フォーマット済み。 ハスキー フックを簡単に共有できるようにする リントステージングされた 速くなり、 コミットリント 一貫したメッセージを保証します。 CI/CDと組み合わせると、 コードの品質を高く保つ堅牢なワークフローを作成します。
🎯 重要なポイント
- Git フックはコミット前チェックとプッシュ前チェックを自動化します
- Husky は Git 経由でフックを共有します (手動構成は不要)
- 変更されたファイルのみの lint ステージングされた lint
- commitlint は変更ログに対して従来のコミットを強制します
- 安全のために CI/CD でテストをプレイする







