"""服务端自带的 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": "", } 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": "", } with (build_dir / "exportOptions.plist").open("wb") as f: plistlib.dump(data, f) # 词典环境宏 ← 服务器环境字段(APPID 取 App 的 AppGuid) DICT_SERVER_MACROS = { "SERVERURL": "DICT_SERVERURL", "SERVERHTTPSURL": "DICT_SERVERHTTPSURL", "UCSERVERURL": "DICT_UCSERVERURL", "RECORDSERVERURL": "DICT_RECORDSERVERURL", "LOGSERVERURL": "DICT_LOGSERVERURL", } _DICT_BLOCK_START = re.compile(r"^\s*#\s*(?:el)?if\s+TARGETTYPE\s*==\s*2\s*$") _PP_OPEN = re.compile(r"^\s*#\s*if") _PP_BRANCH = re.compile(r"^\s*#\s*(?:elif|else)\b") _PP_CLOSE = re.compile(r"^\s*#\s*endif\b") def _replace_dict_env_macros(content: str, values: dict) -> str: """只替换 TARGETTYPE == 2 段落中未注释的 #define,其它 TARGETTYPE 的同名宏不动。""" lines = content.splitlines(keepends=True) start = next((i for i, line in enumerate(lines) if _DICT_BLOCK_START.match(line)), None) if start is None: raise ProjectPatchError("STSConstantsMacro.h 中未找到 #elif TARGETTYPE == 2 词典配置段") counts = {name: 0 for name in values} depth = 0 for i in range(start + 1, len(lines)): line = lines[i] if _PP_OPEN.match(line): depth += 1 continue if _PP_CLOSE.match(line) or _PP_BRANCH.match(line): if depth == 0: break if _PP_CLOSE.match(line): depth -= 1 continue for name, value in values.items(): if re.match(rf"^\s*#define\s+{name}\b", line): ending = "\n" if line.endswith("\n") else "" lines[i] = f'#define {name} @"{value}"{ending}' counts[name] += 1 missing = [name for name, count in counts.items() if count == 0] if missing: raise ProjectPatchError(f"词典配置段中未找到未注释的宏: {', '.join(missing)}") return "".join(lines) def _dict_env_values(config: dict) -> dict: """服务器环境中的词典地址;全部未配置返回空(沿用源码),部分配置视为错误。""" server_vars = config.get("SERVER_VARS") or {} values = {macro: str(server_vars.get(key, "") or "").strip() for macro, key in DICT_SERVER_MACROS.items()} if not any(values.values()): return {} missing = [DICT_SERVER_MACROS[macro] for macro, value in values.items() if not value] if missing: raise ProjectPatchError(f"服务器环境 {config.get('SERVER', '')} 的词典地址未配置完整: {', '.join(missing)}") if not str(config.get("APPID", "") or "").strip(): raise ProjectPatchError("词典 App 未配置 AppGuid,无法写入 APPID") return {"APPID": str(config["APPID"]).strip(), **values} 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") env_values = _dict_env_values(config) if env_values: content = _replace_dict_env_macros(content, env_values) messages.append( f"已替换词典环境配置({config.get('SERVER', '')}): APPID {env_values['APPID']}," f"SERVERURL {env_values['SERVERURL']}" ) else: messages.append(f"服务器环境 {config.get('SERVER', '')} 未配置词典地址,沿用源码中的词典环境配置") 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_dictionary_version(build_dir: Path, config: dict, messages: list[str]): """词典包的 IPA 版本号与构建号同样按版本轨道写入工程(与 readoor31 一致,替换工程内全部构建配置)。""" project = build_dir / "readoor.xcodeproj" / "project.pbxproj" version, build_version = config.get("VERSION", ""), config.get("BUILD_VERSION", "") replacements = [ ("MARKETING_VERSION =", f"\t\t\t\tMARKETING_VERSION = {version};"), ("CURRENT_PROJECT_VERSION =", f"\t\t\t\tCURRENT_PROJECT_VERSION = {build_version};"), ] missing = [keyword for keyword, line in replacements if _replace_lines(project, keyword, line) == 0] if missing: raise ProjectPatchError(f"未找到待替换配置: {', '.join(missing)}") messages.append(f"已替换词典包版本: {version} ({build_version})") 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) _apply_dictionary_version(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, "applinks:", f"\t{config.get('ASSOCIATED_DOMAINS', '')}"), ] 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