|
| 1 | +""" |
| 2 | +Asset Scanner for the FastLED v1 Asset Pipeline (issue #2284). |
| 3 | +
|
| 4 | +Walks a sketch's ``data/`` directory looking for ``*.lnk`` files, parses each |
| 5 | +one for a URL plus optional ``key=value`` metadata lines, and emits a JSON |
| 6 | +manifest that fbuild consumers (notably the WASM loader) can read. |
| 7 | +
|
| 8 | +v1 scope: |
| 9 | + - Platforms: WASM + host/stub only. ESP32 LittleFS is future work. |
| 10 | + - Metadata keys parsed but NOT enforced: ``sha256=<hex>``, ``fallback=<url>``. |
| 11 | + The scanner records them so the shipping manifest is forward-compatible |
| 12 | + with future integrity/retry features; the runtime ignores them in v1. |
| 13 | + - ``.lnk`` file naming: ``<asset>.<ext>.lnk`` (e.g. ``track.mp3.lnk``). The |
| 14 | + scanner reports the relative path WITHOUT the trailing ``.lnk``, so |
| 15 | + sketches can write ``fl::asset("data/track.mp3")`` and get a hit. |
| 16 | +
|
| 17 | +Manifest shape:: |
| 18 | +
|
| 19 | + { |
| 20 | + "data/track.mp3": { |
| 21 | + "url": "https://example.com/track.mp3", |
| 22 | + "sha256": null, |
| 23 | + "fallback": null |
| 24 | + } |
| 25 | + } |
| 26 | +
|
| 27 | +The same dict can be emitted to a JSON file and/or serialized to a |
| 28 | +``window.fastledAssetManifest = {...}`` bootstrap snippet for HTML injection. |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import json |
| 34 | +from dataclasses import asdict, dataclass, field |
| 35 | +from pathlib import Path |
| 36 | + |
| 37 | + |
| 38 | +# ----------------------------------------------------------------------------- |
| 39 | +# Public types |
| 40 | +# ----------------------------------------------------------------------------- |
| 41 | + |
| 42 | + |
| 43 | +@dataclass |
| 44 | +class AssetEntry: |
| 45 | + """Resolved metadata for a single ``*.lnk`` file. |
| 46 | +
|
| 47 | + Attributes: |
| 48 | + url: Primary URL from the first non-comment line of the ``.lnk``. |
| 49 | + sha256: Optional hex digest declared in the ``.lnk`` (``sha256=...``). |
| 50 | + v1 runtime ignores this; parser captures it for forward-compat. |
| 51 | + fallback: Optional mirror URL declared in the ``.lnk`` (``fallback=...``). |
| 52 | + v1 runtime ignores this; parser captures it for forward-compat. |
| 53 | + """ |
| 54 | + |
| 55 | + url: str |
| 56 | + sha256: str | None = None |
| 57 | + fallback: str | None = None |
| 58 | + |
| 59 | + |
| 60 | +@dataclass |
| 61 | +class AssetScanResult: |
| 62 | + """Result of scanning a sketch's ``data/`` directory. |
| 63 | +
|
| 64 | + Attributes: |
| 65 | + manifest: Dict mapping relative asset paths (POSIX form, e.g. |
| 66 | + ``"data/track.mp3"``) to ``AssetEntry``. Missing ``data/`` or an |
| 67 | + empty one yields an empty dict — not an error. |
| 68 | + warnings: Non-fatal issues encountered during scanning (malformed |
| 69 | + ``.lnk`` files, unreadable files, etc.). Callers should log them |
| 70 | + but the build should NOT fail on these. |
| 71 | + """ |
| 72 | + |
| 73 | + manifest: dict[str, AssetEntry] = field(default_factory=dict) |
| 74 | + warnings: list[str] = field(default_factory=list) |
| 75 | + |
| 76 | + def to_json_dict(self) -> dict[str, dict[str, str | None]]: |
| 77 | + """Return manifest as a plain nested dict for JSON serialization.""" |
| 78 | + return {key: asdict(entry) for key, entry in self.manifest.items()} |
| 79 | + |
| 80 | + |
| 81 | +# ----------------------------------------------------------------------------- |
| 82 | +# Internals |
| 83 | +# ----------------------------------------------------------------------------- |
| 84 | + |
| 85 | + |
| 86 | +def _parse_lnk_content(content: str) -> AssetEntry | None: |
| 87 | + """Parse the text of a single ``.lnk`` file. |
| 88 | +
|
| 89 | + Mirrors the C++ ``fl::parse_lnk_with_metadata()`` logic in |
| 90 | + ``src/fl/stl/url.h``: |
| 91 | +
|
| 92 | + - Comment lines (``#...``) and blank lines are skipped. |
| 93 | + - First non-comment line is the primary URL. |
| 94 | + - Subsequent ``key=value`` lines are recorded as metadata. Recognized |
| 95 | + keys: ``sha256``, ``fallback``. Unknown keys are silently ignored. |
| 96 | +
|
| 97 | + Returns ``None`` if no URL was found. |
| 98 | + """ |
| 99 | + primary_url: str | None = None |
| 100 | + sha256: str | None = None |
| 101 | + fallback: str | None = None |
| 102 | + |
| 103 | + for raw_line in content.splitlines(): |
| 104 | + line = raw_line.strip() |
| 105 | + if not line or line.startswith("#"): |
| 106 | + continue |
| 107 | + |
| 108 | + if primary_url is None: |
| 109 | + primary_url = line |
| 110 | + continue |
| 111 | + |
| 112 | + if "=" not in line: |
| 113 | + # Unknown non-kv line — forward-compat, ignore. |
| 114 | + continue |
| 115 | + |
| 116 | + key, _, value = line.partition("=") |
| 117 | + key = key.strip() |
| 118 | + value = value.strip() |
| 119 | + if key == "sha256": |
| 120 | + sha256 = value |
| 121 | + elif key == "fallback": |
| 122 | + fallback = value |
| 123 | + # else: unknown metadata key, ignore. |
| 124 | + |
| 125 | + if primary_url is None: |
| 126 | + return None |
| 127 | + |
| 128 | + return AssetEntry(url=primary_url, sha256=sha256, fallback=fallback) |
| 129 | + |
| 130 | + |
| 131 | +# ----------------------------------------------------------------------------- |
| 132 | +# Public entry points |
| 133 | +# ----------------------------------------------------------------------------- |
| 134 | + |
| 135 | + |
| 136 | +def scan_sketch_assets(sketch_dir: Path) -> AssetScanResult: |
| 137 | + """Scan ``<sketch_dir>/data/`` for ``*.lnk`` asset links. |
| 138 | +
|
| 139 | + Only the ``data/`` subdirectory is walked. Files whose names do NOT end in |
| 140 | + ``.lnk`` are ignored — they ship as-is as normal assets and don't need a |
| 141 | + manifest entry. |
| 142 | +
|
| 143 | + Args: |
| 144 | + sketch_dir: Path to the sketch directory (the one containing the |
| 145 | + ``.ino`` / ``.cpp`` file). |
| 146 | +
|
| 147 | + Returns: |
| 148 | + :class:`AssetScanResult` with the manifest plus any warnings. |
| 149 | + """ |
| 150 | + result = AssetScanResult() |
| 151 | + data_dir = sketch_dir / "data" |
| 152 | + if not data_dir.is_dir(): |
| 153 | + return result |
| 154 | + |
| 155 | + for lnk_path in sorted(data_dir.rglob("*.lnk")): |
| 156 | + if not lnk_path.is_file(): |
| 157 | + continue |
| 158 | + |
| 159 | + # Relative asset path, with the ``.lnk`` suffix stripped so the key |
| 160 | + # matches the name the sketch will write (e.g. ``"data/track.mp3"``). |
| 161 | + rel_with_lnk = lnk_path.relative_to(sketch_dir).as_posix() |
| 162 | + if not rel_with_lnk.endswith(".lnk"): |
| 163 | + # Defensive — rglob should never hand us one of these, but be safe. |
| 164 | + continue |
| 165 | + rel_without_lnk = rel_with_lnk[: -len(".lnk")] |
| 166 | + |
| 167 | + try: |
| 168 | + content = lnk_path.read_text(encoding="utf-8") |
| 169 | + except UnicodeDecodeError as exc: |
| 170 | + result.warnings.append( |
| 171 | + f"asset-scan: {lnk_path}: not valid UTF-8 ({exc}); skipped" |
| 172 | + ) |
| 173 | + continue |
| 174 | + except OSError as exc: |
| 175 | + result.warnings.append( |
| 176 | + f"asset-scan: {lnk_path}: read failed ({exc}); skipped" |
| 177 | + ) |
| 178 | + continue |
| 179 | + |
| 180 | + entry = _parse_lnk_content(content) |
| 181 | + if entry is None: |
| 182 | + result.warnings.append( |
| 183 | + f"asset-scan: {lnk_path}: no URL found in .lnk; skipped" |
| 184 | + ) |
| 185 | + continue |
| 186 | + |
| 187 | + result.manifest[rel_without_lnk] = entry |
| 188 | + |
| 189 | + return result |
| 190 | + |
| 191 | + |
| 192 | +def write_manifest_json(scan: AssetScanResult, out_path: Path) -> None: |
| 193 | + """Serialize the manifest to JSON on disk. |
| 194 | +
|
| 195 | + The format matches what the WASM bootstrap expects for injection as |
| 196 | + ``window.fastledAssetManifest``. ``None`` fields are preserved so future |
| 197 | + JS consumers can detect absent metadata without extra contains-checks. |
| 198 | +
|
| 199 | + Args: |
| 200 | + scan: Result of :func:`scan_sketch_assets`. |
| 201 | + out_path: Destination ``.json`` file. Parent directories are created |
| 202 | + on demand. |
| 203 | + """ |
| 204 | + out_path.parent.mkdir(parents=True, exist_ok=True) |
| 205 | + with out_path.open("w", encoding="utf-8") as f: |
| 206 | + json.dump(scan.to_json_dict(), f, indent=2, sort_keys=True) |
| 207 | + f.write("\n") |
| 208 | + |
| 209 | + |
| 210 | +def manifest_to_js_bootstrap(scan: AssetScanResult) -> str: |
| 211 | + """Produce a ``window.fastledAssetManifest = {...}`` JS snippet. |
| 212 | +
|
| 213 | + Used by the WASM HTML template to inject the manifest before the FastLED |
| 214 | + runtime boots. Callers splice the returned string into a ``<script>`` tag. |
| 215 | + """ |
| 216 | + payload = json.dumps(scan.to_json_dict(), sort_keys=True) |
| 217 | + return f"window.fastledAssetManifest = {payload};\n" |
| 218 | + |
| 219 | + |
| 220 | +def manifest_to_cpp_header(scan: AssetScanResult) -> str: |
| 221 | + """Produce a C++ header that registers all manifest entries at startup. |
| 222 | +
|
| 223 | + Used by the WASM (and future host) C++ build to plug |
| 224 | + ``fl::register_asset(path, url)`` calls into the runtime so |
| 225 | + ``fl::resolve_asset()`` sees the entries without a JS round-trip. |
| 226 | +
|
| 227 | + Emits a self-contained translation unit ready to be compiled alongside |
| 228 | + the sketch. Relies on a function-local static + ``[[maybe_unused]]`` |
| 229 | + variable to force construction-order independence. |
| 230 | + """ |
| 231 | + lines: list[str] = [] |
| 232 | + lines.append("// AUTO-GENERATED by ci/compiler/asset_scanner.py — do not edit.") |
| 233 | + lines.append("// Registers the sketch's v1 asset manifest (issue #2284).") |
| 234 | + lines.append("#pragma once") |
| 235 | + lines.append("") |
| 236 | + lines.append('#include "fl/asset.h"') |
| 237 | + lines.append('#include "fl/stl/url.h"') |
| 238 | + lines.append("") |
| 239 | + lines.append("namespace {") |
| 240 | + lines.append("struct FastledAssetManifestRegistrar {") |
| 241 | + lines.append(" FastledAssetManifestRegistrar() {") |
| 242 | + for key in sorted(scan.manifest.keys()): |
| 243 | + entry = scan.manifest[key] |
| 244 | + path_lit = _cpp_string_literal(key) |
| 245 | + url_lit = _cpp_string_literal(entry.url) |
| 246 | + lines.append(f" ::fl::register_asset({path_lit}, ::fl::url({url_lit}));") |
| 247 | + lines.append(" }") |
| 248 | + lines.append("};") |
| 249 | + lines.append( |
| 250 | + "static FastledAssetManifestRegistrar s_fastled_asset_manifest_registrar;" |
| 251 | + ) |
| 252 | + lines.append("} // namespace") |
| 253 | + lines.append("") |
| 254 | + return "\n".join(lines) |
| 255 | + |
| 256 | + |
| 257 | +def _cpp_string_literal(s: str) -> str: |
| 258 | + """Escape ``s`` as a C++ double-quoted string literal.""" |
| 259 | + escaped = ( |
| 260 | + s.replace("\\", "\\\\") |
| 261 | + .replace('"', '\\"') |
| 262 | + .replace("\n", "\\n") |
| 263 | + .replace("\r", "\\r") |
| 264 | + .replace("\t", "\\t") |
| 265 | + ) |
| 266 | + return f'"{escaped}"' |
0 commit comments