123 lines
4.2 KiB
Python
123 lines
4.2 KiB
Python
"""把 CapacityReport 打成 Metrix 应用包:dist/metrix/capacityreport-<版本>.zip。
|
||
|
||
包里有 metrix-app.json、图标 icon.svg 和镜像文件 image.tar。版本取 app/main.py 的 APP_VERSION
|
||
加 git 短哈希,工作区有未提交的改动时再加 -dirty。需要本机可用的 node 和 docker。
|
||
|
||
用法:
|
||
python scripts/package_metrix.py # 构建前端和镜像后打包
|
||
python scripts/package_metrix.py --skip-build # 直接打包本机已有的同版本镜像
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import zipfile
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
import _env # noqa: E402
|
||
|
||
SLUG = "capacityreport"
|
||
NAME = "CapacityReport"
|
||
WEB_PORT = 9081
|
||
DATA_DIR = "/data"
|
||
ICON = _env.FRONTEND_DIR / "public" / "favicon.svg"
|
||
|
||
|
||
def _git(*args: str) -> str:
|
||
completed = subprocess.run(
|
||
["git", "-c", f"safe.directory={_env.ROOT.as_posix()}", *args],
|
||
cwd=_env.ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=True,
|
||
)
|
||
return completed.stdout.strip()
|
||
|
||
|
||
def version() -> str:
|
||
source = (_env.ROOT / "app" / "main.py").read_text(encoding="utf-8")
|
||
match = re.search(r'^APP_VERSION\s*=\s*"([^"]+)"', source, re.MULTILINE)
|
||
if not match:
|
||
_env.die("没有在 app/main.py 找到 APP_VERSION")
|
||
base = match.group(1)
|
||
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,
|
||
"description": {
|
||
"zh-CN": "处理每周容量报表,生成 4G 和 5G 容量结果,并查看高负荷小区。",
|
||
"en-US": "Processes weekly capacity reports, builds 4G and 5G capacity results, and reviews high-load cells.",
|
||
},
|
||
"user_auth": "metrix",
|
||
"admin_auth": "none",
|
||
"icon": "icon.svg",
|
||
"services": [
|
||
{"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT},
|
||
],
|
||
"data_dir": DATA_DIR,
|
||
"env": {"CAPAREPORT_BASE_DIR": DATA_DIR},
|
||
}
|
||
|
||
|
||
def build_image(image: str) -> None:
|
||
_env.ensure_docker()
|
||
_env.build_frontend()
|
||
_env.step(f"构建镜像 {image}")
|
||
_env.run(["docker", "build", "--progress=plain", "-t", image, "."], cwd=_env.ROOT)
|
||
|
||
|
||
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=f"{SLUG}-pack-", dir=target.parent) as work:
|
||
tar = Path(work) / "image.tar"
|
||
_env.step("导出镜像")
|
||
_env.run(["docker", "save", "-o", str(tar), image])
|
||
_env.step("写入应用包")
|
||
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(ICON, "icon.svg")
|
||
bundle.write(tar, "image.tar")
|
||
os.replace(partial, target)
|
||
|
||
|
||
def main() -> int:
|
||
_env.setup_console()
|
||
parser = argparse.ArgumentParser(description="打包 CapacityReport 为 Metrix 应用包")
|
||
parser.add_argument("--skip-build", action="store_true", help="不重新构建,直接打包本机已有的同版本镜像")
|
||
parser.add_argument("--output", default=str(_env.DIST_DIR / "metrix"), help="输出目录")
|
||
args = parser.parse_args()
|
||
|
||
current = version()
|
||
image = f"{SLUG}:{current}"
|
||
if not args.skip_build:
|
||
build_image(image)
|
||
target = Path(args.output).resolve() / f"{SLUG}-{current}.zip"
|
||
write_bundle(image, current, target)
|
||
size = target.stat().st_size
|
||
_env.step(f"应用包:{target}")
|
||
_env.info(f"大小:{size / 1024 / 1024:.1f} MB({size} 字节)")
|
||
_env.info(f"镜像:{image}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|