"""One-time: move visible external links and blocks out of lesson pages. Every external URL goes into the lesson's front matter `sources:` list (kept in source, never rendered). Inline external links keep their text and lose the link. Usage: python3 scripts/move-sources.py""" import pathlib import re LINK = re.compile(r"\[([^\]]+)\]\((https?://[^)\s]+)\)") RESOURCES = re.compile(r"\n?.*?\n?", re.S) HREF = re.compile(r'href="(https?://[^"]+)"') def split(text): _, fm, body = text.split("---\n", 2) return fm, body def drop_empty_sections(body): parts = re.split(r"(?m)^(?=## )", body) def empty(part): return part.startswith("## ") and not part.partition("\n")[2].strip() return "".join(p for p in parts if not empty(p)) for path in sorted(pathlib.Path("content/lessons").rglob("*.mdx")): fm, body = split(path.read_text()) urls = [] for block in RESOURCES.findall(body): urls += HREF.findall(block) body = RESOURCES.sub("\n", body) urls += [m.group(2) for m in LINK.finditer(body)] body = LINK.sub(r"\1", body) if not urls: continue body = drop_empty_sections(body) body = re.sub(r"\n{3,}", "\n\n", body).rstrip() + "\n" existing = re.findall(r"^ - (\S+)$", fm, re.M) fm = re.sub(r"^sources:\n( - .*\n)*", "", fm, flags=re.M) seen = list(dict.fromkeys(existing + urls)) fm = fm.rstrip("\n") + "\nsources:\n" + "".join(f" - {u}\n" for u in seen) path.write_text(f"---\n{fm}---\n{body}") print(f"{path}: {len(seen)} sources")