Skip to content

Commit 1acb56d

Browse files
committed
Setup LLM-assisted IDE config
1 parent c50b078 commit 1acb56d

5 files changed

Lines changed: 343 additions & 0 deletions

File tree

.cursor/worktrees.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"setup-worktree": [
3+
"./scripts/setup_worktree.py \"$ROOT_WORKTREE_PATH\" -s '/node_modules' -s '.cursor/rules'"
4+
]
5+
}

.gitignore

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,17 @@ coverage-objects
1616
object-coverage-report.json
1717
docs
1818
docs-md
19+
20+
.claude/
21+
!.claude/skills
22+
!.claude/settings.json
23+
.rules/
24+
.clinerules/
25+
.cursor/rules/
26+
.windsurf/rules/
27+
.roo/rules*/
28+
.github/copilot-instructions.md
29+
AGENT.md
30+
AGENTS.override.md
31+
CLAUDE.local.md
32+
README.pochi.md

.opencode/worktree.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"sync": {
3+
"symlinkDirs": ["node_modules"]
4+
}
5+
}

.windsurf/hooks.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"hooks": {
3+
"post_setup_worktree": [
4+
{
5+
"command": "./scripts/setup_worktree.py \"$ROOT_WORKSPACE_PATH\" -s '/node_modules' -s '.windsurf/rules'",
6+
"show_output": true
7+
}
8+
]
9+
}
10+
}

scripts/setup_worktree.py

