|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Pandoc filter to bundle images into output/images/ and rewrite paths to be relative. |
| 3 | +
|
| 4 | +For each image path (assumed to be under AOUSD_IMAGES_ROOT): |
| 5 | + 1. Compute the path relative to AOUSD_IMAGES_ROOT. |
| 6 | + 2. Remove any path components named "images". |
| 7 | + 3. Copy the image to AOUSD_OUTPUT_DIR/images/<relative>. |
| 8 | + 4. Rewrite the AST image path to images/<relative> (relative from output/ to output/images/). |
| 9 | +
|
| 10 | +Both absolute and relative image paths are processed. Relative paths are |
| 11 | +resolved against the images root directory (the pandoc input file's directory). |
| 12 | +
|
| 13 | +Required pandoc metadata: |
| 14 | + AOUSD_IMAGES_ROOT: absolute path to the images root directory |
| 15 | + AOUSD_OUTPUT_DIR: absolute path to the output directory |
| 16 | +
|
| 17 | +An in-process dict tracks which source files have been copied to each destination, |
| 18 | +detecting collisions where two different sources map to the same destination path. |
| 19 | +""" |
| 20 | + |
| 21 | +import shutil |
| 22 | +from pathlib import Path |
| 23 | + |
| 24 | +from pandocfilters import toJSONFilter, Image |
| 25 | + |
| 26 | +# Maps rel_key -> str(src_abs) for collision detection within a single pandoc run. |
| 27 | +_seen: dict[str, str] = {} |
| 28 | + |
| 29 | + |
| 30 | +def _get_metadata_str(metadata: dict, key: str) -> str: |
| 31 | + """Extract a string value from pandoc filter metadata. |
| 32 | +
|
| 33 | + Handles both MetaString (produced by -M on the command line) and |
| 34 | + MetaInlines (produced by --metadata-file YAML). |
| 35 | + """ |
| 36 | + try: |
| 37 | + entry = metadata[key] |
| 38 | + if entry.get("t") == "MetaString": |
| 39 | + return entry["c"] |
| 40 | + return entry["c"][0]["c"] |
| 41 | + except (KeyError, IndexError, TypeError) as e: |
| 42 | + raise KeyError(f"Missing or malformed metadata key {key!r}: {e}") from e |
| 43 | + |
| 44 | + |
| 45 | +def _get_image_rel(src_abs: Path, images_root: Path) -> Path: |
| 46 | + """Compute destination relative path under images/, stripping 'images' components.""" |
| 47 | + try: |
| 48 | + rel = src_abs.relative_to(images_root) |
| 49 | + except ValueError: |
| 50 | + raise ValueError( |
| 51 | + f"Image path {src_abs} is not under images_root {images_root}" |
| 52 | + ) |
| 53 | + parts = [p for p in rel.parts if p != "images"] |
| 54 | + if not parts: |
| 55 | + raise ValueError( |
| 56 | + f"Image {src_abs} reduces to an empty path after removing 'images' components" |
| 57 | + ) |
| 58 | + return Path(*parts) |
| 59 | + |
| 60 | + |
| 61 | +def bundle_image(key, value, _format, metadata): |
| 62 | + if key != "Image": |
| 63 | + return |
| 64 | + |
| 65 | + image_path = value[2][0] |
| 66 | + |
| 67 | + images_root = Path(_get_metadata_str(metadata, "AOUSD_IMAGES_ROOT")) |
| 68 | + output_dir = Path(_get_metadata_str(metadata, "AOUSD_OUTPUT_DIR")) |
| 69 | + |
| 70 | + src = Path(image_path) |
| 71 | + if not src.is_absolute(): |
| 72 | + # Relative paths are relative to the images root (pandoc input file location) |
| 73 | + src = images_root / src |
| 74 | + |
| 75 | + image_rel = _get_image_rel(src, images_root) |
| 76 | + |
| 77 | + dest = output_dir / "images" / image_rel |
| 78 | + rel_key = image_rel.as_posix() |
| 79 | + |
| 80 | + if rel_key in _seen: |
| 81 | + if _seen[rel_key] != str(src): |
| 82 | + raise RuntimeError( |
| 83 | + f"Image name collision at {rel_key!r}: already mapped from " |
| 84 | + f"{_seen[rel_key]!r}, cannot also map from {str(src)!r}" |
| 85 | + ) |
| 86 | + # Already copied earlier in this run; skip |
| 87 | + else: |
| 88 | + dest.parent.mkdir(parents=True, exist_ok=True) |
| 89 | + shutil.copy2(src, dest) |
| 90 | + _seen[rel_key] = str(src) |
| 91 | + |
| 92 | + # Relative from output/ (where the .md output file lives) to output/images/. |
| 93 | + new_path = (Path("images") / image_rel).as_posix() |
| 94 | + |
| 95 | + value[2][0] = new_path |
| 96 | + return Image(value[0], value[1], value[2]) |
| 97 | + |
| 98 | + |
| 99 | +if __name__ == "__main__": |
| 100 | + toJSONFilter(bundle_image) |
0 commit comments