コンテンツにスキップ

Lefthookの設定

LefthookはGitフックを簡単に管理できるツールです。pre-commit、pre-push、commit-msgなどのGitフックをYAMLファイルで設定でき、チーム間で共有できます。

Terminal window
brew install lefthook
Terminal window
# プロジェクトルートで実行
lefthook install

これにより.git/hooksにLefthookのフックがインストールされます。

プロジェクトルートにlefthook.ymlを作成:

lefthook.yml
pre-commit:
parallel: true
commands:
eslint:
files: git diff --name-only --cached --diff-filter=AM
glob: "*.{js,jsx,ts,tsx}"
run: npx eslint {files}
prettier:
files: git diff --name-only --cached --diff-filter=AM
glob: "*.{js,jsx,ts,tsx,json,md}"
run: npx prettier --check {files}
pre-push:
commands:
test:
run: npm test
commit-msg:
commands:
commitlint:
run: npx commitlint --edit
pre-commit:
parallel: true
commands:
dart-format:
glob: "*.dart"
run: dart format --set-exit-if-changed {staged_files}
dart-analyze:
glob: "*.dart"
run: dart analyze
flutter-test:
run: flutter test
pre-commit:
parallel: true
commands:
lint:
glob: "*.{js,jsx,ts,tsx}"
run: npx eslint --fix {staged_files} && git add {staged_files}
type-check:
glob: "*.{ts,tsx}"
run: npx tsc --noEmit
prettier:
glob: "*.{js,jsx,ts,tsx,json,md,yml}"
run: npx prettier --write {staged_files} && git add {staged_files}
pre-push:
commands:
test:
run: npm test -- --coverage
build:
run: npm run build
pre-commit:
parallel: true
commands:
black:
glob: "*.py"
run: black --check {staged_files}
flake8:
glob: "*.py"
run: flake8 {staged_files}
mypy:
glob: "*.py"
run: mypy {staged_files}
pre-push:
commands:
pytest:
run: pytest
pre-commit:
commands:
lint:
skip:
- merge
- rebase
run: npm run lint
pre-commit:
commands:
migration-check:
only:
- ref: main
glob: "**/migrations/*.sql"
run: ./scripts/check-migrations.sh
pre-commit:
scripts:
"check-secrets.sh":
runner: bash
run: |
if git diff --cached --name-only | xargs grep -E "(password|secret|key)" ; then
echo "Potential secrets detected!"
exit 1
fi
Terminal window
# lefthook.ymlをリポジトリに追加
git add lefthook.yml
git commit -m "Add lefthook configuration"
# READMEに追加
echo "Run 'lefthook install' after cloning" >> README.md

各開発者が実行:

Terminal window
# リポジトリクローン後
lefthook install
# フックの無効化(一時的)
LEFTHOOK=0 git commit -m "Skip hooks"
# 特定のフックをスキップ
LEFTHOOK_EXCLUDE=test git push
Terminal window
# フックの再インストール
lefthook uninstall
lefthook install
# デバッグモードで実行
LEFTHOOK_VERBOSE=1 git commit
# 並列実行を有効化
pre-commit:
parallel: true
# ファイルのフィルタリング
commands:
lint:
files: git diff --name-only --cached
glob: "src/**/*.{js,ts}"
run: npx eslint {files}

.lefthook-local.ymlを作成(gitignoreに追加):

# 個人用の追加設定
pre-commit:
commands:
personal-check:
run: ./my-custom-check.sh
  1. 高速なチェックを優先

    • 時間のかかるテストはpre-pushに配置
    • pre-commitは軽量なチェックのみ
  2. 並列実行の活用

    • parallel: trueで実行時間を短縮
  3. 適切なスキップ条件

    • mergeやrebase時は不要なチェックをスキップ
  4. エラーメッセージの改善

    commands:
    check:
    run: ./check.sh || echo "❌ Check failed! Run 'npm run fix' to resolve"