unifypy 2.0.2__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.
Files changed (78) hide show
  1. unifypy/__init__.py +7 -0
  2. unifypy/__main__.py +21 -0
  3. unifypy/cli/__init__.py +10 -0
  4. unifypy/cli/argument_parser.py +209 -0
  5. unifypy/core/__init__.py +8 -0
  6. unifypy/core/config.py +491 -0
  7. unifypy/core/context.py +36 -0
  8. unifypy/core/engine.py +93 -0
  9. unifypy/core/environment.py +509 -0
  10. unifypy/core/event_bus.py +37 -0
  11. unifypy/core/events.py +16 -0
  12. unifypy/core/platforms.py +58 -0
  13. unifypy/core/plugin.py +65 -0
  14. unifypy/core/validators/__init__.py +10 -0
  15. unifypy/core/validators/tool_validator.py +144 -0
  16. unifypy/platforms/__init__.py +10 -0
  17. unifypy/platforms/base.py +127 -0
  18. unifypy/platforms/linux/__init__.py +10 -0
  19. unifypy/platforms/linux/deb_packager.py +289 -0
  20. unifypy/platforms/linux/rpm_packager.py +332 -0
  21. unifypy/platforms/macos/__init__.py +10 -0
  22. unifypy/platforms/macos/dmg_packager.py +477 -0
  23. unifypy/platforms/macos/post_processor.py +272 -0
  24. unifypy/platforms/registry.py +108 -0
  25. unifypy/platforms/windows/__init__.py +9 -0
  26. unifypy/platforms/windows/inno_setup.py +715 -0
  27. unifypy/plugins/__init__.py +3 -0
  28. unifypy/plugins/auto_rollback_plugin.py +156 -0
  29. unifypy/plugins/cleanup_plugin.py +22 -0
  30. unifypy/plugins/config_plugin.py +42 -0
  31. unifypy/plugins/dry_run_plugin.py +22 -0
  32. unifypy/plugins/environment_plugin.py +61 -0
  33. unifypy/plugins/external_plugins_loader.py +42 -0
  34. unifypy/plugins/packaging_plugin.py +125 -0
  35. unifypy/plugins/prepare_plugin.py +89 -0
  36. unifypy/plugins/progress_plugin.py +32 -0
  37. unifypy/plugins/pyinstaller_plugin.py +95 -0
  38. unifypy/plugins/rollback_plugin.py +62 -0
  39. unifypy/plugins/summary_plugin.py +36 -0
  40. unifypy/plugins/windows_language_plugin.py +85 -0
  41. unifypy/pyinstaller/__init__.py +7 -0
  42. unifypy/pyinstaller/config_builder.py +908 -0
  43. unifypy/templates/ChineseSimplified.isl.template +403 -0
  44. unifypy/templates/setup.iss.template +51 -0
  45. unifypy/tools/create-dmg/.this-is-the-create-dmg-repo +3 -0
  46. unifypy/tools/create-dmg/LICENSE +22 -0
  47. unifypy/tools/create-dmg/Makefile +33 -0
  48. unifypy/tools/create-dmg/README.md +126 -0
  49. unifypy/tools/create-dmg/builder/create-dmg.builder +26 -0
  50. unifypy/tools/create-dmg/create-dmg +621 -0
  51. unifypy/tools/create-dmg/doc-project/Developer Notes.md +35 -0
  52. unifypy/tools/create-dmg/doc-project/Release Checklist.md +10 -0
  53. unifypy/tools/create-dmg/examples/01-main-example/installer_background.png +0 -0
  54. unifypy/tools/create-dmg/examples/01-main-example/sample +30 -0
  55. unifypy/tools/create-dmg/examples/01-main-example/source_folder/Application.app +0 -0
  56. unifypy/tools/create-dmg/support/eula-resources-template.xml +105 -0
  57. unifypy/tools/create-dmg/support/template.applescript +74 -0
  58. unifypy/tools/create-dmg/tests/007-space-in-dir-name/my files/hello.txt +1 -0
  59. unifypy/tools/create-dmg/tests/007-space-in-dir-name/run-test +5 -0
  60. unifypy/utils/__init__.py +10 -0
  61. unifypy/utils/cache_manager.py +957 -0
  62. unifypy/utils/command_runner.py +195 -0
  63. unifypy/utils/entitlements_generator.py +450 -0
  64. unifypy/utils/file_ops.py +333 -0
  65. unifypy/utils/icon_converter.py +144 -0
  66. unifypy/utils/info_plist_updater.py +247 -0
  67. unifypy/utils/macos_codesign.py +225 -0
  68. unifypy/utils/parallel_builder.py +355 -0
  69. unifypy/utils/progress.py +371 -0
  70. unifypy/utils/progress_callback_factory.py +56 -0
  71. unifypy/utils/rollback.py +484 -0
  72. unifypy/utils/tool_manager.py +701 -0
  73. unifypy-2.0.2.dist-info/METADATA +609 -0
  74. unifypy-2.0.2.dist-info/RECORD +78 -0
  75. unifypy-2.0.2.dist-info/WHEEL +5 -0
  76. unifypy-2.0.2.dist-info/entry_points.txt +2 -0
  77. unifypy-2.0.2.dist-info/licenses/LICENSE +21 -0
  78. unifypy-2.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,701 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 第三方工具自动下载和管理 支持从GitHub直接获取工具,不依赖系统包管理器.
