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>
This commit is contained in:
shenlei
2026-10-22 14:59:30 +09:00
co-authored by Claude Opus 5.5
parent 2bd5c7057f
commit 8f2f23682f
19 changed files with 1535 additions and 137 deletions
+3 -2
View File
@@ -26,12 +26,13 @@ FastAPI + Vue 3 iOS app auto-packaging service. Supports Ad_Hoc and App_Store bu
- `backend/config.py` — loads .env, defines all config constants - `backend/config.py` — loads .env, defines all config constants
- `frontend/src/views/` — BuildView, HistoryView, ConfigView - `frontend/src/views/` — BuildView, HistoryView, ConfigView
- `config.json` — runtime config (apps, schemes, servers, upload, branches, versions) managed via web UI - `config.json` — runtime config (apps, schemes, servers, upload, branches, versions) managed via web UI
- Versions are per-branch: every branch owns a track in `config["versions"]["tracks"]`, named after the branch (master/main keeps the historical name `release`); `config["branch_track"]` maps branch → track name, and each track's `kind` is `release` (build number auto-increments on App_Store) or `feature` (never increments) - Multi-project: `config.json` is `{"projects": {pid: {definition + data}}, "upload": {...}}`; `backend/projects.py` holds project definitions (git, source_dir, xcode, copy_items, patcher `readoor`/`generic`, patch_rules, app_fields/server_fields, obfuscation). Requests pick the project via `X-Project` header (or `?project=`), bound in a ContextVar by middleware; `load_config()` returns the current project's data plus `upload` and `_project`. Legacy flat config auto-migrates to project `readoor` (uses `.env` Git settings). Tasks store `project_id`; build dirs are `build_{pid}_{task_id}`
- Versions are per-branch (within each project): every branch owns a track in `config["versions"]["tracks"]`, named after the branch (master/main keeps the historical name `release`); `config["branch_track"]` maps branch → track name, and each track's `kind` is `release` (build number auto-increments on App_Store) or `feature` (never increments)
- Tags are buildable refs too: `config["tags"]` (names never collide with branches), tracked in `branch_track` like branches (default kind `release`); tasks store the name in `branch` plus `ref_type` (`branch`/`tag`), and tag builds check out `refs/tags/<tag>` detached - Tags are buildable refs too: `config["tags"]` (names never collide with branches), tracked in `branch_track` like branches (default kind `release`); tasks store the name in `branch` plus `ref_type` (`branch`/`tag`), and tag builds check out `refs/tags/<tag>` detached
## Conventions ## Conventions
- All backend routes require JWT auth except `/api/auth/login` and `/api/health` - All backend routes require JWT auth except `/api/auth/login` and `/api/health`
- Admin-only routes: user management (`/api/users/*`) and all of `/api/config/*` except `/api/config/apps*` - Admin-only routes: user management (`/api/users/*`) and all of `/api/config/*` except `/api/config/apps*` (incl. project CRUD `/api/config/projects*`); `GET /api/projects` is the public project list for any logged-in user
- Config stored in `config.json` (apps/schemes/servers), `.env` (infra), SQLite `build_config` table (build settings) - Config stored in `config.json` (apps/schemes/servers), `.env` (infra), SQLite `build_config` table (build settings)
- Chinese UI and documentation throughout - Chinese UI and documentation throughout
+38
View File
@@ -182,8 +182,11 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
> >
> 导入后即可继续在后台增删改。 > 导入后即可继续在后台增删改。
> 旧的单项目 `config.json`(顶层直接是 apps / servers …)启动后自动迁移为项目 `readoor`,原文件备份为 `config.json.bak`。
| 配置项 | 说明 | | 配置项 | 说明 |
|--------|------| |--------|------|
| 项目管理 | 多项目:每个项目独立的 Git 仓库、Xcode 工程、配置替换方式;见下「多项目」 |
| App 管理 | 应用名称、Scheme、服务器环境、upload_key 等 | | App 管理 | 应用名称、Scheme、服务器环境、upload_key 等 |
| Scheme 管理 | 打包 Scheme 配置 | | Scheme 管理 | 打包 Scheme 配置 |
| 服务器环境 | 测试/正式/自定义环境的 API 地址、Universal Link 等 | | 服务器环境 | 测试/正式/自定义环境的 API 地址、Universal Link 等 |
@@ -191,6 +194,41 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
| 版本号 | 服务端统一管理 App_Ver 和 Build_Ver,不修改分支源码;按版本轨道分开管理(见下) | | 版本号 | 服务端统一管理 App_Ver 和 Build_Ver,不修改分支源码;按版本轨道分开管理(见下) |
| 上传配置 | 服务端内置 OSS / WebDAV 分发,生成 IPA、manifest、下载页和二维码 | | 上传配置 | 服务端内置 OSS / WebDAV 分发,生成 IPA、manifest、下载页和二维码 |
### 多项目
`config.json` 顶层为 `{"projects": {"<项目 ID>": {...}}, "upload": {...}}`:每个项目的 Apps、Schemes、服务器环境、分支/Tag、版本轨道互相独立,上传配置所有项目共用。页面顶部切换当前项目,前端每个请求带 `X-Project` 请求头(下载链接等用 `?project=`)。
管理员在「项目管理」维护项目定义:
| 字段 | 说明 |
|------|------|
| `git` | `remote_url` / `username` / `password`(Token);`use_env: true` 时未填项回退到 `.env` 的 `GIT_*`(迁移出的 `readoor` 项目即如此) |
| `source_dir` | 共享源码工作目录,留空为 `<服务目录>/sources/<项目 ID>`。打包时会 `git reset --hard` + `git clean`,**不要指向本地开发的工作副本** |
| `xcode` | `workspace`(有 CocoaPods 时)或 `project`;无 Podfile 时跳过 `pod install` |
| `copy_items` | 拷贝到打包目录的条目,留空拷贝整个仓库 |
| `patcher` | `readoor`:原阅门户专用替换逻辑;`generic`:通用替换(pbxproj 中的版本号、Bundle ID、签名)+ `patch_rules` |
| `app_fields` / `server_fields` | App / 服务器环境的自定义字段 `[{key, label, required}]`,表单中显示 |
| `patch_rules` | `{"type": "define", "file", "name", "value"}` 替换所有未注释的 `#define name` 行;`{"type": "replace_line", "file", "keyword", "line"}` 整行替换。值可用 `${app.字段}`、`${server.字段}`、`${VERSION}` 等 |
| `obfuscation` | 是否支持代码混淆 |
示例(DyAuction:按环境切换 `ISDEV`,`APPID` 按 App 配置):
```jsonc
"dyauction": {
"name": "多云选",
"git": { "remote_url": "https://git.example.com/trn/triduoyunxuan", "username": "...", "password": "<Token>" },
"xcode": { "project": "DyAuction.xcodeproj" },
"patcher": "generic",
"obfuscation": false,
"app_fields": [{ "key": "APPID", "label": "APPID", "required": true }],
"server_fields": [{ "key": "ISDEV", "label": "ISDEV(1=开发环境,0=正式环境)", "required": true }],
"patch_rules": [
{ "type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "ISDEV", "value": "${server.ISDEV}" },
{ "type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "APPID", "value": "@\"${app.APPID}\"" }
]
}
```
### 版本号与版本轨道 ### 版本号与版本轨道
**每个分支各有一条版本轨道(track)**,App_Ver 与构建号完全独立、互不影响。轨道名即分支名(master / main 沿用历史名称 `release`),轨道类型 `kind` 决定构建号行为: **每个分支各有一条版本轨道(track)**,App_Ver 与构建号完全独立、互不影响。轨道名即分支名(master / main 沿用历史名称 `release`),轨道类型 `kind` 决定构建号行为:
+16 -14
View File
@@ -57,27 +57,29 @@ GIT_USERNAME = os.getenv("GIT_USERNAME", "")
GIT_PASSWORD = os.getenv("GIT_PASSWORD", "") GIT_PASSWORD = os.getenv("GIT_PASSWORD", "")
def get_git_remote_url(with_credentials: bool = False) -> str: def inject_git_credentials(url: str, username: str, password: str = "") -> str:
"""获取 Git 远程地址,可选注入用户名密码""" """向 http(s) 形式的 Git 地址注入用户名密码;已带凭证或非 URL 形式时原样返回"""
if not with_credentials or not GIT_REMOTE_URL or not GIT_USERNAME: if not url or not username or "://" not in url:
return GIT_REMOTE_URL return url
if "://" not in GIT_REMOTE_URL:
return GIT_REMOTE_URL
parts = urlsplit(GIT_REMOTE_URL) parts = urlsplit(url)
if "@" in parts.netloc: if "@" in parts.netloc:
return GIT_REMOTE_URL return url
username = quote(GIT_USERNAME, safe="") auth = quote(username, safe="")
if GIT_PASSWORD: if password:
password = quote(GIT_PASSWORD, safe="") auth = f"{auth}:{quote(password, safe='')}"
auth = f"{username}:{password}"
else:
auth = username
netloc = f"{auth}@{parts.netloc}" netloc = f"{auth}@{parts.netloc}"
return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment)) return urlunsplit((parts.scheme, netloc, parts.path, parts.query, parts.fragment))
def get_git_remote_url(with_credentials: bool = False) -> str:
"""获取 .env 中的 Git 远程地址,可选注入用户名密码"""
if not with_credentials:
return GIT_REMOTE_URL
return inject_git_credentials(GIT_REMOTE_URL, GIT_USERNAME, GIT_PASSWORD)
def mask_git_remote_url(url: str) -> str: def mask_git_remote_url(url: str) -> str:
"""对 Git 远程地址中的凭证做脱敏""" """对 Git 远程地址中的凭证做脱敏"""
if not url or "://" not in url: if not url or "://" not in url:
+1
View File
@@ -27,6 +27,7 @@ def _migrate_db():
("tasks", "error_category", "VARCHAR"), ("tasks", "error_category", "VARCHAR"),
("tasks", "superseded_at", "TIMESTAMP"), ("tasks", "superseded_at", "TIMESTAMP"),
("tasks", "dsym_url", "VARCHAR"), ("tasks", "dsym_url", "VARCHAR"),
("tasks", "project_id", "VARCHAR DEFAULT 'readoor'"),
] ]
with engine.connect() as conn: with engine.connect() as conn:
for table, column, col_type in migrations: for table, column, col_type in migrations:
+14 -1
View File
@@ -12,6 +12,7 @@ from .routers import config, apps, tasks, auth, users, operations
from .services.log_streamer import log_streamer from .services.log_streamer import log_streamer
from .config import BACKEND_PORT, CORS_ALLOWED_ORIGINS, TRUSTED_HOSTS, validate_production_security from .config import BACKEND_PORT, CORS_ALLOWED_ORIGINS, TRUSTED_HOSTS, validate_production_security
from .deps import decode_current_user from .deps import decode_current_user
from .projects import PROJECT_HEADER, current_project_id
STATIC_DIR = Path(__file__).parent / "static" STATIC_DIR = Path(__file__).parent / "static"
@@ -37,11 +38,23 @@ if CORS_ALLOWED_ORIGINS:
allow_origins=CORS_ALLOWED_ORIGINS, allow_origins=CORS_ALLOWED_ORIGINS,
allow_credentials=False, allow_credentials=False,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"], allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type"], allow_headers=["Authorization", "Content-Type", PROJECT_HEADER],
) )
app.add_middleware(TrustedHostMiddleware, allowed_hosts=TRUSTED_HOSTS) app.add_middleware(TrustedHostMiddleware, allowed_hosts=TRUSTED_HOSTS)
@app.middleware("http")
async def bind_project(request: Request, call_next):
"""按请求头 X-Project(下载链接等无法带请求头时用 ?project=)确定本次请求操作的项目。"""
project_id = request.headers.get(PROJECT_HEADER) or request.query_params.get("project") or None
token = current_project_id.set(project_id)
try:
return await call_next(request)
finally:
current_project_id.reset(token)
# 路由 # 路由
app.include_router(auth.router) app.include_router(auth.router)
app.include_router(users.router) app.include_router(users.router)
+1
View File
@@ -9,6 +9,7 @@ class Task(Base):
__tablename__ = "tasks" __tablename__ = "tasks"
id = Column(String, primary_key=True) id = Column(String, primary_key=True)
project_id = Column(String, default="readoor") # 所属项目,见 projects.py
app_id = Column(String, nullable=False) app_id = Column(String, nullable=False)
app_name = Column(String, nullable=False) app_name = Column(String, nullable=False)
build_type = Column(String, nullable=False) build_type = Column(String, nullable=False)
+160
View File
@@ -0,0 +1,160 @@
"""多项目定义:每个项目的源码仓库、Xcode 工程、配置替换方式等。
config.json 结构:
{
"projects": {
"<项目 ID>": {
# —— 项目定义(管理员在「项目管理」维护)——
"name": "显示名称",
"git": {"remote_url": "", "username": "", "password": "", "use_env": false},
"source_dir": "", # 共享源码工作目录,留空为 <服务目录>/sources/<项目 ID>
"xcode": {"workspace": "", "project": "X.xcodeproj"},
"copy_items": [], # 拷贝到打包目录的条目,留空拷贝整个仓库
"patcher": "generic", # readoor(阅门户专用)/ generic(通用 + patch_rules)
"patch_rules": [], # generic 的额外替换规则,见 project_patcher
"app_fields": [], # App 的项目自定义字段 [{key, label, required}]
"server_fields": [], # 服务器环境的项目自定义字段
"obfuscation": false, # 是否支持代码混淆
# —— 项目数据(与原单项目时的顶层字段相同)——
"apps": {}, "schemes": {}, "servers": {}, "branches": [], "tags": [],
"versions": {}, "branch_track": {}, "next_app_id_prefix": 1
}
},
"upload": {...} # 上传与钉钉通知,所有项目共用
}
"""
import re
from contextvars import ContextVar
from pathlib import Path
from .config import (
COPY_ITEMS,
GIT_PASSWORD,
GIT_REMOTE_URL,
GIT_SOURCE_BASE,
GIT_SOURCE_DIR,
GIT_USERNAME,
SERVER_ROOT,
inject_git_credentials,
)
# 升级前的单项目配置迁移为这个项目,并沿用 .env 中的 Git 配置。
LEGACY_PROJECT_ID = "readoor"
PATCHER_READOOR = "readoor"
PATCHER_GENERIC = "generic"
PATCHERS = (PATCHER_READOOR, PATCHER_GENERIC)
# 项目定义字段;其余字段(apps、schemes、versions 等)都是项目数据。
DEFINITION_KEYS = (
"name", "git", "source_dir", "xcode", "copy_items", "patcher",
"patch_rules", "app_fields", "server_fields", "obfuscation",
)
# 原单项目(阅门户)的定义,迁移旧配置时写入。
LEGACY_PROJECT_DEFINITION = {
"name": "Readoor",
"git": {"remote_url": "", "username": "", "password": "", "use_env": True},
"source_dir": "",
"xcode": {"workspace": "readoor.xcworkspace", "project": "readoor.xcodeproj"},
"copy_items": list(COPY_ITEMS),
"patcher": PATCHER_READOOR,
"patch_rules": [],
"app_fields": [],
"server_fields": [],
"obfuscation": True,
}
# 当前请求操作的项目,由 main.py 的中间件按请求头 X-Project 设置;
# load_config() 未显式指定项目时使用它,未设置则取第一个项目。
PROJECT_HEADER = "X-Project"
current_project_id: ContextVar = ContextVar("current_project_id", default=None)
_PROJECT_ID_PATTERN = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
def is_valid_project_id(project_id: str) -> bool:
"""项目 ID 会用于目录名和请求头,只允许小写字母开头的短标识。"""
return bool(_PROJECT_ID_PATTERN.fullmatch(project_id or ""))
def default_definition(project_id: str) -> dict:
"""项目定义缺省值:旧项目沿用原有行为,新项目为通用配置。"""
if project_id == LEGACY_PROJECT_ID:
return LEGACY_PROJECT_DEFINITION
return {
"name": project_id,
"git": {"remote_url": "", "username": "", "password": "", "use_env": False},
"source_dir": "",
"xcode": {"workspace": "", "project": ""},
"copy_items": [],
"patcher": PATCHER_GENERIC,
"patch_rules": [],
"app_fields": [],
"server_fields": [],
"obfuscation": False,
}
def get_definition(project_id: str, project: dict) -> dict:
"""取项目定义,缺失字段用缺省值补齐(只读,不写回配置)。"""
defaults = default_definition(project_id)
definition = {key: project.get(key, defaults[key]) for key in DEFINITION_KEYS}
definition["git"] = {**defaults["git"], **(definition.get("git") or {})}
definition["xcode"] = {**defaults["xcode"], **(definition.get("xcode") or {})}
if definition["patcher"] not in PATCHERS:
definition["patcher"] = PATCHER_GENERIC
return definition
def public_definition(project_id: str, project: dict) -> dict:
"""打包页和配置页渲染所需的项目信息,不含 Git 凭据。"""
definition = get_definition(project_id, project)
return {
"id": project_id,
"name": definition["name"],
"patcher": definition["patcher"],
"obfuscation": bool(definition["obfuscation"]),
"app_fields": definition["app_fields"],
"server_fields": definition["server_fields"],
}
class ProjectSource:
"""项目源码的获取方式。"""
def __init__(self, remote_url: str, remote_url_with_credentials: str,
shared_dir: Path, manual_base: Path = None):
self.remote_url = remote_url
self.remote_url_with_credentials = remote_url_with_credentials
# 配置远程仓库时,所有分支共用的源码工作目录
self.shared_dir = shared_dir
# 未配置远程仓库时,按 <manual_base>/<branch> 读取人工维护的分支目录(仅旧项目支持)
self.manual_base = manual_base
def get_project_source(project_id: str, project: dict) -> ProjectSource:
definition = get_definition(project_id, project)
git = definition["git"]
use_env = bool(git.get("use_env"))
remote_url = (git.get("remote_url") or "").strip() or (GIT_REMOTE_URL if use_env else "")
username = git.get("username") or (GIT_USERNAME if use_env else "")
password = git.get("password") or (GIT_PASSWORD if use_env else "")
source_dir = (definition.get("source_dir") or "").strip()
if source_dir:
shared_dir = Path(source_dir).expanduser()
if not shared_dir.is_absolute():
shared_dir = SERVER_ROOT / shared_dir
elif use_env:
shared_dir = GIT_SOURCE_DIR
else:
shared_dir = SERVER_ROOT / "sources" / project_id
return ProjectSource(
remote_url=remote_url,
remote_url_with_credentials=inject_git_credentials(remote_url, username, password),
shared_dir=shared_dir,
manual_base=GIT_SOURCE_BASE if use_env else None,
)
+18 -5
View File
@@ -1,7 +1,9 @@
"""打包选择 API""" """打包选择 API"""
from fastapi import APIRouter from fastapi import APIRouter, Depends
from .config import get_tags, load_config from ..deps import get_current_user
from ..projects import PATCHER_READOOR, get_definition, public_definition
from .config import get_tags, load_config, load_projects
router = APIRouter(prefix="/api", tags=["apps"]) router = APIRouter(prefix="/api", tags=["apps"])
@@ -15,11 +17,22 @@ _APP_SCHEME_RULES = {
_DEFAULT_SCHEME_NAMES = ("readoor31", "readoor31OtherPay") _DEFAULT_SCHEME_NAMES = ("readoor31", "readoor31OtherPay")
def get_allowed_scheme_names(app: dict) -> tuple[str, ...]: def get_allowed_scheme_names(app: dict, config: dict) -> tuple[str, ...]:
"""返回 App 可使用的 Scheme 名称。""" """返回 App 可使用的 Scheme 名称;空元组表示不限制。
按 App 名称限定 Scheme 是 Readoor 项目的规则,其它项目不限制。
"""
if get_definition(config["_project"], config)["patcher"] != PATCHER_READOOR:
return ()
return _APP_SCHEME_RULES.get(app.get("name", ""), _DEFAULT_SCHEME_NAMES) return _APP_SCHEME_RULES.get(app.get("name", ""), _DEFAULT_SCHEME_NAMES)
@router.get("/projects", dependencies=[Depends(get_current_user)])
async def get_projects():
"""获取项目列表(供切换项目,不含 Git 凭据)"""
return [public_definition(project_id, project) for project_id, project in load_projects().items()]
@router.get("/apps") @router.get("/apps")
async def get_apps_for_build(): async def get_apps_for_build():
"""获取 apps 列表(供打包选择)""" """获取 apps 列表(供打包选择)"""
@@ -27,7 +40,7 @@ async def get_apps_for_build():
apps = {} apps = {}
for app_id, app in config.get("apps", {}).items(): for app_id, app in config.get("apps", {}).items():
app_data = app.copy() app_data = app.copy()
app_data["allowed_scheme_names"] = list(get_allowed_scheme_names(app)) app_data["allowed_scheme_names"] = list(get_allowed_scheme_names(app, config))
apps[app_id] = app_data apps[app_id] = app_data
return apps return apps
+291 -30
View File
@@ -1,5 +1,6 @@
"""配置管理 API""" """配置管理 API"""
import asyncio import asyncio
import copy
import json import json
import os import os
import re import re
@@ -23,6 +24,17 @@ from ..config import (
SKINS_DIR, SKINS_DIR,
) )
from ..deps import get_current_user, require_admin from ..deps import get_current_user, require_admin
from ..projects import (
DEFINITION_KEYS,
LEGACY_PROJECT_DEFINITION,
LEGACY_PROJECT_ID,
PATCHER_READOOR,
PATCHERS,
current_project_id,
default_definition,
get_definition,
is_valid_project_id,
)
def _require_config_permission(request: Request, user: dict = Depends(get_current_user)) -> dict: def _require_config_permission(request: Request, user: dict = Depends(get_current_user)) -> dict:
@@ -533,27 +545,86 @@ def _migrate_old_themes(config: dict) -> bool:
return True return True
def load_config() -> dict: def _default_project_data(project_id: str) -> dict:
"""读取 config.json""" """新项目的初始数据;旧项目沿用原单项目时的默认服务器环境。"""
legacy = project_id == LEGACY_PROJECT_ID
return {
"apps": {}, "schemes": {},
"servers": dict(DEFAULT_SERVERS) if legacy else {},
"next_app_id_prefix": 5 if legacy else 1,
"branches": ["main"],
}
def _migrate_root(raw: dict) -> tuple:
"""把升级前的单项目配置(顶层即项目数据)包装为 projects.readoor,返回 (root, 是否变更)。"""
if isinstance(raw.get("projects"), dict) and raw["projects"]:
return raw, False
project = {key: value for key, value in raw.items() if key not in ("projects", "upload")}
if not project:
project = _default_project_data(LEGACY_PROJECT_ID)
project = {**copy.deepcopy(LEGACY_PROJECT_DEFINITION), **project}
root = {"projects": {LEGACY_PROJECT_ID: project}}
if "upload" in raw:
root["upload"] = raw["upload"]
return root, True
def _read_root() -> dict:
"""读取 config.json 根对象(含所有项目),必要时迁移旧结构。"""
if not CONFIG_JSON_PATH.exists(): if not CONFIG_JSON_PATH.exists():
# 首次部署:优先从项目根目录下的 config.json 导入 # 首次部署:优先从项目根目录下的 config.json 导入
if BOOTSTRAP_CONFIG_PATH.exists(): if BOOTSTRAP_CONFIG_PATH.exists():
CONFIG_JSON_PATH.parent.mkdir(parents=True, exist_ok=True) CONFIG_JSON_PATH.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(BOOTSTRAP_CONFIG_PATH, CONFIG_JSON_PATH) shutil.copy2(BOOTSTRAP_CONFIG_PATH, CONFIG_JSON_PATH)
else: else:
return { root, _ = _migrate_root({})
"apps": {}, "schemes": {}, "servers": DEFAULT_SERVERS, root["upload"] = DEFAULT_UPLOAD
"next_app_id_prefix": 5, "branches": ["main"], "upload": DEFAULT_UPLOAD, return root
}
with open(CONFIG_JSON_PATH, "r", encoding="utf-8") as f: with open(CONFIG_JSON_PATH, "r", encoding="utf-8") as f:
config = json.load(f) root, migrated = _migrate_root(json.load(f))
if "upload" not in root:
root["upload"] = DEFAULT_UPLOAD
if migrated:
_write_root(root)
return root
def _write_root(root: dict):
"""保存 config.json(自动备份)"""
if CONFIG_JSON_PATH.exists():
backup_path = CONFIG_JSON_PATH.with_suffix(".json.bak")
shutil.copy2(CONFIG_JSON_PATH, backup_path)
CONFIG_JSON_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(CONFIG_JSON_PATH, "w", encoding="utf-8") as f:
json.dump(root, f, indent=2, ensure_ascii=False)
def resolve_project_id(root: dict, project_id: str = None) -> str:
"""确定要操作的项目:显式指定 > 请求头 X-Project > 第一个项目。"""
projects = root["projects"]
project_id = project_id or current_project_id.get()
if not project_id:
return next(iter(projects))
if project_id not in projects:
raise HTTPException(status_code=400, detail=f"项目不存在: {project_id}")
return project_id
def load_config(project_id: str = None) -> dict:
"""读取某个项目的配置视图。
返回值与单项目时的 config.json 结构相同(apps/schemes/servers/... + upload),
并带 "_project" 标记,save_config() 据此写回对应项目。
"""
root = _read_root()
project_id = resolve_project_id(root, project_id)
config = {**root["projects"][project_id], "upload": root["upload"], "_project": project_id}
# 确保必要字段存在 # 确保必要字段存在
if "servers" not in config: if "servers" not in config:
config["servers"] = DEFAULT_SERVERS config["servers"] = _default_project_data(project_id)["servers"]
if "branches" not in config: if "branches" not in config:
config["branches"] = ["main"] config["branches"] = ["main"]
if "upload" not in config:
config["upload"] = DEFAULT_UPLOAD
versions_changed = _ensure_versions(config) versions_changed = _ensure_versions(config)
# 自动补齐旧配置的环境前缀、特殊 App 覆盖和 upload_key。 # 自动补齐旧配置的环境前缀、特殊 App 覆盖和 upload_key。
prefixes_changed = _ensure_server_id_prefixes(config) prefixes_changed = _ensure_server_id_prefixes(config)
@@ -568,12 +639,25 @@ def load_config() -> dict:
def save_config(config: dict): def save_config(config: dict):
"""保存 config.json(自动备份)""" """保存 load_config() 返回的项目配置视图(其中的 upload 为所有项目共用)。"""
if CONFIG_JSON_PATH.exists(): root = _read_root()
backup_path = CONFIG_JSON_PATH.with_suffix(".json.bak") project_id = config.get("_project") or resolve_project_id(root)
shutil.copy2(CONFIG_JSON_PATH, backup_path) root["projects"][project_id] = {
with open(CONFIG_JSON_PATH, "w", encoding="utf-8") as f: key: value for key, value in config.items() if key not in ("upload", "_project")
json.dump(config, f, indent=2, ensure_ascii=False) }
if "upload" in config:
root["upload"] = config["upload"]
_write_root(root)
def load_upload_config() -> dict:
"""读取所有项目共用的上传配置"""
return _read_root()["upload"]
def load_projects() -> dict:
"""读取所有项目(项目 ID → 项目配置,不含共用的 upload)。"""
return _read_root()["projects"]
def get_build_config_value(db: Session, key: str, default=None) -> str: def get_build_config_value(db: Session, key: str, default=None) -> str:
@@ -584,14 +668,15 @@ def get_build_config_value(db: Session, key: str, default=None) -> str:
@router.get("") @router.get("")
async def get_full_config(): async def get_full_config():
"""获取完整 config.json""" """获取当前项目的完整配置"""
return load_config() return load_config()
@router.put("") @router.put("")
async def update_full_config(config: dict): async def update_full_config(config: dict):
"""更新整个 config.json""" """更新当前项目的完整配置(upload 为所有项目共用)"""
async with _config_lock: async with _config_lock:
config["_project"] = load_config()["_project"]
save_config(config) save_config(config)
return {"message": "配置已更新"} return {"message": "配置已更新"}
@@ -603,6 +688,25 @@ async def get_apps():
return config.get("apps", {}) return config.get("apps", {})
def _validate_custom_fields(config: dict, fields_key: str, data: dict):
"""校验项目自定义字段(app_fields / server_fields)中的必填项。"""
definition = get_definition(config["_project"], config)
for field in definition[fields_key]:
if field.get("required") and not str(data.get(field["key"], "")).strip():
raise HTTPException(status_code=400, detail=f"{field.get('label') or field['key']} 不能为空")
def _server_entry(config: dict, server_data: dict, app_id_prefix) -> dict:
"""按项目保留服务器环境字段:Readoor 工程使用 api/assDom/universalLink,另加项目自定义字段。"""
definition = get_definition(config["_project"], config)
keys = [field["key"] for field in definition["server_fields"]]
if definition["patcher"] == PATCHER_READOOR:
keys = ["api", "assDom", "universalLink"] + keys
entry = {key: str(server_data.get(key, "")).strip() for key in keys}
entry["app_id_prefix"] = app_id_prefix
return entry
@router.post("/apps") @router.post("/apps")
async def create_app(app: dict): async def create_app(app: dict):
"""新增 app""" """新增 app"""
@@ -611,6 +715,8 @@ async def create_app(app: dict):
config = load_config() config = load_config()
apps = config.get("apps", {}) apps = config.get("apps", {})
_validate_custom_fields(config, "app_fields", app)
# 按服务环境自动生成三位 ID(例如测试环境 1xx、正式环境 2xx)。 # 按服务环境自动生成三位 ID(例如测试环境 1xx、正式环境 2xx)。
_apply_special_app_prefix_override(app) _apply_special_app_prefix_override(app)
_normalize_tencent_app_id(app) _normalize_tencent_app_id(app)
@@ -636,6 +742,7 @@ async def update_app(app_id: str, app: dict):
if app_id not in apps: if app_id not in apps:
raise HTTPException(status_code=404, detail="App 不存在") raise HTTPException(status_code=404, detail="App 不存在")
_validate_custom_fields(config, "app_fields", app)
_normalize_tencent_app_id(app) _normalize_tencent_app_id(app)
apps[app_id] = app apps[app_id] = app
config["apps"] = apps config["apps"] = apps
@@ -1111,13 +1218,9 @@ async def create_server(server_data: dict):
if name in servers: if name in servers:
raise HTTPException(status_code=400, detail="环境名称已存在") raise HTTPException(status_code=400, detail="环境名称已存在")
_validate_custom_fields(config, "server_fields", server_data)
prefix = config.get("next_app_id_prefix", 1) prefix = config.get("next_app_id_prefix", 1)
servers[name] = { servers[name] = _server_entry(config, server_data, prefix)
"api": server_data.get("api", ""),
"assDom": server_data.get("assDom", ""),
"universalLink": server_data.get("universalLink", ""),
"app_id_prefix": prefix,
}
config["servers"] = servers config["servers"] = servers
config["next_app_id_prefix"] = prefix + 1 config["next_app_id_prefix"] = prefix + 1
save_config(config) save_config(config)
@@ -1143,12 +1246,8 @@ async def update_server(server_name: str, server_data: dict):
else: else:
new_name = server_name new_name = server_name
servers[new_name] = { _validate_custom_fields(config, "server_fields", server_data)
"api": server_data.get("api", ""), servers[new_name] = _server_entry(config, server_data, servers[new_name].get("app_id_prefix"))
"assDom": server_data.get("assDom", ""),
"universalLink": server_data.get("universalLink", ""),
"app_id_prefix": servers[new_name].get("app_id_prefix"),
}
config["servers"] = servers config["servers"] = servers
save_config(config) save_config(config)
return {"message": "服务器环境已更新"} return {"message": "服务器环境已更新"}
@@ -1174,3 +1273,165 @@ async def delete_server(server_name: str):
config["servers"] = servers config["servers"] = servers
save_config(config) save_config(config)
return {"message": "服务器环境已删除"} return {"message": "服务器环境已删除"}
# ---- 项目管理 ----
# App / 服务器环境中已有固定含义的字段,项目自定义字段不能占用
_RESERVED_FIELD_KEYS = {
"app_fields": {"name", "server", "certificates", "upload_key", "skins"},
"server_fields": {"name", "app_id_prefix"},
}
_FIELD_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
_RULE_TYPES = {"define": ("file", "name", "value"), "replace_line": ("file", "keyword", "line")}
def _mask_definition(project_id: str, project: dict) -> dict:
"""项目定义(不返回 Git 密码,只标记是否已设置)"""
definition = get_definition(project_id, project)
git = dict(definition["git"])
git["password_set"] = bool(git.pop("password", ""))
return {"id": project_id, **definition, "git": git}
def _clean_fields(fields, fields_key: str) -> list:
if not isinstance(fields, list):
raise HTTPException(status_code=400, detail=f"{fields_key} 必须是数组")
cleaned, seen = [], set()
for field in fields:
key = str((field or {}).get("key", "")).strip()
if not _FIELD_KEY_PATTERN.fullmatch(key):
raise HTTPException(status_code=400, detail=f"字段名无效: {key or '(空)'}(字母、数字、下划线)")
if key in _RESERVED_FIELD_KEYS[fields_key] or key in seen:
raise HTTPException(status_code=400, detail=f"字段名重复或为保留字段: {key}")
seen.add(key)
cleaned.append({
"key": key,
"label": str(field.get("label", "")).strip() or key,
"required": bool(field.get("required")),
})
return cleaned
def _clean_patch_rules(rules) -> list:
if not isinstance(rules, list):
raise HTTPException(status_code=400, detail="patch_rules 必须是数组")
cleaned = []
for index, rule in enumerate(rules, start=1):
rule_type = (rule or {}).get("type")
if rule_type not in _RULE_TYPES:
raise HTTPException(status_code=400, detail=f"第 {index} 条替换规则类型无效(define / replace_line)")
item = {"type": rule_type}
for key in _RULE_TYPES[rule_type]:
value = str(rule.get(key, ""))
if key != "value" and key != "line" and not value.strip():
raise HTTPException(status_code=400, detail=f"第 {index} 条替换规则缺少 {key}")
item[key] = value.strip() if key in ("file", "name", "keyword") else value
file = item["file"]
if file.startswith("/") or ".." in Path(file).parts:
raise HTTPException(status_code=400, detail=f"第 {index} 条替换规则文件需为仓库内相对路径")
cleaned.append(item)
return cleaned
def _apply_definition(project: dict, data: dict, existing_git: dict = None):
"""把请求中的项目定义字段校验后写入 project(只更新请求中出现的字段)。"""
if "name" in data:
name = str(data["name"]).strip()
if not name:
raise HTTPException(status_code=400, detail="项目名称不能为空")
project["name"] = name
if "git" in data:
git = data["git"] or {}
password = str(git.get("password", ""))
if not password and existing_git:
password = existing_git.get("password", "")
project["git"] = {
"remote_url": str(git.get("remote_url", "")).strip(),
"username": str(git.get("username", "")).strip(),
"password": password,
"use_env": bool(git.get("use_env")),
}
if "source_dir" in data:
project["source_dir"] = str(data["source_dir"] or "").strip()
if "xcode" in data:
xcode = data["xcode"] or {}
project["xcode"] = {
"workspace": str(xcode.get("workspace", "")).strip(),
"project": str(xcode.get("project", "")).strip(),
}
if "copy_items" in data:
items = data["copy_items"]
if not isinstance(items, list):
raise HTTPException(status_code=400, detail="copy_items 必须是数组")
project["copy_items"] = [str(item).strip() for item in items if str(item).strip()]
if "patcher" in data:
if data["patcher"] not in PATCHERS:
raise HTTPException(status_code=400, detail=f"配置替换方式无效: {data['patcher']}")
project["patcher"] = data["patcher"]
if "patch_rules" in data:
project["patch_rules"] = _clean_patch_rules(data["patch_rules"])
for fields_key in ("app_fields", "server_fields"):
if fields_key in data:
project[fields_key] = _clean_fields(data[fields_key], fields_key)
if "obfuscation" in data:
project["obfuscation"] = bool(data["obfuscation"])
xcode = project.get("xcode") or {}
if not xcode.get("workspace") and not xcode.get("project"):
raise HTTPException(status_code=400, detail="Xcode workspace 和 project 至少填写一个")
if project.get("patcher") != PATCHER_READOOR and not xcode.get("project"):
raise HTTPException(status_code=400, detail="通用配置替换需要填写 Xcode project(.xcodeproj)")
@router.get("/projects")
async def get_project_definitions():
"""获取所有项目定义"""
return [_mask_definition(project_id, project) for project_id, project in load_projects().items()]
@router.post("/projects")
async def create_project(data: dict):
"""新增项目"""
project_id = str(data.get("id", "")).strip()
if not is_valid_project_id(project_id):
raise HTTPException(status_code=400, detail="项目 ID 需以小写字母开头,仅含小写字母、数字、-、_,最长 32 位")
async with _config_lock:
root = _read_root()
if project_id in root["projects"]:
raise HTTPException(status_code=400, detail="项目 ID 已存在")
project = {**copy.deepcopy(default_definition(project_id)), **_default_project_data(project_id)}
_apply_definition(project, data)
root["projects"][project_id] = project
_write_root(root)
return {"id": project_id, "message": "项目已创建"}
@router.put("/projects/{project_id}")
async def update_project(project_id: str, data: dict):
"""更新项目定义(Git 密码留空则保留原密码)"""
async with _config_lock:
root = _read_root()
if project_id not in root["projects"]:
raise HTTPException(status_code=404, detail="项目不存在")
project = root["projects"][project_id]
current = get_definition(project_id, project)
for key in DEFINITION_KEYS:
project.setdefault(key, copy.deepcopy(current[key]))
_apply_definition(project, {key: data[key] for key in DEFINITION_KEYS if key in data}, current["git"])
_write_root(root)
return {"message": "项目已更新"}
@router.delete("/projects/{project_id}")
async def delete_project(project_id: str):
"""删除项目(至少保留一个项目)"""
async with _config_lock:
root = _read_root()
if project_id not in root["projects"]:
raise HTTPException(status_code=404, detail="项目不存在")
if len(root["projects"]) == 1:
raise HTTPException(status_code=400, detail="至少需要保留一个项目")
del root["projects"][project_id]
_write_root(root)
return {"message": "项目已删除"}
+18 -11
View File
@@ -48,13 +48,18 @@ async def create_task(task: TaskCreate, request: Request, user: dict = Depends(g
raise HTTPException(status_code=400, detail=f"该 App 未配置 {task.build_type} 证书") raise HTTPException(status_code=400, detail=f"该 App 未配置 {task.build_type} 证书")
from .apps import get_allowed_scheme_names from .apps import get_allowed_scheme_names
allowed_scheme_names = get_allowed_scheme_names(app) allowed_scheme_names = get_allowed_scheme_names(app, config)
if allowed_scheme_names and scheme_name not in allowed_scheme_names: if allowed_scheme_names and scheme_name not in allowed_scheme_names:
raise HTTPException( raise HTTPException(
status_code=400, status_code=400,
detail=f"该 App 只能使用 Scheme: {', '.join(allowed_scheme_names)}", detail=f"该 App 只能使用 Scheme: {', '.join(allowed_scheme_names)}",
) )
project_id = config["_project"]
from ..projects import get_definition
if task.obfuscation and not get_definition(project_id, config)["obfuscation"]:
raise HTTPException(status_code=400, detail="该项目不支持代码混淆")
# 分支与 Tag 不允许重名,按名字即可确定要检出的引用类型 # 分支与 Tag 不允许重名,按名字即可确定要检出的引用类型
from .config import get_ref_type from .config import get_ref_type
ref_type = get_ref_type(config, task.branch) ref_type = get_ref_type(config, task.branch)
@@ -62,6 +67,7 @@ async def create_task(task: TaskCreate, request: Request, user: dict = Depends(g
task_id = str(uuid.uuid4()) task_id = str(uuid.uuid4())
db_task = Task( db_task = Task(
id=task_id, id=task_id,
project_id=project_id,
app_id=task.app_id, app_id=task.app_id,
app_name=app.get("name", ""), app_name=app.get("name", ""),
build_type=task.build_type, build_type=task.build_type,
@@ -119,8 +125,9 @@ async def list_tasks(
user: dict = Depends(get_current_user), user: dict = Depends(get_current_user),
db: Session = Depends(get_db) db: Session = Depends(get_db)
): ):
"""获取任务列表""" """获取当前项目的任务列表"""
query = db.query(Task) from .config import load_config
query = db.query(Task).filter(Task.project_id == load_config()["_project"])
if include_superseded: if include_superseded:
if not user.get("is_admin"): if not user.get("is_admin"):
raise HTTPException(status_code=403, detail="需要管理员权限") raise HTTPException(status_code=403, detail="需要管理员权限")
@@ -200,11 +207,11 @@ async def delete_task(task_id: str, request: Request, user: dict = Depends(get_c
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端文件") raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端文件")
try: try:
build_config = json.loads(task.config_json) build_config = json.loads(task.config_json)
from .config import load_config from .config import load_upload_config
from ..services.distribution import DistributionError, delete_published_artifacts from ..services.distribution import DistributionError, delete_published_artifacts
delete_published_artifacts( delete_published_artifacts(
build_config, build_config,
load_config().get("upload", {}), load_upload_config(),
task.oss_url, task.oss_url,
) )
except (json.JSONDecodeError, DistributionError) as exc: except (json.JSONDecodeError, DistributionError) as exc:
@@ -223,9 +230,9 @@ async def delete_task(task_id: str, request: Request, user: dict = Depends(get_c
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端 dSYM 文件") raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端 dSYM 文件")
try: try:
build_config = json.loads(task.config_json) build_config = json.loads(task.config_json)
from .config import load_config from .config import load_upload_config
from ..services.distribution import DistributionError, delete_published_dsym from ..services.distribution import DistributionError, delete_published_dsym
delete_published_dsym(build_config, load_config().get("upload", {}), task.dsym_url) delete_published_dsym(build_config, load_upload_config(), task.dsym_url)
except (json.JSONDecodeError, DistributionError) as exc: except (json.JSONDecodeError, DistributionError) as exc:
raise HTTPException(status_code=502, detail=f"远端 dSYM 删除失败,记录未删除:{exc}") from exc raise HTTPException(status_code=502, detail=f"远端 dSYM 删除失败,记录未删除:{exc}") from exc
@@ -295,13 +302,13 @@ async def get_download_link(task_id: str, request: Request, user: dict = Depends
if not task.oss_url: if not task.oss_url:
raise HTTPException(status_code=404, detail="下载文件不存在") raise HTTPException(status_code=404, detail="下载文件不存在")
try: try:
from .config import load_config from .config import load_upload_config
from ..config import DOWNLOAD_URL_EXPIRE_SECONDS from ..config import DOWNLOAD_URL_EXPIRE_SECONDS
from ..services.distribution import DistributionError, get_published_download_url from ..services.distribution import DistributionError, get_published_download_url
task_config = json.loads(task.config_json or "{}") task_config = json.loads(task.config_json or "{}")
download_url = get_published_download_url( download_url = get_published_download_url(
task_config, task_config,
load_config().get("upload", {}), load_upload_config(),
task.oss_url, task.oss_url,
) )
except (json.JSONDecodeError, DistributionError) as exc: except (json.JSONDecodeError, DistributionError) as exc:
@@ -353,11 +360,11 @@ async def download_dsym(task_id: str, request: Request, user: dict = Depends(get
# dSYM 需要携带认证信息才能访问该接口,浏览器无法直接跳转到本接口的 # dSYM 需要携带认证信息才能访问该接口,浏览器无法直接跳转到本接口的
# 302 目标,因此改为返回 JSON 让前端自行发起下载。 # 302 目标,因此改为返回 JSON 让前端自行发起下载。
try: try:
from .config import load_config from .config import load_upload_config
from ..services.distribution import DistributionError, get_published_dsym_url from ..services.distribution import DistributionError, get_published_dsym_url
download_url = get_published_dsym_url( download_url = get_published_dsym_url(
json.loads(task.config_json or "{}"), json.loads(task.config_json or "{}"),
load_config().get("upload", {}), load_upload_config(),
task.dsym_url, task.dsym_url,
) )
except (json.JSONDecodeError, DistributionError) as exc: except (json.JSONDecodeError, DistributionError) as exc:
+1
View File
@@ -15,6 +15,7 @@ class TaskCreate(BaseModel):
class TaskResponse(BaseModel): class TaskResponse(BaseModel):
id: str id: str
project_id: Optional[str] = "readoor"
app_id: str app_id: str
app_name: str app_name: str
build_type: str build_type: str
+120 -37
View File
@@ -3,6 +3,7 @@ import asyncio
import json import json
import os import os
import plistlib import plistlib
import re
import shutil import shutil
import subprocess import subprocess
import zipfile import zipfile
@@ -12,16 +13,14 @@ from typing import List
from ..config import ( from ..config import (
BUILD_BASE_DIR, BUILD_BASE_DIR,
COPY_ITEMS,
DEFAULT_BUILD_DIR_RETENTION_HOURS, DEFAULT_BUILD_DIR_RETENTION_HOURS,
BUILD_TIMEOUT_HOURS, BUILD_TIMEOUT_HOURS,
SKINS_DIR, SKINS_DIR,
AUTOMATION_DIR, AUTOMATION_DIR,
get_source_dir,
get_shared_source_dir,
get_git_remote_url, get_git_remote_url,
mask_git_remote_url, mask_git_remote_url,
) )
from ..projects import LEGACY_PROJECT_ID, get_definition, get_project_source
from .log_streamer import log_streamer from .log_streamer import log_streamer
from .distribution import DistributionError, publish_dsym, publish_ipa from .distribution import DistributionError, publish_dsym, publish_ipa
from .notification import NotificationError, send_dingtalk_notification from .notification import NotificationError, send_dingtalk_notification
@@ -37,9 +36,36 @@ class BuildError(Exception):
self.detail = detail self.detail = detail
# 共享源码目录只能同时被一个任务切换、清理和复制。 # 共享源码目录只能同时被一个任务切换、清理和复制,每个源码目录一把锁,
# 后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。 # 不同项目的源码准备互不阻塞。后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。
source_prepare_lock = asyncio.Lock() _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: def _patch_afnetworking_private_headers(build_dir: Path) -> int:
@@ -217,7 +243,7 @@ def _cleanup_old_builds(db):
_cleanup_superseded_tasks(db) _cleanup_superseded_tasks(db)
return return
for d in base.iterdir(): for d in base.iterdir():
if d.is_dir() and d.name.startswith("build_readoor_"): if d.is_dir() and _BUILD_DIR_PATTERN.match(d.name):
try: try:
if d.stat().st_mtime < cutoff: if d.stat().st_mtime < cutoff:
shutil.rmtree(d) shutil.rmtree(d)
@@ -291,16 +317,21 @@ def _db_update(db, task, **fields):
db.commit() db.commit()
async def update_source(task_id: str, source_dir: Path, branch: str, ref_type: str = "branch"): async def update_source(task_id: str, source_dir: Path, branch: str, ref_type: str = "branch",
"""将共享源码工作目录强制同步到指定远程分支或 Tag(ref_type="tag" 时 branch 为 Tag 名)。""" remote_url: str = None):
remote_url = get_git_remote_url(with_credentials=True) """将共享源码工作目录强制同步到指定远程分支或 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) remote_url_masked = mask_git_remote_url(remote_url)
git_env = _git_env() git_env = _git_env()
cloned = not source_dir.exists() cloned = not source_dir.exists()
if cloned: if cloned:
if not remote_url: if not remote_url:
raise Exception(f"源码目录不存在且未配置 GIT_REMOTE_URL: {source_dir}") raise Exception(f"源码目录不存在且未配置 Git 仓库地址: {source_dir}")
source_dir.parent.mkdir(parents=True, exist_ok=True) source_dir.parent.mkdir(parents=True, exist_ok=True)
await log_streamer.emit(task_id, f"初始化共享源码目录: {remote_url_masked}") await log_streamer.emit(task_id, f"初始化共享源码目录: {remote_url_masked}")
process = await asyncio.create_subprocess_exec( process = await asyncio.create_subprocess_exec(
@@ -381,25 +412,34 @@ async def get_source_commit(source_dir: Path) -> str:
async def prepare_source_snapshot(task_id: str, task) -> tuple[Path, str]: async def prepare_source_snapshot(task_id: str, task) -> tuple[Path, str]:
"""准备任务独立源码快照;远程仓库模式下此过程全局串行。""" """准备任务独立源码快照;远程仓库模式下同一源码目录的准备过程串行。"""
if not get_git_remote_url(): project_id = _task_project_id(task)
source_dir = get_source_dir(task.branch) 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(): if not source_dir.exists():
raise Exception( raise Exception(
f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支(或 Tag)代码,或配置 GIT_REMOTE_URL" f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支(或 Tag)代码,或配置 GIT_REMOTE_URL"
) )
await log_streamer.emit(task_id, f"使用分支源码: {source_dir}") await log_streamer.emit(task_id, f"使用分支源码: {source_dir}")
return await copy_source_code(task_id, task, source_dir), "" return await copy_source_code(task_id, task, source_dir, definition), ""
source_dir = get_shared_source_dir() source_dir = source.shared_dir
await log_streamer.emit(task_id, "等待共享源码准备队列...") await log_streamer.emit(task_id, "等待共享源码准备队列...")
async with source_prepare_lock: async with _source_prepare_lock(source_dir):
await log_streamer.emit(task_id, "开始准备共享源码快照") await log_streamer.emit(task_id, "开始准备共享源码快照")
ref_type = "tag" if task.ref_type == "tag" else "branch" ref_type = "tag" if task.ref_type == "tag" else "branch"
await update_source(task_id, source_dir, task.branch, ref_type) 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) commit = await get_source_commit(source_dir)
await log_streamer.emit(task_id, f"源码版本: {task.branch} @ {commit}") await log_streamer.emit(task_id, f"源码版本: {task.branch} @ {commit}")
build_dir = await copy_source_code(task_id, task, source_dir) build_dir = await copy_source_code(task_id, task, source_dir, definition)
await log_streamer.emit(task_id, "共享源码快照已就绪,开始并行打包") await log_streamer.emit(task_id, "共享源码快照已就绪,开始并行打包")
return build_dir, commit return build_dir, commit
@@ -438,6 +478,7 @@ async def run_build_task(task_id: str):
nonlocal build_dir nonlocal build_dir
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。 # 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare") 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) build_dir, source_commit = await prepare_source_snapshot(task_id, task)
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir)) await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
@@ -452,7 +493,7 @@ async def run_build_task(task_id: str):
# 3. 替换项目配置 # 3. 替换项目配置
await asyncio.to_thread(_db_update, db, task, current_step="patch") await asyncio.to_thread(_db_update, db, task, current_step="patch")
await patch_project(task_id, task, config_data, build_dir) await patch_project(task_id, task, config_data, build_dir, definition)
# 3.5 安装依赖 # 3.5 安装依赖
await asyncio.to_thread(_db_update, db, task, current_step="pod_install") await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
@@ -465,7 +506,7 @@ async def run_build_task(task_id: str):
# 5. 构建项目 # 5. 构建项目
await asyncio.to_thread(_db_update, db, task, current_step="build") await asyncio.to_thread(_db_update, db, task, current_step="build")
ipa_path = await build_project(task_id, task, config_data, build_dir) ipa_path = await build_project(task_id, task, config_data, build_dir, definition["xcode"])
# 查找 dSYM # 查找 dSYM
dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", "")) dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", ""))
@@ -590,16 +631,36 @@ async def run_build_task(task_id: str):
db.close() db.close()
async def copy_source_code(task_id: str, task, source_dir: Path) -> Path: async def copy_source_code(task_id: str, task, source_dir: Path, definition: dict = None) -> Path:
"""从分支源码目录拷贝代码到打包目录""" """从分支源码目录拷贝代码到打包目录"""
await log_streamer.emit_step(task_id, "拷贝代码") await log_streamer.emit_step(task_id, "拷贝代码")
build_dir = BUILD_BASE_DIR / f"build_readoor_{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(): if build_dir.exists():
shutil.rmtree(build_dir) shutil.rmtree(build_dir)
build_dir.mkdir(parents=True)
for item in COPY_ITEMS: # 未指定拷贝条目时拷贝整个仓库(不含 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
build_dir.mkdir(parents=True)
for item in copy_items:
src = source_dir / item src = source_dir / item
# 历史分支中该文件可能仍是小写 podfile;构建副本统一使用 Pods.xcodeproj # 历史分支中该文件可能仍是小写 podfile;构建副本统一使用 Pods.xcodeproj
# 引用的标准名称 Podfile,避免大小写敏感文件系统报路径不一致。 # 引用的标准名称 Podfile,避免大小写敏感文件系统报路径不一致。
@@ -626,7 +687,8 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
is_release_track, next_build_no, _ensure_track, is_release_track, next_build_no, _ensure_track,
) )
config = load_config() project_id = _task_project_id(task)
config = load_config(project_id)
apps = config.get("apps", {}) apps = config.get("apps", {})
schemes = config.get("schemes", {}) schemes = config.get("schemes", {})
@@ -652,7 +714,7 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
# feature 轨始终使用手动设定的构建号。 # feature 轨始终使用手动设定的构建号。
if is_release and task.build_type == "App_Store": if is_release and task.build_type == "App_Store":
async with _config_lock: async with _config_lock:
config = load_config() config = load_config(project_id)
track = _ensure_track(config, track_name) track = _ensure_track(config, track_name)
track.setdefault("app_ver", app_ver) track.setdefault("app_ver", app_ver)
n = next_build_no(config["versions"]["tracks"], app_ver) n = next_build_no(config["versions"]["tracks"], app_ver)
@@ -666,6 +728,7 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
# 构建配置 # 构建配置
config_data = { config_data = {
"PROJECT_ID": project_id,
"VERSION": app_ver, "VERSION": app_ver,
"BUILD_VERSION": build_ver, "BUILD_VERSION": build_ver,
"SERVER": app.get("server", ""), "SERVER": app.get("server", ""),
@@ -739,6 +802,16 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
if key in app: if key in app:
config_data[key] = app[key] 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")
}
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" config_output_path = build_dir / "config_output.json"
with open(config_output_path, "w", encoding="utf-8") as f: with open(config_output_path, "w", encoding="utf-8") as f:
@@ -748,12 +821,12 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
return config_data return config_data
async def patch_project(task_id: str, task, config_data: dict, build_dir: Path): async def patch_project(task_id: str, task, config_data: dict, build_dir: Path, definition: dict = None):
"""替换项目配置""" """替换项目配置"""
await log_streamer.emit_step(task_id, "替换项目配置") await log_streamer.emit_step(task_id, "替换项目配置")
try: try:
patch_lines = await asyncio.to_thread(apply_project_config, build_dir, config_data) patch_lines = await asyncio.to_thread(apply_project_config, build_dir, config_data, definition)
except ProjectPatchError as exc: except ProjectPatchError as exc:
raise BuildError(str(exc), category="config") from exc raise BuildError(str(exc), category="config") from exc
(build_dir / "patch_result.log").write_text("\n".join(patch_lines), encoding="utf-8") (build_dir / "patch_result.log").write_text("\n".join(patch_lines), encoding="utf-8")
@@ -766,6 +839,10 @@ async def run_pod_install(task_id: str, build_dir: Path):
"""安装 CocoaPods 依赖""" """安装 CocoaPods 依赖"""
await log_streamer.emit_step(task_id, "安装依赖") await log_streamer.emit_step(task_id, "安装依赖")
if not (build_dir / "Podfile").is_file() and not (build_dir / "podfile").is_file():
await log_streamer.emit(task_id, "项目未使用 CocoaPods,跳过")
return
process = await asyncio.create_subprocess_exec( process = await asyncio.create_subprocess_exec(
"pod", "install", "pod", "install",
cwd=str(build_dir), cwd=str(build_dir),
@@ -845,14 +922,21 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
await log_streamer.emit(task_id, "代码混淆完成") await log_streamer.emit(task_id, "代码混淆完成")
async def build_project(task_id: str, task, config_data: dict, build_dir: Path) -> Path: async def build_project(task_id: str, task, config_data: dict, build_dir: Path, xcode: dict = None) -> Path:
"""构建项目""" """构建项目;xcode 为项目定义中的 {workspace, project},优先使用 workspace"""
await log_streamer.emit_step(task_id, "构建项目") await log_streamer.emit_step(task_id, "构建项目")
scheme = config_data.get("SCHEME", "") scheme = config_data.get("SCHEME", "")
export_path = build_dir / "build" export_path = build_dir / "build"
archive_path = export_path / f"{scheme}.xcarchive" archive_path = export_path / f"{scheme}.xcarchive"
workspace_path = build_dir / "readoor.xcworkspace" 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")
export_path.mkdir(parents=True, exist_ok=True) export_path.mkdir(parents=True, exist_ok=True)
@@ -860,7 +944,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
await log_streamer.emit(task_id, "清理项目...") await log_streamer.emit(task_id, "清理项目...")
process = await asyncio.create_subprocess_exec( process = await asyncio.create_subprocess_exec(
"xcodebuild", "clean", "xcodebuild", "clean",
"-workspace", workspace_path.name, *container_args,
"-scheme", scheme, "-scheme", scheme,
"-configuration", "Release", "-configuration", "Release",
"-derivedDataPath", str(export_path / "derived_data"), "-derivedDataPath", str(export_path / "derived_data"),
@@ -879,7 +963,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
archive_output = [] archive_output = []
process = await asyncio.create_subprocess_exec( process = await asyncio.create_subprocess_exec(
"xcodebuild", "archive", "xcodebuild", "archive",
"-workspace", workspace_path.name, *container_args,
"-scheme", scheme, "-scheme", scheme,
"-configuration", "Release", "-configuration", "Release",
"-archivePath", str(archive_path), "-archivePath", str(archive_path),
@@ -957,9 +1041,8 @@ async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, buil
await log_streamer.emit_step(task_id, "上传分发平台") await log_streamer.emit_step(task_id, "上传分发平台")
# 从当前服务的 config.json 读取上传配置,不执行分支源码中的上传脚本。 # 从当前服务的 config.json 读取上传配置,不执行分支源码中的上传脚本。
from ..routers.config import load_config from ..routers.config import load_upload_config
full_config = load_config() config_data["_upload_config"] = load_upload_config()
config_data["_upload_config"] = full_config.get("upload", {})
try: try:
await log_streamer.emit(task_id, f"使用 {config_data['_upload_config'].get('mode', '')} 发布 IPA...") 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) return await asyncio.to_thread(publish_ipa, config_data, ipa_path, build_dir)
+140 -2
View File
@@ -135,8 +135,14 @@ def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str])
messages.append("已替换词典版本配置") messages.append("已替换词典版本配置")
def apply_project_config(build_dir: Path, config: dict) -> list[str]: 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] = [] messages: list[str] = []
if config.get("SCHEME") == "readoorDict": if config.get("SCHEME") == "readoorDict":
_apply_dictionary_config(build_dir, config, messages) _apply_dictionary_config(build_dir, config, messages)
@@ -190,3 +196,135 @@ def apply_project_config(build_dir: Path, config: dict) -> list[str]:
_write_export_options(build_dir, config) _write_export_options(build_dir, config)
messages.append("工程、签名、版本和分发配置已更新") messages.append("工程、签名、版本和分发配置已更新")
return messages 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
+48 -2
View File
@@ -3,6 +3,14 @@
<header class="header"> <header class="header">
<h1>iOS 自动打包服务</h1> <h1>iOS 自动打包服务</h1>
<div class="header-right"> <div class="header-right">
<select
v-if="isLoggedIn && projects.length > 1"
v-model="currentProject"
class="project-select"
title="切换项目"
>
<option v-for="p in projects" :key="p.id" :value="p.id">{{ p.name }}</option>
</select>
<nav v-if="isLoggedIn" class="nav"> <nav v-if="isLoggedIn" class="nav">
<router-link to="/build">打包</router-link> <router-link to="/build">打包</router-link>
<router-link to="/history">历史</router-link> <router-link to="/history">历史</router-link>
@@ -21,7 +29,8 @@
</header> </header>
<template v-if="isLoggedIn"> <template v-if="isLoggedIn">
<router-view /> <!-- 切换项目时重建页面,按新项目重新加载数据 -->
<router-view v-if="projectReady" :key="currentProject" />
</template> </template>
<template v-else> <template v-else>
<div class="login-required"> <div class="login-required">
@@ -52,7 +61,7 @@
</template> </template>
<script setup> <script setup>
import { ref, onMounted, provide } from 'vue' import { ref, computed, onMounted, provide, watch } from 'vue'
const isLoggedIn = ref(false) const isLoggedIn = ref(false)
const isAdmin = ref(false) const isAdmin = ref(false)
@@ -67,6 +76,40 @@ provide('isAdmin', isAdmin)
// 获取存储的 token // 获取存储的 token
const getToken = () => localStorage.getItem('authToken') || '' const getToken = () => localStorage.getItem('authToken') || ''
// 当前项目:所有接口请求通过 X-Project 请求头指定,记在本地以便下次打开沿用
const PROJECT_KEY = 'currentProject'
const readStoredProject = () => {
try { return localStorage.getItem(PROJECT_KEY) || '' } catch { return '' }
}
const projects = ref([])
const currentProject = ref(readStoredProject())
const projectReady = ref(false)
const currentProjectInfo = computed(() => projects.value.find(p => p.id === currentProject.value) || null)
watch(currentProject, (value) => {
try { localStorage.setItem(PROJECT_KEY, value) } catch { /* 忽略存储失败 */ }
})
const loadProjects = async () => {
try {
const res = await fetch('/api/projects', { headers: { 'Authorization': `Bearer ${getToken()}` } })
if (res.ok) {
projects.value = await res.json()
if (!projects.value.some(p => p.id === currentProject.value)) {
currentProject.value = projects.value[0]?.id || ''
}
}
} catch {
// 网络错误时沿用当前项目
}
projectReady.value = true
}
provide('projects', projects)
provide('currentProject', currentProject)
provide('currentProjectInfo', currentProjectInfo)
provide('reloadProjects', loadProjects)
// 对外暴露 token 获取方法,供 API 请求使用 // 对外暴露 token 获取方法,供 API 请求使用
provide('getToken', getToken) provide('getToken', getToken)
@@ -83,6 +126,7 @@ const login = async () => {
isAdmin.value = data.is_admin isAdmin.value = data.is_admin
showLogin.value = false showLogin.value = false
localStorage.setItem('authToken', data.token) localStorage.setItem('authToken', data.token)
await loadProjects()
} else { } else {
alert('用户名或密码错误') alert('用户名或密码错误')
} }
@@ -112,6 +156,7 @@ onMounted(async () => {
const data = await res.json() const data = await res.json()
isLoggedIn.value = true isLoggedIn.value = true
isAdmin.value = data.is_admin isAdmin.value = data.is_admin
await loadProjects()
} else { } else {
localStorage.removeItem('authToken') localStorage.removeItem('authToken')
showLogin.value = true showLogin.value = true
@@ -132,6 +177,7 @@ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; b
.nav a { color: #a0a0a0; text-decoration: none; padding: 8px 16px; border-radius: 6px; } .nav a { color: #a0a0a0; text-decoration: none; padding: 8px 16px; border-radius: 6px; }
.nav a.router-link-active { background: #16213e; color: white; } .nav a.router-link-active { background: #16213e; color: white; }
.nav a:hover { color: white; } .nav a:hover { color: white; }
.project-select { background: #16213e; color: white; border: 1px solid #444; border-radius: 6px; padding: 6px 10px; font-size: 14px; cursor: pointer; }
.user-info { display: flex; align-items: center; gap: 10px; } .user-info { display: flex; align-items: center; gap: 10px; }
.user-avatar { width: 32px; height: 32px; background: #1890ff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600; } .user-avatar { width: 32px; height: 32px; background: #1890ff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600; }
.user-name { font-size: 14px; } .user-name { font-size: 14px; }
+9 -2
View File
@@ -51,7 +51,7 @@
</optgroup> </optgroup>
</select> </select>
</div> </div>
<div class="form-group"> <div v-if="supportsObfuscation" class="form-group">
<label>代码混淆</label> <label>代码混淆</label>
<div class="checkbox-group"> <div class="checkbox-group">
<input type="checkbox" id="obfuscation" v-model="form.obfuscation"> <input type="checkbox" id="obfuscation" v-model="form.obfuscation">
@@ -161,11 +161,15 @@ import { useRoute } from 'vue-router'
const getToken = inject('getToken') const getToken = inject('getToken')
const currentProject = inject('currentProject', ref(''))
const authFetch = (url, options = {}) => { const authFetch = (url, options = {}) => {
const token = getToken() const token = getToken()
if (token) { if (token) {
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` } options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
} }
if (currentProject.value) {
options.headers = { ...options.headers, 'X-Project': currentProject.value }
}
return fetch(url, options) return fetch(url, options)
} }
@@ -182,6 +186,9 @@ const filteredApps = computed(() => {
return Object.entries(apps.value).filter(([, app]) => app.server === selectedServer.value) return Object.entries(apps.value).filter(([, app]) => app.server === selectedServer.value)
}) })
const selectedApp = computed(() => apps.value[form.value.app_id] || null) const selectedApp = computed(() => apps.value[form.value.app_id] || null)
const currentProjectInfo = inject('currentProjectInfo', ref(null))
// 未加载到项目信息时(旧版服务)保持原有行为
const supportsObfuscation = computed(() => currentProjectInfo.value?.obfuscation ?? true)
const availableBuildTypes = computed(() => { const availableBuildTypes = computed(() => {
const certificates = selectedApp.value?.certificates || {} const certificates = selectedApp.value?.certificates || {}
return ['Ad_Hoc', 'App_Store'].filter(buildType => Boolean(certificates[buildType])) return ['Ad_Hoc', 'App_Store'].filter(buildType => Boolean(certificates[buildType]))
@@ -373,7 +380,7 @@ const submitTask = async () => {
const res = await authFetch('/api/tasks', { const res = await authFetch('/api/tasks', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(form.value), body: JSON.stringify({ ...form.value, obfuscation: supportsObfuscation.value && form.value.obfuscation }),
}) })
if (res.ok) { if (res.ok) {
const task = await res.json() const task = await res.json()
+308 -26
View File
@@ -8,7 +8,9 @@
<div v-else class="admin-page"> <div v-else class="admin-page">
<div class="sidebar"> <div class="sidebar">
<h3>配置管理</h3> <h3>配置管理</h3>
<div v-if="currentProjectInfo" class="sidebar-project">当前项目:{{ currentProjectInfo.name }}</div>
<ul class="sidebar-menu"> <ul class="sidebar-menu">
<li v-if="isAdmin" :class="{ active: tab === 'projects' }" @click="tab = 'projects'">项目管理</li>
<li v-if="isAdmin" :class="{ active: tab === 'users' }" @click="tab = 'users'">用户管理</li> <li v-if="isAdmin" :class="{ active: tab === 'users' }" @click="tab = 'users'">用户管理</li>
<li v-if="isAdmin" :class="{ active: tab === 'servers' }" @click="tab = 'servers'">服务器环境</li> <li v-if="isAdmin" :class="{ active: tab === 'servers' }" @click="tab = 'servers'">服务器环境</li>
<li :class="{ active: tab === 'apps' }" @click="tab = 'apps'">Apps 配置</li> <li :class="{ active: tab === 'apps' }" @click="tab = 'apps'">Apps 配置</li>
@@ -20,6 +22,38 @@
</ul> </ul>
</div> </div>
<div class="main-content"> <div class="main-content">
<!-- 项目管理 -->
<div v-if="tab === 'projects'">
<h2>项目管理</h2>
<p style="color: #666; margin-bottom: 16px; font-size: 14px;">每个项目有独立的源码仓库、Apps、Schemes、服务器环境、分支和版本号;上传配置所有项目共用。页面顶部切换当前项目。</p>
<button class="btn btn-primary" style="width: auto; margin-bottom: 16px;" @click="openProjectModal()">+ 新增项目</button>
<table class="config-table">
<thead>
<tr>
<th>ID</th>
<th>名称</th>
<th>Git 仓库</th>
<th>Xcode</th>
<th>配置替换</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="p in projectDefinitions" :key="p.id">
<td>{{ p.id }}</td>
<td><strong>{{ p.name }}</strong></td>
<td>{{ p.git.remote_url || (p.git.use_env ? '.env 中的 GIT_REMOTE_URL' : '-') }}</td>
<td>{{ p.xcode.workspace || p.xcode.project }}</td>
<td>{{ p.patcher === 'readoor' ? 'Readoor 专用' : `通用(${p.patch_rules.length} 条规则)` }}</td>
<td class="action-btns">
<button class="action-btn" @click="openProjectModal(p)">编辑</button>
<button class="action-btn delete" @click="deleteProject(p)">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- 用户管理 --> <!-- 用户管理 -->
<div v-if="tab === 'users'"> <div v-if="tab === 'users'">
<h2>用户管理</h2> <h2>用户管理</h2>
@@ -65,20 +99,22 @@
<thead> <thead>
<tr> <tr>
<th>环境名称</th> <th>环境名称</th>
<th>API 地址</th> <th v-if="isReadoorProject">API 地址</th>
<th>App ID 前缀</th> <th>App ID 前缀</th>
<th>Associated Domains</th> <th v-if="isReadoorProject">Associated Domains</th>
<th>Universal Link</th> <th v-if="isReadoorProject">Universal Link</th>
<th v-for="field in serverFields" :key="field.key">{{ field.label }}</th>
<th>操作</th> <th>操作</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr v-for="(server, name) in servers" :key="name"> <tr v-for="(server, name) in servers" :key="name">
<td><strong>{{ name }}</strong></td> <td><strong>{{ name }}</strong></td>
<td>{{ server.api }}</td> <td v-if="isReadoorProject">{{ server.api }}</td>
<td>{{ server.app_id_prefix }}</td> <td>{{ server.app_id_prefix }}</td>
<td>{{ server.assDom }}</td> <td v-if="isReadoorProject">{{ server.assDom }}</td>
<td>{{ server.universalLink }}</td> <td v-if="isReadoorProject">{{ server.universalLink }}</td>
<td v-for="field in serverFields" :key="field.key">{{ server[field.key] }}</td>
<td class="action-btns"> <td class="action-btns">
<button class="action-btn" @click="openServerModal(name, server)">编辑</button> <button class="action-btn" @click="openServerModal(name, server)">编辑</button>
<button class="action-btn delete" @click="deleteServer(name)">删除</button> <button class="action-btn delete" @click="deleteServer(name)">删除</button>
@@ -98,7 +134,8 @@
<th>ID</th> <th>ID</th>
<th>名称</th> <th>名称</th>
<th>环境</th> <th>环境</th>
<th>AppGuid</th> <th v-if="isReadoorProject">AppGuid</th>
<th v-for="field in appFields" :key="field.key">{{ field.label }}</th>
<th>证书</th> <th>证书</th>
<th>操作</th> <th>操作</th>
</tr> </tr>
@@ -108,7 +145,8 @@
<td>{{ id }}</td> <td>{{ id }}</td>
<td>{{ app.name }}</td> <td>{{ app.name }}</td>
<td>{{ app.server }}</td> <td>{{ app.server }}</td>
<td>{{ app.AppGuid || app.AppId }}</td> <td v-if="isReadoorProject">{{ app.AppGuid || app.AppId }}</td>
<td v-for="field in appFields" :key="field.key">{{ app[field.key] }}</td>
<td>{{ Object.keys(app.certificates || {}).join(', ') || '-' }}</td> <td>{{ Object.keys(app.certificates || {}).join(', ') || '-' }}</td>
<td class="action-btns"> <td class="action-btns">
<button class="action-btn" @click="openAppModal(id, app)">编辑</button> <button class="action-btn" @click="openAppModal(id, app)">编辑</button>
@@ -413,17 +451,23 @@
<label>环境名称 *</label> <label>环境名称 *</label>
<input v-model="serverForm.name" type="text" placeholder="例如:测试环境" :disabled="!!editingServerName"> <input v-model="serverForm.name" type="text" placeholder="例如:测试环境" :disabled="!!editingServerName">
</div> </div>
<div class="form-group"> <template v-if="isReadoorProject">
<label>API 地址 *</label> <div class="form-group">
<input v-model="serverForm.api" type="text" placeholder="https://api3-dev.readoor.cn"> <label>API 地址 *</label>
</div> <input v-model="serverForm.api" type="text" placeholder="https://api3-dev.readoor.cn">
<div class="form-group"> </div>
<label>Associated Domains</label> <div class="form-group">
<input v-model="serverForm.assDom" type="text" placeholder="applinks:dev-data1.readoor.cn"> <label>Associated Domains</label>
</div> <input v-model="serverForm.assDom" type="text" placeholder="applinks:dev-data1.readoor.cn">
<div class="form-group"> </div>
<label>Universal Link</label> <div class="form-group">
<input v-model="serverForm.universalLink" type="text" placeholder="https://dev-data1.readoor.cn"> <label>Universal Link</label>
<input v-model="serverForm.universalLink" type="text" placeholder="https://dev-data1.readoor.cn">
</div>
</template>
<div v-for="field in serverFields" :key="field.key" class="form-group">
<label>{{ field.label }}{{ field.required ? ' *' : '' }}</label>
<input v-model="serverForm[field.key]" type="text">
</div> </div>
<div class="form-group"> <div class="form-group">
<label>App ID 前缀</label> <label>App ID 前缀</label>
@@ -467,7 +511,7 @@
<input v-model.number="appForm.app_id_prefix_override" type="number" min="1" placeholder="仅特殊 App 使用"> <input v-model.number="appForm.app_id_prefix_override" type="number" min="1" placeholder="仅特殊 App 使用">
</div> </div>
</div> </div>
<div class="form-row"> <div v-if="isReadoorProject" class="form-row">
<div class="form-group"> <div class="form-group">
<label>AppGuid *</label> <label>AppGuid *</label>
<input v-model="appForm.AppGuid" type="text" placeholder="应用唯一标识"> <input v-model="appForm.AppGuid" type="text" placeholder="应用唯一标识">
@@ -478,7 +522,15 @@
</div> </div>
</div> </div>
<div v-if="appFields.length" class="form-row">
<div v-for="field in appFields" :key="field.key" class="form-group">
<label>{{ field.label }}{{ field.required ? ' *' : '' }}</label>
<input v-model="appForm[field.key]" type="text">
</div>
</div>
<!-- 关联配置 --> <!-- 关联配置 -->
<template v-if="isReadoorProject">
<h4 class="section-title">关联配置</h4> <h4 class="section-title">关联配置</h4>
<div class="form-row"> <div class="form-row">
<div class="form-group"> <div class="form-group">
@@ -516,6 +568,7 @@
<input v-model="appForm.AlivcLicenseKey" type="text"> <input v-model="appForm.AlivcLicenseKey" type="text">
</div> </div>
</div> </div>
</template>
<!-- 证书配置 --> <!-- 证书配置 -->
<h4 class="section-title">证书配置</h4> <h4 class="section-title">证书配置</h4>
@@ -542,7 +595,7 @@
<label>Provisioning Profile 名称</label> <label>Provisioning Profile 名称</label>
<input v-model="appForm.certificates[certType].pro" type="text" placeholder="/Users/.../xxx.mobileprovision"> <input v-model="appForm.certificates[certType].pro" type="text" placeholder="/Users/.../xxx.mobileprovision">
</div> </div>
<div class="form-group"> <div v-if="isReadoorProject" class="form-group">
<label>主题目录</label> <label>主题目录</label>
<select v-if="appSkins.length" <select v-if="appSkins.length"
:value="appSkins.some(s => s.name.replace('.zip', '') === appForm.certificates[certType].theme) ? appForm.certificates[certType].theme : ''" :value="appSkins.some(s => s.name.replace('.zip', '') === appForm.certificates[certType].theme) ? appForm.certificates[certType].theme : ''"
@@ -562,6 +615,7 @@
</div> </div>
<!-- 皮肤包管理 --> <!-- 皮肤包管理 -->
<template v-if="isReadoorProject">
<h4 class="section-title" style="margin-top: 20px;">皮肤包管理</h4> <h4 class="section-title" style="margin-top: 20px;">皮肤包管理</h4>
<div class="skins-section"> <div class="skins-section">
<div v-if="!appForm.upload_key" class="skins-hint">请先保存 APP 后再上传皮肤包</div> <div v-if="!appForm.upload_key" class="skins-hint">请先保存 APP 后再上传皮肤包</div>
@@ -589,6 +643,7 @@
</label> </label>
</div> </div>
</div> </div>
</template>
<div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;"> <div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
<button class="action-btn" style="padding: 8px 16px;" @click="showAppModal = false">取消</button> <button class="action-btn" style="padding: 8px 16px;" @click="showAppModal = false">取消</button>
@@ -597,6 +652,106 @@
</div> </div>
</div> </div>
<!-- 项目编辑弹窗 -->
<div v-if="showProjectModal" class="modal-overlay" @click.self="showProjectModal = false">
<div class="modal-content modal-large">
<div class="modal-header">
<h3>{{ editingProjectId ? '编辑' : '新增' }}项目</h3>
<button class="modal-close" @click="showProjectModal = false">&times;</button>
</div>
<div class="form-row">
<div class="form-group">
<label>项目 ID *</label>
<input v-model="projectForm.id" type="text" placeholder="例如:dyauction(小写字母开头)" :disabled="!!editingProjectId">
</div>
<div class="form-group">
<label>项目名称 *</label>
<input v-model="projectForm.name" type="text" placeholder="例如:多云选">
</div>
</div>
<h4 class="section-title">源码仓库</h4>
<div class="form-group">
<label>Git 仓库地址</label>
<input v-model="projectForm.git.remote_url" type="text" placeholder="https://git.example.com/group/repo.git">
</div>
<div class="form-row">
<div class="form-group">
<label>Git 用户名</label>
<input v-model="projectForm.git.username" type="text" autocomplete="off">
</div>
<div class="form-group">
<label>Git 密码 / Token</label>
<input v-model="projectForm.git.password" type="password" autocomplete="new-password"
:placeholder="projectForm.git.password_set ? '已设置,留空保持不变' : ''">
</div>
</div>
<label class="checkbox-label" style="margin-bottom: 12px;">
<input type="checkbox" v-model="projectForm.git.use_env">
未填写的 Git 配置使用 .env 中的 GIT_REMOTE_URL / GIT_USERNAME / GIT_PASSWORD
</label>
<div class="form-group">
<label>共享源码目录</label>
<input v-model="projectForm.source_dir" type="text" :placeholder="`留空为 <服务目录>/sources/${projectForm.id || '<项目 ID>'}`">
<div class="field-hint">打包时会对该目录执行 git reset --hard 和 git clean,不要指向本地开发用的工作副本。</div>
</div>
<h4 class="section-title">Xcode 工程</h4>
<div class="form-row">
<div class="form-group">
<label>Workspace</label>
<input v-model="projectForm.xcode.workspace" type="text" placeholder="X.xcworkspace(使用 CocoaPods 时填写)">
</div>
<div class="form-group">
<label>Project</label>
<input v-model="projectForm.xcode.project" type="text" placeholder="X.xcodeproj">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label>配置替换方式</label>
<select v-model="projectForm.patcher">
<option value="generic">通用(版本号、签名 + 替换规则)</option>
<option value="readoor">Readoor 专用</option>
</select>
</div>
<div class="form-group">
<label>代码混淆</label>
<label class="checkbox-label"><input type="checkbox" v-model="projectForm.obfuscation"> 支持代码混淆</label>
</div>
</div>
<div class="form-group">
<label>拷贝条目(每行一个,留空拷贝整个仓库)</label>
<textarea v-model="projectForm.copy_items_text" rows="3" class="code-textarea"></textarea>
</div>
<h4 class="section-title">自定义字段与替换规则(JSON)</h4>
<div class="form-group">
<label>App 字段</label>
<textarea v-model="projectForm.app_fields_text" rows="3" class="code-textarea"
placeholder='[{"key": "APPID", "label": "APPID", "required": true}]'></textarea>
</div>
<div class="form-group">
<label>服务器环境字段</label>
<textarea v-model="projectForm.server_fields_text" rows="3" class="code-textarea"
placeholder='[{"key": "ISDEV", "label": "ISDEV(1=开发,0=正式)", "required": true}]'></textarea>
</div>
<div class="form-group">
<label>替换规则</label>
<textarea v-model="projectForm.patch_rules_text" rows="6" class="code-textarea"
placeholder='[{"type": "define", "file": "App/Macro.h", "name": "ISDEV", "value": "${server.ISDEV}"}]'></textarea>
<div class="field-hint">
define:替换文件中所有未注释的 <code>#define 名称</code> 行;replace_line:整行替换包含 keyword 的行(字段为 line)。
值中可用 <code>${app.字段}</code>、<code>${server.字段}</code>、<code>${VERSION}</code> 等。
</div>
</div>
<div style="margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;">
<button class="action-btn" style="padding: 8px 16px;" @click="showProjectModal = false">取消</button>
<button class="btn btn-primary" style="width: auto; padding: 8px 24px;" @click="saveProject">保存</button>
</div>
</div>
</div>
<!-- Scheme 编辑弹窗 --> <!-- Scheme 编辑弹窗 -->
<div v-if="showSchemeModal" class="modal-overlay" @click.self="showSchemeModal = false"> <div v-if="showSchemeModal" class="modal-overlay" @click.self="showSchemeModal = false">
<div class="modal-content"> <div class="modal-content">
@@ -634,6 +789,16 @@ const isLoggedIn = inject('isLoggedIn')
const isAdmin = inject('isAdmin') const isAdmin = inject('isAdmin')
const tab = ref('apps') const tab = ref('apps')
// 当前项目决定 App / 服务器环境表单显示哪些字段
const currentProjectInfo = inject('currentProjectInfo', ref(null))
const reloadProjects = inject('reloadProjects', async () => {})
const isReadoorProject = computed(() => (currentProjectInfo.value?.patcher ?? 'readoor') === 'readoor')
const appFields = computed(() => currentProjectInfo.value?.app_fields || [])
const serverFields = computed(() => currentProjectInfo.value?.server_fields || [])
const missingRequiredFields = (fields, data) => fields
.filter(field => field.required && !String(data[field.key] ?? '').trim())
.map(field => field.label || field.key)
// 用户管理 // 用户管理
const users = ref([]) const users = ref([])
const showUserModal = ref(false) const showUserModal = ref(false)
@@ -643,11 +808,15 @@ const passwordTarget = ref(null)
const newPassword = ref('') const newPassword = ref('')
// 带认证的 fetch 封装 // 带认证的 fetch 封装
const currentProject = inject('currentProject', ref(''))
const authFetch = (url, options = {}) => { const authFetch = (url, options = {}) => {
const token = getToken() const token = getToken()
if (token) { if (token) {
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` } options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
} }
if (currentProject.value) {
options.headers = { ...options.headers, 'X-Project': currentProject.value }
}
return fetch(url, options) return fetch(url, options)
} }
const apps = ref({}) const apps = ref({})
@@ -762,7 +931,7 @@ const loadData = async () => {
return return
} }
const [appsRes, schemesRes, serversRes, branchesRes, tagsRes, buildRes, uploadRes, configRes, versionsRes, usersRes] = await Promise.all([ const [appsRes, schemesRes, serversRes, branchesRes, tagsRes, buildRes, uploadRes, configRes, versionsRes, usersRes, projectsRes] = await Promise.all([
authFetch('/api/config/apps'), authFetch('/api/config/apps'),
authFetch('/api/config/schemes'), authFetch('/api/config/schemes'),
authFetch('/api/config/servers'), authFetch('/api/config/servers'),
@@ -773,6 +942,7 @@ const loadData = async () => {
authFetch('/api/config'), authFetch('/api/config'),
authFetch('/api/config/versions'), authFetch('/api/config/versions'),
authFetch('/api/users'), authFetch('/api/users'),
authFetch('/api/config/projects'),
]) ])
apps.value = await appsRes.json() apps.value = await appsRes.json()
schemes.value = await schemesRes.json() schemes.value = await schemesRes.json()
@@ -785,6 +955,105 @@ const loadData = async () => {
jsonContent.value = JSON.stringify(await configRes.json(), null, 2) jsonContent.value = JSON.stringify(await configRes.json(), null, 2)
applyVersions(await versionsRes.json()) applyVersions(await versionsRes.json())
if (usersRes.ok) users.value = await usersRes.json() if (usersRes.ok) users.value = await usersRes.json()
if (projectsRes?.ok) projectDefinitions.value = await projectsRes.json()
}
// 项目管理
const projectDefinitions = ref([])
const showProjectModal = ref(false)
const editingProjectId = ref(null)
const projectForm = ref({})
const toJsonText = value => (value && value.length ? JSON.stringify(value, null, 2) : '')
const openProjectModal = (project = null) => {
editingProjectId.value = project?.id || null
const p = project || {
id: '', name: '', source_dir: '', patcher: 'generic', obfuscation: false, copy_items: [],
git: { remote_url: '', username: '', use_env: false, password_set: false },
xcode: { workspace: '', project: '' }, app_fields: [], server_fields: [], patch_rules: [],
}
projectForm.value = {
id: p.id,
name: p.name,
source_dir: p.source_dir || '',
patcher: p.patcher,
obfuscation: !!p.obfuscation,
git: { ...p.git, password: '' },
xcode: { ...p.xcode },
copy_items_text: (p.copy_items || []).join('\n'),
app_fields_text: toJsonText(p.app_fields),
server_fields_text: toJsonText(p.server_fields),
patch_rules_text: toJsonText(p.patch_rules),
}
showProjectModal.value = true
}
const saveProject = async () => {
const form = projectForm.value
if (!form.id || !form.name) {
alert('请填写必填字段:项目 ID、项目名称')
return
}
const parsed = {}
for (const [key, label] of [['app_fields', 'App 字段'], ['server_fields', '服务器环境字段'], ['patch_rules', '替换规则']]) {
const text = (form[`${key}_text`] || '').trim()
try {
parsed[key] = text ? JSON.parse(text) : []
} catch {
alert(`${label} 不是有效的 JSON`)
return
}
if (!Array.isArray(parsed[key])) {
alert(`${label} 必须是 JSON 数组`)
return
}
}
const { password_set: _passwordSet, ...git } = form.git
const body = {
id: form.id,
name: form.name,
git,
source_dir: form.source_dir,
xcode: form.xcode,
patcher: form.patcher,
obfuscation: form.obfuscation,
copy_items: form.copy_items_text.split('\n').map(item => item.trim()).filter(Boolean),
...parsed,
}
const editing = editingProjectId.value
try {
const res = await authFetch(editing ? `/api/config/projects/${encodeURIComponent(editing)}` : '/api/config/projects', {
method: editing ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
throw new Error(err.detail || '保存失败')
}
showProjectModal.value = false
await loadData()
await reloadProjects()
alert('保存成功')
} catch (e) {
alert('保存失败: ' + e.message)
}
}
const deleteProject = async (project) => {
if (!confirm(`确定删除项目「${project.name}」?该项目的 Apps、Schemes、服务器环境、分支和版本配置都会删除(打包记录保留)。`)) return
try {
const res = await authFetch(`/api/config/projects/${encodeURIComponent(project.id)}`, { method: 'DELETE' })
if (!res.ok) {
const err = await res.json().catch(() => ({}))
throw new Error(err.detail || '删除失败')
}
await loadData()
await reloadProjects()
alert('删除成功')
} catch (e) {
alert('删除失败: ' + e.message)
}
} }
// 用户管理 // 用户管理
@@ -882,8 +1151,13 @@ const openServerModal = (name = null, server = null) => {
} }
const saveServer = async () => { const saveServer = async () => {
if (!serverForm.value.name || !serverForm.value.api) { const missing = [
alert('请填写必填字段:环境名称、API 地址') ...(!serverForm.value.name ? ['环境名称'] : []),
...(isReadoorProject.value && !serverForm.value.api ? ['API 地址'] : []),
...missingRequiredFields(serverFields.value, serverForm.value),
]
if (missing.length) {
alert(`请填写必填字段:${missing.join('、')}`)
return return
} }
@@ -1087,8 +1361,13 @@ const normalizeTencentAppId = () => {
} }
const saveApp = async () => { const saveApp = async () => {
if (!appForm.value.name || !appForm.value.AppGuid) { const missing = [
alert('请填写必填字段:App 名称、AppGuid') ...(!appForm.value.name ? ['App 名称'] : []),
...(isReadoorProject.value && !appForm.value.AppGuid ? ['AppGuid'] : []),
...missingRequiredFields(appFields.value, appForm.value),
]
if (missing.length) {
alert(`请填写必填字段:${missing.join('、')}`)
return return
} }
@@ -1362,6 +1641,9 @@ const formatJson = () => {
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; } .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.modal-content { background: white; border-radius: 12px; padding: 24px; width: 500px; max-height: 80vh; overflow-y: auto; } .modal-content { background: white; border-radius: 12px; padding: 24px; width: 500px; max-height: 80vh; overflow-y: auto; }
.modal-large { width: 700px; } .modal-large { width: 700px; }
.sidebar-project { font-size: 12px; color: #888; margin: -8px 0 12px; }
.code-textarea { width: 100%; font-family: Menlo, Monaco, monospace; font-size: 12px; padding: 8px; border: 1px solid #d9d9d9; border-radius: 4px; resize: vertical; box-sizing: border-box; }
.field-hint { font-size: 12px; color: #999; margin-top: 4px; line-height: 1.6; }
.modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.modal-header h3 { font-size: 16px; margin: 0; } .modal-header h3 { font-size: 16px; margin: 0; }
.modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; } .modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
+4
View File
@@ -165,11 +165,15 @@ const getToken = inject('getToken', () => '')
const isAdmin = inject('isAdmin', ref(false)) const isAdmin = inject('isAdmin', ref(false))
const tasks = ref([]) const tasks = ref([])
const currentProject = inject('currentProject', ref(''))
const authFetch = (url, options = {}) => { const authFetch = (url, options = {}) => {
const token = getToken() const token = getToken()
if (token) { if (token) {
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` } options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
} }
if (currentProject.value) {
options.headers = { ...options.headers, 'X-Project': currentProject.value }
}
return fetch(url, options) return fetch(url, options)
} }
const filterStatus = ref('') const filterStatus = ref('')
+15 -5
View File
@@ -55,6 +55,17 @@ def tmp_dirs(tmp_path):
return source_dir, build_dir return source_dir, build_dir
def _patch_project_source(source_dir, remote_url="git@github.com:test/repo.git"):
"""让任务所属项目使用指定的远程仓库和共享源码目录"""
from backend.projects import ProjectSource
source = ProjectSource(remote_url, remote_url, source_dir)
return patch.multiple(
"backend.services.build_service",
load_task_project=MagicMock(return_value={}),
get_project_source=MagicMock(return_value=source),
)
def _make_mock_process(returncode=0, output=b"ok\n"): def _make_mock_process(returncode=0, output=b"ok\n"):
"""创建 mock 进程,支持 async for stdout""" """创建 mock 进程,支持 async for stdout"""
proc = AsyncMock() proc = AsyncMock()
@@ -87,7 +98,7 @@ async def test_update_source_clone_no_remote(tmp_path, log_streamer):
source_dir = tmp_path / "branches" / "main" source_dir = tmp_path / "branches" / "main"
with patch("backend.services.build_service.get_git_remote_url", return_value=""): with patch("backend.services.build_service.get_git_remote_url", return_value=""):
with pytest.raises(Exception, match="GIT_REMOTE_URL"): with pytest.raises(Exception, match="未配置 Git 仓库地址"):
await update_source("t1", source_dir, "main") await update_source("t1", source_dir, "main")
@@ -152,8 +163,7 @@ async def test_prepare_source_snapshot_serializes_shared_source(tmp_dirs, log_st
source_dir, build_dir_parent = tmp_dirs source_dir, build_dir_parent = tmp_dirs
task = MagicMock(branch="main") task = MagicMock(branch="main")
with patch("backend.services.build_service.get_git_remote_url", return_value="git@github.com:test/repo.git"), \ with _patch_project_source(source_dir), \
patch("backend.services.build_service.get_shared_source_dir", return_value=source_dir), \
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \ patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \ patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"): patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
@@ -168,8 +178,7 @@ async def test_prepare_source_snapshot_passes_tag_ref_type(tmp_dirs, log_streame
source_dir, build_dir_parent = tmp_dirs source_dir, build_dir_parent = tmp_dirs
task = MagicMock(id="tag-task", branch="v3.2.0", ref_type="tag") task = MagicMock(id="tag-task", branch="v3.2.0", ref_type="tag")
with patch("backend.services.build_service.get_git_remote_url", return_value="git@github.com:test/repo.git"), \ with _patch_project_source(source_dir), \
patch("backend.services.build_service.get_shared_source_dir", return_value=source_dir), \
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \ patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \ patch("backend.services.build_service.update_source", new_callable=AsyncMock) as mock_update, \
patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"): patch("backend.services.build_service.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
@@ -266,6 +275,7 @@ async def test_run_pod_install_patches_afnetworking(tmp_path, log_streamer):
source_dir.mkdir(parents=True) source_dir.mkdir(parents=True)
source_file = source_dir / "AFHTTPSessionManager.m" source_file = source_dir / "AFHTTPSessionManager.m"
source_file.write_text("#import <netinet6/in6.h>\n") source_file.write_text("#import <netinet6/in6.h>\n")
(tmp_path / "Podfile").write_text("pod 'AFNetworking'")
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()): with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()):
await run_pod_install("t1", tmp_path) await run_pod_install("t1", tmp_path)
+330
View File
@@ -0,0 +1,330 @@
"""多项目配置测试"""
import json
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.projects import get_project_source
from backend.services.project_patcher import ProjectPatchError, apply_project_config
DY_PROJECT = {
"id": "dyauction",
"name": "多云选",
"git": {"remote_url": "https://git.example.com/dy.git", "username": "bot", "password": "secret"},
"xcode": {"workspace": "", "project": "DyAuction.xcodeproj"},
"patcher": "generic",
"patch_rules": [
{"type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "ISDEV", "value": "${server.ISDEV}"},
{"type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "APPID", "value": '@"${app.APPID}"'},
],
"app_fields": [{"key": "APPID", "label": "APPID", "required": True}],
"server_fields": [{"key": "ISDEV", "label": "ISDEV", "required": True}],
}
DY = {"X-Project": "dyauction"}
@pytest.fixture
def dy_project(client, tmp_config):
resp = client.post("/api/config/projects", json=DY_PROJECT)
assert resp.status_code == 200, resp.text
return "dyauction"
def _root(tmp_config: Path) -> dict:
return json.loads(tmp_config.read_text())
# ---- 迁移与隔离 ----
def test_legacy_config_migrates_to_readoor_project(client, tmp_config):
assert client.get("/api/config/apps").status_code == 200
root = _root(tmp_config)
assert list(root["projects"]) == ["readoor"]
readoor = root["projects"]["readoor"]
assert readoor["patcher"] == "readoor"
assert readoor["git"]["use_env"] is True
assert readoor["apps"]["1"]["name"] == "测试App"
assert "apps" not in root
assert "upload" not in readoor
def test_projects_list_hides_git_password(client, dy_project):
public = client.get("/api/projects").json()
assert [p["id"] for p in public] == ["readoor", "dyauction"]
assert "git" not in public[1]
assert public[1]["app_fields"][0]["key"] == "APPID"
admin = client.get("/api/config/projects").json()
dy = next(p for p in admin if p["id"] == "dyauction")
assert dy["git"]["password_set"] is True
assert "password" not in dy["git"]
def test_project_data_is_isolated(client, dy_project):
assert client.get("/api/apps", headers=DY).json() == {}
assert "1" in client.get("/api/apps").json()
resp = client.post("/api/config/servers", headers=DY, json={"name": "测试环境", "ISDEV": "1", "api": "x"})
assert resp.status_code == 200
servers = client.get("/api/config/servers", headers=DY).json()
# 通用项目只保留自定义字段
assert servers["测试环境"] == {"ISDEV": "1", "app_id_prefix": 1}
# Readoor 项目的同名环境不受影响
assert client.get("/api/config/servers").json()["测试环境"]["api"] == "https://test.api.com"
def test_unknown_project_rejected(client, tmp_config):
resp = client.get("/api/apps", headers={"X-Project": "nope"})
assert resp.status_code == 400
def test_required_custom_fields(client, dy_project):
resp = client.post("/api/config/servers", headers=DY, json={"name": "正式环境"})
assert resp.status_code == 400
client.post("/api/config/servers", headers=DY, json={"name": "正式环境", "ISDEV": "0"})
resp = client.post("/api/config/apps", headers=DY, json={"name": "多云选", "server": "正式环境"})
assert resp.status_code == 400
resp = client.post("/api/config/apps", headers=DY,
json={"name": "多云选", "server": "正式环境", "APPID": "1587365345"})
assert resp.status_code == 200
assert resp.json()["id"] == "100"
def test_upload_config_is_shared(client, dy_project):
client.put("/api/config/upload", headers=DY, json={"mode": "webdav"})
assert client.get("/api/config/upload").json()["mode"] == "webdav"
def test_full_config_put_keeps_current_project(client, dy_project):
config = client.get("/api/config", headers=DY).json()
config["branches"] = ["develop"]
config["_project"] = "readoor"
assert client.put("/api/config", headers=DY, json=config).status_code == 200
assert client.get("/api/branches", headers=DY).json() == ["develop"]
assert client.get("/api/branches").json() == ["main", "dev"]
# ---- 项目管理 ----
def test_update_project_keeps_password_when_empty(client, dy_project, tmp_config):
resp = client.put("/api/config/projects/dyauction",
json={"name": "多云选拍卖", "git": {"remote_url": "https://git.example.com/dy2.git", "username": "bot"}})
assert resp.status_code == 200
dy = _root(tmp_config)["projects"]["dyauction"]
assert dy["name"] == "多云选拍卖"
assert dy["git"]["password"] == "secret"
assert dy["git"]["remote_url"].endswith("dy2.git")
@pytest.mark.parametrize("payload", [
{"id": "Bad ID"},
{"id": "readoor"},
{"id": "x1", "xcode": {"workspace": "X.xcworkspace"}}, # 通用替换需要 project
{"id": "x2", "xcode": {"project": "X.xcodeproj"}, "app_fields": [{"key": "server"}]},
{"id": "x3", "xcode": {"project": "X.xcodeproj"}, "patch_rules": [{"type": "define", "file": "../a.h", "name": "A"}]},
{"id": "x4", "xcode": {"project": "X.xcodeproj"}, "patch_rules": [{"type": "sed"}]},
])
def test_create_project_validation(client, tmp_config, payload):
assert client.post("/api/config/projects", json=payload).status_code == 400
def test_delete_project_keeps_last(client, dy_project):
assert client.delete("/api/config/projects/dyauction").status_code == 200
assert client.delete("/api/config/projects/readoor").status_code == 400
def test_project_management_requires_admin(client, tmp_config):
client.post("/api/users", json={"username": "builder", "password": "builder-password-123", "is_admin": False})
token = client.post("/api/auth/login",
json={"username": "builder", "password": "builder-password-123"}).json()["token"]
headers = {"Authorization": f"Bearer {token}"}
assert client.get("/api/config/projects", headers=headers).status_code == 403
assert client.post("/api/config/projects", json=DY_PROJECT, headers=headers).status_code == 403
assert client.get("/api/projects", headers=headers).status_code == 200
# ---- 任务 ----
def _create_dy_app(client):
client.post("/api/config/servers", headers=DY, json={"name": "正式环境", "ISDEV": "0"})
client.post("/api/config/schemes", headers=DY, json={"name": "DyAuction", "ossFloder": "dy"})
resp = client.post("/api/config/apps", headers=DY, json={
"name": "多云选", "server": "正式环境", "APPID": "1587365345",
"certificates": {"Ad_Hoc": {"name": "cn.touchv.auction", "cer": "c", "pro": "p"}},
})
return resp.json()["id"]
def test_task_belongs_to_project(client, dy_project):
app_id = _create_dy_app(client)
with patch("backend.services.build_queue.build_queue.submit", new_callable=AsyncMock):
resp = client.post("/api/tasks", headers=DY, json={
"app_id": app_id, "build_type": "Ad_Hoc", "scheme_id": "1", "branch": "main",
})
assert resp.status_code == 200, resp.text
assert resp.json()["project_id"] == "dyauction"
assert len(client.get("/api/tasks", headers=DY).json()) == 1
assert client.get("/api/tasks").json() == []
def test_task_rejects_obfuscation_when_unsupported(client, dy_project):
app_id = _create_dy_app(client)
resp = client.post("/api/tasks", headers=DY, json={
"app_id": app_id, "build_type": "Ad_Hoc", "scheme_id": "1", "branch": "main", "obfuscation": True,
})
assert resp.status_code == 400
def test_generic_project_does_not_restrict_schemes(client, dy_project):
_create_dy_app(client)
apps = client.get("/api/apps", headers=DY).json()
assert all(app["allowed_scheme_names"] == [] for app in apps.values())
# ---- 源码目录 ----
def test_project_source_uses_own_git_settings():
source = get_project_source("dyauction", DY_PROJECT)
assert source.remote_url == "https://git.example.com/dy.git"
assert source.remote_url_with_credentials == "https://bot:secret@git.example.com/dy.git"
assert source.shared_dir.parts[-2:] == ("sources", "dyauction")
assert source.manual_base is None
def test_legacy_project_source_falls_back_to_env():
with patch("backend.projects.GIT_REMOTE_URL", "https://env.example.com/r.git"), \
patch("backend.projects.GIT_USERNAME", "env"), patch("backend.projects.GIT_PASSWORD", ""):
source = get_project_source("readoor", {})
assert source.remote_url_with_credentials == "https://env@env.example.com/r.git"
assert source.manual_base is not None
async def test_build_uses_xcodeproj_when_no_workspace(tmp_path):
from backend.services.build_service import build_project
from backend.services.log_streamer import LogStreamer
proc = AsyncMock(returncode=0)
proc.wait = AsyncMock(return_value=0)
async def _stdout():
yield b"ok\n"
def _make(*args, **kwargs):
proc.stdout = _stdout()
return proc
with patch("backend.services.build_service.log_streamer", LogStreamer()), \
patch("asyncio.create_subprocess_exec", side_effect=_make) as mock_exec:
with pytest.raises(Exception, match="未找到 IPA 文件"):
await build_project("t1", MagicMock(), {"SCHEME": "DyAuction"}, tmp_path,
{"workspace": "", "project": "DyAuction.xcodeproj"})
archive_args = mock_exec.call_args_list[1].args
assert ("-project", "DyAuction.xcodeproj") == archive_args[2:4]
# ---- 通用配置替换 ----
PBXPROJ = """
A1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CURRENT_PROJECT_VERSION = 1.2.25;
DEVELOPMENT_TEAM = AAA;
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = BBB;
MARKETING_VERSION = 1.2.25;
PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.auction;
PROVISIONING_PROFILE_SPECIFIER = duoyunxuan;
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = TouchLinked_adHoc;
};
name = Release;
};
A2 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.DyAuctionTests;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/DyAuction.app/DyAuction";
};
name = Release;
};
"""
MACRO = """#define APPCHEME @"cntouchauction"
#define ISDEV 1
#if ISDEV
//#define APPID @"1587429852"
#define APPID @"1587026338"
#else
#define APPID @"1587365345"
#endif
"""
@pytest.fixture
def dy_build_dir(tmp_path):
(tmp_path / "DyAuction.xcodeproj").mkdir()
(tmp_path / "DyAuction.xcodeproj" / "project.pbxproj").write_text(PBXPROJ)
(tmp_path / "DyAuction" / "Public").mkdir(parents=True)
(tmp_path / "DyAuction" / "Public" / "DyConstantsMacro.h").write_text(MACRO)
return tmp_path
def _dy_config(**overrides):
config = {
"VERSION": "1.2.26", "BUILD_VERSION": "1.2.26.1", "BUILD_TYPE": "Ad_Hoc",
"BUNDLE_ID": "cn.touchv.auction2", "TEAM_ID": "MG4Z7FU83W", "PROVISIONING_NAME": "Dy AdHoc",
"CERTIFICATE": "Apple Distribution", "APP_VARS": {"APPID": "1587000000"}, "SERVER_VARS": {"ISDEV": "0"},
}
config.update(overrides)
return config
def test_generic_patcher_replaces_macros_and_settings(dy_build_dir):
messages = apply_project_config(dy_build_dir, _dy_config(), DY_PROJECT)
macro = (dy_build_dir / "DyAuction" / "Public" / "DyConstantsMacro.h").read_text()
assert "#define ISDEV 0\n" in macro
assert macro.count('#define APPID @"1587000000"') == 2
assert '//#define APPID @"1587429852"' in macro
pbx = (dy_build_dir / "DyAuction.xcodeproj" / "project.pbxproj").read_text()
assert "MARKETING_VERSION = 1.2.26;" in pbx
assert "CURRENT_PROJECT_VERSION = 1.2.26.1;" in pbx
assert "PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.auction2;" in pbx
assert "PRODUCT_BUNDLE_IDENTIFIER = cn.touchv.DyAuctionTests;" in pbx
assert '"DEVELOPMENT_TEAM[sdk=iphoneos*]" = MG4Z7FU83W;' in pbx
assert '"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "Dy AdHoc";' in pbx
assert '"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";' in pbx
assert (dy_build_dir / "exportOptions.plist").exists()
assert any("ISDEV 0" in line for line in messages)
def test_generic_patcher_requires_template_values(dy_build_dir):
with pytest.raises(ProjectPatchError, match="app.APPID"):
apply_project_config(dy_build_dir, _dy_config(APP_VARS={"APPID": ""}), DY_PROJECT)
def test_generic_patcher_reports_missing_define(dy_build_dir):
project = {**DY_PROJECT, "patch_rules": [
{"type": "define", "file": "DyAuction/Public/DyConstantsMacro.h", "name": "NOPE", "value": "1"},
]}
with pytest.raises(ProjectPatchError, match="NOPE"):
apply_project_config(dy_build_dir, _dy_config(), project)
def test_generic_patcher_replace_line_rule(dy_build_dir):
project = {**DY_PROJECT, "patch_rules": [
{"type": "replace_line", "file": "DyAuction/Public/DyConstantsMacro.h",
"keyword": "APPCHEME", "line": '#define APPCHEME @"${BUNDLE_ID}"'},
]}
apply_project_config(dy_build_dir, _dy_config(), project)
macro = (dy_build_dir / "DyAuction" / "Public" / "DyConstantsMacro.h").read_text()
assert '#define APPCHEME @"cn.touchv.auction2"' in macro