crogram-pythub 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crogram_pythub-0.1.0.dist-info/METADATA +148 -0
- crogram_pythub-0.1.0.dist-info/RECORD +27 -0
- crogram_pythub-0.1.0.dist-info/WHEEL +5 -0
- crogram_pythub-0.1.0.dist-info/entry_points.txt +3 -0
- crogram_pythub-0.1.0.dist-info/licenses/LICENSE +21 -0
- crogram_pythub-0.1.0.dist-info/top_level.txt +1 -0
- pythub/__init__.py +22 -0
- pythub/__main__.py +6 -0
- pythub/analyzer.py +142 -0
- pythub/bootloader/bootex.c +1310 -0
- pythub/bootloader/miniz_LICENSE +22 -0
- pythub/bootloader/miniz_common.h +146 -0
- pythub/bootloader/miniz_export.h +5 -0
- pythub/bootloader/miniz_tinfl.c +765 -0
- pythub/bootloader/miniz_tinfl.h +148 -0
- pythub/builder.py +421 -0
- pythub/cli.py +348 -0
- pythub/config.py +77 -0
- pythub/deps.py +90 -0
- pythub/exe_archive.py +414 -0
- pythub/formats.py +227 -0
- pythub/gui.py +690 -0
- pythub/native_builder.py +71 -0
- pythub/pypa.py +213 -0
- pythub/runtime.py +336 -0
- pythub/signing.py +104 -0
- pythub/utils.py +330 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
#include "miniz_common.h"
|
|
3
|
+
/* ------------------- Low-level Decompression API Definitions */
|
|
4
|
+
|
|
5
|
+
#ifndef MINIZ_NO_INFLATE_APIS
|
|
6
|
+
|
|
7
|
+
#ifdef __cplusplus
|
|
8
|
+
extern "C" {
|
|
9
|
+
#endif
|
|
10
|
+
/* Decompression flags used by tinfl_decompress(). */
|
|
11
|
+
/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */
|
|
12
|
+
/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */
|
|
13
|
+
/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */
|
|
14
|
+
/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */
|
|
15
|
+
enum
|
|
16
|
+
{
|
|
17
|
+
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
|
|
18
|
+
TINFL_FLAG_HAS_MORE_INPUT = 2,
|
|
19
|
+
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
|
|
20
|
+
TINFL_FLAG_COMPUTE_ADLER32 = 8
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/* High level decompression functions: */
|
|
24
|
+
/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */
|
|
25
|
+
/* On entry: */
|
|
26
|
+
/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */
|
|
27
|
+
/* On return: */
|
|
28
|
+
/* Function returns a pointer to the decompressed data, or NULL on failure. */
|
|
29
|
+
/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */
|
|
30
|
+
/* The caller must call mz_free() on the returned block when it's no longer needed. */
|
|
31
|
+
MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
|
|
32
|
+
|
|
33
|
+
/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */
|
|
34
|
+
/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */
|
|
35
|
+
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
|
|
36
|
+
MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
|
|
37
|
+
|
|
38
|
+
/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */
|
|
39
|
+
/* Returns 1 on success or 0 on failure. */
|
|
40
|
+
typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
|
|
41
|
+
MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
|
|
42
|
+
|
|
43
|
+
struct tinfl_decompressor_tag;
|
|
44
|
+
typedef struct tinfl_decompressor_tag tinfl_decompressor;
|
|
45
|
+
|
|
46
|
+
#ifndef MINIZ_NO_MALLOC
|
|
47
|
+
/* Allocate the tinfl_decompressor structure in C so that */
|
|
48
|
+
/* non-C language bindings to tinfl_ API don't need to worry about */
|
|
49
|
+
/* structure size and allocation mechanism. */
|
|
50
|
+
MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void);
|
|
51
|
+
MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp);
|
|
52
|
+
#endif
|
|
53
|
+
|
|
54
|
+
/* Max size of LZ dictionary. */
|
|
55
|
+
#define TINFL_LZ_DICT_SIZE 32768
|
|
56
|
+
|
|
57
|
+
/* Return status. */
|
|
58
|
+
typedef enum {
|
|
59
|
+
/* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */
|
|
60
|
+
/* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */
|
|
61
|
+
/* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */
|
|
62
|
+
TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
|
|
63
|
+
|
|
64
|
+
/* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */
|
|
65
|
+
TINFL_STATUS_BAD_PARAM = -3,
|
|
66
|
+
|
|
67
|
+
/* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */
|
|
68
|
+
TINFL_STATUS_ADLER32_MISMATCH = -2,
|
|
69
|
+
|
|
70
|
+
/* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */
|
|
71
|
+
TINFL_STATUS_FAILED = -1,
|
|
72
|
+
|
|
73
|
+
/* Any status code less than TINFL_STATUS_DONE must indicate a failure. */
|
|
74
|
+
|
|
75
|
+
/* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */
|
|
76
|
+
/* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */
|
|
77
|
+
TINFL_STATUS_DONE = 0,
|
|
78
|
+
|
|
79
|
+
/* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */
|
|
80
|
+
/* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */
|
|
81
|
+
/* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */
|
|
82
|
+
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
|
|
83
|
+
|
|
84
|
+
/* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */
|
|
85
|
+
/* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */
|
|
86
|
+
/* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */
|
|
87
|
+
/* so I may need to add some code to address this. */
|
|
88
|
+
TINFL_STATUS_HAS_MORE_OUTPUT = 2
|
|
89
|
+
} tinfl_status;
|
|
90
|
+
|
|
91
|
+
/* Initializes the decompressor to its initial state. */
|
|
92
|
+
#define tinfl_init(r) \
|
|
93
|
+
do \
|
|
94
|
+
{ \
|
|
95
|
+
(r)->m_state = 0; \
|
|
96
|
+
} \
|
|
97
|
+
MZ_MACRO_END
|
|
98
|
+
#define tinfl_get_adler32(r) (r)->m_check_adler32
|
|
99
|
+
|
|
100
|
+
/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */
|
|
101
|
+
/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */
|
|
102
|
+
MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
|
|
103
|
+
|
|
104
|
+
/* Internal/private bits follow. */
|
|
105
|
+
enum
|
|
106
|
+
{
|
|
107
|
+
TINFL_MAX_HUFF_TABLES = 3,
|
|
108
|
+
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
|
|
109
|
+
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
|
|
110
|
+
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
|
|
111
|
+
TINFL_FAST_LOOKUP_BITS = 10,
|
|
112
|
+
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
#if MINIZ_HAS_64BIT_REGISTERS
|
|
116
|
+
#define TINFL_USE_64BIT_BITBUF 1
|
|
117
|
+
#else
|
|
118
|
+
#define TINFL_USE_64BIT_BITBUF 0
|
|
119
|
+
#endif
|
|
120
|
+
|
|
121
|
+
#if TINFL_USE_64BIT_BITBUF
|
|
122
|
+
typedef mz_uint64 tinfl_bit_buf_t;
|
|
123
|
+
#define TINFL_BITBUF_SIZE (64)
|
|
124
|
+
#else
|
|
125
|
+
typedef mz_uint32 tinfl_bit_buf_t;
|
|
126
|
+
#define TINFL_BITBUF_SIZE (32)
|
|
127
|
+
#endif
|
|
128
|
+
|
|
129
|
+
struct tinfl_decompressor_tag
|
|
130
|
+
{
|
|
131
|
+
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
|
|
132
|
+
tinfl_bit_buf_t m_bit_buf;
|
|
133
|
+
size_t m_dist_from_out_buf_start;
|
|
134
|
+
mz_int16 m_look_up[TINFL_MAX_HUFF_TABLES][TINFL_FAST_LOOKUP_SIZE];
|
|
135
|
+
mz_int16 m_tree_0[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
|
|
136
|
+
mz_int16 m_tree_1[TINFL_MAX_HUFF_SYMBOLS_1 * 2];
|
|
137
|
+
mz_int16 m_tree_2[TINFL_MAX_HUFF_SYMBOLS_2 * 2];
|
|
138
|
+
mz_uint8 m_code_size_0[TINFL_MAX_HUFF_SYMBOLS_0];
|
|
139
|
+
mz_uint8 m_code_size_1[TINFL_MAX_HUFF_SYMBOLS_1];
|
|
140
|
+
mz_uint8 m_code_size_2[TINFL_MAX_HUFF_SYMBOLS_2];
|
|
141
|
+
mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
#ifdef __cplusplus
|
|
145
|
+
}
|
|
146
|
+
#endif
|
|
147
|
+
|
|
148
|
+
#endif /*#ifndef MINIZ_NO_INFLATE_APIS*/
|
pythub/builder.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"""Pythub 打包引擎主流程。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
import zipfile
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import List, Optional
|
|
14
|
+
|
|
15
|
+
from pythub import DEFAULT_FORMAT, PLATFORM_FORMATS
|
|
16
|
+
from pythub.analyzer import analyze
|
|
17
|
+
from pythub.config import app_config, load_requirements
|
|
18
|
+
from pythub.deps import download_wheels, unpack_wheels
|
|
19
|
+
from pythub import formats
|
|
20
|
+
from pythub.runtime import fetch_runtime, interpreter_path
|
|
21
|
+
from pythub.utils import (
|
|
22
|
+
ProgressLogger,
|
|
23
|
+
copy_tree,
|
|
24
|
+
make_tar_gz,
|
|
25
|
+
make_zip,
|
|
26
|
+
set_executable,
|
|
27
|
+
temp_dir,
|
|
28
|
+
zip_dir,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
EXCLUDE_DIRS = {
|
|
32
|
+
"__pycache__", ".git", ".hg", ".svn", ".venv", "venv", "env",
|
|
33
|
+
"build", "dist", ".pythub", "node_modules", ".idea", ".vscode",
|
|
34
|
+
".mypy_cache", ".pytest_cache", ".tox", ".eggs",
|
|
35
|
+
}
|
|
36
|
+
EXCLUDE_SUFFIXES = {".pyc", ".pyo", ".pyd.bak"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class BuildSpec:
|
|
41
|
+
project_dir: Path
|
|
42
|
+
name: str = ""
|
|
43
|
+
entry: str = ""
|
|
44
|
+
version: str = "0.1.0"
|
|
45
|
+
requirements: List[str] = field(default_factory=list)
|
|
46
|
+
platform: str = "linux"
|
|
47
|
+
arch: str = "x86_64"
|
|
48
|
+
python: str = "3.12"
|
|
49
|
+
fmt: str = ""
|
|
50
|
+
output: Path = Path("dist")
|
|
51
|
+
engine: str = "zipapp"
|
|
52
|
+
windowed: bool = False
|
|
53
|
+
sign: bool = False # Authenticode 签名(仅 exe 格式生效)
|
|
54
|
+
sign_cert: str = "" # 签名证书 PEM 路径(空 = 自动自签)
|
|
55
|
+
sign_key: str = "" # 签名私钥 PEM 路径
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def target_fmt(self) -> str:
|
|
59
|
+
return self.fmt or DEFAULT_FORMAT.get(self.platform, "dir")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def spec_from_project(
|
|
63
|
+
project_dir: Path,
|
|
64
|
+
logger: logging.Logger,
|
|
65
|
+
overrides: Optional[dict] = None,
|
|
66
|
+
) -> BuildSpec:
|
|
67
|
+
cfg = app_config(project_dir, overrides)
|
|
68
|
+
reqs = list(cfg.get("requirements") or [])
|
|
69
|
+
reqs += load_requirements(project_dir)
|
|
70
|
+
if overrides and overrides.get("requirements"):
|
|
71
|
+
reqs += list(overrides["requirements"])
|
|
72
|
+
return BuildSpec(
|
|
73
|
+
project_dir=project_dir,
|
|
74
|
+
name=cfg["name"],
|
|
75
|
+
entry=cfg["entry"],
|
|
76
|
+
version=cfg["version"],
|
|
77
|
+
requirements=reqs,
|
|
78
|
+
platform=cfg.get("platform", "linux"),
|
|
79
|
+
arch=cfg.get("arch", "x86_64"),
|
|
80
|
+
python=cfg.get("python", "3.12"),
|
|
81
|
+
fmt=cfg.get("fmt", ""),
|
|
82
|
+
output=Path(cfg.get("output", "dist")),
|
|
83
|
+
engine=cfg.get("engine", "zipapp"),
|
|
84
|
+
windowed=bool(cfg.get("windowed", False)),
|
|
85
|
+
sign=bool(cfg.get("sign", False)),
|
|
86
|
+
sign_cert=str(cfg.get("sign_cert", "")),
|
|
87
|
+
sign_key=str(cfg.get("sign_key", "")),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build(spec: BuildSpec, logger: logging.Logger) -> List[Path]:
|
|
92
|
+
"""执行打包,返回产物文件/目录列表。"""
|
|
93
|
+
if spec.platform not in PLATFORM_FORMATS:
|
|
94
|
+
raise ValueError(f"不支持的平台: {spec.platform}")
|
|
95
|
+
if spec.target_fmt not in PLATFORM_FORMATS[spec.platform]:
|
|
96
|
+
raise ValueError(
|
|
97
|
+
f"平台 {spec.platform} 不支持格式 {spec.target_fmt},"
|
|
98
|
+
f"可用: {', '.join(PLATFORM_FORMATS[spec.platform])}"
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
entry = (spec.project_dir / spec.entry).resolve()
|
|
102
|
+
if not entry.exists():
|
|
103
|
+
raise FileNotFoundError(f"入口脚本不存在: {entry}")
|
|
104
|
+
|
|
105
|
+
logger.info("=" * 60)
|
|
106
|
+
logger.info(
|
|
107
|
+
"Pythub 开始打包: %s -> %s (%s/%s, Python %s, 引擎 %s)",
|
|
108
|
+
spec.name, spec.target_fmt, spec.platform, spec.arch, spec.python, spec.engine,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# nexe 只能在本机平台+架构生成;架构与本机不符时自动改用本机架构
|
|
112
|
+
# (而非直接报错),Apple Silicon 默认配置也可直接打包。必须在运行时
|
|
113
|
+
# 下载之前解析,保证内嵌解释器与引导器架构一致。
|
|
114
|
+
if spec.target_fmt == "nexe":
|
|
115
|
+
host_arch = formats.native_host_arch()
|
|
116
|
+
if spec.arch != host_arch:
|
|
117
|
+
logger.warning(
|
|
118
|
+
"nexe 仅支持本机架构(本机: %s),已自动改用(原目标: %s)",
|
|
119
|
+
host_arch, spec.arch,
|
|
120
|
+
)
|
|
121
|
+
spec.arch = host_arch
|
|
122
|
+
|
|
123
|
+
if spec.engine == "pyinstaller":
|
|
124
|
+
from pythub.native_builder import build_native
|
|
125
|
+
return build_native(spec, logger)
|
|
126
|
+
|
|
127
|
+
return _build_zipapp(spec, entry, logger)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---------------------------------------------------------------- zipapp 引擎
|
|
131
|
+
|
|
132
|
+
def _build_zipapp(spec: BuildSpec, entry: Path, logger: logging.Logger) -> List[Path]:
|
|
133
|
+
with temp_dir(f"pythub-{spec.name}-") as td:
|
|
134
|
+
work = Path(td)
|
|
135
|
+
|
|
136
|
+
# 1. 依赖分析
|
|
137
|
+
logger.info("[1/6] 分析依赖...")
|
|
138
|
+
info = analyze(entry, spec.project_dir)
|
|
139
|
+
logger.info(
|
|
140
|
+
" 标准库模块 %d 个,第三方模块 %d 个",
|
|
141
|
+
len(info["stdlib"]), len(info["thirdparty_modules"]),
|
|
142
|
+
)
|
|
143
|
+
if info["unresolved"]:
|
|
144
|
+
logger.warning(
|
|
145
|
+
" 未能映射为发行包的模块(如需打包请写入 requirements.txt): %s",
|
|
146
|
+
", ".join(info["unresolved"]),
|
|
147
|
+
)
|
|
148
|
+
reqs = list(dict.fromkeys(
|
|
149
|
+
(spec.requirements or []) + info["thirdparty_packages"]
|
|
150
|
+
))
|
|
151
|
+
|
|
152
|
+
# 2. 下载目标平台依赖 wheel(按目标平台过滤组件)
|
|
153
|
+
wheels: List[Path] = []
|
|
154
|
+
if reqs:
|
|
155
|
+
logger.info("[2/6] 下载目标平台第三方组件...")
|
|
156
|
+
wheels = download_wheels(
|
|
157
|
+
reqs, spec.platform, spec.arch, spec.python, work / "wheels", logger
|
|
158
|
+
)
|
|
159
|
+
unpack_wheels(wheels, work / "lib")
|
|
160
|
+
logger.info(" 已集成 %d 个 wheel", len(wheels))
|
|
161
|
+
else:
|
|
162
|
+
logger.info("[2/6] 无第三方依赖,跳过")
|
|
163
|
+
|
|
164
|
+
# 3. 获取目标平台嵌入式 Python 运行时
|
|
165
|
+
logger.info("[3/6] 准备目标平台嵌入式 Python 运行时...")
|
|
166
|
+
runtime = fetch_runtime(spec.platform, spec.arch, spec.python, logger)
|
|
167
|
+
_check_interpreter(runtime, spec.platform)
|
|
168
|
+
|
|
169
|
+
# 4. 生成 app.pyz
|
|
170
|
+
logger.info("[4/6] 组装 app.pyz(源码 + 组件库 + 自举)...")
|
|
171
|
+
pyz = work / "app.pyz"
|
|
172
|
+
_build_pyz(spec, entry, work / "lib" if (work / "lib").exists() else None, pyz)
|
|
173
|
+
|
|
174
|
+
# 5. 组装目标产物
|
|
175
|
+
logger.info("[5/6] 组装平台产物 (%s) ...", spec.target_fmt)
|
|
176
|
+
artifacts = _assemble(spec, runtime, pyz, work, logger)
|
|
177
|
+
|
|
178
|
+
# 6. 完成
|
|
179
|
+
logger.info("[6/6] 打包完成:")
|
|
180
|
+
for a in artifacts:
|
|
181
|
+
logger.info(" -> %s", a)
|
|
182
|
+
return artifacts
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _check_interpreter(runtime: Path, platform: str) -> None:
|
|
186
|
+
py = interpreter_path(runtime, platform)
|
|
187
|
+
if not py.exists():
|
|
188
|
+
raise RuntimeError(f"运行时解释器缺失: {py}")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _build_pyz(spec: BuildSpec, entry: Path, lib_dir: Optional[Path], pyz: Path) -> None:
|
|
192
|
+
"""生成 zipapp:项目源码 + lib/ + 自举 __main__.py。"""
|
|
193
|
+
entry_rel = str(Path(spec.entry).as_posix())
|
|
194
|
+
# 项目目录本身是包(含 __init__.py)时,按 "<包名>/" 前缀布局打包,
|
|
195
|
+
# 使包内 `import <包名>` 绝对导入可用(如用 pythub 打包 pythub 自身)
|
|
196
|
+
pkg_prefix = ""
|
|
197
|
+
if (spec.project_dir / "__init__.py").is_file():
|
|
198
|
+
pkg_prefix = spec.project_dir.name
|
|
199
|
+
if not entry_rel.startswith(pkg_prefix + "/"):
|
|
200
|
+
entry_rel = f"{pkg_prefix}/{entry_rel}"
|
|
201
|
+
elif entry_rel == "__main__.py":
|
|
202
|
+
# 入口名与自举脚本冲突:改存 __entry__.py,避免自举覆盖入口造成自我递归
|
|
203
|
+
entry_rel = "__entry__.py"
|
|
204
|
+
bootstrap = f'''\
|
|
205
|
+
import os, sys, runpy
|
|
206
|
+
|
|
207
|
+
_zp = os.path.dirname(os.path.abspath(__file__))
|
|
208
|
+
_entry = {entry_rel!r}
|
|
209
|
+
_lib = os.path.join(_zp, "lib")
|
|
210
|
+
sys.path.insert(0, _zp)
|
|
211
|
+
|
|
212
|
+
if os.path.isfile(_zp):
|
|
213
|
+
# pyz 单文件模式
|
|
214
|
+
import zipfile
|
|
215
|
+
has_bin = False
|
|
216
|
+
try:
|
|
217
|
+
with zipfile.ZipFile(_zp) as _z:
|
|
218
|
+
for _n in _z.namelist():
|
|
219
|
+
if _n.startswith("lib/") and (_n.endswith(".so") or ".so." in _n or _n.endswith(".pyd")):
|
|
220
|
+
has_bin = True
|
|
221
|
+
break
|
|
222
|
+
except OSError:
|
|
223
|
+
pass
|
|
224
|
+
if has_bin:
|
|
225
|
+
# 含二进制扩展,解包到缓存目录后再导入
|
|
226
|
+
cache = os.path.join(os.path.expanduser("~"), ".cache", "pythub", "pyzlib",
|
|
227
|
+
hashlib.md5((_zp + str(os.path.getmtime(_zp))).encode()).hexdigest())
|
|
228
|
+
if not os.path.isdir(cache):
|
|
229
|
+
os.makedirs(cache, exist_ok=True)
|
|
230
|
+
with zipfile.ZipFile(_zp) as _z:
|
|
231
|
+
_z.extractall(cache)
|
|
232
|
+
_lib = os.path.join(cache, "lib")
|
|
233
|
+
sys.path.insert(0, _lib)
|
|
234
|
+
with zipfile.ZipFile(_zp) as _z:
|
|
235
|
+
_src = _z.read(_entry).decode("utf-8")
|
|
236
|
+
_g = {{"__name__": "__main__", "__file__": os.path.join(_zp, _entry)}}
|
|
237
|
+
exec(compile(_src, _entry, "exec"), _g)
|
|
238
|
+
else:
|
|
239
|
+
# 目录模式
|
|
240
|
+
if os.path.isdir(_lib):
|
|
241
|
+
sys.path.insert(0, _lib)
|
|
242
|
+
runpy.run_path(os.path.join(_zp, _entry), run_name="__main__")
|
|
243
|
+
'''
|
|
244
|
+
# 注意: 单文件模式里用到了 hashlib,统一顶部导入
|
|
245
|
+
bootstrap = bootstrap.replace("import os, sys, runpy", "import os, sys, runpy, hashlib")
|
|
246
|
+
|
|
247
|
+
files: List[Tuple[str, object, bool]] = []
|
|
248
|
+
for rel in _project_files(spec.project_dir):
|
|
249
|
+
arc = rel.as_posix()
|
|
250
|
+
if pkg_prefix:
|
|
251
|
+
arc = f"{pkg_prefix}/{arc}"
|
|
252
|
+
if arc == "__main__.py":
|
|
253
|
+
arc = "__entry__.py" # 避免覆盖自举 __main__.py
|
|
254
|
+
files.append((arc, spec.project_dir / rel, False))
|
|
255
|
+
if lib_dir:
|
|
256
|
+
for root, dirs, fnames in os.walk(lib_dir):
|
|
257
|
+
rel_root = Path(root).relative_to(lib_dir)
|
|
258
|
+
dirs[:] = [d for d in dirs if d != "__pycache__"]
|
|
259
|
+
for fn in fnames:
|
|
260
|
+
p = Path(root) / fn
|
|
261
|
+
arc = (Path("lib") / rel_root / fn).as_posix()
|
|
262
|
+
files.append((arc, p, False))
|
|
263
|
+
files.append(("__main__.py", bootstrap.encode("utf-8"), False))
|
|
264
|
+
|
|
265
|
+
pyz.parent.mkdir(parents=True, exist_ok=True)
|
|
266
|
+
with open(pyz, "wb") as f:
|
|
267
|
+
f.write(b"#!/usr/bin/env python3\n") # zipapp 惯例头
|
|
268
|
+
with zipfile.ZipFile(f, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
269
|
+
for arcname, source, _exe in files:
|
|
270
|
+
zi = zipfile.ZipInfo(str(arcname), date_time=(1980, 1, 1, 0, 0, 0))
|
|
271
|
+
zi.external_attr = 0o644 << 16
|
|
272
|
+
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
273
|
+
if isinstance(source, Path):
|
|
274
|
+
with open(source, "rb") as src:
|
|
275
|
+
zf.writestr(zi, src.read())
|
|
276
|
+
else:
|
|
277
|
+
zf.writestr(zi, source)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _project_files(project_dir: Path) -> List[Path]:
|
|
281
|
+
result = []
|
|
282
|
+
for root, dirs, fnames in os.walk(project_dir):
|
|
283
|
+
rel_root = Path(root).relative_to(project_dir)
|
|
284
|
+
dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS and not d.startswith("*.egg-info")]
|
|
285
|
+
dirs[:] = [d for d in dirs if not d.endswith(".egg-info")]
|
|
286
|
+
for fn in fnames:
|
|
287
|
+
if fn.endswith(tuple(EXCLUDE_SUFFIXES)):
|
|
288
|
+
continue
|
|
289
|
+
if fn == "pythub.toml" and rel_root == Path("."):
|
|
290
|
+
continue
|
|
291
|
+
result.append(rel_root / fn)
|
|
292
|
+
return result
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ---------------------------------------------------------------- 产物组装
|
|
296
|
+
|
|
297
|
+
def _assemble(
|
|
298
|
+
spec: BuildSpec,
|
|
299
|
+
runtime: Path,
|
|
300
|
+
pyz: Path,
|
|
301
|
+
work: Path,
|
|
302
|
+
logger: logging.Logger,
|
|
303
|
+
) -> List[Path]:
|
|
304
|
+
fmt = spec.target_fmt
|
|
305
|
+
arch = spec.arch # nexe 架构已在 build() 阶段解析为本机架构
|
|
306
|
+
out_root = spec.output / f"{spec.name}-{spec.python}-{spec.platform}-{arch}"
|
|
307
|
+
out_root.mkdir(parents=True, exist_ok=True)
|
|
308
|
+
artifacts: List[Path] = []
|
|
309
|
+
|
|
310
|
+
if fmt == "pyz":
|
|
311
|
+
dest = out_root / f"{spec.name}-{spec.python}-{spec.platform}-{spec.arch}.pyz"
|
|
312
|
+
shutil.copy2(pyz, dest)
|
|
313
|
+
set_executable(dest)
|
|
314
|
+
return [dest]
|
|
315
|
+
|
|
316
|
+
# 需要 runtime 的格式:先组装自包含目录
|
|
317
|
+
bundle = work / "bundle" / spec.name
|
|
318
|
+
bundle.mkdir(parents=True)
|
|
319
|
+
shutil.copy2(pyz, bundle / "app.pyz")
|
|
320
|
+
# 保留符号链接(bin/python3 -> python3.12 等):归档/压缩包按链接存储,
|
|
321
|
+
# 避免目标文件被重复打包;Windows runtime 无符号链接,不受影响
|
|
322
|
+
shutil.copytree(runtime, bundle / "runtime", symlinks=True)
|
|
323
|
+
|
|
324
|
+
if spec.platform == "windows":
|
|
325
|
+
launcher = bundle / f"{spec.name}.cmd"
|
|
326
|
+
launcher.write_text(formats.windows_launcher(spec.name), encoding="utf-8", newline="\r\n")
|
|
327
|
+
else:
|
|
328
|
+
launcher = bundle / spec.name
|
|
329
|
+
launcher.write_text(
|
|
330
|
+
formats.unix_launcher(spec.name, "runtime/bin/python3", "app.pyz"),
|
|
331
|
+
encoding="utf-8", newline="\n",
|
|
332
|
+
)
|
|
333
|
+
set_executable(launcher)
|
|
334
|
+
|
|
335
|
+
if fmt == "dir":
|
|
336
|
+
dest = out_root / spec.name
|
|
337
|
+
if dest.exists():
|
|
338
|
+
shutil.rmtree(dest)
|
|
339
|
+
shutil.copytree(bundle, dest, symlinks=True)
|
|
340
|
+
return [dest]
|
|
341
|
+
|
|
342
|
+
if fmt == "exe.zip":
|
|
343
|
+
dest = out_root / f"{spec.name}.exe.zip"
|
|
344
|
+
if dest.exists():
|
|
345
|
+
dest.unlink()
|
|
346
|
+
return [formats.make_exe_zip(bundle, dest)]
|
|
347
|
+
|
|
348
|
+
if fmt == "exe":
|
|
349
|
+
dest = out_root / f"{spec.name}.exe"
|
|
350
|
+
if dest.exists():
|
|
351
|
+
dest.unlink()
|
|
352
|
+
artifact = formats.make_exe(bundle, dest, spec.arch, spec.python, logger,
|
|
353
|
+
console=not spec.windowed, app_name=spec.name)
|
|
354
|
+
if spec.sign:
|
|
355
|
+
from pythub.signing import sign_pe
|
|
356
|
+
|
|
357
|
+
artifact = sign_pe(
|
|
358
|
+
artifact,
|
|
359
|
+
cert=Path(spec.sign_cert) if spec.sign_cert else None,
|
|
360
|
+
key=Path(spec.sign_key) if spec.sign_key else None,
|
|
361
|
+
logger=logger,
|
|
362
|
+
)
|
|
363
|
+
return [artifact]
|
|
364
|
+
|
|
365
|
+
if fmt == "nexe":
|
|
366
|
+
dest = out_root / f"{spec.name}.nexe"
|
|
367
|
+
if dest.exists():
|
|
368
|
+
dest.unlink()
|
|
369
|
+
return [formats.make_native_exe(bundle, dest, spec.platform, arch,
|
|
370
|
+
spec.python, logger,
|
|
371
|
+
console=not spec.windowed,
|
|
372
|
+
app_name=spec.name)]
|
|
373
|
+
|
|
374
|
+
if fmt == "tar.gz":
|
|
375
|
+
dest = out_root / f"{spec.name}-{spec.platform}-{spec.arch}.tar.gz"
|
|
376
|
+
if dest.exists():
|
|
377
|
+
dest.unlink()
|
|
378
|
+
make_tar_gz(dest, bundle)
|
|
379
|
+
return [dest]
|
|
380
|
+
|
|
381
|
+
if fmt == "run":
|
|
382
|
+
dest = out_root / f"{spec.name}.run"
|
|
383
|
+
if dest.exists():
|
|
384
|
+
dest.unlink()
|
|
385
|
+
return [formats.make_run(bundle, dest, spec.name)]
|
|
386
|
+
|
|
387
|
+
if spec.platform == "macos":
|
|
388
|
+
staging = work / "stage"
|
|
389
|
+
staging.mkdir(parents=True)
|
|
390
|
+
app = formats.build_app_bundle(staging, spec.name, spec.version, runtime, pyz, logger)
|
|
391
|
+
if fmt == "app":
|
|
392
|
+
dest = out_root / app.name
|
|
393
|
+
if dest.exists():
|
|
394
|
+
shutil.rmtree(dest)
|
|
395
|
+
shutil.copytree(app, dest, symlinks=True)
|
|
396
|
+
return [dest]
|
|
397
|
+
if fmt == "dmg":
|
|
398
|
+
dest = out_root / f"{spec.name}.dmg"
|
|
399
|
+
if dest.exists():
|
|
400
|
+
dest.unlink()
|
|
401
|
+
return [formats.make_dmg(staging, dest, spec.name)]
|
|
402
|
+
if fmt == "pkg":
|
|
403
|
+
dest = out_root / f"{spec.name}-{spec.version}.pkg"
|
|
404
|
+
if dest.exists():
|
|
405
|
+
dest.unlink()
|
|
406
|
+
return [formats.make_pkg(staging, dest, spec.name, spec.version)]
|
|
407
|
+
|
|
408
|
+
if fmt == "appimage" and spec.platform == "linux":
|
|
409
|
+
dest = out_root / f"{spec.name}-{spec.arch}.AppImage"
|
|
410
|
+
if dest.exists():
|
|
411
|
+
dest.unlink()
|
|
412
|
+
result = formats.make_appimage(work / "stage", dest, spec.name, runtime, pyz, logger)
|
|
413
|
+
if result:
|
|
414
|
+
return [result]
|
|
415
|
+
logger.warning("未找到 appimagetool,降级为单文件 .run(自解压可执行,无需任何工具)。")
|
|
416
|
+
dest = out_root / f"{spec.name}.run"
|
|
417
|
+
if dest.exists():
|
|
418
|
+
dest.unlink()
|
|
419
|
+
return [formats.make_run(bundle, dest, spec.name)]
|
|
420
|
+
|
|
421
|
+
raise ValueError(f"格式 {fmt} 不适用于平台 {spec.platform}")
|