#!/usr/bin/env python3 """Assemble 电子书小红书包 — 同步壳层后强制 hackrobot 正文,再扁平打包。""" from __future__ import annotations import shutil import sys from pathlib import Path from subprocess import check_call ROOT = Path(__file__).resolve().parents[1] MINI = ROOT.parent SRC = ROOT / "tool" OUT = ROOT / "release-book" PACK = MINI / "scripts" / "pack-hackrobot-book.py" def main() -> int: check_call([sys.executable, str(ROOT / "scripts" / "sync_data.py")]) # export 会写回旧册;必须再用 hackrobot 覆盖 book-data + portal.book if PACK.is_file(): check_call([sys.executable, str(PACK)]) else: print(f"WARN missing {PACK}", file=sys.stderr) if OUT.exists(): shutil.rmtree(OUT, ignore_errors=True) OUT.mkdir(parents=True) parts = [] for name in ("book/book-data.js", "book/markdown.js", "book/xhs-bridge.js", "book-app.js"): p = SRC / name if not p.is_file(): print(f"missing {name}", file=sys.stderr) return 1 text = p.read_text(encoding="utf-8") if name == "book-app.js": marker = "(function ()" idx = text.find(marker) if idx < 0: idx = text.find("function getBook") if idx > 0 and "var BOOK_DATA" in text[:idx]: text = "/* book-app runtime */\n" + text[idx:] parts.append(text) html_src = SRC / "book.html" css_src = SRC / "book-styles.css" if not html_src.is_file() or not css_src.is_file(): print("missing book.html / book-styles.css", file=sys.stderr) return 1 shutil.copy2(html_src, OUT / "index.html") shutil.copy2(css_src, OUT / "styles.css") (OUT / "app.js").write_text( "/* bundled xhs ebook — hackrobot offline BOOK_DATA */\n" + "\n".join(parts) + "\n", encoding="utf-8", ) book_imgs = SRC / "book" / "images" if book_imgs.is_dir(): shutil.copytree(book_imgs, OUT / "images") nested = [p for p in OUT.rglob("index.html") if p != OUT / "index.html"] if nested: print("FATAL nested index.html", nested, file=sys.stderr) return 1 app_js = (OUT / "app.js").read_text(encoding="utf-8", errors="ignore") if "低成本工作室" not in app_js or "数字游民:自动化杠杆副业" not in app_js: print("FATAL release-book missing hackrobot chapters", file=sys.stderr) return 1 print(f"assembled {OUT}") for p in sorted(OUT.iterdir()): if p.is_file(): print(f" {p.name}\t{p.stat().st_size}") return 0 if __name__ == "__main__": raise SystemExit(main())