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,195 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 静默命令执行器 只在错误时输出详细信息.
5
+ """
6
+
7
+ import subprocess
8
+ import sys
9
+ from typing import List, Optional, Union
10
+
11
+ from .progress import ProgressManager
12
+
13
+
14
+ class SilentRunner:
15
+ """
16
+ 静默命令执行器,只在错误时输出.
17
+ """
18
+
19
+ def __init__(self, progress_manager: ProgressManager):
20
+ """初始化命令执行器.
21
+
22
+ Args:
23
+ progress_manager: 进度管理器实例
24
+ """
25
+ self.progress = progress_manager
26
+ self.log_buffer = []
27
+
28
+ def run_command(
29
+ self,
30
+ command: Union[str, List[str]],
31
+ stage: str,
32
+ step_description: str = "",
33
+ step_weight: int = 10,
34
+ capture_output: bool = True,
35
+ shell: bool = True,
36
+ cwd: Optional[str] = None,
37
+ ) -> bool:
38
+ """执行命令,只在错误时显示输出.
39
+
40
+ Args:
41
+ command: 要执行的命令
42
+ stage: 当前阶段名称
43
+ step_description: 步骤描述
44
+ step_weight: 进度权重
45
+ capture_output: 是否捕获输出
46
+ shell: 是否使用shell执行
47
+
48
+ Returns:
49
+ bool: 执行是否成功
50
+ """
51
+ # 更新进度描述
52
+ if step_description:
53
+ self.progress.update_stage(stage, advance=0, description=step_description)
54
+
55
+ # 在verbose模式下显示执行的命令
56
+ if self.progress.verbose:
57
+ cmd_str = " ".join(command) if isinstance(command, list) else command
58
+ self.progress.info(f"执行命令: {cmd_str}")
59
+
60
+ try:
61
+ # 执行命令
62
+ if capture_output:
63
+ result = subprocess.run(
64
+ command,
65
+ shell=shell,
66
+ capture_output=True,
67
+ text=True,
68
+ encoding="utf-8",
69
+ cwd=cwd,
70
+ )
71
+ else:
72
+ result = subprocess.run(
73
+ command,
74
+ shell=shell,
75
+ stdout=subprocess.PIPE,
76
+ stderr=subprocess.PIPE,
77
+ text=True,
78
+ encoding="utf-8",
79
+ cwd=cwd,
80
+ )
81
+
82
+ # 检查执行结果
83
+ if result.returncode == 0:
84
+ # 成功时更新进度
85
+ self.progress.update_stage(stage, advance=step_weight)
86
+
87
+ # 在verbose模式下显示输出
88
+ if (
89
+ self.progress.verbose
90
+ and hasattr(result, "stdout")
91
+ and result.stdout
92
+ ):
93
+ self.progress.info(f"输出: {result.stdout.strip()}")
94
+
95
+ return True
96
+ else:
97
+ # 失败时显示错误信息
98
+ error_msg = f"命令执行失败 (返回码: {result.returncode})"
99
+
100
+ details = ""
101
+ if hasattr(result, "stderr") and result.stderr:
102
+ details += f"\n[red]错误输出:[/red]\n{result.stderr}"
103
+ if hasattr(result, "stdout") and result.stdout:
104
+ details += f"\n[yellow]标准输出:[/yellow]\n{result.stdout}"
105
+
106
+ cmd_str = " ".join(command) if isinstance(command, list) else command
107
+ details += f"\n[cyan]执行的命令:[/cyan]\n{cmd_str}"
108
+
109
+ self.progress.on_error(Exception(error_msg), stage, details)
110
+ return False
111
+
112
+ except FileNotFoundError as e:
113
+ self.progress.on_error(
114
+ Exception(f"命令未找到: {e}"),
115
+ stage,
116
+ f"\n请确认相关工具已正确安装并在PATH中。\n命令: {command}",
117
+ )
118
+ return False
119
+
120
+ except KeyboardInterrupt:
121
+ # 传递给上层,由引擎统一处理
122
+ raise
123
+ except Exception as e:
124
+ self.progress.on_error(e, stage)
125
+ return False
126
+
127
+ def run_python_script(
128
+ self,
129
+ script_path: str,
130
+ args: List[str],
131
+ stage: str,
132
+ step_description: str = "",
133
+ step_weight: int = 10,
134
+ ) -> bool:
135
+ """执行Python脚本.
136
+
137
+ Args:
138
+ script_path: 脚本路径
139
+ args: 脚本参数
140
+ stage: 当前阶段
141
+ step_description: 步骤描述
142
+ step_weight: 进度权重
143
+
144
+ Returns:
145
+ bool: 执行是否成功
146
+ """
147
+ command = [sys.executable, script_path] + args
148
+ return self.run_command(
149
+ command, stage, step_description, step_weight, shell=False
150
+ )
151
+
152
+ def check_tool_available(self, tool_name: str) -> bool:
153
+ """检查工具是否可用.
154
+
155
+ Args:
156
+ tool_name: 工具名称
157
+
158
+ Returns:
159
+ bool: 工具是否可用
160
+ """
161
+ try:
162
+ result = subprocess.run(
163
+ [tool_name, "--version"], capture_output=True, text=True
164
+ )
165
+ return result.returncode == 0
166
+ except FileNotFoundError:
167
+ return False
168
+ except:
169
+ # 有些工具可能不支持--version,尝试--help
170
+ try:
171
+ result = subprocess.run(
172
+ [tool_name, "--help"], capture_output=True, text=True
173
+ )
174
+ return result.returncode == 0
175
+ except:
176
+ return False
177
+
178
+ def get_tool_version(self, tool_name: str) -> Optional[str]:
179
+ """获取工具版本.
180
+
181
+ Args:
182
+ tool_name: 工具名称
183
+
184
+ Returns:
185
+ Optional[str]: 工具版本,如果无法获取则返回None
186
+ """
187
+ try:
188
+ result = subprocess.run(
189
+ [tool_name, "--version"], capture_output=True, text=True
190
+ )
191
+ if result.returncode == 0:
192
+ return result.stdout.strip()
193
+ except:
194
+ pass
195
+ return None
@@ -0,0 +1,450 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ MacOS Entitlements.plist 自动生成器 根据配置自动生成 entitlements.plist 文件.
5
+ """
6
+
7
+ from pathlib import Path
8
+ from typing import Any, Dict, List
9
+
10
+
11
+ class EntitlementsGenerator:
12
+ """
13
+ MacOS Entitlements.plist 自动生成器.
14
+ """
15
+
16
+ # Info.plist 权限描述到 Entitlements 权限的映射
17
+ #
18
+ # 重要说明:
19
+ # - 摄像头权限: com.apple.security.device.camera 适用于沙盒和非沙盒应用
20
+ # - 麦克风权限: 需要根据应用类型选择不同的entitlement:
21
+ # * 沙盒应用: com.apple.security.device.microphone
22
+ # * 非沙盒应用: com.apple.security.device.audio-input
23
+ # - 屏幕录制权限: com.apple.security.device.screen-capture 适用于所有应用
24
+ PRIVACY_TO_ENTITLEMENTS_MAPPING = {
25
+ # 媒体设备权限 - 麦克风 (根据应用类型选择不同的entitlement)
26
+ "NSMicrophoneUsageDescription": [
27
+ "com.apple.security.device.audio-input", # 加固运行时应用 (非沙盒)
28
+ "com.apple.security.device.microphone", # 沙盒应用 (Mac App Store)
29
+ ],
30
+ "NSCameraUsageDescription": ["com.apple.security.device.camera"],
31
+ # 屏幕录制权限
32
+ "NSScreenCaptureUsageDescription": ["com.apple.security.device.screen-capture"],
33
+ # 位置服务权限
34
+ "NSLocationWhenInUseUsageDescription": [
35
+ "com.apple.security.personal-information.location"
36
+ ],
37
+ "NSLocationAlwaysAndWhenInUseUsageDescription": [
38
+ "com.apple.security.personal-information.location"
39
+ ],
40
+ # 个人信息权限
41
+ "NSContactsUsageDescription": [
42
+ "com.apple.security.personal-information.addressbook"
43
+ ],
44
+ "NSCalendarsUsageDescription": [
45
+ "com.apple.security.personal-information.calendars"
46
+ ],
47
+ "NSRemindersUsageDescription": [
48
+ "com.apple.security.personal-information.calendars"
49
+ ],
50
+ # 照片和媒体权限
51
+ "NSPhotoLibraryUsageDescription": [
52
+ "com.apple.security.assets.pictures.read-only"
53
+ ],
54
+ "NSPhotoLibraryAddUsageDescription": [
55
+ "com.apple.security.assets.pictures.read-write"
56
+ ],
57
+ # 音乐权限
58
+ "NSAppleMusicUsageDescription": ["com.apple.security.assets.music.read-only"],
59
+ # 蓝牙权限
60
+ "NSBluetoothAlwaysUsageDescription": ["com.apple.security.device.bluetooth"],
61
+ "NSBluetoothPeripheralUsageDescription": [
62
+ "com.apple.security.device.bluetooth"
63
+ ],
64
+ # 网络权限
65
+ "NSLocalNetworkUsageDescription": [
66
+ "com.apple.security.network.client",
67
+ "com.apple.security.network.server",
68
+ ],
69
+ }
70
+
71
+ # 配置键到 Info.plist 键的映射
72
+ CONFIG_TO_PLIST_MAPPING = {
73
+ "microphone_usage_description": "NSMicrophoneUsageDescription",
74
+ "camera_usage_description": "NSCameraUsageDescription",
75
+ "screen_capture_usage_description": "NSScreenCaptureUsageDescription",
76
+ "location_when_in_use_usage_description": "NSLocationWhenInUseUsageDescription",
77
+ "location_always_and_when_in_use_usage_description": "NSLocationAlwaysAndWhenInUseUsageDescription",
78
+ "contacts_usage_description": "NSContactsUsageDescription",
79
+ "calendars_usage_description": "NSCalendarsUsageDescription",
80
+ "reminders_usage_description": "NSRemindersUsageDescription",
81
+ "photo_library_usage_description": "NSPhotoLibraryUsageDescription",
82
+ "photo_library_add_usage_description": "NSPhotoLibraryAddUsageDescription",
83
+ "music_usage_description": "NSAppleMusicUsageDescription",
84
+ "bluetooth_always_usage_description": "NSBluetoothAlwaysUsageDescription",
85
+ "bluetooth_peripheral_usage_description": "NSBluetoothPeripheralUsageDescription",
86
+ "local_network_usage_description": "NSLocalNetworkUsageDescription",
87
+ "apple_events_usage_description": "NSAppleEventsUsageDescription",
88
+ "system_administration_usage_description": "NSSystemAdministrationUsageDescription",
89
+ "accessibility_usage_description": "NSAccessibilityUsageDescription",
90
+ "desktop_folder_usage_description": "NSDesktopFolderUsageDescription",
91
+ "documents_folder_usage_description": "NSDocumentsFolderUsageDescription",
92
+ "downloads_folder_usage_description": "NSDownloadsFolderUsageDescription",
93
+ "network_volumes_usage_description": "NSNetworkVolumesUsageDescription",
94
+ "removable_volumes_usage_description": "NSRemovableVolumesUsageDescription",
95
+ }
96
+
97
+ def __init__(self, progress_callback=None):
98
+ """
99
+ 初始化生成器.
100
+
101
+ Args:
102
+ progress_callback: 进度回调函数(可选)
103
+ """
104
+ self.progress_callback = progress_callback
105
+
106
+ def generate_entitlements(
107
+ self, macos_config: Dict[str, Any], development: bool = False
108
+ ) -> str:
109
+ """根据配置生成 entitlements.plist 内容.
110
+
111
+ Args:
112
+ macos_config: macOS 配置字典
113
+ development: 是否为开发版本
114
+
115
+ Returns:
116
+ str: entitlements.plist 文件内容
117
+ """
118
+ entitlements = {}
119
+
120
+ # 根据隐私权限描述添加相应的 entitlements
121
+ required_entitlements = self._extract_required_entitlements(macos_config)
122
+ entitlements.update(required_entitlements)
123
+
124
+ # 添加基础网络权限(大多数应用都需要)
125
+ if self._needs_network_access(macos_config):
126
+ entitlements["com.apple.security.network.client"] = True
127
+ # 如果有网络服务需求,添加服务端权限
128
+ if macos_config.get("local_network_usage_description"):
129
+ entitlements["com.apple.security.network.server"] = True
130
+
131
+ # 沙盒配置
132
+ if macos_config.get("sandboxed", False):
133
+ entitlements["com.apple.security.app-sandbox"] = True
134
+ # 沙盒模式下的额外配置
135
+ self._add_sandbox_entitlements(entitlements, macos_config)
136
+ else:
137
+ entitlements["com.apple.security.app-sandbox"] = False
138
+
139
+ # 开发版本的特殊配置
140
+ if development:
141
+ self._add_development_entitlements(entitlements)
142
+
143
+ # 特殊权限处理
144
+ self._add_special_entitlements(entitlements, macos_config)
145
+
146
+ return self._generate_plist_content(entitlements)
147
+
148
+ def _extract_required_entitlements(
149
+ self, macos_config: Dict[str, Any]
150
+ ) -> Dict[str, Any]:
151
+ """
152
+ 从配置中提取所需的 entitlements.
153
+ """
154
+ entitlements = {}
155
+ is_sandboxed = macos_config.get("sandboxed", False)
156
+
157
+ for config_key, description in macos_config.items():
158
+ # 检查是否是权限描述配置
159
+ if config_key in self.CONFIG_TO_PLIST_MAPPING and description:
160
+ plist_key = self.CONFIG_TO_PLIST_MAPPING[config_key]
161
+
162
+ # 获取对应的 entitlements
163
+ if plist_key in self.PRIVACY_TO_ENTITLEMENTS_MAPPING:
164
+ entitlement_list = self.PRIVACY_TO_ENTITLEMENTS_MAPPING[plist_key]
165
+
166
+ # 特殊处理麦克风权限 - 根据沙盒状态选择正确的entitlement
167
+ if plist_key == "NSMicrophoneUsageDescription":
168
+ if is_sandboxed:
169
+ # 沙盒应用使用 microphone entitlement
170
+ entitlements["com.apple.security.device.microphone"] = True
171
+ else:
172
+ # 非沙盒应用使用 audio-input entitlement
173
+ entitlements["com.apple.security.device.audio-input"] = True
174
+ else:
175
+ # 其他权限按原逻辑处理
176
+ for entitlement in entitlement_list:
177
+ if entitlement: # 跳过空字符串
178
+ entitlements[entitlement] = True
179
+
180
+ return entitlements
181
+
182
+ def _needs_network_access(self, macos_config: Dict[str, Any]) -> bool:
183
+ """
184
+ 判断应用是否需要网络访问权限.
185
+ """
186
+ # 如果配置了网络相关权限描述,说明需要网络访问
187
+ network_indicators = [
188
+ "local_network_usage_description",
189
+ ]
190
+
191
+ for indicator in network_indicators:
192
+ if macos_config.get(indicator):
193
+ return True
194
+
195
+ # 如果配置了 ATS,说明需要网络访问
196
+ if macos_config.get("app_transport_security"):
197
+ return True
198
+
199
+ # 默认假设需要网络访问(大多数现代应用都需要)
200
+ return True
201
+
202
+ def _add_sandbox_entitlements(
203
+ self, entitlements: Dict[str, Any], macos_config: Dict[str, Any]
204
+ ):
205
+ """
206
+ 添加沙盒模式下的 entitlements.
207
+ """
208
+ # 沙盒模式下需要明确指定文件访问权限
209
+ if any(
210
+ key in macos_config
211
+ for key in [
212
+ "desktop_folder_usage_description",
213
+ "documents_folder_usage_description",
214
+ "downloads_folder_usage_description",
215
+ ]
216
+ ):
217
+ entitlements["com.apple.security.files.user-selected.read-write"] = True
218
+
219
+ # 如果需要访问特定文件夹
220
+ if macos_config.get("downloads_folder_usage_description"):
221
+ entitlements["com.apple.security.files.downloads.read-write"] = True
222
+
223
+ if macos_config.get("photo_library_usage_description"):
224
+ entitlements["com.apple.security.assets.pictures.read-only"] = True
225
+
226
+ if macos_config.get("photo_library_add_usage_description"):
227
+ entitlements["com.apple.security.assets.pictures.read-write"] = True
228
+
229
+ def _add_development_entitlements(self, entitlements: Dict[str, Any]):
230
+ """
231
+ 添加开发版本的 entitlements(用于未签名应用)
232
+ """
233
+ # 调试权限
234
+ entitlements["com.apple.security.get-task-allow"] = True
235
+
236
+ # Python 应用的必需权限
237
+ entitlements["com.apple.security.cs.allow-jit"] = True
238
+ entitlements["com.apple.security.cs.allow-unsigned-executable-memory"] = True
239
+
240
+ # 禁用库验证(Python 动态加载需要)
241
+ entitlements["com.apple.security.cs.disable-library-validation"] = True
242
+
243
+ # 允许动态环境变量(Python 需要)
244
+ entitlements["com.apple.security.cs.allow-dyld-environment-variables"] = True
245
+
246
+ # 文件系统访问权限(未签名应用需要)
247
+ entitlements["com.apple.security.files.user-selected.read-write"] = True
248
+ entitlements["com.apple.security.files.documents.read-write"] = True
249
+ entitlements["com.apple.security.files.downloads.read-write"] = True
250
+ entitlements["com.apple.security.files.home.read-write"] = True
251
+
252
+ # AppleScript 权限(自动化需要)
253
+ entitlements["com.apple.security.automation.apple-events"] = True
254
+
255
+ def _add_special_entitlements(
256
+ self, entitlements: Dict[str, Any], macos_config: Dict[str, Any]
257
+ ):
258
+ """
259
+ 添加特殊权限配置.
260
+ """
261
+ # AppleScript 权限需要特殊处理
262
+ if macos_config.get("apple_events_usage_description"):
263
+ # 添加常见的脚本目标
264
+ scripting_targets = {
265
+ "com.apple.finder": ["com.apple.events.appleevents"],
266
+ "com.apple.systemevents": ["com.apple.events.appleevents"],
267
+ }
268
+
269
+ # 如果用户自定义了脚本目标,使用用户配置
270
+ if "scripting_targets" in macos_config:
271
+ scripting_targets.update(macos_config["scripting_targets"])
272
+
273
+ entitlements["com.apple.security.scripting-targets"] = scripting_targets
274
+
275
+ # 应用组权限
276
+ if "app_groups" in macos_config:
277
+ app_groups = macos_config["app_groups"]
278
+ if isinstance(app_groups, list):
279
+ entitlements["com.apple.security.application-groups"] = app_groups
280
+
281
+ # 打印权限
282
+ if macos_config.get("print_access", False):
283
+ entitlements["com.apple.security.print"] = True
284
+
285
+ def _generate_plist_content(self, entitlements: Dict[str, Any]) -> str:
286
+ """
287
+ 生成 plist 文件内容.
288
+ """
289
+ content_parts = [
290
+ '<?xml version="1.0" encoding="UTF-8"?>',
291
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
292
+ '<plist version="1.0">',
293
+ "<dict>",
294
+ ]
295
+
296
+ # 按键名排序以确保输出一致性
297
+ for key in sorted(entitlements.keys()):
298
+ value = entitlements[key]
299
+ content_parts.extend(self._format_plist_entry(key, value))
300
+
301
+ content_parts.extend(["</dict>", "</plist>"])
302
+
303
+ return "\n".join(content_parts)
304
+
305
+ def _format_plist_entry(self, key: str, value: Any) -> List[str]:
306
+ """
307
+ 格式化单个 plist 条目.
308
+ """
309
+ lines = [f" <key>{key}</key>"]
310
+
311
+ if isinstance(value, bool):
312
+ bool_str = "true" if value else "false"
313
+ lines.append(f" <{bool_str}/>")
314
+ elif isinstance(value, str):
315
+ lines.append(f" <string>{value}</string>")
316
+ elif isinstance(value, (int, float)):
317
+ lines.append(f" <real>{value}</real>")
318
+ elif isinstance(value, list):
319
+ lines.append(" <array>")
320
+ for item in value:
321
+ if isinstance(item, str):
322
+ lines.append(f" <string>{item}</string>")
323
+ lines.append(" </array>")
324
+ elif isinstance(value, dict):
325
+ lines.append(" <dict>")
326
+ for sub_key in sorted(value.keys()):
327
+ sub_value = value[sub_key]
328
+ lines.append(f" <key>{sub_key}</key>")
329
+ if isinstance(sub_value, list):
330
+ lines.append(" <array>")
331
+ for item in sub_value:
332
+ lines.append(f" <string>{item}</string>")
333
+ lines.append(" </array>")
334
+ else:
335
+ lines.append(f" <string>{sub_value}</string>")
336
+ lines.append(" </dict>")
337
+
338
+ return lines
339
+
340
+ def generate_entitlements_file(
341
+ self, macos_config: Dict[str, Any], output_path: Path, development: bool = False
342
+ ) -> bool:
343
+ """生成 entitlements.plist 文件.
344
+
345
+ Args:
346
+ macos_config: macOS 配置字典
347
+ output_path: 输出文件路径
348
+ development: 是否为开发版本
349
+
350
+ Returns:
351
+ bool: 是否生成成功
352
+ """
353
+ try:
354
+ content = self.generate_entitlements(macos_config, development)
355
+
356
+ # 确保输出目录存在
357
+ output_path.parent.mkdir(parents=True, exist_ok=True)
358
+
359
+ # 写入文件
360
+ with open(output_path, "w", encoding="utf-8") as f:
361
+ f.write(content)
362
+
363
+ return True
364
+
365
+ except Exception as e:
366
+ print(f"生成 entitlements.plist 失败: {e}")
367
+ return False
368
+
369
+ def get_required_entitlements_summary(
370
+ self, macos_config: Dict[str, Any]
371
+ ) -> Dict[str, List[str]]:
372
+ """获取所需权限的摘要信息.
373
+
374
+ Args:
375
+ macos_config: macOS 配置字典
376
+
377
+ Returns:
378
+ Dict: 权限分类摘要
379
+ """
380
+ summary = {
381
+ "设备权限": [],
382
+ "网络权限": [],
383
+ "文件访问权限": [],
384
+ "个人信息权限": [],
385
+ "系统权限": [],
386
+ "开发权限": [],
387
+ }
388
+
389
+ # 分析配置中的权限
390
+ for config_key, description in macos_config.items():
391
+ if config_key in self.CONFIG_TO_PLIST_MAPPING and description:
392
+ permission_name = self._get_permission_friendly_name(config_key)
393
+ category = self._get_permission_category(config_key)
394
+
395
+ if category in summary:
396
+ summary[category].append(permission_name)
397
+
398
+ # 移除空的分类
399
+ return {k: v for k, v in summary.items() if v}
400
+
401
+ def _get_permission_friendly_name(self, config_key: str) -> str:
402
+ """
403
+ 获取权限的友好名称.
404
+ """
405
+ name_mapping = {
406
+ "microphone_usage_description": "麦克风访问",
407
+ "camera_usage_description": "摄像头访问",
408
+ "location_when_in_use_usage_description": "位置服务(使用时)",
409
+ "location_always_and_when_in_use_usage_description": "位置服务(始终)",
410
+ "contacts_usage_description": "通讯录访问",
411
+ "calendars_usage_description": "日历访问",
412
+ "reminders_usage_description": "提醒事项访问",
413
+ "photo_library_usage_description": "照片库访问",
414
+ "photo_library_add_usage_description": "照片库写入",
415
+ "bluetooth_always_usage_description": "蓝牙访问",
416
+ "local_network_usage_description": "本地网络访问",
417
+ "apple_events_usage_description": "AppleScript 控制",
418
+ "system_administration_usage_description": "系统管理权限",
419
+ "accessibility_usage_description": "辅助功能",
420
+ "desktop_folder_usage_description": "桌面文件夹访问",
421
+ "documents_folder_usage_description": "文档文件夹访问",
422
+ "downloads_folder_usage_description": "下载文件夹访问",
423
+ }
424
+ return name_mapping.get(config_key, config_key)
425
+
426
+ def _get_permission_category(self, config_key: str) -> str:
427
+ """
428
+ 获取权限所属分类.
429
+ """
430
+ category_mapping = {
431
+ "microphone_usage_description": "设备权限",
432
+ "camera_usage_description": "设备权限",
433
+ "bluetooth_always_usage_description": "设备权限",
434
+ "bluetooth_peripheral_usage_description": "设备权限",
435
+ "local_network_usage_description": "网络权限",
436
+ "contacts_usage_description": "个人信息权限",
437
+ "calendars_usage_description": "个人信息权限",
438
+ "reminders_usage_description": "个人信息权限",
439
+ "location_when_in_use_usage_description": "个人信息权限",
440
+ "location_always_and_when_in_use_usage_description": "个人信息权限",
441
+ "photo_library_usage_description": "文件访问权限",
442
+ "photo_library_add_usage_description": "文件访问权限",
443
+ "desktop_folder_usage_description": "文件访问权限",
444
+ "documents_folder_usage_description": "文件访问权限",
445
+ "downloads_folder_usage_description": "文件访问权限",
446
+ "apple_events_usage_description": "系统权限",
447
+ "system_administration_usage_description": "系统权限",
448
+ "accessibility_usage_description": "系统权限",
449
+ }
450
+ return category_mapping.get(config_key, "其他权限")