-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsessionstart.py
More file actions
69 lines (54 loc) · 1.81 KB
/
Copy pathsessionstart.py
File metadata and controls
69 lines (54 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
"""SessionStart hook — inject current branch + working-tree state as session context.
Claude Code treats stdout as `additionalContext` on SessionStart, so this script
prints the current git branch and `git status --short` — giving the agent the
same orientation a human gets from opening the terminal. Runs once per session.
Silent and zero-exit on any failure: a missing git directory or a transient
command error must never block session startup.
"""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path
def project_dir() -> Path:
env = os.environ.get("CLAUDE_PROJECT_DIR")
if env:
return Path(env)
return Path(__file__).resolve().parent.parent.parent
def git_output(args: list[str], cwd: Path) -> str:
try:
return subprocess.check_output(
["git", *args],
cwd=cwd,
stderr=subprocess.DEVNULL,
text=True,
errors="replace",
timeout=5,
).strip()
except (
subprocess.CalledProcessError,
subprocess.TimeoutExpired,
FileNotFoundError,
):
return ""
def main() -> None:
base = project_dir()
branch = git_output(["branch", "--show-current"], base)
status = git_output(["status", "--short"], base)
if not branch and not status:
return
lines = ["# Repository context (injected by SessionStart hook)"]
if branch:
lines.append(f"- Current branch: `{branch}`")
if status:
lines.append("")
lines.append("Working tree (`git status --short`):")
lines.append("```")
lines.append(status)
lines.append("```")
else:
lines.append("- Working tree: clean")
sys.stdout.write("\n".join(lines) + "\n")
if __name__ == "__main__":
main()