Lines changed: 309 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,309 @@
1+
#!/usr/bin/env -S uv run --no-config --script
2+
# /// script
3+
# dependencies = ["gitignore-parser"]
4+
# ///
5+
"""Set up a worktree by copying or symlinking files from a root workspace."""
6+
7+
from __future__ import annotations
8+
9+
import argparse
10+
import os
11+
import shutil
12+
import sys
13+
import tempfile
14+
from concurrent.futures import ThreadPoolExecutor, as_completed
15+
from pathlib import Path
16+
17+
from gitignore_parser import parse_gitignore
18+
19+
20+
def parse_args() -> argparse.Namespace:
21+
parser = argparse.ArgumentParser(
22+
description="Copy or symlink files from a root workspace into the current directory."
23+
)
24+
parser.add_argument("root_path", type=Path, help="Root workspace path")
25+
parser.add_argument(
26+
"-s",
27+
"--symlink",
28+
action="append",
29+
default=[],
30+
metavar="PATTERN",
31+
help="Glob pattern for files to symlink (repeatable)",
32+
)
33+
parser.add_argument(
34+
"-c",
35+
"--copy",
36+
action="append",
37+
default=[],
38+
metavar="PATTERN",
39+
help="Glob pattern for files to copy (repeatable)",
40+
)
41+
return parser.parse_args()
42+
43+
44+
def _canonicalize(p: Path) -> Path:
45+
"""Canonicalize a path by resolving each symlink component via readlink."""
46+
result = Path(p.anchor)
47+
for part in p.relative_to(p.anchor).parts:
48+
if part == "..":
49+
result = result.parent
50+
continue
51+
if part == ".":
52+
continue
53+
candidate = result / part
54+
seen: set[Path] = set()
55+
while candidate.is_symlink():
56+
if candidate in seen:
57+
raise OSError(f"symlink cycle detected at {candidate}")
58+
seen.add(candidate)
59+
link = Path(os.readlink(candidate))
60+
candidate = link if link.is_absolute() else candidate.parent / link
61+
result = candidate
62+
return result
63+
64+
65+
def _pattern_targets_dotgit(pattern: str) -> bool:
66+
stripped = pattern.lstrip("!").lstrip("/")
67+
return stripped == ".git" or stripped.startswith(".git/")
68+
69+
70+
def _is_relative_to(path: Path, parent: Path) -> bool:
71+
try:
72+
path.relative_to(parent)
73+
return True
74+
except ValueError:
75+
return False
76+
77+
78+
def _read_patterns(path: Path) -> list[str]:
79+
"""Read gitignore-format patterns from a file, returning raw pattern lines."""
80+
patterns = []
81+
for line in path.read_text().splitlines():
82+
stripped = line.strip()
83+
if stripped and not stripped.startswith("#"):
84+
patterns.append(stripped)
85+
return patterns
86+
87+
88+
def _build_matcher(patterns: list[str], root: Path):
89+
"""Build a gitignore-style matcher from a list of patterns."""
90+
if not patterns:
91+
return None
92+
with tempfile.NamedTemporaryFile(mode="w", suffix=".gitignore", delete=False) as f:
93+
for p in patterns:
94+
f.write(p + "\n")
95+
tmp_path = f.name
96+
try:
97+
return parse_gitignore(tmp_path, base_dir=str(root))
98+
finally:
99+
os.unlink(tmp_path)
100+
101+
102+
def _lowest_common_ancestor(a: Path, b: Path) -> Path:
103+
"""Return the deepest common ancestor directory of two absolute paths."""
104+
common: list[str] = []
105+
for pa, pb in zip(a.parts, b.parts):
106+
if pa == pb:
107+
common.append(pa)
108+
else:
109+
break
110+
return Path(*common) if common else Path("/")
111+
112+
113+
def _readjust_symlink_target(link_target: Path, root: Path, cwd: Path) -> Path:
114+
"""Decide whether a symlink target inside root should be readjusted for cwd.
115+
116+
Returns the (possibly adjusted) target path.
117+
"""
118+
if not _is_relative_to(cwd, root):
119+
return cwd / link_target.relative_to(root)
120+
lca = _lowest_common_ancestor(cwd, link_target)
121+
if lca == root:
122+
return cwd / link_target.relative_to(root)
123+
return link_target
124+
125+
126+
def _dst_exists(dst: Path) -> bool:
127+
"""Check if dst exists (includes broken symlinks)."""
128+
return dst.exists() or dst.is_symlink()
129+
130+
131+
def copy_entry(src: Path, dst: Path, root: Path, cwd: Path) -> None:
132+
"""Copy a file or directory from src to dst, handling symlink readjustment."""
133+
if src.is_symlink():
134+
if _dst_exists(dst):
135+
return
136+
137+
raw_target = Path(os.readlink(src))
138+
139+
if raw_target.is_absolute():
140+
link_target = _canonicalize(raw_target)
141+
if _is_relative_to(link_target, root):
142+
new_target = _readjust_symlink_target(link_target, root, cwd)
143+
else:
144+
new_target = link_target
145+
else:
146+
resolved = _canonicalize(src.parent / raw_target)
147+
if _is_relative_to(resolved, root):
148+
# Inside root: preserve the relative target unchanged
149+
new_target = raw_target
150+
else:
151+
# Outside root: convert to absolute
152+
new_target = resolved
153+
154+
dst.parent.mkdir(parents=True, exist_ok=True)
155+
os.symlink(new_target, dst)
156+
elif src.is_dir():
157+
if dst.exists() and (not dst.is_dir() or any(dst.iterdir())):
158+
return
159+
if dst.exists():
160+
shutil.rmtree(dst)
161+
shutil.copytree(src, dst, symlinks=True, copy_function=shutil.copy2)
162+
else:
163+
if dst.exists() and (not dst.is_file() or dst.stat().st_size > 0):
164+
return
165+
dst.parent.mkdir(parents=True, exist_ok=True)
166+
shutil.copy2(src, dst)
167+
168+
169+
def symlink_entry(src: Path, dst: Path) -> None:
170+
"""Create an absolute symlink at dst pointing to src."""
171+
if _dst_exists(dst):
172+
return
173+
dst.parent.mkdir(parents=True, exist_ok=True)
174+
os.symlink(_canonicalize(src), dst)
175+
176+
177+
def main() -> None:
178+
args = parse_args()
179+
root = _canonicalize(args.root_path.absolute())
180+
cwd = _canonicalize(Path.cwd())
181+
182+
if not root.is_dir():
183+
print(f"error: root path is not a directory: {root}", file=sys.stderr)
184+
sys.exit(1)
185+
186+
# Collect patterns: .worktreeinclude first, then CLI (CLI overrides)
187+
copy_patterns = []
188+
worktreeinclude = root / ".worktreeinclude"
189+
if worktreeinclude.is_file():
190+
copy_patterns.extend(_read_patterns(worktreeinclude))
191+
copy_patterns.extend(args.copy)
192+
symlink_patterns = list(args.symlink)
193+
194+
if not copy_patterns and not symlink_patterns:
195+
print(
196+
"error: no patterns specified (use -c, -s, or .worktreeinclude)",
197+
file=sys.stderr,
198+
)
199+
sys.exit(1)
200+
201+
# Build matchers
202+
copy_matcher = _build_matcher(copy_patterns, root)
203+
symlink_matcher = _build_matcher(symlink_patterns, root)
204+
copy_allows_dotgit = any(_pattern_targets_dotgit(p) for p in copy_patterns)
205+
symlink_allows_dotgit = any(_pattern_targets_dotgit(p) for p in symlink_patterns)
206+
any_allows_dotgit = copy_allows_dotgit or symlink_allows_dotgit
207+
208+
# Determine cwd exclusion: only if cwd is inside root
209+
cwd_exclude = cwd if _is_relative_to(cwd, root) else None
210+
211+
# Walk root and collect work items
212+
work: list[tuple[str, Path, Path]] = []
213+
seen_dsts: set[Path] = set()
214+
215+
for dirpath, dirnames, filenames in os.walk(root):
216+
dp = Path(dirpath)
217+
218+
# Skip root's .git unless any pattern allows it
219+
if dp == root and not any_allows_dotgit:
220+
try:
221+
dirnames.remove(".git")
222+
except ValueError:
223+
pass
224+
225+
# cwd exclusion
226+
if cwd_exclude is not None:
227+
canon = _canonicalize(dp)
228+
if canon == cwd_exclude or _is_relative_to(canon, cwd_exclude):
229+
dirnames.clear()
230+
continue
231+
232+
# Check subdirectories for whole-directory matches
233+
skip_dirs: set[str] = set()
234+
for dname in list(dirnames):
235+
src = dp / dname
236+
rel = src.relative_to(root)
237+
in_dotgit = bool(rel.parts) and rel.parts[0] == ".git"
238+
dst = cwd / rel
239+
240+
if dst in seen_dsts:
241+
skip_dirs.add(dname)
242+
continue
243+
244+
if copy_matcher and copy_matcher(str(src)):
245+
if not (in_dotgit and not copy_allows_dotgit):
246+
seen_dsts.add(dst)
247+
work.append(("copy", src, dst))
248+
skip_dirs.add(dname)
249+
continue
250+
251+
if symlink_matcher and symlink_matcher(str(src)):
252+
if not (in_dotgit and not symlink_allows_dotgit):
253+
seen_dsts.add(dst)
254+
work.append(("symlink", src, dst))
255+
skip_dirs.add(dname)
256+
257+
dirnames[:] = [d for d in dirnames if d not in skip_dirs]
258+
259+
# Check files (includes symlinks to files)
260+
for fname in filenames:
261+
src = dp / fname
262+
rel = src.relative_to(root)
263+
in_dotgit = bool(rel.parts) and rel.parts[0] == ".git"
264+
dst = cwd / rel
265+
266+
if dst in seen_dsts:
267+
continue
268+
269+
if copy_matcher and copy_matcher(str(src)):
270+
if not (in_dotgit and not copy_allows_dotgit):
271+
seen_dsts.add(dst)
272+
work.append(("copy", src, dst))
273+
continue
274+
275+
if symlink_matcher and symlink_matcher(str(src)):
276+
if not (in_dotgit and not symlink_allows_dotgit):
277+
seen_dsts.add(dst)
278+
work.append(("symlink", src, dst))
279+
280+
if not work:
281+
print("warning: no files matched any pattern", file=sys.stderr)
282+
return
283+
284+
errors: list[tuple[str, Path, Exception]] = []
285+
286+
with ThreadPoolExecutor() as executor:
287+
futures = {}
288+
for action, src, dst in work:
289+
if action == "copy":
290+
fut = executor.submit(copy_entry, src, dst, root, cwd)
291+
else:
292+
fut = executor.submit(symlink_entry, src, dst)
293+
futures[fut] = (action, src)
294+
295+
for fut in as_completed(futures):
296+
action, src = futures[fut]
297+
try:
298+
fut.result()
299+
except Exception as exc:
300+
errors.append((action, src, exc))
301+
302+
if errors:
303+
for action, src, exc in errors:
304+
print(f"error: {action} {src}: {exc}", file=sys.stderr)
305+
sys.exit(1)
306+
307+
308+
if __name__ == "__main__":
309+
main()

0 commit comments

Comments
 (0)