|
| 1 | +# /// script |
| 2 | +# dependencies = [ |
| 3 | +# "requests", |
| 4 | +# ] |
| 5 | +# /// |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +default_version = "0.30" |
| 9 | +default_output_path = Path(__file__).parent / "commonmark.json" |
| 10 | +default_fixture_test_path = ( |
| 11 | + Path(__file__).parent.parent / "test_port" / "fixtures" / "commonmark_spec.md" |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +def create_argparser(): |
| 16 | + import argparse |
| 17 | + |
| 18 | + parser = argparse.ArgumentParser(description="Download CommonMark spec JSON") |
| 19 | + parser.add_argument( |
| 20 | + "version", |
| 21 | + nargs="?", |
| 22 | + default=default_version, |
| 23 | + help=f"CommonMark spec version to download (default: {default_version})", |
| 24 | + ) |
| 25 | + parser.add_argument( |
| 26 | + "--output", |
| 27 | + "-o", |
| 28 | + type=Path, |
| 29 | + default=default_output_path, |
| 30 | + help=f"Output file path (default: {default_output_path})", |
| 31 | + ) |
| 32 | + parser.add_argument( |
| 33 | + "--test-fixture", |
| 34 | + type=Path, |
| 35 | + default=default_fixture_test_path, |
| 36 | + help=f"Write to test fixture (default: {default_fixture_test_path})", |
| 37 | + ) |
| 38 | + return parser |
| 39 | + |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + import requests # type: ignore[import-untyped] |
| 43 | + |
| 44 | + args = create_argparser().parse_args() |
| 45 | + version: str = args.version |
| 46 | + output_path: Path = args.output |
| 47 | + write_to_test_fixture = True |
| 48 | + test_fixture: Path = args.test_fixture |
| 49 | + changed = False |
| 50 | + url = f"https://spec.commonmark.org/{version}/spec.json" |
| 51 | + print(f"Downloading CommonMark spec from {url}") |
| 52 | + response = requests.get(url) |
| 53 | + response.raise_for_status() |
| 54 | + if not output_path.exists() or output_path.read_text() != response.text: |
| 55 | + changed = True |
| 56 | + with output_path.open("w") as f: |
| 57 | + f.write(response.text) |
| 58 | + print(f"Updated to {output_path}") |
| 59 | + else: |
| 60 | + print(f"Spec file {output_path} is up to date, not overwriting") |
| 61 | + |
| 62 | + if write_to_test_fixture: |
| 63 | + data = response.json() |
| 64 | + text = "" |
| 65 | + for item in data: |
| 66 | + text += "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" |
| 67 | + text += f"src line: {item['start_line'] - 1}\n\n" |
| 68 | + text += f".\n{item['markdown']}.\n{item['html']}.\n\n" |
| 69 | + if not test_fixture.exists() or test_fixture.read_text() != text: |
| 70 | + changed = True |
| 71 | + with test_fixture.open("w") as f: |
| 72 | + f.write(text) |
| 73 | + print(f"Also updated to {test_fixture}") |
| 74 | + else: |
| 75 | + print(f"Fixture file {test_fixture} is up to date, not overwriting") |
| 76 | + |
| 77 | + raise SystemExit(0 if not changed else 1) |
0 commit comments