forked from tearne/cod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopt-in.py
More file actions
executable file
·295 lines (239 loc) · 9.97 KB
/
Copy pathopt-in.py
File metadata and controls
executable file
·295 lines (239 loc) · 9.97 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/usr/bin/env -S uv run --script --
# /// script
# requires-python = "==3.12.*"
# dependencies = ["rich"]
# ///
import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from rich.console import Console
VERSION = "1.3.0"
console = Console()
AGENT_DIR = Path(__file__).parent / "agent"
CHANGELOG_SRC = Path(__file__).parent / "CHANGELOG.md"
FRAMEWORK_FILES = ["README.md", "PROCESS.md", "STYLE.md", "MAP-GUIDANCE.md", "KEYWORDS.md"]
POINTER_PATTERN = re.compile(r"^@(agent/README\.md|changes/agents?/.*README\.md)\s*$")
VERSION_HEADING_PATTERN = re.compile(r"^##\s+(\d{4}-\d{2}-\d{2}(?:\.\d+)?)\s*$")
def git_root() -> Path:
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True, text=True,
)
if result.returncode != 0:
console.print("[bold red]Error:[/bold red] not inside a git repository.")
sys.exit(1)
return Path(result.stdout.strip())
def resolve_install_root(repo_root: Path) -> Path:
cwd = Path.cwd().resolve()
if cwd == repo_root.resolve():
return repo_root
confirm_subdir_install(repo_root, cwd)
return cwd
def confirm_subdir_install(repo_root: Path, cwd: Path) -> None:
console.print(
"You are inside a subdirectory of the repository, not its root:\n"
f" repo root: [bold]{repo_root}[/bold]\n"
f" this dir: [bold]{cwd}[/bold]\n"
)
answer = console.input(
"Set up the agent process here, in this subdirectory, rather than at the repo root? [y/N] "
)
if answer.strip().lower() not in ("y", "yes"):
console.print(
"[bold]Aborted.[/bold] Re-run from the repository root to install there."
)
sys.exit(0)
def main():
parser = argparse.ArgumentParser(
description="Opt a project in to the agent change process."
)
parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
parser.parse_args()
install_root = resolve_install_root(git_root())
console.print(f"Setting up agent process in [bold]{install_root}[/bold]\n")
if AGENT_DIR.resolve() == (install_root / "agent").resolve():
console.print(
"[bold red]Error:[/bold red] refusing to run — source and destination resolve to the same path.\n"
"This script is its own source of truth; running it here would install the agent files on top of themselves."
)
sys.exit(1)
version_name = read_latest_version_from_changelog()
version_dir = install_root / "changes/agent" / version_name
new_pointer = f"@changes/agent/{version_name}/README.md\n"
copy_framework_files(version_dir)
copy_asset(CHANGELOG_SRC, version_dir / "CHANGELOG.md")
remove_legacy_orphan_changelog(install_root)
pointer_outcome = rewrite_claude_md(install_root, new_pointer)
create_settings(
install_root / ".claude" / "settings.local.json",
excludes=["~/.claude/CLAUDE.md"],
)
create_dir(install_root / "changes/open")
create_dir(install_root / "changes/archive")
update_gitignore(install_root / ".gitignore")
warn_if_legacy_layout(install_root, pointer_outcome)
console.print(
f"\n[bold green]Done.[/bold green] Installed as [bold]{version_name}[/bold]."
)
console.print(
f"Release notes: [dim]{version_dir / 'CHANGELOG.md'}[/dim]"
)
def read_latest_version_from_changelog() -> str:
if not CHANGELOG_SRC.exists():
console.print(
"[bold red]Error:[/bold red] source CHANGELOG.md not found — cannot determine version."
)
sys.exit(1)
for line in CHANGELOG_SRC.read_text().splitlines():
match = VERSION_HEADING_PATTERN.match(line)
if match:
return match.group(1)
console.print(
"[bold red]Error:[/bold red] no `## YYYY-MM-DD[.N]` section found in CHANGELOG.md."
)
sys.exit(1)
def copy_framework_files(version_dir: Path) -> None:
for name in FRAMEWORK_FILES:
copy_asset(AGENT_DIR / name, version_dir / name)
additional_src = AGENT_DIR / "ADDITIONAL"
additional_dest = version_dir / "ADDITIONAL"
if additional_src.is_dir():
for f in sorted(additional_src.iterdir()):
if f.is_file():
copy_asset(f, additional_dest / f.name)
def remove_legacy_orphan_changelog(install_root: Path) -> None:
orphan = install_root / "changes/agent/CHANGELOG.md"
if orphan.exists() and orphan.is_file():
orphan.unlink()
report("removed", orphan, "legacy orphan — now lives inside each version dir")
def copy_asset(src: Path, dest: Path) -> None:
content = src.read_text()
if dest.exists():
if dest.read_text() == content:
report("already present", dest)
return
dest.write_text(content)
report("updated", dest)
return
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(content)
report("created", dest)
def create_file(path: Path, content: str) -> None:
if path.exists():
if path.read_text() == content:
report("already present", path)
else:
report("conflict", path, "exists with different content — left untouched")
return
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
report("created", path)
def create_settings(path: Path, excludes: list[str]) -> None:
desired = {"claudeMdExcludes": excludes}
if path.exists():
try:
existing = json.loads(path.read_text())
except json.JSONDecodeError:
report("conflict", path, "could not parse JSON — left untouched")
return
if "claudeMdExcludes" in existing:
if existing["claudeMdExcludes"] == excludes:
report("already present", path)
else:
report("conflict", path, "claudeMdExcludes already set to a different value — left untouched")
return
existing["claudeMdExcludes"] = excludes
path.write_text(json.dumps(existing, indent=2) + "\n")
report("updated", path)
return
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(desired, indent=2) + "\n")
report("created", path)
def create_dir(path: Path) -> None:
if path.exists():
report("already present", path)
return
path.mkdir(parents=True, exist_ok=True)
report("created", path)
def update_gitignore(path: Path) -> None:
entries = ["CLAUDE.md", "changes/agent/"]
content = path.read_text() if path.exists() else ""
lines = content.splitlines()
to_add = [e for e in entries if e not in lines]
if not to_add:
report("already present", path)
return
separator = "\n" if content and not content.endswith("\n") else ""
block = "\n".join(to_add)
with path.open("w") as f:
f.write(content + separator + block + "\n")
report("updated", path, f"added: {', '.join(to_add)}")
def rewrite_claude_md(install_root: Path, new_pointer: str) -> str:
path = install_root / "CLAUDE.md"
if not path.exists():
path.write_text(new_pointer)
report("created", path)
return "created"
existing = path.read_text()
if existing == new_pointer:
report("already present", path)
return "unchanged"
if not POINTER_PATTERN.match(existing.strip() + "\n"):
report("conflict", path, "exists with non-pointer content — left untouched")
return "refused_foreign"
if has_uncommitted_changes(install_root, path):
report("conflict", path, "pointer update needed but file has uncommitted changes — left untouched")
return "refused_modified"
path.write_text(new_pointer)
report("updated", path, f"pointer now {new_pointer.strip()}")
return "rewrote"
def has_uncommitted_changes(install_root: Path, path: Path) -> bool:
result = subprocess.run(
["git", "status", "--porcelain", "--", str(path.relative_to(install_root))],
cwd=install_root, capture_output=True, text=True,
)
status = result.stdout
if not status:
return False
return status[:2] != "??"
def warn_if_legacy_layout(install_root: Path, pointer_outcome: str) -> None:
legacy_agent_dir = install_root / "agent"
legacy_changes_agents = install_root / "changes/agents"
notes: list[str] = []
if legacy_agent_dir.is_dir() and legacy_agent_dir.resolve() != AGENT_DIR.resolve():
notes.append(" - delete the old folder: [dim]rm -rf agent[/dim]")
notes.append(" - remove any stale [dim]agent/[/dim] line from [dim].gitignore[/dim]")
if legacy_changes_agents.is_dir():
notes.append(" - delete the older folder: [dim]rm -rf changes/agents[/dim]")
notes.append(" - remove any stale [dim]changes/agents/[/dim] line from [dim].gitignore[/dim]")
if pointer_outcome == "refused_modified":
notes.append(
" - your [dim]CLAUDE.md[/dim] has uncommitted changes and was left untouched — "
"update its pointer manually once resolved"
)
if pointer_outcome == "refused_foreign":
notes.append(
" - your [dim]CLAUDE.md[/dim] contains unrecognised content and was left untouched — "
"update its pointer manually"
)
if not notes:
return
console.print(
"\n[bold yellow]Legacy layout detected.[/bold yellow] To finish migrating:\n"
+ "\n".join(notes)
)
def report(status: str, path: Path, note: str = "") -> None:
colours = {"created": "green", "updated": "cyan", "already present": "dim", "conflict": "yellow"}
colour = colours.get(status, "white")
label = f"[{colour}]{status:<15}[/{colour}]"
detail = f" [dim]{note}[/dim]" if note else ""
console.print(f" {label} {path}{detail}")
if __name__ == "__main__":
if not os.environ.get("VIRTUAL_ENV"):
print("Error: no virtual environment detected. Run this script via './opt-in' (requires uv), or activate a virtual environment first.")
sys.exit(100)
main()