Repository Public License Research preview
1#!/usr/bin/env python32"""Propagate course.yaml (single source of truth) to generated artifacts.34 latex/atlas-course.tex author / institution / language macros for every deck5 sessions/SXX-slug/metadata.yaml created for sessions that do not have one (status: planned)6 sessions/SXX-slug/README.md created for planned sessions only (never overwrites real work)78Run with --check to fail when a generated file is out of date (used by tests and CI).9"""10from __future__ import annotations1112import argparse13import sys1415import yaml1617from atlaslib import ROOT, load_course, load_yaml, session_dir1819GENERATED_NOTE = "% GENERATED from course.yaml by tools/sync_course.py — do not edit by hand.\n"202122def tex_escape(s: str) -> str:23 for a, b in (("\\", r"\textbackslash{}"), ("&", r"\&"), ("%", r"\%"), ("#", r"\#"), ("_", r"\_")):24 s = s.replace(a, b)25 return s262728def course_tex(course: dict) -> str:29 c, a = course["course"], course["author"]30 fields = {31 "AtlasCourseTitle": c["title"], "AtlasCourseShort": c["short_title"],32 "AtlasCourseTagline": c["tagline"], "AtlasCourseSubtitle": c["subtitle"],33 "AtlasCourseLanguage": c["language"], "AtlasCourseVersion": c["version"],34 "AtlasAuthorName": a["name"], "AtlasAuthorRole": a["role"],35 "AtlasAuthorInstitution": a["institution"], "AtlasAuthorInstitutionShort": a["institution_short"],36 "AtlasAuthorDepartment": a["department"], "AtlasAuthorTitleLine": a["title_line"],37 "AtlasAuthorInstitute": a["latex_institute"], "AtlasFooterAttribution": a["footer_attribution"],38 }39 lines = [GENERATED_NOTE]40 lines += [f"\\newcommand{{\\{k}}}{{{tex_escape(str(v))}}}\n" for k, v in fields.items()]41 return "".join(lines)424344def planned_metadata(course: dict, s: dict) -> dict:45 return {46 "id": s["id"], "slug": s["slug"], "title": s["title"], "part": s["part"],47 "level": s["level"], "language": course["course"]["language"],48 "author": course["author"]["name"], "affiliation": course["author"]["title_line"],49 "status": "planned", "outcomes": s["outcomes"], "tags": s["tags"],50 "dependencies": s["depends_on"],51 }525354def planned_readme(course: dict, s: dict) -> str:55 a = course["author"]56 part = next(p for p in course["parts"] if p["id"] == s["part"])57 deps = ", ".join(s["depends_on"]) or "aucun"58 outcomes = "\n".join(f"- {o}" for o in s["outcomes"])59 return f"""# {s['id']} — {s['title']}6061**{course['course']['short_title']}** · Partie {part['id']} — {part['title']} · Niveau : {s['level']}6263**Enseignant et auteur :** {a['name']} — {a['title_line']}, {a['department']}6465> **État : planifiée.** Cette séance n'est pas encore rédigée. Seuls ses objectifs et ses66> dépendances sont fixés ; aucun diaporama, laboratoire ni quiz n'existe pour l'instant.67> L'état réel de chaque séance figure dans `reports/STATUS.md`.6869## Résultats d'apprentissage visés7071{outcomes}7273## Préalables7475Séances préalables : {deps}.7677<!-- Fichier généré par tools/sync_course.py tant que la séance est « planned ». -->78"""798081def main() -> int:82 ap = argparse.ArgumentParser(description=__doc__)83 ap.add_argument("--check", action="store_true", help="verify only; exit 1 if out of date")84 args = ap.parse_args()85 course = load_course()86 stale: list[str] = []8788 def emit(path, content: str) -> None:89 current = path.read_text(encoding="utf-8") if path.exists() else None90 if current == content:91 return92 if args.check:93 stale.append(str(path.relative_to(ROOT)))94 else:95 path.parent.mkdir(parents=True, exist_ok=True)96 path.write_text(content, encoding="utf-8")97 print(f"wrote {path.relative_to(ROOT)}")9899 emit(ROOT / "latex" / "atlas-course.tex", course_tex(course))100 for s in course["sessions"]:101 d = session_dir(s)102 meta_path = d / "metadata.yaml"103 meta = load_yaml(meta_path) if meta_path.exists() else None104 if meta is None or meta.get("status", "planned") == "planned":105 emit(meta_path, yaml.safe_dump(planned_metadata(course, s), allow_unicode=True,106 sort_keys=False, width=100))107 emit(d / "README.md", planned_readme(course, s))108 if stale:109 print("Out of date (run `make sync`): " + ", ".join(stale), file=sys.stderr)110 return 1111 return 0112113114if __name__ == "__main__":115 sys.exit(main())116