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
pythub/signing.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Authenticode 交叉签名(需求 14): 基于 osslsigncode 给 Windows .exe 附加
|
|
2
|
+
数字签名;未提供证书时可用 openssl 自动生成自签名证书。
|
|
3
|
+
|
|
4
|
+
说明:
|
|
5
|
+
- 自签名证书可减少部分杀软误报,但不会获得系统信任;正式分发请使用受信
|
|
6
|
+
代码签名证书(或配合 -t 时间戳服务)。
|
|
7
|
+
- 仅标准库实现;osslsigncode / openssl 为可选外部依赖,仅在启用签名时需要。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Optional, Tuple
|
|
16
|
+
|
|
17
|
+
from pythub.utils import PYTHUB_CACHE_DIR, find_executable
|
|
18
|
+
|
|
19
|
+
CERT_DIR = PYTHUB_CACHE_DIR / "certs"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def find_sign_tool() -> str:
|
|
23
|
+
"""定位 osslsigncode,缺失时给出安装指引。"""
|
|
24
|
+
tool = find_executable("osslsigncode")
|
|
25
|
+
if not tool:
|
|
26
|
+
raise RuntimeError(
|
|
27
|
+
"Authenticode 签名需要 osslsigncode。\n"
|
|
28
|
+
"macOS: brew install osslsigncode | Ubuntu: apt install osslsigncode"
|
|
29
|
+
)
|
|
30
|
+
return tool
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def ensure_selfsigned_cert(
|
|
34
|
+
common_name: str = "Pythub Self-Signed",
|
|
35
|
+
logger=None,
|
|
36
|
+
) -> Tuple[Path, Path]:
|
|
37
|
+
"""生成(或复用)自签名代码签名证书,缓存在 cache/pythub/certs/。"""
|
|
38
|
+
cert = CERT_DIR / "selfsigned.crt"
|
|
39
|
+
key = CERT_DIR / "selfsigned.key"
|
|
40
|
+
if cert.exists() and key.exists():
|
|
41
|
+
return cert, key
|
|
42
|
+
|
|
43
|
+
openssl = find_executable("openssl")
|
|
44
|
+
if not openssl:
|
|
45
|
+
raise RuntimeError("未找到 openssl(自动生成自签名证书需要)")
|
|
46
|
+
CERT_DIR.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
tmp_key = key.with_name(key.name + ".tmp")
|
|
48
|
+
tmp_crt = cert.with_name(cert.name + ".tmp")
|
|
49
|
+
proc = subprocess.run(
|
|
50
|
+
[openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes",
|
|
51
|
+
"-keyout", str(tmp_key), "-out", str(tmp_crt),
|
|
52
|
+
"-days", "3650",
|
|
53
|
+
"-subj", f"/CN={common_name}/O=CROGRAM"],
|
|
54
|
+
capture_output=True,
|
|
55
|
+
text=True,
|
|
56
|
+
)
|
|
57
|
+
if proc.returncode != 0:
|
|
58
|
+
raise RuntimeError(f"自签名证书生成失败:\n{proc.stderr}")
|
|
59
|
+
os.replace(tmp_key, key)
|
|
60
|
+
os.replace(tmp_crt, cert)
|
|
61
|
+
try:
|
|
62
|
+
key.chmod(0o600)
|
|
63
|
+
except OSError:
|
|
64
|
+
pass
|
|
65
|
+
if logger:
|
|
66
|
+
logger.info("已生成自签名证书: %s(正式分发请使用受信代码签名证书)", cert)
|
|
67
|
+
return cert, key
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def sign_pe(
|
|
71
|
+
target: Path,
|
|
72
|
+
cert: Optional[Path] = None,
|
|
73
|
+
key: Optional[Path] = None,
|
|
74
|
+
timestamp_url: Optional[str] = None,
|
|
75
|
+
logger=None,
|
|
76
|
+
) -> Path:
|
|
77
|
+
"""给 PE(.exe)附加 Authenticode 签名,成功后原子替换原文件。
|
|
78
|
+
|
|
79
|
+
cert/key 缺省时自动生成(复用)自签名证书;timestamp_url 提供 RFC3161
|
|
80
|
+
时间戳服务地址(可选)。"""
|
|
81
|
+
if bool(cert) != bool(key):
|
|
82
|
+
raise ValueError("sign_cert 与 sign_key 必须成对提供(或不提供以自动自签)")
|
|
83
|
+
tool = find_sign_tool()
|
|
84
|
+
if cert is None:
|
|
85
|
+
cert, key = ensure_selfsigned_cert(logger=logger)
|
|
86
|
+
|
|
87
|
+
out = target.with_name(f"{target.name}.signed.tmp")
|
|
88
|
+
cmd = [tool, "sign", "-certs", str(cert), "-key", str(key)]
|
|
89
|
+
if timestamp_url:
|
|
90
|
+
cmd += ["-t", timestamp_url]
|
|
91
|
+
# 注意: osslsigncode 2.x 对 --in/--out 双横线形式解析异常(误报
|
|
92
|
+
# "Overwriting an existing file"),必须使用单横线 -in/-out
|
|
93
|
+
cmd += ["-in", str(target), "-out", str(out)]
|
|
94
|
+
if logger:
|
|
95
|
+
logger.info("Authenticode 签名: %s%s", target,
|
|
96
|
+
f"(时间戳: {timestamp_url})" if timestamp_url else "")
|
|
97
|
+
proc = subprocess.run(cmd, capture_output=True, text=True)
|
|
98
|
+
if proc.returncode != 0 or not out.exists():
|
|
99
|
+
Path(out).unlink(missing_ok=True)
|
|
100
|
+
raise RuntimeError(
|
|
101
|
+
f"osslsigncode 签名失败:\n{proc.stderr or proc.stdout}".strip()
|
|
102
|
+
)
|
|
103
|
+
os.replace(out, target)
|
|
104
|
+
return target
|
pythub/utils.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""通用工具:日志、下载、压缩、文件操作。仅使用标准库实现。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import sys
|
|
11
|
+
import tarfile
|
|
12
|
+
import tempfile
|
|
13
|
+
import urllib.request
|
|
14
|
+
import zipfile
|
|
15
|
+
from pathlib import Path, PurePosixPath
|
|
16
|
+
from typing import Callable, Iterable, List, Optional
|
|
17
|
+
|
|
18
|
+
PYTHUB_CACHE_DIR = Path(
|
|
19
|
+
os.environ.get("PYTHUB_CACHE", Path.home() / ".cache" / "pythub")
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
CHUNK_SIZE = 256 * 1024
|
|
23
|
+
|
|
24
|
+
# 持久化设置与日志落盘(需求 17/18)
|
|
25
|
+
SETTINGS_FILE = PYTHUB_CACHE_DIR / "settings.json"
|
|
26
|
+
LOG_DIR = PYTHUB_CACHE_DIR / "logs"
|
|
27
|
+
_file_handler: Optional[logging.FileHandler] = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_settings() -> dict:
|
|
31
|
+
"""读取持久化设置(cache/pythub/settings.json),缺失/损坏返回空 dict。"""
|
|
32
|
+
try:
|
|
33
|
+
return json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
|
|
34
|
+
except (OSError, ValueError):
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def save_settings(settings: dict) -> None:
|
|
39
|
+
"""原子写入设置(临时文件 + rename),避免并发/中断产生损坏的 JSON。"""
|
|
40
|
+
SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
tmp = SETTINGS_FILE.with_name(f"{SETTINGS_FILE.name}.tmp-{os.getpid()}")
|
|
42
|
+
try:
|
|
43
|
+
tmp.write_text(
|
|
44
|
+
json.dumps(settings, ensure_ascii=False, indent=2) + "\n",
|
|
45
|
+
encoding="utf-8",
|
|
46
|
+
)
|
|
47
|
+
os.replace(tmp, SETTINGS_FILE)
|
|
48
|
+
finally:
|
|
49
|
+
if tmp.exists():
|
|
50
|
+
tmp.unlink(missing_ok=True)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def log_file_path() -> Path:
|
|
54
|
+
"""当天日志文件:cache/pythub/logs/pythub-YYYYMMDD.log(按天分文件)。"""
|
|
55
|
+
return LOG_DIR / f"pythub-{datetime.date.today():%Y%m%d}.log"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def set_file_logging(enabled: bool, name: str = "pythub") -> Optional[Path]:
|
|
59
|
+
"""开关"日志落盘":给 logger 挂/摘 FileHandler,返回当前日志文件路径。
|
|
60
|
+
|
|
61
|
+
开关状态持久化到 cache/pythub/settings.json,下次启动 get_logger
|
|
62
|
+
会自动恢复;幂等,可重复调用。
|
|
63
|
+
"""
|
|
64
|
+
global _file_handler
|
|
65
|
+
logger = logging.getLogger(name)
|
|
66
|
+
if enabled:
|
|
67
|
+
if _file_handler is None:
|
|
68
|
+
path = log_file_path()
|
|
69
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
_file_handler = logging.FileHandler(path, encoding="utf-8")
|
|
71
|
+
_file_handler.setFormatter(
|
|
72
|
+
logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s")
|
|
73
|
+
)
|
|
74
|
+
logger.addHandler(_file_handler)
|
|
75
|
+
settings = load_settings()
|
|
76
|
+
settings["log_to_file"] = True
|
|
77
|
+
save_settings(settings)
|
|
78
|
+
return log_file_path()
|
|
79
|
+
if _file_handler is not None:
|
|
80
|
+
logger.removeHandler(_file_handler)
|
|
81
|
+
_file_handler.close()
|
|
82
|
+
_file_handler = None
|
|
83
|
+
settings = load_settings()
|
|
84
|
+
settings["log_to_file"] = False
|
|
85
|
+
save_settings(settings)
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ---------------- 本地构建缓存维护(需求 14: 缓存清理) ----------------
|
|
90
|
+
# 构建机缓存顶层子目录(运行时用户缓存 exe/、run/ 由引导器自管理,不在此列)
|
|
91
|
+
BUILD_CACHE_SUBDIRS = ("runtimes", "pyzlib", "bootloader")
|
|
92
|
+
|
|
93
|
+
DEFAULT_CACHE_MAX_BYTES = 4 << 30 # 4GB
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def dir_size(path: Path) -> int:
|
|
97
|
+
"""目录递归占用字节数(不跟随符号链接)。"""
|
|
98
|
+
total = 0
|
|
99
|
+
for root, dirs, files in os.walk(path):
|
|
100
|
+
dirs[:] = [d for d in dirs if not (Path(root) / d).is_symlink()]
|
|
101
|
+
for f in files:
|
|
102
|
+
fp = Path(root) / f
|
|
103
|
+
if fp.is_symlink():
|
|
104
|
+
continue
|
|
105
|
+
try:
|
|
106
|
+
total += fp.stat().st_size
|
|
107
|
+
except OSError:
|
|
108
|
+
pass
|
|
109
|
+
return total
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def cache_stats() -> dict:
|
|
113
|
+
"""构建机缓存按顶层子目录(runtimes/pyzlib/bootloader)的占用统计。"""
|
|
114
|
+
stats = {}
|
|
115
|
+
for sub in BUILD_CACHE_SUBDIRS:
|
|
116
|
+
d = PYTHUB_CACHE_DIR / sub
|
|
117
|
+
if d.exists():
|
|
118
|
+
stats[sub] = dir_size(d)
|
|
119
|
+
return stats
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def prune_cache(max_bytes: Optional[int] = None) -> List[Path]:
|
|
123
|
+
"""把构建机缓存裁剪到大小上限(LRU: 按缓存条目 mtime 从旧到新删除)。
|
|
124
|
+
|
|
125
|
+
条目 = runtimes/pyzlib/bootloader 下的各版本/md5 缓存目录;返回被删除
|
|
126
|
+
的条目路径列表。不触碰运行时用户缓存(exe/、run/,由引导器自行清理)
|
|
127
|
+
与 settings/logs。"""
|
|
128
|
+
if max_bytes is None:
|
|
129
|
+
max_bytes = DEFAULT_CACHE_MAX_BYTES
|
|
130
|
+
if max_bytes <= 0:
|
|
131
|
+
raise ValueError("max_bytes 必须为正数(防呆: 0 会清空全部缓存)")
|
|
132
|
+
entries = [] # (mtime, path, size)
|
|
133
|
+
total = 0
|
|
134
|
+
for sub in BUILD_CACHE_SUBDIRS:
|
|
135
|
+
d = PYTHUB_CACHE_DIR / sub
|
|
136
|
+
if not d.exists():
|
|
137
|
+
continue
|
|
138
|
+
for child in d.iterdir():
|
|
139
|
+
try:
|
|
140
|
+
mtime = child.stat().st_mtime
|
|
141
|
+
size = dir_size(child)
|
|
142
|
+
except OSError:
|
|
143
|
+
continue
|
|
144
|
+
entries.append((mtime, child, size))
|
|
145
|
+
total += size
|
|
146
|
+
pruned: List[Path] = []
|
|
147
|
+
for mtime, child, size in sorted(entries, key=lambda e: e[0]):
|
|
148
|
+
if total <= max_bytes:
|
|
149
|
+
break
|
|
150
|
+
shutil.rmtree(child, ignore_errors=True)
|
|
151
|
+
pruned.append(child)
|
|
152
|
+
total -= size
|
|
153
|
+
return pruned
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def get_logger(name: str = "pythub") -> logging.Logger:
|
|
157
|
+
logger = logging.getLogger(name)
|
|
158
|
+
if not logger.handlers:
|
|
159
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
160
|
+
handler.setFormatter(
|
|
161
|
+
logging.Formatter("[%(levelname).1s] %(message)s")
|
|
162
|
+
)
|
|
163
|
+
logger.addHandler(handler)
|
|
164
|
+
# 无论是否已有 handler(如 GUI 已挂载队列 handler),都确保 INFO 级别生效
|
|
165
|
+
if logger.level == logging.NOTSET or logger.level > logging.INFO:
|
|
166
|
+
logger.setLevel(logging.INFO)
|
|
167
|
+
# 日志落盘(需求 18):按持久化设置自动恢复(幂等,已挂载则跳过)
|
|
168
|
+
if _file_handler is None and load_settings().get("log_to_file"):
|
|
169
|
+
set_file_logging(True, name)
|
|
170
|
+
return logger
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ProgressLogger:
|
|
174
|
+
"""把进度回调转为日志输出(0~1)。"""
|
|
175
|
+
|
|
176
|
+
def __init__(self, logger: logging.Logger, label: str):
|
|
177
|
+
self.logger = logger
|
|
178
|
+
self.label = label
|
|
179
|
+
self._last = -1
|
|
180
|
+
|
|
181
|
+
def __call__(self, ratio: float) -> None:
|
|
182
|
+
pct = int(ratio * 100)
|
|
183
|
+
if pct != self._last and pct % 5 == 0:
|
|
184
|
+
self._last = pct
|
|
185
|
+
self.logger.info("下载 %s: %d%%", self.label, pct)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def download_file(
|
|
189
|
+
url: str,
|
|
190
|
+
dest: Path,
|
|
191
|
+
logger: Optional[logging.Logger] = None,
|
|
192
|
+
progress: Optional[Callable[[float], None]] = None,
|
|
193
|
+
) -> Path:
|
|
194
|
+
"""下载文件到指定路径,支持断点重试一次。"""
|
|
195
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
196
|
+
tmp = dest.with_suffix(dest.suffix + ".part")
|
|
197
|
+
req = urllib.request.Request(url, headers={"User-Agent": "pythub/0.1"})
|
|
198
|
+
|
|
199
|
+
for attempt in (1, 2):
|
|
200
|
+
try:
|
|
201
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
202
|
+
total = int(resp.headers.get("Content-Length") or 0)
|
|
203
|
+
done = 0
|
|
204
|
+
with open(tmp, "wb") as f:
|
|
205
|
+
while True:
|
|
206
|
+
chunk = resp.read(CHUNK_SIZE)
|
|
207
|
+
if not chunk:
|
|
208
|
+
break
|
|
209
|
+
f.write(chunk)
|
|
210
|
+
done += len(chunk)
|
|
211
|
+
if progress and total:
|
|
212
|
+
progress(done / total)
|
|
213
|
+
tmp.replace(dest)
|
|
214
|
+
return dest
|
|
215
|
+
except Exception as e: # noqa: BLE001
|
|
216
|
+
if attempt == 2:
|
|
217
|
+
tmp.unlink(missing_ok=True)
|
|
218
|
+
raise RuntimeError(f"下载失败: {url}\n{e}") from e
|
|
219
|
+
if logger:
|
|
220
|
+
logger.warning("下载中断,重试: %s (%s)", url, e)
|
|
221
|
+
raise RuntimeError("unreachable")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def is_frozen_unix_executable(path: Path) -> bool:
|
|
225
|
+
"""pyz/app 内的启动器需要可执行权限。"""
|
|
226
|
+
return path.suffix in {"", ".sh", ".pyz", ".AppImage", ".app"}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def set_executable(path: Path) -> None:
|
|
230
|
+
try:
|
|
231
|
+
path.chmod(0o755)
|
|
232
|
+
except OSError:
|
|
233
|
+
pass
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def make_executable_script(path: Path, content: str) -> None:
|
|
237
|
+
path.write_text(content, encoding="utf-8", newline="\n")
|
|
238
|
+
set_executable(path)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def copy_tree(
|
|
242
|
+
src: Path,
|
|
243
|
+
dest: Path,
|
|
244
|
+
exclude_dirs: Optional[Iterable[str]] = None,
|
|
245
|
+
exclude_suffixes: Optional[Iterable[str]] = None,
|
|
246
|
+
) -> None:
|
|
247
|
+
"""复制目录树,忽略常见垃圾目录。"""
|
|
248
|
+
exclude_dirs = set(exclude_dirs or [])
|
|
249
|
+
exclude_suffixes = set(exclude_suffixes or [])
|
|
250
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
251
|
+
for root, dirs, files in os.walk(src):
|
|
252
|
+
rel_root = Path(root).relative_to(src)
|
|
253
|
+
dirs[:] = [
|
|
254
|
+
d
|
|
255
|
+
for d in dirs
|
|
256
|
+
if d not in exclude_dirs and d != "__pycache__"
|
|
257
|
+
]
|
|
258
|
+
for d in dirs:
|
|
259
|
+
(dest / rel_root / d).mkdir(parents=True, exist_ok=True)
|
|
260
|
+
for fn in files:
|
|
261
|
+
if any(fn.endswith(s) for s in exclude_suffixes):
|
|
262
|
+
continue
|
|
263
|
+
shutil.copy2(Path(root) / fn, dest / rel_root / fn)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def make_zip(zip_path: Path, files: List[tuple]) -> None:
|
|
267
|
+
"""files: [(arcname, Path_or_bytes, is_executable)]"""
|
|
268
|
+
zip_path.parent.mkdir(parents=True, exist_ok=True)
|
|
269
|
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
270
|
+
for arcname, source, executable in files:
|
|
271
|
+
zi = zipfile.ZipInfo(str(arcname))
|
|
272
|
+
zi.external_attr = ((0o755 if executable else 0o644) << 16)
|
|
273
|
+
zi.compress_type = zipfile.ZIP_DEFLATED
|
|
274
|
+
if isinstance(source, Path):
|
|
275
|
+
zi.date_time = (1980, 1, 1, 0, 0, 0)
|
|
276
|
+
with open(source, "rb") as f:
|
|
277
|
+
zf.writestr(zi, f.read())
|
|
278
|
+
else:
|
|
279
|
+
zi.date_time = (1980, 1, 1, 0, 0, 0)
|
|
280
|
+
zf.writestr(zi, source)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def make_tar_gz(tar_path: Path, src_dir: Path) -> None:
|
|
284
|
+
tar_path.parent.mkdir(parents=True, exist_ok=True)
|
|
285
|
+
with tarfile.open(tar_path, "w:gz") as tf:
|
|
286
|
+
tf.add(src_dir, arcname=src_dir.name)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def safe_extract(archive: Path, dest: Path) -> None:
|
|
290
|
+
"""安全解压 zip/tar(防路径穿越)。"""
|
|
291
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
292
|
+
if archive.suffix == ".zip":
|
|
293
|
+
with zipfile.ZipFile(archive) as zf:
|
|
294
|
+
_check_members(zf.namelist())
|
|
295
|
+
zf.extractall(dest)
|
|
296
|
+
elif archive.name.endswith((".tar.gz", ".tgz")):
|
|
297
|
+
with tarfile.open(archive) as tf:
|
|
298
|
+
_check_members(tf.getnames())
|
|
299
|
+
tf.extractall(dest)
|
|
300
|
+
else:
|
|
301
|
+
raise ValueError(f"不支持的压缩格式: {archive}")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _check_members(names: Iterable[str]) -> None:
|
|
305
|
+
for name in names:
|
|
306
|
+
p = PurePosixPath(name)
|
|
307
|
+
if p.is_absolute() or ".." in p.parts:
|
|
308
|
+
raise ValueError(f"压缩包内包含不安全路径: {name}")
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def zip_dir(zip_path: Path, src_dir: Path) -> None:
|
|
312
|
+
files: List[tuple] = []
|
|
313
|
+
for root, dirs, fnames in os.walk(src_dir):
|
|
314
|
+
rel = Path(root).relative_to(src_dir)
|
|
315
|
+
dirs[:] = [d for d in dirs if d != "__pycache__"]
|
|
316
|
+
for fn in fnames:
|
|
317
|
+
p = Path(root) / fn
|
|
318
|
+
arc = src_dir.name / rel / fn
|
|
319
|
+
exe = os.access(p, os.X_OK) and not fn.endswith((".py", ".txt", ".json"))
|
|
320
|
+
files.append((str(arc), p, exe))
|
|
321
|
+
make_zip(zip_path, files)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def find_executable(name: str) -> Optional[str]:
|
|
325
|
+
"""在 PATH 中查找可执行文件。"""
|
|
326
|
+
return shutil.which(name)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def temp_dir(prefix: str = "pythub-") -> tempfile.TemporaryDirectory:
|
|
330
|
+
return tempfile.TemporaryDirectory(prefix=prefix)
|