|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import re |
| 5 | +from pathlib import Path |
| 6 | +from urllib.parse import urlsplit |
| 7 | +from urllib.request import Request, urlopen |
| 8 | + |
| 9 | + |
| 10 | +CDN_URL_RE = re.compile( |
| 11 | + rb"https://(?:unpkg\.com|cdn\.jsdelivr\.net)/[A-Za-z0-9@%_+./?=&~-]+" |
| 12 | +) |
| 13 | +def download(url: str, destination: Path) -> None: |
| 14 | + request = Request(url, headers={"User-Agent": "msys2.org site builder"}) |
| 15 | + with urlopen(request, timeout=120) as response: |
| 16 | + content = response.read() |
| 17 | + |
| 18 | + destination.parent.mkdir(parents=True, exist_ok=True) |
| 19 | + destination.write_bytes(content) |
| 20 | + |
| 21 | + |
| 22 | +def local_path(site_dir: Path, url: str) -> Path: |
| 23 | + parsed = urlsplit(url) |
| 24 | + path = parsed.path.lstrip("/") |
| 25 | + if not path or path.endswith("/"): |
| 26 | + raise ValueError(f"CDN URL does not identify a file: {url}") |
| 27 | + if parsed.netloc == "unpkg.com" and "/" not in path: |
| 28 | + path += "/index.js" |
| 29 | + return site_dir / "assets" / "vendor" / parsed.netloc / path |
| 30 | + |
| 31 | + |
| 32 | +def root_relative(site_dir: Path, path: Path) -> str: |
| 33 | + return "/" + path.relative_to(site_dir).as_posix() |
| 34 | + |
| 35 | + |
| 36 | +def localize(site_dir: Path) -> None: |
| 37 | + javascript_files = sorted(site_dir.rglob("*.js")) |
| 38 | + if not javascript_files: |
| 39 | + raise FileNotFoundError(f"No JavaScript files found in {site_dir}") |
| 40 | + |
| 41 | + references = { |
| 42 | + match.group().decode("ascii") |
| 43 | + for path in javascript_files |
| 44 | + for match in CDN_URL_RE.finditer(path.read_bytes()) |
| 45 | + } |
| 46 | + replacements = {} |
| 47 | + for url in sorted(references): |
| 48 | + if "pyodide" in urlsplit(url).path: |
| 49 | + continue |
| 50 | + |
| 51 | + destination = local_path(site_dir, url) |
| 52 | + download(url, destination) |
| 53 | + replacements[url] = root_relative(site_dir, destination) |
| 54 | + |
| 55 | + for path in javascript_files: |
| 56 | + content = path.read_bytes() |
| 57 | + for url, replacement in replacements.items(): |
| 58 | + content = content.replace(url.encode(), replacement.encode()) |
| 59 | + path.write_bytes(content) |
| 60 | + |
| 61 | + print(f"Localized {len(replacements)} CDN references") |
| 62 | + |
| 63 | + |
| 64 | +def main() -> None: |
| 65 | + parser = argparse.ArgumentParser( |
| 66 | + description="Download CDN assets referenced by generated JavaScript" |
| 67 | + ) |
| 68 | + parser.add_argument("site_dir", nargs="?", default="site", type=Path) |
| 69 | + args = parser.parse_args() |
| 70 | + localize(args.site_dir.resolve()) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + main() |
0 commit comments