build_package.py 3.09 KB
# -*- coding: utf-8 -*-
"""打包门店取数端:dist/store_edge/(解压即用的文件夹)+ dist/门店取数端_store_edge.zip。

    python edge/build_package.py [--no-config]      --no-config:不带含账号密码的 config.ini(只带模板)

包内文件名全部是 ASCII(Win7 自带解压对 UTF-8 中文文件名会乱码),只有 zip 本身的名字是中文。
需要 edge/python38/(嵌入式 Python 3.8);edge/browser/chrome-win/chrome.exe(便携 Chromium 109)有就带上,没有会提示。
"""
import os
import shutil
import sys
import zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
DIST = os.path.join(ROOT, "dist")
OUT = os.path.join(DIST, "store_edge")
ZIP = os.path.join(DIST, "门店取数端_store_edge.zip")

FILES = ["main.py", "start.bat", "serve.bat", "config.example.ini", "expected.csv", "README.txt"]
DIRS = ["edgeclient", "python38", "ca", "browser"]
SKIP_DIRS = {"__pycache__", "profile"}


def main():
    with_config = "--no-config" not in sys.argv
    if not os.path.exists(os.path.join(HERE, "python38", "python.exe")):
        sys.exit("缺少 edge/python38(嵌入式 Python 3.8)")
    chrome = os.path.join(HERE, "browser", "chrome-win", "chrome.exe")
    if not os.path.exists(chrome):
        print("[注意] 没有找到便携 Chrome:%s\n       包里不带浏览器,门店电脑需自行指定 chrome_path,否则截图会报错。" % chrome)
    if os.path.isdir(OUT):
        shutil.rmtree(OUT)
    os.makedirs(OUT)
    for f in FILES:
        shutil.copy2(os.path.join(HERE, f), OUT)
    if with_config and os.path.exists(os.path.join(HERE, "config.ini")):
        shutil.copy2(os.path.join(HERE, "config.ini"), OUT)
        print("[注意] 已带上 config.ini(含 DMS 明文账号密码),压缩包请勿外传。")
    for d in DIRS:
        src = os.path.join(HERE, d)
        if os.path.isdir(src):
            shutil.copytree(src, os.path.join(OUT, d), ignore=shutil.ignore_patterns(*SKIP_DIRS, "*.pyc"))
    # 给人看/改的文本文件转成 CRLF(Win7 记事本不认 LF 换行,会挤成一行)
    for n in ["start.bat", "serve.bat", "config.example.ini", "config.ini", "README.txt", "expected.csv"]:
        fp = os.path.join(OUT, n)
        if os.path.exists(fp):
            with open(fp, "rb") as f:
                data = f.read()
            with open(fp, "wb") as f:
                f.write(data.replace(b"\r\n", b"\n").replace(b"\n", b"\r\n"))
    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))
    size = os.path.getsize(ZIP) / 1024 / 1024
    print("打包完成:\n  文件夹 %s\n  压缩包 %s(%.1f MB)" % (OUT, ZIP, size))


if __name__ == "__main__":
    main()