#!/usr/bin/env python """Prepare ``deeptutor_web`` package data from a Next.js standalone build.""" from __future__ import annotations import argparse from pathlib import Path import shutil import subprocess PROJECT_ROOT = Path(__file__).resolve().parent.parent WEB_DIR = PROJECT_ROOT / "web" PACKAGE_DIR = PROJECT_ROOT / "deeptutor_web" def _clean_package_dir(package_dir: Path) -> None: package_dir.mkdir(parents=True, exist_ok=True) init_file = package_dir / "__init__.py" init_text = init_file.read_text(encoding="utf-8") if init_file.exists() else "" for child in package_dir.iterdir(): if child.name == "__init__.py": continue if child.is_dir(): shutil.rmtree(child) else: child.unlink() if init_text: init_file.write_text(init_text, encoding="utf-8") def prepare_web_package(*, skip_build: bool = False) -> None: if not skip_build: subprocess.run(["npm", "run", "build"], cwd=WEB_DIR, check=True) standalone = WEB_DIR / ".next" / "standalone" static_dir = WEB_DIR / ".next" / "static" public_dir = WEB_DIR / "public" if not (standalone / "server.js").exists(): raise SystemExit( "Missing web/.next/standalone/server.js. Run this script after `npm run build` " "or omit --skip-build." ) _clean_package_dir(PACKAGE_DIR) shutil.copytree(standalone, PACKAGE_DIR, dirs_exist_ok=True) if static_dir.exists(): shutil.copytree(static_dir, PACKAGE_DIR / ".next" / "static", dirs_exist_ok=True) if public_dir.exists(): shutil.copytree(public_dir, PACKAGE_DIR / "public", dirs_exist_ok=True) (PACKAGE_DIR / "BUILD_INFO").write_text( "Generated by scripts/prepare_web_package.py from web/.next/standalone.\n", encoding="utf-8", ) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--skip-build", action="store_true", help="Copy an existing web/.next/standalone build without running npm.", ) args = parser.parse_args() prepare_web_package(skip_build=args.skip_build) if __name__ == "__main__": main()