Branchwell

Become a Pro / website · becomeapro.ai / scripts / move-sources.py

Raw 1.5 KB on d27a4e234d2622fe12dfe92667dd00367e1dc2de
1"""One-time: move visible external links and <Resources> blocks out of lesson pages.
2Every external URL goes into the lesson's front matter `sources:` list (kept in source, never rendered).
3Inline external links keep their text and lose the link. Usage: python3 scripts/move-sources.py"""
4import pathlib
5import re
6
7LINK = re.compile(r"\[([^\]]+)\]\((https?://[^)\s]+)\)")
8RESOURCES = re.compile(r"\n?<Resources>.*?</Resources>\n?", re.S)
9HREF = re.compile(r'href="(https?://[^"]+)"')
10
11
12def split(text):
13 _, fm, body = text.split("---\n", 2)
14 return fm, body
15
16
17def drop_empty_sections(body):
18 parts = re.split(r"(?m)^(?=## )", body)
19 def empty(part):
20 return part.startswith("## ") and not part.partition("\n")[2].strip()
21 return "".join(p for p in parts if not empty(p))
22
23
24for path in sorted(pathlib.Path("content/lessons").rglob("*.mdx")):
25 fm, body = split(path.read_text())
26 urls = []
27 for block in RESOURCES.findall(body):
28 urls += HREF.findall(block)
29 body = RESOURCES.sub("\n", body)
30 urls += [m.group(2) for m in LINK.finditer(body)]
31 body = LINK.sub(r"\1", body)
32 if not urls:
33 continue
34 body = drop_empty_sections(body)
35 body = re.sub(r"\n{3,}", "\n\n", body).rstrip() + "\n"
36 existing = re.findall(r"^ - (\S+)$", fm, re.M)
37 fm = re.sub(r"^sources:\n( - .*\n)*", "", fm, flags=re.M)
38 seen = list(dict.fromkeys(existing + urls))
39 fm = fm.rstrip("\n") + "\nsources:\n" + "".join(f" - {u}\n" for u in seen)
40 path.write_text(f"---\n{fm}---\n{body}")
41 print(f"{path}: {len(seen)} sources")