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,715 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Windows Inno Setup 打包器 支持完整的Inno Setup脚本配置.
5
+ """
6
+
7
+ import os
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from ..base import BasePackager
13
+
14
+
15
+ class InnoSetupPackager(BasePackager):
16
+ """
17
+ Inno Setup 打包器.
18
+ """
19
+
20
+ def __init__(self, *args, **kwargs):
21
+ super().__init__(*args, **kwargs)
22
+ self._project_chinese_file = None # 项目自带的中文语言文件路径
23
+ self._check_project_language_file()
24
+
25
+ # 初始化缓存管理器
26
+ from ...utils.cache_manager import CacheManager
27
+ self.cache_manager = CacheManager(".")
28
+
29
+ def _check_project_language_file(self):
30
+ """
31
+ 检查项目是否自带中文语言文件.
32
+ """
33
+ try:
34
+ import os
35
+
36
+ # 多个可能的查找位置
37
+ search_paths = []
38
+
39
+ # 1. 基于配置文件路径的目录
40
+ if self.config_file_path:
41
+ config_dir = os.path.dirname(os.path.abspath(self.config_file_path))
42
+ search_paths.append(os.path.join(config_dir, "ChineseSimplified.isl"))
43
+
44
+ # 2. 当前工作目录
45
+ search_paths.append(os.path.join(os.getcwd(), "ChineseSimplified.isl"))
46
+
47
+ # 3. 项目根目录(如果 env_manager 可用)
48
+ if hasattr(self, "env_manager") and hasattr(self.env_manager, "project_dir"):
49
+ search_paths.append(os.path.join(self.env_manager.project_dir, "ChineseSimplified.isl"))
50
+
51
+ # 尝试查找文件
52
+ for chinese_file in search_paths:
53
+ if os.path.exists(chinese_file):
54
+ self._project_chinese_file = chinese_file
55
+ if hasattr(self, "progress"):
56
+ self.progress.info(f"✅ 检测到项目自带的中文语言文件: {chinese_file}")
57
+ return
58
+
59
+ except Exception:
60
+ pass # 忽略错误,继续使用默认行为
61
+
62
+ def get_supported_formats(self) -> List[str]:
63
+ """
64
+ 获取支持的打包格式.
65
+ """
66
+ return ["exe"]
67
+
68
+ def can_package_format(self, format_type: str) -> bool:
69
+ """
70
+ 检查是否支持指定格式.
71
+ """
72
+ return format_type in self.get_supported_formats()
73
+
74
+ def package(self, format_type: str, source_path: Path, output_path: Path) -> bool:
75
+ """执行Inno Setup打包.
76
+
77
+ Args:
78
+ format_type: 打包格式 (exe)
79
+ source_path: PyInstaller生成的可执行文件路径
80
+ output_path: 输出安装包路径
81
+
82
+ Returns:
83
+ bool: 打包是否成功
84
+ """
85
+ if not self.can_package_format(format_type):
86
+ self.progress.on_error(
87
+ Exception(f"不支持的格式: {format_type}"), "Windows打包"
88
+ )
89
+ return False
90
+
91
+ # 获取Inno Setup配置
92
+ inno_config = self.get_format_config("inno_setup")
93
+
94
+ # 检查Inno Setup编译器
95
+ compiler_path = self._find_inno_setup_compiler()
96
+ if not compiler_path:
97
+ # 尝试使用ToolManager自动获取
98
+ try:
99
+ if hasattr(self, "tool_manager") and self.tool_manager:
100
+ self.progress.info("🔄 尝试通过ToolManager获取Inno Setup...")
101
+ compiler_path = self.tool_manager.ensure_tool("inno-setup")
102
+ if compiler_path:
103
+ self.progress.info(f"✅ ToolManager找到Inno Setup: {compiler_path}")
104
+ else:
105
+ raise RuntimeError("ToolManager不可用")
106
+ except Exception as e:
107
+ self.progress.on_error(
108
+ Exception(f"未找到Inno Setup编译器: {e}"),
109
+ "Windows打包",
110
+ "解决方案:\n1. 手动安装Inno Setup: https://jrsoftware.org/isinfo.php\n2. 或在配置中指定路径: 'inno_setup_path': 'C:\\\\path\\\\to\\\\ISCC.exe'",
111
+ )
112
+ return False
113
+
114
+ # 智能缓存管理:检查是否需要重新生成 ISS 脚本
115
+ use_cached_iss = False
116
+ cached_iss_content = None
117
+
118
+ if not self.cache_manager.should_regenerate_config(self.config, "windows"):
119
+ # 配置未变化,尝试使用缓存的 ISS 文件
120
+ cached_iss_content = self.cache_manager.load_cached_file("windows", "iss")
121
+ if cached_iss_content:
122
+ use_cached_iss = True
123
+ self.progress.info("✅ 使用缓存的 ISS 配置")
124
+
125
+ if not use_cached_iss:
126
+ # 需要重新生成 ISS 脚本
127
+ self.progress.info("🔄 生成新的 ISS 配置")
128
+
129
+ # 处理 AppID:确保存在并写回配置文件
130
+ app_id = self.cache_manager.get_or_generate_app_id(self.config)
131
+ if not self.config.get("platforms", {}).get("windows", {}).get("inno_setup", {}).get("app_id"):
132
+ # AppID 不在配置中,需要写回
133
+ if self.cache_manager.update_build_config_with_app_id(self.config_file_path, app_id):
134
+ self.progress.info(f"✅ AppID 已写入配置文件: {app_id}")
135
+ # 重新加载配置以包含新的 AppID
136
+ import json
137
+ try:
138
+ with open(self.config_file_path, "r", encoding="utf-8") as f:
139
+ updated_config = json.load(f)
140
+ self.config = updated_config
141
+ inno_config = self.get_format_config("inno_setup")
142
+ except Exception as e:
143
+ self.progress.warning(f"重新加载配置失败: {e}")
144
+
145
+ # 创建ISS脚本
146
+ iss_content = self._build_iss_script(inno_config, source_path, output_path)
147
+
148
+ # 缓存生成的 ISS 文件
149
+ self.cache_manager.save_cached_file("windows", "iss", iss_content)
150
+ self.cache_manager.save_config_hash(
151
+ self.cache_manager.calculate_config_hash(self.config, "windows"),
152
+ "windows"
153
+ )
154
+ self.progress.info("💾 ISS 配置已缓存")
155
+ else:
156
+ iss_content = cached_iss_content
157
+
158
+ # 写入临时ISS文件 - 使用UTF-8 BOM编码确保中文字符正确显示
159
+ with tempfile.NamedTemporaryFile(
160
+ mode="w", suffix=".iss", delete=False, encoding="utf-8-sig"
161
+ ) as f:
162
+ f.write(iss_content)
163
+ iss_file = f.name
164
+
165
+ try:
166
+ # 执行编译
167
+ command = [compiler_path, "/Q", iss_file]
168
+
169
+ success = self.runner.run_command(
170
+ command, "Windows打包", f"正在生成Windows安装程序...", 80, shell=False
171
+ )
172
+
173
+ if success:
174
+ self.progress.update_stage("Windows打包", 10, "验证输出文件")
175
+ if output_path.exists():
176
+ return True
177
+ else:
178
+ self.progress.on_error(
179
+ Exception(f"输出文件不存在: {output_path}"), "Windows打包"
180
+ )
181
+ return False
182
+ else:
183
+ return False
184
+
185
+ finally:
186
+ # 清理临时文件
187
+ try:
188
+ os.unlink(iss_file)
189
+ except:
190
+ pass
191
+
192
+ def _find_inno_setup_compiler(self) -> str:
193
+ """
194
+ 查找Inno Setup编译器.
195
+ """
196
+ # 首先检查配置中的路径
197
+ inno_path = self.config.get("inno_setup_path")
198
+ if inno_path and os.path.exists(inno_path):
199
+ if hasattr(self, "progress"):
200
+ self.progress.info(f"✅ 使用配置中的 Inno Setup 路径: {inno_path}")
201
+ return inno_path
202
+
203
+ # 检查PATH环境变量
204
+ try:
205
+ import shutil
206
+ path_found = shutil.which("ISCC.exe")
207
+ if path_found:
208
+ if hasattr(self, "progress"):
209
+ self.progress.info(f"✅ 在PATH中找到 Inno Setup: {path_found}")
210
+ return path_found
211
+ except Exception:
212
+ pass
213
+
214
+ # 自动检测Inno Setup安装
215
+ detected_path = self._auto_detect_inno_setup()
216
+ if detected_path:
217
+ if hasattr(self, "progress"):
218
+ self.progress.info(f"✅ 自动检测到 Inno Setup: {detected_path}")
219
+ return detected_path
220
+
221
+ return None
222
+
223
+ def _auto_detect_inno_setup(self) -> str:
224
+ """
225
+ 自动检测Inno Setup安装路径.
226
+ """
227
+ # 检查注册表
228
+ registry_path = self._check_registry_for_inno_setup()
229
+ if registry_path and os.path.exists(registry_path):
230
+ return registry_path
231
+
232
+ # 检查常见安装路径(按版本从新到旧)
233
+ common_paths = [
234
+ r"C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
235
+ r"C:\Program Files\Inno Setup 6\ISCC.exe",
236
+ r"C:\Program Files (x86)\Inno Setup 5\ISCC.exe",
237
+ r"C:\Program Files\Inno Setup 5\ISCC.exe",
238
+ ]
239
+
240
+ if hasattr(self, "progress"):
241
+ self.progress.info("🔍 搜索 Inno Setup 安装路径...")
242
+
243
+ for path in common_paths:
244
+ if os.path.exists(path):
245
+ # 检查并设置语言文件
246
+ self._setup_language_files(os.path.dirname(path))
247
+ return path
248
+
249
+ if hasattr(self, "progress"):
250
+ self.progress.warning("⚠️ 未找到 Inno Setup 安装,请手动安装或在配置中指定路径")
251
+
252
+ return None
253
+
254
+ def _check_registry_for_inno_setup(self) -> str:
255
+ """
256
+ 从Windows注册表检查Inno Setup安装路径.
257
+ """
258
+ try:
259
+ import winreg
260
+
261
+ # 检查不同版本的注册表项
262
+ registry_keys = [
263
+ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 6_is1",
264
+ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1",
265
+ r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 6_is1",
266
+ r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1",
267
+ ]
268
+
269
+ for key_path in registry_keys:
270
+ try:
271
+ with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
272
+ install_location, _ = winreg.QueryValueEx(
273
+ key, "InstallLocation"
274
+ )
275
+ if install_location:
276
+ iscc_path = os.path.join(install_location, "ISCC.exe")
277
+ if os.path.exists(iscc_path):
278
+ # 设置语言文件
279
+ self._setup_language_files(install_location)
280
+ return iscc_path
281
+ except (FileNotFoundError, OSError):
282
+ continue
283
+
284
+ except ImportError:
285
+ # winreg模块不可用(非Windows系统)
286
+ pass
287
+ except Exception as e:
288
+ self.progress.warning(f"检查注册表时出错: {e}")
289
+
290
+ return None
291
+
292
+ def _setup_language_files(self, inno_setup_dir: str):
293
+ """
294
+ 设置Inno Setup语言文件.
295
+ """
296
+ # 如果项目已经提供了中文语言文件,就不需要检查系统文件了
297
+ if self._project_chinese_file:
298
+ return
299
+
300
+ # 检查 Inno Setup 系统目录
301
+ languages_dir = os.path.join(inno_setup_dir, "Languages")
302
+
303
+ if not os.path.exists(languages_dir):
304
+ return
305
+
306
+ # 检查系统中文语言文件
307
+ chinese_file = os.path.join(languages_dir, "ChineseSimplified.isl")
308
+
309
+ if not os.path.exists(chinese_file):
310
+ self.progress.info("正在下载中文语言文件...")
311
+ success = self._download_chinese_language_file(chinese_file)
312
+ if success:
313
+ self.progress.info("✅ 中文语言文件已安装")
314
+ else:
315
+ self.progress.warning("❌ 中文语言文件下载失败,将只支持英语界面")
316
+ else:
317
+ self.progress.info("✅ 检测到中文语言文件支持")
318
+
319
+ def _download_chinese_language_file(self, target_path: str) -> bool:
320
+ """
321
+ 下载中文语言文件.
322
+ """
323
+ try:
324
+ import urllib.request
325
+
326
+ # Inno Setup官方中文语言文件URL
327
+ language_urls = [
328
+ "https://raw.githubusercontent.com/jrsoftware/issrc/main/Files/Languages/Unofficial/ChineseSimplified.isl",
329
+ "https://github.com/jrsoftware/issrc/raw/main/Files/Languages/Unofficial/ChineseSimplified.isl",
330
+ ]
331
+
332
+ for url in language_urls:
333
+ try:
334
+ self.progress.info(f"从 {url} 下载...")
335
+ urllib.request.urlretrieve(url, target_path)
336
+
337
+ # 验证文件
338
+ if (
339
+ os.path.exists(target_path)
340
+ and os.path.getsize(target_path) > 100
341
+ ):
342
+ return True
343
+ else:
344
+ os.remove(target_path) if os.path.exists(target_path) else None
345
+
346
+ except Exception as e:
347
+ self.progress.warning(f"从 {url} 下载失败: {e}")
348
+ continue
349
+
350
+ # 如果下载失败,创建一个基本的中文语言文件
351
+ return self._create_basic_chinese_language_file(target_path)
352
+
353
+ except Exception as e:
354
+ self.progress.warning(f"下载中文语言文件时出错: {e}")
355
+ return False
356
+
357
+ def _create_basic_chinese_language_file(self, target_path: str) -> bool:
358
+ """
359
+ 创建中文语言文件:优先从模板读取并写入目标路径。
360
+ 模板路径:unifypy/templates/ChineseSimplified.isl.template
361
+ """
362
+ try:
363
+ # 尝试从模板读取
364
+ template_candidates = [
365
+ Path(__file__).parent.parent.parent / "templates" / "ChineseSimplified.isl.template",
366
+ Path("unifypy/templates/ChineseSimplified.isl.template"),
367
+ Path("templates/ChineseSimplified.isl.template"),
368
+ ]
369
+
370
+ content = None
371
+ for p in template_candidates:
372
+ if p.exists():
373
+ with open(p, "r", encoding="utf-8") as rf:
374
+ content = rf.read()
375
+ break
376
+
377
+ if not content:
378
+ # 模板缺失则放弃创建
379
+ self.progress.warning("未找到 ChineseSimplified.isl 模板,跳过创建")
380
+ return False
381
+
382
+ with open(target_path, "w", encoding="utf-8-sig") as f:
383
+ f.write(content)
384
+
385
+ return True
386
+
387
+ except Exception as e:
388
+ self.progress.warning(f"创建中文语言文件失败: {e}")
389
+ return False
390
+
391
+ def _build_iss_script(
392
+ self, config: Dict[str, Any], source_path: Path, output_path: Path
393
+ ) -> str:
394
+ """
395
+ 构建Inno Setup脚本.
396
+ """
397
+ # 尝试使用模板文件
398
+ template_path = self._find_iss_template()
399
+ if template_path:
400
+ return self._process_template(template_path, config, source_path, output_path)
401
+ else:
402
+ # 回退到内置生成逻辑
403
+ return self._generate_iss_script(config, source_path, output_path)
404
+
405
+ def _find_iss_template(self) -> Optional[Path]:
406
+ """
407
+ 查找ISS模板文件.
408
+ """
409
+ # 查找模板文件的可能位置
410
+ template_locations = [
411
+ # 包内 templates 目录 (推荐位置)
412
+ Path(__file__).parent.parent.parent / "templates" / "setup.iss.template",
413
+ # 项目根目录下的 templates (兼容性)
414
+ Path("templates/setup.iss.template"),
415
+ Path("../templates/setup.iss.template"),
416
+ # 绝对路径查找(包名迁移后)
417
+ Path(__file__).parent.parent.parent.parent / "unifypy" / "templates" / "setup.iss.template",
418
+ ]
419
+
420
+ if hasattr(self, "progress"):
421
+ self.progress.info("🔍 查找 ISS 模板文件...")
422
+
423
+ for location in template_locations:
424
+ if location.exists():
425
+ if hasattr(self, "progress"):
426
+ self.progress.info(f"✅ 找到模板文件: {location}")
427
+ return location
428
+
429
+ if hasattr(self, "progress"):
430
+ self.progress.info("⚠️ 未找到模板文件,使用内置生成器")
431
+ return None
432
+
433
+ def _process_template(
434
+ self, template_path: Path, config: Dict[str, Any], source_path: Path, output_path: Path
435
+ ) -> str:
436
+ """
437
+ 处理ISS模板文件.
438
+ """
439
+ app_name = self.config.get("name", "MyApp")
440
+ app_version = self.config.get("version", "1.0.0")
441
+ publisher = self.config.get("publisher", "Unknown Publisher")
442
+ app_url = config.get("app_url", "")
443
+ display_name = self.config.get("display_name", app_name)
444
+
445
+ # 生成APP_ID - 修复格式问题
446
+ app_id = config.get('app_id', None)
447
+ if not app_id:
448
+ # 生成基于应用名称的伪GUID格式,注意这里不包含花括号
449
+ import hashlib
450
+ name_hash = hashlib.md5(app_name.encode()).hexdigest()[:8].upper()
451
+ app_id = f"C4D8B3F2-1234-5678-9ABC-{name_hash}12345678"
452
+ elif app_id.startswith('{') and app_id.endswith('}'):
453
+ # 移除现有的花括号,因为模板中已经有了
454
+ app_id = app_id.strip('{}')
455
+
456
+ # 确定源文件路径和可执行文件名
457
+ source_path_str = str(source_path).replace('/', '\\')
458
+
459
+ if source_path.is_file():
460
+ # 单文件模式
461
+ source_files = f'Source: "{source_path_str}"; DestDir: "{{app}}"; Flags: ignoreversion'
462
+ exe_name = source_path.name
463
+ else:
464
+ # 目录模式
465
+ source_files = f'Source: "{source_path_str}\\*"; DestDir: "{{app}}"; Flags: ignoreversion recursesubdirs createallsubdirs'
466
+ exe_name = f"{app_name}.exe"
467
+
468
+ # 读取模板内容
469
+ with open(template_path, 'r', encoding='utf-8') as f:
470
+ template_content = f.read()
471
+
472
+ # 替换模板变量
473
+ replacements = {
474
+ '{{APP_ID}}': app_id,
475
+ '{{APP_NAME}}': app_name,
476
+ '{{APP_VERSION}}': app_version,
477
+ '{{APP_DISPLAY_NAME}}': display_name,
478
+ '{{APP_PUBLISHER}}': publisher,
479
+ '{{APP_URL}}': app_url,
480
+ '{{OUTPUT_DIR}}': str(output_path.parent).replace('/', '\\'),
481
+ '{{OUTPUT_FILENAME}}': output_path.stem,
482
+ '{{SOURCE_FILES}}': source_files,
483
+ '{{EXE_NAME}}': exe_name,
484
+ }
485
+
486
+ # 条件块处理
487
+ conditions = {
488
+ '{{#APP_URL}}': bool(app_url),
489
+ '{{#LICENSE_FILE}}': bool(config.get('license_file')) and os.path.exists(config.get('license_file', '')),
490
+ '{{#SETUP_ICON}}': bool(config.get('setup_icon')) and os.path.exists(config.get('setup_icon', '')),
491
+ '{{#CREATE_DESKTOP_ICON}}': config.get('create_desktop_icon', True),
492
+ '{{#CREATE_START_MENU_ICON}}': config.get('create_start_menu_icon', False),
493
+ '{{#RUN_AFTER_INSTALL}}': config.get('run_after_install', False),
494
+ '{{#CHINESE_SUPPORT}}': 'chinesesimplified' in config.get('languages', []) or 'chinese' in config.get('languages', []),
495
+ }
496
+
497
+ # 处理条件块 - 改进的处理逻辑
498
+ result = template_content
499
+ for condition, should_include in conditions.items():
500
+ start_tag = condition
501
+ end_tag = condition.replace('#', '/')
502
+
503
+ # 查找条件块
504
+ start_idx = result.find(start_tag)
505
+ while start_idx != -1:
506
+ end_idx = result.find(end_tag, start_idx)
507
+ if end_idx == -1:
508
+ break
509
+
510
+ if should_include:
511
+ # 保留内容,移除标记
512
+ content = result[start_idx + len(start_tag):end_idx]
513
+ result = result[:start_idx] + content + result[end_idx + len(end_tag):]
514
+ start_idx = result.find(start_tag, start_idx + len(content))
515
+ else:
516
+ # 移除整个块
517
+ result = result[:start_idx] + result[end_idx + len(end_tag):]
518
+ start_idx = result.find(start_tag, start_idx)
519
+
520
+ # 处理特殊替换
521
+ if conditions['{{#LICENSE_FILE}}']:
522
+ result = result.replace('{{LICENSE_FILE}}', str(Path(config.get('license_file')).resolve()).replace('/', '\\'))
523
+
524
+ if conditions['{{#SETUP_ICON}}']:
525
+ result = result.replace('{{SETUP_ICON}}', str(Path(config.get('setup_icon')).resolve()).replace('/', '\\'))
526
+
527
+ if conditions['{{#CHINESE_SUPPORT}}']:
528
+ chinese_isl_path = self._get_chinese_isl_path()
529
+ result = result.replace('{{CHINESE_ISL_PATH}}', chinese_isl_path)
530
+
531
+ # 清理其他特殊标记
532
+ result = result.replace('{{LICENSE_FILE}}', '')
533
+ result = result.replace('{{SETUP_ICON}}', '')
534
+ result = result.replace('{{CHINESE_ISL_PATH}}', '')
535
+
536
+ # 执行基本替换
537
+ for placeholder, value in replacements.items():
538
+ result = result.replace(placeholder, value)
539
+
540
+ # 清理剩余的模板标记
541
+ import re
542
+ # 移除任何剩余的 {{#...}} 和 {{/...}} 标记
543
+ result = re.sub(r'\{\{[#/][^}]+\}\}', '', result)
544
+ # 移除多余的空行
545
+ result = re.sub(r'\n\s*\n\s*\n', '\n\n', result)
546
+
547
+ return result.strip()
548
+
549
+ def _get_chinese_isl_path(self) -> str:
550
+ """
551
+ 获取中文ISL文件路径.
552
+ """
553
+ if self._project_chinese_file:
554
+ return str(Path(self._project_chinese_file).resolve()).replace('/', '\\')
555
+ else:
556
+ return 'compiler:Languages\\ChineseSimplified.isl'
557
+
558
+ def _generate_iss_script(
559
+ self, config: Dict[str, Any], source_path: Path, output_path: Path
560
+ ) -> str:
561
+ """
562
+ 内置ISS脚本生成逻辑 (回退方案).
563
+ """
564
+ app_name = self.config.get("name", "MyApp")
565
+ app_version = self.config.get("version", "1.0.0")
566
+ publisher = self.config.get("publisher", "Unknown Publisher")
567
+ app_url = config.get("app_url", "")
568
+ display_name = self.config.get("display_name", app_name)
569
+
570
+ # 确定源文件路径 - 修复路径分隔符问题
571
+ source_path_str = str(source_path).replace('/', '\\')
572
+
573
+ if source_path.is_file():
574
+ # 单文件模式
575
+ source_files = f'Source: "{source_path_str}"; DestDir: "{{app}}"; Flags: ignoreversion'
576
+ exe_name = source_path.name
577
+ else:
578
+ # 目录模式 - 确保正确的通配符路径
579
+ source_files = f'Source: "{source_path_str}\\*"; DestDir: "{{app}}"; Flags: ignoreversion recursesubdirs createallsubdirs'
580
+ # 在目录模式下,可执行文件通常是 app_name.exe
581
+ exe_name = f"{app_name}.exe"
582
+
583
+ # 构建Setup节 - 修复路径问题和空值处理
584
+ app_id = config.get('app_id', None)
585
+ if not app_id:
586
+ # 生成基于应用名称的伪GUID格式
587
+ import hashlib
588
+ name_hash = hashlib.md5(app_name.encode()).hexdigest()[:8].upper()
589
+ app_id = f"{{C4D8B3F2-1234-5678-9ABC-{name_hash}12345678}}"
590
+ elif not (app_id.startswith('{') and app_id.endswith('}')):
591
+ # 确保使用花括号格式
592
+ app_id = f"{{{app_id}}}"
593
+
594
+ # 处理路径中的反斜杠
595
+ output_dir = str(output_path.parent).replace('/', '\\')
596
+
597
+ setup_section = f"""[Setup]
598
+ AppId={app_id}
599
+ AppName={app_name}
600
+ AppVersion={app_version}
601
+ AppVerName={display_name} {app_version}
602
+ AppPublisher={publisher}
603
+ DefaultDirName={{autopf}}\\{app_name}
604
+ DefaultGroupName={app_name}
605
+ AllowNoIcons=yes
606
+ OutputDir={output_dir}
607
+ OutputBaseFilename={output_path.stem}
608
+ Compression=lzma
609
+ SolidCompression=yes
610
+ WizardStyle=modern"""
611
+
612
+ # 只在存在时添加可选字段
613
+ if app_url:
614
+ setup_section += f"\nAppPublisherURL={app_url}"
615
+ setup_section += f"\nAppSupportURL={app_url}"
616
+ setup_section += f"\nAppUpdatesURL={app_url}"
617
+
618
+ license_file = config.get('license_file', '')
619
+ if license_file and os.path.exists(license_file):
620
+ license_path = str(Path(license_file)).replace('/', '\\')
621
+ setup_section += f"\nLicenseFile={license_path}"
622
+
623
+ setup_icon = config.get('setup_icon', '')
624
+ if setup_icon and os.path.exists(setup_icon):
625
+ setup_icon_path = str(Path(setup_icon)).replace('/', '\\')
626
+ setup_section += f"\nSetupIconFile={setup_icon_path}"
627
+
628
+ # 语言支持
629
+ languages_section = "[Languages]"
630
+ languages = config.get("languages", ["english"])
631
+ if "english" in languages:
632
+ languages_section += (
633
+ '\nName: "english"; MessagesFile: "compiler:Default.isl"'
634
+ )
635
+ if "chinesesimplified" in languages or "chinese" in languages:
636
+ # 优先使用项目自带的中文语言文件
637
+ if hasattr(self, "_project_chinese_file") and self._project_chinese_file:
638
+ # 使用项目自带的语言文件,需要转换为相对路径或绝对路径
639
+ chinese_file_path = os.path.abspath(self._project_chinese_file).replace(
640
+ "\\", "\\\\"
641
+ )
642
+ languages_section += (
643
+ f'\nName: "chinesesimplified"; MessagesFile: "{chinese_file_path}"'
644
+ )
645
+ else:
646
+ # 使用系统中的语言文件
647
+ languages_section += '\nName: "chinesesimplified"; MessagesFile: "compiler:Languages\\ChineseSimplified.isl"'
648
+
649
+ # 任务节
650
+ tasks_section = "[Tasks]"
651
+ if config.get("create_desktop_icon", True):
652
+ tasks_section += f'\nName: "desktopicon"; Description: "{{cm:CreateDesktopIcon}}"; GroupDescription: "{{cm:AdditionalIcons}}"; Flags: unchecked'
653
+
654
+ # 文件节
655
+ files_section = f"[Files]\n{source_files}"
656
+
657
+ # 图标节 - 使用 display_name 作为快捷方式名称
658
+ icons_section = "[Icons]"
659
+ icons_section += f'\nName: "{{group}}\\{display_name}"; Filename: "{{app}}\\{exe_name}"'
660
+
661
+ if config.get("create_desktop_icon", True):
662
+ icons_section += f'\nName: "{{autodesktop}}\\{display_name}"; Filename: "{{app}}\\{exe_name}"; Tasks: desktopicon'
663
+
664
+ # 添加卸载程序快捷方式
665
+ icons_section += f'\nName: "{{group}}\\{{cm:UninstallProgram,{display_name}}}"; Filename: "{{uninstallexe}}"'
666
+
667
+ # 运行节
668
+ run_section = "[Run]"
669
+ if config.get("run_after_install", False):
670
+ run_section += f'\nFilename: "{{app}}\\{exe_name}"; Description: "{{cm:LaunchProgram,{display_name}}}"; Flags: nowait postinstall skipifsilent'
671
+
672
+ # 组装完整脚本
673
+ iss_script = f"""; Script generated by UnifyPy 2.0
674
+ ; Inno Setup Script
675
+ ; Encoding: UTF-8
676
+
677
+ {setup_section}
678
+
679
+ {languages_section}
680
+
681
+ {tasks_section}
682
+
683
+ {files_section}
684
+
685
+ {icons_section}
686
+
687
+ {run_section}
688
+ """
689
+
690
+ return iss_script
691
+
692
+ def validate_config(self, format_type: str) -> List[str]:
693
+ """
694
+ 验证Inno Setup配置.
695
+ """
696
+ errors = []
697
+
698
+ config = self.get_format_config("inno_setup")
699
+
700
+ # 检查Inno Setup编译器
701
+ compiler_path = self._find_inno_setup_compiler()
702
+ if not compiler_path:
703
+ errors.append("未找到Inno Setup编译器 (ISCC.exe)。请安装Inno Setup或在配置中指定路径")
704
+
705
+ # 检查许可证文件
706
+ license_file = config.get("license_file")
707
+ if license_file and not os.path.exists(license_file):
708
+ errors.append(f"许可证文件不存在: {license_file}")
709
+
710
+ # 检查图标文件
711
+ setup_icon = config.get("setup_icon")
712
+ if setup_icon and not os.path.exists(setup_icon):
713
+ errors.append(f"安装程序图标文件不存在: {setup_icon}")
714
+
715
+ return errors