Py Git Hooksのロゴ

Py Git Hooks

コミュニティ
l-mb
py-git-hooks

Set up git pre-commit hooks to run ruff, mypy, and basedpyright before commits. Use when configuring automated quality checks in git workflow.

Add to TypingMind

概要

公開者l-mb
リポジトリpython-refactoring-skills
スキル名py-git-hooks
スター
57
フォーク
1
同梱ファイル
1
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 1個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    l-mbがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Py Git Hooks」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-git-hooks
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/l-mb/python-refactoring-skills.git /tmp/python-refactoring-skills
mkdir -p .claude/skills
cp -r /tmp/python-refactoring-skills/skills/py-git-hooks .claude/skills/py-git-hooks
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでPy Git Hooksを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にPy Git Hooksを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Py Git Hooksは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Python Git Hooks Setup

Configure git pre-commit hooks using the pre-commit framework to enforce code quality before commits.

Objectives

  1. Install pre-commit framework with Python quality hooks
  2. Migrate any existing manual hooks to pre-commit framework
  3. Configure Claude Code Stop hook lint gate (runs full lint suite before returning to user)
  4. Ensure hooks run incrementally on changed files only
  5. Auto-fix issues where possible, block on critical errors

Required Tools

Add to [dependency-groups] dev: "pre-commit", "ruff", "mypy", "basedpyright"

  • pre-commit: Hook management framework (required)
  • ruff: Fast linter with auto-fix capability
  • mypy: Standard Python type checker
  • basedpyright: Enhanced type analysis

Permissions: Run py-quality-setup first to configure .claude/settings.local.json with all needed tool permissions.

Setup Workflow

Step 1: Check for Existing Hooks

bash
# Check if manual hooks exist
ls -la .git/hooks/pre-commit 2>/dev/null

# If exists and not a pre-commit managed hook, migrate it (see Migration section)

Step 2: Create Pre-commit Configuration

Create .pre-commit-config.yaml:

yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.8.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.13.0
    hooks:
      - id: mypy
        additional_dependencies: []  # Add type stubs as needed

  - repo: local
    hooks:
      - id: basedpyright
        name: basedpyright
        entry: basedpyright
        language: system
        types: [python]
        pass_filenames: true

Step 3: Install Hooks

bash
# Install pre-commit to project venv
uv pip install pre-commit

# Install git hooks
pre-commit install

# Verify installation
ls -la .git/hooks/pre-commit

Step 4: Test Hooks

bash
# Run on all files (initial validation)
pre-commit run --all-files

# Or test on staged files only
git add some_file.py
pre-commit run

Step 5: Configure Claude Code Stop Hook Lint Gate

Strongly recommended: Configure a Claude Code Stop hook that runs the full lint suite (ruff, mypy, basedpyright) on modified Python files before Claude returns control to the user. If any linter reports errors, Claude is blocked from stopping and must fix them first.

This replaces the older PostToolUse approach (which ran ruff after every individual edit, generating noise on intermediate states).

Install the lint gate script (symlink so updates propagate automatically):

bash
mkdir -p ~/.claude/hooks
ln -sf ~/.claude/skills/py-git-hooks/lint-gate.py ~/.claude/hooks/lint-gate.py

Configure the Stop hook in ~/.claude/settings.json:

json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/lint-gate.py"
          }
        ]
      }
    ]
  }
}

How it works:

  • Fires once when Claude finishes responding, before the user sees the result
  • Finds modified .py files via git diff (staged, unstaged, and untracked)
  • Auto-fix pass: runs ruff check --fix and ruff format to silently fix trivial issues (import sorting, whitespace, style)
  • Check pass: runs ruff check, mypy, and basedpyright to find remaining unfixable errors
  • If errors remain: returns {"decision": "block", "reason": "..."} — Claude sees the lint output and continues working to fix the issues
  • If clean (after auto-fix): returns {"decision": "stop"} — Claude returns to the user
  • Loop prevention: if stop_hook_active is true in the input (meaning Claude is already retrying after a previous block), the hook allows the stop to prevent infinite loops
  • Gracefully skips tools that aren't installed in the project

Benefits over PostToolUse hooks:

  • Runs once per turn instead of after every edit — no noise from intermediate states
  • Auto-fixes trivial issues so Claude only blocks on real errors
  • Runs the full suite (ruff + mypy + basedpyright), not just ruff
  • User always sees a clean codebase when Claude returns
  • Claude learns from the feedback and avoids repeating the same mistakes

Migration from Manual Hooks

If the project has an existing manual .git/hooks/pre-commit script:

Step 1: Backup Existing Hook

bash
cp .git/hooks/pre-commit .git/hooks/pre-commit.backup

Step 2: Analyze Existing Hook

Read the existing hook to understand what checks it runs:

  • Linting (ruff, flake8, pylint)?
  • Type checking (mypy, pyright)?
  • Formatting (black, isort)?
  • Custom checks?

Step 3: Map to Pre-commit Config

For each check in the manual hook, add equivalent to .pre-commit-config.yaml:

Manual Hook CheckPre-commit Equivalent
ruff checkruff-pre-commit repo
blackruff-format (ruff replaces black)
isortruff with isort rules (I)
flake8ruff (replaces flake8)
mypymirrors-mypy repo
basedpyrightlocal hook
Custom scriptlocal hook with entry: ./script.sh

Step 4: Install Pre-commit and Remove Manual Hook

