-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_canon.py
More file actions
435 lines (357 loc) · 13.9 KB
/
Copy pathsync_canon.py
File metadata and controls
435 lines (357 loc) · 13.9 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
"""Derive the self-contained Python canon from the vault styleguide docs.
Reads the language-neutral core styleguide and the Python styleguide from the
Obsidian vault, strips vault-only Markdown (wikilinks, callouts, footnotes),
inlines the core rules each Python section links to, and writes one clean file
per section into the skill's references directory. Run with ``--check`` to test
whether the generated canon has fallen behind the source docs.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
# --- Configuration: edit these if the source files move. -------------------
VAULT_DIR = Path.home() / "org" / "Styleguide"
CORE_DOC = VAULT_DIR / "Styleguide.md"
PYTHON_DOC = VAULT_DIR / "Python Styleguide.md"
# Outputs are located relative to this script, so a rebuild updates whichever
# plugin copy runs it (the installed cache copy or the source dir).
PLUGIN_ROOT = Path(__file__).resolve().parent.parent
REFS_DIR = PLUGIN_ROOT / "skills" / "pythonic-canon" / "references"
MARKDOWN_BANNER = (
"<!-- GENERATED by src/sync_canon.py from the vault styleguide. "
"Do not edit by hand; edit the vault docs and rebuild. -->"
)
# The Audit Protocol is the shared review preamble. It is emitted once as
# audit-protocol.md; a subagent reads it before any section file rather than
# finding a full copy embedded in each. This names it in the source doc.
PREAMBLE_SECTION = "Audit Protocol"
# Sections that do not become standalone audit files. Foreword and Conventions
# fold into principles.md; the preamble is emitted on its own as
# audit-protocol.md; the rest carry no rules.
SKIP_SECTIONS = frozenset({
"Foreword",
"Conventions",
"Audit Protocol",
"Future Topics",
"References",
})
# Curated filename and one-line purpose per section. A section not listed here
# still gets a file, under a slugged name, so new sections never drop silently.
CURATED: dict[str, tuple[str, str]] = {
"Layout": ("layout.md", "Blank lines, line width, imports"),
"Naming": ("naming.md", "Casing, abbreviation, units, modifiers"),
"Type Annotations": ("typing.md", "Annotations, modern syntax, aliases"),
"Functions": ("functions.md", "Size, nesting, guards, arguments"),
"Control Flow": ("control-flow.md", "Truthiness, EAFP, loops, exceptions"),
"Documentation": ("documentation.md", "Docstrings and comments"),
"Strings & Logging": ("strings-logging.md", "f-strings, lazy logging"),
"Performance": ("performance.md", "Profiling, complexity, built-ins"),
"Security": ("security.md", "eval/exec, secrets, timezones, asserts"),
"Testing": ("testing.md", "pytest style and conventions"),
"Packaging": ("packaging.md", "uv, pyproject, dependencies"),
"Project Layout": ("project-layout.md", "src layout, packages, tests"),
}
SECTION_NOTE = (
"This section's rules and its Audit checklist. Read `audit-protocol.md` "
"first for the severity mapping and review scope. Generated; do not edit."
)
CALLOUT_RE = re.compile(r"^\[!(\w+)\]\s*(.*)$")
CORE_REF_RE = re.compile(r"\[\[Styleguide#([^\]|]+)\]\]")
def _emit(message: str) -> None:
"""Write a line to stdout for this command-line tool."""
sys.stdout.write(f"{message}\n")
def _headings(text: str) -> tuple[list[str], list[tuple[int, int, str]]]:
"""Split text into lines and locate headings outside code fences.
Args:
text: The Markdown document.
Returns:
The lines, and a list of (line_index, level, title) for each heading
that sits outside a fenced code block.
"""
lines = text.split("\n")
heads: list[tuple[int, int, str]] = []
in_fence = False
for index, line in enumerate(lines):
if line.lstrip().startswith("```"):
in_fence = not in_fence
continue
if in_fence:
continue
match = re.match(r"^(#{1,6}) (.+)$", line)
if match:
heads.append((index, len(match.group(1)), match.group(2).strip()))
return lines, heads
def _body_between(
lines: list[str],
heads: list[tuple[int, int, str]],
start_pos: int,
level: int,
) -> str:
"""Return a heading's body, up to the next same-or-higher heading.
Args:
lines: The document lines.
heads: All located headings as (line_index, level, title).
start_pos: Line index of the heading whose body is wanted.
level: Heading level of that heading.
Returns:
The body text between the heading and the next peer-or-higher one.
"""
end = len(lines)
for index, head_level, _title in heads:
if index > start_pos and head_level <= level:
end = index
break
return "\n".join(lines[start_pos + 1 : end]).strip("\n")
def top_sections(text: str) -> list[tuple[str, str]]:
"""Return (title, body) for every level-2 section in the document.
Args:
text: The Markdown document.
Returns:
Each level-2 section as a (title, body) pair, in document order.
"""
lines, heads = _headings(text)
sections: list[tuple[str, str]] = []
for index, level, title in heads:
if level == 2:
sections.append((title, _body_between(lines, heads, index, 2)))
return sections
def heading_index(text: str) -> dict[str, str]:
"""Map every heading title to its body, for cross-reference lookups.
Args:
text: The Markdown document.
Returns:
A title-to-body mapping covering all heading levels.
"""
lines, heads = _headings(text)
index: dict[str, str] = {}
for pos, level, title in heads:
index[title] = _body_between(lines, heads, pos, level)
return index
def _resolve_wikilink(match: re.Match[str]) -> str:
"""Reduce a wikilink to its most readable label.
Args:
match: A regex match whose first group is the wikilink target.
Returns:
The display text, fragment, or target, whichever is most specific.
"""
inner = match.group(1)
if "|" in inner:
inner = inner.split("|", 1)[1]
if "#" in inner:
inner = inner.split("#", 1)[1]
return inner.strip()
def _expand_leading_tabs(text: str) -> str:
"""Convert leading tabs to four spaces so example code reads correctly.
Args:
text: The text whose lines may start with tabs.
Returns:
The text with each leading tab replaced by four spaces.
"""
out: list[str] = []
for line in text.split("\n"):
body = line.lstrip("\t")
depth = len(line) - len(body)
out.append(" " * depth + body)
return "\n".join(out)
def clean(text: str) -> str:
"""Strip vault-only Markdown, leaving portable, self-contained prose.
Removes blockquote and callout markers, footnotes, and wikilink syntax, and
normalizes indentation. The ``@`` precedence markers and ``Ruff:`` footers
are plain text and survive untouched.
Args:
text: A section of the raw vault document.
Returns:
The cleaned section text.
"""
out: list[str] = []
for raw_line in text.split("\n"):
if re.match(r"^\[\^[^\]]+\]:", raw_line):
continue
line = (
re.sub(r"^>\s?", "", raw_line)
if raw_line.startswith(">")
else raw_line
)
callout = CALLOUT_RE.match(line)
if callout:
label = callout.group(2).strip() or callout.group(1).capitalize()
line = f"**{label}**"
out.append(line)
text = "\n".join(out)
text = re.sub(r"\[\^[^\]]+\]", "", text)
text = re.sub(r"\[\[([^\]]+)\]\]", _resolve_wikilink, text)
text = _expand_leading_tabs(text)
text = re.sub(r"([^\n])\n(#{1,6} )", r"\1\n\n\2", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip("\n")
def promote_headings(text: str) -> str:
"""Raise every heading one level so a section reads as a standalone file.
Args:
text: Markdown text containing level-2-or-deeper headings.
Returns:
The text with each heading promoted by one level.
"""
return re.sub(
r"^(#{2,6}) ",
lambda m: "#" * (len(m.group(1)) - 1) + " ",
text,
flags=re.MULTILINE,
)
def slug(title: str) -> str:
"""Convert a section title to a filename stem.
Args:
title: The section heading.
Returns:
A lowercase, dash-separated stem safe to use as a filename.
"""
stem = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
return stem or "section"
def render_section(title: str, raw_body: str, core: dict[str, str]) -> str:
"""Render one section file: its rules and Audit checklist.
The shared Audit Protocol is not embedded here; it lives once in
audit-protocol.md, which a subagent reads before any section file.
Args:
title: The section heading.
raw_body: The section body from the Python styleguide, uncleaned.
core: Heading-to-body index of the core styleguide.
Returns:
The full Markdown content for the section's reference file.
"""
parts = [
MARKDOWN_BANNER,
f"# {title}",
"",
SECTION_NOTE,
"",
"---",
"",
promote_headings(clean(raw_body)),
]
seen: set[str] = set()
for raw_ref in CORE_REF_RE.findall(raw_body):
ref = raw_ref.strip()
if ref in seen or ref not in core:
continue
seen.add(ref)
parts.extend([
f"\n## Core principle: {ref}\n",
promote_headings(clean(core[ref])),
])
return "\n".join(parts).strip("\n") + "\n"
def render_principles(core: dict[str, str], py: dict[str, str]) -> str:
"""Assemble the precedence model, conventions, and Zen into one file.
Args:
core: Level-2 section index of the core styleguide.
py: Level-2 section index of the Python styleguide.
Returns:
The Markdown content for the principles reference file.
"""
blocks = [
MARKDOWN_BANNER,
"# Principles",
"",
"## Precedence and the Zen",
"",
promote_headings(clean(py.get("Foreword", ""))),
"",
"## Python conventions",
"",
promote_headings(clean(py.get("Conventions", ""))),
"",
"## Core conventions (rule keywords)",
"",
promote_headings(clean(core.get("Conventions", ""))),
]
return "\n".join(blocks).strip("\n") + "\n"
def render_index(rows: list[tuple[str, str, str]]) -> str:
"""Build the router table that points to each section file.
Args:
rows: One (title, filename, purpose) tuple per section.
Returns:
The Markdown content for the index reference file.
"""
intro = (
"One file per section, each carrying that section's rules and its "
"Audit checklist. Read `audit-protocol.md` first for the severity "
"mapping and review scope; then read the section file(s) for the code "
"under review. Precedence, conventions, and the Zen live in "
"`principles.md`."
)
parts = [
MARKDOWN_BANNER,
"# Canon index",
"",
intro,
"",
"| Section | File | Covers |",
"| ------- | ---- | ------ |",
]
for title, filename, purpose in rows:
parts.append(f"| {title} | `{filename}` | {purpose} |")
return "\n".join(parts) + "\n"
def build() -> None:
"""Regenerate every reference file from the current vault docs."""
core_text = CORE_DOC.read_text(encoding="utf-8")
python_text = PYTHON_DOC.read_text(encoding="utf-8")
core = heading_index(core_text)
py_sections = dict(top_sections(python_text))
preamble = clean(py_sections.get(PREAMBLE_SECTION, ""))
REFS_DIR.mkdir(parents=True, exist_ok=True)
for stale in REFS_DIR.glob("*.md"):
stale.unlink()
rows: list[tuple[str, str, str]] = []
for title, raw in py_sections.items():
if title in SKIP_SECTIONS:
continue
filename, purpose = CURATED.get(title, (f"{slug(title)}.md", "—"))
if title not in CURATED:
_emit(f"notice: new section {title!r} -> {filename}")
(REFS_DIR / filename).write_text(
render_section(title, raw, core), encoding="utf-8"
)
rows.append((title, filename, purpose))
(REFS_DIR / "principles.md").write_text(
render_principles(core, py_sections), encoding="utf-8"
)
(REFS_DIR / "audit-protocol.md").write_text(
f"{MARKDOWN_BANNER}\n# Audit Protocol\n\n{preamble}\n",
encoding="utf-8",
)
(REFS_DIR / "index.md").write_text(render_index(rows), encoding="utf-8")
written = sorted(path.name for path in REFS_DIR.glob("*.md"))
_emit(f"wrote {len(written)} files to {REFS_DIR}:")
for name in written:
_emit(f" {name}")
def is_stale() -> bool:
"""Report whether either vault doc is newer than the generated canon.
Returns:
True if the canon is missing or older than a present source doc;
False when no source docs exist (the vault is absent, so the
committed canon cannot be rebuilt and is treated as current).
"""
generated = list(REFS_DIR.glob("*.md"))
if not generated:
return True
sources = [doc for doc in (CORE_DOC, PYTHON_DOC) if doc.exists()]
if not sources:
return False
newest_generated = max(item.stat().st_mtime for item in generated)
newest_source = max(item.stat().st_mtime for item in sources)
return newest_source > newest_generated
def main(argv: list[str]) -> int:
"""Run the build, or the staleness check under ``--check``.
Args:
argv: Command-line arguments without the program name.
Returns:
Process exit code: 0 on success or a fresh canon, 1 when stale.
"""
if "--check" in argv:
if is_stale():
_emit("canon is STALE: rebuild with `python sync_canon.py`")
return 1
_emit("canon is fresh")
return 0
build()
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))