Add PyArmor obfuscation packaging flow

This commit is contained in:
Your Name committed 2026-06-17 23:42:15 +08:00
1 parent 5166678590
commit 11de0f75c7
4 files changed
+292 -5

No files matched your search

+145
View File
@@ -0,0 +1,145 @@
from __future__ import annotations
import argparse
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Sequence
import sys
RUNTIME_SOURCE_DIRS = ("douyin", "gui", "operations")
RUNTIME_ENTRY_FILES = ("bin/run_cli.py",)
FORBIDDEN_STAGING_PREFIXES = ("tools/", "tests/", "artifacts/", "docs/", "packaging/")
FORBIDDEN_STAGING_FILES = ("tools/license_dev.py",)
Runner = Callable[..., subprocess.CompletedProcess]
@dataclass(frozen=True)
class ObfuscationResult:
staging_root: Path
runtime_package: str
def _as_posix(path: str | Path) -> str:
return str(path).replace("\\", "/")
def _iter_files(root: Path) -> list[str]:
if not root.exists():
return []
return sorted(path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file())
def _find_runtime_package(staging_root: Path) -> str:
for path in staging_root.iterdir() if staging_root.exists() else []:
if path.is_dir() and path.name.startswith("pyarmor_runtime"):
return path.name
return ""
def validate_pyarmor_staging(staging_root: str | Path) -> ObfuscationResult:
root = Path(staging_root)
missing: list[str] = []
for rel in [*RUNTIME_SOURCE_DIRS, *RUNTIME_ENTRY_FILES]:
if not (root / rel).exists():
missing.append(rel)
if missing:
raise RuntimeError(f"obfuscation staging missing required entries: {', '.join(missing)}")
runtime_package = _find_runtime_package(root)
if not runtime_package:
raise RuntimeError("obfuscation staging missing pyarmor_runtime package")
entries = _iter_files(root)
forbidden: list[str] = []
for entry in entries:
lower = entry.lower()
if any(lower.startswith(prefix) for prefix in FORBIDDEN_STAGING_PREFIXES):
forbidden.append(entry)
if lower in {item.lower() for item in FORBIDDEN_STAGING_FILES}:
forbidden.append(entry)
if forbidden:
raise RuntimeError(f"obfuscation staging contains forbidden entries: {', '.join(forbidden[:20])}")
return ObfuscationResult(staging_root=root, runtime_package=runtime_package)
def build_pyarmor_command(source_root: str | Path, staging_root: str | Path) -> list[str]:
source = Path(source_root)
target = Path(staging_root)
pyarmor = shutil.which("pyarmor")
if not pyarmor:
raise FileNotFoundError("pyarmor executable not found")
inputs = [
*RUNTIME_SOURCE_DIRS,
*RUNTIME_ENTRY_FILES,
]
return [
pyarmor,
"gen",
"--recursive",
"--output",
str(target),
*[_as_posix(item) for item in inputs if (source / item).exists()],
]
def normalize_pyarmor_staging_layout(staging_root: str | Path) -> None:
root = Path(staging_root)
for rel in RUNTIME_ENTRY_FILES:
expected = root / rel
if expected.exists():
continue
flat = root / Path(rel).name
if not flat.exists():
continue
expected.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(flat), str(expected))
def create_pyarmor_staging(
source_root: str | Path,
staging_root: str | Path,
*,
runner: Runner = subprocess.run,
) -> ObfuscationResult:
source = Path(source_root).resolve()
target = Path(staging_root).resolve()
if target.exists():
shutil.rmtree(target)
target.parent.mkdir(parents=True, exist_ok=True)
cmd = build_pyarmor_command(source, target)
runner(cmd, cwd=source, check=True)
normalize_pyarmor_staging_layout(target)
return validate_pyarmor_staging(target)
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="生成 PyInstaller 使用的 PyArmor 混淆源码 staging 目录")
parser.add_argument("--source-root", default=".", help="项目根目录")
parser.add_argument("--staging-root", required=True, help="输出 staging 目录")
args = parser.parse_args(argv)
try:
result = create_pyarmor_staging(args.source_root, args.staging_root)
except FileNotFoundError:
print("[OBFUSCATE] FAIL pyarmor is not installed. Run: python -m pip install pyarmor", file=sys.stderr)
return 2
except subprocess.CalledProcessError as exc:
print(f"[OBFUSCATE] FAIL pyarmor exited with code {exc.returncode}", file=sys.stderr)
return exc.returncode or 1
except Exception as exc:
print(f"[OBFUSCATE] FAIL {exc}", file=sys.stderr)
return 1
print(f"[OBFUSCATE] PASS staging={result.staging_root} runtime={result.runtime_package}")
return 0
if __name__ == "__main__":
raise SystemExit(main())