feat: 修复混淆路径过滤与错误分类误报,并加速打包流程
- 同步 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)
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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 = []
|
||||
|
||||
Reference in New Issue
Block a user