bash
pre-commit install  # This overwrites .git/hooks/pre-commit
pre-commit run --all-files  # Verify all checks pass

Step 5: Verify and Clean Up

bash
# Test that hooks work
git add .
git commit -m "test" --dry-run

# If successful, remove backup
rm .git/hooks/pre-commit.backup

Hook Behavior

Auto-fixable issues (handled by both pre-commit and the Stop hook lint gate):

  • Import sorting
  • Trailing whitespace
  • Simple style violations
  • Many code quality issues

Blocking issues (require Claude or manual intervention):

  • Type errors (mypy/basedpyright)
  • Syntax errors
  • Complex linting violations that can't be auto-fixed

Bypass (use sparingly):

bash
git commit --no-verify

Performance Optimization

For large codebases:

  • Pre-commit runs on staged files only by default
  • Use mypy incremental mode (cache in .mypy_cache)
  • Consider running mypy/basedpyright in CI only for speed

For monorepos:

  • Use files: pattern in hook config to limit scope
  • Configure separate hooks per package
yaml
- id: mypy
  files: ^src/mypackage/

Troubleshooting

Hook not running:

bash
pre-commit install --force  # Reinstall hooks

Tools not found:

bash
# Ensure tools installed in venv
uv pip install ruff mypy basedpyright

Hook too slow:

  • Profile: pre-commit run --verbose
  • Consider removing mypy/basedpyright from pre-commit, run in CI instead
  • Use stages: [manual] for slow hooks, run explicitly

Update hook versions:

bash
pre-commit autoupdate

Migration from PostToolUse Hooks

If the project was previously set up with PostToolUse hooks for ruff (the older approach), migrate to the Stop hook lint gate:

Step 1: Check for Existing PostToolUse Hooks

bash
grep -A 10 '"PostToolUse"' ~/.claude/settings.json

Step 2: Remove PostToolUse Ruff Hooks

Edit ~/.claude/settings.json and remove any PostToolUse entries that match Edit|Write|MultiEdit and run ruff check. Keep any non-ruff PostToolUse hooks.

Step 3: Install Stop Hook

Follow Step 5 in the Setup Workflow above to install lint-gate.py and configure the Stop hook.

Step 4: Verify

Make a Python edit that introduces a ruff error. Confirm that:

  • No feedback appears after the edit itself (PostToolUse hook removed)
  • When Claude finishes responding, the Stop hook fires and blocks with the error
  • Claude fixes the error and returns clean output

Lint Learning

Claude should learn from lint gate feedback to avoid repeating the same mistakes.

After being blocked by the lint gate: note the error pattern. If the same linter rule triggers repeatedly across edits, record it in auto-memory under the lint-patterns topic. Format:

- **[rule-code]** (tool): What triggers it and how to avoid it.

Before editing Python files: consult auto-memory for known lint pitfalls in this project. Apply those lessons proactively so the lint gate passes on the first try.

This creates a cross-session feedback loop: each lint gate block teaches Claude to write cleaner code next time.

Verification Checklist

  • .pre-commit-config.yaml exists with ruff, mypy, basedpyright hooks
  • pre-commit install has been run
  • pre-commit run --all-files passes
  • Any existing manual hooks have been migrated
  • ~/.claude/hooks/lint-gate.py installed and executable
  • Claude Code Stop hook configured in ~/.claude/settings.json
  • Any old PostToolUse ruff hooks removed from settings
  • Bypass with --no-verify works for emergencies (git pre-commit only)

Examples

Example: New project setup

1. Create venv: uv venv && source .venv/bin/activate
2. Install tools: uv pip install pre-commit ruff mypy basedpyright
3. Create .pre-commit-config.yaml with ruff, mypy, basedpyright
4. Install hooks: pre-commit install
5. Test: pre-commit run --all-files
6. Install lint-gate.py and configure Stop hook in settings.json

Example: Migrate from PostToolUse to Stop hook

1. Remove PostToolUse ruff hooks from ~/.claude/settings.json
2. Symlink lint-gate.py to ~/.claude/hooks/
3. Add Stop hook to ~/.claude/settings.json
4. Verify: make an edit with a ruff error, confirm block-on-stop behavior

Example: Migrate existing manual hook

1. Backup: cp .git/hooks/pre-commit .git/hooks/pre-commit.backup
2. Read backup to identify checks (ruff, mypy, custom scripts)
3. Create .pre-commit-config.yaml mapping each check
4. Install: pre-commit install (overwrites manual hook)
5. Verify: pre-commit run --all-files
6. Clean up: rm .git/hooks/pre-commit.backup

Example: Add to existing pre-commit config

1. Edit .pre-commit-config.yaml
2. Add basedpyright local hook
3. Run: pre-commit run --all-files
4. Commit updated config

Related Skills

  • Prerequisites: py-quality-setup (tools must be configured before adding hooks)
  • Complements: py-security (add bandit to pre-commit for security scanning)
  • See also: All skills benefit from automated enforcement via hooks

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Py Git Hooks」では何ができますか?

Set up git pre-commit hooks to run ruff, mypy, and basedpyright before commits. Use when configuring automated quality checks in git workflow.

TypingMindでPy Git Hooksを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Py Git Hooksはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにPy Git Hooksをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/l-mb/python-refactoring-skills/tree/main/skills/py-git-hooksを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Py Git Hooksを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Py Git Hooksで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもPy Git Hooksを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Py Git Hooks」は無料ですか?

はい。l-mbがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