build_package.py 8.1 KB
# -*- coding: utf-8 -*-
"""打包门店取数端(产物名都带版本号):

    edge\\vendor\\python38\\python.exe edge\\tools\\build_package.py [--with-config] [--suffix _retry] [--update]
    默认          :完整安装包 dist/store_edge_<版本>/ + dist/门店取数端_<版本>.zip(首次安装 / 换运行时用)
    --update      :只打远程更新包 dist/edge_update_<版本>.zip(只含 edgeclient/),企业后台「取数端 → 版本更新」上传;
                    根目录的 bat / README.txt / config.example.ini 放在 edgeclient/_root/ 里,取数端转正后同步到安装目录
    --with-config :把开发机上的 config.ini 一起打进去(只有云端地址和设备令牌,默认不带;门店上由 install.bat 向导填写)
    --suffix X    :产物名再加后缀,如 _retry → dist/store_edge_3.2.0_retry/
打包时生成 edgeclient/_build.py:版本号 + 构建时间 + git 短哈希(心跳、日志、后台都会显示)。

包内结构(文件名全部 ASCII:Win7 自带解压对 UTF-8 中文文件名会乱码;只有 zip 本身的名字是中文):
    install.bat uninstall.bat status.bat tool.bat update.bat   安装 / 卸载服务、查看状态、现场调试菜单、更新到最新版本
    main.py edgeclient/ config.example.ini README.txt ca/
    python38/              ← vendor/python38(嵌入式 Python 3.8)
    browser/chrome-win/    ← vendor/chrome-win(便携 Chromium 109)
    service/               StoreEdge.xml + WinSW.NET2.exe / WinSW.NET4.exe(← vendor/winsw)
"""
import datetime
import os
import re
import shutil
import subprocess
import sys
import zipfile

EDGE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
VENDOR = os.path.join(EDGE, "vendor")
ROOT = os.path.dirname(EDGE)
DIST = os.path.join(ROOT, "dist")
OUT = ZIP = ""


def _suffix():
    if "--suffix" in sys.argv:
        i = sys.argv.index("--suffix")
        s = sys.argv[i + 1] if i + 1 < len(sys.argv) else ""
        if s and all(ch.isalnum() or ch in "_-" for ch in s):
            return s
        sys.exit("--suffix 只能用字母、数字、下划线、减号")
    return ""

FILES = ["main.py", "config.example.ini", "README.txt"]
ROOT_BATS = ["install.bat", "uninstall.bat", "status.bat", "tool.bat", "update.bat", "cleanup.bat"]   # 从 service/ 拷到包根目录
DIRS = ["edgeclient", "ca"]
VENDOR_DIRS = [("python38", "python38"), ("chrome-win", os.path.join("browser", "chrome-win"))]
WINSW = ["WinSW.NET2.exe", "WinSW.NET4.exe"]
SKIP = ("__pycache__", "profile", "*.pyc", "debug.log", "_root")
TEXT = (".bat", ".ini", ".txt", ".csv", ".xml")


def crlf(data):
    """给人看 / 改的文本文件统一 CRLF(Win7 记事本不认 LF;bat 用 LF 偶尔也会出怪问题)。"""
    return data.replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")


def root_files():
    """更新包里 edgeclient/_root/ 的内容:[(文件名, CRLF 后的字节)](取数端转正后同步到安装目录根下)。"""
    out = []
    for name, path in ([(b, os.path.join(EDGE, "service", b)) for b in ROOT_BATS]
                       + [(f, os.path.join(EDGE, f)) for f in ("README.txt", "config.example.ini")]):
        with open(path, "rb") as f:
            out.append((name, crlf(f.read())))
    return out


def version():
    with open(os.path.join(EDGE, "edgeclient", "__init__.py"), encoding="utf-8") as f:
        return re.search(r"""__version__\s*=\s*["']([\d.]+)["']""", f.read()).group(1)


def build_info():
    try:
        rev = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=EDGE, capture_output=True, text=True,
                             timeout=5).stdout.strip()
        dirty = subprocess.run(["git", "status", "--porcelain", "--", "edgeclient"], cwd=EDGE, capture_output=True,
                               text=True, timeout=5).stdout.strip()
    except Exception:  # noqa: BLE001
        rev, dirty = "", ""
    return "%s %s%s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), rev or "local", "+" if dirty else "")


def build_py(ver, build):
    return '# 打包时生成\nVERSION = "%s"\nBUILD = "%s"\n' % (ver, build)


