Files
iOSBuildServer/backend/services/project_patcher.py
T
shenleiandClaude Opus 5.5 8f2f23682f feat: 支持多项目打包
- config.json 改为按项目存储(projects.<id>),上传配置全局共用;旧单项目配置自动迁移为 readoor
- 新增项目管理(管理员):Git 仓库/凭据、源码目录、Xcode 工程、拷贝条目、配置替换方式、自定义字段、替换规则
- 通用配置替换:pbxproj 版本号与签名,patch_rules 支持 define / replace_line 及 ${app.X}、${server.X} 模板
- 请求通过 X-Project 头选择项目;打包任务记录 project_id,历史按项目过滤
- 前端顶部切换项目,App/服务器环境表单按项目显示字段

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:59:30 +09:00

331 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""服务端自带的 iOS 工程配置替换逻辑。"""
import plistlib
import re
import shutil
from pathlib import Path
class ProjectPatchError(Exception):
"""工程配置无法完整写入。"""
def _replace_lines(path: Path, keyword: str, replacement: str) -> int:
if not path.exists():
raise ProjectPatchError(f"配置文件不存在: {path.relative_to(path.parent.parent)}")
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
count = 0
result = []
for line in lines:
if keyword in line and not line.lstrip().startswith("//"):
result.append(f"{replacement}\n")
count += 1
else:
result.append(line)
path.write_text("".join(result), encoding="utf-8")
return count
def _update_plist(path: Path, config: dict):
if not path.exists():
raise ProjectPatchError(f"Info.plist 不存在: {path}")
with path.open("rb") as f:
plist = plistlib.load(f)
plist["CFBundleDisplayName"] = config.get("APPID_NAME", "")
plist["AlivcLicenseKey"] = config.get("AlivcLicenseKey", "") or ""
scheme = (config.get("BUNDLE_ID", "") or "").replace(".", "").lower()
values = {
"weixinlogin": config.get("weixinlogin", ""),
"wechatpay": config.get("weixinpay", ""),
"tencent": config.get("tencent", ""),
# 企业微信 Schema 与微信登录 AppID 同样存在 CFBundleURLTypes 中
# (CFBundleURLName == "wxwork"),未配置则整条移除。
"wxwork": (config.get("wxworkSchema", "") or "").strip(),
"readoorUrlScheme": scheme,
}
url_types = []
for item in plist.get("CFBundleURLTypes", []):
name = item.get("CFBundleURLName")
value = values.get(name)
if name in values:
if not value:
continue
item["CFBundleURLSchemes"] = [value]
url_types.append(item)
plist["CFBundleURLTypes"] = url_types
with path.open("wb") as f:
plistlib.dump(plist, f, fmt=plistlib.FMT_XML)
def _apply_theme(build_dir: Path, theme_dir: str, messages: list[str]):
if not theme_dir:
return
source = Path(theme_dir)
if not source.is_dir():
raise ProjectPatchError(f"皮肤目录不存在: {source}")
target_assets = build_dir / "readoor" / "BookShelf" / "Resources" / "Images.xcassets"
for item in source.iterdir():
if not item.is_dir():
continue
# 跳过 macOS 压缩包内的 __MACOSX 及隐藏目录,仅复制真实皮肤资源
if item.name == "__MACOSX" or item.name.startswith("."):
continue
destination = target_assets / item.name
if destination.exists():
shutil.rmtree(destination)
shutil.copytree(item, destination)
messages.append(f"已替换皮肤资源: {destination.relative_to(build_dir)}")
icon = source / "AppIcon.appiconset" / "icon-1024.png"
logo = build_dir / "readoor" / "3.0" / "Resources" / "3.0.xcassets" / "AppLogo.imageset" / "icon-1024.png"
if icon.exists() and logo.parent.exists():
shutil.copy2(icon, logo)
messages.append("已替换应用 Logo")
license_file = source / "license.crt"
license_target = build_dir / "readoor" / "3.0" / "Resources" / "license.crt"
if license_file.exists() and license_target.parent.exists():
shutil.copy2(license_file, license_target)
messages.append("已替换渠道 License")
def _write_export_options(build_dir: Path, config: dict):
if config.get("NO_CERT"):
data = {
"destination": "export",
"method": "development" if config.get("BUILD_TYPE") == "Ad_Hoc" else "app-store-connect",
"stripSwiftSymbols": True,
"thinning": "<none>",
}
else:
data = {
"destination": "export",
"method": "release-testing" if config.get("BUILD_TYPE") == "Ad_Hoc" else "app-store-connect",
"teamID": config.get("TEAM_ID", ""),
"provisioningProfiles": {config.get("BUNDLE_ID", ""): config.get("PROVISIONING_NAME", "")},
"signingCertificate": config.get("CERTIFICATE", ""),
"signingStyle": "manual",
"stripSwiftSymbols": True,
"thinning": "<none>",
}
with (build_dir / "exportOptions.plist").open("wb") as f:
plistlib.dump(data, f)
def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str]):
macro = build_dir / "readoor" / "BookShelf" / "Classes" / "Macro" / "STSConstantsMacro.h"
if not macro.exists():
raise ProjectPatchError(f"词典配置文件不存在: {macro}")
content = macro.read_text(encoding="utf-8")
version = config.get("VERSION", "")
content, count = re.subn(
r'^(#define\s+SOURCE_VERSION\s+)@"[^"]*"',
rf'\1@"{version}"',
content,
flags=re.MULTILINE,
)
if count == 0:
raise ProjectPatchError("未找到词典 SOURCE_VERSION 配置")
macro.write_text(content, encoding="utf-8")
messages.append("已替换词典版本配置")
def apply_project_config(build_dir: Path, config: dict, definition: dict = None) -> list[str]:
"""写入项目配置,返回适合实时日志展示的变更说明。
definition 为项目定义(见 backend/projects.py),未传或 patcher 为 readoor 时按 Readoor 工程处理。
"""
if definition and definition.get("patcher") != "readoor":
return apply_generic_config(build_dir, config, definition)
messages: list[str] = []
if config.get("SCHEME") == "readoorDict":
_apply_dictionary_config(build_dir, config, messages)
_write_export_options(build_dir, config)
return messages
project = build_dir / "readoor.xcodeproj" / "project.pbxproj"
swift = build_dir / "readoor" / "3.0" / "AppConfig" / "RDAppConfiguration.swift"
entitlements = build_dir / "readoor" / "3.0" / "readoor31.entitlements"
plist = build_dir / "readoor" / "3.0" / "readoor31.plist"
replacements = [
(project, "MARKETING_VERSION =", f"\t\t\t\tMARKETING_VERSION = {config.get('VERSION', '')};"),
(project, "CURRENT_PROJECT_VERSION =", f"\t\t\t\tCURRENT_PROJECT_VERSION = {config.get('BUILD_VERSION', '')};"),
(swift, "let RD_APP_GUID: String =", f"let RD_APP_GUID: String = \"{config.get('APPID', '')}\""),
(swift, "let RD_API_DOMAIN: String", f"let RD_API_DOMAIN: String = \"{config.get('API', '')}\""),
(swift, "let RD_WECHAT_PAY_ID: String", f"let RD_WECHAT_PAY_ID: String = \"{config.get('weixinpay', '')}\""),
(swift, "let RD_SOURCE_VERSION: String", f"let RD_SOURCE_VERSION: String = \"{config.get('VERSION', '')}\""),
(entitlements, "<string>applinks:", f"\t<string>{config.get('ASSOCIATED_DOMAINS', '')}</string>"),
]
if config.get("BUNDLE_ID"):
replacements.append((project, "PRODUCT_BUNDLE_IDENTIFIER =", f"\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = {config['BUNDLE_ID']};"))
if config.get("TEAM_ID"):
replacements.extend([
(project, "DEVELOPMENT_TEAM =", f"\t\t\t\tDEVELOPMENT_TEAM = {config['TEAM_ID']};"),
(project, '"DEVELOPMENT_TEAM[sdk=iphoneos*]" =', f"\t\t\t\t\"DEVELOPMENT_TEAM[sdk=iphoneos*]\" = {config['TEAM_ID']};"),
])
if config.get("PROVISIONING_NAME"):
replacements.extend([
(project, "PROVISIONING_PROFILE_SPECIFIER =", f"\t\t\t\tPROVISIONING_PROFILE_SPECIFIER = {config['PROVISIONING_NAME']};"),
(project, '"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" =', f"\t\t\t\t\"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]\" = {config['PROVISIONING_NAME']};"),
])
# 与 AutoPacking/replace_build_info.py 保持一致:工程内所有构建配置都使用
# Distribution identity。只更新 exportOptions.plist 不足以覆盖 Archive 阶段,
# 否则 pbxproj 中残留的 iPhone/iOS Developer 会让 Xcode 查找开发证书。
replacements.extend([
(project, "CODE_SIGN_IDENTITY =", '\t\t\t\tCODE_SIGN_IDENTITY = "iPhone Distribution";'),
(project, '"CODE_SIGN_IDENTITY[sdk=iphoneos*]" =', '\t\t\t\t"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";'),
])
missing = []
for path, keyword, replacement in replacements:
if _replace_lines(path, keyword, replacement) == 0:
missing.append(keyword)
if missing:
raise ProjectPatchError(f"未找到待替换配置: {', '.join(missing)}")
_update_plist(plist, config)
_apply_theme(build_dir, config.get("THEME", ""), messages)
_write_export_options(build_dir, config)
messages.append("工程、签名、版本和分发配置已更新")
return messages
# —— 通用工程(patcher = generic)——
_TEMPLATE_PATTERN = re.compile(r"\$\{([A-Za-z0-9_.]+)\}")
_BUILD_SETTINGS_PATTERN = re.compile(r"buildSettings = \{\n(.*?)\n\t*\};", re.DOTALL)
_PLAIN_PBX_VALUE = re.compile(r"^[A-Za-z0-9_.$/-]+$")
def _render_template(template: str, config: dict) -> str:
"""替换 ${app.X}、${server.X}、${KEY}:分别取 App 字段、服务器环境字段和打包配置;值为空时报错。"""
def _lookup(match):
name = match.group(1)
if name.startswith("app."):
value = config.get("APP_VARS", {}).get(name[4:], "")
elif name.startswith("server."):
value = config.get("SERVER_VARS", {}).get(name[7:], "")
else:
value = config.get(name, "")
if value is None or str(value) == "":
raise ProjectPatchError(f"替换规则引用的 {name} 未配置")
return str(value)
return _TEMPLATE_PATTERN.sub(_lookup, template)
def _pbx_value(value: str) -> str:
return value if _PLAIN_PBX_VALUE.match(value) else '"' + value.replace('"', '\\"') + '"'
def _patch_pbxproj(path: Path, settings: dict) -> dict:
"""在 App 目标的 buildSettings 中替换设置(含 [sdk=iphoneos*] 变体),返回每个设置的替换次数。
测试目标(含 TEST_HOST / TEST_TARGET_NAME)有自己的 Bundle ID 和签名,跳过。
"""
if not path.exists():
raise ProjectPatchError(f"工程文件不存在: {path.parent.name}/{path.name}")
counts = {key: 0 for key in settings}
def _patch_block(match):
block = match.group(1)
if "TEST_HOST" in block or "TEST_TARGET_NAME" in block:
return match.group(0)
for key, value in settings.items():
pattern = re.compile(
rf'^(\s*)("?{re.escape(key)}(?:\[sdk=iphoneos\*\])?"?) = .*;$', re.MULTILINE
)
block, n = pattern.subn(lambda m: f"{m.group(1)}{m.group(2)} = {_pbx_value(value)};", block)
counts[key] += n
return match.group(0).replace(match.group(1), block, 1)
content = _BUILD_SETTINGS_PATTERN.sub(_patch_block, path.read_text(encoding="utf-8"))
path.write_text(content, encoding="utf-8")
return counts
def _apply_define_rule(path: Path, name: str, value: str) -> int:
"""替换所有未注释的 #define NAME ... 行(#if/#else 各分支中的同名宏都会被替换)。"""
pattern = re.compile(rf"^([ \t]*#define[ \t]+{re.escape(name)})(?:[ \t].*)?$", re.MULTILINE)
content, count = pattern.subn(lambda m: f"{m.group(1)} {value}", path.read_text(encoding="utf-8"))
path.write_text(content, encoding="utf-8")
return count
def _resolve_rule_file(build_dir: Path, file: str) -> Path:
path = (build_dir / file).resolve()
if not file or not path.is_relative_to(build_dir.resolve()):
raise ProjectPatchError(f"替换规则文件路径无效: {file}")
if not path.is_file():
raise ProjectPatchError(f"替换规则文件不存在: {file}")
return path
def apply_generic_config(build_dir: Path, config: dict, definition: dict) -> list[str]:
"""通用工程:替换 pbxproj 的版本号与签名、生成 exportOptions.plist,再执行项目的 patch_rules。
patch_rules 每项:
{"type": "define", "file": "相对路径", "name": "宏名", "value": "模板"}
替换所有未注释的 #define 宏名 行
{"type": "replace_line", "file": "相对路径", "keyword": "关键字", "line": "模板"}
整行替换包含关键字且未注释的行
模板中的 ${app.X} / ${server.X} / ${KEY} 取 App 字段、服务器环境字段、打包配置。
"""
messages: list[str] = []
xcodeproj = (definition.get("xcode") or {}).get("project", "")
if not xcodeproj:
raise ProjectPatchError("项目未配置 Xcode project(.xcodeproj)")
settings = {
"MARKETING_VERSION": config.get("VERSION", ""),
"CURRENT_PROJECT_VERSION": config.get("BUILD_VERSION", ""),
}
if config.get("BUNDLE_ID"):
settings["PRODUCT_BUNDLE_IDENTIFIER"] = config["BUNDLE_ID"]
if not config.get("NO_CERT"):
if config.get("TEAM_ID"):
settings["DEVELOPMENT_TEAM"] = config["TEAM_ID"]
if config.get("PROVISIONING_NAME"):
settings["PROVISIONING_PROFILE_SPECIFIER"] = config["PROVISIONING_NAME"]
settings["CODE_SIGN_STYLE"] = "Manual"
settings["CODE_SIGN_IDENTITY"] = "iPhone Distribution"
counts = _patch_pbxproj(build_dir / xcodeproj / "project.pbxproj", settings)
missing = [key for key in ("MARKETING_VERSION", "CURRENT_PROJECT_VERSION") if counts[key] == 0]
if missing:
raise ProjectPatchError(f"未找到待替换配置: {', '.join(missing)}")
messages.append(
f"工程配置已更新: 版本 {settings['MARKETING_VERSION']} ({settings['CURRENT_PROJECT_VERSION']})"
+ (f",Bundle ID {settings['PRODUCT_BUNDLE_IDENTIFIER']}" if "PRODUCT_BUNDLE_IDENTIFIER" in settings else "")
)
for index, rule in enumerate(definition.get("patch_rules") or [], start=1):
rule_type = rule.get("type")
path = _resolve_rule_file(build_dir, rule.get("file", ""))
if rule_type == "define":
name = rule.get("name", "")
value = _render_template(rule.get("value", ""), config)
if _apply_define_rule(path, name, value) == 0:
raise ProjectPatchError(f"{rule['file']} 中未找到 #define {name}")
messages.append(f"{rule['file']}: #define {name} {value}")
elif rule_type == "replace_line":
keyword = rule.get("keyword", "")
line = _render_template(rule.get("line", ""), config)
if not keyword or _replace_lines(path, keyword, line) == 0:
raise ProjectPatchError(f"{rule['file']} 中未找到包含 {keyword} 的行")
messages.append(f"{rule['file']}: {line.strip()}")
else:
raise ProjectPatchError(f"第 {index} 条替换规则类型无效: {rule_type}")
_write_export_options(build_dir, config)
messages.append("签名和分发配置已更新")
return messages