Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ When Claude is ready to stop:
- Run the tests with `pytest` (only if files were edited)

Note: We defer all quality checks until Claude stops to avoid changing files while Claude is working. Changing files during editing would spoil Claude's edits and force it to reread files. Quality checks only run when at least one Python file has been edited during the session.

### Git worktrees

Claude Code (for example, the desktop app) may start a session in the main checkout and then do its work in a git worktree. The hooks are configured, and `CLAUDE_PROJECT_DIR` points, at the main checkout, but the quality checks run in the checkout that contains each edited file. Worktrees nested inside the main checkout (such as `.claude/worktrees/<name>`) are recognized by their own `.git` file. If the project lives in a subdirectory of its repository, the checks run in the same subdirectory of the worktree. Checkouts without edits from this session are not checked, so unrelated failures in the main checkout are not reported to the agent. Session tracking state and toggle settings stay in the main checkout's `.claude` directory.
## Installation

```bash
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "python-claude"
version = "0.5.0"
version = "0.5.1"
description = "Python hooks for Claude Code"
authors = [{name = "CVector", email = "support@cvector.com"}]
readme = "README.md"
Expand Down
62 changes: 62 additions & 0 deletions src/python_claude/hooks/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,37 @@ def from_stdin(cls) -> "HookInput":
return cls(session_id=session_id, tool_input=tool_input, raw=data)


def _git_root(path: Path) -> Path | None:
"""Find the nearest directory containing a .git entry (a directory in a main checkout, a file in a worktree)."""
for candidate in [path, *path.parents]:
if (candidate / ".git").exists():
return candidate
return None


def checkout_dir(path: Path, project_dir: Path) -> Path:
"""Find the directory that plays the role of project_dir in the checkout containing path.

Claude Code may edit files in a git worktree rather than in the checkout where the session started (CLAUDE_PROJECT_DIR). Quality checks must run in the worktree, at the same relative location as the project directory within its repository.
"""
root = _git_root(path)
if root is None:
return project_dir
project_root = _git_root(project_dir)
if project_root is not None:
candidate = root / project_dir.relative_to(project_root)
if path.is_relative_to(candidate):
return candidate
return root


def combine_exit_codes(exit_codes: list[int]) -> int:
"""Combine exit codes from several checkouts, preferring 2 so that Claude is asked to fix any failure it can act on."""
if 2 in exit_codes:
return 2
return next((code for code in exit_codes if code != 0), 0)


class Hook(ABC):
"""Base class for Claude Code hooks."""

Expand All @@ -59,6 +90,37 @@ def project_dir(self) -> Path:
self._project_dir = Path.cwd()
return self._project_dir

@property
def working_dir(self) -> Path:
"""Get the checkout containing the session's current working directory."""
cwd = self.input.raw.get("cwd")
if not cwd:
return self.project_dir
return checkout_dir(Path(cwd), self.project_dir)

def group_by_checkout(self, files: list[str]) -> dict[Path, list[str]]:
"""Group edited files by the checkout that contains them."""
groups: dict[Path, list[str]] = {}
for file_path in files:
checkout = checkout_dir(Path(file_path), self.project_dir)
groups.setdefault(checkout, []).append(file_path)
return groups

def read_tracked_files(self, track_file: Path) -> list[str]:
"""Read the files recorded in a tracking file."""
if not track_file.exists():
return []
return [
line.strip() for line in track_file.read_text().split("\n") if line.strip()
]

def retain_tracked_files(self, track_file: Path, files: list[str]) -> None:
"""Replace the contents of a tracking file, removing it when no files remain."""
if files:
track_file.write_text("".join(f"{file_path}\n" for file_path in files))
else:
track_file.unlink(missing_ok=True)

@property
def log_dir(self) -> Path:
"""Get the log directory for this session."""
Expand Down
2 changes: 1 addition & 1 deletion src/python_claude/hooks/git_status_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ def run(self) -> int:
print("# git status")
result = subprocess.run(
["git", "status"],
cwd=self.project_dir,
cwd=self.working_dir,
)
return result.returncode
59 changes: 36 additions & 23 deletions src/python_claude/hooks/mypy_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import sys
from pathlib import Path

from python_claude.hooks.base import Hook, HookInput
from python_claude.hooks.base import (
Hook,
HookInput,
checkout_dir,
combine_exit_codes,
)
from python_claude.hooks.state import QualityCheckState


Expand Down Expand Up @@ -35,37 +40,45 @@ def run(self) -> int:

file_path = self.input.file_path

# Determine what to type check
if file_path:
# File path provided - check if it's a Python file
if not self.is_python_file(file_path):
return 0
mypy_target = file_path
else:
# No file path (Stop hook) - check if any Python files were edited
if not self.track_file.exists() or self.track_file.stat().st_size == 0:
self.log("No edited Python files")
return 0
# Check entire project
mypy_target = "."
checkout = checkout_dir(Path(file_path), self.project_dir)
exit_code = self._run_mypy(file_path, checkout)
# Map mypy exit code 1 (type errors) to exit code 2 for Claude Code correction
return 2 if exit_code == 1 else exit_code

# No file path (Stop hook) - check if any Python files were edited
files = self.read_tracked_files(self.track_file)
if not files:
self.log("No edited Python files")
return 0

# Check the entire project in each checkout where files were edited
exit_codes: list[int] = []
remaining: list[str] = []
for checkout, checkout_files in self.group_by_checkout(files).items():
exit_code = self._run_mypy(".", checkout)
if exit_code == 1:
exit_code = 2
if exit_code != 0:
remaining.extend(checkout_files)
exit_codes.append(exit_code)

self.log(mypy_target)
self.retain_tracked_files(self.track_file, remaining)
return combine_exit_codes(exit_codes)

def _run_mypy(self, mypy_target: str, checkout: Path) -> int:
"""Run mypy on the target in the given checkout and return its exit code."""
self.log(f"{mypy_target} in {checkout}")

# mypy writes errors to stdout, but only stderr is fed back to Claude
result = subprocess.run(
["uv", "run", "mypy", mypy_target],
cwd=self.project_dir,
cwd=checkout,
stdout=sys.stderr, # Redirect stdout to stderr for Claude
)

exit_code = result.returncode
self.log(f"exit {exit_code}")

# Clean up tracking file on success (only for Stop hook)
if exit_code == 0 and not file_path:
self.track_file.unlink(missing_ok=True)

# Map mypy exit code 1 (type errors) to exit code 2 for Claude Code correction
if exit_code == 1:
return 2
return exit_code
self.log(f"exit {result.returncode}")
return result.returncode
42 changes: 24 additions & 18 deletions src/python_claude/hooks/pytest_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
from pathlib import Path

from python_claude.hooks.base import Hook, HookInput
from python_claude.hooks.base import Hook, HookInput, combine_exit_codes
from python_claude.hooks.state import QualityCheckState


Expand Down Expand Up @@ -32,27 +32,33 @@ def run(self) -> int:
self.log(f"{self.track_file}")

# Check if any Python files were edited
if not self.track_file.exists() or self.track_file.stat().st_size == 0:
files = self.read_tracked_files(self.track_file)
if not files:
self.log("No edited Python files")
return 0

self.log("Running pytest")
exit_codes: list[int] = []
remaining: list[str] = []
for checkout, checkout_files in self.group_by_checkout(files).items():
self.log(f"Running pytest in {checkout}")

result = subprocess.run(
["uv", "run", "pytest"],
cwd=self.project_dir,
stdout=sys.stderr,
)
result = subprocess.run(
["uv", "run", "pytest"],
cwd=checkout,
stdout=sys.stderr,
)

exit_code = result.returncode
# Transform pytest exit code 1 (test failures) to exit code 2
# for Claude Code to properly understand test failures
if exit_code == 1:
exit_code = 2
self.log(f"exit {exit_code}")
exit_code = result.returncode
# Transform pytest exit code 1 (test failures) to exit code 2
# for Claude Code to properly understand test failures
if exit_code == 1:
exit_code = 2
self.log(f"exit {exit_code}")

# Clean up tracking file on success
if exit_code == 0:
self.track_file.unlink(missing_ok=True)
# Keep tracking files of checkouts that still fail
if exit_code != 0:
remaining.extend(checkout_files)
exit_codes.append(exit_code)

return exit_code
self.retain_tracked_files(self.track_file, remaining)
return combine_exit_codes(exit_codes)
47 changes: 25 additions & 22 deletions src/python_claude/hooks/ruff_check_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
from pathlib import Path

from python_claude.hooks.base import Hook, HookInput
from python_claude.hooks.base import Hook, HookInput, combine_exit_codes
from python_claude.hooks.state import QualityCheckState


Expand All @@ -29,37 +29,40 @@ def run(self) -> int:
return 0

# Check if tracking file exists and has content
if not self.track_file.exists() or self.track_file.stat().st_size == 0:
tracked = self.read_tracked_files(self.track_file)
if not tracked:
self.log("No edited Python files to check")
return 0

files: list[str] = []
for line in self.track_file.read_text().strip().split("\n"):
file_path = line.strip()
if file_path and Path(file_path).exists():
files.append(file_path)

files = [file_path for file_path in tracked if Path(file_path).exists()]
if not files:
self.log("No existing Python files to check")
self.track_file.unlink(missing_ok=True)
return 0

self.log(f"Checking {len(files)} files: {' '.join(files)}")
exit_codes: list[int] = []
remaining: list[str] = []
for checkout, checkout_files in self.group_by_checkout(files).items():
self.log(
f"Checking {len(checkout_files)} files in {checkout}: {' '.join(checkout_files)}"
)

result = subprocess.run(
["uv", "run", "ruff", "check", "--fix", *files],
cwd=self.project_dir,
stdout=sys.stderr,
)
result = subprocess.run(
["uv", "run", "ruff", "check", "--fix", *checkout_files],
cwd=checkout,
stdout=sys.stderr,
)

exit_code = result.returncode
self.log(f"exit {exit_code}")
exit_code = result.returncode
self.log(f"exit {exit_code}")

if exit_code == 0:
self.track_file.unlink(missing_ok=True)
# ruff check exit code 1 indicates a lint error that was not automatically fixed; return status 2 to signal claude to consider fixing it
if exit_code == 1:
exit_code = 2

# ruff check exit code 1 indicates a lint error that was not automatically fixed; return status 2 to signal claude to consider fixing it
if exit_code == 1:
return 2
if exit_code != 0:
remaining.extend(checkout_files)
exit_codes.append(exit_code)

return exit_code
self.retain_tracked_files(self.track_file, remaining)
return combine_exit_codes(exit_codes)
41 changes: 22 additions & 19 deletions src/python_claude/hooks/ruff_format_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys
from pathlib import Path

from python_claude.hooks.base import Hook, HookInput
from python_claude.hooks.base import Hook, HookInput, combine_exit_codes
from python_claude.hooks.state import QualityCheckState


Expand All @@ -29,33 +29,36 @@ def run(self) -> int:
return 0

# Check if tracking file exists and has content
if not self.track_file.exists() or self.track_file.stat().st_size == 0:
tracked = self.read_tracked_files(self.track_file)
if not tracked:
self.log("No edited Python files to format")
return 0

files: list[str] = []
for line in self.track_file.read_text().strip().split("\n"):
file_path = line.strip()
if file_path and Path(file_path).exists():
files.append(file_path)

files = [file_path for file_path in tracked if Path(file_path).exists()]
if not files:
self.log("No existing Python files to format")
self.track_file.unlink(missing_ok=True)
return 0

self.log(f"Formatting {len(files)} files: {' '.join(files)}")
exit_codes: list[int] = []
remaining: list[str] = []
for checkout, checkout_files in self.group_by_checkout(files).items():
self.log(
f"Formatting {len(checkout_files)} files in {checkout}: {' '.join(checkout_files)}"
)

result = subprocess.run(
["uv", "run", "ruff", "format", *files],
cwd=self.project_dir,
stdout=sys.stderr,
)
result = subprocess.run(
["uv", "run", "ruff", "format", *checkout_files],
cwd=checkout,
stdout=sys.stderr,
)

exit_code = result.returncode
self.log(f"exit {exit_code}")
exit_code = result.returncode
self.log(f"exit {exit_code}")

if exit_code == 0:
self.track_file.unlink(missing_ok=True)
if exit_code != 0:
remaining.extend(checkout_files)
exit_codes.append(exit_code)

return exit_code
self.retain_tracked_files(self.track_file, remaining)
return combine_exit_codes(exit_codes)
Loading
Loading