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,484 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 回滚机制 当构建失败时,自动恢复到之前的状态.
5
+ """
6
+
7
+ import json
8
+ import shutil
9
+ import time
10
+ from dataclasses import asdict, dataclass
11
+ from enum import Enum
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional
14
+
15
+
16
+ class OperationType(Enum):
17
+ """
18
+ 操作类型枚举.
19
+ """
20
+
21
+ CREATE_FILE = "create_file"
22
+ CREATE_DIR = "create_dir"
23
+ MODIFY_FILE = "modify_file"
24
+ DELETE_FILE = "delete_file"
25
+ MOVE_FILE = "move_file"
26
+ COPY_FILE = "copy_file"
27
+
28
+
29
+ @dataclass
30
+ class RollbackOperation:
31
+ """
32
+ 回滚操作记录.
33
+ """
34
+
35
+ operation_type: OperationType
36
+ target_path: str
37
+ backup_path: Optional[str] = None
38
+ original_content: Optional[str] = None
39
+ timestamp: float = 0.0
40
+
41
+ def __post_init__(self):
42
+ if self.timestamp == 0.0:
43
+ self.timestamp = time.time()
44
+
45
+
46
+ class RollbackManager:
47
+ """
48
+ 回滚管理器.
49
+ """
50
+
51
+ def __init__(self, project_dir: Path, progress_manager=None):
52
+ """初始化回滚管理器.
53
+
54
+ Args:
55
+ project_dir: 项目根目录
56
+ progress_manager: 进度管理器
57
+ """
58
+ self.project_dir = project_dir
59
+ self.progress = progress_manager
60
+ self.rollback_dir = project_dir / ".unifypy_rollback"
61
+ self.operations: List[RollbackOperation] = []
62
+ self.session_id = str(int(time.time()))
63
+
64
+ # 创建回滚目录
65
+ self.rollback_dir.mkdir(exist_ok=True)
66
+ # 写入 .gitignore,避免被纳入版本控制
67
+ try:
68
+ gi = self.rollback_dir / ".gitignore"
69
+ if not gi.exists():
70
+ with open(gi, "w", encoding="utf-8") as f:
71
+ f.write("*\n")
72
+ except Exception:
73
+ pass
74
+
75
+ # 备份目录
76
+ self.backup_dir = self.rollback_dir / f"backup_{self.session_id}"
77
+ self.backup_dir.mkdir(exist_ok=True)
78
+
79
+ # 操作日志文件
80
+ self.log_file = self.rollback_dir / f"operations_{self.session_id}.json"
81
+
82
+ def __enter__(self):
83
+ """
84
+ 进入上下文管理器.
85
+ """
86
+ self._log_info("开始跟踪文件操作...")
87
+ return self
88
+
89
+ def __exit__(self, exc_type, exc_val, exc_tb):
90
+ """
91
+ 退出上下文管理器.
92
+ """
93
+ if exc_type is not None:
94
+ # 发生异常,执行回滚
95
+ self._log_info("检测到异常,开始自动回滚...")
96
+ self.rollback()
97
+ else:
98
+ # 正常完成,清理回滚数据
99
+ self._log_info("构建成功完成,清理回滚数据...")
100
+ self.cleanup()
101
+
102
+ def track_file_creation(self, file_path: Path) -> None:
103
+ """
104
+ 跟踪文件创建.
105
+ """
106
+ operation = RollbackOperation(
107
+ operation_type=OperationType.CREATE_FILE, target_path=str(file_path)
108
+ )
109
+ self.operations.append(operation)
110
+ self._save_operations()
111
+ self._log_debug(f"跟踪文件创建: {file_path}")
112
+
113
+ def track_dir_creation(self, dir_path: Path) -> None:
114
+ """
115
+ 跟踪目录创建.
116
+ """
117
+ operation = RollbackOperation(
118
+ operation_type=OperationType.CREATE_DIR, target_path=str(dir_path)
119
+ )
120
+ self.operations.append(operation)
121
+ self._save_operations()
122
+ self._log_debug(f"跟踪目录创建: {dir_path}")
123
+
124
+ def track_file_modification(self, file_path: Path) -> None:
125
+ """
126
+ 跟踪文件修改.
127
+ """
128
+ if not file_path.exists():
129
+ return
130
+
131
+ # 创建备份
132
+ backup_filename = f"{file_path.name}_{len(self.operations)}"
133
+ backup_path = self.backup_dir / backup_filename
134
+
135
+ try:
136
+ shutil.copy2(file_path, backup_path)
137
+
138
+ operation = RollbackOperation(
139
+ operation_type=OperationType.MODIFY_FILE,
140
+ target_path=str(file_path),
141
+ backup_path=str(backup_path),
142
+ )
143
+ self.operations.append(operation)
144
+ self._save_operations()
145
+ self._log_debug(f"跟踪文件修改: {file_path}")
146
+
147
+ except Exception as e:
148
+ self._log_warning(f"备份文件失败: {file_path}, 错误: {e}")
149
+
150
+ def track_file_deletion(self, file_path: Path) -> None:
151
+ """
152
+ 跟踪文件删除.
153
+ """
154
+ if not file_path.exists():
155
+ return
156
+
157
+ # 创建备份
158
+ backup_filename = f"{file_path.name}_{len(self.operations)}_deleted"
159
+ backup_path = self.backup_dir / backup_filename
160
+
161
+ try:
162
+ shutil.copy2(file_path, backup_path)
163
+
164
+ operation = RollbackOperation(
165
+ operation_type=OperationType.DELETE_FILE,
166
+ target_path=str(file_path),
167
+ backup_path=str(backup_path),
168
+ )
169
+ self.operations.append(operation)
170
+ self._save_operations()
171
+ self._log_debug(f"跟踪文件删除: {file_path}")
172
+
173
+ except Exception as e:
174
+ self._log_warning(f"备份待删除文件失败: {file_path}, 错误: {e}")
175
+
176
+ def track_file_move(self, src_path: Path, dst_path: Path) -> None:
177
+ """
178
+ 跟踪文件移动.
179
+ """
180
+ operation = RollbackOperation(
181
+ operation_type=OperationType.MOVE_FILE,
182
+ target_path=str(dst_path),
183
+ backup_path=str(src_path), # 原始位置作为备份信息
184
+ )
185
+ self.operations.append(operation)
186
+ self._save_operations()
187
+ self._log_debug(f"跟踪文件移动: {src_path} -> {dst_path}")
188
+
189
+ def safe_create_file(self, file_path: Path, content: str = "") -> None:
190
+ """
191
+ 安全创建文件(带回滚跟踪)
192
+ """
193
+ self.track_file_creation(file_path)
194
+
195
+ try:
196
+ file_path.parent.mkdir(parents=True, exist_ok=True)
197
+ with open(file_path, "w", encoding="utf-8") as f:
198
+ f.write(content)
199
+ except Exception as e:
200
+ self._log_error(f"创建文件失败: {file_path}, 错误: {e}")
201
+ raise
202
+
203
+ def safe_create_dir(self, dir_path: Path) -> None:
204
+ """
205
+ 安全创建目录(带回滚跟踪)
206
+ """
207
+ if dir_path.exists():
208
+ return
209
+
210
+ self.track_dir_creation(dir_path)
211
+
212
+ try:
213
+ dir_path.mkdir(parents=True, exist_ok=True)
214
+ except Exception as e:
215
+ self._log_error(f"创建目录失败: {dir_path}, 错误: {e}")
216
+ raise
217
+
218
+ def safe_modify_file(self, file_path: Path, content: str) -> None:
219
+ """
220
+ 安全修改文件(带回滚跟踪)
221
+ """
222
+ self.track_file_modification(file_path)
223
+
224
+ try:
225
+ with open(file_path, "w", encoding="utf-8") as f:
226
+ f.write(content)
227
+ except Exception as e:
228
+ self._log_error(f"修改文件失败: {file_path}, 错误: {e}")
229
+ raise
230
+
231
+ def safe_delete_file(self, file_path: Path) -> None:
232
+ """
233
+ 安全删除文件(带回滚跟踪)
234
+ """
235
+ if not file_path.exists():
236
+ return
237
+
238
+ self.track_file_deletion(file_path)
239
+
240
+ try:
241
+ file_path.unlink()
242
+ except Exception as e:
243
+ self._log_error(f"删除文件失败: {file_path}, 错误: {e}")
244
+ raise
245
+
246
+ def safe_move_file(self, src_path: Path, dst_path: Path) -> None:
247
+ """
248
+ 安全移动文件(带回滚跟踪)
249
+ """
250
+ if not src_path.exists():
251
+ raise FileNotFoundError(f"源文件不存在: {src_path}")
252
+
253
+ self.track_file_move(src_path, dst_path)
254
+
255
+ try:
256
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
257
+ shutil.move(str(src_path), str(dst_path))
258
+ except Exception as e:
259
+ self._log_error(f"移动文件失败: {src_path} -> {dst_path}, 错误: {e}")
260
+ raise
261
+
262
+ def rollback(self) -> bool:
263
+ """
264
+ 执行回滚操作.
265
+ """
266
+ if not self.operations:
267
+ self._log_info("没有需要回滚的操作")
268
+ return True
269
+
270
+ self._log_info(f"开始回滚 {len(self.operations)} 个操作...")
271
+ success_count = 0
272
+
273
+ # 按时间倒序回滚
274
+ for operation in reversed(self.operations):
275
+ try:
276
+ success = self._rollback_single_operation(operation)
277
+ if success:
278
+ success_count += 1
279
+ else:
280
+ self._log_warning(f"回滚操作失败: {operation.operation_type.value}")
281
+
282
+ except Exception as e:
283
+ self._log_error(
284
+ f"回滚操作时发生异常: {operation.operation_type.value}, 错误: {e}"
285
+ )
286
+
287
+ self._log_info(f"回滚完成: {success_count}/{len(self.operations)} 个操作成功")
288
+ return success_count == len(self.operations)
289
+
290
+ def _rollback_single_operation(self, operation: RollbackOperation) -> bool:
291
+ """
292
+ 回滚单个操作.
293
+ """
294
+ target_path = Path(operation.target_path)
295
+
296
+ try:
297
+ if operation.operation_type == OperationType.CREATE_FILE:
298
+ # 删除创建的文件
299
+ if target_path.exists():
300
+ target_path.unlink()
301
+ self._log_debug(f"回滚: 删除文件 {target_path}")
302
+ return True
303
+
304
+ elif operation.operation_type == OperationType.CREATE_DIR:
305
+ # 删除创建的目录(仅当为空时)
306
+ if target_path.exists() and target_path.is_dir():
307
+ try:
308
+ target_path.rmdir() # 只删除空目录
309
+ self._log_debug(f"回滚: 删除目录 {target_path}")
310
+ except OSError:
311
+ # 目录不为空,不强制删除
312
+ self._log_debug(f"目录不为空,跳过删除: {target_path}")
313
+ return True
314
+
315
+ elif operation.operation_type == OperationType.MODIFY_FILE:
316
+ # 恢复文件内容
317
+ if operation.backup_path and Path(operation.backup_path).exists():
318
+ shutil.copy2(operation.backup_path, target_path)
319
+ self._log_debug(f"回滚: 恢复文件 {target_path}")
320
+ return True
321
+
322
+ elif operation.operation_type == OperationType.DELETE_FILE:
323
+ # 恢复删除的文件
324
+ if operation.backup_path and Path(operation.backup_path).exists():
325
+ target_path.parent.mkdir(parents=True, exist_ok=True)
326
+ shutil.copy2(operation.backup_path, target_path)
327
+ self._log_debug(f"回滚: 恢复删除的文件 {target_path}")
328
+ return True
329
+
330
+ elif operation.operation_type == OperationType.MOVE_FILE:
331
+ # 移回原位置
332
+ if target_path.exists() and operation.backup_path:
333
+ src_path = Path(operation.backup_path)
334
+ src_path.parent.mkdir(parents=True, exist_ok=True)
335
+ shutil.move(str(target_path), str(src_path))
336
+ self._log_debug(f"回滚: 移动文件 {target_path} -> {src_path}")
337
+ return True
338
+
339
+ except Exception as e:
340
+ self._log_error(
341
+ f"执行回滚操作失败: {operation.operation_type.value}, 错误: {e}"
342
+ )
343
+ return False
344
+
345
+ return False
346
+
347
+ def cleanup(self) -> None:
348
+ """
349
+ 清理回滚数据.
350
+ """
351
+ try:
352
+ # 删除备份目录
353
+ if self.backup_dir.exists():
354
+ shutil.rmtree(self.backup_dir)
355
+
356
+ # 删除操作日志
357
+ if self.log_file.exists():
358
+ self.log_file.unlink()
359
+
360
+ self._log_debug("回滚数据清理完成")
361
+
362
+ except Exception as e:
363
+ self._log_warning(f"清理回滚数据失败: {e}")
364
+
365
+ def _save_operations(self) -> None:
366
+ """
367
+ 保存操作记录到文件.
368
+ """
369
+ try:
370
+ operations_data = [asdict(op) for op in self.operations]
371
+ # 将枚举转换为字符串
372
+ for op_data in operations_data:
373
+ op_data["operation_type"] = op_data["operation_type"].value
374
+
375
+ with open(self.log_file, "w", encoding="utf-8") as f:
376
+ json.dump(operations_data, f, indent=2, ensure_ascii=False)
377
+
378
+ except Exception as e:
379
+ self._log_warning(f"保存操作记录失败: {e}")
380
+
381
+ def load_operations(self, session_id: str) -> bool:
382
+ """
383
+ 从文件加载操作记录.
384
+ """
385
+ log_file = self.rollback_dir / f"operations_{session_id}.json"
386
+
387
+ if not log_file.exists():
388
+ return False
389
+
390
+ try:
391
+ with open(log_file, "r", encoding="utf-8") as f:
392
+ operations_data = json.load(f)
393
+
394
+ self.operations = []
395
+ for op_data in operations_data:
396
+ # 将字符串转换回枚举
397
+ op_data["operation_type"] = OperationType(op_data["operation_type"])
398
+ operation = RollbackOperation(**op_data)
399
+ self.operations.append(operation)
400
+
401
+ self.session_id = session_id
402
+ self.backup_dir = self.rollback_dir / f"backup_{session_id}"
403
+ self.log_file = log_file
404
+
405
+ return True
406
+
407
+ except Exception as e:
408
+ self._log_error(f"加载操作记录失败: {e}")
409
+ return False
410
+
411
+ def list_rollback_sessions(self) -> List[str]:
412
+ """
413
+ 列出可用的回滚会话.
414
+ """
415
+ sessions = []
416
+
417
+ if not self.rollback_dir.exists():
418
+ return sessions
419
+
420
+ for file_path in self.rollback_dir.glob("operations_*.json"):
421
+ session_id = file_path.stem.replace("operations_", "")
422
+ sessions.append(session_id)
423
+
424
+ return sorted(sessions, reverse=True) # 按时间倒序
425
+
426
+ def get_session_info(self, session_id: str) -> Optional[Dict[str, Any]]:
427
+ """
428
+ 获取会话信息.
429
+ """
430
+ if not self.load_operations(session_id):
431
+ return None
432
+
433
+ if not self.operations:
434
+ return None
435
+
436
+ return {
437
+ "session_id": session_id,
438
+ "operation_count": len(self.operations),
439
+ "start_time": min(op.timestamp for op in self.operations),
440
+ "end_time": max(op.timestamp for op in self.operations),
441
+ "operations": [
442
+ {
443
+ "type": op.operation_type.value,
444
+ "target": op.target_path,
445
+ "timestamp": op.timestamp,
446
+ }
447
+ for op in self.operations
448
+ ],
449
+ }
450
+
451
+ def _log_info(self, message: str):
452
+ """
453
+ 记录信息日志.
454
+ """
455
+ if self.progress:
456
+ self.progress.info(f"[回滚] {message}")
457
+ else:
458
+ print(f"[INFO] [回滚] {message}")
459
+
460
+ def _log_warning(self, message: str):
461
+ """
462
+ 记录警告日志.
463
+ """
464
+ if self.progress:
465
+ self.progress.warning(f"[回滚] {message}")
466
+ else:
467
+ print(f"[WARNING] [回滚] {message}")
468
+
469
+ def _log_error(self, message: str):
470
+ """
471
+ 记录错误日志.
472
+ """
473
+ if self.progress:
474
+ self.progress.on_error(Exception(message), "回滚系统")
475
+ else:
476
+ print(f"[ERROR] [回滚] {message}")
477
+
478
+ def _log_debug(self, message: str):
479
+ """
480
+ 记录调试日志.
481
+ """
482
+ if self.progress and hasattr(self.progress, "debug"):
483
+ self.progress.debug(f"[回滚] {message}")
484
+ # 在非详细模式下不输出调试信息