def update_package(ver, build):
    out = os.path.join(DIST, "edge_update_%s.zip" % ver)
    os.makedirs(DIST, exist_ok=True)
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
        for p, dirs, fs in os.walk(os.path.join(EDGE, "edgeclient")):
            dirs[:] = [d for d in dirs if d != "__pycache__"]
            for n in fs:
                if not n.endswith((".pyc", ".pyo")) and n != "_build.py" and "_root" not in p:
                    full = os.path.join(p, n)
                    z.write(full, os.path.relpath(full, EDGE).replace(os.sep, "/"))
        z.writestr("edgeclient/_build.py", build_py(ver, build))
        for name, data in root_files():
            z.writestr("edgeclient/_root/" + name, data)
    print("更新包:%s(版本 %s,%s,%.1f KB)\n企业后台「取数端 → 版本更新」上传后,对设备点「更新到 %s」。"
          % (out, ver, build, os.path.getsize(out) / 1024.0, ver))


def main():
    global OUT, ZIP
    ver, build = version(), build_info()
    if "--update" in sys.argv:
        return update_package(ver, build)
    sfx = _suffix()
    OUT = os.path.join(DIST, "store_edge_%s%s" % (ver, sfx))
    ZIP = os.path.join(DIST, "门店取数端_%s%s.zip" % (ver, sfx))
    with_config = "--with-config" in sys.argv
    need = [os.path.join(VENDOR, "python38", "python.exe")] + [os.path.join(VENDOR, "winsw", w) for w in WINSW]
    miss = [p for p in need if not os.path.exists(p)]
    if miss:
        sys.exit("缺少运行时文件(见 edge/vendor/README.md):\n  " + "\n  ".join(miss))
    if not os.path.exists(os.path.join(VENDOR, "chrome-win", "chrome.exe")):
        print("[注意] 没有找到 vendor/chrome-win/chrome.exe:包里不带浏览器,截图会失败。")
    if os.path.isdir(OUT):
        shutil.rmtree(OUT)
    os.makedirs(os.path.join(OUT, "service"))
    for f in FILES:
        shutil.copy2(os.path.join(EDGE, f), OUT)
    for b in ROOT_BATS:
        shutil.copy2(os.path.join(EDGE, "service", b), OUT)
    for f in ("StoreEdge.xml", "xcopy_exclude.txt"):
        shutil.copy2(os.path.join(EDGE, "service", f), os.path.join(OUT, "service"))
    for w in WINSW:
        shutil.copy2(os.path.join(VENDOR, "winsw", w), os.path.join(OUT, "service"))
    if with_config and os.path.exists(os.path.join(EDGE, "config.ini")):
        shutil.copy2(os.path.join(EDGE, "config.ini"), OUT)
        print("[注意] 已带上 config.ini(含设备令牌),压缩包请勿外传。")
    for d in DIRS:
        shutil.copytree(os.path.join(EDGE, d), os.path.join(OUT, d), ignore=shutil.ignore_patterns(*SKIP, "_build.py"))
    with open(os.path.join(OUT, "edgeclient", "_build.py"), "w", encoding="utf-8") as f:
        f.write(build_py(ver, build))
    for src, dst in VENDOR_DIRS:
        if os.path.isdir(os.path.join(VENDOR, src)):
            shutil.copytree(os.path.join(VENDOR, src), os.path.join(OUT, dst), ignore=shutil.ignore_patterns(*SKIP))
    for p, _, fs in os.walk(OUT):
        if "python38" in p or "browser" in p or "edgeclient" in p:
            continue
        for n in fs:
            if n.endswith(TEXT):
                fp = os.path.join(p, n)
                with open(fp, "rb") as f:
                    data = f.read()
                with open(fp, "wb") as f:
                    f.write(crlf(data))
    bad = [p for p, _, fs in os.walk(OUT) for n in fs + [os.path.basename(p)] if any(ord(ch) > 127 for ch in n)]
    if bad:
        sys.exit("包内有非 ASCII 文件名(Win7 解压会乱码):%s" % bad[:5])
    if os.path.exists(ZIP):
        os.remove(ZIP)
    with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED) as z:
        for p, _, fs in os.walk(OUT):
            for n in fs:
                full = os.path.join(p, n)
                z.write(full, os.path.relpath(full, DIST))
    print("打包完成(版本 %s,%s):\n  文件夹 %s\n  压缩包 %s(%.1f MB)\n门店电脑:解压后右键 install.bat →「以管理员身份运行」。"
          % (ver, build, OUT, ZIP, os.path.getsize(ZIP) / 1024 / 1024))


if __name__ == "__main__":
    main()