1570 lines
65 KiB
Python
1570 lines
65 KiB
Python
"""打包服务核心"""
|
||
import asyncio
|
||
import json
|
||
import os
|
||
import plistlib
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import zipfile
|
||
from datetime import datetime, timedelta
|
||
from pathlib import Path
|
||
from typing import List, Optional
|
||
|
||
from ..config import (
|
||
ARTIFACTS_DIR,
|
||
BUILD_BASE_DIR,
|
||
DEFAULT_BUILD_DIR_RETENTION_HOURS,
|
||
DEFAULT_IG_OBF_MODE,
|
||
BUILD_TIMEOUT_HOURS,
|
||
IG_CACHE_DIR,
|
||
IG_TOOLCHAIN_CACHE_DIR,
|
||
SKINS_DIR,
|
||
AUTOMATION_DIR,
|
||
get_git_remote_url,
|
||
mask_git_remote_url,
|
||
)
|
||
from ..projects import LEGACY_PROJECT_ID, PATCHER_READOOR, get_definition, get_project_source
|
||
from .log_streamer import log_streamer
|
||
from .distribution import DistributionError, publish_dsym, publish_ipa
|
||
from .notification import NotificationError, merge_project_at_mobiles, send_dingtalk_notification
|
||
from .project_patcher import ProjectPatchError, apply_project_config
|
||
from .toolchain_manager import ensure_toolchain
|
||
|
||
|
||
class BuildError(Exception):
|
||
"""带分类的打包错误"""
|
||
|
||
def __init__(self, message: str, category: str = "unknown", detail: str = ""):
|
||
super().__init__(message)
|
||
self.category = category
|
||
self.detail = detail
|
||
|
||
|
||
# 共享源码目录只能同时被一个任务切换、清理和复制,每个源码目录一把锁,
|
||
# 不同项目的源码准备互不阻塞。后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。
|
||
_source_prepare_locks: dict = {}
|
||
|
||
# 打包目录名:build_<项目 ID>_<任务 ID>
|
||
_BUILD_DIR_PATTERN = re.compile(r"^build_[a-z][a-z0-9_-]{0,31}_.+")
|
||
|
||
|
||
def _source_prepare_lock(source_dir: Path) -> asyncio.Lock:
|
||
return _source_prepare_locks.setdefault(str(source_dir.resolve()), asyncio.Lock())
|
||
|
||
|
||
def _task_project_id(task) -> str:
|
||
project_id = getattr(task, "project_id", None)
|
||
return project_id if isinstance(project_id, str) and project_id else LEGACY_PROJECT_ID
|
||
|
||
|
||
def load_task_project(task) -> dict:
|
||
"""读取任务所属项目的配置视图(见 routers.config.load_config)。"""
|
||
from fastapi import HTTPException
|
||
from ..routers.config import load_config
|
||
try:
|
||
return load_config(_task_project_id(task))
|
||
except HTTPException as exc:
|
||
raise BuildError(str(exc.detail), category="config") from exc
|
||
|
||
|
||
def get_task_definition(task) -> dict:
|
||
project_id = _task_project_id(task)
|
||
return get_definition(project_id, load_task_project(task))
|
||
|
||
|
||
def _patch_afnetworking_private_headers(build_dir: Path) -> int:
|
||
"""移除旧版 AFNetworking 对 Xcode 新 SDK 私有头的直接引用。"""
|
||
afnetworking_dir = build_dir / "Pods" / "AFNetworking"
|
||
if not afnetworking_dir.is_dir():
|
||
return 0
|
||
|
||
private_import = "#import <netinet6/in6.h>"
|
||
patched_files = 0
|
||
for source_path in afnetworking_dir.rglob("*"):
|
||
if source_path.suffix not in {".h", ".m", ".mm"} or not source_path.is_file():
|
||
continue
|
||
|
||
content = source_path.read_text(encoding="utf-8")
|
||
if private_import not in content:
|
||
continue
|
||
|
||
updated_lines = [
|
||
line for line in content.splitlines(keepends=True)
|
||
if line.strip() != private_import
|
||
]
|
||
original_mode = source_path.stat().st_mode
|
||
try:
|
||
source_path.chmod(original_mode | 0o200)
|
||
source_path.write_text("".join(updated_lines), encoding="utf-8")
|
||
finally:
|
||
source_path.chmod(original_mode)
|
||
patched_files += 1
|
||
|
||
return patched_files
|
||
|
||
|
||
def _decode_provisioning_profile(profile_path: Path) -> dict:
|
||
"""沿用 AutoPacking 脚本的 security cms 方式读取描述文件。"""
|
||
try:
|
||
plist_xml = subprocess.check_output(
|
||
["security", "cms", "-D", "-i", str(profile_path)],
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
# 与原脚本一致,跳过 security 可能输出在 XML 前面的 Apple 标记行。
|
||
lines = plist_xml.splitlines(keepends=True)
|
||
xml_start = next(
|
||
(
|
||
index
|
||
for index, line in enumerate(lines)
|
||
if line.lstrip().startswith((b"<?xml", b"<!DOCTYPE"))
|
||
),
|
||
0,
|
||
)
|
||
return plistlib.loads(b"".join(lines[xml_start:]))
|
||
except (OSError, subprocess.CalledProcessError, plistlib.InvalidFileException) as exc:
|
||
raise BuildError(f"读取描述文件失败: {profile_path.name}", category="provisioning") from exc
|
||
|
||
|
||
def _resolve_provisioning_profile(profile_reference: str) -> tuple[str, str]:
|
||
"""按 AutoPacking 的规则从描述文件名称提取 Name 和 TeamIdentifier。"""
|
||
configured_path = Path(profile_reference).expanduser()
|
||
if configured_path.is_file():
|
||
profile = _decode_provisioning_profile(configured_path)
|
||
else:
|
||
profiles_dir = (
|
||
Path.home()
|
||
/ "Library"
|
||
/ "Developer"
|
||
/ "Xcode"
|
||
/ "UserData"
|
||
/ "Provisioning Profiles"
|
||
)
|
||
if not profiles_dir.is_dir():
|
||
raise BuildError(f"Provisioning Profiles 目录不存在: {profiles_dir}", category="provisioning")
|
||
|
||
profile = None
|
||
for candidate in profiles_dir.iterdir():
|
||
if candidate.suffix != ".mobileprovision":
|
||
continue
|
||
try:
|
||
candidate_profile = _decode_provisioning_profile(candidate)
|
||
except BuildError:
|
||
continue
|
||
if candidate_profile.get("Name") == profile_reference:
|
||
profile = candidate_profile
|
||
break
|
||
if profile is None:
|
||
raise BuildError(f"未找到名称为 [{profile_reference}] 的描述文件", category="provisioning")
|
||
|
||
profile_name = profile.get("Name", "")
|
||
team_ids = profile.get("TeamIdentifier", [])
|
||
team_id = team_ids[0] if isinstance(team_ids, list) and team_ids else team_ids
|
||
if not profile_name or not team_id:
|
||
raise BuildError(f"描述文件缺少 Name 或 TeamIdentifier: {profile_reference}", category="provisioning")
|
||
return profile_name, team_id
|
||
|
||
|
||
# 错误分类规则:(关键词列表, category, 友好提示)
|
||
_ERROR_RULES = [
|
||
(["No signing certificate", "Signing certificate \"", "Code Signing Error",
|
||
"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"],
|
||
"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"],
|
||
"compilation", "Swift 编译错误:请检查代码语法和类型引用"),
|
||
([" error:", "fatal error:"],
|
||
"compilation", "代码编译错误:请检查代码是否有语法或类型错误"),
|
||
(["CocoaPods", "pod install", "ld: library not found for",
|
||
"library not found for", "Sandbox is not in sync with Podfile.lock"],
|
||
"dependency", "依赖问题:Pod 依赖缺失或版本不兼容,请检查 Podfile"),
|
||
(["xcodebuild: error", "Unable to access scheme", "does not contain a scheme"],
|
||
"build", "构建配置错误:Scheme 或 Workspace 配置有误"),
|
||
]
|
||
|
||
|
||
def _git_env() -> dict:
|
||
"""为无人值守的构建任务禁用交互提示与凭据缓存写入。"""
|
||
env = os.environ.copy()
|
||
env["GIT_TERMINAL_PROMPT"] = "0"
|
||
return env
|
||
|
||
|
||
_GIT_NO_CREDENTIAL_HELPER = ("git", "-c", "credential.helper=")
|
||
|
||
|
||
def _classify_build_error(output_lines: list, step: str) -> tuple:
|
||
"""解析构建输出,返回 (category, friendly_message)
|
||
|
||
Args:
|
||
output_lines: 构建过程的输出行列表
|
||
step: 失败步骤 (archive/export)
|
||
|
||
Returns:
|
||
(category, friendly_message) 元组
|
||
"""
|
||
output_text = "\n".join(output_lines)
|
||
|
||
missing_script = re.search(r"""can't open file ['"]([^'"]+)['"]: \[Errno 2\] No such file or directory""", output_text)
|
||
if missing_script:
|
||
return "config", f"构建脚本缺失:{missing_script.group(1)},请检查源码拷贝配置"
|
||
|
||
for keywords, category, hint in _ERROR_RULES:
|
||
for kw in keywords:
|
||
if kw.lower() in output_text.lower():
|
||
return category, hint
|
||
|
||
# 未匹配到特定分类
|
||
if step == "archive":
|
||
return "build", "Archive 失败:请查看详细日志排查原因"
|
||
elif step == "export":
|
||
return "build", "导出 IPA 失败:请查看详细日志排查原因"
|
||
return "unknown", "打包失败:请查看详细日志排查原因"
|
||
|
||
|
||
def _cleanup_build_dir(build_dir: Path):
|
||
"""删除整个打包目录"""
|
||
try:
|
||
if build_dir.exists():
|
||
shutil.rmtree(build_dir)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _cleanup_old_builds(db):
|
||
"""清理超过保留时间的打包目录"""
|
||
from ..models import BuildConfig
|
||
config = db.query(BuildConfig).filter(BuildConfig.key == "build_dir_retention_hours").first()
|
||
hours = int(config.value) if config else DEFAULT_BUILD_DIR_RETENTION_HOURS
|
||
cutoff = datetime.utcnow().timestamp() - hours * 3600
|
||
|
||
base = BUILD_BASE_DIR
|
||
if not base.exists():
|
||
_cleanup_superseded_tasks(db)
|
||
return
|
||
for d in base.iterdir():
|
||
if d.is_dir() and _BUILD_DIR_PATTERN.match(d.name):
|
||
try:
|
||
if d.stat().st_mtime < cutoff:
|
||
shutil.rmtree(d)
|
||
except Exception:
|
||
pass
|
||
_cleanup_superseded_tasks(db)
|
||
|
||
|
||
def _cleanup_superseded_tasks(db):
|
||
"""7 天后删除已被新 OSS 包覆盖的历史记录及仅本地保留的文件。"""
|
||
from ..models import Task
|
||
cutoff = datetime.utcnow() - timedelta(days=7)
|
||
tasks = db.query(Task).filter(
|
||
Task.superseded_at.isnot(None), Task.superseded_at < cutoff,
|
||
).all()
|
||
for task in tasks:
|
||
for path_value in (task.build_dir, task.dsym_path, task.obfuscation_maps_path):
|
||
if not path_value:
|
||
continue
|
||
try:
|
||
path = Path(path_value)
|
||
if path.is_dir():
|
||
shutil.rmtree(path, ignore_errors=True)
|
||
elif path.exists():
|
||
path.unlink()
|
||
except OSError:
|
||
pass
|
||
log_path = Path(__file__).parent.parent / "logs" / f"{task.id}.log"
|
||
try:
|
||
log_path.unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
task_artifacts_dir = ARTIFACTS_DIR / task.id
|
||
if task_artifacts_dir.exists():
|
||
shutil.rmtree(task_artifacts_dir, ignore_errors=True)
|
||
db.delete(task)
|
||
if tasks:
|
||
db.commit()
|
||
|
||
|
||
def _mark_superseded_tasks(db, latest_task):
|
||
"""标记同一 OSS 对象的旧成功记录;OSS 文件由最新任务覆盖。"""
|
||
if not latest_task.oss_url:
|
||
return
|
||
from ..models import Task
|
||
db.query(Task).filter(
|
||
Task.id != latest_task.id,
|
||
Task.status == "completed",
|
||
Task.oss_url == latest_task.oss_url,
|
||
Task.superseded_at.is_(None),
|
||
).update({Task.superseded_at: datetime.utcnow()}, synchronize_session=False)
|
||
db.commit()
|
||
|
||
|
||
def _cleanup_old_logs():
|
||
"""清理超过 7 天的打包日志"""
|
||
logs_dir = Path(__file__).parent.parent / "logs"
|
||
if not logs_dir.exists():
|
||
return
|
||
cutoff = datetime.utcnow().timestamp() - 7 * 86400
|
||
for f in logs_dir.iterdir():
|
||
if f.is_file() and f.suffix == ".log":
|
||
try:
|
||
if f.stat().st_mtime < cutoff:
|
||
f.unlink()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _db_update(db, task, **fields):
|
||
"""同步更新 task 字段并 commit(在线程中调用)"""
|
||
for k, v in fields.items():
|
||
setattr(task, k, v)
|
||
db.commit()
|
||
|
||
|
||
async def update_source(task_id: str, source_dir: Path, branch: str, ref_type: str = "branch",
|
||
remote_url: str = None):
|
||
"""将共享源码工作目录强制同步到指定远程分支或 Tag(ref_type="tag" 时 branch 为 Tag 名)。
|
||
|
||
remote_url 为带凭证的项目仓库地址,未传时使用 .env 中的 GIT_REMOTE_URL。
|
||
"""
|
||
if remote_url is None:
|
||
remote_url = get_git_remote_url(with_credentials=True)
|
||
remote_url_masked = mask_git_remote_url(remote_url)
|
||
git_env = _git_env()
|
||
|
||
cloned = not source_dir.exists()
|
||
if cloned:
|
||
if not remote_url:
|
||
raise Exception(f"源码目录不存在且未配置 Git 仓库地址: {source_dir}")
|
||
source_dir.parent.mkdir(parents=True, exist_ok=True)
|
||
await log_streamer.emit(task_id, f"初始化共享源码目录: {remote_url_masked}")
|
||
process = await asyncio.create_subprocess_exec(
|
||
*_GIT_NO_CREDENTIAL_HELPER, "clone", remote_url, str(source_dir),
|
||
env=git_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()
|
||
if process.returncode != 0:
|
||
raise Exception("git clone 失败")
|
||
|
||
# git clone 成功即保证目录有效;已有目录则额外拦截误配置路径。
|
||
if not cloned and not (source_dir / ".git").exists():
|
||
raise Exception(f"共享源码目录不是 Git 仓库: {source_dir}")
|
||
|
||
is_tag = ref_type == "tag"
|
||
await log_streamer.emit(task_id, f"同步共享源码到{'Tag' if is_tag else '分支'}: {branch}")
|
||
|
||
if remote_url:
|
||
process = await asyncio.create_subprocess_exec(
|
||
*_GIT_NO_CREDENTIAL_HELPER, "remote", "set-url", "origin", remote_url,
|
||
env=git_env,
|
||
cwd=str(source_dir), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
|
||
)
|
||
await process.wait()
|
||
if process.returncode != 0:
|
||
raise Exception("git remote set-url 失败")
|
||
|
||
if is_tag:
|
||
# Tag 检出为游离 HEAD;--force 让远端被移动过的 Tag 覆盖本地旧 Tag
|
||
tag_ref = f"refs/tags/{branch}"
|
||
commands = [
|
||
(("git", "fetch", "origin", "--tags", "--force"), "git fetch 失败"),
|
||
(("git", "checkout", "--detach", tag_ref), f"git checkout Tag {branch} 失败"),
|
||
(("git", "reset", "--hard", tag_ref), f"git reset Tag {branch} 失败"),
|
||
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||
]
|
||
else:
|
||
commands = [
|
||
(("git", "fetch", "origin"), "git fetch 失败"),
|
||
(("git", "checkout", "-B", branch, f"origin/{branch}"), f"git checkout {branch} 失败"),
|
||
(("git", "reset", "--hard", f"origin/{branch}"), f"git reset {branch} 失败"),
|
||
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||
]
|
||
for command, error_message in commands:
|
||
process = await asyncio.create_subprocess_exec(
|
||
*_GIT_NO_CREDENTIAL_HELPER, *command[1:], env=git_env,
|
||
cwd=str(source_dir), 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()
|
||
if process.returncode != 0:
|
||
raise Exception(error_message)
|
||
|
||
await log_streamer.emit(task_id, f"源码已就绪: {source_dir}")
|
||
|
||
|
||
async def get_source_commit(source_dir: Path) -> str:
|
||
"""读取当前共享源码快照的 commit SHA。"""
|
||
process = await asyncio.create_subprocess_exec(
|
||
"git", "rev-parse", "HEAD", cwd=str(source_dir),
|
||
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
|
||
)
|
||
output = await process.stdout.read()
|
||
await process.wait()
|
||
if process.returncode != 0:
|
||
raise Exception("读取源码 commit 失败")
|
||
return output.decode("utf-8", errors="replace").strip()
|
||
|
||
|
||
async def prepare_source_snapshot(task_id: str, task) -> tuple[Path, str]:
|
||
"""准备任务独立源码快照;远程仓库模式下同一源码目录的准备过程串行。"""
|
||
project_id = _task_project_id(task)
|
||
project = load_task_project(task)
|
||
definition = get_definition(project_id, project)
|
||
source = get_project_source(project_id, project)
|
||
await log_streamer.emit(task_id, f"项目: {definition['name']}({project_id})")
|
||
|
||
if not source.remote_url:
|
||
if source.manual_base is None:
|
||
raise BuildError(f"项目 {definition['name']} 未配置 Git 仓库地址", category="config")
|
||
source_dir = source.manual_base / task.branch
|
||
if not source_dir.exists():
|
||
raise Exception(
|
||
f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支(或 Tag)代码,或配置 GIT_REMOTE_URL"
|
||
)
|
||
await log_streamer.emit(task_id, f"使用分支源码: {source_dir}")
|
||
return await copy_source_code(task_id, task, source_dir, definition), ""
|
||
|
||
source_dir = source.shared_dir
|
||
await log_streamer.emit(task_id, "等待共享源码准备队列...")
|
||
async with _source_prepare_lock(source_dir):
|
||
await log_streamer.emit(task_id, "开始准备共享源码快照")
|
||
ref_type = "tag" if task.ref_type == "tag" else "branch"
|
||
await update_source(task_id, source_dir, task.branch, ref_type,
|
||
remote_url=source.remote_url_with_credentials)
|
||
commit = await get_source_commit(source_dir)
|
||
await log_streamer.emit(task_id, f"源码版本: {task.branch} @ {commit}")
|
||
build_dir = await copy_source_code(task_id, task, source_dir, definition)
|
||
await log_streamer.emit(task_id, "共享源码快照已就绪,开始并行打包")
|
||
return build_dir, commit
|
||
|
||
|
||
async def run_build_task(task_id: str):
|
||
"""执行打包任务"""
|
||
from ..database import SessionLocal
|
||
from ..models import Task
|
||
|
||
db = SessionLocal()
|
||
try:
|
||
task = await asyncio.to_thread(
|
||
lambda: db.query(Task).filter(Task.id == task_id).first()
|
||
)
|
||
if not task:
|
||
return
|
||
|
||
# 创建日志队列(必须在 emit 之前)
|
||
log_streamer.create_queue(task_id)
|
||
|
||
# 更新状态
|
||
await asyncio.to_thread(_db_update, db, task,
|
||
status="running", started_at=datetime.utcnow())
|
||
|
||
await log_streamer.emit_step(task_id, "开始打包")
|
||
|
||
# 清理过期的打包目录和日志
|
||
await asyncio.to_thread(_cleanup_old_builds, db)
|
||
await asyncio.to_thread(_cleanup_old_logs)
|
||
|
||
build_dir = None
|
||
try:
|
||
timeout_seconds = BUILD_TIMEOUT_HOURS * 3600
|
||
|
||
async def _prepare_until_obfuscation():
|
||
nonlocal build_dir
|
||
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
|
||
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare")
|
||
definition = await asyncio.to_thread(get_task_definition, task)
|
||
build_dir, source_commit = await prepare_source_snapshot(task_id, task)
|
||
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
|
||
|
||
# 1.5 按分支自身声明决定是否混淆:分支 build_policy.json 声明强制时必混淆,
|
||
# 否则沿用任务勾选(兼容旧分支/旧 Tag)。先于生成配置写回,保证 ENABLE_OBFUSCATION 与实际一致。
|
||
run_obf, obf_reason = _resolve_obfuscation_decision(build_dir, definition, task)
|
||
await log_streamer.emit(task_id, f"代码混淆: {'启用' if run_obf else '不启用'}({obf_reason})")
|
||
if bool(task.obfuscation) != run_obf:
|
||
await asyncio.to_thread(_db_update, db, task, obfuscation=run_obf)
|
||
|
||
# 2. 生成配置
|
||
await asyncio.to_thread(_db_update, db, task, current_step="config")
|
||
config_data = await generate_config(task_id, task, build_dir)
|
||
config_data["SOURCE_BRANCH"] = task.branch
|
||
config_data["SOURCE_REF_TYPE"] = "tag" if task.ref_type == "tag" else "branch"
|
||
config_data["SOURCE_COMMIT"] = source_commit
|
||
await asyncio.to_thread(_db_update, db, task,
|
||
config_json=json.dumps(config_data, ensure_ascii=False))
|
||
|
||
# 3. 替换项目配置
|
||
await asyncio.to_thread(_db_update, db, task, current_step="patch")
|
||
await patch_project(task_id, task, config_data, build_dir, definition)
|
||
|
||
# 3.5 安装依赖
|
||
await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
|
||
await run_pod_install(task_id, build_dir, definition["xcode"])
|
||
|
||
# 4. 代码混淆(是否执行已在 1.5 按分支策略/任务勾选确定)
|
||
if run_obf:
|
||
await asyncio.to_thread(_db_update, db, task, current_step="obfuscation")
|
||
await run_obfuscation(task_id, task, config_data, build_dir)
|
||
|
||
return definition, config_data
|
||
|
||
definition, config_data = await asyncio.wait_for(_prepare_until_obfuscation(), timeout=timeout_seconds)
|
||
|
||
# 4.5 校验并按需自愈 LLVM opt 工具链(独立于构建超时预算)
|
||
await asyncio.to_thread(_db_update, db, task, current_step="toolchain_prepare")
|
||
prepared_env = await _prepare_iosguard_build_env(task_id, config_data, build_dir)
|
||
|
||
async def _build_and_upload():
|
||
# 5. 构建项目
|
||
await asyncio.to_thread(_db_update, db, task, current_step="build")
|
||
ipa_path = await build_project(
|
||
task_id, task, config_data, build_dir, definition["xcode"], prepared_env=prepared_env
|
||
)
|
||
|
||
# 查找并持久化 dSYM、混淆映射、事件码与混淆审计到 DATA_DIR/artifacts/<task_id>,防止 _cleanup_build_dir 删除
|
||
dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", ""))
|
||
persisted_dsym_path, persisted_maps_path = await asyncio.to_thread(
|
||
persist_task_artifacts,
|
||
task_id,
|
||
build_dir,
|
||
config_data.get("SCHEME", ""),
|
||
dsym_path,
|
||
)
|
||
if persisted_dsym_path is not None:
|
||
dsym_path = persisted_dsym_path
|
||
|
||
update_fields = {"ipa_path": str(ipa_path)}
|
||
if dsym_path:
|
||
update_fields["dsym_path"] = str(dsym_path)
|
||
if persisted_maps_path:
|
||
update_fields["obfuscation_maps_path"] = str(persisted_maps_path)
|
||
await asyncio.to_thread(_db_update, db, task, **update_fields)
|
||
|
||
# 6. 上传产物:Ad Hoc 发布安装页,App Store 上传 IPA 供下载提交。
|
||
await asyncio.to_thread(_db_update, db, task, current_step="upload")
|
||
oss_url, qr_code_path = await upload_ipa(
|
||
task_id, task, config_data, ipa_path, build_dir
|
||
)
|
||
upload_fields = {}
|
||
if oss_url:
|
||
upload_fields["oss_url"] = oss_url
|
||
if qr_code_path:
|
||
upload_fields["qr_code_path"] = qr_code_path
|
||
|
||
# dSYM 用于后续崩溃符号化,按上传配置一并保存到远端;失败不影响本次打包结果。
|
||
if dsym_path:
|
||
dsym_url = await upload_dsym(task_id, task, config_data, dsym_path, build_dir)
|
||
if dsym_url:
|
||
upload_fields["dsym_url"] = dsym_url
|
||
|
||
if upload_fields:
|
||
await asyncio.to_thread(_db_update, db, task, **upload_fields)
|
||
|
||
# 完成
|
||
await asyncio.to_thread(_db_update, db, task,
|
||
status="completed", completed_at=datetime.utcnow(),
|
||
current_step=None)
|
||
await asyncio.to_thread(_mark_superseded_tasks, db, task)
|
||
|
||
await log_streamer.emit_step(task_id, "打包完成")
|
||
await log_streamer.emit(task_id, f"IPA: {ipa_path}")
|
||
if task.oss_url:
|
||
await log_streamer.emit(task_id, f"下载链接: {task.oss_url}")
|
||
|
||
# Ad Hoc 发安装页二维码通知,App Store 发 IPA 下载地址通知;
|
||
# 两者标题与 @ 名单不同,均由 send_dingtalk_notification 按 BUILD_TYPE 区分;
|
||
# 项目配置了 @ 名单时覆盖全局名单。
|
||
# 通知不影响已完成的打包结果,发送失败仅写入日志以便排查。
|
||
dingtalk_config = merge_project_at_mobiles(
|
||
config_data.get("_upload_config", {}).get("dingtalk", {}),
|
||
definition.get("dingtalk_at"),
|
||
)
|
||
try:
|
||
notified = await asyncio.to_thread(
|
||
send_dingtalk_notification,
|
||
dingtalk_config,
|
||
config_data,
|
||
task.oss_url or oss_url,
|
||
task.qr_code_path or qr_code_path,
|
||
)
|
||
if notified:
|
||
await log_streamer.emit(task_id, "钉钉通知发送成功")
|
||
except NotificationError as exc:
|
||
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
||
|
||
# 带超时执行编译构建与上传
|
||
await asyncio.wait_for(_build_and_upload(), timeout=timeout_seconds)
|
||
|
||
# 保存打包日志
|
||
if build_dir and build_dir.exists():
|
||
await asyncio.to_thread(log_streamer.save_log, task_id, build_dir)
|
||
|
||
# 清理打包目录(保留产物文件,删除源码拷贝)
|
||
await log_streamer.emit(task_id, "清理临时文件...")
|
||
await asyncio.to_thread(_cleanup_build_dir, build_dir)
|
||
|
||
except asyncio.TimeoutError:
|
||
error_msg = f"打包超时(已运行 {BUILD_TIMEOUT_HOURS} 小时)"
|
||
await asyncio.to_thread(_db_update, db, task,
|
||
status="failed", completed_at=datetime.utcnow(),
|
||
error_message=error_msg, error_category="timeout")
|
||
await log_streamer.emit_error(task_id, error_msg)
|
||
if build_dir and build_dir.exists():
|
||
await log_streamer.emit(task_id, f"临时文件保留在: {build_dir}")
|
||
await asyncio.to_thread(log_streamer.save_log, task_id, build_dir)
|
||
|
||
except asyncio.CancelledError:
|
||
await asyncio.to_thread(_db_update, db, task,
|
||
status="cancelled", completed_at=datetime.utcnow())
|
||
await log_streamer.emit(task_id, "任务已取消")
|
||
if build_dir and build_dir.exists():
|
||
await asyncio.to_thread(log_streamer.save_log, task_id, build_dir)
|
||
await asyncio.to_thread(_cleanup_build_dir, build_dir)
|
||
else:
|
||
await asyncio.to_thread(log_streamer.save_log, task_id, None)
|
||
|
||
except Exception as e:
|
||
if isinstance(e, BuildError):
|
||
category = e.category
|
||
error_msg = str(e)
|
||
else:
|
||
# 根据异常消息推断分类
|
||
msg = str(e).lower()
|
||
if "git" in msg:
|
||
category = "git"
|
||
elif "配置替换" in msg:
|
||
category = "config"
|
||
elif "混淆" in msg:
|
||
category = "config"
|
||
else:
|
||
category = "unknown"
|
||
error_msg = str(e)
|
||
await asyncio.to_thread(_db_update, db, task,
|
||
status="failed", completed_at=datetime.utcnow(),
|
||
error_message=error_msg, error_category=category)
|
||
await log_streamer.emit_error(task_id, f"打包失败: {error_msg}")
|
||
if build_dir and build_dir.exists():
|
||
await log_streamer.emit(task_id, f"临时文件保留在: {build_dir}")
|
||
await asyncio.to_thread(log_streamer.save_log, task_id, build_dir)
|
||
|
||
finally:
|
||
log_streamer.complete(task_id)
|
||
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
async def copy_source_code(task_id: str, task, source_dir: Path, definition: dict = None) -> Path:
|
||
"""从分支源码目录拷贝代码到打包目录"""
|
||
await log_streamer.emit_step(task_id, "拷贝代码")
|
||
|
||
project_id = _task_project_id(task)
|
||
if definition is None:
|
||
definition = get_definition(project_id, {})
|
||
build_dir = BUILD_BASE_DIR / f"build_{project_id}_{task_id}"
|
||
if build_dir.exists():
|
||
shutil.rmtree(build_dir)
|
||
|
||
# 未指定拷贝条目时拷贝整个仓库(不含 Git 数据和编译缓存)
|
||
copy_items = definition.get("copy_items") or []
|
||
if not copy_items:
|
||
await log_streamer.emit(task_id, "拷贝整个仓库")
|
||
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
|
||
|
||
shutil.copytree(source_dir, build_dir, symlinks=True, ignore=_ignore)
|
||
await log_streamer.emit(task_id, "代码拷贝完成")
|
||
return build_dir
|
||
|
||
# 旧项目配置可能早于 Route 2 集成,按分支实际内容补齐快照。
|
||
if (project_id == LEGACY_PROJECT_ID or definition.get("patcher") == PATCHER_READOOR) and (
|
||
source_dir / "iOSGuardIntegration"
|
||
).is_dir() and "iOSGuardIntegration" not in copy_items:
|
||
copy_items = [*copy_items, "iOSGuardIntegration"]
|
||
|
||
build_dir.mkdir(parents=True)
|
||
for item in copy_items:
|
||
src = source_dir / item
|
||
# 历史分支中该文件可能仍是小写 podfile;构建副本统一使用 Pods.xcodeproj
|
||
# 引用的标准名称 Podfile,避免大小写敏感文件系统报路径不一致。
|
||
if item == "Podfile" and not src.is_file():
|
||
src = source_dir / "podfile"
|
||
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"))
|
||
elif src.is_file():
|
||
await log_streamer.emit(task_id, f"拷贝文件: {item}")
|
||
shutil.copy2(src, dst)
|
||
|
||
await log_streamer.emit(task_id, "代码拷贝完成")
|
||
return build_dir
|
||
|
||
|
||
async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||
"""生成打包配置"""
|
||
await log_streamer.emit_step(task_id, "生成配置")
|
||
|
||
from ..routers.config import (
|
||
load_config, _config_lock, get_track, get_track_name, track_build_ver,
|
||
is_release_track, next_build_no, _ensure_track,
|
||
)
|
||
|
||
project_id = _task_project_id(task)
|
||
config = load_config(project_id)
|
||
apps = config.get("apps", {})
|
||
schemes = config.get("schemes", {})
|
||
|
||
app = apps.get(task.app_id, {})
|
||
scheme = schemes.get(task.scheme_id, {})
|
||
|
||
# 版本号由当前服务配置统一管理,不读取分支源码中的手动打包脚本。
|
||
# 按分支所属轨道取版本号:每个上架分支(master、develop 等)一条独立轨道,
|
||
# 自测分支共用 feature 轨,各轨道的 App_Ver 互不影响。
|
||
track_name = get_track_name(config, task.branch)
|
||
track = get_track(config, track_name)
|
||
app_ver = track.get("app_ver") or "2.180.0"
|
||
|
||
# 构建号按版本号独立记录:build_map[app_ver] 为该版本号已用到的最大第四位。
|
||
build_ver = track_build_ver(track)
|
||
is_release = is_release_track(track)
|
||
await log_streamer.emit(
|
||
task_id,
|
||
f"版本轨道: {track_name}({'上架,App_Store 打包自增' if is_release else '自测,构建号不自增'})",
|
||
)
|
||
|
||
# 上架轨的 App_Store 打包,在该版本号的构建号上 +1(回退到旧版本号也从它自己的最大值继续);
|
||
# feature 轨始终使用手动设定的构建号。
|
||
if is_release and task.build_type == "App_Store":
|
||
async with _config_lock:
|
||
config = load_config(project_id)
|
||
track = _ensure_track(config, track_name)
|
||
track.setdefault("app_ver", app_ver)
|
||
n = next_build_no(config["versions"]["tracks"], app_ver)
|
||
track.setdefault("build_map", {})[app_ver] = n
|
||
build_ver = f"{app_ver}.{n}"
|
||
|
||
from ..routers.config import save_config
|
||
save_config(config)
|
||
|
||
await log_streamer.emit(task_id, f"Build_Ver 已递增: {build_ver}")
|
||
|
||
# 构建配置
|
||
config_data = {
|
||
"PROJECT_ID": project_id,
|
||
"VERSION": app_ver,
|
||
"BUILD_VERSION": build_ver,
|
||
"SERVER": app.get("server", ""),
|
||
"API": app.get("API", ""),
|
||
"APPID_NAME": app.get("name", ""),
|
||
"APPID": app.get("AppGuid", app.get("AppId", "")),
|
||
"UPLOAD_KEY": app.get("upload_key", task.app_id),
|
||
"SCHEME": scheme.get("name", ""),
|
||
"OSS_FLODER": scheme.get("ossFloder", ""),
|
||
"BUILD_TYPE": task.build_type,
|
||
"EXCLUDE_SYMBOLS": bool(task.exclude_symbols),
|
||
"ENABLE_OBFUSCATION": task.obfuscation,
|
||
}
|
||
|
||
# 证书配置
|
||
certificates = app.get("certificates", {})
|
||
|
||
# 无需证书的应用(如英汉大词典),使用项目默认签名
|
||
if not certificates:
|
||
config_data["NO_CERT"] = True
|
||
await log_streamer.emit(task_id, "该应用无需配置证书,使用项目默认签名")
|
||
else:
|
||
cert = certificates.get(task.build_type, {})
|
||
if cert:
|
||
config_data["CERTIFICATE"] = cert.get("cer", "")
|
||
config_data["PROVISIONING_PROFILE"] = cert.get("pro", "")
|
||
config_data["BUNDLE_ID"] = cert.get("name", "")
|
||
theme_value = cert.get("theme", "")
|
||
config_data["THEME"] = theme_value
|
||
|
||
# 皮肤只从服务端托管的上传包或默认资源读取,不使用分支源码目录。
|
||
if theme_value:
|
||
skin_name = Path(theme_value).name
|
||
skin_zip = SKINS_DIR / app.get("upload_key", "") / f"{skin_name}.zip"
|
||
if skin_zip.exists():
|
||
skin_extract_dir = build_dir / "skin_temp"
|
||
skin_extract_dir.mkdir(exist_ok=True)
|
||
with zipfile.ZipFile(skin_zip, "r") as zf:
|
||
zf.extractall(skin_extract_dir)
|
||
# 过滤掉 macOS 压缩产生的 __MACOSX 及隐藏文件,避免把它们
|
||
# 当成皮肤资源目录一起复制进 Images.xcassets。
|
||
entries = [
|
||
e for e in skin_extract_dir.iterdir()
|
||
if e.name != "__MACOSX" and not e.name.startswith(".")
|
||
]
|
||
if len(entries) == 1 and entries[0].is_dir():
|
||
config_data["THEME"] = str(entries[0])
|
||
else:
|
||
config_data["THEME"] = str(skin_extract_dir)
|
||
await log_streamer.emit(task_id, f"皮肤包 {skin_name}.zip 已解压")
|
||
else:
|
||
default_theme = AUTOMATION_DIR / "themes" / skin_name
|
||
if default_theme.is_dir():
|
||
config_data["THEME"] = str(default_theme)
|
||
await log_streamer.emit(task_id, f"使用服务默认皮肤: {skin_name}")
|
||
else:
|
||
await log_streamer.emit(task_id, f"皮肤 {theme_value} 不存在")
|
||
|
||
# 严格沿用 AutoPacking/start_build_app.py 的 configure_provisioning:
|
||
# 描述文件必须成功匹配,并从文件本身提取 Name 与 TeamIdentifier。
|
||
provisioning_profile = config_data.get("PROVISIONING_PROFILE", "")
|
||
if provisioning_profile:
|
||
profile_name, team_id = await asyncio.to_thread(
|
||
_resolve_provisioning_profile, provisioning_profile
|
||
)
|
||
config_data["PROVISIONING_NAME"] = profile_name
|
||
config_data["TEAM_ID"] = team_id
|
||
|
||
# 关联域名等配置
|
||
config_data["ASSOCIATED_DOMAINS"] = app.get("AssDom", "")
|
||
for key in ["weixinlogin", "weixinpay", "wxworkSchema", "tencent", "UniversalLink", "AlivcLicenseKey"]:
|
||
if key in app:
|
||
config_data[key] = app[key]
|
||
|
||
# 项目自定义字段,供通用替换规则以 ${app.X} / ${server.X} 引用
|
||
definition = get_definition(project_id, config)
|
||
server = config.get("servers", {}).get(app.get("server", ""), {})
|
||
config_data["APP_VARS"] = {
|
||
field["key"]: app.get(field["key"], "") for field in definition["app_fields"] if field.get("key")
|
||
}
|
||
# 通用项目没有 AppGuid:以第一个 App 字段(如 APPID)作为 App 标识,
|
||
# 用于产物文件名和通知;未配置 App 字段时用 upload_key。
|
||
if definition["patcher"] != PATCHER_READOOR:
|
||
id_field = next((field for field in definition["app_fields"] if field.get("key")), None)
|
||
app_ident = config_data["APP_VARS"].get(id_field["key"], "") if id_field else ""
|
||
config_data["APPID"] = app_ident or config_data["UPLOAD_KEY"]
|
||
config_data["APPID_LABEL"] = (id_field.get("label") or id_field["key"]) if app_ident else "App 标识"
|
||
config_data["SERVER_VARS"] = {
|
||
field["key"]: server.get(field["key"], "") for field in definition["server_fields"] if field.get("key")
|
||
}
|
||
|
||
# 写入配置文件
|
||
config_output_path = build_dir / "config_output.json"
|
||
with open(config_output_path, "w", encoding="utf-8") as f:
|
||
json.dump(config_data, f, indent=2, ensure_ascii=False)
|
||
|
||
await log_streamer.emit(task_id, "配置已生成")
|
||
return config_data
|
||
|
||
|
||
async def patch_project(task_id: str, task, config_data: dict, build_dir: Path, definition: dict = None):
|
||
"""替换项目配置"""
|
||
await log_streamer.emit_step(task_id, "替换项目配置")
|
||
|
||
try:
|
||
patch_lines = await asyncio.to_thread(apply_project_config, build_dir, config_data, definition)
|
||
except ProjectPatchError as exc:
|
||
raise BuildError(str(exc), category="config") from exc
|
||
(build_dir / "patch_result.log").write_text("\n".join(patch_lines), encoding="utf-8")
|
||
for line in patch_lines:
|
||
await log_streamer.emit(task_id, line)
|
||
await log_streamer.emit(task_id, "项目配置替换完成")
|
||
|
||
|
||
def _pod_dir(build_dir: Path, xcode: dict = None) -> Path:
|
||
"""Podfile 所在目录:工程在仓库子目录时(如 sub/App.xcworkspace),优先取该子目录。"""
|
||
candidates = []
|
||
for key in ("workspace", "project"):
|
||
rel = ((xcode or {}).get(key) or "").strip()
|
||
if rel:
|
||
candidates.append(build_dir / Path(rel).parent)
|
||
candidates.append(build_dir)
|
||
for directory in candidates:
|
||
if (directory / "Podfile").is_file() or (directory / "podfile").is_file():
|
||
return directory
|
||
return None
|
||
|
||
|
||
_POD_SPEC_MISSING = "Unable to find a specification for"
|
||
|
||
|
||
async def _run_pod(task_id: str, pod_dir: Path, *extra_args: str) -> tuple:
|
||
"""执行 pod install,实时输出日志,返回 (退出码, 输出行)。"""
|
||
process = await asyncio.create_subprocess_exec(
|
||
"pod", "install", *extra_args,
|
||
cwd=str(pod_dir),
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.STDOUT,
|
||
)
|
||
output = []
|
||
async for line in process.stdout:
|
||
decoded = line.decode("utf-8", errors="replace").strip()
|
||
if decoded:
|
||
output.append(decoded)
|
||
await log_streamer.emit(task_id, decoded)
|
||
await process.wait()
|
||
return process.returncode, output
|
||
|
||
|
||
async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||
"""安装 CocoaPods 依赖"""
|
||
await log_streamer.emit_step(task_id, "安装依赖")
|
||
|
||
pod_dir = _pod_dir(build_dir, xcode)
|
||
if pod_dir is None:
|
||
await log_streamer.emit(task_id, "项目未使用 CocoaPods,跳过")
|
||
return
|
||
if pod_dir != build_dir:
|
||
await log_streamer.emit(task_id, f"Podfile 目录: {pod_dir.relative_to(build_dir)}")
|
||
|
||
returncode, output = await _run_pod(task_id, pod_dir)
|
||
# 打包机本地的 Specs 索引过旧时找不到新版本 Pod,更新索引后重试一次
|
||
if returncode != 0 and any(_POD_SPEC_MISSING in line for line in output):
|
||
await log_streamer.emit(task_id, "本地 Pod 索引缺少所需版本,更新索引后重试(pod install --repo-update)", level="warn")
|
||
returncode, output = await _run_pod(task_id, pod_dir, "--repo-update")
|
||
|
||
if returncode != 0:
|
||
raise BuildError("pod install 失败", category="config")
|
||
|
||
patched_files = await asyncio.to_thread(_patch_afnetworking_private_headers, pod_dir)
|
||
if patched_files:
|
||
await log_streamer.emit(
|
||
task_id,
|
||
f"已修复 AFNetworking 私有头引用: {patched_files} 个文件",
|
||
)
|
||
|
||
await log_streamer.emit(task_id, "依赖安装完成")
|
||
|
||
|
||
BRANCH_BUILD_POLICY = Path("AutoPacking") / "build_policy.json"
|
||
|
||
|
||
def _load_branch_build_policy(build_dir: Path) -> dict:
|
||
"""读取源码快照自带的打包策略 AutoPacking/build_policy.json。
|
||
|
||
策略随分支代码提交,由分支声明自身的打包契约;文件缺失、解析失败或非对象时返回空字典,
|
||
即按旧分支处理(行为与引入该文件前一致)。
|
||
"""
|
||
policy_file = build_dir / BRANCH_BUILD_POLICY
|
||
if not policy_file.is_file():
|
||
return {}
|
||
try:
|
||
data = json.loads(policy_file.read_text(encoding="utf-8"))
|
||
except (OSError, ValueError):
|
||
return {}
|
||
return data if isinstance(data, dict) else {}
|
||
|
||
|
||
def _resolve_obfuscation_decision(build_dir: Path, definition: dict, task) -> tuple:
|
||
"""决定本次是否执行 L1 混淆,返回 (是否混淆, 原因)。
|
||
|
||
- 项目不支持混淆:始终不混淆;
|
||
- 分支 build_policy.json 显式声明 "force_obfuscation": true:强制混淆,忽略任务勾选;
|
||
- 其余(含所有旧分支/旧 Tag):沿用任务勾选。
|
||
不按混淆脚本是否存在推断:2.195.0 起的旧 Tag 已带脚本,但当时混淆为可选。
|
||
"""
|
||
if not definition.get("obfuscation"):
|
||
return False, "项目不支持代码混淆"
|
||
policy = _load_branch_build_policy(build_dir)
|
||
if policy.get("force_obfuscation") is True:
|
||
return True, f"分支 {BRANCH_BUILD_POLICY} 声明强制混淆"
|
||
if (build_dir / BRANCH_BUILD_POLICY).is_file() and not policy:
|
||
return bool(task.obfuscation), f"分支 {BRANCH_BUILD_POLICY} 无法解析,按任务勾选"
|
||
return bool(task.obfuscation), "分支未声明强制混淆,按任务勾选"
|
||
|
||
|
||
def _resolve_obfuscation_dir(build_dir: Path) -> Path:
|
||
"""优先使用源码分支自带的 AutoPacking/obfuscation(如 feat/llvm-obf-m0),旧分支回退服务端内置脚本。"""
|
||
branch_dir = build_dir / "AutoPacking" / "obfuscation"
|
||
if (
|
||
(branch_dir / "obfuscate_symbols.py").is_file()
|
||
and (branch_dir / "scripts" / "obfuscation_self_check.sh").is_file()
|
||
):
|
||
return branch_dir
|
||
return AUTOMATION_DIR / "obfuscation"
|
||
|
||
|
||
async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path):
|
||
"""执行代码混淆"""
|
||
await log_streamer.emit_step(task_id, "代码混淆")
|
||
|
||
obf_root = _resolve_obfuscation_dir(build_dir)
|
||
await log_streamer.emit(task_id, f"L1 混淆脚本目录: {obf_root}")
|
||
if obf_root == AUTOMATION_DIR / "obfuscation":
|
||
await log_streamer.emit_warning(
|
||
task_id,
|
||
"分支未自带混淆脚本,改用服务端内置脚本混淆;该脚本面向新版代码,旧版本若混淆失败可取消勾选混淆后重打",
|
||
)
|
||
|
||
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["OBF_SALT"] = seed
|
||
# 自检
|
||
self_check_script = obf_root / "scripts" / "obfuscation_self_check.sh"
|
||
process = await asyncio.create_subprocess_exec(
|
||
"bash", str(self_check_script), str(build_dir),
|
||
cwd=str(build_dir),
|
||
env=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()
|
||
|
||
if process.returncode != 0:
|
||
raise Exception("混淆自检失败")
|
||
|
||
await log_streamer.emit(task_id, "混淆自检通过")
|
||
|
||
# 执行混淆
|
||
obfuscate_script = obf_root / "obfuscate_symbols.py"
|
||
process = await asyncio.create_subprocess_exec(
|
||
"python3", str(obfuscate_script), "--archive-mode", "--salt", seed,
|
||
cwd=str(build_dir),
|
||
env=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()
|
||
|
||
if process.returncode != 0:
|
||
raise Exception("代码混淆失败")
|
||
|
||
await log_streamer.emit(task_id, "代码混淆完成")
|
||
|
||
|
||
def _prune_old_obj_caches(obj_cache_root: Path, current_ver_dir: str, keep: int = 3) -> None:
|
||
if not obj_cache_root.is_dir():
|
||
return
|
||
keep_n = max(1, int(keep))
|
||
others = [
|
||
d for d in obj_cache_root.iterdir()
|
||
if d.is_dir() and d.name != current_ver_dir
|
||
]
|
||
others.sort(key=lambda d: d.stat().st_mtime_ns, reverse=True)
|
||
for stale in others[max(0, keep_n - 1):]:
|
||
shutil.rmtree(stale, ignore_errors=True)
|
||
|
||
|
||
async def _prepare_iosguard_build_env(task_id: str, config_data: dict, build_dir: Path) -> dict:
|
||
"""注入 iOSGuard LLVM IR/Route 2 模式、分渠道与版本隔离的缓存,并在构建前自愈校验 `opt` 工具链。"""
|
||
env = os.environ.copy()
|
||
env["SKIP_OBF_PHASE"] = "1"
|
||
|
||
dist_channel = "appstore" if config_data.get("BUILD_TYPE") == "App_Store" else "dev"
|
||
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')}"
|
||
|
||
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"))
|
||
sdk_cache_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
env["IG_DIST_CHANNEL"] = dist_channel
|
||
env["IG_OBF_MODE"] = effective_mode
|
||
env["IG_ALL_GUARD_OFF"] = all_off
|
||
env["IG_RELEASE_SEED"] = seed
|
||
env["IG_TOOLCHAIN_CACHE_DIR"] = str(IG_TOOLCHAIN_CACHE_DIR)
|
||
env["IG_SDK_CACHE_DIR"] = str(sdk_cache_dir)
|
||
|
||
resolver_path = build_dir / "iOSGuardIntegration" / "toolchain" / "tools" / "llvm_obf" / "ig_toolchain_resolver.py"
|
||
if not resolver_path.is_file():
|
||
default_obj_dir = Path(obj_cache_override) if obj_cache_override else (IG_CACHE_DIR / "obj_cache" / f"default-{dist_channel}")
|
||
default_obj_dir.mkdir(parents=True, exist_ok=True)
|
||
env["IG_OBF_OBJ_CACHE_DIR"] = str(default_obj_dir)
|
||
return env
|
||
|
||
if all_off == "1" or effective_mode == "off":
|
||
default_obj_dir = Path(obj_cache_override) if obj_cache_override else (IG_CACHE_DIR / "obj_cache")
|
||
default_obj_dir.mkdir(parents=True, exist_ok=True)
|
||
env["IG_OBF_OBJ_CACHE_DIR"] = str(default_obj_dir)
|
||
await log_streamer.emit(
|
||
task_id,
|
||
f"iOSGuard IR 混淆已显式关闭,跳过 opt 校验(IG_OBF_MODE={effective_mode}, IG_ALL_GUARD_OFF={all_off})",
|
||
)
|
||
return env
|
||
|
||
await log_streamer.emit_step(task_id, "检查工具链")
|
||
env["IG_REQUIRE_LLVM_OBF"] = "1"
|
||
try:
|
||
tc_info = await ensure_toolchain(resolver_path, task_id=task_id, notify_on_event=True)
|
||
except Exception as exc:
|
||
raise BuildError(f"LLVM IR 混淆工具链校验失败(IG_REQUIRE_LLVM_OBF=1): {exc}", category="config") from exc
|
||
|
||
if obj_cache_override:
|
||
obj_cache_dir = Path(obj_cache_override)
|
||
else:
|
||
xc_build = ((tc_info or {}).get("xcode") or {}).get("xcode_build") or "unknown"
|
||
passes_h8 = ((tc_info or {}).get("passes_hash") or "legacy")[:8]
|
||
obj_cache_dir = IG_CACHE_DIR / "obj_cache" / f"{xc_build}-{passes_h8}" / dist_channel
|
||
await asyncio.to_thread(_prune_old_obj_caches, IG_CACHE_DIR / "obj_cache", obj_cache_dir.parent.name, 3)
|
||
obj_cache_dir.mkdir(parents=True, exist_ok=True)
|
||
env["IG_OBF_OBJ_CACHE_DIR"] = str(obj_cache_dir)
|
||
|
||
await log_streamer.emit(
|
||
task_id,
|
||
f"iOSGuard 发布模式: IG_OBF_MODE={effective_mode}, IG_DIST_CHANNEL={dist_channel}, "
|
||
f"opt={tc_info.get('source_mode', 'ready')}, seed={seed}, obj_cache={obj_cache_dir}",
|
||
)
|
||
return env
|
||
|
||
|
||
def persist_task_artifacts(
|
||
task_id: str,
|
||
build_dir: Path,
|
||
scheme: str = "",
|
||
dsym_path: Path = None,
|
||
) -> tuple:
|
||
"""将 dSYM、符号/方法映射、诊断事件码与混淆审计持久化到 ARTIFACTS_DIR/<task_id>,脱离 build_dir 生命周期。"""
|
||
artifact_root = ARTIFACTS_DIR / task_id
|
||
persisted_dsym = None
|
||
persisted_maps = None
|
||
|
||
archive_dsyms_dir = build_dir / "build" / f"{scheme}.xcarchive" / "dSYMs" if scheme else None
|
||
dsym_bundles = sorted(archive_dsyms_dir.glob("*.dSYM")) if archive_dsyms_dir and archive_dsyms_dir.is_dir() else []
|
||
|
||
if dsym_bundles:
|
||
dsym_dest_dir = artifact_root / f"{scheme or 'app'}_dSYMs"
|
||
dsym_dest_dir.mkdir(parents=True, exist_ok=True)
|
||
for bundle in dsym_bundles:
|
||
dst = dsym_dest_dir / bundle.name
|
||
if dst.exists():
|
||
shutil.rmtree(dst, ignore_errors=True)
|
||
shutil.copytree(bundle, dst, symlinks=True)
|
||
persisted_dsym = dsym_dest_dir
|
||
elif dsym_path and Path(dsym_path).exists():
|
||
src = Path(dsym_path)
|
||
artifact_root.mkdir(parents=True, exist_ok=True)
|
||
dst = artifact_root / src.name
|
||
if src.is_dir():
|
||
if dst.exists():
|
||
shutil.rmtree(dst, ignore_errors=True)
|
||
shutil.copytree(src, dst, symlinks=True)
|
||
else:
|
||
shutil.copy2(src, dst)
|
||
persisted_dsym = dst
|
||
|
||
maps_dest_dir = artifact_root / "obfuscation_maps"
|
||
copied_any = False
|
||
|
||
src_maps_dir = build_dir / "obfuscation_maps"
|
||
if src_maps_dir.is_dir():
|
||
for item in sorted(src_maps_dir.glob("*.json")):
|
||
if item.is_file():
|
||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(item, maps_dest_dir / item.name)
|
||
copied_any = True
|
||
|
||
unmapped_file = build_dir / "unmapped_mappings.json"
|
||
if unmapped_file.is_file():
|
||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(unmapped_file, maps_dest_dir / unmapped_file.name)
|
||
copied_any = True
|
||
|
||
diag_events = build_dir / "iOSGuardIntegration" / "toolchain" / "config" / "ig_diag_events.json"
|
||
if diag_events.is_file():
|
||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(diag_events, maps_dest_dir / "ig_diag_events.json")
|
||
copied_any = True
|
||
|
||
derived_data = build_dir / "build" / "derived_data"
|
||
if derived_data.is_dir():
|
||
audits = sorted(derived_data.rglob("ig_obfuscation_audit.json"))
|
||
if audits:
|
||
chosen = next((a for a in audits if scheme and f"{scheme}.build" in str(a)), audits[0])
|
||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(chosen, maps_dest_dir / "ig_obfuscation_audit.json")
|
||
copied_any = True
|
||
|
||
ipa_audit_report = build_dir / "build" / "ipa_audit_report.json"
|
||
if ipa_audit_report.is_file():
|
||
maps_dest_dir.mkdir(parents=True, exist_ok=True)
|
||
shutil.copy2(ipa_audit_report, maps_dest_dir / "ipa_audit_report.json")
|
||
copied_any = True
|
||
|
||
if copied_any:
|
||
persisted_maps = maps_dest_dir
|
||
|
||
return persisted_dsym, persisted_maps
|
||
|
||
|
||
async def _run_exported_ipa_audit(
|
||
task_id: str,
|
||
audit_script: Path,
|
||
ipa_path: Path,
|
||
archive_path: Path,
|
||
export_path: Path,
|
||
config_data: dict,
|
||
build_dir: Path,
|
||
build_env: dict,
|
||
) -> None:
|
||
"""导出后执行完整 IPA 加固门禁审计(Route 2 + StaticHygieneGate + Mach-O 门禁),不通过直接阻断上传。"""
|
||
scheme = config_data.get("SCHEME", "")
|
||
cmd = [
|
||
sys.executable or "python3",
|
||
str(audit_script),
|
||
str(ipa_path),
|
||
"--archive",
|
||
str(archive_path),
|
||
"--report-out",
|
||
str(export_path / "ipa_audit_report.json"),
|
||
]
|
||
if config_data.get("BUNDLE_ID"):
|
||
cmd.extend(["--bundle-id", config_data["BUNDLE_ID"]])
|
||
|
||
derived_data = export_path / "derived_data"
|
||
if derived_data.is_dir():
|
||
audits = sorted(derived_data.rglob("ig_obfuscation_audit.json"))
|
||
if audits:
|
||
chosen = next((a for a in audits if scheme and f"{scheme}.build" in str(a)), audits[0])
|
||
cmd.extend(["--audit-json", str(chosen)])
|
||
|
||
maps_dir = build_dir / "obfuscation_maps"
|
||
if maps_dir.is_dir():
|
||
sym_maps = sorted(maps_dir.glob("symbol_map_*.json"))
|
||
if sym_maps:
|
||
exact = [m for m in sym_maps if scheme and f"_{scheme}_" in m.name]
|
||
chosen_sym = (exact or sym_maps)[-1]
|
||
cmd.extend(["--symbol-map", str(chosen_sym)])
|
||
|
||
await log_streamer.emit(task_id, "开始 IPA 加固门禁审计...")
|
||
process = await asyncio.create_subprocess_exec(
|
||
*cmd,
|
||
cwd=str(build_dir),
|
||
env=build_env,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.STDOUT,
|
||
)
|
||
audit_output = []
|
||
async for line in process.stdout:
|
||
decoded = line.decode("utf-8", errors="replace").strip()
|
||
if decoded:
|
||
audit_output.append(decoded)
|
||
await log_streamer.emit(task_id, decoded)
|
||
await process.wait()
|
||
if process.returncode != 0:
|
||
raise BuildError(
|
||
"IPA 加固门禁审计失败,已阻止上传",
|
||
category="build",
|
||
detail="\n".join(audit_output[-25:]),
|
||
)
|
||
|
||
|
||
IG_APPSTORE_FLAG = "IG_APPSTORE_DISTRIBUTION"
|
||
IG_ANTI_TAMPER_SOURCE = "IGAntiTamper.c"
|
||
|
||
|
||
async def _verify_dist_channel_flag(
|
||
task_id: str,
|
||
container_args: tuple,
|
||
scheme: str,
|
||
build_dir: Path,
|
||
build_env: dict,
|
||
) -> None:
|
||
"""Archive 前核对分发渠道编译条件,确保 500/501 防砸壳/重签名校验与渠道一致。
|
||
|
||
App 工程不再在 Release 写死 IG_APPSTORE_DISTRIBUTION,唯一来源是本服务透传的
|
||
IG_DIST_CHANNEL=appstore。上架包缺失该条件 → 防砸壳/重签名检测整体失效,必须阻断;
|
||
非上架包带上该条件(旧分支仍写死)→ Ad-hoc 包会被误判 500/501 而锁定敏感入口,仅告警不阻断。
|
||
未接入 anti_tamper 的历史分支直接跳过。
|
||
"""
|
||
project_file = build_dir / "readoor.xcodeproj" / "project.pbxproj"
|
||
if not project_file.is_file():
|
||
return
|
||
if IG_ANTI_TAMPER_SOURCE not in project_file.read_text(encoding="utf-8", errors="replace"):
|
||
return
|
||
|
||
channel = build_env.get("IG_DIST_CHANNEL", "dev")
|
||
cmd = [
|
||
"xcodebuild", "-showBuildSettings",
|
||
*container_args,
|
||
"-scheme", scheme,
|
||
"-configuration", "Release",
|
||
"-sdk", "iphoneos",
|
||
f"IG_DIST_CHANNEL={channel}",
|
||
f"IG_ALL_GUARD_OFF={build_env.get('IG_ALL_GUARD_OFF', '0')}",
|
||
]
|
||
process = await asyncio.create_subprocess_exec(
|
||
*cmd,
|
||
cwd=str(build_dir),
|
||
env=build_env,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.STDOUT,
|
||
)
|
||
flag_lines = []
|
||
tail = []
|
||
async for line in process.stdout:
|
||
decoded = line.decode("utf-8", errors="replace").strip()
|
||
if not decoded:
|
||
continue
|
||
tail = (tail + [decoded])[-20:]
|
||
if decoded.startswith(("OTHER_SWIFT_FLAGS =", "SWIFT_ACTIVE_COMPILATION_CONDITIONS =")) \
|
||
and any(tok in (IG_APPSTORE_FLAG, f"-D{IG_APPSTORE_FLAG}") for tok in decoded.split()):
|
||
flag_lines.append(decoded)
|
||
await process.wait()
|
||
|
||
if channel == "appstore":
|
||
if process.returncode != 0:
|
||
raise BuildError(
|
||
f"上架包分发渠道编译条件核对失败(xcodebuild -showBuildSettings 退出码 {process.returncode})",
|
||
category="config",
|
||
detail="\n".join(tail),
|
||
)
|
||
if not flag_lines:
|
||
raise BuildError(
|
||
f"上架包未注入 {IG_APPSTORE_FLAG}(IG_DIST_CHANNEL=appstore 未生效),"
|
||
"防砸壳/重签名检测将失效,已阻止 Archive",
|
||
category="config",
|
||
)
|
||
await log_streamer.emit(task_id, f"分发渠道核对通过:上架包已注入 {IG_APPSTORE_FLAG}")
|
||
elif flag_lines:
|
||
await log_streamer.emit_warning(
|
||
task_id,
|
||
f"非上架包仍带 {IG_APPSTORE_FLAG}(分支工程可能仍在 Release 写死该条件),"
|
||
"安装后可能因 500/501 被锁定登录/支付并延迟退出,请升级分支工程配置",
|
||
)
|
||
|
||
|
||
async def build_project(
|
||
task_id: str,
|
||
task,
|
||
config_data: dict,
|
||
build_dir: Path,
|
||
xcode: dict = None,
|
||
prepared_env: Optional[dict] = None,
|
||
) -> Path:
|
||
"""构建项目;xcode 为项目定义中的 {workspace, project},优先使用 workspace"""
|
||
await log_streamer.emit_step(task_id, "构建项目")
|
||
|
||
scheme = config_data.get("SCHEME", "")
|
||
export_path = build_dir / "build"
|
||
archive_path = export_path / f"{scheme}.xcarchive"
|
||
if xcode is None:
|
||
xcode = get_definition(LEGACY_PROJECT_ID, {})["xcode"]
|
||
if xcode.get("workspace"):
|
||
container_args = ("-workspace", xcode["workspace"])
|
||
elif xcode.get("project"):
|
||
container_args = ("-project", xcode["project"])
|
||
else:
|
||
raise BuildError("项目未配置 Xcode workspace 或 project", category="config")
|
||
|
||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||
project_file = build_dir / "readoor.xcodeproj" / "project.pbxproj"
|
||
if project_file.is_file():
|
||
project_text = project_file.read_text(encoding="utf-8")
|
||
for script in ("ig_ld_wrapper.py", "ig_guard_frameworks_phase.py"):
|
||
relative = Path("iOSGuardIntegration/toolchain/tools/xcode_archive") / script
|
||
if str(relative) in project_text and not (build_dir / relative).is_file():
|
||
raise BuildError(f"源码快照缺少工程引用的脚本:{relative}", category="config")
|
||
|
||
build_env = prepared_env if prepared_env is not None else await _prepare_iosguard_build_env(task_id, config_data, build_dir)
|
||
export_path.mkdir(parents=True, exist_ok=True)
|
||
|
||
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
|
||
await log_streamer.emit(task_id, "开始 Archive...")
|
||
archive_started_at = time.monotonic()
|
||
archive_output = []
|
||
archive_cmd = [
|
||
"xcodebuild", "archive",
|
||
*container_args,
|
||
"-scheme", scheme,
|
||
"-configuration", "Release",
|
||
"-archivePath", str(archive_path),
|
||
"-derivedDataPath", str(export_path / "derived_data"),
|
||
"-destination", "generic/platform=ios",
|
||
]
|
||
if scheme in ("readoor31", "readoor31OtherPay"):
|
||
archive_cmd.extend([
|
||
f"IG_DIST_CHANNEL={build_env['IG_DIST_CHANNEL']}",
|
||
f"IG_OBF_MODE={build_env['IG_OBF_MODE']}",
|
||
f"IG_ALL_GUARD_OFF={build_env['IG_ALL_GUARD_OFF']}",
|
||
f"IG_RELEASE_SEED={build_env['IG_RELEASE_SEED']}",
|
||
])
|
||
process = await asyncio.create_subprocess_exec(
|
||
*archive_cmd,
|
||
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:
|
||
archive_output.append(decoded)
|
||
await log_streamer.emit(task_id, decoded)
|
||
await process.wait()
|
||
archive_elapsed = time.monotonic() - archive_started_at
|
||
|
||
if process.returncode != 0:
|
||
category, hint = _classify_build_error(archive_output, "archive")
|
||
raise BuildError(hint, category=category, detail="\n".join(archive_output[-20:]))
|
||
await log_streamer.emit(task_id, f"Archive 构建完成,耗时: {archive_elapsed:.1f}s")
|
||
|
||
# 导出 IPA
|
||
await log_streamer.emit(task_id, "导出 IPA...")
|
||
export_plist = build_dir / "exportOptions.plist"
|
||
export_output = []
|
||
process = await asyncio.create_subprocess_exec(
|
||
"xcodebuild", "-exportArchive",
|
||
"-archivePath", str(archive_path),
|
||
"-exportPath", str(export_path),
|
||
"-exportOptionsPlist", str(export_plist),
|
||
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:
|
||
export_output.append(decoded)
|
||
await log_streamer.emit(task_id, decoded)
|
||
await process.wait()
|
||
|
||
if process.returncode != 0:
|
||
category, hint = _classify_build_error(export_output, "export")
|
||
raise BuildError(hint, category=category, detail="\n".join(export_output[-20:]))
|
||
|
||
# 查找 IPA 文件
|
||
ipa_files = list(export_path.glob("*.ipa"))
|
||
if not ipa_files:
|
||
raise Exception("未找到 IPA 文件")
|
||
|
||
ipa_path = ipa_files[0]
|
||
await log_streamer.emit(task_id, f"IPA 已导出: {ipa_path.name}")
|
||
|
||
if (
|
||
scheme in ("readoor31", "readoor31OtherPay")
|
||
and build_env.get("IG_ALL_GUARD_OFF") != "1"
|
||
and build_env.get("IG_OBF_MODE") != "off"
|
||
):
|
||
audit_script = (
|
||
build_dir
|
||
/ "iOSGuardIntegration"
|
||
/ "toolchain"
|
||
/ "tools"
|
||
/ "xcode_archive"
|
||
/ "audit_exported_ipa.py"
|
||
)
|
||
if audit_script.is_file():
|
||
await _run_exported_ipa_audit(
|
||
task_id,
|
||
audit_script,
|
||
ipa_path,
|
||
archive_path,
|
||
export_path,
|
||
config_data,
|
||
build_dir,
|
||
build_env,
|
||
)
|
||
|
||
return ipa_path
|
||
|
||
|
||
async def find_dsym(task_id: str, build_dir: Path, scheme: str = "") -> Path:
|
||
"""优先从 .xcarchive/dSYMs 查找全部 dSYM(含主 App 与 IGArchiveGuard.framework),否则回退 derived_data。"""
|
||
if scheme:
|
||
archive_dsyms = build_dir / "build" / f"{scheme}.xcarchive" / "dSYMs"
|
||
if archive_dsyms.is_dir():
|
||
main_dsym = archive_dsyms / f"{scheme}.app.dSYM"
|
||
if main_dsym.exists():
|
||
return main_dsym
|
||
bundles = sorted(archive_dsyms.glob("*.dSYM"))
|
||
if bundles:
|
||
return bundles[0]
|
||
|
||
derived_data = build_dir / "build" / "derived_data"
|
||
if not derived_data.exists():
|
||
return None
|
||
|
||
dsyms = list(derived_data.rglob("*.dSYM"))
|
||
if not dsyms:
|
||
return None
|
||
|
||
if scheme:
|
||
for dsym in dsyms:
|
||
if dsym.name == f"{scheme}.app.dSYM":
|
||
return dsym
|
||
|
||
return dsyms[0]
|
||
|
||
|
||
async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, build_dir: Path) -> tuple:
|
||
"""上传 IPA,返回 (download_url, qr_code_path)"""
|
||
await log_streamer.emit_step(task_id, "上传分发平台")
|
||
|
||
# 从当前服务的 config.json 读取上传配置,不执行分支源码中的上传脚本。
|
||
from ..routers.config import load_upload_config
|
||
config_data["_upload_config"] = load_upload_config()
|
||
try:
|
||
await log_streamer.emit(task_id, f"使用 {config_data['_upload_config'].get('mode', '')} 发布 IPA...")
|
||
return await asyncio.to_thread(publish_ipa, config_data, ipa_path, build_dir)
|
||
except DistributionError as exc:
|
||
raise BuildError(str(exc), category="upload") from exc
|
||
|
||
|
||
async def upload_dsym(task_id: str, task, config_data: dict, dsym_path: Path, build_dir: Path) -> str:
|
||
"""上传 dSYM,返回下载 URL;上传失败仅记录警告,不影响已完成的打包结果"""
|
||
await log_streamer.emit_step(task_id, "上传 dSYM")
|
||
try:
|
||
return await asyncio.to_thread(publish_dsym, config_data, dsym_path, build_dir)
|
||
except DistributionError as exc:
|
||
await log_streamer.emit(task_id, f"dSYM 上传失败: {exc}", level="warn")
|
||
return ""
|