5
+ """
6
+
7
+ import os
8
+ from unifypy.core.platforms import normalize_platform, normalize_arch
9
+ import shutil
10
+ import tempfile
11
+ import zipfile
12
+ from pathlib import Path
13
+ from typing import Dict, List, Optional
14
+
15
+ import requests
16
+
17
+
18
+ class ToolManager:
19
+ """
20
+ 第三方工具自动下载和管理.
21
+ """
22
+
23
+ def __init__(self, tools_dir: Optional[str] = None):
24
+ """初始化工具管理器.
25
+
26
+ Args:
27
+ tools_dir: 工具存储目录,默认为用户缓存目录下的unifypy_tools
28
+ """
29
+ if tools_dir:
30
+ self.tools_dir = Path(tools_dir).resolve()
31
+ else:
32
+ # 使用用户缓存目录,避免在项目根目录创建tools文件夹
33
+ cache_base = Path.home() / ".cache" / "unifypy"
34
+ plat = normalize_platform()
35
+ if plat == "macos": # macOS
36
+ cache_base = Path.home() / "Library" / "Caches" / "unifypy"
37
+ elif plat == "windows": # Windows
38
+ cache_base = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "unifypy"
39
+ self.tools_dir = cache_base / "tools"
40
+
41
+ self.tools_dir.mkdir(parents=True, exist_ok=True)
42
+
43
+ # 初始化缓存管理器
44
+ from .cache_manager import CacheManager
45
+
46
+ self.cache_manager = CacheManager(str(Path.cwd()))
47
+
48
+ # 当前平台信息
49
+ self.current_platform = self._detect_platform()
50
+ self.current_arch = self._detect_architecture()
51
+
52
+ # 本地工具配置(UnifyPy内置工具)
53
+ # 获取UnifyPy项目根目录
54
+ project_root = Path(__file__).parent.parent.parent
55
+
56
+ self.local_tools = {
57
+ "create-dmg": {
58
+ "executable": "create-dmg",
59
+ "platform": "macos",
60
+ "path": str(project_root / "unifypy" / "tools" / "create-dmg" / "create-dmg"),
61
+ }
62
+ }
63
+
64
+ # GitHub工具配置(仅保留现行支持工具)
65
+ self.github_tools = {
66
+ "inno-setup": {
67
+ "repo": "jrsoftware/issrc",
68
+ "executable": "ISCC.exe",
69
+ "platform": "windows",
70
+ "type": "installer", # 安装包类型
71
+ "download_url": "https://jrsoftware.org/download.php/is.exe",
72
+ "install_method": "download_installer",
73
+ "description": "Inno Setup 编译器 - Windows 安装包制作工具",
74
+ },
75
+ }
76
+
77
+ # 缓存GitHub API响应
78
+ self._api_cache = {}
79
+
80
+ # 平台打包器工具配置
81
+ self.platform_tools = {
82
+ "windows": [
83
+ {
84
+ "name": "inno-setup",
85
+ "display_name": "Inno Setup",
86
+ "description": "Windows 安装包制作工具",
87
+ "download_url": "https://jrsoftware.org/isdl.php",
88
+ "install_instructions": [
89
+ "1. 访问上述 URL 下载 Inno Setup 安装程序",
90
+ "2. 运行安装程序,按照向导完成安装",
91
+ "3. 安装后重新运行 UnifyPy 构建命令"
92
+ ],
93
+ "config_example": '"inno_setup_path": "C:\\\\Program Files (x86)\\\\Inno Setup 6\\\\ISCC.exe"',
94
+ "check_method": "_check_inno_setup"
95
+ }
96
+ ],
97
+ "macos": [
98
+ {
99
+ "name": "create-dmg",
100
+ "display_name": "create-dmg",
101
+ "description": "macOS DMG 创建工具 (UnifyPy 内置)",
102
+ "download_url": "https://github.com/create-dmg/create-dmg",
103
+ "install_instructions": [
104
+ "✅ create-dmg 已内置在 UnifyPy 中,无需手动安装"
105
+ ],
106
+ "check_method": "_check_create_dmg"
107
+ }
108
+ ],
109
+ "linux": [
110
+ {
111
+ "name": "dpkg-deb",
112
+ "display_name": "dpkg-deb",
113
+ "description": "Debian/Ubuntu 包构建工具",
114
+ "download_url": "通常预装在 Debian/Ubuntu 系统",
115
+ "install_instructions": [
116
+ "在 Debian/Ubuntu 系统上安装:",
117
+ " sudo apt-get update",
118
+ " sudo apt-get install dpkg-dev"
119
+ ],
120
+ "check_method": "_check_dpkg_deb"
121
+ },
122
+ {
123
+ "name": "rpmbuild",
124
+ "display_name": "rpmbuild",
125
+ "description": "RedHat/CentOS/Fedora 包构建工具",
126
+ "download_url": "通常预装在 RedHat/CentOS/Fedora 系统",
127
+ "install_instructions": [
128
+ "在 RedHat/CentOS/Fedora 系统上安装:",
129
+ " sudo yum install rpm-build # 或 sudo dnf install rpm-build"
130
+ ],
131
+ "check_method": "_check_rpmbuild"
132
+ }
133
+ ]
134
+ }
135
+
136
+ def _detect_platform(self) -> str:
137
+ """
138
+ 检测当前平台.
139
+ """
140
+ return normalize_platform()
141
+
142
+ def _detect_architecture(self) -> str:
143
+ """检测当前架构,标准化后返回工具常用命名。
144
+
145
+ 返回:
146
+ - x64 → x86_64(工具常用)
147
+ - arm64 → arm64
148
+ 其余架构不在支持范围(normalize_arch 将抛错)。
149
+ """
150
+ arch = normalize_arch()
151
+ return "x86_64" if arch == "x64" else "arm64"
152
+
153
+ def ensure_tool(self, tool_name: str, version: str = "latest") -> str:
154
+ """确保工具可用,自动下载如果不存在.
155
+
156
+ Args:
157
+ tool_name: 工具名称
158
+ version: 工具版本,默认为latest
159
+
160
+ Returns:
161
+ str: 工具可执行文件路径
162
+
163
+ Raises:
164
+ ValueError: 不支持的工具或平台
165
+ RuntimeError: 下载或安装失败
166
+ """
167
+ # 优先检查本地工具
168
+ if tool_name in self.local_tools:
169
+ return self._get_local_tool_path(tool_name)
170
+
171
+ if tool_name not in self.github_tools:
172
+ raise ValueError(f"不支持的工具: {tool_name}")
173
+
174
+ tool_config = self.github_tools[tool_name]
175
+
176
+ # 检查平台兼容性
177
+ if (
178
+ tool_config["platform"] != "all"
179
+ and tool_config["platform"] != self.current_platform
180
+ ):
181
+ raise ValueError(f"工具 {tool_name} 不支持当前平台 {self.current_platform}")
182
+
183
+ # 检查工具是否已存在
184
+ executable_path = self._get_tool_path(tool_name)
185
+ if executable_path and os.path.exists(executable_path):
186
+ return executable_path
187
+
188
+ # 下载并安装工具
189
+ return self._download_and_install_tool(tool_name, version)
190
+
191
+ def _get_local_tool_path(self, tool_name: str) -> str:
192
+ """获取本地工具路径.
193
+
194
+ Args:
195
+ tool_name: 工具名称
196
+
197
+ Returns:
198
+ str: 本地工具路径
199
+
200
+ Raises:
201
+ ValueError: 工具不存在或不支持当前平台
202
+ RuntimeError: 工具文件不存在或无执行权限
203
+ """
204
+ if tool_name not in self.local_tools:
205
+ raise ValueError(f"未知的本地工具: {tool_name}")
206
+
207
+ tool_config = self.local_tools[tool_name]
208
+
209
+ # 检查平台兼容性
210
+ if (
211
+ tool_config["platform"] != "all"
212
+ and tool_config["platform"] != self.current_platform
213
+ ):
214
+ raise ValueError(f"工具 {tool_name} 不支持当前平台 {self.current_platform}")
215
+
216
+ # 获取项目根目录
217
+ project_root = Path(__file__).parent.parent.parent # 从 unifypy/utils/ 回到项目根目录
218
+ tool_path = project_root / tool_config["path"]
219
+
220
+ if not tool_path.exists():
221
+ raise RuntimeError(f"本地工具不存在: {tool_path}")
222
+
223
+ if not os.access(tool_path, os.X_OK):
224
+ # 尝试设置执行权限
225
+ try:
226
+ os.chmod(tool_path, 0o755)
227
+ except OSError as e:
228
+ raise RuntimeError(f"无法设置工具执行权限: {tool_path}, 错误: {e}")
229
+
230
+ return str(tool_path)
231
+
232
+ def _get_tool_path(self, tool_name: str) -> Optional[str]:
233
+ """获取工具的本地路径.
234
+
235
+ Args:
236
+ tool_name: 工具名称
237
+
238
+ Returns:
239
+ Optional[str]: 工具路径,如果不存在则返回None
240
+ """
241
+ tool_config = self.github_tools[tool_name]
242
+ executable_name = tool_config["executable"]
243
+
244
+ # 在tools目录中查找
245
+ tool_dir = self.tools_dir / tool_name
246
+ possible_paths = [
247
+ tool_dir / executable_name,
248
+ tool_dir / f"{executable_name}.exe", # Windows
249
+ ]
250
+
251
+ for path in possible_paths:
252
+ if path.exists() and os.access(path, os.X_OK):
253
+ return str(path)
254
+
255
+ return None
256
+
257
+ def _download_and_install_tool(self, tool_name: str, version: str) -> str:
258
+ """下载并安装工具.
259
+
260
+ Args:
261
+ tool_name: 工具名称
262
+ version: 版本
263
+
264
+ Returns:
265
+ str: 安装后的工具路径
266
+ """
267
+ tool_config = self.github_tools[tool_name]
268
+ repo = tool_config["repo"]
269
+ install_method = tool_config["install_method"]
270
+
271
+ if install_method == "copy_executable":
272
+ return self._install_source_tool(tool_name, repo, version)
273
+ elif install_method == "download_binary":
274
+ return self._install_binary_tool(tool_name, repo, version)
275
+ elif install_method == "download_installer":
276
+ return self._install_installer_tool(tool_name, tool_config)
277
+ else:
278
+ raise ValueError(f"未知的安装方法: {install_method}")
279
+
280
+ def _install_source_tool(self, tool_name: str, repo: str, version: str) -> str:
281
+ """安装源码类型的工具(如create-dmg)
282
+
283
+ Args:
284
+ tool_name: 工具名称
285
+ repo: GitHub仓库
286
+ version: 版本
287
+
288
+ Returns:
289
+ str: 工具路径
290
+ """
291
+ # 下载源码
292
+ download_url = self._get_source_download_url(repo, version)
293
+
294
+ with tempfile.TemporaryDirectory() as temp_dir:
295
+ temp_path = Path(temp_dir)
296
+
297
+ # 下载并解压
298
+ archive_path = temp_path / "source.zip"
299
+ self._download_file(download_url, archive_path)
300
+
301
+ extract_dir = temp_path / "extracted"
302
+ extract_dir.mkdir()
303
+
304
+ with zipfile.ZipFile(archive_path, "r") as zip_ref:
305
+ zip_ref.extractall(extract_dir)
306
+
307
+ # 找到解压后的目录(通常是repo名称)
308
+ extracted_dirs = [d for d in extract_dir.iterdir() if d.is_dir()]
309
+ if not extracted_dirs:
310
+ raise RuntimeError("解压后未找到源码目录")
311
+
312
+ source_dir = extracted_dirs[0]
313
+
314
+ # 安装到tools目录
315
+ tool_dir = self.tools_dir / tool_name
316
+ if tool_dir.exists():
317
+ shutil.rmtree(tool_dir)
318
+
319
+ shutil.copytree(source_dir, tool_dir)
320
+
321
+ # 设置可执行权限
322
+ executable_path = tool_dir / self.github_tools[tool_name]["executable"]
323
+ if executable_path.exists():
324
+ os.chmod(executable_path, 0o755)
325
+ return str(executable_path)
326
+ else:
327
+ raise RuntimeError(f"未找到可执行文件: {executable_path}")
328
+
329
+ def _install_binary_tool(self, tool_name: str, repo: str, version: str) -> str:
330
+ """安装二进制类型的工具
331
+
332
+ Args:
333
+ tool_name: 工具名称
334
+ repo: GitHub仓库
335
+ version: 版本
336
+
337
+ Returns:
338
+ str: 工具路径
339
+ """
340
+ tool_config = self.github_tools[tool_name]
341
+
342
+ # 获取下载URL
343
+ download_url = self._get_binary_download_url(
344
+ repo, tool_config["asset_pattern"], version
345
+ )
346
+
347
+ # 确定目标路径
348
+ tool_dir = self.tools_dir / tool_name
349
+ tool_dir.mkdir(exist_ok=True)
350
+
351
+ executable_name = tool_config["executable"]
352
+ # 保持原始扩展名
353
+
354
+ target_path = tool_dir / executable_name
355
+
356
+ # 下载文件
357
+ self._download_file(download_url, target_path)
358
+
359
+ # 设置可执行权限
360
+ os.chmod(target_path, 0o755)
361
+
362
+ return str(target_path)
363
+
364
+ def _install_installer_tool(self, tool_name: str, tool_config: Dict) -> str:
365
+ """安装安装包类型的工具(如Inno Setup)
366
+
367
+ Args:
368
+ tool_name: 工具名称
369
+ tool_config: 工具配置
370
+
371
+ Returns:
372
+ str: 工具路径
373
+ """
374
+ download_url = tool_config.get("download_url")
375
+ if not download_url:
376
+ raise ValueError(f"工具 {tool_name} 缺少下载URL配置")
377
+
378
+ # 提示用户手动安装
379
+ print(f"\n🔧 需要安装 {tool_name}")
380
+ print(f"📝 描述: {tool_config.get('description', '第三方工具')}")
381
+ print(f"🌐 下载地址: {download_url}")
382
+ print(f"\n⚠️ 由于 {tool_name} 是完整的安装包软件,需要手动安装:")
383
+ print(f" 1. 访问上述URL下载安装包")
384
+ print(f" 2. 运行安装程序完成安装")
385
+ print(f" 3. 重新运行UnifyPy构建命令")
386
+ print(f"\n💡 或者,您可以在配置文件中指定已安装的路径:")
387
+ print(
388
+ f' "inno_setup_path": "C:\\\\Program Files (x86)\\\\Inno Setup 6\\\\ISCC.exe"'
389
+ )
390
+
391
+ # 检查是否已经安装
392
+ print(f"\n🔍 正在检查系统中是否已安装 {tool_name}...")
393
+
394
+ # 尝试自动检测
395
+ if tool_name == "inno-setup":
396
+ # 调用Inno Setup打包器的检测逻辑
397
+ detected_path = self._detect_existing_inno_setup()
398
+ if detected_path:
399
+ print(f"✅ 检测到已安装的 {tool_name}: {detected_path}")
400
+ return detected_path
401
+
402
+ # 如果没有检测到,抛出异常
403
+ raise RuntimeError(f"未找到 {tool_name},请按照上述说明手动安装")
404
+
405
+ def _detect_existing_inno_setup(self) -> Optional[str]:
406
+ """
407
+ 检测已安装的Inno Setup.
408
+ """
409
+ try:
410
+ # 检查注册表
411
+ registry_path = self._check_registry_for_inno_setup()
412
+ if registry_path and os.path.exists(registry_path):
413
+ return registry_path
414
+
415
+ # 检查常见路径
416
+ common_paths = [
417
+ r"C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
418
+ r"C:\Program Files\Inno Setup 6\ISCC.exe",
419
+ r"C:\Program Files (x86)\Inno Setup 5\ISCC.exe",
420
+ r"C:\Program Files\Inno Setup 5\ISCC.exe",
421
+ ]
422
+
423
+ for path in common_paths:
424
+ if os.path.exists(path):
425
+ return path
426
+
427
+ # 检查PATH
428
+ import shutil
429
+
430
+ path_found = shutil.which("ISCC.exe")
431
+ if path_found:
432
+ return path_found
433
+
434
+ except Exception:
435
+ pass
436
+
437
+ return None
438
+
439
+ def _check_registry_for_inno_setup(self) -> Optional[str]:
440
+ """
441
+ 从Windows注册表检查Inno Setup.
442
+ """
443
+ try:
444
+ import winreg
445
+
446
+ registry_keys = [
447
+ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 6_is1",
448
+ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1",
449
+ r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 6_is1",
450
+ r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1",
451
+ ]
452
+
453
+ for key_path in registry_keys:
454
+ try:
455
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
456
+ install_location, _ = winreg.QueryValueEx(
457
+ key, "InstallLocation"
458
+ )
459
+ if install_location:
460
+ iscc_path = os.path.join(install_location, "ISCC.exe")
461
+ if os.path.exists(iscc_path):
462
+ return iscc_path
463
+ except (FileNotFoundError, OSError):
464
+ continue
465
+
466
+ except ImportError:
467
+ # winreg模块不可用(非Windows系统)
468
+ pass
469
+ except Exception:
470
+ pass
471
+
472
+ return None
473
+
474
+ def _get_source_download_url(self, repo: str, version: str) -> str:
475
+ """获取源码下载URL.
476
+
477
+ Args:
478
+ repo: GitHub仓库
479
+ version: 版本
480
+
481
+ Returns:
482
+ str: 下载URL
483
+ """
484
+ if version == "latest":
485
+ # 获取最新版本
486
+ api_url = f"https://api.github.com/repos/{repo}/releases/latest"
487
+ response = self._github_api_request(api_url)
488
+ version = response["tag_name"]
489
+
490
+ return f"https://github.com/{repo}/archive/refs/tags/{version}.zip"
491
+
492
+ def _get_binary_download_url(
493
+ self, repo: str, asset_pattern: str, version: str
494
+ ) -> str:
495
+ """获取二进制文件下载URL.
496
+
497
+ Args:
498
+ repo: GitHub仓库
499
+ asset_pattern: 资源文件模式
500
+ version: 版本
501
+
502
+ Returns:
503
+ str: 下载URL
504
+ """
505
+ if version == "latest":
506
+ api_url = f"https://api.github.com/repos/{repo}/releases/latest"
507
+ else:
508
+ api_url = f"https://api.github.com/repos/{repo}/releases/tags/{version}"
509
+
510
+ response = self._github_api_request(api_url)
511
+
512
+ # 格式化资源文件名
513
+ asset_name = asset_pattern.format(arch=self.current_arch)
514
+
515
+ # 查找匹配的资源
516
+ for asset in response["assets"]:
517
+ if asset["name"] == asset_name or asset_name in asset["name"]:
518
+ return asset["browser_download_url"]
519
+
520
+ # 如果找不到精确匹配,尝试模糊匹配
521
+ for asset in response["assets"]:
522
+ if self.current_arch in asset["name"].lower():
523
+ return asset["browser_download_url"]
524
+
525
+ raise RuntimeError(f"未找到匹配的资源文件: {asset_name}")
526
+
527
+ def _github_api_request(self, url: str) -> Dict:
528
+ """发起GitHub API请求.
529
+
530
+ Args:
531
+ url: API URL
532
+
533
+ Returns:
534
+ Dict: API响应
535
+ """
536
+ if url in self._api_cache:
537
+ return self._api_cache[url]
538
+
539
+ headers = {
540
+ "Accept": "application/vnd.github.v3+json",
541
+ "User-Agent": "UnifyPy/2.0",
542
+ }
543
+
544
+ response = requests.get(url, headers=headers, timeout=30)
545
+ response.raise_for_status()
546
+
547
+ data = response.json()
548
+ self._api_cache[url] = data
549
+
550
+ return data
551
+
552
+ def _download_file(self, url: str, target_path: Path):
553
+ """下载文件.
554
+
555
+ Args:
556
+ url: 下载URL
557
+ target_path: 目标路径
558
+ """
559
+ response = requests.get(url, stream=True, timeout=30)
560
+ response.raise_for_status()
561
+
562
+ target_path.parent.mkdir(parents=True, exist_ok=True)
563
+
564
+ with open(target_path, "wb") as f:
565
+ for chunk in response.iter_content(chunk_size=8192):
566
+ f.write(chunk)
567
+
568
+ def list_available_tools(self) -> List[str]:
569
+ """列出所有可用的工具.
570
+
571
+ Returns:
572
+ List[str]: 工具名称列表
573
+ """
574
+ local_tools = list(self.local_tools.keys())
575
+ github_tools = list(self.github_tools.keys())
576
+ return local_tools + github_tools
577
+
578
+ def get_tool_info(self, tool_name: str) -> Dict:
579
+ """获取工具信息.
580
+
581
+ Args:
582
+ tool_name: 工具名称
583
+
584
+ Returns:
585
+ Dict: 工具信息
586
+ """
587
+ if tool_name in self.local_tools:
588
+ config = self.local_tools[tool_name].copy()
589
+ config["type"] = "local"
590
+ try:
591
+ config["local_path"] = self._get_local_tool_path(tool_name)
592
+ config["available"] = True
593
+ except (ValueError, RuntimeError):
594
+ config["local_path"] = None
595
+ config["available"] = False
596
+ return config
597
+
598
+ if tool_name not in self.github_tools:
599
+ raise ValueError(f"未知工具: {tool_name}")
600
+
601
+ config = self.github_tools[tool_name].copy()
602
+ config["type"] = "github"
603
+ config["local_path"] = self._get_tool_path(tool_name)
604
+ config["available"] = config["local_path"] is not None
605
+
606
+ return config
607
+
608
+ def remove_tool(self, tool_name: str):
609
+ """移除工具.
610
+
611
+ Args:
612
+ tool_name: 工具名称
613
+ """
614
+ tool_dir = self.tools_dir / tool_name
615
+ if tool_dir.exists():
616
+ shutil.rmtree(tool_dir)
617
+
618
+ def update_tool(self, tool_name: str, version: str = "latest") -> str:
619
+ """更新工具到指定版本.
620
+
621
+ Args:
622
+ tool_name: 工具名称
623
+ version: 版本
624
+
625
+ Returns:
626
+ str: 更新后的工具路径
627
+ """
628
+ self.remove_tool(tool_name)
629
+ return self.ensure_tool(tool_name, version)
630
+
631
+ def get_required_tools_for_platform(self, platform_name: str) -> List[Dict]:
632
+ """获取指定平台需要的工具列表.
633
+
634
+ Args:
635
+ platform_name: 平台名称 (windows/macos/linux)
636
+
637
+ Returns:
638
+ List[Dict]: 工具信息列表
639
+ """
640
+ return self.platform_tools.get(platform_name, [])
641
+
642
+ def check_tool_available(self, tool_name: str) -> bool:
643
+ """检查工具是否可用.
644
+
645
+ Args:
646
+ tool_name: 工具名称
647
+
648
+ Returns:
649
+ bool: 工具是否可用
650
+ """
651
+ # 根据工具名称调用对应的检测方法
652
+ if tool_name == "inno-setup":
653
+ return self._check_inno_setup()
654
+ elif tool_name == "create-dmg":
655
+ return self._check_create_dmg()
656
+ elif tool_name == "dpkg-deb":
657
+ return self._check_dpkg_deb()
658
+ elif tool_name == "rpmbuild":
659
+ return self._check_rpmbuild()
660
+ else:
661
+ # 未知工具,尝试通过 shutil.which 检查
662
+ return shutil.which(tool_name) is not None
663
+
664
+ def _check_inno_setup(self) -> bool:
665
+ """检查 Inno Setup 是否可用.
666
+
667
+ Returns:
668
+ bool: 是否可用
669
+ """
670
+ return self._detect_existing_inno_setup() is not None
671
+
672
+ def _check_create_dmg(self) -> bool:
673
+ """检查 create-dmg 是否可用 (内置工具).
674
+
675
+ Returns:
676
+ bool: 是否可用
677
+ """
678
+ try:
679
+ # 检查本地工具
680
+ if "create-dmg" in self.local_tools:
681
+ tool_path = self._get_local_tool_path("create-dmg")
682
+ return Path(tool_path).exists()
683
+ return False
684
+ except (ValueError, RuntimeError):
685
+ return False
686
+
687
+ def _check_dpkg_deb(self) -> bool:
688
+ """检查 dpkg-deb 是否可用.
689
+
690
+ Returns:
691
+ bool: 是否可用
692
+ """
693
+ return shutil.which("dpkg-deb") is not None
694
+
695
+ def _check_rpmbuild(self) -> bool:
696
+ """检查 rpmbuild 是否可用.
697
+
698
+ Returns:
699
+ bool: 是否可用
700
+ """
701
+ return shutil.which("rpmbuild") is not None