|
1 | | -"""Git hooks for recording AI prompts in commit messages.""" |
2 | | - |
3 | | -from __future__ import annotations |
4 | | - |
5 | | -import importlib.resources |
6 | | -import json |
7 | | -import subprocess |
8 | | -import sys |
9 | | -from pathlib import Path |
10 | | - |
11 | | - |
12 | | -PROMPTS_DIRECTORY = ".prompts" |
13 | | - |
14 | | - |
15 | | -def _repo_root() -> Path: |
16 | | - return Path( |
17 | | - subprocess.check_output( |
18 | | - ["git", "rev-parse", "--show-toplevel"], text=True |
19 | | - ).strip() |
20 | | - ) |
21 | | - |
22 | | - |
23 | | -def prepare_repository() -> int: |
24 | | - """Set up .prompts/, .gitignore, and .claude/settings.json in the target repo.""" |
25 | | - repo_root = _repo_root() |
26 | | - |
27 | | - # Initialize PROMPTS_DIRECTORY with a .gitignore that ignores everything |
28 | | - prompts_dir = repo_root / PROMPTS_DIRECTORY |
29 | | - prompts_dir.mkdir(parents=True, exist_ok=True) |
30 | | - prompts_gitignore = prompts_dir / ".gitignore" |
31 | | - existing_patterns = prompts_gitignore.read_text(encoding="utf-8").splitlines() if prompts_gitignore.exists() else [] |
32 | | - if "*" not in existing_patterns: |
33 | | - with prompts_gitignore.open("a", encoding="utf-8") as fh: |
34 | | - fh.write("*\n") |
35 | | - print(f"Initialized {prompts_gitignore}") |
36 | | - else: |
37 | | - print(f"{prompts_gitignore} already ignores *") |
38 | | - |
39 | | - # Install the UserPromptSubmit hook into .claude/settings.json |
40 | | - ref = importlib.resources.files("ai_prompt_auto_commit.data").joinpath("claude_settings.json") |
41 | | - bundled = json.loads(ref.read_text(encoding="utf-8")) |
42 | | - hook_def = bundled["hooks"]["UserPromptSubmit"][0]["hooks"][0] |
43 | | - hook_id = hook_def["id"] |
44 | | - |
45 | | - claude_dest = repo_root / ".claude" |
46 | | - dest_file = claude_dest / "settings.json" |
47 | | - |
48 | | - if dest_file.exists(): |
49 | | - settings = json.loads(dest_file.read_text(encoding="utf-8")) |
50 | | - else: |
51 | | - settings = {} |
52 | | - |
53 | | - # Walk existing UserPromptSubmit matchers to check if hook is already present |
54 | | - matchers = settings.setdefault("hooks", {}).setdefault("UserPromptSubmit", []) |
55 | | - already_installed = any( |
56 | | - h.get("id") == hook_id |
57 | | - for matcher in matchers |
58 | | - for h in matcher.get("hooks", []) |
59 | | - ) |
60 | | - |
61 | | - if already_installed: |
62 | | - print(f"Hook '{hook_id}' already present in {dest_file}") |
63 | | - else: |
64 | | - if matchers: |
65 | | - matchers[0].setdefault("hooks", []).append(hook_def) |
66 | | - else: |
67 | | - matchers.append({"hooks": [hook_def]}) |
68 | | - claude_dest.mkdir(parents=True, exist_ok=True) |
69 | | - dest_file.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8") |
70 | | - print(f"Inserted hook '{hook_id}' into {dest_file}") |
71 | | - |
72 | | - return 0 |
73 | | - |
74 | | - |
75 | | -def unstage() -> int: |
76 | | - """pre-commit: remove any .prompts/ files from the git index.""" |
77 | | - result = subprocess.run( |
78 | | - ["git", "diff", "--cached", "--name-only", "--", f"{PROMPTS_DIRECTORY}/"], |
79 | | - capture_output=True, |
80 | | - text=True, |
81 | | - ) |
82 | | - staged = result.stdout.strip() |
83 | | - if not staged: |
84 | | - return 0 |
85 | | - for filepath in staged.splitlines(): |
86 | | - subprocess.run(["git", "restore", "--staged", "--", filepath], check=True) |
87 | | - return 0 |
88 | | - |
89 | | - |
90 | | -def append_to_commit_msg(commit_msg_file: Path) -> int: |
91 | | - """prepare-commit-msg: append pending prompts to the commit message.""" |
92 | | - repo_root = _repo_root() |
93 | | - prompts_dir = repo_root / PROMPTS_DIRECTORY |
94 | | - |
95 | | - pending = sorted(prompts_dir.glob("*.md")) |
96 | | - if not pending: |
97 | | - return 0 |
98 | | - |
99 | | - lines: list[str] = ["\nAI Prompts:\n"] |
100 | | - for filepath in pending: |
101 | | - stem = filepath.stem |
102 | | - model = stem.split("_", 1)[1] if "_" in stem else stem |
103 | | - raw = filepath.read_text(encoding="utf-8") |
104 | | - # Join lines and strip trailing whitespace |
105 | | - content = " ".join(raw.splitlines()).rstrip() |
106 | | - # Remove absolute repo root from any paths embedded in the prompt |
107 | | - content = content.replace(str(repo_root) + "/", "./") |
108 | | - lines.append(f"{model}: {content}\n") |
109 | | - |
110 | | - with commit_msg_file.open("a", encoding="utf-8") as fh: |
111 | | - fh.writelines(lines) |
112 | | - return 0 |
113 | | - |
114 | | - |
115 | | -def archive() -> int: |
116 | | - """post-commit: move pending prompts to .prompts/committed/<name>_<hash>.md.""" |
117 | | - repo_root = _repo_root() |
118 | | - prompts_dir = repo_root / PROMPTS_DIRECTORY |
119 | | - committed_dir = prompts_dir / "committed" |
120 | | - |
121 | | - pending = sorted(prompts_dir.glob("*.md")) |
122 | | - if not pending: |
123 | | - return 0 |
124 | | - |
125 | | - commit_hash = subprocess.check_output( |
126 | | - ["git", "rev-parse", "HEAD"], text=True |
127 | | - ).strip() |
128 | | - committed_dir.mkdir(parents=True, exist_ok=True) |
129 | | - |
130 | | - for filepath in pending: |
131 | | - dest = committed_dir / f"{filepath.stem}_{commit_hash}.md" |
132 | | - filepath.rename(dest) |
133 | | - return 0 |
134 | | - |
135 | | - |
136 | | -def prepare_repository_main() -> None: |
137 | | - sys.exit(prepare_repository()) |
138 | | - |
139 | | - |
140 | | -def unstage_main() -> None: |
141 | | - sys.exit(unstage()) |
142 | | - |
143 | | - |
144 | | -def append_main() -> None: |
145 | | - if len(sys.argv) < 2: |
146 | | - print("Usage: append-ai-prompts <commit-msg-file>", file=sys.stderr) |
147 | | - exit(1) |
148 | | - sys.exit(append_to_commit_msg(Path(sys.argv[1]))) |
149 | | - |
150 | | - |
151 | | -def archive_main() -> None: |
152 | | - sys.exit(archive()) |
| 1 | +"""Re-exports for backwards compatibility and console-script entry points.""" |
| 2 | + |
| 3 | +from .append import append_to_commit_msg, main as append_main |
| 4 | +from .archive import archive, main as archive_main |
| 5 | +from .common import PROMPTS_DIRECTORY, _repo_root |
| 6 | +from .prepare_repository import main as prepare_repository_main |
| 7 | +from .prepare_repository import prepare_repository |
| 8 | +from .unstage import main as unstage_main |
| 9 | +from .unstage import unstage |
| 10 | + |
| 11 | +__all__ = [ |
| 12 | + "PROMPTS_DIRECTORY", |
| 13 | + "_repo_root", |
| 14 | + "prepare_repository", |
| 15 | + "prepare_repository_main", |
| 16 | + "unstage", |
| 17 | + "unstage_main", |
| 18 | + "append_to_commit_msg", |
| 19 | + "append_main", |
| 20 | + "archive", |
| 21 | + "archive_main", |
| 22 | +] |
0 commit comments