From dee9e3a4f22d858c852d30d563f1bc012be73680 Mon Sep 17 00:00:00 2001 From: shenlei Date: Tue, 24 Nov 2026 14:26:44 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BF=AE=E5=A4=8D=E6=B7=B7=E6=B7=86?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E8=BF=87=E6=BB=A4=E4=B8=8E=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=88=86=E7=B1=BB=E8=AF=AF=E6=8A=A5=EF=BC=8C=E5=B9=B6=E5=8A=A0?= =?UTF-8?q?=E9=80=9F=E6=89=93=E5=8C=85=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 同步 discovery.py 修复:相对 scan_dir 路径过滤,防止 ./build 目录下 Pods/ 第三方库保护失效 - 同步 obfuscate_symbols.py 多进程并行混淆写盘,build_service 启用 PYTHONUNBUFFERED=1 与 python3 -u 实时输出进度 - build_service 移除全新 derived_data 下多余的 xcodebuild clean,macOS APFS 优先使用 cp -c -R 零拷贝克隆源码 - Ad_Hoc 包按「分支 + 版本号」稳定复用 L1/LLVM seed 命中 obj_cache,App_Store 保持每次唯一 - 收紧 _classify_build_error 中 provisioning 关键词并补充协议遵循失败匹配,避免编译错误被误报为描述文件问题 - 更新与补充单元测试(226 passed) --- .../obfuscation/obfuscate_symbols.py | 78 ++++++++++- .../obfuscation_runtime/discovery.py | 42 +++++- backend/services/build_service.py | 122 ++++++++++++------ tests/test_build_service.py | 90 ++++++++++++- tests/test_projects.py | 3 +- 5 files changed, 282 insertions(+), 53 deletions(-) diff --git a/backend/automation/obfuscation/obfuscate_symbols.py b/backend/automation/obfuscation/obfuscate_symbols.py index 1b2f431..6d87e01 100644 --- a/backend/automation/obfuscation/obfuscate_symbols.py +++ b/backend/automation/obfuscation/obfuscate_symbols.py @@ -4630,6 +4630,43 @@ _GLOBAL_WORKER_AHO = None _GLOBAL_WORKER_SELECTOR_MAPPING = None _GLOBAL_WORKER_SWIFT_SIGNATURE_MAPPING = None _GLOBAL_WORKER_DIRECT_METHOD_MAPPING = None +_GLOBAL_WORKER_VERBOSE = False + +def _set_fork_worker_globals( + mapping, + mapping_re, + mapping_aho, + objc_selector_mapping, + swift_signature_mapping, + direct_method_mapping, + verbose: bool, +): + global _GLOBAL_WORKER_MAPPING, _GLOBAL_WORKER_MAPPING_RE, _GLOBAL_WORKER_AHO + global _GLOBAL_WORKER_SELECTOR_MAPPING, _GLOBAL_WORKER_SWIFT_SIGNATURE_MAPPING + global _GLOBAL_WORKER_DIRECT_METHOD_MAPPING, _GLOBAL_WORKER_VERBOSE + _GLOBAL_WORKER_MAPPING = mapping + _GLOBAL_WORKER_MAPPING_RE = mapping_re + _GLOBAL_WORKER_AHO = mapping_aho + _GLOBAL_WORKER_SELECTOR_MAPPING = objc_selector_mapping + _GLOBAL_WORKER_SWIFT_SIGNATURE_MAPPING = swift_signature_mapping + _GLOBAL_WORKER_DIRECT_METHOD_MAPPING = direct_method_mapping + _GLOBAL_WORKER_VERBOSE = bool(verbose) + +def _fork_archive_plan_and_write_worker(path: str): + """archive_mode 下由 fork 子进程直接完成规划与原子写盘,绕过 GIL 并将写盘分散到多进程。""" + _, changed, stats, new_text, _ = plan_file_change( + path, + _GLOBAL_WORKER_MAPPING, + _GLOBAL_WORKER_MAPPING_RE, + objc_selector_mapping=_GLOBAL_WORKER_SELECTOR_MAPPING, + swift_signature_mapping=_GLOBAL_WORKER_SWIFT_SIGNATURE_MAPPING, + mapping_aho=_GLOBAL_WORKER_AHO, + method_direct_mapping=_GLOBAL_WORKER_DIRECT_METHOD_MAPPING, + ) + if changed: + atomic_write_text(path, new_text, encoding="utf-8") + return path, True, (stats if _GLOBAL_WORKER_VERBOSE else None) + return path, False, None def _pool_init(mapping_json_str: str, selector_mapping_json_str: str, swift_signature_mapping_json_str: str, direct_method_mapping_json_str: str): global _GLOBAL_WORKER_MAPPING, _GLOBAL_WORKER_MAPPING_RE, _GLOBAL_WORKER_AHO, _GLOBAL_WORKER_SELECTOR_MAPPING, _GLOBAL_WORKER_SWIFT_SIGNATURE_MAPPING, _GLOBAL_WORKER_DIRECT_METHOD_MAPPING @@ -5496,7 +5533,36 @@ def main(): print(f"🔁 总目标文件 {len(all_targets)},需处理 {len(files_to_process)}(基于缓存)") - if args.workers > 1 and len(files_to_process) >= 20: + already_written_in_workers = False + if args.archive_mode and not args.generate_patch_dir and args.workers > 1 and len(files_to_process) >= 20: + _set_fork_worker_globals( + mapping, + mapping_re, + mapping_aho, + objc_selector_mapping, + swift_signature_mapping, + method_direct_mapping, + args.verbose_changes, + ) + try: + ctx = multiprocessing.get_context("fork") + with ctx.Pool(processes=args.workers) as pool: + for idx, (path, changed, stats) in enumerate( + pool.imap_unordered(_fork_archive_plan_and_write_worker, files_to_process, chunksize=8), + start=1, + ): + if changed: + planned_changes[path] = {"stats": stats or {}} + total_changed += 1 + if idx % 50 == 0: + print(f" ... 进度 {idx}/{len(files_to_process)}", flush=True) + already_written_in_workers = True + except (ValueError, OSError): + # 平台不支持 fork 时回退下方线程池分支 + planned_changes.clear() + total_changed = 0 + + if not already_written_in_workers and args.workers > 1 and len(files_to_process) >= 20: # Avoid returning full file contents over multiprocessing pipes in archive mode. # Use threads and flush per-file patches to disk when --generate-patch-dir is used # to reduce memory pressure and allow inspecting progress live. @@ -5549,7 +5615,7 @@ def main(): planned_changes[path]['original_text'] = original_text total_changed += 1 if idx % 50 == 0: - print(f" ... 进度 {idx}/{len(files_to_process)}") + print(f" ... 进度 {idx}/{len(files_to_process)}", flush=True) if write_patches_live: # finalize manifest try: @@ -5561,7 +5627,7 @@ def main(): _log_stage_duration("替换规划", planning_stage_started_at) _log_stage_duration("本次执行总耗时", total_started_at) return - else: + elif not already_written_in_workers: for idx, path in enumerate(files_to_process, start=1): path, changed, stats, new_text, original_text = plan_file_change(path, mapping, mapping_re, objc_selector_mapping, swift_signature_mapping, mapping_aho, method_direct_mapping) if changed: @@ -5573,7 +5639,7 @@ def main(): planned_changes[path]['original_text'] = original_text total_changed += 1 if idx % 50 == 0: - print(f" ... 进度 {idx}/{len(files_to_process)}") + print(f" ... 进度 {idx}/{len(files_to_process)}", flush=True) # update cache for processed files for p in files_to_process: @@ -5613,7 +5679,9 @@ def main(): write_stage_started_at = time.perf_counter() changed_files = sorted(planned_changes.keys()) - if args.archive_mode: + if already_written_in_workers: + print(" (已在多进程规划阶段完成原子写盘)") + elif args.archive_mode: direct_write(planned_changes) else: transactional_write(planned_changes) diff --git a/backend/automation/obfuscation/obfuscation_runtime/discovery.py b/backend/automation/obfuscation/obfuscation_runtime/discovery.py index 79b24f8..be883d8 100644 --- a/backend/automation/obfuscation/obfuscation_runtime/discovery.py +++ b/backend/automation/obfuscation/obfuscation_runtime/discovery.py @@ -15,6 +15,33 @@ def should_exclude_path(path: str, exclude_path_fragments) -> bool: return any(fragment in path for fragment in exclude_path_fragments) +def _rel_path_within_scan_dir(path: str, scan_dir: str) -> str: + """将 path 转为相对 scan_dir 的路径,避免上层工作目录名(如 build/)触发误排除。""" + try: + rel = os.path.relpath(os.path.abspath(path), os.path.abspath(scan_dir)) + except ValueError: + return path + if rel == ".": + return "" + if rel == ".." or rel.startswith(".." + os.sep): + return path + return rel + + +def _rel_path_for_filter(path: str, scan_dirs: list) -> str: + abs_path = os.path.abspath(path) + best_rel = None + best_len = -1 + for scan_dir in scan_dirs: + abs_scan = os.path.abspath(scan_dir) + prefix = abs_scan.rstrip(os.sep) + os.sep + if abs_path == abs_scan or abs_path.startswith(prefix): + if len(abs_scan) > best_len: + best_len = len(abs_scan) + best_rel = _rel_path_within_scan_dir(abs_path, abs_scan) + return best_rel if best_rel is not None else path + + def _run_command_capture_stdout(args: list) -> str: try: completed = subprocess.run( @@ -40,7 +67,8 @@ def _discover_files_via_os_walk(scan_dirs: list, allowed_exts: tuple, exclude_pa directory for directory in dirs if not any(fragment.strip("/") in directory for fragment in exclude_path_fragments) ] - if path_matches_dir_names(root, skip_dir_names): + rel_root = _rel_path_within_scan_dir(root, scan_dir) + if path_matches_dir_names(rel_root, skip_dir_names): continue for filename in filenames: ext = os.path.splitext(filename)[1] @@ -50,9 +78,10 @@ def _discover_files_via_os_walk(scan_dirs: list, allowed_exts: tuple, exclude_pa if basename_prefixes and not any(name_no_ext.startswith(prefix) for prefix in basename_prefixes): continue full_path = os.path.normpath(os.path.join(root, filename)) - if should_exclude_path(full_path, exclude_path_fragments): + rel_file = _rel_path_within_scan_dir(full_path, scan_dir) + if should_exclude_path(rel_file, exclude_path_fragments): continue - if path_matches_dir_names(full_path, skip_dir_names): + if path_matches_dir_names(rel_file, skip_dir_names): continue files.append(full_path) return sorted(set(files)) @@ -77,9 +106,12 @@ def _discover_files_via_rg(scan_dirs: list, allowed_exts: tuple, exclude_path_fr files = [] for line in output.splitlines(): path = os.path.normpath(line.strip()) - if not path or should_exclude_path(path, exclude_path_fragments): + if not path: continue - if path_matches_dir_names(path, skip_dir_names): + rel_path = _rel_path_for_filter(path, scan_dirs) + if should_exclude_path(rel_path, exclude_path_fragments): + continue + if path_matches_dir_names(rel_path, skip_dir_names): continue if basename_prefixes: name_no_ext = os.path.splitext(os.path.basename(path))[0] diff --git a/backend/services/build_service.py b/backend/services/build_service.py index 91e9072..0a171d9 100644 --- a/backend/services/build_service.py +++ b/backend/services/build_service.py @@ -173,16 +173,17 @@ _ERROR_RULES = [ "Code Sign error", "errSecInternalComponent", "CSSMERR_TP_NOT_TRUSTED", "iPhone Distribution: no identity found", "iPhone Developer: no identity found"], "certificate", "签名证书问题:证书过期、未安装或不匹配,请检查钥匙串中的证书"), - (["Provisioning profile", "No matching provisioning profiles", - "embedded.mobileprovision", "PROVISIONING_PROFILE_SPECIFIER", - "provisioning profile", "No matching", - "requires a provisioning profile"], + (["No matching provisioning profiles", "requires a provisioning profile", + "No profiles for", "provisioning profile has expired", + "doesn't include signing certificate", "doesn't match the entitlements", + "doesn't support the"], "provisioning", "描述文件问题:描述文件过期、不匹配或未安装,请检查 Apple Developer 后台"), (["Undefined symbols", "linker command failed", "ld: symbol(s) not found", "ld: framework not found for"], "compilation", "链接错误:符号未定义或框架缺失,请检查代码引用"), (["Swift Compiler Error", "Use of undeclared identifier", - "cannot find type", "cannot find symbol in scope", "no such module"], + "cannot find type", "cannot find symbol in scope", "no such module", + "does not conform to protocol"], "compilation", "Swift 编译错误:请检查代码语法和类型引用"), ([" error:", "fatal error:"], "compilation", "代码编译错误:请检查代码是否有语法或类型错误"), @@ -673,6 +674,29 @@ async def run_build_task(task_id: str): db.close() +def _dir_contains_excluded(src: Path) -> bool: + for _, dirs, files in os.walk(src): + if ".git" in dirs or ".git" in files or "DerivedData" in dirs: + return True + return False + + +def _copy_dir_fast(src: Path, dst: Path) -> None: + """macOS APFS 上优先用 cp -c -R(Copy-on-Write 零拷贝)克隆目录,含排除项或失败时回退 shutil.copytree。""" + if sys.platform == "darwin" and not _dir_contains_excluded(src): + proc = subprocess.run( + ["cp", "-c", "-R", str(src), str(dst)], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + if proc.returncode == 0: + return + if dst.exists(): + shutil.rmtree(dst, ignore_errors=True) + shutil.copytree(src, dst, symlinks=True, ignore=shutil.ignore_patterns(".git", "DerivedData")) + + async def copy_source_code(task_id: str, task, source_dir: Path, definition: dict = None) -> Path: """从分支源码目录拷贝代码到打包目录""" await log_streamer.emit_step(task_id, "拷贝代码") @@ -684,20 +708,33 @@ async def copy_source_code(task_id: str, task, source_dir: Path, definition: dic if build_dir.exists(): shutil.rmtree(build_dir) - # 未指定拷贝条目时拷贝整个仓库(不含 Git 数据和编译缓存) + # 未指定拷贝条目时拷贝整个仓库(不含 Git 数据、DerivedData 与根 build 目录) copy_items = definition.get("copy_items") or [] if not copy_items: await log_streamer.emit(task_id, "拷贝整个仓库") - root = str(source_dir) + if sys.platform == "darwin": + build_dir.mkdir(parents=True) + for entry in source_dir.iterdir(): + if entry.name in (".git", "DerivedData", "build"): + continue + dst = build_dir / entry.name + if entry.is_symlink(): + os.symlink(os.readlink(entry), dst) + elif entry.is_dir(): + _copy_dir_fast(entry, dst) + elif entry.is_file(): + shutil.copy2(entry, dst) + else: + root = str(source_dir) - def _ignore(directory, names): - ignored = {name for name in names if name in (".git", "DerivedData")} - # 仓库根目录的 build 与打包产物目录同名,不拷贝 - if directory == root and "build" in names: - ignored.add("build") - return ignored + def _ignore(directory, names): + ignored = {name for name in names if name in (".git", "DerivedData")} + # 仓库根目录的 build 与打包产物目录同名,不拷贝 + if directory == root and "build" in names: + ignored.add("build") + return ignored - shutil.copytree(source_dir, build_dir, symlinks=True, ignore=_ignore) + shutil.copytree(source_dir, build_dir, symlinks=True, ignore=_ignore) await log_streamer.emit(task_id, "代码拷贝完成") return build_dir @@ -717,7 +754,7 @@ async def copy_source_code(task_id: str, task, source_dir: Path, definition: dic dst = build_dir / item if src.is_dir(): await log_streamer.emit(task_id, f"拷贝目录: {item}") - shutil.copytree(src, dst, symlinks=True, ignore=shutil.ignore_patterns(".git", "DerivedData")) + _copy_dir_fast(src, dst) elif src.is_file(): await log_streamer.emit(task_id, f"拷贝文件: {item}") shutil.copy2(src, dst) @@ -1004,6 +1041,31 @@ def _resolve_obfuscation_dir(build_dir: Path) -> Path: return AUTOMATION_DIR / "obfuscation" +def _sanitize_seed_part(raw: str, fallback: str) -> str: + cleaned = re.sub(r"[^A-Za-z0-9]+", "_", raw).strip("_") + return cleaned or fallback + + +def _resolve_release_seed(task_id: str, config_data: dict) -> str: + """计算 L1 混淆盐值与 LLVM IR seed。 + + - 显式传入环境变量或配置 IG_RELEASE_SEED 时优先使用; + - App_Store 上架包每次使用唯一 task_id,保证每次上架符号表不同; + - Ad_Hoc 等非上架包按「分支 + 版本号」生成稳定 seed(仅含单下划线和字母数字, + 不含 `__` 以防破坏 `-DIG_OBF_CTL_...__$(IG_RELEASE_SEED)__...=1` 宏分隔), + 让同分支同版本连续测试包复用 L1 映射并命中 LLVM obj_cache。 + """ + explicit = os.environ.get("IG_RELEASE_SEED", "").strip() or str(config_data.get("IG_RELEASE_SEED") or "").strip() + if explicit: + return explicit + build_version = str(config_data.get("BUILD_VERSION") or "0") + if config_data.get("BUILD_TYPE") == "App_Store": + return f"{task_id}_{build_version}" + branch = _sanitize_seed_part(str(config_data.get("SOURCE_BRANCH") or ""), "dev") + ver = _sanitize_seed_part(build_version, "0") + return f"adhoc_{branch}_{ver}" + + async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path): """执行代码混淆""" await log_streamer.emit_step(task_id, "代码混淆") @@ -1019,7 +1081,8 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path env = os.environ.copy() env["TARGET_NAME"] = config_data.get("SCHEME", "") env["SKIP_OBF_PHASE"] = "1" - seed = os.environ.get("IG_RELEASE_SEED") or config_data.get("IG_RELEASE_SEED") or f"{task_id}_{config_data.get('BUILD_VERSION', '0')}" + env["PYTHONUNBUFFERED"] = "1" + seed = _resolve_release_seed(task_id, config_data) env["OBF_SALT"] = seed # 自检 self_check_script = obf_root / "scripts" / "obfuscation_self_check.sh" @@ -1043,10 +1106,10 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path await log_streamer.emit(task_id, "混淆自检通过") - # 执行混淆 + # 执行混淆(-u 关闭子进程 stdout 缓冲,保证网页日志实时刷出进度) obfuscate_script = obf_root / "obfuscate_symbols.py" process = await asyncio.create_subprocess_exec( - "python3", str(obfuscate_script), "--archive-mode", "--salt", seed, + "python3", "-u", str(obfuscate_script), "--archive-mode", "--salt", seed, cwd=str(build_dir), env=env, stdout=asyncio.subprocess.PIPE, @@ -1088,7 +1151,7 @@ async def _prepare_iosguard_build_env(task_id: str, config_data: dict, build_dir all_off = "1" if os.environ.get("IG_ALL_GUARD_OFF") == "1" else "0" raw_mode = (os.environ.get("IG_OBF_MODE") or config_data.get("IG_OBF_MODE") or DEFAULT_IG_OBF_MODE).strip() or "full" effective_mode = "off" if all_off == "1" else raw_mode - seed = os.environ.get("IG_RELEASE_SEED") or config_data.get("IG_RELEASE_SEED") or f"{task_id}_{config_data.get('BUILD_VERSION', '0')}" + seed = _resolve_release_seed(task_id, config_data) obj_cache_override = os.environ.get("IG_OBF_OBJ_CACHE_DIR", "").strip() sdk_cache_dir = Path(os.environ.get("IG_SDK_CACHE_DIR") or (IG_CACHE_DIR / "sdk_cache")) @@ -1397,26 +1460,7 @@ async def build_project( if scheme in ("readoor31", "readoor31OtherPay"): await _verify_dist_channel_flag(task_id, container_args, scheme, build_dir, build_env) - # 清理 - await log_streamer.emit(task_id, "清理项目...") - process = await asyncio.create_subprocess_exec( - "xcodebuild", "clean", - *container_args, - "-scheme", scheme, - "-configuration", "Release", - "-derivedDataPath", str(export_path / "derived_data"), - cwd=str(build_dir), - env=build_env, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.STDOUT, - ) - async for line in process.stdout: - decoded = line.decode("utf-8", errors="replace").strip() - if decoded: - await log_streamer.emit(task_id, decoded) - await process.wait() - - # Archive + # Archive(每次任务的 derived_data 为全新空目录,跳过多余的 xcodebuild clean) await log_streamer.emit(task_id, "开始 Archive...") archive_started_at = time.monotonic() archive_output = [] diff --git a/tests/test_build_service.py b/tests/test_build_service.py index 30999bb..78b50a7 100644 --- a/tests/test_build_service.py +++ b/tests/test_build_service.py @@ -363,7 +363,8 @@ async def test_build_project_passes_scheme_as_exec_argument(tmp_path, log_stream await build_project("t1", task, config_data, build_dir) assert mock_shell.call_count == 0 - archive_args = mock_exec.call_args_list[1].args + assert not any(c.args[0:2] == ("xcodebuild", "clean") for c in mock_exec.call_args_list) + archive_args = mock_exec.call_args_list[0].args assert archive_args[0:2] == ("xcodebuild", "archive") assert "App; touch /tmp/should-not-run" in archive_args @@ -808,7 +809,8 @@ async def test_run_obfuscation_prefers_branch_scripts_and_falls_back(tmp_path, l patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec: await run_obfuscation("t-branch", MagicMock(), {"SCHEME": "readoor31OtherPay", "BUILD_VERSION": "1.0.0.1"}, build_dir) assert mock_exec.call_args_list[0].args[1] == str(branch_check) - assert mock_exec.call_args_list[1].args[1] == str(branch_obf_py) + assert mock_exec.call_args_list[1].args[1:3] == ("-u", str(branch_obf_py)) + assert mock_exec.call_args_list[1].kwargs["env"]["PYTHONUNBUFFERED"] == "1" # 移除分支脚本后回退到服务端脚本 branch_obf_py.unlink() @@ -816,7 +818,7 @@ async def test_run_obfuscation_prefers_branch_scripts_and_falls_back(tmp_path, l patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec_fb: await run_obfuscation("t-fb", MagicMock(), {"SCHEME": "readoor31OtherPay", "BUILD_VERSION": "1.0.0.1"}, build_dir) assert mock_exec_fb.call_args_list[0].args[1] == str(fb_check) - assert mock_exec_fb.call_args_list[1].args[1] == str(fb_py) + assert mock_exec_fb.call_args_list[1].args[1:3] == ("-u", str(fb_py)) async def test_build_project_passes_dist_channel_and_blocks_on_audit_failure(tmp_path, log_streamer): @@ -1061,3 +1063,85 @@ def test_unsupported_project_never_obfuscates_even_if_policy_forces(tmp_path): run, reason = _resolve_obfuscation_decision(build_dir, {"obfuscation": False}, MagicMock(obfuscation=True)) assert run is False assert "不支持" in reason + + +# ---- 打包加速:seed 复用与 APFS CoW 回退 ---- + +def test_resolve_release_seed_reuses_for_adhoc_and_sanitizes(monkeypatch): + """Ad_Hoc 按分支+版本稳定复用 seed 且不含 `__`;App_Store 每次含 task_id;显式配置优先。""" + from backend.services.build_service import _resolve_release_seed + + monkeypatch.delenv("IG_RELEASE_SEED", raising=False) + cfg = {"BUILD_TYPE": "Ad_Hoc", "SOURCE_BRANCH": "feat/llvm-obf__m0", "BUILD_VERSION": "2.201.0.0"} + seed1 = _resolve_release_seed("task-a", cfg) + seed2 = _resolve_release_seed("task-b", cfg) + assert seed1 == seed2 == "adhoc_feat_llvm_obf_m0_2_201_0_0" + assert "__" not in seed1 + + appstore_seed = _resolve_release_seed("task-a", {**cfg, "BUILD_TYPE": "App_Store"}) + assert appstore_seed == "task-a_2.201.0.0" + + assert _resolve_release_seed("task-a", {**cfg, "IG_RELEASE_SEED": "cfg_seed"}) == "cfg_seed" + monkeypatch.setenv("IG_RELEASE_SEED", "env_seed") + assert _resolve_release_seed("task-a", {**cfg, "IG_RELEASE_SEED": "cfg_seed"}) == "env_seed" + + +async def test_run_obfuscation_seed_matches_llvm_env_and_unbuffered(tmp_path, monkeypatch): + """L1 OBF_SALT 与 LLVM IG_RELEASE_SEED 对同一 Ad_Hoc 分支/版本保持一致,且开启无缓冲输出。""" + from backend.services.build_service import run_obfuscation, _prepare_iosguard_build_env + + monkeypatch.delenv("IG_RELEASE_SEED", raising=False) + build_dir = tmp_path / "snap" + obf = build_dir / "AutoPacking" / "obfuscation" + (obf / "scripts").mkdir(parents=True) + (obf / "scripts" / "obfuscation_self_check.sh").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + (obf / "obfuscate_symbols.py").write_text("# stub\n", encoding="utf-8") + + cfg = { + "SCHEME": "readoor31OtherPay", + "BUILD_TYPE": "Ad_Hoc", + "SOURCE_BRANCH": "readoor-test", + "BUILD_VERSION": "2.201.0.0", + } + with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec: + await run_obfuscation("t-adhoc-1", MagicMock(), cfg, build_dir) + obf_call = mock_exec.call_args_list[1] + assert obf_call.args[1] == "-u" + assert obf_call.kwargs["env"]["PYTHONUNBUFFERED"] == "1" + obf_salt = obf_call.kwargs["env"]["OBF_SALT"] + assert obf_salt == "adhoc_readoor_test_2_201_0_0" + + with patch("backend.services.build_service.IG_CACHE_DIR", tmp_path / "cache"): + llvm_env = await _prepare_iosguard_build_env("t-adhoc-2", cfg, build_dir) + assert llvm_env["IG_RELEASE_SEED"] == obf_salt + + +async def test_copy_source_code_falls_back_when_cow_clone_fails(tmp_dirs): + """APFS cp -c -R 失败时自动清理半成品并回退 shutil.copytree,且仍排除 .git。""" + source_dir, build_dir_parent = tmp_dirs + (source_dir / "readoor" / ".git").mkdir() + + def failing_cp(*args, **kwargs): + return MagicMock(returncode=1) + + with patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \ + patch("backend.services.build_service.subprocess.run", side_effect=failing_cp): + result = await copy_source_code("t-fallback", MagicMock(), source_dir) + + assert (result / "readoor" / "AppDelegate.swift").exists() + assert not (result / "readoor" / ".git").exists() + + +def test_classify_build_error_prefers_swift_compile_over_normal_provisioning_mentions(): + """正常构建日志含 embedded.mobileprovision / PROVISIONING_PROFILE_SPECIFIER 时,不应盖过编译错误。""" + lines = [ + "CodeSign /tmp/build/readoor.app/embedded.mobileprovision", + "PROVISIONING_PROFILE_SPECIFIER = abc_adhoc", + "Foo.swift:10:1: error: type 'Bar' does not conform to protocol 'Baz'", + ] + category, hint = _classify_build_error(lines, "archive") + assert category == "compilation" + assert "Swift" in hint + + assert _classify_build_error(["error: No profiles for 'com.foo' were found"], "archive")[0] == "provisioning" + assert _classify_build_error(["No matching provisioning profiles found"], "archive")[0] == "provisioning" diff --git a/tests/test_projects.py b/tests/test_projects.py index ab81ff5..f415088 100644 --- a/tests/test_projects.py +++ b/tests/test_projects.py @@ -223,7 +223,8 @@ async def test_build_uses_xcodeproj_when_no_workspace(tmp_path): with pytest.raises(Exception, match="未找到 IPA 文件"): await build_project("t1", MagicMock(), {"SCHEME": "DyAuction"}, tmp_path, {"workspace": "", "project": "DyAuction.xcodeproj"}) - archive_args = mock_exec.call_args_list[1].args + archive_args = mock_exec.call_args_list[0].args + assert archive_args[0:2] == ("xcodebuild", "archive") assert ("-project", "DyAuction.xcodeproj") == archive_args[2:4]