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,3 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from pathlib import Path
5
+
6
+ from unifypy.core.plugin import BasePlugin
7
+ from unifypy.core.event_bus import EventBus
8
+ from unifypy.core.events import ON_START, PREPARE, ON_ERROR, ON_SUCCESS
9
+ from unifypy.utils.rollback import RollbackManager
10
+ from unifypy.utils.file_ops import FileOperations
11
+
12
+
13
+ class _RollbackFileOps(FileOperations):
14
+ """包装 FileOperations,使用 RollbackManager 进行安全操作跟踪。"""
15
+
16
+ def __init__(self, base_ops: FileOperations, rb: RollbackManager, excluded_roots=None, ignore_patterns=None):
17
+ super().__init__()
18
+ self._base = base_ops
19
+ self._rb = rb
20
+ self._excluded_roots = [Path(p).resolve() for p in (excluded_roots or [])]
21
+ self._ignore_patterns = ignore_patterns or ["__pycache__", ".DS_Store", ".git", ".gitignore", "*.pyc", "*.pyo", "*.log"]
22
+
23
+ def _is_excluded(self, p: Path) -> bool:
24
+ p = p.resolve()
25
+ for root in self._excluded_roots:
26
+ try:
27
+ if root in p.parents or p == root:
28
+ return True
29
+ except Exception:
30
+ continue
31
+ return False
32
+
33
+ def _is_ignored_file(self, p: Path) -> bool:
34
+ name = p.name
35
+ # 简单匹配通配符后缀
36
+ for pat in self._ignore_patterns:
37
+ if pat == name:
38
+ return True
39
+ if pat.startswith("*.") and name.endswith(pat[1:]):
40
+ return True
41
+ return False
42
+
43
+ def ensure_dir(self, dir_path: str):
44
+ p = Path(dir_path)
45
+ if self._is_excluded(p):
46
+ return self._base.ensure_dir(dir_path)
47
+ if not p.exists():
48
+ self._rb.safe_create_dir(p)
49
+ else:
50
+ self._base.ensure_dir(dir_path)
51
+
52
+ def remove_dir(self, dir_path: str):
53
+ p = Path(dir_path)
54
+ if not p.exists():
55
+ return
56
+ # 对临时/输出目录不做回滚追踪
57
+ if self._is_excluded(p):
58
+ return self._base.remove_dir(str(p))
59
+ # 递归安全删除文件,保留空目录(不强制删)
60
+ self._safe_remove_dir(p)
61
+
62
+ def _safe_remove_dir(self, p: Path):
63
+ for item in p.iterdir():
64
+ if item.is_file():
65
+ if not self._is_ignored_file(item):
66
+ self._rb.safe_delete_file(item)
67
+ elif item.is_dir():
68
+ self._safe_remove_dir(item)
69
+ # 尝试删除空目录(非必须)
70
+ try:
71
+ p.rmdir()
72
+ except Exception:
73
+ pass
74
+
75
+ def create_temp_dir(self, prefix: str = "unifypy_") -> str:
76
+ path = self._base.create_temp_dir(prefix)
77
+ try:
78
+ self._rb.track_dir_creation(Path(path))
79
+ except Exception:
80
+ pass
81
+ return path
82
+
83
+
84
+ class AutoRollbackPlugin(BasePlugin):
85
+ name = "auto_rollback"
86
+ # 在 prepare(40) 之前安装包装,且晚于 config(20)/env(30)
87
+ priority = 35
88
+
89
+ def register(self, bus: EventBus):
90
+ self._bus = bus
91
+ bus.subscribe(ON_START, self.on_start, priority=18)
92
+ bus.subscribe(PREPARE, self.on_prepare, priority=self.priority)
93
+ bus.subscribe(ON_ERROR, self.on_error, priority=4)
94
+ bus.subscribe(ON_SUCCESS, self.on_success, priority=91)
95
+
96
+ def on_start(self, ctx):
97
+ if getattr(ctx.args, "no_rollback", False):
98
+ ctx.state["rollback_enabled"] = False
99
+ return
100
+ ctx.state["rollback_enabled"] = True
101
+ ctx.state["rollback_manager"] = RollbackManager(ctx.project_dir, ctx.progress)
102
+ # 清理老旧会话,仅保留最近 3 次
103
+ try:
104
+ rb = ctx.state["rollback_manager"]
105
+ keep = getattr(ctx.args, "rollback_keep", 3) or 0
106
+ if keep > 0:
107
+ sessions = rb.list_rollback_sessions()
108
+ if len(sessions) > keep:
109
+ for sid in sessions[keep:]:
110
+ # 删除旧备份与记录
111
+ try:
112
+ # 删除备份目录
113
+ backup_dir = rb.rollback_dir / f"backup_{sid}"
114
+ if backup_dir.exists():
115
+ import shutil
116
+ shutil.rmtree(backup_dir, ignore_errors=True)
117
+ # 删除操作日志
118
+ log_file = rb.rollback_dir / f"operations_{sid}.json"
119
+ if log_file.exists():
120
+ log_file.unlink()
121
+ except Exception:
122
+ pass
123
+ except Exception:
124
+ pass
125
+
126
+ def on_prepare(self, ctx):
127
+ if not ctx.state.get("rollback_enabled"):
128
+ return
129
+ rb = ctx.state.get("rollback_manager")
130
+ if rb and ctx.file_ops:
131
+ # 用包装替换文件操作
132
+ excluded = [ctx.dist_dir, ctx.installer_dir, ctx.project_dir / ".unifypy", ctx.project_dir / ".unifypy_rollback", ctx.project_dir / "build"]
133
+ ctx.file_ops = _RollbackFileOps(ctx.file_ops, rb, excluded_roots=excluded)
134
+
135
+ def on_error(self, ctx):
136
+ rb = ctx.state.get("rollback_manager")
137
+ if not rb:
138
+ return
139
+ try:
140
+ ok = rb.rollback()
141
+ except Exception:
142
+ ok = False
143
+ # 无论回滚是否成功,都清理当前会话,避免堆积
144
+ try:
145
+ rb.cleanup()
146
+ except Exception:
147
+ pass
148
+
149
+ def on_success(self, ctx):
150
+ rb = ctx.state.get("rollback_manager")
151
+ if not rb:
152
+ return
153
+ try:
154
+ rb.cleanup()
155
+ except Exception:
156
+ pass
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from unifypy.core.plugin import BasePlugin
5
+ from unifypy.core.event_bus import EventBus
6
+ from unifypy.core.events import ON_EXIT
7
+
8
+
9
+ class CleanupPlugin(BasePlugin):
10
+ name = "cleanup"
11
+ priority = 995
12
+
13
+ def register(self, bus: EventBus):
14
+ bus.subscribe(ON_EXIT, self.on_exit, priority=self.priority)
15
+
16
+ def on_exit(self, ctx):
17
+ # 清理临时目录
18
+ try:
19
+ if getattr(ctx, "temp_dir", None) and ctx.file_ops:
20
+ ctx.file_ops.cleanup_temp_dir(str(ctx.temp_dir))
21
+ except Exception:
22
+ pass
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from pathlib import Path
5
+
6
+ from unifypy.core.plugin import BasePlugin
7
+ from unifypy.core.event_bus import EventBus
8
+ from unifypy.core.events import LOAD_CONFIG
9
+ from unifypy.core.context import BuildContext
10
+ from unifypy.core.config import ConfigManager
11
+ from unifypy.utils.file_ops import FileOperations
12
+ from unifypy.utils.cache_manager import CacheManager
13
+ from unifypy.platforms.registry import PackagerRegistry
14
+ from unifypy.core.environment import EnvironmentManager
15
+
16
+
17
+ class ConfigPlugin(BasePlugin):
18
+ name = "config"
19
+ priority = 20
20
+
21
+ def register(self, bus: EventBus):
22
+ bus.subscribe(LOAD_CONFIG, self.load_config, priority=self.priority)
23
+
24
+ def load_config(self, ctx: BuildContext):
25
+ # 准备基础组件
26
+ ctx.file_ops = ctx.file_ops or FileOperations()
27
+ ctx.packager_registry = ctx.packager_registry or PackagerRegistry()
28
+ ctx.env_manager = ctx.env_manager or EnvironmentManager(str(ctx.project_dir))
29
+
30
+ # 加载配置
31
+ try:
32
+ ctx.config = ConfigManager(config_path=ctx.args.config, args=vars(ctx.args))
33
+ except Exception as e:
34
+ ctx.errors.append(("load_config", e))
35
+ raise
36
+
37
+ # 初始化缓存管理器
38
+ ctx.cache_manager = CacheManager(str(ctx.project_dir))
39
+
40
+ # 创建常用目录
41
+ ctx.file_ops.ensure_dir(str(ctx.dist_dir))
42
+ ctx.file_ops.ensure_dir(str(ctx.installer_dir))
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from unifypy.core.plugin import BasePlugin
5
+ from unifypy.core.event_bus import EventBus
6
+ from unifypy.core.events import ON_START
7
+
8
+
9
+ class DryRunPlugin(BasePlugin):
10
+ name = "dry_run"
11
+ priority = 12 # 在 Progress(10) 之后、Rollback(15) 之前
12
+
13
+ def register(self, bus: EventBus):
14
+ bus.subscribe(ON_START, self.on_start, priority=self.priority)
15
+
16
+ def on_start(self, ctx):
17
+ # 仅设置标志,后续阶段自然跳过
18
+ if getattr(ctx.args, "dry_run", False):
19
+ setattr(ctx.args, "skip_exe", True)
20
+ setattr(ctx.args, "skip_installer", True)
21
+ if ctx.progress:
22
+ ctx.progress.info("🔎 Dry-run 模式:仅执行环境检查与准备,跳过构建与打包")
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from unifypy.core.plugin import BasePlugin
5
+ from unifypy.core.event_bus import EventBus
6
+ from unifypy.core.events import ENVIRONMENT_CHECK
7
+ from unifypy.core.validators.tool_validator import ToolValidator
8
+ from unifypy.utils.tool_manager import ToolManager
9
+ from unifypy.core.platforms import normalize_arch, is_supported_arch
10
+
11
+
12
+ class EnvironmentPlugin(BasePlugin):
13
+ name = "environment"
14
+ priority = 30
15
+
16
+ def register(self, bus: EventBus):
17
+ bus.subscribe(ENVIRONMENT_CHECK, self.environment_check, priority=self.priority)
18
+
19
+ def environment_check(self, ctx):
20
+ stage = "环境检查"
21
+ if ctx.progress:
22
+ ctx.progress.start_stage(stage, "验证项目配置和依赖")
23
+
24
+ # 检查项目目录与入口文件
25
+ if not ctx.project_dir.exists():
26
+ raise FileNotFoundError(f"项目目录不存在: {ctx.project_dir}")
27
+ if ctx.progress:
28
+ ctx.progress.update_stage(stage, 10, "检查入口文件", absolute=True)
29
+ entry_file = ctx.config.resolve_path(ctx.config.get("entry"))
30
+ if not entry_file.exists():
31
+ raise FileNotFoundError(f"入口文件不存在: {entry_file}")
32
+
33
+ # 工具检测
34
+ ctx.tool_manager = ctx.tool_manager or ToolManager()
35
+ validator = ToolValidator(tool_manager=ctx.tool_manager, progress_manager=ctx.progress)
36
+
37
+ # 架构检测(仅支持 x64/arm64)
38
+ try:
39
+ arch = normalize_arch()
40
+ if not is_supported_arch(arch):
41
+ raise ValueError(f"不支持的架构: {arch}(仅支持 x64/arm64)")
42
+ except Exception as e:
43
+ raise RuntimeError(str(e))
44
+
45
+ # PyInstaller 可用性
46
+ from unifypy.utils.command_runner import SilentRunner
47
+
48
+ ctx.runner = ctx.runner or SilentRunner(ctx.progress)
49
+ if not ctx.runner.check_tool_available("pyinstaller"):
50
+ raise RuntimeError("PyInstaller未安装,请运行: pip install pyinstaller")
51
+
52
+ # 平台特定打包器
53
+ if not getattr(ctx.args, "skip_installer", False):
54
+ validator.validate_and_raise(platform=ctx.config.current_platform, verbose=True)
55
+
56
+ # 磁盘空间提示
57
+ if ctx.file_ops and not ctx.file_ops.check_disk_space(str(ctx.project_dir), 500):
58
+ ctx.progress.warning("磁盘空间可能不足(建议至少500MB)")
59
+
60
+ if ctx.progress:
61
+ ctx.progress.complete_stage(stage)
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import importlib
5
+ from typing import List
6
+
7
+ from unifypy.core.plugin import BasePlugin
8
+ from unifypy.core.event_bus import EventBus
9
+ from unifypy.core.events import LOAD_CONFIG
10
+
11
+
12
+ class ExternalPluginsLoaderPlugin(BasePlugin):
13
+ name = "external_plugins_loader"
14
+ priority = 22 # 在 config(20) 之后、env(30) 之前
15
+
16
+ def register(self, bus: EventBus):
17
+ self._bus = bus
18
+ bus.subscribe(LOAD_CONFIG, self.load_external_plugins, priority=self.priority)
19
+
20
+ def load_external_plugins(self, ctx):
21
+ # 支持在配置中指定:
22
+ # plugins: ["package.module:ClassName", "another.module:Plugin"]
23
+ plugins: List[str] = []
24
+ try:
25
+ plugins = ctx.config.merged_config.get("plugins", []) or []
26
+ except Exception:
27
+ return
28
+
29
+ for ref in plugins:
30
+ try:
31
+ module_name, class_name = ref.split(":", 1)
32
+ mod = importlib.import_module(module_name)
33
+ cls = getattr(mod, class_name)
34
+ # 简单校验是否像插件
35
+ instance = cls(ctx)
36
+ if hasattr(instance, "register"):
37
+ instance.register(self._bus)
38
+ if ctx.progress:
39
+ ctx.progress.info(f"🔌 外部插件已加载: {ref}")
40
+ except Exception as e:
41
+ if ctx.progress:
42
+ ctx.progress.warning(f"加载外部插件失败 {ref}: {e}")
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from typing import List
5
+ from pathlib import Path
6
+
7
+ from unifypy.core.plugin import BasePlugin
8
+ from unifypy.core.event_bus import EventBus
9
+ from unifypy.core.events import GENERATE_INSTALLERS
10
+ from unifypy.utils.parallel_builder import ParallelBuilder
11
+
12
+
13
+ class PackagingPlugin(BasePlugin):
14
+ name = "packaging"
15
+ priority = 60
16
+
17
+ def register(self, bus: EventBus):
18
+ bus.subscribe(GENERATE_INSTALLERS, self.generate_installers, priority=self.priority)
19
+
20
+ def generate_installers(self, ctx):
21
+ if getattr(ctx.args, "skip_installer", False):
22
+ return
23
+
24
+ stage = "安装包生成"
25
+ if ctx.progress:
26
+ ctx.progress.start_stage(stage, "生成平台特定的安装包")
27
+
28
+ platform = ctx.config.current_platform
29
+ requested_formats = self._get_requested_formats(ctx, platform)
30
+
31
+ if not requested_formats:
32
+ if ctx.progress:
33
+ ctx.progress.warning(f"未指定 {platform} 平台的输出格式")
34
+ ctx.progress.complete_stage(stage)
35
+ return
36
+
37
+ # 源文件路径
38
+ app_name = ctx.config.get("name")
39
+ if ctx.config.get_pyinstaller_config().get("onefile"):
40
+ source_path = ctx.dist_dir / f"{app_name}{ctx.file_ops.get_executable_extension()}"
41
+ else:
42
+ source_path = ctx.dist_dir / app_name
43
+
44
+ # 并行或串行
45
+ success_count = 0
46
+ total_formats = len(requested_formats)
47
+
48
+ processed_config = ctx.config.preprocess_paths(ctx.config.merged_config)
49
+
50
+ if getattr(ctx.args, "parallel", False) and total_formats > 1:
51
+ try:
52
+ with ParallelBuilder(ctx.progress, ctx.args.max_workers) as pb:
53
+ pb.optimize_pyinstaller_build(ctx.config.get_pyinstaller_config(), str(ctx.project_dir / ctx.config.get("entry")), ctx.project_dir)
54
+ results = pb.build_multiple_formats(platform, requested_formats, ctx.packager_registry, source_path, ctx.installer_dir, processed_config)
55
+ success_count = sum(1 for s in results.values() if s)
56
+ except Exception as e:
57
+ ctx.progress.on_error(Exception(f"并行构建失败: {e}"), stage)
58
+ success_count = 0
59
+ else:
60
+ for i, fmt in enumerate(requested_formats):
61
+ format_progress = int(80 * (i + 1) / total_formats)
62
+ if self._build_single_format(ctx, platform, fmt, source_path, processed_config, format_progress):
63
+ success_count += 1
64
+
65
+ if success_count == 0:
66
+ ctx.progress.on_error(Exception("所有格式的安装包生成都失败了"), stage)
67
+ elif success_count < total_formats:
68
+ ctx.progress.warning(f"部分安装包生成失败 ({success_count}/{total_formats} 成功)")
69
+
70
+ if ctx.progress:
71
+ ctx.progress.complete_stage(stage)
72
+
73
+ def _build_single_format(self, ctx, platform: str, format_type: str, source_path: Path, processed_config: dict, progress_weight: int) -> bool:
74
+ packager_class = ctx.packager_registry.get_packager(platform, format_type)
75
+ if not packager_class:
76
+ ctx.progress.warning(f"未找到 {platform}/{format_type} 格式的打包器")
77
+ return False
78
+
79
+ packager = packager_class(ctx.progress, ctx.runner, ctx.tool_manager, processed_config)
80
+
81
+ errors = packager.validate_config(format_type)
82
+ if errors:
83
+ ctx.progress.warning(f"{format_type}格式配置验证失败:")
84
+ for err in errors:
85
+ ctx.progress.warning(f" - {err}")
86
+
87
+ app_name = ctx.config.get("name")
88
+ version = ctx.config.get("version")
89
+ output_filename = packager.get_output_filename(format_type, app_name, version)
90
+ output_path = ctx.installer_dir / output_filename
91
+
92
+ ctx.progress.update_stage("安装包生成", 0, f"正在生成 {format_type.upper()} 格式安装包...")
93
+
94
+ try:
95
+ success = packager.package(format_type, source_path, output_path)
96
+ if success:
97
+ ctx.progress.update_stage("安装包生成", progress_weight)
98
+ ctx.progress.info(f"✅ {format_type.upper()} 安装包已生成: {output_path}")
99
+ return True
100
+ else:
101
+ ctx.progress.warning(f"❌ {format_type.upper()} 安装包生成失败")
102
+ return False
103
+ except Exception as e:
104
+ ctx.progress.on_error(Exception(f"{format_type.upper()} 打包失败: {e}"), "安装包生成")
105
+ return False
106
+
107
+ def _get_requested_formats(self, ctx, platform: str) -> List[str]:
108
+ # 优先命令行指定
109
+ if ctx.args.format:
110
+ return [ctx.args.format]
111
+
112
+ platform_config = ctx.config.get("platforms", {}).get(platform, {})
113
+ formats = []
114
+ for key in platform_config.keys():
115
+ if ctx.packager_registry.is_format_supported(platform, key):
116
+ formats.append(key)
117
+
118
+ if not formats:
119
+ default_formats = {
120
+ "windows": ["exe"],
121
+ "macos": ["dmg"],
122
+ "linux": ["deb"],
123
+ }
124
+ formats = default_formats.get(platform, [])
125
+ return formats
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from pathlib import Path
5
+
6
+ from unifypy.core.plugin import BasePlugin
7
+ from unifypy.core.event_bus import EventBus
8
+ from unifypy.core.events import PREPARE
9
+ from unifypy.utils.file_ops import FileOperations
10
+
11
+
12
+ class PreparePlugin(BasePlugin):
13
+ name = "prepare"
14
+ priority = 40
15
+
16
+ def register(self, bus: EventBus):
17
+ bus.subscribe(PREPARE, self.prepare, priority=self.priority)
18
+
19
+ def prepare(self, ctx):
20
+ stage = "环境准备"
21
+ if ctx.progress:
22
+ ctx.progress.start_stage(stage, "创建构建目录和临时文件")
23
+
24
+ ctx.file_ops = ctx.file_ops or FileOperations()
25
+
26
+ # 创建临时目录
27
+ temp_dir = ctx.file_ops.create_temp_dir("unifypy_build_")
28
+ ctx.temp_dir = Path(temp_dir)
29
+ if ctx.progress:
30
+ ctx.progress.update_stage(stage, 20, f"创建临时目录: {ctx.temp_dir}", absolute=True)
31
+
32
+ # 创建输出目录
33
+ ctx.file_ops.ensure_dir(str(ctx.dist_dir))
34
+ ctx.file_ops.ensure_dir(str(ctx.installer_dir))
35
+ if ctx.progress:
36
+ ctx.progress.update_stage(stage, 40, "创建输出目录", absolute=True)
37
+
38
+ # 清理旧文件(按需)
39
+ if getattr(ctx.args, "clean", False):
40
+ if ctx.progress:
41
+ ctx.progress.update_stage(stage, 60, "清理旧的构建文件", absolute=True)
42
+ ctx.file_ops.remove_dir(str(ctx.dist_dir))
43
+ ctx.file_ops.remove_dir(str(ctx.installer_dir))
44
+ ctx.file_ops.ensure_dir(str(ctx.dist_dir))
45
+ ctx.file_ops.ensure_dir(str(ctx.installer_dir))
46
+
47
+ # 预生成多平台配置(按需)
48
+ try:
49
+ if ctx.cache_manager and ctx.cache_manager.should_pre_generate_all_configs(ctx.config.merged_config):
50
+ if ctx.progress:
51
+ ctx.progress.update_stage(stage, 45, "预生成多平台配置", absolute=True)
52
+ # 仅在 verbose 下输出详细日志
53
+ def cb(msg, level='info'):
54
+ if getattr(ctx.args, "verbose", False) and ctx.progress:
55
+ ctx.progress.info(msg)
56
+ results = ctx.cache_manager.pre_generate_all_platform_configs(
57
+ ctx.config.merged_config,
58
+ ctx.config.config_path if hasattr(ctx.config, 'config_path') else None,
59
+ progress_callback=cb,
60
+ )
61
+ # 简要摘要
62
+ success_count = len([k for k, v in results.items() if v is True])
63
+ total_count = len([k for k, v in results.items() if v != "skipped"]) or 0
64
+ if success_count > 0 and ctx.progress:
65
+ if not getattr(ctx.args, "verbose", False):
66
+ ctx.progress.info(f"✅ 已预生成 {success_count}/{total_count} 个平台配置")
67
+ else:
68
+ ctx.progress.info(f"✅ 预生成 {success_count}/{total_count} 个平台配置完成")
69
+ else:
70
+ if ctx.progress:
71
+ ctx.progress.update_stage(stage, 45, "使用缓存配置", absolute=True)
72
+ if getattr(ctx.args, "verbose", False):
73
+ ctx.progress.info("📋 使用现有缓存配置")
74
+ except Exception as e:
75
+ if ctx.progress:
76
+ ctx.progress.warning(f"配置预生成失败: {e}")
77
+
78
+ # 预处理图标(如无效则移除,避免PyInstaller报错)
79
+ icon_path = ctx.config.get("icon")
80
+ if icon_path:
81
+ icon_full = ctx.config.resolve_path(icon_path)
82
+ if not icon_full.exists():
83
+ ctx.config.merged_config.pop("icon", None)
84
+ if "pyinstaller" in ctx.config.merged_config:
85
+ ctx.config.merged_config["pyinstaller"].pop("icon", None)
86
+
87
+ if ctx.progress:
88
+ ctx.progress.update_stage(stage, 80, "准备资源文件", absolute=True)
89
+ ctx.progress.complete_stage(stage)
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from unifypy.core.plugin import BasePlugin
5
+ from unifypy.core.event_bus import EventBus
6
+ from unifypy.core.events import ON_START, ON_EXIT, ON_ERROR
7
+ from unifypy.utils.progress import ProgressManager
8
+
9
+
10
+ class ProgressPlugin(BasePlugin):
11
+ name = "progress"
12
+ priority = 10
13
+
14
+ def register(self, bus: EventBus):
15
+ bus.subscribe(ON_START, self.on_start, priority=self.priority)
16
+ bus.subscribe(ON_EXIT, self.on_exit, priority=999)
17
+ bus.subscribe(ON_ERROR, self.on_error, priority=5)
18
+
19
+ def on_start(self, ctx):
20
+ ctx.progress = ProgressManager(verbose=getattr(ctx.args, "verbose", False))
21
+ ctx.progress.start()
22
+
23
+ def on_exit(self, ctx):
24
+ if ctx.progress:
25
+ ctx.progress.stop()
26
+
27
+ def on_error(self, ctx):
28
+ # 将已收集的错误打印出来(如果有)
29
+ if not ctx.progress:
30
+ return
31
+ for event, err in ctx.errors:
32
+ ctx.progress.on_error(err, f"{event}")