Files
DecomEval/scripts/package_metrix.py
T

130 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""把 DecomEval 打成 Metrix 应用包:dist/metrix/decomeval-<版本>.zip。
包里有 metrix-app.json 和镜像文件 image.tar。版本取 web/package.json 的 version 加 git 短哈希,
工作区有未提交的改动时再加 -dirty。需要本机可用的 docker。
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SLUG = "decomeval"
NAME = "DecomEval"
WEB_PORT = 8000
DATA_DIR = "/data"
def _git(*args: str) -> str:
completed = subprocess.run(
["git", "-c", f"safe.directory={ROOT.as_posix()}", *args],
cwd=ROOT,
capture_output=True,
text=True,
check=True,
)
return completed.stdout.strip()
def version() -> str:
base = json.loads((ROOT / "web" / "package.json").read_text(encoding="utf-8"))["version"]
try:
commit = _git("rev-parse", "--short", "HEAD")
dirty = bool(_git("status", "--porcelain", "--untracked-files=no"))
except (OSError, subprocess.CalledProcessError):
return base
return f"{base}-{commit}-dirty" if dirty else f"{base}-{commit}"
def manifest(image: str, release: str) -> dict:
return {
"schema": 2,
"slug": SLUG,
"name": NAME,
"version": release,
"user_auth": "app",
"admin_auth": "metrix",
"admin_path": "/admin",
"icon": "icon.svg",
"services": [
{"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT},
{"name": "worker", "image": image, "image_file": "image.tar", "command": "python -m worker.main"},
],
"data_dir": DATA_DIR,
"env": {
"DECOM_DATA_DIR": DATA_DIR,
"DECOM_INLINE_WORKER": "0",
"DECOM_DB_WAIT_SECONDS": "180",
},
}
def _run(command: list[str]) -> None:
print("+ " + " ".join(command), flush=True)
subprocess.run(command, cwd=ROOT, check=True)
def build_image(image: str, args: argparse.Namespace) -> None:
command = ["docker", "build", "-t", image]
for key, value in (
("NODE_IMAGE", args.node_image),
("PYTHON_IMAGE", args.python_image),
("NPM_REGISTRY", args.npm_registry),
("PIP_INDEX", args.pip_index),
):
if value:
command += ["--build-arg", f"{key}={value}"]
command.append(".")
_run(command)
def write_bundle(image: str, release: str, target: Path) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
partial = target.with_name(target.name + ".partial")
with tempfile.TemporaryDirectory(prefix="decomeval-pack-", dir=target.parent) as work:
tar = Path(work) / "image.tar"
_run(["docker", "save", "-o", str(tar), image])
with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle:
bundle.writestr("metrix-app.json", json.dumps(manifest(image, release), ensure_ascii=False, indent=2) + "\n")
bundle.write(ROOT / "web" / "public" / "favicon.svg", "icon.svg")
bundle.write(tar, "image.tar")
os.replace(partial, target)
def main() -> int:
parser = argparse.ArgumentParser(description="打包 DecomEval 为 Metrix 应用包")
parser.add_argument("--skip-build", action="store_true", help="不重新构建,直接打包本机已有的同版本镜像")
parser.add_argument("--node-image", default=os.environ.get("DECOM_NODE_IMAGE", ""), help="构建网页用的 Node 镜像")
parser.add_argument("--python-image", default=os.environ.get("DECOM_PYTHON_IMAGE", ""), help="运行层用的 Python 镜像")
parser.add_argument("--npm-registry", default=os.environ.get("DECOM_NPM_REGISTRY", ""), help="npm 源")
parser.add_argument("--pip-index", default=os.environ.get("DECOM_PIP_INDEX", ""), help="pip 源")
parser.add_argument("--output", default=str(ROOT / "dist" / "metrix"), help="输出目录")
args = parser.parse_args()
if shutil.which("docker") is None:
print("没有找到 docker", file=sys.stderr)
return 1
current = version()
image = f"{SLUG}:{current}"
if not args.skip_build:
build_image(image, args)
target = Path(args.output).resolve() / f"{SLUG}-{current}.zip"
write_bundle(image, current, target)
size = target.stat().st_size
print(f"应用包:{target}")
print(f"大小:{size / 1024 / 1024:.1f} MB({size} 字节)")
print(f"镜像:{image}")
return 0
if __name__ == "__main__":
sys.exit(main())