142 lines
4.6 KiB
Python
142 lines
4.6 KiB
Python
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Callable, Sequence
|
|
|
|
|
|
ROOT_EXES = ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe")
|
|
SMOKE_COMMANDS = (
|
|
("run_cli.exe", "--help"),
|
|
)
|
|
RUNTIME_MUTABLE_DIRS = ("logs", "pic", "state")
|
|
Runner = Callable[..., subprocess.CompletedProcess]
|
|
|
|
|
|
def _smoke_env() -> dict[str, str]:
|
|
env = os.environ.copy()
|
|
env["DOUYIN_LICENSE_REQUIRED"] = "0"
|
|
env["SKIP_OCR_INIT"] = "1"
|
|
return env
|
|
|
|
|
|
def _snapshot_runtime_files(root: Path) -> set[Path]:
|
|
files: set[Path] = set()
|
|
for name in RUNTIME_MUTABLE_DIRS:
|
|
runtime_dir = root / name
|
|
if not runtime_dir.exists():
|
|
continue
|
|
files.update(path for path in runtime_dir.rglob("*") if path.is_file())
|
|
return files
|
|
|
|
|
|
def _cleanup_new_runtime_files(root: Path, before: set[Path]) -> None:
|
|
for path in sorted(_snapshot_runtime_files(root) - before, reverse=True):
|
|
if path.name == ".keep":
|
|
continue
|
|
try:
|
|
path.unlink()
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
|
|
def resolve_upx(upx_dir: str | None = None) -> str:
|
|
if upx_dir:
|
|
candidate = Path(upx_dir) / ("upx.exe" if sys.platform.startswith("win") else "upx")
|
|
if candidate.exists():
|
|
return str(candidate)
|
|
raise FileNotFoundError(f"upx executable not found in {upx_dir}")
|
|
found = shutil.which("upx")
|
|
if not found:
|
|
raise FileNotFoundError("upx executable not found")
|
|
return found
|
|
|
|
|
|
def pack_distribution_exes(
|
|
dist_dir: str | Path,
|
|
*,
|
|
upx_dir: str | None = None,
|
|
force: bool = False,
|
|
runner: Runner = subprocess.run,
|
|
) -> list[Path]:
|
|
root = Path(dist_dir)
|
|
missing = [name for name in ROOT_EXES if not (root / name).is_file()]
|
|
if missing:
|
|
raise RuntimeError(f"missing root exe files: {', '.join(missing)}")
|
|
|
|
upx = resolve_upx(upx_dir)
|
|
packed: list[Path] = []
|
|
for name in ROOT_EXES:
|
|
exe = root / name
|
|
cmd = [upx, "--best", "--lzma"]
|
|
if force:
|
|
cmd.append("--force")
|
|
cmd.append(str(exe))
|
|
runner(cmd, check=True)
|
|
packed.append(exe)
|
|
return packed
|
|
|
|
|
|
def smoke_check_distribution_exes(
|
|
dist_dir: str | Path,
|
|
*,
|
|
runner: Runner = subprocess.run,
|
|
timeout: int = 20,
|
|
) -> None:
|
|
root = Path(dist_dir)
|
|
before = _snapshot_runtime_files(root)
|
|
try:
|
|
for exe_name, arg in SMOKE_COMMANDS:
|
|
exe = root / exe_name
|
|
proc = runner([str(exe), arg], capture_output=True, text=True, timeout=timeout, env=_smoke_env())
|
|
if proc.returncode != 0:
|
|
detail = (proc.stderr or proc.stdout or "").strip().replace("\r", " ").replace("\n", " ")
|
|
raise RuntimeError(f"smoke check failed for {exe_name}: exit={proc.returncode} {detail}")
|
|
finally:
|
|
_cleanup_new_runtime_files(root, before)
|
|
|
|
|
|
def main(argv: Sequence[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description="使用 UPX 加壳/压缩分发目录根部 exe")
|
|
parser.add_argument("dist_dir", help="例如 dist/DouyinGuaji-3.3.3")
|
|
parser.add_argument("--upx-dir", default="", help="UPX 所在目录;为空则从 PATH 查找")
|
|
parser.add_argument("--force", action="store_true", help="强制加壳 GUARD_CF 等 UPX 默认拒绝的 exe")
|
|
parser.add_argument("--no-smoke", action="store_true", help="跳过加壳后的 exe 启动冒烟检查")
|
|
parser.add_argument("--smoke-only", action="store_true", help="只运行 exe 启动冒烟检查,不调用 UPX")
|
|
args = parser.parse_args(argv)
|
|
|
|
try:
|
|
packed: list[Path] = []
|
|
if args.smoke_only:
|
|
smoke_check_distribution_exes(args.dist_dir)
|
|
else:
|
|
packed = pack_distribution_exes(args.dist_dir, upx_dir=args.upx_dir or None, force=args.force)
|
|
if not args.no_smoke:
|
|
smoke_check_distribution_exes(args.dist_dir)
|
|
except FileNotFoundError as exc:
|
|
print(f"[PACK-EXE] FAIL {exc}. Download UPX and pass -UpxDir <dir>.", file=sys.stderr)
|
|
return 2
|
|
except subprocess.CalledProcessError as exc:
|
|
print(f"[PACK-EXE] FAIL upx exited with code {exc.returncode}", file=sys.stderr)
|
|
return exc.returncode or 1
|
|
except Exception as exc:
|
|
print(f"[PACK-EXE] FAIL {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
if args.smoke_only:
|
|
print("[PACK-EXE] PASS smoke_only=1")
|
|
return 0
|
|
|
|
print(f"[PACK-EXE] PASS packed={len(packed)}")
|
|
for exe in packed:
|
|
print(f" {exe}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|