-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocsync.py
More file actions
203 lines (163 loc) · 5.74 KB
/
docsync.py
File metadata and controls
203 lines (163 loc) · 5.74 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
import time
from dataclasses import dataclass
from difflib import unified_diff
from pathlib import Path
@dataclass(frozen=True)
class DocSyncDraft:
title: str
goal: str
edited_files: list[str]
suggested_ai_arch: dict[str, list[str]]
test_cmd: str | None = None
def build_docsync_draft(root, *, edited_files, goal, title=None, test_cmd=None):
root = Path(root)
edited = sorted({_norm_rel(p) for p in (edited_files or []) if _norm_rel(p)})
goal = (goal or "").strip()
if not goal:
goal = "Update project"
title = (title or "").strip()
if not title:
title = _infer_title(goal)
suggested = _suggest_ai_arch_updates(root, edited)
return DocSyncDraft(
title=title,
goal=goal,
edited_files=edited,
suggested_ai_arch=suggested,
test_cmd=(test_cmd or "").strip() or None,
)
def format_docsync_draft(draft: DocSyncDraft):
lines = []
lines.append("DocSync Draft:")
lines.append(f"- Title: {draft.title}")
lines.append(f"- Goal: {draft.goal}")
if draft.test_cmd:
lines.append(f"- Test: {draft.test_cmd}")
if draft.edited_files:
lines.append("- Edited files:")
for f in draft.edited_files:
lines.append(f" - {f}")
if draft.suggested_ai_arch:
lines.append("- Suggested AI_ARCH.md updates:")
for ai_arch, files in sorted(draft.suggested_ai_arch.items()):
lines.append(f" - {ai_arch}:")
for f in files:
lines.append(f" - mention {f}")
lines.append("")
lines.append("Next:")
lines.append("- Run: /docsync preview (preview AI_ARCH.md changes)")
lines.append("- Run: /docsync apply (apply AI_ARCH.md changes)")
lines.append("- Or: /docsync show (print this draft again)")
return "\n".join(lines).rstrip()
def preview_ai_arch_updates(root, draft: DocSyncDraft):
root = Path(root)
diffs = {}
for ai_arch_rel, files in sorted((draft.suggested_ai_arch or {}).items()):
path = root / ai_arch_rel
if not path.is_file():
continue
before = path.read_text(encoding="utf-8", errors="replace")
after = apply_ai_arch_update_text(before, draft, ai_arch_rel=ai_arch_rel, files=files)
if after != before:
diffs[ai_arch_rel] = "\n".join(
unified_diff(
before.splitlines(),
after.splitlines(),
fromfile=ai_arch_rel,
tofile=ai_arch_rel,
lineterm="",
)
).rstrip()
return diffs
def apply_ai_arch_updates(root, draft: DocSyncDraft):
root = Path(root)
changed = []
for ai_arch_rel, files in sorted((draft.suggested_ai_arch or {}).items()):
path = root / ai_arch_rel
if not path.is_file():
continue
before = path.read_text(encoding="utf-8", errors="replace")
after = apply_ai_arch_update_text(before, draft, ai_arch_rel=ai_arch_rel, files=files)
if after != before:
path.write_text(after, encoding="utf-8")
changed.append(ai_arch_rel)
return changed
def apply_ai_arch_update_text(text, draft: DocSyncDraft, *, ai_arch_rel, files):
files = sorted({_norm_rel(f) for f in (files or []) if _norm_rel(f)})
if not files:
return text
date = time.strftime("%Y-%m-%d")
header = "## DocSync"
existing = set()
for f in files:
if f in text:
existing.add(f)
to_add = [f for f in files if f not in existing]
if not to_add and draft.goal.strip() in text:
return text
lines = text.splitlines()
out = []
inserted = False
i = 0
while i < len(lines):
line = lines[i]
out.append(line)
if not inserted and line.strip() == header:
j = i + 1
while j < len(lines) and lines[j].strip() == "":
out.append(lines[j])
j += 1
out.append(f"- {date} — {draft.goal.strip()}")
for f in to_add:
out.append(f"- {f}")
out.append("")
inserted = True
i = j
continue
i += 1
if not inserted:
if out and out[-1].strip() != "":
out.append("")
out.append(header)
out.append(f"- {date} — {draft.goal.strip()}")
for f in to_add:
out.append(f"- {f}")
out.append("")
return "\n".join(out).rstrip() + "\n"
def _infer_title(goal):
first = goal.splitlines()[0].strip()
if len(first) > 80:
first = first[:77].rstrip() + "..."
return first or "feature"
def _norm_rel(p):
if not p:
return ""
p = str(p).strip().replace("\\", "/")
if not p or p.startswith("/"):
p = p.lstrip("/")
return p
def _suggest_ai_arch_updates(root: Path, edited_files: list[str]):
suggestions: dict[str, list[str]] = {}
for rel in edited_files:
if rel.endswith("AI_ARCH.md") or rel.endswith("PROJECT_OVERVIEW.md"):
continue
if rel.startswith("DAP/") or rel.startswith(".aider/") or rel.startswith(".git/"):
continue
p = root / rel
ai_arch = _find_nearest_ai_arch(root, p)
if not ai_arch:
continue
ai_arch_rel = ai_arch.relative_to(root).as_posix()
suggestions.setdefault(ai_arch_rel, []).append(rel)
for k in list(suggestions.keys()):
suggestions[k] = sorted(set(suggestions[k]))
return suggestions
def _find_nearest_ai_arch(root: Path, path: Path):
cur = path.parent
while True:
cand = cur / "AI_ARCH.md"
if cand.is_file():
return cand
if cur == root or cur.parent == cur:
return None
cur = cur.parent