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.
pythub/cli.py ADDED
@@ -0,0 +1,348 @@
1
+ """Pythub 命令行入口。
2
+
3
+ 用法:
4
+ pythub build <项目目录> [-p 平台...] [-f 格式...] [--arch] [--py] [-o 输出目录]
5
+ pythub gui
6
+ pythub init [目录]
7
+ pythub analyze <项目目录>
8
+ pythub formats
9
+ pythub pypa build <项目目录> [-o dist]
10
+ pythub pypa publish <文件...> [--repo pypi|testpypi] [--token ...]
11
+ pythub cache [--prune] [--max-mb N]
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import List, Optional
20
+
21
+ from pythub import DEFAULT_FORMAT, PLATFORM_FORMATS, SUPPORTED_ARCHS, SUPPORTED_PYTHON, __version__
22
+ from pythub.utils import get_logger
23
+
24
+
25
+ def _parse_targets(values: List[str], valid, kind: str) -> List[str]:
26
+ result = []
27
+ for v in values:
28
+ if v == "all":
29
+ result.extend(valid)
30
+ else:
31
+ if v not in valid:
32
+ raise SystemExit(f"不支持的{kind}: {v}(可选: {', '.join(valid)})")
33
+ result.append(v)
34
+ return list(dict.fromkeys(result)) or list(valid)
35
+
36
+
37
+ def cmd_build(args) -> int:
38
+ from pythub.builder import build, spec_from_project
39
+
40
+ logger = get_logger()
41
+ project_dir = Path(args.path).resolve()
42
+ if not project_dir.exists():
43
+ raise SystemExit(f"项目目录不存在: {project_dir}")
44
+
45
+ platforms = _parse_targets(args.platform, PLATFORM_FORMATS.keys(), "目标平台")
46
+ fmts = args.format or []
47
+ if not fmts or fmts == ["auto"]:
48
+ fmts = [DEFAULT_FORMAT[p] for p in platforms]
49
+ else:
50
+ fmts = _parse_targets(fmts, [f for p in platforms for f in PLATFORM_FORMATS[p]], "输出格式")
51
+
52
+ overrides = {
53
+ "name": args.name,
54
+ "entry": args.entry,
55
+ "python": args.python,
56
+ "arch": args.arch,
57
+ "requirements": args.requirement,
58
+ "output": args.output,
59
+ "engine": args.engine,
60
+ "windowed": args.windowed,
61
+ }
62
+
63
+ total = 0
64
+ for p in platforms:
65
+ for f in fmts:
66
+ if f not in PLATFORM_FORMATS[p]:
67
+ continue
68
+ spec = spec_from_project(project_dir, logger, overrides)
69
+ spec.platform = p
70
+ spec.arch = args.arch or spec.arch
71
+ spec.python = args.python or spec.python
72
+ spec.fmt = f
73
+ spec.output = Path(args.output or "dist").resolve()
74
+ if args.sign:
75
+ spec.sign = True
76
+ if args.sign_cert:
77
+ spec.sign_cert = args.sign_cert
78
+ if args.sign_key:
79
+ spec.sign_key = args.sign_key
80
+ artifacts = build(spec, logger)
81
+ total += len(artifacts)
82
+ logger.info("共生成 %d 个产物。", total)
83
+ return 0
84
+
85
+
86
+ def cmd_gui(_args) -> int:
87
+ from pythub.gui import run
88
+
89
+ return run()
90
+
91
+
92
+ def cmd_init(args) -> int:
93
+ base = Path(args.directory or ".").resolve() / "hello_app"
94
+ base.mkdir(parents=True, exist_ok=True)
95
+ (base / "main.py").write_text(_EXAMPLE_MAIN, encoding="utf-8")
96
+ (base / "pythub.toml").write_text(_EXAMPLE_TOML, encoding="utf-8")
97
+ print(f"示例工程已创建: {base}")
98
+ print(f"试试: pythub build {base} -p all")
99
+ return 0
100
+
101
+
102
+ def cmd_analyze(args) -> int:
103
+ from pythub.analyzer import analyze
104
+
105
+ project_dir = Path(args.path).resolve()
106
+ cfg_dir = project_dir if project_dir.is_dir() else project_dir.parent
107
+ entry = project_dir if project_dir.is_file() else cfg_dir / "main.py"
108
+ from pythub.config import app_config
109
+
110
+ cfg = app_config(cfg_dir)
111
+ if entry.is_file() is False:
112
+ entry = cfg_dir / cfg["entry"]
113
+ info = analyze(entry, cfg_dir)
114
+ print("导入的模块:")
115
+ print(" 标准库 :", ", ".join(info["stdlib"]) or "-")
116
+ print(" 第三方 :", ", ".join(info["thirdparty_modules"]) or "-")
117
+ print(" 发行包 :", ", ".join(info["thirdparty_packages"]) or "-")
118
+ if info["unresolved"]:
119
+ print(" 未映射 :", ", ".join(info["unresolved"]),
120
+ "(如需打包,请加入 requirements.txt)")
121
+ return 0
122
+
123
+
124
+ def cmd_formats(_args) -> int:
125
+ cur = None
126
+ try:
127
+ from pythub.runtime import current_platform
128
+
129
+ cur = current_platform()
130
+ except Exception:
131
+ pass
132
+ print("各平台可用输出格式(✱ 为默认格式):")
133
+ for p, fmts in PLATFORM_FORMATS.items():
134
+ mark = "(当前平台)" if p == cur else ""
135
+ print(f" {p}{mark}: " + ", ".join(f"{f}{'✱' if f == DEFAULT_FORMAT[p] else ''}" for f in fmts))
136
+ print("支持架构:", ", ".join(SUPPORTED_ARCHS))
137
+ print("支持 Python 版本:", ", ".join(SUPPORTED_PYTHON))
138
+ return 0
139
+
140
+
141
+ def cmd_pypa(args) -> int:
142
+ from pythub.pypa import build_package, publish
143
+
144
+ logger = get_logger()
145
+ if args.pypa_cmd == "build":
146
+ project_dir = Path(args.path).resolve()
147
+ if not project_dir.exists():
148
+ raise SystemExit(f"项目目录不存在: {project_dir}")
149
+ out = Path(args.output or "dist").resolve()
150
+ artifacts = build_package(project_dir, out, logger)
151
+ print("发行包已生成:")
152
+ for a in artifacts:
153
+ print(f" {a}")
154
+ print(f"发布: pythub pypa publish {out}/*.whl --token <pypi-token>")
155
+ return 0
156
+ if args.pypa_cmd == "publish":
157
+ files = [Path(f) for f in args.files]
158
+ for f in files:
159
+ if not f.exists():
160
+ raise SystemExit(f"文件不存在: {f}")
161
+ token = args.token
162
+ if not token:
163
+ import getpass
164
+
165
+ token = getpass.getpass("PyPI API Token (pypi-...): ").strip()
166
+ publish(files, token, args.repo, logger)
167
+ return 0
168
+ raise SystemExit("pypa 子命令: build / publish")
169
+
170
+
171
+ def _human(n: float) -> str:
172
+ for unit in ("B", "KB", "MB", "GB", "TB"):
173
+ if n < 1024:
174
+ return f"{int(n)} {unit}" if unit == "B" else f"{n:.1f} {unit}"
175
+ n /= 1024.0
176
+ return f"{n:.1f} PB"
177
+
178
+
179
+ def cmd_cache(args) -> int:
180
+ import json as _json
181
+
182
+ from pythub.utils import DEFAULT_CACHE_MAX_BYTES, PYTHUB_CACHE_DIR, cache_stats, prune_cache
183
+
184
+ if args.max_mb is not None and args.max_mb <= 0:
185
+ print("错误: --max-mb 必须为正整数(MB)", file=sys.stderr)
186
+ return 1
187
+
188
+ stats = cache_stats()
189
+ total = sum(stats.values())
190
+ pruned = None
191
+ if args.prune:
192
+ cap = (args.max_mb << 20) if args.max_mb else DEFAULT_CACHE_MAX_BYTES
193
+ pruned = prune_cache(cap)
194
+ if getattr(args, "json", False):
195
+ print(_json.dumps({
196
+ "dir": str(PYTHUB_CACHE_DIR),
197
+ "stats": stats,
198
+ "total_bytes": total,
199
+ "pruned": [str(p) for p in pruned] if pruned else [],
200
+ }, ensure_ascii=False, indent=2))
201
+ return 0
202
+
203
+ print(f"缓存目录: {PYTHUB_CACHE_DIR}")
204
+ for sub, size in stats.items():
205
+ print(f" {sub}: {_human(size)}")
206
+ print(f" 合计: {_human(total)}")
207
+ if args.prune:
208
+ if pruned:
209
+ print(f"已按 LRU 清理 {len(pruned)} 个缓存条目:")
210
+ for p in pruned:
211
+ print(f" - {p}")
212
+ else:
213
+ print("缓存未超上限,无需清理。")
214
+ return 0
215
+
216
+
217
+ def build_parser() -> argparse.ArgumentParser:
218
+ parser = argparse.ArgumentParser(
219
+ prog="pythub",
220
+ description="Pythub —— 开源的 Python 应用打包工具:一条命令,"
221
+ "把应用打包成免装 Python、可直接运行的产物(版权归属 CROGRAM)",
222
+ )
223
+ parser.add_argument("--version", action="version", version=f"pythub {__version__}")
224
+ sub = parser.add_subparsers(dest="cmd")
225
+
226
+ p = sub.add_parser("build", help="打包项目(支持多平台/多版本/多架构交叉打包)")
227
+ p.add_argument("path", help="项目目录(含 pythub.toml 或 main.py)")
228
+ p.add_argument("-p", "--platform", action="append", default=[],
229
+ help="目标平台: macos/linux/windows/all,可多选")
230
+ p.add_argument("-f", "--format", action="append", default=[],
231
+ help="输出格式(auto 为平台默认),可多选")
232
+ p.add_argument("--arch", default=None, help="目标架构: x86_64/aarch64")
233
+ p.add_argument("--py", "--python", dest="python", default=None,
234
+ help="目标 Python 版本: 3.10/3.11/3.12")
235
+ p.add_argument("-o", "--output", default=None, help="输出目录(默认 dist)")
236
+ p.add_argument("--name", default=None, help="应用名(默认取 pythub.toml 或目录名)")
237
+ p.add_argument("--entry", default=None, help="入口脚本(默认 main.py)")
238
+ p.add_argument("-r", "--requirement", action="append", default=[],
239
+ help="额外依赖(可多选)")
240
+ p.add_argument("--engine", default="zipapp", choices=["zipapp", "pyinstaller"],
241
+ help="打包引擎: zipapp(默认,支持交叉)/ pyinstaller(本机真二进制)")
242
+ p.add_argument("--windowed", action="store_true", help="GUI 应用(不显示控制台)")
243
+ p.add_argument("--sign", action="store_true",
244
+ help="给 .exe 附加 Authenticode 签名(需 osslsigncode;无证书时自动自签)")
245
+ p.add_argument("--sign-cert", default=None, help="签名证书 PEM 路径(配合 --sign-key)")
246
+ p.add_argument("--sign-key", default=None, help="签名私钥 PEM 路径(配合 --sign-cert)")
247
+ p.set_defaults(func=cmd_build)
248
+
249
+ p = sub.add_parser("gui", help="打开可视化操作界面")
250
+ p.set_defaults(func=cmd_gui)
251
+
252
+ p = sub.add_parser("init", help="创建示例工程")
253
+ p.add_argument("directory", nargs="?", default=None)
254
+ p.set_defaults(func=cmd_init)
255
+
256
+ p = sub.add_parser("analyze", help="分析项目依赖")
257
+ p.add_argument("path", help="项目目录或入口脚本")
258
+ p.set_defaults(func=cmd_analyze)
259
+
260
+ p = sub.add_parser("formats", help="列出各平台可用格式")
261
+ p.set_defaults(func=cmd_formats)
262
+
263
+ p = sub.add_parser("cache", help="查看/清理本地构建缓存")
264
+ p.add_argument("--prune", action="store_true", help="超过大小上限时按 LRU 清理")
265
+ p.add_argument("--max-mb", type=int, default=None, help="缓存大小上限 MB(默认 4096)")
266
+ p.add_argument("--json", action="store_true", help="以 JSON 输出统计与清理结果(供 GUI/脚本消费)")
267
+ p.set_defaults(func=cmd_cache)
268
+
269
+ p = sub.add_parser("pypa", help="打包为 PyPI 发行包 / 发布到 PyPI")
270
+ psub = p.add_subparsers(dest="pypa_cmd", required=True)
271
+ pb = psub.add_parser("build", help="构建 sdist 与 wheel")
272
+ pb.add_argument("path", help="项目目录")
273
+ pb.add_argument("-o", "--output", default="dist")
274
+ pb.set_defaults(func=cmd_pypa)
275
+ pp = psub.add_parser("publish", help="发布到 PyPI")
276
+ pp.add_argument("files", nargs="+", help="待上传的 .whl/.tar.gz")
277
+ pp.add_argument("--repo", default="pypi", choices=["pypi", "testpypi"])
278
+ pp.add_argument("--token", default=None, help="PyPI API Token(不填则交互输入)")
279
+ pp.set_defaults(func=cmd_pypa)
280
+
281
+ return parser
282
+
283
+
284
+ def main(argv: Optional[List[str]] = None) -> int:
285
+ parser = build_parser()
286
+ args = parser.parse_args(argv)
287
+ if not getattr(args, "cmd", None):
288
+ parser.print_help()
289
+ return 0
290
+ try:
291
+ return args.func(args) or 0
292
+ except KeyboardInterrupt:
293
+ print("\n已取消")
294
+ return 130
295
+ except Exception as e: # noqa: BLE001
296
+ print(f"错误: {e}", file=sys.stderr)
297
+ return 1
298
+
299
+
300
+ _EXAMPLE_MAIN = '''\
301
+ """hello_app —— Pythub 示例工程。"""
302
+ import platform
303
+ import sys
304
+
305
+
306
+ def info():
307
+ return f"Python {platform.python_version()} @ {platform.system()} {platform.machine()}"
308
+
309
+
310
+ def main():
311
+ args = sys.argv[1:]
312
+ if "--console" in args or not sys.stdout.isatty() and "--gui" not in args:
313
+ pass
314
+ try:
315
+ import tkinter
316
+ except ImportError:
317
+ tkinter = None
318
+
319
+ if tkinter and "--console" not in args:
320
+ root = tkinter.Tk()
321
+ root.title("Hello Pythub")
322
+ root.geometry("420x180")
323
+ tkinter.Label(root, text="Hello, Pythub!", font=("Helvetica", 20)).pack(pady=20)
324
+ tkinter.Label(root, text=info()).pack()
325
+ root.mainloop()
326
+ else:
327
+ print("Hello, Pythub!")
328
+ print(info())
329
+
330
+
331
+ if __name__ == "__main__":
332
+ main()
333
+ '''
334
+
335
+ _EXAMPLE_TOML = '''\
336
+ [app]
337
+ name = "hello-pythub"
338
+ entry = "main.py"
339
+ version = "0.1.0"
340
+ description = "Pythub 示例应用"
341
+ author = "CROGRAM"
342
+ requirements = [] # 第三方依赖,例如 ["requests"]
343
+ windowed = false # GUI 应用在 PyInstaller 引擎下隐藏控制台
344
+ '''
345
+
346
+
347
+ if __name__ == "__main__":
348
+ sys.exit(main())
pythub/config.py ADDED
@@ -0,0 +1,77 @@
1
+ """项目配置:pythub.toml 解析(3.11+ 用 tomllib,3.10 用内置简易解析器)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Optional
8
+
9
+
10
+ def _parse_toml_minimal(text: str) -> Dict[str, Any]:
11
+ """极简 TOML 解析:仅支持 [section] 与 key = "value"/value(满足 pythub.toml 需求)。"""
12
+ result: Dict[str, Any] = {}
13
+ section = result
14
+ for raw in text.splitlines():
15
+ line = raw.split("#", 1)[0].strip()
16
+ if not line:
17
+ continue
18
+ m = re.match(r"^\[(.+)\]$", line)
19
+ if m:
20
+ section = result
21
+ for part in m.group(1).split("."):
22
+ section = section.setdefault(part.strip(), {})
23
+ continue
24
+ m = re.match(r"^([\w-]+)\s*=\s*(.+)$", line)
25
+ if m:
26
+ key, val = m.group(1), m.group(2).strip()
27
+ if val.startswith(('"', "'")) and val.endswith(('"', "'")):
28
+ val = val[1:-1]
29
+ elif val.startswith("["):
30
+ items = re.findall(r'"([^"]*)"', val)
31
+ val = items
32
+ section[key] = val
33
+ return result
34
+
35
+
36
+ def load_config(project_dir: Path) -> Dict[str, Any]:
37
+ path = project_dir / "pythub.toml"
38
+ if not path.exists():
39
+ return {}
40
+ text = path.read_text(encoding="utf-8")
41
+ try:
42
+ import tomllib
43
+
44
+ return tomllib.loads(text)
45
+ except ImportError:
46
+ return _parse_toml_minimal(text)
47
+
48
+
49
+ def load_requirements(project_dir: Path) -> list:
50
+ """读取 requirements.txt(每行一个依赖,忽略注释与空行)。"""
51
+ path = project_dir / "requirements.txt"
52
+ if not path.exists():
53
+ return []
54
+ reqs = []
55
+ for line in path.read_text(encoding="utf-8").splitlines():
56
+ line = line.strip()
57
+ if line and not line.startswith("#"):
58
+ reqs.append(line)
59
+ return reqs
60
+
61
+
62
+ def app_config(project_dir: Path, overrides: Optional[dict] = None) -> Dict[str, Any]:
63
+ """合并 pythub.toml 的 [app] 段与命令行覆盖参数。"""
64
+ cfg = load_config(project_dir).get("app", {})
65
+ result = {
66
+ "name": cfg.get("name", project_dir.name or "app"),
67
+ "entry": cfg.get("entry", "main.py"),
68
+ "version": cfg.get("version", "0.1.0"),
69
+ "description": cfg.get("description", ""),
70
+ "author": cfg.get("author", ""),
71
+ "requirements": cfg.get("requirements", []),
72
+ "windowed": bool(cfg.get("windowed", False)),
73
+ }
74
+ for key, val in (overrides or {}).items():
75
+ if val:
76
+ result[key] = val
77
+ return result
pythub/deps.py ADDED
@@ -0,0 +1,90 @@
1
+ """跨平台依赖下载:为目标平台/架构/Python 版本下载对应 wheel。
2
+
3
+ 即需求中"在 Mac 上打包时只打包 Mac 需要的组件,在 Windows 上打包时只打包
4
+ Windows 需要的组件" —— 通过 pip 的 --platform/--abi/--python-version 实现。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import subprocess
11
+ import sys
12
+ import zipfile
13
+ from pathlib import Path
14
+ from typing import List, Optional
15
+
16
+ # (platform, arch) -> pip 平台标签
17
+ PIP_PLATFORM_TAGS = {
18
+ ("macos", "x86_64"): "macosx_11_0_x86_64",
19
+ ("macos", "aarch64"): "macosx_11_0_arm64",
20
+ ("windows", "x86_64"): "win_amd64",
21
+ ("windows", "aarch64"): "win_arm64",
22
+ ("linux", "x86_64"): "manylinux2014_x86_64",
23
+ ("linux", "aarch64"): "manylinux2014_aarch64",
24
+ }
25
+
26
+
27
+ def abi_tag(pyver: str) -> str:
28
+ minor = pyver.split(".")[1]
29
+ return f"cp{pyver.split('.')[0]}{minor}"
30
+
31
+
32
+ def download_wheels(
33
+ requirements: List[str],
34
+ platform: str,
35
+ arch: str,
36
+ pyver: str,
37
+ dest: Path,
38
+ logger: Optional[logging.Logger] = None,
39
+ ) -> List[Path]:
40
+ """下载目标平台的二进制 wheel,返回 wheel 文件列表。"""
41
+ if not requirements:
42
+ return []
43
+ tag = PIP_PLATFORM_TAGS.get((platform, arch))
44
+ if not tag:
45
+ raise ValueError(f"不支持的 目标平台/架构: {platform}/{arch}")
46
+
47
+ dest.mkdir(parents=True, exist_ok=True)
48
+ cmd = [
49
+ sys.executable, "-m", "pip", "download",
50
+ "--only-binary=:all:",
51
+ "--platform", tag,
52
+ "--abi", abi_tag(pyver),
53
+ "--python-version", pyver,
54
+ "--implementation", "cp",
55
+ "--disable-pip-version-check",
56
+ "-q",
57
+ "-d", str(dest),
58
+ *requirements,
59
+ ]
60
+ if logger:
61
+ logger.info("下载目标平台依赖 (%s/%s py%s): %s", platform, arch, pyver, ", ".join(requirements))
62
+ proc = subprocess.run(cmd, capture_output=True, text=True)
63
+ if proc.returncode != 0:
64
+ err = (proc.stderr or proc.stdout).strip()
65
+ raise RuntimeError(
66
+ f"依赖下载失败(目标平台 {platform}/{arch}, Python {pyver}):\n{err}\n"
67
+ f"提示: 确认依赖存在对应平台的二进制 wheel,或移除该依赖。"
68
+ )
69
+ return sorted(dest.glob("*.whl"))
70
+
71
+
72
+ def unpack_wheels(wheels: List[Path], dest: Path) -> None:
73
+ """把 wheel 解包进 lib 目录(处理 *.data/purelib 等目录)。"""
74
+ dest.mkdir(parents=True, exist_ok=True)
75
+ import shutil
76
+
77
+ for whl in wheels:
78
+ with zipfile.ZipFile(whl) as zf:
79
+ zf.extractall(dest)
80
+ # 合并 .data 目录
81
+ for data_dir in dest.glob("*.data"):
82
+ for sub in data_dir.iterdir():
83
+ if sub.name in ("purelib", "platlib"):
84
+ for item in sub.iterdir():
85
+ target = dest / item.name
86
+ if target.is_dir() and item.is_dir():
87
+ shutil.copytree(item, target, dirs_exist_ok=True)
88
+ else:
89
+ shutil.move(str(item), str(target))
90
+ shutil.rmtree(data_dir, ignore_errors=True)