Compare commits
20
Commits
1.2.0
...
10c39b5116
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10c39b5116 | ||
|
|
a4cd855b0c | ||
|
|
9c0b677d38 | ||
|
|
6890f13aa9 | ||
|
|
8f2f23682f | ||
|
|
2bd5c7057f | ||
|
|
74ff4701d6 | ||
|
|
9465c98859 | ||
|
|
5582aadc09 | ||
|
|
6867a3cb01 | ||
|
|
9b4667cab5 | ||
|
|
bf7a5a0449 | ||
|
|
dae14a8a10 | ||
|
|
9ace2c8aca | ||
|
|
fa559101b9 | ||
|
|
e10afb180d | ||
|
|
082c487cf8 | ||
|
|
1466e24c83 | ||
|
|
c17b7d5ad9 | ||
|
|
84a2d3db01 |
@@ -26,11 +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
|
||||
- `frontend/src/views/` — BuildView, HistoryView, ConfigView
|
||||
- `config.json` — runtime config (apps, schemes, servers, upload, branches, versions) managed via web UI
|
||||
- Versions are per-track: `release` (master/develop, build number auto-increments on App_Store) and `feature` (self-test, never increments); each branch's track lives in `config["branch_track"]`
|
||||
- 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
|
||||
|
||||
## Conventions
|
||||
|
||||
- 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)
|
||||
- Chinese UI and documentation throughout
|
||||
|
||||
@@ -182,26 +182,80 @@ GIT_PASSWORD=<仅 read_repository 权限的 Personal Access Token>
|
||||
>
|
||||
> 导入后即可继续在后台增删改。
|
||||
|
||||
> 旧的单项目 `config.json`(顶层直接是 apps / servers …)启动后自动迁移为项目 `readoor`,原文件备份为 `config.json.bak`。
|
||||
|
||||
| 配置项 | 说明 |
|
||||
|--------|------|
|
||||
| 项目管理 | 多项目:每个项目独立的 Git 仓库、Xcode 工程、配置替换方式;见下「多项目」 |
|
||||
| App 管理 | 应用名称、Scheme、服务器环境、upload_key 等 |
|
||||
| Scheme 管理 | 打包 Scheme 配置 |
|
||||
| 服务器环境 | 测试/正式/自定义环境的 API 地址、Universal Link 等 |
|
||||
| 分支管理 | 可打包的代码分支列表,以及每个分支所属的版本轨道 |
|
||||
| 分支管理 | 可打包的代码分支和 Tag 列表,以及各自的版本轨道类型(上架 / 自测);Tag 打包时以游离 HEAD 检出 `refs/tags/<tag>` |
|
||||
| 版本号 | 服务端统一管理 App_Ver 和 Build_Ver,不修改分支源码;按版本轨道分开管理(见下) |
|
||||
| 上传配置 | 服务端内置 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 各自独立填写、互不影响:
|
||||
**每个分支各有一条版本轨道(track)**,App_Ver 与构建号完全独立、互不影响。轨道名即分支名(master / main 沿用历史名称 `release`),轨道类型 `kind` 决定构建号行为:
|
||||
|
||||
| 轨道 | 适用分支 | 构建号行为 |
|
||||
|------|----------|-----------|
|
||||
| `release`(上架) | master、develop(共用同一套版本号与构建号序列) | App_Store 打包时按当前 App_Ver 自动 +1 |
|
||||
| `feature`(自测) | feature/* 等其他分支 | 永不自增,始终使用配置页填写的值(默认 `.0`) |
|
||||
| 轨道类型 | 默认适用分支 | 构建号行为 |
|
||||
|----------|--------------|-----------|
|
||||
| `release`(上架) | master、main、develop、dev、release-*、hotfix-* | App_Store 打包时按当前 App_Ver 自动 +1 |
|
||||
| `feature`(自测) | 其余分支 | 永不自增,始终使用配置页填写的值(默认 `.0`) |
|
||||
|
||||
- 分支归属默认按名字推断(master/main/develop/dev/release-*/hotfix-* → release,其余 → feature),可在「分支管理」页逐个改。
|
||||
```jsonc
|
||||
"versions": {
|
||||
"tracks": {
|
||||
"release": { "kind": "release", "app_ver": "2.195.0", "build_map": { "2.195.0": 7 } }, // master
|
||||
"develop": { "kind": "release", "app_ver": "2.196.0", "build_map": {} },
|
||||
"feature/login": { "kind": "feature", "app_ver": "2.100.0", "build_map": {} }
|
||||
}
|
||||
},
|
||||
"branch_track": { "master": "release", "develop": "develop", "feature/login": "feature/login" }
|
||||
```
|
||||
|
||||
- 新增分支时自动建一条同名轨道,类型按分支名推断,可在「分支管理」页逐个改(只改构建号是否自增,版本号仍各自独立)。
|
||||
- Tag 存在 `config["tags"]`,与分支不可重名,同样在 `branch_track` 中各有一条同名轨道,新增时默认为上架轨。
|
||||
- 「打包设置」页按分支分块填写版本号。
|
||||
- 每条轨道内的构建号按 App_Ver 独立记录(`build_map`),回退到打过包的旧版本号时会从它自己的最大值继续,不会与 App Store Connect 上已传构建号冲突。
|
||||
- App Store 的构建号唯一性按 App_Ver 全局判定,因此两个上架分支若临时用了同一个 App_Ver,递增时会跨轨道取最大值 +1,避免重号被拒。
|
||||
- 旧配置(master/develop 共用的 `release` 轨、各自测分支共用的 `feature` 轨)首次启动时自动拆开:master 留在 `release` 轨,其余分支新建同名轨道并复制一份已用构建号。
|
||||
- 需要两个分支共用同一条版本线时,可直接把 `branch_track` 里的值指向另一条轨道名。
|
||||
|
||||
### 服务端自动化资源
|
||||
|
||||
|
||||
+16
-14
@@ -57,27 +57,29 @@ GIT_USERNAME = os.getenv("GIT_USERNAME", "")
|
||||
GIT_PASSWORD = os.getenv("GIT_PASSWORD", "")
|
||||
|
||||
|
||||
def get_git_remote_url(with_credentials: bool = False) -> str:
|
||||
"""获取 Git 远程地址,可选注入用户名密码"""
|
||||
if not with_credentials or not GIT_REMOTE_URL or not GIT_USERNAME:
|
||||
return GIT_REMOTE_URL
|
||||
if "://" not in GIT_REMOTE_URL:
|
||||
return GIT_REMOTE_URL
|
||||
def inject_git_credentials(url: str, username: str, password: str = "") -> str:
|
||||
"""向 http(s) 形式的 Git 地址注入用户名密码;已带凭证或非 URL 形式时原样返回"""
|
||||
if not url or not username or "://" not in url:
|
||||
return url
|
||||
|
||||
parts = urlsplit(GIT_REMOTE_URL)
|
||||
parts = urlsplit(url)
|
||||
if "@" in parts.netloc:
|
||||
return GIT_REMOTE_URL
|
||||
return url
|
||||
|
||||
username = quote(GIT_USERNAME, safe="")
|
||||
if GIT_PASSWORD:
|
||||
password = quote(GIT_PASSWORD, safe="")
|
||||
auth = f"{username}:{password}"
|
||||
else:
|
||||
auth = username
|
||||
auth = quote(username, safe="")
|
||||
if password:
|
||||
auth = f"{auth}:{quote(password, safe='')}"
|
||||
netloc = f"{auth}@{parts.netloc}"
|
||||
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:
|
||||
"""对 Git 远程地址中的凭证做脱敏"""
|
||||
if not url or "://" not in url:
|
||||
|
||||
@@ -23,8 +23,11 @@ def _migrate_db():
|
||||
"""简单的数据库迁移:为旧表添加缺失的列"""
|
||||
migrations = [
|
||||
("tasks", "branch", "VARCHAR DEFAULT 'main'"),
|
||||
("tasks", "ref_type", "VARCHAR DEFAULT 'branch'"),
|
||||
("tasks", "error_category", "VARCHAR"),
|
||||
("tasks", "superseded_at", "TIMESTAMP"),
|
||||
("tasks", "dsym_url", "VARCHAR"),
|
||||
("tasks", "project_id", "VARCHAR DEFAULT 'readoor'"),
|
||||
]
|
||||
with engine.connect() as conn:
|
||||
for table, column, col_type in migrations:
|
||||
|
||||
+14
-1
@@ -12,6 +12,7 @@ from .routers import config, apps, tasks, auth, users, operations
|
||||
from .services.log_streamer import log_streamer
|
||||
from .config import BACKEND_PORT, CORS_ALLOWED_ORIGINS, TRUSTED_HOSTS, validate_production_security
|
||||
from .deps import decode_current_user
|
||||
from .projects import PROJECT_HEADER, current_project_id
|
||||
|
||||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
|
||||
@@ -37,11 +38,23 @@ if CORS_ALLOWED_ORIGINS:
|
||||
allow_origins=CORS_ALLOWED_ORIGINS,
|
||||
allow_credentials=False,
|
||||
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.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(users.router)
|
||||
|
||||
+4
-1
@@ -9,13 +9,15 @@ class Task(Base):
|
||||
__tablename__ = "tasks"
|
||||
|
||||
id = Column(String, primary_key=True)
|
||||
project_id = Column(String, default="readoor") # 所属项目,见 projects.py
|
||||
app_id = Column(String, nullable=False)
|
||||
app_name = Column(String, nullable=False)
|
||||
build_type = Column(String, nullable=False)
|
||||
scheme_id = Column(String, nullable=False)
|
||||
scheme_name = Column(String, nullable=False)
|
||||
obfuscation = Column(Boolean, default=False)
|
||||
branch = Column(String, default="main")
|
||||
branch = Column(String, default="main") # 分支名或 Tag 名,由 ref_type 区分
|
||||
ref_type = Column(String, default="branch") # branch/tag
|
||||
|
||||
# 状态
|
||||
status = Column(String, default="pending") # pending/running/completed/failed/cancelled
|
||||
@@ -32,6 +34,7 @@ class Task(Base):
|
||||
ipa_path = Column(String)
|
||||
oss_url = Column(String)
|
||||
dsym_path = Column(String)
|
||||
dsym_url = Column(String)
|
||||
obfuscation_maps_path = Column(String)
|
||||
qr_code_path = Column(String)
|
||||
build_dir = Column(String)
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""多项目定义:每个项目的源码仓库、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, # 是否支持代码混淆
|
||||
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||
# 本项目钉钉 @ 名单,为空则用 upload.dingtalk 的全局名单
|
||||
# —— 项目数据(与原单项目时的顶层字段相同)——
|
||||
"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", "dingtalk_at",
|
||||
)
|
||||
|
||||
# 原单项目(阅门户)的定义,迁移旧配置时写入。
|
||||
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,
|
||||
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||
}
|
||||
|
||||
# 当前请求操作的项目,由 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,
|
||||
"dingtalk_at": {"at_mobiles": [], "at_mobiles_app_store": []},
|
||||
}
|
||||
|
||||
|
||||
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 {})}
|
||||
definition["dingtalk_at"] = {**defaults["dingtalk_at"], **(definition.get("dingtalk_at") 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,
|
||||
)
|
||||
+24
-5
@@ -1,7 +1,9 @@
|
||||
"""打包选择 API"""
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from .config import 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"])
|
||||
|
||||
@@ -15,11 +17,22 @@ _APP_SCHEME_RULES = {
|
||||
_DEFAULT_SCHEME_NAMES = ("readoor31", "readoor31OtherPay")
|
||||
|
||||
|
||||
def get_allowed_scheme_names(app: dict) -> tuple[str, ...]:
|
||||
"""返回 App 可使用的 Scheme 名称。"""
|
||||
def get_allowed_scheme_names(app: dict, config: dict) -> tuple[str, ...]:
|
||||
"""返回 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)
|
||||
|
||||
|
||||
@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")
|
||||
async def get_apps_for_build():
|
||||
"""获取 apps 列表(供打包选择)"""
|
||||
@@ -27,7 +40,7 @@ async def get_apps_for_build():
|
||||
apps = {}
|
||||
for app_id, app in config.get("apps", {}).items():
|
||||
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
|
||||
return apps
|
||||
|
||||
@@ -44,3 +57,9 @@ async def get_branches_for_build():
|
||||
"""获取分支列表(供打包选择)"""
|
||||
config = load_config()
|
||||
return config.get("branches", ["main"])
|
||||
|
||||
|
||||
@router.get("/tags")
|
||||
async def get_tags_for_build():
|
||||
"""获取 Tag 列表(供打包选择)"""
|
||||
return get_tags(load_config())
|
||||
|
||||
+631
-113
@@ -1,5 +1,6 @@
|
||||
"""配置管理 API"""
|
||||
import asyncio
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -23,6 +24,18 @@ from ..config import (
|
||||
SKINS_DIR,
|
||||
)
|
||||
from ..deps import get_current_user, require_admin
|
||||
from ..services.notification import AT_MOBILES_KEYS, normalize_mobiles
|
||||
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:
|
||||
@@ -51,13 +64,15 @@ DEFAULT_UPLOAD = {
|
||||
"server_url": "",
|
||||
"username": "",
|
||||
"password": "",
|
||||
"base_path": "/ios-builds",
|
||||
"base_path": "/",
|
||||
"public_url": "",
|
||||
},
|
||||
"dingtalk": {
|
||||
"enabled": False,
|
||||
"webhook_url": "",
|
||||
"secret": "",
|
||||
"at_mobiles": [],
|
||||
"at_mobiles_app_store": [],
|
||||
},
|
||||
}
|
||||
|
||||
@@ -91,74 +106,180 @@ DEFAULT_SERVERS = {
|
||||
|
||||
DEFAULT_APP_VER = "2.180.0"
|
||||
|
||||
# 版本轨道:上架分支(master/develop)共用 release,自测分支(feature/*)用 feature。
|
||||
# 两条轨道的 App_Ver 各自独立填写,互不影响。
|
||||
TRACK_RELEASE = "release"
|
||||
TRACK_FEATURE = "feature"
|
||||
TRACKS = (TRACK_RELEASE, TRACK_FEATURE)
|
||||
# 版本轨道:每个分支各有一条独立轨道,轨道名即分支名(master/main 沿用历史名称 release),
|
||||
# 各分支的 App_Ver 与构建号互不影响。轨道类型(kind)决定构建号行为:
|
||||
# release(上架)— App_Store 打包时自增;feature(自测)— 永不自增。
|
||||
KIND_RELEASE = "release"
|
||||
KIND_FEATURE = "feature"
|
||||
KINDS = (KIND_RELEASE, KIND_FEATURE)
|
||||
TRACK_RELEASE = "release" # master/main 的轨道名(沿用旧名,历史构建号原地保留)
|
||||
TRACK_FEATURE = "feature" # 旧版所有自测分支共用的轨道名,迁移时按分支拆开
|
||||
FIXED_TRACKS = (TRACK_RELEASE, TRACK_FEATURE)
|
||||
|
||||
# 按名字推断轨道的默认规则;config["branch_track"] 中的显式配置优先。
|
||||
RELEASE_BRANCH_NAMES = {"master", "main", "develop", "dev"}
|
||||
# 按名字推断轨道类型的默认规则;轨道记录里的 kind 为准,此处只用于新建轨道。
|
||||
MASTER_BRANCH_NAMES = {"master", "main"}
|
||||
RELEASE_BRANCH_NAMES = MASTER_BRANCH_NAMES | {"develop", "dev"}
|
||||
RELEASE_BRANCH_PREFIXES = ("release/", "release-", "hotfix/", "hotfix-")
|
||||
|
||||
# 可打包的代码引用类型:分支在 config["branches"],Tag 在 config["tags"],两者名字不可重复,
|
||||
# 因此任务里只存名字即可反查类型;分支与 Tag 共用 branch_track 映射各自的版本轨道。
|
||||
REF_BRANCH = "branch"
|
||||
REF_TAG = "tag"
|
||||
|
||||
|
||||
def get_tags(config: dict) -> list:
|
||||
"""取可打包的 Tag 列表。"""
|
||||
tags = config.get("tags")
|
||||
return tags if isinstance(tags, list) else []
|
||||
|
||||
|
||||
def get_ref_type(config: dict, name: str) -> str:
|
||||
"""按名字判断是分支还是 Tag。"""
|
||||
return REF_TAG if name in get_tags(config) else REF_BRANCH
|
||||
|
||||
|
||||
def _build_refs(config: dict) -> list:
|
||||
"""所有可打包的引用(分支在前,Tag 在后)。"""
|
||||
return list(config.get("branches", []) or []) + get_tags(config)
|
||||
|
||||
|
||||
def _is_release_branch(branch: str) -> bool:
|
||||
"""按分支名推断是否为上架分支。"""
|
||||
name = (branch or "").strip().lower()
|
||||
return name in RELEASE_BRANCH_NAMES or name.startswith(RELEASE_BRANCH_PREFIXES)
|
||||
|
||||
|
||||
def _default_kind_for_branch(branch: str) -> str:
|
||||
"""新建轨道时按分支名推断轨道类型。"""
|
||||
return KIND_RELEASE if _is_release_branch(branch) else KIND_FEATURE
|
||||
|
||||
|
||||
def _default_kind_for_ref(config: dict, name: str) -> str:
|
||||
"""新建轨道时的缺省类型:Tag 一般用于重打已发布的版本,默认上架轨;分支按名字推断。"""
|
||||
if get_ref_type(config, name) == REF_TAG:
|
||||
return KIND_RELEASE
|
||||
return _default_kind_for_branch(name)
|
||||
|
||||
|
||||
def _default_track_for_branch(branch: str) -> str:
|
||||
"""按分支名推断所属版本轨道。"""
|
||||
name = (branch or "").strip().lower()
|
||||
if name in RELEASE_BRANCH_NAMES or name.startswith(RELEASE_BRANCH_PREFIXES):
|
||||
"""分支自己的轨道名:master/main 沿用历史名 release,其余即分支名。
|
||||
|
||||
分支恰好叫 release / feature(且不是 master)时加前缀避让,免得撞上固定轨道名。
|
||||
"""
|
||||
if (branch or "").strip().lower() in MASTER_BRANCH_NAMES:
|
||||
return TRACK_RELEASE
|
||||
return TRACK_FEATURE
|
||||
return f"branch:{branch}" if branch in FIXED_TRACKS else branch
|
||||
|
||||
|
||||
def _new_track(app_ver: str = DEFAULT_APP_VER) -> dict:
|
||||
def _new_track(app_ver: str = DEFAULT_APP_VER, kind: str = KIND_RELEASE) -> dict:
|
||||
# 每个版本号(App_Ver)独立记录已用到的最大构建号第四位。
|
||||
# App Store 的构建号唯一性按 MARKETING_VERSION(即完整 App_Ver) 分别计算,
|
||||
# 因此必须按版本号分别记录,回退到旧版本号时才能从它自己的最大值继续递增。
|
||||
return {"app_ver": app_ver, "build_map": {}}
|
||||
return {"kind": kind, "app_ver": app_ver, "build_map": {}}
|
||||
|
||||
|
||||
def _seed_track(tracks: dict, kind: str, legacy: dict = None) -> dict:
|
||||
"""新建轨道的初值:优先沿用被拆分的旧共用轨(含已用构建号),
|
||||
否则沿用任一同类型轨道的 App_Ver,都没有则用默认版本号。"""
|
||||
if legacy:
|
||||
return {"kind": kind, "app_ver": legacy["app_ver"], "build_map": dict(legacy["build_map"])}
|
||||
for track in tracks.values():
|
||||
if isinstance(track, dict) and track.get("kind") == kind:
|
||||
return _new_track(track.get("app_ver") or DEFAULT_APP_VER, kind)
|
||||
return _new_track(kind=kind)
|
||||
|
||||
|
||||
def _ensure_track(config: dict, track_name: str, kind: str = None) -> dict:
|
||||
"""确保轨道存在(新建时沿用同类型轨道的 App_Ver,构建号从 .0 起);
|
||||
显式传 kind 时同时把轨道类型改成它。"""
|
||||
tracks = config.setdefault("versions", {}).setdefault("tracks", {})
|
||||
track = tracks.get(track_name)
|
||||
if not isinstance(track, dict):
|
||||
track = tracks[track_name] = _seed_track(
|
||||
tracks, kind or _default_kind_for_track(track_name)
|
||||
)
|
||||
elif kind:
|
||||
track["kind"] = kind
|
||||
return track
|
||||
|
||||
|
||||
def _default_kind_for_track(track_name: str) -> str:
|
||||
"""轨道记录缺 kind 时按轨道名推断(轨道名即分支名)。"""
|
||||
if track_name == TRACK_RELEASE:
|
||||
return KIND_RELEASE
|
||||
if track_name == TRACK_FEATURE:
|
||||
return KIND_FEATURE
|
||||
return _default_kind_for_branch(track_name)
|
||||
|
||||
|
||||
def _legacy_single_track(versions: dict) -> dict:
|
||||
"""把最旧的单轨结构读成 {app_ver, build_map}。"""
|
||||
app_ver = versions.get("app_ver") or DEFAULT_APP_VER
|
||||
build_map = versions.get("build_map")
|
||||
if not isinstance(build_map, dict):
|
||||
build_map = {}
|
||||
# 更旧的单值形式 "2.195.0.3" → {"2.195.0": 3}
|
||||
old = versions.get("build_ver")
|
||||
if isinstance(old, str):
|
||||
parts = old.split(".")
|
||||
if len(parts) >= 4 and parts[3].isdigit():
|
||||
build_map[".".join(parts[:3])] = int(parts[3])
|
||||
versions.pop("app_ver", None)
|
||||
versions.pop("build_map", None)
|
||||
versions.pop("build_ver", None)
|
||||
return {"app_ver": app_ver, "build_map": build_map}
|
||||
|
||||
|
||||
def _legacy_shared_track(tracks: dict, name: str) -> dict:
|
||||
"""取出待拆分的旧共用轨(迁移后的轨道都带 kind,没有 kind 的即旧共用轨)。"""
|
||||
track = tracks.get(name)
|
||||
if not isinstance(track, dict) or "kind" in track:
|
||||
return None
|
||||
build_map = track.get("build_map")
|
||||
return {
|
||||
"app_ver": track.get("app_ver") or DEFAULT_APP_VER,
|
||||
"build_map": build_map if isinstance(build_map, dict) else {},
|
||||
}
|
||||
|
||||
|
||||
def _ensure_versions(config: dict) -> bool:
|
||||
"""确保 versions 为双轨结构,并迁移旧式单轨/单值 build_ver 配置。
|
||||
"""确保 versions 为「每个分支一条轨道」结构,并迁移旧配置。
|
||||
|
||||
旧式 ``{"app_ver": ..., "build_map": ...}`` 整体迁入 release 轨;
|
||||
feature 轨用同一个 App_Ver 初始化,构建号从 .0 起且永不自增。
|
||||
旧式单轨 ``{"app_ver": ..., "build_map": ...}``、旧的 master/develop 共用
|
||||
``release`` 轨和所有自测分支共用的 ``feature`` 轨,都会按分支拆开:
|
||||
master/main 留在 release 轨(历史构建号原地保留),其余分支新建以分支名命名的
|
||||
轨道并复制一份已用构建号,使拆分后每个分支都从原来的构建号继续。
|
||||
"""
|
||||
versions = config.get("versions")
|
||||
changed = False
|
||||
|
||||
if not isinstance(versions, dict):
|
||||
config["versions"] = {"tracks": {TRACK_RELEASE: _new_track(), TRACK_FEATURE: _new_track()}}
|
||||
return True
|
||||
|
||||
tracks = versions.get("tracks")
|
||||
if not isinstance(tracks, dict):
|
||||
# 旧式单轨结构 → release 轨
|
||||
legacy_app_ver = versions.get("app_ver") or DEFAULT_APP_VER
|
||||
legacy_build_map = versions.get("build_map")
|
||||
if not isinstance(legacy_build_map, dict):
|
||||
legacy_build_map = {}
|
||||
# 更旧的单值形式 "2.195.0.3" → {"2.195.0": 3}
|
||||
old = versions.get("build_ver")
|
||||
if isinstance(old, str):
|
||||
parts = old.split(".")
|
||||
if len(parts) >= 4 and parts[3].isdigit():
|
||||
legacy_build_map[".".join(parts[:3])] = int(parts[3])
|
||||
versions.pop("app_ver", None)
|
||||
versions.pop("build_map", None)
|
||||
versions.pop("build_ver", None)
|
||||
tracks = {
|
||||
TRACK_RELEASE: {"app_ver": legacy_app_ver, "build_map": legacy_build_map},
|
||||
TRACK_FEATURE: _new_track(legacy_app_ver),
|
||||
}
|
||||
versions["tracks"] = tracks
|
||||
versions = {}
|
||||
config["versions"] = versions
|
||||
changed = True
|
||||
|
||||
for name in TRACKS:
|
||||
track = tracks.get(name)
|
||||
# 待拆分到各分支的旧共用轨(按类型各一条)
|
||||
legacy = {KIND_RELEASE: None, KIND_FEATURE: None}
|
||||
tracks = versions.get("tracks")
|
||||
if not isinstance(tracks, dict):
|
||||
legacy[KIND_RELEASE] = _legacy_single_track(versions)
|
||||
legacy[KIND_FEATURE] = dict(legacy[KIND_RELEASE], build_map={})
|
||||
tracks = {}
|
||||
versions["tracks"] = tracks
|
||||
changed = True
|
||||
else:
|
||||
# release 轨拆分后继续作为 master/main 的轨道,feature 轨拆分后成为无人引用的模板
|
||||
legacy[KIND_RELEASE] = _legacy_shared_track(tracks, TRACK_RELEASE)
|
||||
legacy[KIND_FEATURE] = _legacy_shared_track(tracks, TRACK_FEATURE)
|
||||
splitting = any(legacy.values())
|
||||
split_kinds = set() # 实际被拆分出去的旧共用轨类型
|
||||
|
||||
for name, track in tracks.items():
|
||||
if not isinstance(track, dict):
|
||||
tracks[name] = _new_track()
|
||||
track = tracks[name] = _new_track(kind=_default_kind_for_track(name))
|
||||
changed = True
|
||||
if track.get("kind") not in KINDS:
|
||||
track["kind"] = _default_kind_for_track(name)
|
||||
changed = True
|
||||
continue
|
||||
if not track.get("app_ver"):
|
||||
track["app_ver"] = DEFAULT_APP_VER
|
||||
changed = True
|
||||
@@ -166,33 +287,111 @@ def _ensure_versions(config: dict) -> bool:
|
||||
track["build_map"] = {}
|
||||
changed = True
|
||||
|
||||
# 分支归属:只存显式配置,缺省按名字规则推断
|
||||
# 分支归属:值为轨道名,缺省用分支自己的轨道
|
||||
branch_track = config.get("branch_track")
|
||||
if not isinstance(branch_track, dict):
|
||||
branch_track = {}
|
||||
config["branch_track"] = branch_track
|
||||
changed = True
|
||||
for branch in config.get("branches", []) or []:
|
||||
if branch_track.get(branch) not in TRACKS:
|
||||
branch_track[branch] = _default_track_for_branch(branch)
|
||||
for branch in _build_refs(config):
|
||||
name = branch_track.get(branch)
|
||||
if splitting and name in FIXED_TRACKS:
|
||||
# 旧的共用轨 → 各分支自己的轨道(master/main 仍留在 release 轨)
|
||||
name = _default_track_for_branch(branch)
|
||||
if not isinstance(name, str) or not name:
|
||||
name = _default_track_for_branch(branch)
|
||||
if branch_track.get(branch) != name:
|
||||
branch_track[branch] = name
|
||||
changed = True
|
||||
if name not in tracks:
|
||||
kind = _default_kind_for_ref(config, branch)
|
||||
tracks[name] = _seed_track(tracks, kind, legacy[kind])
|
||||
if legacy[kind]:
|
||||
split_kinds.add(kind)
|
||||
changed = True
|
||||
|
||||
# 内容已复制到各分支轨道、又没有分支引用的旧共用轨,直接删掉,免得配置里留下无用条目
|
||||
for name in FIXED_TRACKS:
|
||||
kind = _default_kind_for_track(name)
|
||||
if kind in split_kinds and name in tracks and name not in branch_track.values():
|
||||
tracks.pop(name)
|
||||
changed = True
|
||||
|
||||
return changed
|
||||
|
||||
|
||||
def _primary_track_name(config: dict) -> str:
|
||||
"""主上架轨:第一个上架分支(kind=release)所属的轨道;都没有则取第一个分支的轨道。
|
||||
|
||||
仅用于顶层 app_ver/build_ver 的兼容字段和未指定轨道时的缺省值。
|
||||
"""
|
||||
fallback = TRACK_RELEASE
|
||||
for index, branch in enumerate(config.get("branches", []) or []):
|
||||
name = get_track_name(config, branch)
|
||||
if index == 0:
|
||||
fallback = name
|
||||
if is_release_track(get_track(config, name)):
|
||||
return name
|
||||
return fallback
|
||||
|
||||
|
||||
def get_track_name(config: dict, branch: str) -> str:
|
||||
"""取分支所属的版本轨道名。"""
|
||||
track = (config.get("branch_track") or {}).get(branch)
|
||||
return track if track in TRACKS else _default_track_for_branch(branch)
|
||||
name = (config.get("branch_track") or {}).get(branch)
|
||||
tracks = (config.get("versions") or {}).get("tracks") or {}
|
||||
if isinstance(name, str) and name in tracks:
|
||||
return name
|
||||
return _default_track_for_branch(branch)
|
||||
|
||||
|
||||
def get_track(config: dict, track_name: str) -> dict:
|
||||
"""取某条轨道的版本记录(不存在时返回默认值,不写回配置)。"""
|
||||
"""取某条轨道的版本记录副本(不存在时返回默认值;只读,不写回配置)。
|
||||
|
||||
未迁移的旧记录没有 kind,按轨道名(即分支名)推断补上。
|
||||
"""
|
||||
tracks = (config.get("versions") or {}).get("tracks") or {}
|
||||
track = tracks.get(track_name)
|
||||
kind = _default_kind_for_track(track_name)
|
||||
if not isinstance(track, dict):
|
||||
return _new_track()
|
||||
return track
|
||||
return _new_track(kind=kind)
|
||||
return {**track, "kind": track.get("kind") if track.get("kind") in KINDS else kind}
|
||||
|
||||
|
||||
def is_release_track(track: dict) -> bool:
|
||||
"""该轨道是否为上架轨(App_Store 打包时构建号自增)。"""
|
||||
return track.get("kind", KIND_RELEASE) == KIND_RELEASE
|
||||
|
||||
|
||||
def next_build_no(tracks: dict, app_ver: str) -> int:
|
||||
"""该 App_Ver 下一个可用的构建号。
|
||||
|
||||
构建号唯一性由 App Store 按 MARKETING_VERSION 全局判定,与分支无关,
|
||||
因此取所有上架轨在这个版本号上已用到的最大值再 +1,避免两个上架分支
|
||||
临时使用同一 App_Ver 时产生重复构建号被拒。
|
||||
"""
|
||||
used = [
|
||||
int((track.get("build_map") or {}).get(app_ver, 0))
|
||||
for track in tracks.values()
|
||||
if isinstance(track, dict) and is_release_track(track)
|
||||
]
|
||||
return max(used, default=0) + 1
|
||||
|
||||
|
||||
def resolve_track(config: dict, branch: str, track: str, default_kind: str = None):
|
||||
"""把用户传入的轨道值解析为 (轨道名, 轨道类型)。
|
||||
|
||||
传类型(release / feature)时用分支自己的轨道,并把它设成该类型;
|
||||
也可直接传已存在的轨道名,让这个分支与另一个分支共用同一条版本线(类型不变)。
|
||||
不传时类型取 default_kind,缺省按分支名推断。
|
||||
"""
|
||||
value = (track or "").strip()
|
||||
if not value:
|
||||
return _default_track_for_branch(branch), default_kind or _default_kind_for_branch(branch)
|
||||
if value in KINDS:
|
||||
return _default_track_for_branch(branch), value
|
||||
if value in ((config.get("versions") or {}).get("tracks") or {}):
|
||||
return value, None
|
||||
raise HTTPException(status_code=400, detail=f"未知的版本轨道: {track}")
|
||||
|
||||
|
||||
def track_build_ver(track: dict) -> str:
|
||||
@@ -201,6 +400,7 @@ def track_build_ver(track: dict) -> str:
|
||||
build_map = track.get("build_map") or {}
|
||||
return f"{app_ver}.{int(build_map.get(app_ver, 0))}"
|
||||
|
||||
|
||||
# 为已有环境迁移的固定前缀;后续环境从配置中的 next_app_id_prefix 自动分配。
|
||||
LEGACY_SERVER_PREFIXES = {
|
||||
"测试环境": 1,
|
||||
@@ -300,8 +500,14 @@ def _ensure_upload_keys(config: dict) -> bool:
|
||||
|
||||
|
||||
def _migrate_old_themes(config: dict) -> bool:
|
||||
"""将旧式目录皮肤迁移为 ZIP 存入 data/skins/,返回是否有变更"""
|
||||
changed = False
|
||||
"""将旧式目录皮肤迁移为 ZIP 存入 data/skins/,返回是否有变更。
|
||||
|
||||
仅在首次执行(用旧配置升级时)生效,之后写入标记跳过:否则每次 load_config()
|
||||
都会重新执行——一旦某个皮肤被删除,只要对应证书的 theme 仍引用它、且旧版
|
||||
themes 目录还在,就会被立刻重新生成,导致皮肤包无法真正删除。
|
||||
"""
|
||||
if config.get("_legacy_themes_migrated"):
|
||||
return False
|
||||
themes_dir = AUTOMATION_DIR / "themes"
|
||||
for app_id, app in config.get("apps", {}).items():
|
||||
upload_key = app.get("upload_key", "")
|
||||
@@ -336,31 +542,90 @@ def _migrate_old_themes(config: dict) -> bool:
|
||||
app["skins"] = skins
|
||||
if theme != skin_name:
|
||||
cert["theme"] = skin_name
|
||||
changed = True
|
||||
return changed
|
||||
config["_legacy_themes_migrated"] = True
|
||||
return True
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
"""读取 config.json"""
|
||||
def _default_project_data(project_id: str) -> dict:
|
||||
"""新项目的初始数据;旧项目沿用原单项目时的默认服务器环境。"""
|
||||
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():
|
||||
# 首次部署:优先从项目根目录下的 config.json 导入
|
||||
if BOOTSTRAP_CONFIG_PATH.exists():
|
||||
CONFIG_JSON_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(BOOTSTRAP_CONFIG_PATH, CONFIG_JSON_PATH)
|
||||
else:
|
||||
return {
|
||||
"apps": {}, "schemes": {}, "servers": DEFAULT_SERVERS,
|
||||
"next_app_id_prefix": 5, "branches": ["main"], "upload": DEFAULT_UPLOAD,
|
||||
}
|
||||
root, _ = _migrate_root({})
|
||||
root["upload"] = DEFAULT_UPLOAD
|
||||
return root
|
||||
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:
|
||||
config["servers"] = DEFAULT_SERVERS
|
||||
config["servers"] = _default_project_data(project_id)["servers"]
|
||||
if "branches" not in config:
|
||||
config["branches"] = ["main"]
|
||||
if "upload" not in config:
|
||||
config["upload"] = DEFAULT_UPLOAD
|
||||
versions_changed = _ensure_versions(config)
|
||||
# 自动补齐旧配置的环境前缀、特殊 App 覆盖和 upload_key。
|
||||
prefixes_changed = _ensure_server_id_prefixes(config)
|
||||
@@ -375,12 +640,25 @@ def load_config() -> dict:
|
||||
|
||||
|
||||
def save_config(config: dict):
|
||||
"""保存 config.json(自动备份)"""
|
||||
if CONFIG_JSON_PATH.exists():
|
||||
backup_path = CONFIG_JSON_PATH.with_suffix(".json.bak")
|
||||
shutil.copy2(CONFIG_JSON_PATH, backup_path)
|
||||
with open(CONFIG_JSON_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=2, ensure_ascii=False)
|
||||
"""保存 load_config() 返回的项目配置视图(其中的 upload 为所有项目共用)。"""
|
||||
root = _read_root()
|
||||
project_id = config.get("_project") or resolve_project_id(root)
|
||||
root["projects"][project_id] = {
|
||||
key: value for key, value in config.items() if key not in ("upload", "_project")
|
||||
}
|
||||
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:
|
||||
@@ -391,14 +669,15 @@ def get_build_config_value(db: Session, key: str, default=None) -> str:
|
||||
|
||||
@router.get("")
|
||||
async def get_full_config():
|
||||
"""获取完整 config.json"""
|
||||
"""获取当前项目的完整配置"""
|
||||
return load_config()
|
||||
|
||||
|
||||
@router.put("")
|
||||
async def update_full_config(config: dict):
|
||||
"""更新整个 config.json"""
|
||||
"""更新当前项目的完整配置(upload 为所有项目共用)"""
|
||||
async with _config_lock:
|
||||
config["_project"] = load_config()["_project"]
|
||||
save_config(config)
|
||||
return {"message": "配置已更新"}
|
||||
|
||||
@@ -410,6 +689,25 @@ async def 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")
|
||||
async def create_app(app: dict):
|
||||
"""新增 app"""
|
||||
@@ -418,6 +716,8 @@ async def create_app(app: dict):
|
||||
config = load_config()
|
||||
apps = config.get("apps", {})
|
||||
|
||||
_validate_custom_fields(config, "app_fields", app)
|
||||
|
||||
# 按服务环境自动生成三位 ID(例如测试环境 1xx、正式环境 2xx)。
|
||||
_apply_special_app_prefix_override(app)
|
||||
_normalize_tencent_app_id(app)
|
||||
@@ -443,6 +743,7 @@ async def update_app(app_id: str, app: dict):
|
||||
if app_id not in apps:
|
||||
raise HTTPException(status_code=404, detail="App 不存在")
|
||||
|
||||
_validate_custom_fields(config, "app_fields", app)
|
||||
_normalize_tencent_app_id(app)
|
||||
apps[app_id] = app
|
||||
config["apps"] = apps
|
||||
@@ -644,43 +945,50 @@ async def get_branches():
|
||||
|
||||
@router.post("/branches")
|
||||
async def add_branch(data: dict):
|
||||
"""新增分支,可指定所属版本轨道(缺省按分支名推断)"""
|
||||
"""新增分支,可指定版本轨道类型(缺省按分支名推断)。
|
||||
|
||||
每个分支都有自己独立的一条轨道(轨道名即分支名):track 传 release 表示上架用、
|
||||
App_Store 打包时构建号自增,feature 表示自测用、构建号不自增;
|
||||
也可直接传已有轨道名,让该分支与另一个分支共用同一条版本线。
|
||||
"""
|
||||
name = data.get("name", "").strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="分支名称不能为空")
|
||||
|
||||
track = (data.get("track") or "").strip() or _default_track_for_branch(name)
|
||||
if track not in TRACKS:
|
||||
raise HTTPException(status_code=400, detail=f"未知的版本轨道: {track}")
|
||||
|
||||
async with _config_lock:
|
||||
config = load_config()
|
||||
branches = config.get("branches", ["main"])
|
||||
if name in branches:
|
||||
raise HTTPException(status_code=400, detail="分支已存在")
|
||||
if name in get_tags(config):
|
||||
raise HTTPException(status_code=400, detail="已存在同名 Tag")
|
||||
track, kind = resolve_track(config, name, data.get("track"))
|
||||
branches.append(name)
|
||||
config["branches"] = branches
|
||||
config.setdefault("branch_track", {})[name] = track
|
||||
_ensure_track(config, track, kind)
|
||||
save_config(config)
|
||||
return {"message": "分支已添加", "track": track}
|
||||
|
||||
|
||||
@router.put("/branches/track")
|
||||
async def update_branch_track(data: dict):
|
||||
"""修改分支所属的版本轨道(release=上架,feature=自测)。
|
||||
"""修改分支或 Tag 的版本轨道类型(release=上架,构建号自增;feature=自测,不自增)。
|
||||
|
||||
每个分支用自己的一条轨道,切换类型只改这条轨道的行为,版本号仍与其它分支互不影响。
|
||||
分支名可能含 /(如 feature/login),因此走请求体而非路径参数。
|
||||
"""
|
||||
branch = (data.get("branch") or "").strip()
|
||||
track = (data.get("track") or "").strip()
|
||||
if track not in TRACKS:
|
||||
raise HTTPException(status_code=400, detail=f"未知的版本轨道: {track}")
|
||||
if not (data.get("track") or "").strip():
|
||||
raise HTTPException(status_code=400, detail="未指定版本轨道")
|
||||
|
||||
async with _config_lock:
|
||||
config = load_config()
|
||||
if branch not in config.get("branches", []):
|
||||
if branch not in _build_refs(config):
|
||||
raise HTTPException(status_code=404, detail="分支不存在")
|
||||
track, kind = resolve_track(config, branch, data.get("track"))
|
||||
config.setdefault("branch_track", {})[branch] = track
|
||||
_ensure_track(config, track, kind)
|
||||
save_config(config)
|
||||
return {"message": "分支版本轨道已更新", "branch": branch, "track": track}
|
||||
|
||||
@@ -700,6 +1008,51 @@ async def delete_branch(branch_name: str):
|
||||
return {"message": "分支已删除"}
|
||||
|
||||
|
||||
# Tag 管理 API:打包时检出指定 Tag 的代码,版本轨道与分支一样按名字各自独立
|
||||
@router.get("/tags")
|
||||
async def get_tags_list():
|
||||
"""获取 Tag 列表"""
|
||||
return get_tags(load_config())
|
||||
|
||||
|
||||
@router.post("/tags")
|
||||
async def add_tag(data: dict):
|
||||
"""新增 Tag,可指定版本轨道类型(缺省为上架轨,App_Store 打包构建号自增)。"""
|
||||
name = data.get("name", "").strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="Tag 名称不能为空")
|
||||
|
||||
async with _config_lock:
|
||||
config = load_config()
|
||||
tags = get_tags(config)
|
||||
if name in tags:
|
||||
raise HTTPException(status_code=400, detail="Tag 已存在")
|
||||
if name in config.get("branches", []):
|
||||
raise HTTPException(status_code=400, detail="已存在同名分支")
|
||||
track, kind = resolve_track(config, name, data.get("track"), default_kind=KIND_RELEASE)
|
||||
tags.append(name)
|
||||
config["tags"] = tags
|
||||
config.setdefault("branch_track", {})[name] = track
|
||||
_ensure_track(config, track, kind)
|
||||
save_config(config)
|
||||
return {"message": "Tag 已添加", "track": track}
|
||||
|
||||
|
||||
@router.delete("/tags/{tag_name:path}")
|
||||
async def delete_tag(tag_name: str):
|
||||
"""删除 Tag"""
|
||||
async with _config_lock:
|
||||
config = load_config()
|
||||
tags = get_tags(config)
|
||||
if tag_name not in tags:
|
||||
raise HTTPException(status_code=404, detail="Tag 不存在")
|
||||
tags.remove(tag_name)
|
||||
config["tags"] = tags
|
||||
config.get("branch_track", {}).pop(tag_name, None)
|
||||
save_config(config)
|
||||
return {"message": "Tag 已删除"}
|
||||
|
||||
|
||||
@router.get("/build")
|
||||
async def get_build_settings(db: Session = Depends(get_db)):
|
||||
"""获取打包设置"""
|
||||
@@ -747,27 +1100,32 @@ async def update_build_settings(settings: BuildConfigUpdate, db: Session = Depen
|
||||
# 版本号配置 API
|
||||
@router.get("/versions")
|
||||
async def get_versions():
|
||||
"""获取两条版本轨道各自的 App_Ver 及其当前构建号。
|
||||
"""获取各条版本轨道的 App_Ver 及其当前构建号。
|
||||
|
||||
每个上架分支(master / develop 等)一条独立轨道,轨道名即分支名;自测分支共用 feature 轨。
|
||||
build_ver 为该轨道当前 App_Ver 已用到的最大构建号(形如 2.195.0.5,尚未打包则 .0),
|
||||
仅供展示;实际递增只发生在 release 轨的 App_Store 打包时,feature 轨永不自增。
|
||||
顶层 app_ver / build_ver 为 release 轨的镜像,保留给旧客户端。
|
||||
仅供展示;实际递增只发生在上架轨的 App_Store 打包时,feature 轨永不自增。
|
||||
顶层 app_ver / build_ver 为主上架轨的镜像,保留给旧客户端。
|
||||
"""
|
||||
config = load_config()
|
||||
tracks = {}
|
||||
for name in TRACKS:
|
||||
track = get_track(config, name)
|
||||
tracks[name] = {
|
||||
tracks = {
|
||||
name: {
|
||||
"kind": track.get("kind") if track.get("kind") in KINDS else _default_kind_for_track(name),
|
||||
"app_ver": track.get("app_ver") or DEFAULT_APP_VER,
|
||||
"build_ver": track_build_ver(track),
|
||||
"build_map": track.get("build_map") or {},
|
||||
}
|
||||
for name, track in ((config.get("versions") or {}).get("tracks") or {}).items()
|
||||
if isinstance(track, dict)
|
||||
}
|
||||
primary = _primary_track_name(config)
|
||||
return {
|
||||
**tracks[TRACK_RELEASE],
|
||||
**{k: v for k, v in tracks.get(primary, {}).items() if k != "kind"},
|
||||
"tracks": tracks,
|
||||
"primary_track": primary,
|
||||
"branch_track": {
|
||||
branch: get_track_name(config, branch)
|
||||
for branch in config.get("branches", []) or []
|
||||
for branch in _build_refs(config)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -779,14 +1137,12 @@ async def update_versions(data: dict):
|
||||
每个 App_Ver 的构建号在所属轨道内独立保存于 build_map 各自递增,因此来回切换
|
||||
版本号(包括回退到打过包的旧版本号)都不会重复,不会被 App Store 拒绝。
|
||||
|
||||
- track:release(master/develop,上架用)或 feature(自测用),缺省 release。
|
||||
- track:轨道名,上架分支为分支名(如 master、develop),自测为 feature;缺省为主上架轨。
|
||||
- 不传 build_ver:保留该版本号已记录的构建号,仅更新该轨道的当前 App_Ver。
|
||||
- 传 build_ver:形如 2.196.0.3,前三位须与 app_ver 一致,第四位为构建号;
|
||||
直接写入该版本号的记录(可用于手动对齐 App Store Connect 上的已传构建号)。
|
||||
"""
|
||||
track_name = (data.get("track") or TRACK_RELEASE).strip()
|
||||
if track_name not in TRACKS:
|
||||
raise HTTPException(status_code=400, detail=f"未知的版本轨道: {track_name}")
|
||||
track_name = (data.get("track") or "").strip()
|
||||
|
||||
app_ver = data.get("app_ver", "").strip()
|
||||
if not re.fullmatch(r"\d+\.\d+\.\d+", app_ver):
|
||||
@@ -806,7 +1162,10 @@ async def update_versions(data: dict):
|
||||
async with _config_lock:
|
||||
config = load_config()
|
||||
tracks = config.setdefault("versions", {}).setdefault("tracks", {})
|
||||
track = tracks.setdefault(track_name, _new_track())
|
||||
track_name = track_name or _primary_track_name(config)
|
||||
if track_name not in tracks:
|
||||
raise HTTPException(status_code=400, detail=f"未知的版本轨道: {track_name}")
|
||||
track = tracks[track_name]
|
||||
track["app_ver"] = app_ver
|
||||
build_map = track.setdefault("build_map", {})
|
||||
if build_no is not None:
|
||||
@@ -860,13 +1219,9 @@ async def create_server(server_data: dict):
|
||||
if name in servers:
|
||||
raise HTTPException(status_code=400, detail="环境名称已存在")
|
||||
|
||||
_validate_custom_fields(config, "server_fields", server_data)
|
||||
prefix = config.get("next_app_id_prefix", 1)
|
||||
servers[name] = {
|
||||
"api": server_data.get("api", ""),
|
||||
"assDom": server_data.get("assDom", ""),
|
||||
"universalLink": server_data.get("universalLink", ""),
|
||||
"app_id_prefix": prefix,
|
||||
}
|
||||
servers[name] = _server_entry(config, server_data, prefix)
|
||||
config["servers"] = servers
|
||||
config["next_app_id_prefix"] = prefix + 1
|
||||
save_config(config)
|
||||
@@ -892,12 +1247,8 @@ async def update_server(server_name: str, server_data: dict):
|
||||
else:
|
||||
new_name = server_name
|
||||
|
||||
servers[new_name] = {
|
||||
"api": server_data.get("api", ""),
|
||||
"assDom": server_data.get("assDom", ""),
|
||||
"universalLink": server_data.get("universalLink", ""),
|
||||
"app_id_prefix": servers[new_name].get("app_id_prefix"),
|
||||
}
|
||||
_validate_custom_fields(config, "server_fields", server_data)
|
||||
servers[new_name] = _server_entry(config, server_data, servers[new_name].get("app_id_prefix"))
|
||||
config["servers"] = servers
|
||||
save_config(config)
|
||||
return {"message": "服务器环境已更新"}
|
||||
@@ -923,3 +1274,170 @@ async def delete_server(server_name: str):
|
||||
config["servers"] = servers
|
||||
save_config(config)
|
||||
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"])
|
||||
if "dingtalk_at" in data:
|
||||
dingtalk_at = data["dingtalk_at"] or {}
|
||||
if not isinstance(dingtalk_at, dict):
|
||||
raise HTTPException(status_code=400, detail="dingtalk_at 必须是对象")
|
||||
project["dingtalk_at"] = {key: normalize_mobiles(dingtalk_at.get(key)) for key in AT_MOBILES_KEYS}
|
||||
|
||||
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": "项目已删除"}
|
||||
|
||||
@@ -11,7 +11,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import get_current_user
|
||||
from ..models import OperationLog
|
||||
from ..models import OperationLog, Task
|
||||
|
||||
router = APIRouter(prefix="/api/operations", tags=["operations"])
|
||||
|
||||
@@ -31,6 +31,27 @@ def _query_logs(db: Session, days: int, username: str = "", action: str = ""):
|
||||
return query
|
||||
|
||||
|
||||
def _task_versions(db: Session, task_ids: set[str]) -> dict[str, str]:
|
||||
versions = {}
|
||||
if not task_ids:
|
||||
return versions
|
||||
for task_id, config_json in db.query(Task.id, Task.config_json).filter(Task.id.in_(task_ids)).all():
|
||||
try:
|
||||
config = json.loads(config_json or "{}")
|
||||
versions[task_id] = config.get("VERSION", "") if isinstance(config, dict) else ""
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
versions[task_id] = ""
|
||||
return versions
|
||||
|
||||
|
||||
def _log_detail(log: OperationLog) -> dict:
|
||||
try:
|
||||
detail = json.loads(log.detail_json or "{}")
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
return {}
|
||||
return detail if isinstance(detail, dict) else {}
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
async def operation_summary(days: int = Query(30, ge=1, le=365), user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
_require_admin(user)
|
||||
@@ -48,10 +69,20 @@ async def operation_summary(days: int = Query(30, ge=1, le=365), user: dict = De
|
||||
async def list_operations(days: int = Query(30, ge=1, le=365), username: str = "", action: str = "", limit: int = Query(100, ge=1, le=500), user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
_require_admin(user)
|
||||
logs = _query_logs(db, days, username, action).order_by(OperationLog.created_at.desc()).limit(limit).all()
|
||||
return [{"id": log.id, "created_at": log.created_at, "username": log.username,
|
||||
"action": log.action, "app_name": log.app_name, "task_id": log.task_id,
|
||||
"resource_type": log.resource_type, "resource_name": log.resource_name,
|
||||
"detail": json.loads(log.detail_json or "{}"), "client_ip": log.client_ip} for log in logs]
|
||||
task_ids = {log.task_id for log in logs if log.action == "ipa_download_requested" and log.task_id}
|
||||
task_versions = _task_versions(db, task_ids)
|
||||
|
||||
result = []
|
||||
for log in logs:
|
||||
detail = _log_detail(log)
|
||||
item = {"id": log.id, "created_at": log.created_at, "username": log.username,
|
||||
"action": log.action, "app_name": log.app_name, "task_id": log.task_id,
|
||||
"resource_type": log.resource_type, "resource_name": log.resource_name,
|
||||
"detail": detail}
|
||||
if log.action == "ipa_download_requested":
|
||||
item["version"] = detail.get("version") or task_versions.get(log.task_id, "")
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/export")
|
||||
@@ -59,7 +90,14 @@ async def export_operations(days: int = Query(30, ge=1, le=365), user: dict = De
|
||||
_require_admin(user)
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(["时间", "用户", "操作", "App", "资源类型", "资源名称", "IP", "详情"])
|
||||
for log in _query_logs(db, days).order_by(OperationLog.created_at.desc()).all():
|
||||
writer.writerow([log.created_at, log.username, log.action, log.app_name or "", log.resource_type or "", log.resource_name or "", log.client_ip or "", log.detail_json or ""])
|
||||
writer.writerow(["时间", "用户", "操作", "App", "资源类型", "资源名称", "版本", "详情"])
|
||||
logs = _query_logs(db, days).order_by(OperationLog.created_at.desc()).all()
|
||||
task_ids = {log.task_id for log in logs if log.action == "ipa_download_requested" and log.task_id}
|
||||
task_versions = _task_versions(db, task_ids)
|
||||
for log in logs:
|
||||
detail = _log_detail(log)
|
||||
version = ""
|
||||
if log.action == "ipa_download_requested":
|
||||
version = detail.get("version") or task_versions.get(log.task_id, "")
|
||||
writer.writerow([log.created_at, log.username, log.action, log.app_name or "", log.resource_type or "", log.resource_name or "", version, log.detail_json or ""])
|
||||
return StreamingResponse(iter(["\ufeff" + output.getvalue()]), media_type="text/csv", headers={"Content-Disposition": "attachment; filename=operation-logs.csv"})
|
||||
|
||||
+88
-22
@@ -3,6 +3,7 @@ import os
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
@@ -18,6 +19,10 @@ from ..deps import get_current_user
|
||||
|
||||
router = APIRouter(prefix="/api/tasks", tags=["tasks"], dependencies=[Depends(get_current_user)])
|
||||
|
||||
# 同一用户对同一任务连击下载按钮时,短时间内只记一次操作日志,避免刷屏
|
||||
_DOWNLOAD_LOG_DEBOUNCE_SECONDS = 5
|
||||
_recent_download_logs: dict[str, float] = {}
|
||||
|
||||
|
||||
@router.post("", response_model=TaskResponse)
|
||||
async def create_task(task: TaskCreate, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
@@ -43,16 +48,26 @@ async def create_task(task: TaskCreate, request: Request, user: dict = Depends(g
|
||||
raise HTTPException(status_code=400, detail=f"该 App 未配置 {task.build_type} 证书")
|
||||
|
||||
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:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
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 不允许重名,按名字即可确定要检出的引用类型
|
||||
from .config import get_ref_type
|
||||
ref_type = get_ref_type(config, task.branch)
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
db_task = Task(
|
||||
id=task_id,
|
||||
project_id=project_id,
|
||||
app_id=task.app_id,
|
||||
app_name=app.get("name", ""),
|
||||
build_type=task.build_type,
|
||||
@@ -60,12 +75,13 @@ async def create_task(task: TaskCreate, request: Request, user: dict = Depends(g
|
||||
scheme_name=scheme.get("displayName") or scheme_name,
|
||||
obfuscation=task.obfuscation,
|
||||
branch=task.branch,
|
||||
ref_type=ref_type,
|
||||
status="pending",
|
||||
)
|
||||
db.add(db_task)
|
||||
from ..services.audit_log import record_operation
|
||||
record_operation(db, user, "build_created", request=request, task=db_task,
|
||||
detail={"branch": task.branch, "build_type": task.build_type})
|
||||
detail={"branch": task.branch, "ref_type": ref_type, "build_type": task.build_type})
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
|
||||
@@ -109,8 +125,9 @@ async def list_tasks(
|
||||
user: dict = Depends(get_current_user),
|
||||
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 not user.get("is_admin"):
|
||||
raise HTTPException(status_code=403, detail="需要管理员权限")
|
||||
@@ -190,16 +207,35 @@ async def delete_task(task_id: str, request: Request, user: dict = Depends(get_c
|
||||
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端文件")
|
||||
try:
|
||||
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
|
||||
delete_published_artifacts(
|
||||
build_config,
|
||||
load_config().get("upload", {}),
|
||||
load_upload_config(),
|
||||
task.oss_url,
|
||||
)
|
||||
except (json.JSONDecodeError, DistributionError) as exc:
|
||||
raise HTTPException(status_code=502, detail=f"远端产物删除失败,记录未删除:{exc}") from exc
|
||||
|
||||
# dSYM 压缩包的远端对象键与 IPA 独立,同一版本/分支重复打包会复用并覆盖同一个远端文件,
|
||||
# 仍有其他历史记录引用时不能删除。
|
||||
has_shared_dsym = bool(
|
||||
task.dsym_url and db.query(Task).filter(
|
||||
Task.id != task.id,
|
||||
Task.dsym_url == task.dsym_url,
|
||||
).first()
|
||||
)
|
||||
if task.dsym_url and not has_shared_dsym:
|
||||
if not task.config_json:
|
||||
raise HTTPException(status_code=400, detail="缺少打包配置快照,无法安全删除远端 dSYM 文件")
|
||||
try:
|
||||
build_config = json.loads(task.config_json)
|
||||
from .config import load_upload_config
|
||||
from ..services.distribution import DistributionError, delete_published_dsym
|
||||
delete_published_dsym(build_config, load_upload_config(), task.dsym_url)
|
||||
except (json.JSONDecodeError, DistributionError) as exc:
|
||||
raise HTTPException(status_code=502, detail=f"远端 dSYM 删除失败,记录未删除:{exc}") from exc
|
||||
|
||||
# 删除日志文件
|
||||
log_path = Path(__file__).parent.parent / "logs" / f"{task_id}.log"
|
||||
if log_path.exists():
|
||||
@@ -266,27 +302,39 @@ async def get_download_link(task_id: str, request: Request, user: dict = Depends
|
||||
if not task.oss_url:
|
||||
raise HTTPException(status_code=404, detail="下载文件不存在")
|
||||
try:
|
||||
from .config import load_config
|
||||
from .config import load_upload_config
|
||||
from ..config import DOWNLOAD_URL_EXPIRE_SECONDS
|
||||
from ..services.distribution import DistributionError, get_published_download_url
|
||||
task_config = json.loads(task.config_json or "{}")
|
||||
download_url = get_published_download_url(
|
||||
json.loads(task.config_json or "{}"),
|
||||
load_config().get("upload", {}),
|
||||
task_config,
|
||||
load_upload_config(),
|
||||
task.oss_url,
|
||||
)
|
||||
except (json.JSONDecodeError, DistributionError) as exc:
|
||||
raise HTTPException(status_code=502, detail=f"生成下载链接失败:{exc}") from exc
|
||||
from ..services.audit_log import record_operation
|
||||
record_operation(db, user, "ipa_download_requested", request=request, task=task,
|
||||
resource_type="ipa", resource_name=task.oss_url,
|
||||
detail={"controlled": True})
|
||||
db.commit()
|
||||
|
||||
debounce_key = f"{user.get('username')}:{task_id}"
|
||||
now = time.monotonic()
|
||||
last = _recent_download_logs.get(debounce_key)
|
||||
if last is None or now - last > _DOWNLOAD_LOG_DEBOUNCE_SECONDS:
|
||||
if len(_recent_download_logs) > 500:
|
||||
cutoff = now - _DOWNLOAD_LOG_DEBOUNCE_SECONDS
|
||||
for key, ts in list(_recent_download_logs.items()):
|
||||
if ts < cutoff:
|
||||
del _recent_download_logs[key]
|
||||
_recent_download_logs[debounce_key] = now
|
||||
from ..services.audit_log import record_operation
|
||||
record_operation(db, user, "ipa_download_requested", request=request, task=task,
|
||||
resource_type="ipa", resource_name=task.oss_url,
|
||||
detail={"controlled": True, "version": task_config.get("VERSION", "")})
|
||||
db.commit()
|
||||
return {"url": download_url, "expires_in": DOWNLOAD_URL_EXPIRE_SECONDS}
|
||||
|
||||
|
||||
@router.get("/{task_id}/dsym")
|
||||
async def download_dsym(task_id: str, request: Request, user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
"""下载 dSYM 文件"""
|
||||
"""下载 dSYM 文件:本地文件已被清理时回退到构建时上传保存的远端地址"""
|
||||
import shutil
|
||||
import zipfile
|
||||
import tempfile
|
||||
@@ -294,17 +342,35 @@ async def download_dsym(task_id: str, request: Request, user: dict = Depends(get
|
||||
task = db.query(Task).filter(Task.id == task_id).first()
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="任务不存在")
|
||||
if not task.dsym_path:
|
||||
raise HTTPException(status_code=404, detail="dSYM 文件不存在")
|
||||
from ..services.audit_log import record_operation
|
||||
record_operation(db, user, "dsym_downloaded", request=request, task=task,
|
||||
resource_type="dsym", resource_name=os.path.basename(task.dsym_path))
|
||||
db.commit()
|
||||
|
||||
dsym_path = task.dsym_path
|
||||
if not os.path.exists(dsym_path):
|
||||
local_exists = bool(dsym_path) and os.path.exists(dsym_path)
|
||||
if not local_exists and not task.dsym_url:
|
||||
if not dsym_path:
|
||||
raise HTTPException(status_code=404, detail="dSYM 文件不存在")
|
||||
raise HTTPException(status_code=404, detail="dSYM 文件已被清理")
|
||||
|
||||
from ..services.audit_log import record_operation
|
||||
resource_name = os.path.basename(dsym_path) if dsym_path else os.path.basename(task.dsym_url)
|
||||
record_operation(db, user, "dsym_downloaded", request=request, task=task,
|
||||
resource_type="dsym", resource_name=resource_name)
|
||||
db.commit()
|
||||
|
||||
if not local_exists:
|
||||
# dSYM 需要携带认证信息才能访问该接口,浏览器无法直接跳转到本接口的
|
||||
# 302 目标,因此改为返回 JSON 让前端自行发起下载。
|
||||
try:
|
||||
from .config import load_upload_config
|
||||
from ..services.distribution import DistributionError, get_published_dsym_url
|
||||
download_url = get_published_dsym_url(
|
||||
json.loads(task.config_json or "{}"),
|
||||
load_upload_config(),
|
||||
task.dsym_url,
|
||||
)
|
||||
except (json.JSONDecodeError, DistributionError) as exc:
|
||||
raise HTTPException(status_code=502, detail=f"生成下载链接失败:{exc}") from exc
|
||||
return {"url": download_url}
|
||||
|
||||
# .dSYM 是目录(macOS bundle),需要压缩为 zip 再下载
|
||||
if os.path.isdir(dsym_path):
|
||||
zip_path = os.path.join(tempfile.gettempdir(), os.path.basename(dsym_path) + ".zip")
|
||||
|
||||
@@ -15,6 +15,7 @@ class TaskCreate(BaseModel):
|
||||
|
||||
class TaskResponse(BaseModel):
|
||||
id: str
|
||||
project_id: Optional[str] = "readoor"
|
||||
app_id: str
|
||||
app_name: str
|
||||
build_type: str
|
||||
@@ -22,6 +23,7 @@ class TaskResponse(BaseModel):
|
||||
scheme_name: str
|
||||
obfuscation: bool
|
||||
branch: str
|
||||
ref_type: Optional[str] = "branch"
|
||||
status: str
|
||||
current_step: Optional[str]
|
||||
created_at: Optional[datetime]
|
||||
@@ -31,6 +33,7 @@ class TaskResponse(BaseModel):
|
||||
ipa_path: Optional[str]
|
||||
oss_url: Optional[str]
|
||||
dsym_path: Optional[str]
|
||||
dsym_url: Optional[str] = None
|
||||
obfuscation_maps_path: Optional[str]
|
||||
qr_code_path: Optional[str]
|
||||
build_dir: Optional[str]
|
||||
|
||||
@@ -3,6 +3,7 @@ import asyncio
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
@@ -12,19 +13,17 @@ from typing import List
|
||||
|
||||
from ..config import (
|
||||
BUILD_BASE_DIR,
|
||||
COPY_ITEMS,
|
||||
DEFAULT_BUILD_DIR_RETENTION_HOURS,
|
||||
BUILD_TIMEOUT_HOURS,
|
||||
SKINS_DIR,
|
||||
AUTOMATION_DIR,
|
||||
get_source_dir,
|
||||
get_shared_source_dir,
|
||||
get_git_remote_url,
|
||||
mask_git_remote_url,
|
||||
)
|
||||
from ..projects import LEGACY_PROJECT_ID, PATCHER_READOOR, get_definition, get_project_source
|
||||
from .log_streamer import log_streamer
|
||||
from .distribution import DistributionError, publish_ipa
|
||||
from .notification import NotificationError, send_dingtalk_notification
|
||||
from .distribution import DistributionError, publish_dsym, publish_ipa
|
||||
from .notification import NotificationError, merge_project_at_mobiles, send_dingtalk_notification
|
||||
from .project_patcher import ProjectPatchError, apply_project_config
|
||||
|
||||
|
||||
@@ -37,9 +36,36 @@ class BuildError(Exception):
|
||||
self.detail = detail
|
||||
|
||||
|
||||
# 共享源码目录只能同时被一个任务切换、清理和复制。
|
||||
# 后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。
|
||||
source_prepare_lock = asyncio.Lock()
|
||||
# 共享源码目录只能同时被一个任务切换、清理和复制,每个源码目录一把锁,
|
||||
# 不同项目的源码准备互不阻塞。后续在各自 build_dir 中执行的配置、依赖安装和编译不受此锁限制。
|
||||
_source_prepare_locks: dict = {}
|
||||
|
||||
# 打包目录名:build_<项目 ID>_<任务 ID>
|
||||
_BUILD_DIR_PATTERN = re.compile(r"^build_[a-z][a-z0-9_-]{0,31}_.+")
|
||||
|
||||
|
||||
def _source_prepare_lock(source_dir: Path) -> asyncio.Lock:
|
||||
return _source_prepare_locks.setdefault(str(source_dir.resolve()), asyncio.Lock())
|
||||
|
||||
|
||||
def _task_project_id(task) -> str:
|
||||
project_id = getattr(task, "project_id", None)
|
||||
return project_id if isinstance(project_id, str) and project_id else LEGACY_PROJECT_ID
|
||||
|
||||
|
||||
def load_task_project(task) -> dict:
|
||||
"""读取任务所属项目的配置视图(见 routers.config.load_config)。"""
|
||||
from fastapi import HTTPException
|
||||
from ..routers.config import load_config
|
||||
try:
|
||||
return load_config(_task_project_id(task))
|
||||
except HTTPException as exc:
|
||||
raise BuildError(str(exc.detail), category="config") from exc
|
||||
|
||||
|
||||
def get_task_definition(task) -> dict:
|
||||
project_id = _task_project_id(task)
|
||||
return get_definition(project_id, load_task_project(task))
|
||||
|
||||
|
||||
def _patch_afnetworking_private_headers(build_dir: Path) -> int:
|
||||
@@ -217,7 +243,7 @@ def _cleanup_old_builds(db):
|
||||
_cleanup_superseded_tasks(db)
|
||||
return
|
||||
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:
|
||||
if d.stat().st_mtime < cutoff:
|
||||
shutil.rmtree(d)
|
||||
@@ -291,16 +317,21 @@ def _db_update(db, task, **fields):
|
||||
db.commit()
|
||||
|
||||
|
||||
async def update_source(task_id: str, source_dir: Path, branch: str):
|
||||
"""将共享源码工作目录强制同步到指定远程分支。"""
|
||||
remote_url = get_git_remote_url(with_credentials=True)
|
||||
async def update_source(task_id: str, source_dir: Path, branch: str, ref_type: str = "branch",
|
||||
remote_url: str = None):
|
||||
"""将共享源码工作目录强制同步到指定远程分支或 Tag(ref_type="tag" 时 branch 为 Tag 名)。
|
||||
|
||||
remote_url 为带凭证的项目仓库地址,未传时使用 .env 中的 GIT_REMOTE_URL。
|
||||
"""
|
||||
if remote_url is None:
|
||||
remote_url = get_git_remote_url(with_credentials=True)
|
||||
remote_url_masked = mask_git_remote_url(remote_url)
|
||||
git_env = _git_env()
|
||||
|
||||
cloned = not source_dir.exists()
|
||||
if cloned:
|
||||
if not remote_url:
|
||||
raise Exception(f"源码目录不存在且未配置 GIT_REMOTE_URL: {source_dir}")
|
||||
raise Exception(f"源码目录不存在且未配置 Git 仓库地址: {source_dir}")
|
||||
source_dir.parent.mkdir(parents=True, exist_ok=True)
|
||||
await log_streamer.emit(task_id, f"初始化共享源码目录: {remote_url_masked}")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
@@ -321,7 +352,8 @@ async def update_source(task_id: str, source_dir: Path, branch: str):
|
||||
if not cloned and not (source_dir / ".git").exists():
|
||||
raise Exception(f"共享源码目录不是 Git 仓库: {source_dir}")
|
||||
|
||||
await log_streamer.emit(task_id, f"同步共享源码到分支: {branch}")
|
||||
is_tag = ref_type == "tag"
|
||||
await log_streamer.emit(task_id, f"同步共享源码到{'Tag' if is_tag else '分支'}: {branch}")
|
||||
|
||||
if remote_url:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
@@ -333,12 +365,22 @@ async def update_source(task_id: str, source_dir: Path, branch: str):
|
||||
if process.returncode != 0:
|
||||
raise Exception("git remote set-url 失败")
|
||||
|
||||
commands = [
|
||||
(("git", "fetch", "origin"), "git fetch 失败"),
|
||||
(("git", "checkout", "-B", branch, f"origin/{branch}"), f"git checkout {branch} 失败"),
|
||||
(("git", "reset", "--hard", f"origin/{branch}"), f"git reset {branch} 失败"),
|
||||
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||||
]
|
||||
if is_tag:
|
||||
# Tag 检出为游离 HEAD;--force 让远端被移动过的 Tag 覆盖本地旧 Tag
|
||||
tag_ref = f"refs/tags/{branch}"
|
||||
commands = [
|
||||
(("git", "fetch", "origin", "--tags", "--force"), "git fetch 失败"),
|
||||
(("git", "checkout", "--detach", tag_ref), f"git checkout Tag {branch} 失败"),
|
||||
(("git", "reset", "--hard", tag_ref), f"git reset Tag {branch} 失败"),
|
||||
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||||
]
|
||||
else:
|
||||
commands = [
|
||||
(("git", "fetch", "origin"), "git fetch 失败"),
|
||||
(("git", "checkout", "-B", branch, f"origin/{branch}"), f"git checkout {branch} 失败"),
|
||||
(("git", "reset", "--hard", f"origin/{branch}"), f"git reset {branch} 失败"),
|
||||
(("git", "clean", "-ffdx"), "git clean 失败"),
|
||||
]
|
||||
for command, error_message in commands:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*_GIT_NO_CREDENTIAL_HELPER, *command[1:], env=git_env,
|
||||
@@ -370,24 +412,34 @@ async def get_source_commit(source_dir: Path) -> str:
|
||||
|
||||
|
||||
async def prepare_source_snapshot(task_id: str, task) -> tuple[Path, str]:
|
||||
"""准备任务独立源码快照;远程仓库模式下此过程全局串行。"""
|
||||
if not get_git_remote_url():
|
||||
source_dir = get_source_dir(task.branch)
|
||||
"""准备任务独立源码快照;远程仓库模式下同一源码目录的准备过程串行。"""
|
||||
project_id = _task_project_id(task)
|
||||
project = load_task_project(task)
|
||||
definition = get_definition(project_id, project)
|
||||
source = get_project_source(project_id, project)
|
||||
await log_streamer.emit(task_id, f"项目: {definition['name']}({project_id})")
|
||||
|
||||
if not source.remote_url:
|
||||
if source.manual_base is None:
|
||||
raise BuildError(f"项目 {definition['name']} 未配置 Git 仓库地址", category="config")
|
||||
source_dir = source.manual_base / task.branch
|
||||
if not source_dir.exists():
|
||||
raise Exception(
|
||||
f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支代码,或配置 GIT_REMOTE_URL"
|
||||
f"分支源码目录不存在: {source_dir},请先在 GIT_SOURCE_BASE 下准备分支(或 Tag)代码,或配置 GIT_REMOTE_URL"
|
||||
)
|
||||
await log_streamer.emit(task_id, f"使用分支源码: {source_dir}")
|
||||
return await copy_source_code(task_id, task, source_dir), ""
|
||||
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, "等待共享源码准备队列...")
|
||||
async with source_prepare_lock:
|
||||
async with _source_prepare_lock(source_dir):
|
||||
await log_streamer.emit(task_id, "开始准备共享源码快照")
|
||||
await update_source(task_id, source_dir, task.branch)
|
||||
ref_type = "tag" if task.ref_type == "tag" else "branch"
|
||||
await update_source(task_id, source_dir, task.branch, ref_type,
|
||||
remote_url=source.remote_url_with_credentials)
|
||||
commit = await get_source_commit(source_dir)
|
||||
await log_streamer.emit(task_id, f"源码版本: {task.branch} @ {commit}")
|
||||
build_dir = await copy_source_code(task_id, task, source_dir)
|
||||
build_dir = await copy_source_code(task_id, task, source_dir, definition)
|
||||
await log_streamer.emit(task_id, "共享源码快照已就绪,开始并行打包")
|
||||
return build_dir, commit
|
||||
|
||||
@@ -426,6 +478,7 @@ async def run_build_task(task_id: str):
|
||||
nonlocal build_dir
|
||||
# 1. 串行准备源码快照;后续步骤在任务独立目录中并行执行。
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="source_prepare")
|
||||
definition = await asyncio.to_thread(get_task_definition, task)
|
||||
build_dir, source_commit = await prepare_source_snapshot(task_id, task)
|
||||
await asyncio.to_thread(_db_update, db, task, build_dir=str(build_dir))
|
||||
|
||||
@@ -433,17 +486,18 @@ async def run_build_task(task_id: str):
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="config")
|
||||
config_data = await generate_config(task_id, task, build_dir)
|
||||
config_data["SOURCE_BRANCH"] = task.branch
|
||||
config_data["SOURCE_REF_TYPE"] = "tag" if task.ref_type == "tag" else "branch"
|
||||
config_data["SOURCE_COMMIT"] = source_commit
|
||||
await asyncio.to_thread(_db_update, db, task,
|
||||
config_json=json.dumps(config_data, ensure_ascii=False))
|
||||
|
||||
# 3. 替换项目配置
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="patch")
|
||||
await patch_project(task_id, task, config_data, build_dir)
|
||||
await patch_project(task_id, task, config_data, build_dir, definition)
|
||||
|
||||
# 3.5 安装依赖
|
||||
await asyncio.to_thread(_db_update, db, task, current_step="pod_install")
|
||||
await run_pod_install(task_id, build_dir)
|
||||
await run_pod_install(task_id, build_dir, definition["xcode"])
|
||||
|
||||
# 4. 代码混淆(可选)
|
||||
if task.obfuscation:
|
||||
@@ -452,10 +506,10 @@ async def run_build_task(task_id: str):
|
||||
|
||||
# 5. 构建项目
|
||||
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_path = await find_dsym(task_id, build_dir)
|
||||
dsym_path = await find_dsym(task_id, build_dir, config_data.get("SCHEME", ""))
|
||||
|
||||
# 查找混淆映射表
|
||||
obf_maps_path = build_dir / "obfuscation_maps"
|
||||
@@ -477,6 +531,13 @@ async def run_build_task(task_id: str):
|
||||
upload_fields["oss_url"] = oss_url
|
||||
if qr_code_path:
|
||||
upload_fields["qr_code_path"] = qr_code_path
|
||||
|
||||
# dSYM 用于后续崩溃符号化,按上传配置一并保存到远端;失败不影响本次打包结果。
|
||||
if dsym_path:
|
||||
dsym_url = await upload_dsym(task_id, task, config_data, dsym_path, build_dir)
|
||||
if dsym_url:
|
||||
upload_fields["dsym_url"] = dsym_url
|
||||
|
||||
if upload_fields:
|
||||
await asyncio.to_thread(_db_update, db, task, **upload_fields)
|
||||
|
||||
@@ -491,22 +552,26 @@ async def run_build_task(task_id: str):
|
||||
if task.oss_url:
|
||||
await log_streamer.emit(task_id, f"下载链接: {task.oss_url}")
|
||||
|
||||
# App Store 仅提供 IPA 下载地址,不发送下载通知;Ad Hoc 才发送安装页二维码通知。
|
||||
if task.build_type == "Ad_Hoc":
|
||||
# 通知不影响已完成的打包结果,发送失败仅写入日志以便排查。
|
||||
dingtalk_config = config_data.get("_upload_config", {}).get("dingtalk", {})
|
||||
try:
|
||||
notified = await asyncio.to_thread(
|
||||
send_dingtalk_notification,
|
||||
dingtalk_config,
|
||||
config_data,
|
||||
task.oss_url or oss_url,
|
||||
task.qr_code_path or qr_code_path,
|
||||
)
|
||||
if notified:
|
||||
await log_streamer.emit(task_id, "钉钉通知发送成功")
|
||||
except NotificationError as exc:
|
||||
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
||||
# Ad Hoc 发安装页二维码通知,App Store 发 IPA 下载地址通知;
|
||||
# 两者标题与 @ 名单不同,均由 send_dingtalk_notification 按 BUILD_TYPE 区分;
|
||||
# 项目配置了 @ 名单时覆盖全局名单。
|
||||
# 通知不影响已完成的打包结果,发送失败仅写入日志以便排查。
|
||||
dingtalk_config = merge_project_at_mobiles(
|
||||
config_data.get("_upload_config", {}).get("dingtalk", {}),
|
||||
definition.get("dingtalk_at"),
|
||||
)
|
||||
try:
|
||||
notified = await asyncio.to_thread(
|
||||
send_dingtalk_notification,
|
||||
dingtalk_config,
|
||||
config_data,
|
||||
task.oss_url or oss_url,
|
||||
task.qr_code_path or qr_code_path,
|
||||
)
|
||||
if notified:
|
||||
await log_streamer.emit(task_id, "钉钉通知发送成功")
|
||||
except NotificationError as exc:
|
||||
await log_streamer.emit(task_id, f"钉钉通知未发送: {exc}", level="warn")
|
||||
|
||||
# 带超时执行打包
|
||||
await asyncio.wait_for(_do_build(), timeout=timeout_seconds)
|
||||
@@ -570,16 +635,36 @@ async def run_build_task(task_id: str):
|
||||
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, "拷贝代码")
|
||||
|
||||
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():
|
||||
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
|
||||
# 历史分支中该文件可能仍是小写 podfile;构建副本统一使用 Pods.xcodeproj
|
||||
# 引用的标准名称 Podfile,避免大小写敏感文件系统报路径不一致。
|
||||
@@ -603,10 +688,11 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||||
|
||||
from ..routers.config import (
|
||||
load_config, _config_lock, get_track, get_track_name, track_build_ver,
|
||||
TRACK_RELEASE, _new_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", {})
|
||||
schemes = config.get("schemes", {})
|
||||
|
||||
@@ -614,29 +700,29 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||||
scheme = schemes.get(task.scheme_id, {})
|
||||
|
||||
# 版本号由当前服务配置统一管理,不读取分支源码中的手动打包脚本。
|
||||
# 按分支所属轨道取版本号:master/develop 走 release 轨(上架用),feature 走 feature 轨(自测用),
|
||||
# 两条轨道的 App_Ver 各自独立。
|
||||
# 按分支所属轨道取版本号:每个上架分支(master、develop 等)一条独立轨道,
|
||||
# 自测分支共用 feature 轨,各轨道的 App_Ver 互不影响。
|
||||
track_name = get_track_name(config, task.branch)
|
||||
track = get_track(config, track_name)
|
||||
app_ver = track.get("app_ver") or "2.180.0"
|
||||
|
||||
# 构建号按版本号独立记录:build_map[app_ver] 为该版本号已用到的最大第四位。
|
||||
build_ver = track_build_ver(track)
|
||||
is_release = is_release_track(track)
|
||||
await log_streamer.emit(
|
||||
task_id,
|
||||
f"版本轨道: {track_name}({'上架,App_Store 打包自增' if track_name == TRACK_RELEASE else '自测,构建号不自增'})",
|
||||
f"版本轨道: {track_name}({'上架,App_Store 打包自增' if is_release else '自测,构建号不自增'})",
|
||||
)
|
||||
|
||||
# release 轨的 App_Store 打包,在该版本号自己的构建号上 +1
|
||||
# (回退到旧版本号也从它自己的最大值继续);feature 轨始终使用手动设定的构建号。
|
||||
if track_name == TRACK_RELEASE and task.build_type == "App_Store":
|
||||
# 上架轨的 App_Store 打包,在该版本号的构建号上 +1(回退到旧版本号也从它自己的最大值继续);
|
||||
# feature 轨始终使用手动设定的构建号。
|
||||
if is_release and task.build_type == "App_Store":
|
||||
async with _config_lock:
|
||||
config = load_config()
|
||||
tracks = config.setdefault("versions", {}).setdefault("tracks", {})
|
||||
track = tracks.setdefault(track_name, _new_track(app_ver))
|
||||
build_map = track.setdefault("build_map", {})
|
||||
n = int(build_map.get(app_ver, 0)) + 1
|
||||
build_map[app_ver] = n
|
||||
config = load_config(project_id)
|
||||
track = _ensure_track(config, track_name)
|
||||
track.setdefault("app_ver", app_ver)
|
||||
n = next_build_no(config["versions"]["tracks"], app_ver)
|
||||
track.setdefault("build_map", {})[app_ver] = n
|
||||
build_ver = f"{app_ver}.{n}"
|
||||
|
||||
from ..routers.config import save_config
|
||||
@@ -646,6 +732,7 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||||
|
||||
# 构建配置
|
||||
config_data = {
|
||||
"PROJECT_ID": project_id,
|
||||
"VERSION": app_ver,
|
||||
"BUILD_VERSION": build_ver,
|
||||
"SERVER": app.get("server", ""),
|
||||
@@ -715,10 +802,27 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||||
|
||||
# 关联域名等配置
|
||||
config_data["ASSOCIATED_DOMAINS"] = app.get("AssDom", "")
|
||||
for key in ["weixinlogin", "weixinpay", "tencent", "UniversalLink", "AlivcLicenseKey"]:
|
||||
for key in ["weixinlogin", "weixinpay", "wxworkSchema", "tencent", "UniversalLink", "AlivcLicenseKey"]:
|
||||
if key in app:
|
||||
config_data[key] = app[key]
|
||||
|
||||
# 项目自定义字段,供通用替换规则以 ${app.X} / ${server.X} 引用
|
||||
definition = get_definition(project_id, config)
|
||||
server = config.get("servers", {}).get(app.get("server", ""), {})
|
||||
config_data["APP_VARS"] = {
|
||||
field["key"]: app.get(field["key"], "") for field in definition["app_fields"] if field.get("key")
|
||||
}
|
||||
# 通用项目没有 AppGuid:以第一个 App 字段(如 APPID)作为 App 标识,
|
||||
# 用于产物文件名和通知;未配置 App 字段时用 upload_key。
|
||||
if definition["patcher"] != PATCHER_READOOR:
|
||||
id_field = next((field for field in definition["app_fields"] if field.get("key")), None)
|
||||
app_ident = config_data["APP_VARS"].get(id_field["key"], "") if id_field else ""
|
||||
config_data["APPID"] = app_ident or config_data["UPLOAD_KEY"]
|
||||
config_data["APPID_LABEL"] = (id_field.get("label") or id_field["key"]) if app_ident else "App 标识"
|
||||
config_data["SERVER_VARS"] = {
|
||||
field["key"]: server.get(field["key"], "") for field in definition["server_fields"] if field.get("key")
|
||||
}
|
||||
|
||||
# 写入配置文件
|
||||
config_output_path = build_dir / "config_output.json"
|
||||
with open(config_output_path, "w", encoding="utf-8") as f:
|
||||
@@ -728,12 +832,12 @@ async def generate_config(task_id: str, task, build_dir: Path) -> dict:
|
||||
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, "替换项目配置")
|
||||
|
||||
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:
|
||||
raise BuildError(str(exc), category="config") from exc
|
||||
(build_dir / "patch_result.log").write_text("\n".join(patch_lines), encoding="utf-8")
|
||||
@@ -742,13 +846,34 @@ async def patch_project(task_id: str, task, config_data: dict, build_dir: Path):
|
||||
await log_streamer.emit(task_id, "项目配置替换完成")
|
||||
|
||||
|
||||
async def run_pod_install(task_id: str, build_dir: Path):
|
||||
def _pod_dir(build_dir: Path, xcode: dict = None) -> Path:
|
||||
"""Podfile 所在目录:工程在仓库子目录时(如 sub/App.xcworkspace),优先取该子目录。"""
|
||||
candidates = []
|
||||
for key in ("workspace", "project"):
|
||||
rel = ((xcode or {}).get(key) or "").strip()
|
||||
if rel:
|
||||
candidates.append(build_dir / Path(rel).parent)
|
||||
candidates.append(build_dir)
|
||||
for directory in candidates:
|
||||
if (directory / "Podfile").is_file() or (directory / "podfile").is_file():
|
||||
return directory
|
||||
return None
|
||||
|
||||
|
||||
async def run_pod_install(task_id: str, build_dir: Path, xcode: dict = None):
|
||||
"""安装 CocoaPods 依赖"""
|
||||
await log_streamer.emit_step(task_id, "安装依赖")
|
||||
|
||||
pod_dir = _pod_dir(build_dir, xcode)
|
||||
if pod_dir is None:
|
||||
await log_streamer.emit(task_id, "项目未使用 CocoaPods,跳过")
|
||||
return
|
||||
if pod_dir != build_dir:
|
||||
await log_streamer.emit(task_id, f"Podfile 目录: {pod_dir.relative_to(build_dir)}")
|
||||
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"pod", "install",
|
||||
cwd=str(build_dir),
|
||||
cwd=str(pod_dir),
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.STDOUT,
|
||||
)
|
||||
@@ -763,7 +888,7 @@ async def run_pod_install(task_id: str, build_dir: Path):
|
||||
if process.returncode != 0:
|
||||
raise BuildError("pod install 失败", category="config")
|
||||
|
||||
patched_files = await asyncio.to_thread(_patch_afnetworking_private_headers, build_dir)
|
||||
patched_files = await asyncio.to_thread(_patch_afnetworking_private_headers, pod_dir)
|
||||
if patched_files:
|
||||
await log_streamer.emit(
|
||||
task_id,
|
||||
@@ -825,14 +950,21 @@ async def run_obfuscation(task_id: str, task, config_data: dict, build_dir: Path
|
||||
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, "构建项目")
|
||||
|
||||
scheme = config_data.get("SCHEME", "")
|
||||
export_path = build_dir / "build"
|
||||
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)
|
||||
|
||||
@@ -840,7 +972,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
|
||||
await log_streamer.emit(task_id, "清理项目...")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"xcodebuild", "clean",
|
||||
"-workspace", workspace_path.name,
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
"-configuration", "Release",
|
||||
"-derivedDataPath", str(export_path / "derived_data"),
|
||||
@@ -859,7 +991,7 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
|
||||
archive_output = []
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"xcodebuild", "archive",
|
||||
"-workspace", workspace_path.name,
|
||||
*container_args,
|
||||
"-scheme", scheme,
|
||||
"-configuration", "Release",
|
||||
"-archivePath", str(archive_path),
|
||||
@@ -914,15 +1046,22 @@ async def build_project(task_id: str, task, config_data: dict, build_dir: Path)
|
||||
return ipa_path
|
||||
|
||||
|
||||
async def find_dsym(task_id: str, build_dir: Path) -> Path:
|
||||
"""查找 dSYM 文件"""
|
||||
async def find_dsym(task_id: str, build_dir: Path, scheme: str = "") -> Path:
|
||||
"""查找当前 target(主 App)对应的 dSYM 文件,忽略 Extension/Framework 各自的 dSYM"""
|
||||
derived_data = build_dir / "build" / "derived_data"
|
||||
if not derived_data.exists():
|
||||
return None
|
||||
|
||||
for dsym in derived_data.rglob("*.dSYM"):
|
||||
return dsym
|
||||
return None
|
||||
dsyms = list(derived_data.rglob("*.dSYM"))
|
||||
if not dsyms:
|
||||
return None
|
||||
|
||||
if scheme:
|
||||
for dsym in dsyms:
|
||||
if dsym.name == f"{scheme}.app.dSYM":
|
||||
return dsym
|
||||
|
||||
return dsyms[0]
|
||||
|
||||
|
||||
async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, build_dir: Path) -> tuple:
|
||||
@@ -930,11 +1069,20 @@ async def upload_ipa(task_id: str, task, config_data: dict, ipa_path: Path, buil
|
||||
await log_streamer.emit_step(task_id, "上传分发平台")
|
||||
|
||||
# 从当前服务的 config.json 读取上传配置,不执行分支源码中的上传脚本。
|
||||
from ..routers.config import load_config
|
||||
full_config = load_config()
|
||||
config_data["_upload_config"] = full_config.get("upload", {})
|
||||
from ..routers.config import load_upload_config
|
||||
config_data["_upload_config"] = load_upload_config()
|
||||
try:
|
||||
await log_streamer.emit(task_id, f"使用 {config_data['_upload_config'].get('mode', '')} 发布 IPA...")
|
||||
return await asyncio.to_thread(publish_ipa, config_data, ipa_path, build_dir)
|
||||
except DistributionError as exc:
|
||||
raise BuildError(str(exc), category="upload") from exc
|
||||
|
||||
|
||||
async def upload_dsym(task_id: str, task, config_data: dict, dsym_path: Path, build_dir: Path) -> str:
|
||||
"""上传 dSYM,返回下载 URL;上传失败仅记录警告,不影响已完成的打包结果"""
|
||||
await log_streamer.emit_step(task_id, "上传 dSYM")
|
||||
try:
|
||||
return await asyncio.to_thread(publish_dsym, config_data, dsym_path, build_dir)
|
||||
except DistributionError as exc:
|
||||
await log_streamer.emit(task_id, f"dSYM 上传失败: {exc}", level="warn")
|
||||
return ""
|
||||
|
||||
@@ -4,6 +4,7 @@ import plistlib
|
||||
import posixpath
|
||||
import re
|
||||
import shutil
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, unquote, urlparse
|
||||
|
||||
@@ -54,18 +55,149 @@ def _write_manifest(config: dict, manifest: Path, ipa_url: str):
|
||||
plistlib.dump(data, f)
|
||||
|
||||
|
||||
DOWNLOAD_PAGE_TEMPLATE = """<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="format-detection" content="telephone=no">
|
||||
<title>{title} - 安装</title>
|
||||
<style>
|
||||
:root {{
|
||||
--bg: #f2f3f7;
|
||||
--card: #ffffff;
|
||||
--text: #1c1c1e;
|
||||
--muted: #8a8a8e;
|
||||
--line: rgba(60, 60, 67, .12);
|
||||
--brand: #50a0ff;
|
||||
}}
|
||||
@media (prefers-color-scheme: dark) {{
|
||||
:root {{
|
||||
--bg: #000000;
|
||||
--card: #1c1c1e;
|
||||
--text: #f5f5f7;
|
||||
--muted: #98989d;
|
||||
--line: rgba(255, 255, 255, .12);
|
||||
}}
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
padding: 10vh 20px calc(32px + env(safe-area-inset-bottom));
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 16px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", Arial, sans-serif;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}}
|
||||
.card {{
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
background: var(--card);
|
||||
border-radius: 20px;
|
||||
padding: 28px 24px 24px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, .08);
|
||||
text-align: center;
|
||||
}}
|
||||
.name {{
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
word-break: break-word;
|
||||
}}
|
||||
.version {{
|
||||
margin: 6px 0 22px;
|
||||
color: var(--muted);
|
||||
font-size: 15px;
|
||||
}}
|
||||
.install {{
|
||||
display: block;
|
||||
padding: 15px;
|
||||
border-radius: 14px;
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}}
|
||||
.install:active {{ opacity: .75; }}
|
||||
.meta {{
|
||||
margin: 22px 0 0;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--line);
|
||||
text-align: left;
|
||||
font-size: 14px;
|
||||
}}
|
||||
.meta div {{
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 5px 0;
|
||||
}}
|
||||
.meta dt {{ color: var(--muted); flex: none; }}
|
||||
.meta dd {{
|
||||
margin: 0;
|
||||
text-align: right;
|
||||
word-break: break-all;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}}
|
||||
.tips {{
|
||||
margin: 18px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
text-align: left;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1 class="name">{title}</h1>
|
||||
<p class="version">版本 {version}</p>
|
||||
<a class="install" href="{install_url}">安装 App</a>
|
||||
<dl class="meta">{meta}</dl>
|
||||
<p class="tips">请使用 iPhone 自带的 Safari 浏览器打开本页面安装。<br>
|
||||
安装后如提示“未受信任的开发者”,请前往「设置 → 通用 → VPN 与设备管理」信任该描述文件。</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def _write_download_page(config: dict, html: Path, manifest_url: str):
|
||||
install_url = f"itms-services://?action=download-manifest&url={quote(manifest_url, safe=':/?=&') }"
|
||||
title = config.get("APPID_NAME", "iOS App")
|
||||
install_url = f"itms-services://?action=download-manifest&url={quote(manifest_url, safe=':/?=&')}"
|
||||
title = config.get("APPID_NAME") or "iOS App"
|
||||
meta_items = [
|
||||
("构建版本", config.get("BUILD_VERSION", "")),
|
||||
("Bundle ID", config.get("BUNDLE_ID", "")),
|
||||
("Tag" if config.get("SOURCE_REF_TYPE") == "tag" else "分支", config.get("SOURCE_BRANCH", "")),
|
||||
]
|
||||
meta = "".join(
|
||||
f"<div><dt>{escape(label)}</dt><dd>{escape(str(value))}</dd></div>"
|
||||
for label, value in meta_items
|
||||
if value
|
||||
)
|
||||
html.write_text(
|
||||
"<!doctype html><html lang=\"zh-CN\"><meta charset=\"utf-8\">"
|
||||
f"<title>{title}</title><body><h2>{title}</h2>"
|
||||
f"<p>版本 {config.get('VERSION', '')}</p><a href=\"{install_url}\">安装 App</a>"
|
||||
"</body></html>",
|
||||
DOWNLOAD_PAGE_TEMPLATE.format(
|
||||
title=escape(title),
|
||||
version=escape(str(config.get("VERSION", ""))),
|
||||
install_url=escape(install_url, quote=True),
|
||||
meta=meta,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def _dsym_remote_path(config: dict) -> str:
|
||||
stem = _artifact_stem(config)
|
||||
folder = config.get("OSS_FLODER", "ios-builds").strip("/") or "ios-builds"
|
||||
return posixpath.join(folder, "iOS", f"{stem}.dSYM.zip")
|
||||
|
||||
|
||||
def _remote_paths(config: dict) -> tuple[str, str, str, str]:
|
||||
stem = _artifact_stem(config)
|
||||
folder = config.get("OSS_FLODER", "ios-builds").strip("/") or "ios-builds"
|
||||
@@ -84,12 +216,10 @@ def _delete_webdav(config: dict, remote_paths: list[str]):
|
||||
if not server_url or not webdav.get("username"):
|
||||
raise DistributionError("WebDAV 配置不完整")
|
||||
|
||||
base_path = webdav.get("base_path", "/ios-builds").strip("/")
|
||||
auth = (webdav.get("username", ""), webdav.get("password", ""))
|
||||
with httpx.Client(auth=auth, timeout=120, follow_redirects=True) as client:
|
||||
for relative_path in remote_paths:
|
||||
remote_path = posixpath.join(base_path, relative_path)
|
||||
response = client.delete(f"{server_url}/{remote_path}")
|
||||
response = client.delete(f"{server_url}/{quote(relative_path, safe='/')}")
|
||||
# 404 代表文件已不存在,可视为清理完成。
|
||||
if response.status_code not in (200, 202, 204, 404):
|
||||
raise DistributionError(f"WebDAV 删除失败: {relative_path} ({response.status_code})")
|
||||
@@ -126,15 +256,37 @@ def _remote_paths_from_published_url(
|
||||
return None
|
||||
|
||||
remote_path = unquote(parsed.path).lstrip("/")
|
||||
# base_url 允许带路径前缀;该前缀是公开地址的一部分,不属于 OSS 对象键。
|
||||
base_url = upload_config.get("oss", {}).get("base_url", "")
|
||||
if any(segment == ".." for segment in remote_path.split("/")):
|
||||
return None
|
||||
# 公开地址允许带路径前缀;该前缀是下载路由的一部分,不属于远端文件路径。
|
||||
mode = upload_config.get("mode")
|
||||
if mode == "webdav":
|
||||
webdav = upload_config.get("webdav", {})
|
||||
base_url = webdav.get("public_url", "")
|
||||
else:
|
||||
base_url = upload_config.get("oss", {}).get("base_url", "")
|
||||
base = urlparse(base_url)
|
||||
if base_url and base.netloc == parsed.netloc:
|
||||
base_path = unquote(base.path).strip("/")
|
||||
if base_path and remote_path.startswith(f"{base_path}/"):
|
||||
remote_path = remote_path[len(base_path) + 1:]
|
||||
|
||||
# Historical WebDAV links may contain the configured directory twice, e.g.
|
||||
# public_url=/iOS plus base_path=/iOS produced /iOS/iOS/file. If public_url
|
||||
# was later corrected to the site root, the current prefix stripping above
|
||||
# cannot remove the old extra segment. Files were still uploaded only once
|
||||
# under base_path, so collapse that duplicated prefix when recovering the
|
||||
# remote path for deletion.
|
||||
if mode == "webdav":
|
||||
configured_path = str(webdav.get("base_path") or "/").strip("/")
|
||||
if configured_path:
|
||||
duplicated_prefix = f"{configured_path}/{configured_path}/"
|
||||
if remote_path.startswith(duplicated_prefix):
|
||||
remote_path = remote_path[len(configured_path) + 1:]
|
||||
|
||||
path = Path(remote_path)
|
||||
if path.suffix == ".zip":
|
||||
return [str(path)]
|
||||
if path.suffix not in {".ipa", ".plist", ".html", ".png"}:
|
||||
return None
|
||||
if build_config.get("BUILD_TYPE") == "App_Store":
|
||||
@@ -155,28 +307,46 @@ def delete_published_artifacts(
|
||||
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
||||
|
||||
remote_paths = None
|
||||
if mode == "oss" and published_url:
|
||||
if published_url:
|
||||
remote_paths = _remote_paths_from_published_url(
|
||||
build_config, upload_config, published_url,
|
||||
)
|
||||
if not remote_paths:
|
||||
ipa_remote, manifest_remote, html_remote, qr_remote = _remote_paths(build_config)
|
||||
remote_paths = [ipa_remote]
|
||||
paths = [ipa_remote]
|
||||
if build_config.get("BUILD_TYPE") != "App_Store":
|
||||
remote_paths.extend([manifest_remote, html_remote, qr_remote])
|
||||
paths.extend([manifest_remote, html_remote, qr_remote])
|
||||
if mode == "webdav":
|
||||
remote_paths = [_webdav_remote_path(upload_config, Path(path).name) for path in paths]
|
||||
else:
|
||||
remote_paths = paths
|
||||
|
||||
deleter = _delete_oss if mode == "oss" else _delete_webdav
|
||||
deleter(upload_config, remote_paths)
|
||||
|
||||
|
||||
def get_published_download_url(build_config: dict, upload_config: dict, published_url: str) -> str:
|
||||
"""返回用于受控下载的短时链接;WebDAV 保持原公开链接。"""
|
||||
if upload_config.get("mode") != "oss":
|
||||
return published_url
|
||||
def delete_published_dsym(build_config: dict, upload_config: dict, published_url: str = ""):
|
||||
"""删除任务对应的远端 dSYM 压缩包。
|
||||
|
||||
remote_paths = _remote_paths_from_published_url(build_config, upload_config, published_url)
|
||||
dSYM 的远端对象键完全由构建配置(APPID/版本/分支/构建类型)决定,
|
||||
无需像 IPA 那样从已保存的下载链接反推,直接按命名规则删除即可。
|
||||
"""
|
||||
mode = upload_config.get("mode", "")
|
||||
if mode not in {"oss", "webdav"}:
|
||||
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
||||
|
||||
remote_paths = _remote_paths_from_published_url(build_config, upload_config, published_url) if published_url else None
|
||||
if not remote_paths:
|
||||
raise DistributionError("无法识别 OSS 文件路径,无法生成受控下载链接")
|
||||
remote_path = _dsym_remote_path(build_config)
|
||||
if mode == "webdav":
|
||||
remote_path = _webdav_remote_path(upload_config, Path(remote_path).name)
|
||||
remote_paths = [remote_path]
|
||||
|
||||
deleter = _delete_oss if mode == "oss" else _delete_webdav
|
||||
deleter(upload_config, remote_paths)
|
||||
|
||||
|
||||
def _sign_oss_url(upload_config: dict, remote_path: str) -> str:
|
||||
oss = upload_config.get("oss", {})
|
||||
required = ["access_key_id", "access_key_secret", "endpoint", "bucket_name"]
|
||||
if any(not oss.get(key) for key in required):
|
||||
@@ -190,18 +360,52 @@ def get_published_download_url(build_config: dict, upload_config: dict, publishe
|
||||
oss2.Auth(oss["access_key_id"], oss["access_key_secret"]),
|
||||
oss["endpoint"], oss["bucket_name"], connect_timeout=30,
|
||||
)
|
||||
return bucket.sign_url("GET", remote_paths[0], DOWNLOAD_URL_EXPIRE_SECONDS, slash_safe=True)
|
||||
return bucket.sign_url("GET", remote_path, DOWNLOAD_URL_EXPIRE_SECONDS, slash_safe=True)
|
||||
|
||||
|
||||
def get_published_download_url(build_config: dict, upload_config: dict, published_url: str) -> str:
|
||||
"""返回用于受控下载的短时链接;WebDAV 保持原公开链接。"""
|
||||
if upload_config.get("mode") != "oss":
|
||||
return published_url
|
||||
|
||||
remote_paths = _remote_paths_from_published_url(build_config, upload_config, published_url)
|
||||
if not remote_paths:
|
||||
raise DistributionError("无法识别 OSS 文件路径,无法生成受控下载链接")
|
||||
return _sign_oss_url(upload_config, remote_paths[0])
|
||||
|
||||
|
||||
def get_published_dsym_url(build_config: dict, upload_config: dict, dsym_url: str) -> str:
|
||||
"""返回 dSYM 受控下载的短时链接;WebDAV 保持原公开链接。
|
||||
|
||||
dSYM 的远端对象键完全由构建配置决定,直接按命名规则重新计算即可,
|
||||
不需要像 IPA 那样从已保存的下载链接反推。
|
||||
"""
|
||||
if upload_config.get("mode") != "oss":
|
||||
return dsym_url
|
||||
return _sign_oss_url(upload_config, _dsym_remote_path(build_config))
|
||||
|
||||
|
||||
def _ensure_webdav_dirs(client: httpx.Client, server_url: str, remote_path: str):
|
||||
path = ""
|
||||
for segment in remote_path.strip("/").split("/")[:-1]:
|
||||
path = f"{path}/{segment}"
|
||||
response = client.request("MKCOL", f"{server_url.rstrip('/')}{path}")
|
||||
response = client.request("MKCOL", f"{server_url.rstrip('/')}{path}/")
|
||||
if response.status_code not in (200, 201, 204, 301, 405):
|
||||
raise DistributionError(f"创建 WebDAV 目录失败: {path} ({response.status_code})")
|
||||
|
||||
|
||||
def _webdav_remote_path(upload_config: dict, filename: str) -> str:
|
||||
"""Return the exact WebDAV destination path configured in the admin UI."""
|
||||
webdav = upload_config.get("webdav", {})
|
||||
base_path = str(webdav.get("base_path") or "/").strip("/")
|
||||
if any(segment in {".", ".."} for segment in base_path.split("/")):
|
||||
raise DistributionError("WebDAV 远程路径不能包含 . 或 ..")
|
||||
filename = Path(filename).name
|
||||
if not filename or filename in {".", ".."}:
|
||||
raise DistributionError("WebDAV 文件名无效")
|
||||
return posixpath.join(base_path, filename) if base_path else filename
|
||||
|
||||
|
||||
def _upload_webdav(config: dict, files: list[tuple[Path, str]]) -> dict[str, str]:
|
||||
webdav = config.get("webdav", {})
|
||||
server_url = webdav.get("server_url", "").rstrip("/")
|
||||
@@ -209,18 +413,18 @@ def _upload_webdav(config: dict, files: list[tuple[Path, str]]) -> dict[str, str
|
||||
if not server_url or not webdav.get("username"):
|
||||
raise DistributionError("WebDAV 配置不完整")
|
||||
|
||||
base_path = webdav.get("base_path", "/ios-builds").strip("/")
|
||||
auth = (webdav.get("username", ""), webdav.get("password", ""))
|
||||
urls = {}
|
||||
with httpx.Client(auth=auth, timeout=120, follow_redirects=True) as client:
|
||||
for local_path, relative_path in files:
|
||||
remote_path = posixpath.join(base_path, relative_path)
|
||||
for local_path, _relative_path in files:
|
||||
# WebDAV 的远程路径由后台配置;不沿用 OSS 的 ios-builds/iOS 对象键。
|
||||
remote_path = _webdav_remote_path(config, local_path.name)
|
||||
_ensure_webdav_dirs(client, server_url, remote_path)
|
||||
with local_path.open("rb") as f:
|
||||
response = client.put(f"{server_url}/{remote_path}", content=f.read())
|
||||
response = client.put(f"{server_url}/{quote(remote_path, safe='/')}", content=f.read())
|
||||
if response.status_code not in (200, 201, 204):
|
||||
raise DistributionError(f"WebDAV 上传失败: {local_path.name} ({response.status_code})")
|
||||
urls[local_path.suffix] = f"{public_url}/{quote(remote_path)}"
|
||||
urls[local_path.suffix] = f"{public_url}/{quote(remote_path, safe='/')}"
|
||||
return urls
|
||||
|
||||
|
||||
@@ -250,6 +454,22 @@ def _upload_oss(config: dict, files: list[tuple[Path, str]]) -> dict[str, str]:
|
||||
return urls
|
||||
|
||||
|
||||
# 桌面端钉钉会把 Markdown 图片裁成约 1.4:1 的横向区域,正方形二维码上下被裁掉
|
||||
# (手机端完整显示)。居中放到 3:2 的白底画布上:桌面端裁掉的只是空白,
|
||||
# 手机端二维码仍占图片宽度的 2/3,不至于太小。
|
||||
_QR_CANVAS_RATIO = 1.5
|
||||
|
||||
|
||||
def _pad_to_wide(image):
|
||||
from PIL import Image
|
||||
|
||||
image = image.convert("RGB")
|
||||
width, height = image.size
|
||||
canvas = Image.new("RGB", (round(height * _QR_CANVAS_RATIO), height), "white")
|
||||
canvas.paste(image, ((canvas.width - width) // 2, 0))
|
||||
return canvas
|
||||
|
||||
|
||||
def publish_ipa(config: dict, ipa_path: Path, build_dir: Path) -> tuple[str, str]:
|
||||
"""发布 IPA,返回下载 URL 与二维码公开 URL。"""
|
||||
upload = config.get("_upload_config", {})
|
||||
@@ -280,6 +500,28 @@ def publish_ipa(config: dict, ipa_path: Path, build_dir: Path) -> tuple[str, str
|
||||
import qrcode
|
||||
except ImportError as exc:
|
||||
raise DistributionError("未安装 qrcode,请重新执行 ./deploy.sh build") from exc
|
||||
qrcode.make(urls[".html"]).save(qr_path)
|
||||
qr = qrcode.QRCode(box_size=5, border=4)
|
||||
qr.add_data(urls[".html"])
|
||||
qr.make(fit=True)
|
||||
_pad_to_wide(qr.make_image(fill_color="black", back_color="white").get_image()).save(qr_path)
|
||||
urls.update(uploader(upload, [(qr_path, qr_remote)]))
|
||||
return urls[".html"], urls[".png"]
|
||||
|
||||
|
||||
def publish_dsym(config: dict, dsym_path: Path, build_dir: Path) -> str:
|
||||
"""压缩并上传主 target 的 dSYM,返回下载 URL。"""
|
||||
upload = config.get("_upload_config", {})
|
||||
mode = upload.get("mode", "")
|
||||
if mode not in {"oss", "webdav"}:
|
||||
raise DistributionError("请选择 OSS 或 WebDAV 上传方式")
|
||||
|
||||
output_dir = build_dir / "distribution"
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
zip_base = output_dir / f"{_artifact_stem(config)}.dSYM"
|
||||
zip_path = Path(shutil.make_archive(
|
||||
str(zip_base), "zip", root_dir=str(dsym_path.parent), base_dir=dsym_path.name,
|
||||
))
|
||||
|
||||
uploader = _upload_oss if mode == "oss" else _upload_webdav
|
||||
urls = uploader(upload, [(zip_path, _dsym_remote_path(config))])
|
||||
return urls[".zip"]
|
||||
|
||||
@@ -27,23 +27,66 @@ def _signed_webhook_url(webhook_url: str, secret: str) -> str:
|
||||
return f"{webhook_url}{separator}timestamp={timestamp}&sign={quote(base64.b64encode(signature))}"
|
||||
|
||||
|
||||
def build_dingtalk_payload(config_data: dict, download_url: str, qr_code_url: str = "") -> dict:
|
||||
def normalize_mobiles(at_mobiles) -> list:
|
||||
"""把手机号配置统一成去重、去空的字符串列表,兼容列表或逗号/换行分隔的字符串。"""
|
||||
if not at_mobiles:
|
||||
return []
|
||||
if isinstance(at_mobiles, str):
|
||||
raw = at_mobiles.replace("\n", ",").replace(",", ",").replace(" ", ",").split(",")
|
||||
else:
|
||||
raw = at_mobiles
|
||||
seen = []
|
||||
for item in raw:
|
||||
mobile = str(item).strip()
|
||||
if mobile and mobile not in seen:
|
||||
seen.append(mobile)
|
||||
return seen
|
||||
|
||||
|
||||
# Ad_Hoc / App_Store 两份 @ 名单在配置中的键名
|
||||
AT_MOBILES_KEYS = ("at_mobiles", "at_mobiles_app_store")
|
||||
|
||||
|
||||
def merge_project_at_mobiles(dingtalk_config: dict, project_at: dict) -> dict:
|
||||
"""项目配置了 @ 名单时覆盖全局名单(按打包类型分别覆盖),为空则沿用全局名单。"""
|
||||
merged = dict(dingtalk_config or {})
|
||||
for key in AT_MOBILES_KEYS:
|
||||
mobiles = normalize_mobiles((project_at or {}).get(key))
|
||||
if mobiles:
|
||||
merged[key] = mobiles
|
||||
return merged
|
||||
|
||||
|
||||
def build_dingtalk_payload(
|
||||
config_data: dict,
|
||||
download_url: str,
|
||||
qr_code_url: str = "",
|
||||
at_mobiles=None,
|
||||
) -> dict:
|
||||
"""生成与 AutoPacking/upload_iap.py 一致的钉钉 Markdown 内容。"""
|
||||
mobiles = normalize_mobiles(at_mobiles)
|
||||
# App_Store 包与 Ad Hoc 用不同标题,App_Store 只有 IPA 下载地址、无二维码。
|
||||
# 标题必须保留「打包」二字:钉钉机器人启用了自定义关键词,缺少关键词会被拒收。
|
||||
heading = "【iOS】App_Store 打包信息" if config_data.get("BUILD_TYPE") == "App_Store" else "【iOS】打包信息"
|
||||
details = (
|
||||
f"**环境:** {config_data.get('SERVER', '')}\n\n"
|
||||
f"**版本:** {config_data.get('VERSION', '')}\n\n"
|
||||
f"**APP名称:** {config_data.get('APPID_NAME', '')}\n\n"
|
||||
f"**包名:** {config_data.get('BUNDLE_ID', '')}\n\n"
|
||||
f"**App Guid:** {config_data.get('APPID', '')}"
|
||||
f"**{config_data.get('APPID_LABEL', 'App Guid')}:** {config_data.get('APPID', '')}"
|
||||
)
|
||||
text = f"## 【iOS】打包信息\n\n{details}\n\n**iOS 下载链接:** {download_url}\n"
|
||||
text = f"## {heading}\n\n{details}\n\n**iOS 下载链接:** {download_url}\n"
|
||||
if qr_code_url:
|
||||
text += f"\n"
|
||||
# 钉钉 markdown 消息必须在正文内出现 @手机号 才会真正 @ 到人,
|
||||
# 仅靠 at.atMobiles 不生效。
|
||||
if mobiles:
|
||||
text += "\n\n" + " ".join(f"@{m}" for m in mobiles)
|
||||
|
||||
return {
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": "iOS应用下载", "text": text},
|
||||
"at": {"atMobiles": [], "isAtAll": False},
|
||||
"at": {"atMobiles": mobiles, "isAtAll": False},
|
||||
}
|
||||
|
||||
|
||||
@@ -61,8 +104,11 @@ def send_dingtalk_notification(
|
||||
if not webhook_url:
|
||||
raise NotificationError("钉钉通知已启用,但未配置 Webhook URL")
|
||||
|
||||
payload = build_dingtalk_payload(config_data, download_url, qr_code_url)
|
||||
payload["at"]["atMobiles"] = dingtalk_config.get("at_mobiles", [])
|
||||
# Ad_Hoc 与 App_Store 使用各自的 @ 名单。
|
||||
mobiles_key = "at_mobiles_app_store" if config_data.get("BUILD_TYPE") == "App_Store" else "at_mobiles"
|
||||
payload = build_dingtalk_payload(
|
||||
config_data, download_url, qr_code_url, dingtalk_config.get(mobiles_key, [])
|
||||
)
|
||||
response = httpx.post(
|
||||
_signed_webhook_url(webhook_url, dingtalk_config.get("secret", "")),
|
||||
json=payload,
|
||||
|
||||
@@ -35,11 +35,15 @@ def _update_plist(path: Path, config: dict):
|
||||
|
||||
plist["CFBundleDisplayName"] = config.get("APPID_NAME", "")
|
||||
plist["AlivcLicenseKey"] = config.get("AlivcLicenseKey", "") or ""
|
||||
|
||||
scheme = (config.get("BUNDLE_ID", "") or "").replace(".", "").lower()
|
||||
values = {
|
||||
"weixinlogin": config.get("weixinlogin", ""),
|
||||
"wechatpay": config.get("weixinpay", ""),
|
||||
"tencent": config.get("tencent", ""),
|
||||
# 企业微信 Schema 与微信登录 AppID 同样存在 CFBundleURLTypes 中
|
||||
# (CFBundleURLName == "wxwork"),未配置则整条移除。
|
||||
"wxwork": (config.get("wxworkSchema", "") or "").strip(),
|
||||
"readoorUrlScheme": scheme,
|
||||
}
|
||||
url_types = []
|
||||
@@ -131,8 +135,14 @@ def _apply_dictionary_config(build_dir: Path, config: dict, messages: list[str])
|
||||
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] = []
|
||||
if config.get("SCHEME") == "readoorDict":
|
||||
_apply_dictionary_config(build_dir, config, messages)
|
||||
@@ -186,3 +196,135 @@ def apply_project_config(build_dir: Path, config: dict) -> list[str]:
|
||||
_write_export_options(build_dir, config)
|
||||
messages.append("工程、签名、版本和分发配置已更新")
|
||||
return messages
|
||||
|
||||
|
||||
# —— 通用工程(patcher = generic)——
|
||||
|
||||
_TEMPLATE_PATTERN = re.compile(r"\$\{([A-Za-z0-9_.]+)\}")
|
||||
_BUILD_SETTINGS_PATTERN = re.compile(r"buildSettings = \{\n(.*?)\n\t*\};", re.DOTALL)
|
||||
_PLAIN_PBX_VALUE = re.compile(r"^[A-Za-z0-9_.$/-]+$")
|
||||
|
||||
|
||||
def _render_template(template: str, config: dict) -> str:
|
||||
"""替换 ${app.X}、${server.X}、${KEY}:分别取 App 字段、服务器环境字段和打包配置;值为空时报错。"""
|
||||
def _lookup(match):
|
||||
name = match.group(1)
|
||||
if name.startswith("app."):
|
||||
value = config.get("APP_VARS", {}).get(name[4:], "")
|
||||
elif name.startswith("server."):
|
||||
value = config.get("SERVER_VARS", {}).get(name[7:], "")
|
||||
else:
|
||||
value = config.get(name, "")
|
||||
if value is None or str(value) == "":
|
||||
raise ProjectPatchError(f"替换规则引用的 {name} 未配置")
|
||||
return str(value)
|
||||
|
||||
return _TEMPLATE_PATTERN.sub(_lookup, template)
|
||||
|
||||
|
||||
def _pbx_value(value: str) -> str:
|
||||
return value if _PLAIN_PBX_VALUE.match(value) else '"' + value.replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
def _patch_pbxproj(path: Path, settings: dict) -> dict:
|
||||
"""在 App 目标的 buildSettings 中替换设置(含 [sdk=iphoneos*] 变体),返回每个设置的替换次数。
|
||||
|
||||
测试目标(含 TEST_HOST / TEST_TARGET_NAME)有自己的 Bundle ID 和签名,跳过。
|
||||
"""
|
||||
if not path.exists():
|
||||
raise ProjectPatchError(f"工程文件不存在: {path.parent.name}/{path.name}")
|
||||
counts = {key: 0 for key in settings}
|
||||
|
||||
def _patch_block(match):
|
||||
block = match.group(1)
|
||||
if "TEST_HOST" in block or "TEST_TARGET_NAME" in block:
|
||||
return match.group(0)
|
||||
for key, value in settings.items():
|
||||
pattern = re.compile(
|
||||
rf'^(\s*)("?{re.escape(key)}(?:\[sdk=iphoneos\*\])?"?) = .*;$', re.MULTILINE
|
||||
)
|
||||
block, n = pattern.subn(lambda m: f"{m.group(1)}{m.group(2)} = {_pbx_value(value)};", block)
|
||||
counts[key] += n
|
||||
return match.group(0).replace(match.group(1), block, 1)
|
||||
|
||||
content = _BUILD_SETTINGS_PATTERN.sub(_patch_block, path.read_text(encoding="utf-8"))
|
||||
path.write_text(content, encoding="utf-8")
|
||||
return counts
|
||||
|
||||
|
||||
def _apply_define_rule(path: Path, name: str, value: str) -> int:
|
||||
"""替换所有未注释的 #define NAME ... 行(#if/#else 各分支中的同名宏都会被替换)。"""
|
||||
pattern = re.compile(rf"^([ \t]*#define[ \t]+{re.escape(name)})(?:[ \t].*)?$", re.MULTILINE)
|
||||
content, count = pattern.subn(lambda m: f"{m.group(1)} {value}", path.read_text(encoding="utf-8"))
|
||||
path.write_text(content, encoding="utf-8")
|
||||
return count
|
||||
|
||||
|
||||
def _resolve_rule_file(build_dir: Path, file: str) -> Path:
|
||||
path = (build_dir / file).resolve()
|
||||
if not file or not path.is_relative_to(build_dir.resolve()):
|
||||
raise ProjectPatchError(f"替换规则文件路径无效: {file}")
|
||||
if not path.is_file():
|
||||
raise ProjectPatchError(f"替换规则文件不存在: {file}")
|
||||
return path
|
||||
|
||||
|
||||
def apply_generic_config(build_dir: Path, config: dict, definition: dict) -> list[str]:
|
||||
"""通用工程:替换 pbxproj 的版本号与签名、生成 exportOptions.plist,再执行项目的 patch_rules。
|
||||
|
||||
patch_rules 每项:
|
||||
{"type": "define", "file": "相对路径", "name": "宏名", "value": "模板"}
|
||||
替换所有未注释的 #define 宏名 行
|
||||
{"type": "replace_line", "file": "相对路径", "keyword": "关键字", "line": "模板"}
|
||||
整行替换包含关键字且未注释的行
|
||||
模板中的 ${app.X} / ${server.X} / ${KEY} 取 App 字段、服务器环境字段、打包配置。
|
||||
"""
|
||||
messages: list[str] = []
|
||||
xcodeproj = (definition.get("xcode") or {}).get("project", "")
|
||||
if not xcodeproj:
|
||||
raise ProjectPatchError("项目未配置 Xcode project(.xcodeproj)")
|
||||
|
||||
settings = {
|
||||
"MARKETING_VERSION": config.get("VERSION", ""),
|
||||
"CURRENT_PROJECT_VERSION": config.get("BUILD_VERSION", ""),
|
||||
}
|
||||
if config.get("BUNDLE_ID"):
|
||||
settings["PRODUCT_BUNDLE_IDENTIFIER"] = config["BUNDLE_ID"]
|
||||
if not config.get("NO_CERT"):
|
||||
if config.get("TEAM_ID"):
|
||||
settings["DEVELOPMENT_TEAM"] = config["TEAM_ID"]
|
||||
if config.get("PROVISIONING_NAME"):
|
||||
settings["PROVISIONING_PROFILE_SPECIFIER"] = config["PROVISIONING_NAME"]
|
||||
settings["CODE_SIGN_STYLE"] = "Manual"
|
||||
settings["CODE_SIGN_IDENTITY"] = "iPhone Distribution"
|
||||
|
||||
counts = _patch_pbxproj(build_dir / xcodeproj / "project.pbxproj", settings)
|
||||
missing = [key for key in ("MARKETING_VERSION", "CURRENT_PROJECT_VERSION") if counts[key] == 0]
|
||||
if missing:
|
||||
raise ProjectPatchError(f"未找到待替换配置: {', '.join(missing)}")
|
||||
messages.append(
|
||||
f"工程配置已更新: 版本 {settings['MARKETING_VERSION']} ({settings['CURRENT_PROJECT_VERSION']})"
|
||||
+ (f",Bundle ID {settings['PRODUCT_BUNDLE_IDENTIFIER']}" if "PRODUCT_BUNDLE_IDENTIFIER" in settings else "")
|
||||
)
|
||||
|
||||
for index, rule in enumerate(definition.get("patch_rules") or [], start=1):
|
||||
rule_type = rule.get("type")
|
||||
path = _resolve_rule_file(build_dir, rule.get("file", ""))
|
||||
if rule_type == "define":
|
||||
name = rule.get("name", "")
|
||||
value = _render_template(rule.get("value", ""), config)
|
||||
if _apply_define_rule(path, name, value) == 0:
|
||||
raise ProjectPatchError(f"{rule['file']} 中未找到 #define {name}")
|
||||
messages.append(f"{rule['file']}: #define {name} {value}")
|
||||
elif rule_type == "replace_line":
|
||||
keyword = rule.get("keyword", "")
|
||||
line = _render_template(rule.get("line", ""), config)
|
||||
if not keyword or _replace_lines(path, keyword, line) == 0:
|
||||
raise ProjectPatchError(f"{rule['file']} 中未找到包含 {keyword} 的行")
|
||||
messages.append(f"{rule['file']}: {line.strip()}")
|
||||
else:
|
||||
raise ProjectPatchError(f"第 {index} 条替换规则类型无效: {rule_type}")
|
||||
|
||||
_write_export_options(build_dir, config)
|
||||
messages.append("签名和分发配置已更新")
|
||||
return messages
|
||||
|
||||
+13
-5
@@ -11,6 +11,7 @@
|
||||
"tencent": "",
|
||||
"weixinlogin": "",
|
||||
"weixinpay": "",
|
||||
"wxworkSchema": "",
|
||||
"skins": ["default.zip"],
|
||||
"certificates": {
|
||||
"Ad_Hoc": {
|
||||
@@ -46,7 +47,7 @@
|
||||
}
|
||||
},
|
||||
"next_app_id_prefix": 3,
|
||||
"branches": ["master", "develop"],
|
||||
"branches": ["master", "develop", "feature/示例分支"],
|
||||
"upload": {
|
||||
"mode": "webdav",
|
||||
"oss": {
|
||||
@@ -66,14 +67,21 @@
|
||||
"dingtalk": {
|
||||
"enabled": false,
|
||||
"webhook_url": "",
|
||||
"secret": ""
|
||||
"secret": "",
|
||||
"at_mobiles": [],
|
||||
"at_mobiles_app_store": []
|
||||
}
|
||||
},
|
||||
"versions": {
|
||||
"tracks": {
|
||||
"release": { "app_ver": "2.180.0", "build_map": {} },
|
||||
"feature": { "app_ver": "2.180.0", "build_map": {} }
|
||||
"release": { "kind": "release", "app_ver": "2.180.0", "build_map": {} },
|
||||
"develop": { "kind": "release", "app_ver": "2.180.0", "build_map": {} },
|
||||
"feature/示例分支": { "kind": "feature", "app_ver": "2.180.0", "build_map": {} }
|
||||
}
|
||||
},
|
||||
"branch_track": { "master": "release", "develop": "release" }
|
||||
"branch_track": {
|
||||
"master": "release",
|
||||
"develop": "develop",
|
||||
"feature/示例分支": "feature/示例分支"
|
||||
}
|
||||
}
|
||||
|
||||
+48
-2
@@ -3,6 +3,14 @@
|
||||
<header class="header">
|
||||
<h1>iOS 自动打包服务</h1>
|
||||
<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">
|
||||
<router-link to="/build">打包</router-link>
|
||||
<router-link to="/history">历史</router-link>
|
||||
@@ -21,7 +29,8 @@
|
||||
</header>
|
||||
|
||||
<template v-if="isLoggedIn">
|
||||
<router-view />
|
||||
<!-- 切换项目时重建页面,按新项目重新加载数据 -->
|
||||
<router-view v-if="projectReady" :key="currentProject" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="login-required">
|
||||
@@ -52,7 +61,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, provide } from 'vue'
|
||||
import { ref, computed, onMounted, provide, watch } from 'vue'
|
||||
|
||||
const isLoggedIn = ref(false)
|
||||
const isAdmin = ref(false)
|
||||
@@ -67,6 +76,40 @@ provide('isAdmin', isAdmin)
|
||||
// 获取存储的 token
|
||||
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 请求使用
|
||||
provide('getToken', getToken)
|
||||
|
||||
@@ -83,6 +126,7 @@ const login = async () => {
|
||||
isAdmin.value = data.is_admin
|
||||
showLogin.value = false
|
||||
localStorage.setItem('authToken', data.token)
|
||||
await loadProjects()
|
||||
} else {
|
||||
alert('用户名或密码错误')
|
||||
}
|
||||
@@ -112,6 +156,7 @@ onMounted(async () => {
|
||||
const data = await res.json()
|
||||
isLoggedIn.value = true
|
||||
isAdmin.value = data.is_admin
|
||||
await loadProjects()
|
||||
} else {
|
||||
localStorage.removeItem('authToken')
|
||||
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.router-link-active { background: #16213e; 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-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; }
|
||||
|
||||
@@ -73,6 +73,46 @@ describe('BuildView.vue', () => {
|
||||
expect(branchSelect).toBeTruthy()
|
||||
})
|
||||
|
||||
it('分支和 Tag 分组显示,可选择 Tag 提交', async () => {
|
||||
fetch.mockImplementation((url, opts) => {
|
||||
if (url === '/api/tasks' && opts?.method === 'POST') {
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({ id: 'tag-task', status: 'pending' }) })
|
||||
}
|
||||
const responses = {
|
||||
'/api/apps': { '1': { name: '测试App', server: '测试环境', certificates: { Ad_Hoc: {} } } },
|
||||
'/api/schemes': { '1': { name: 'testScheme' } },
|
||||
'/api/branches': ['main', 'dev'],
|
||||
'/api/tags': ['v3.2.0'],
|
||||
'/api/tasks': [],
|
||||
}
|
||||
return Promise.resolve({ json: () => Promise.resolve(responses[url] || {}) })
|
||||
})
|
||||
|
||||
const wrapper = mountBuildView()
|
||||
await flushPromises()
|
||||
|
||||
const groups = wrapper.findAll('optgroup')
|
||||
expect(groups.map(g => g.attributes('label'))).toEqual(['分支', 'Tag'])
|
||||
expect(groups[1].findAll('option').map(o => o.text())).toEqual(['v3.2.0'])
|
||||
|
||||
wrapper.vm.selectedServer = '测试环境'
|
||||
await wrapper.vm.$nextTick()
|
||||
wrapper.vm.form.app_id = '1'
|
||||
wrapper.vm.form.branch = 'v3.2.0'
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.find('.btn-primary').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const post = fetch.mock.calls.find(([url, opts]) => url === '/api/tasks' && opts?.method === 'POST')
|
||||
expect(JSON.parse(post[1].body).branch).toBe('v3.2.0')
|
||||
})
|
||||
|
||||
it('没有 Tag 时不显示 Tag 分组', async () => {
|
||||
const wrapper = mountBuildView()
|
||||
await flushPromises()
|
||||
expect(wrapper.findAll('optgroup').map(g => g.attributes('label'))).toEqual(['分支'])
|
||||
})
|
||||
|
||||
it('默认值正确', async () => {
|
||||
const wrapper = mountBuildView()
|
||||
await flushPromises()
|
||||
|
||||
@@ -23,15 +23,18 @@ function mockFetch(url) {
|
||||
'/api/config/schemes': { '1': { name: 'testScheme', ossFloder: 'test' } },
|
||||
'/api/config/servers': { '测试环境': { api: 'https://test.com', assDom: '', universalLink: '' } },
|
||||
'/api/config/branches': ['main', 'dev'],
|
||||
'/api/config/tags': ['v3.2.0'],
|
||||
'/api/config/build': { max_concurrent_builds: 2, build_dir_retention_hours: 24, build_base_dir: '/tmp' },
|
||||
'/api/config/versions': {
|
||||
app_ver: '2.195.0',
|
||||
build_ver: '2.195.0.0',
|
||||
primary_track: 'release',
|
||||
tracks: {
|
||||
release: { app_ver: '2.195.0', build_ver: '2.195.0.0', build_map: {} },
|
||||
feature: { app_ver: '2.100.0', build_ver: '2.100.0.0', build_map: {} },
|
||||
release: { kind: 'release', app_ver: '2.195.0', build_ver: '2.195.0.0', build_map: {} },
|
||||
dev: { kind: 'feature', app_ver: '2.100.0', build_ver: '2.100.0.0', build_map: {} },
|
||||
'v3.2.0': { kind: 'release', app_ver: '3.2.0', build_ver: '3.2.0.0', build_map: {} },
|
||||
},
|
||||
branch_track: { main: 'release', dev: 'release' },
|
||||
branch_track: { main: 'release', dev: 'dev', 'v3.2.0': 'v3.2.0' },
|
||||
},
|
||||
'/api/config': { apps: {}, schemes: {}, branches: ['main'] },
|
||||
}
|
||||
@@ -191,7 +194,7 @@ describe('ConfigView.vue', () => {
|
||||
expect(fetch.mock.calls.map(c => c[0])).toEqual(['/api/config/apps'])
|
||||
})
|
||||
|
||||
it('两条版本轨道各自独立展示与保存', async () => {
|
||||
it('每个分支的版本号各自独立展示与保存', async () => {
|
||||
const calls = []
|
||||
fetch.mockImplementation((url, opts) => {
|
||||
if (url === '/api/config/versions' && opts?.method === 'PUT') {
|
||||
@@ -212,16 +215,20 @@ describe('ConfigView.vue', () => {
|
||||
await buildMenu.trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// 每个分支一块:main(上架,release 轨)、dev(自测,dev 轨)
|
||||
expect(wrapper.text()).toContain('上架版本号(main)')
|
||||
expect(wrapper.text()).toContain('自测版本号(dev)')
|
||||
|
||||
const inputs = wrapper.findAll('input[type="text"]')
|
||||
expect(inputs[0].element.value).toBe('2.195.0') // release App_Ver
|
||||
expect(inputs[2].element.value).toBe('2.100.0') // feature App_Ver
|
||||
expect(inputs[0].element.value).toBe('2.195.0') // main 分支 App_Ver
|
||||
expect(inputs[2].element.value).toBe('2.100.0') // dev 分支 App_Ver
|
||||
|
||||
await inputs[2].setValue('2.101.0')
|
||||
const saveBtn = wrapper.findAll('.btn-primary').find(b => b.text() === '保存自测版本号')
|
||||
const saveBtn = wrapper.findAll('.btn-primary').find(b => b.text() === '保存 dev 版本号')
|
||||
await saveBtn.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(calls).toEqual([{ track: 'feature', app_ver: '2.101.0', build_ver: '2.101.0.0' }])
|
||||
expect(calls).toEqual([{ track: 'dev', app_ver: '2.101.0', build_ver: '2.101.0.0' }])
|
||||
})
|
||||
|
||||
it('分支管理可切换版本轨道', async () => {
|
||||
@@ -242,10 +249,47 @@ describe('ConfigView.vue', () => {
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const select = wrapper.find('.config-table select')
|
||||
expect(select.element.value).toBe('release')
|
||||
expect(select.element.value).toBe('release') // main → release 轨(上架)
|
||||
await select.setValue('feature')
|
||||
await flushPromises()
|
||||
|
||||
expect(calls).toEqual([{ branch: 'main', track: 'feature' }])
|
||||
})
|
||||
|
||||
it('分支管理可添加和删除 Tag', async () => {
|
||||
window.confirm = vi.fn(() => true)
|
||||
const calls = []
|
||||
fetch.mockImplementation((url, opts) => {
|
||||
if (opts?.method === 'POST' || opts?.method === 'DELETE') {
|
||||
calls.push([opts.method, url, opts.body && JSON.parse(opts.body)])
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({ message: 'ok' }) })
|
||||
}
|
||||
return mockFetch(url)
|
||||
})
|
||||
|
||||
const wrapper = mountConfigView()
|
||||
await flushPromises()
|
||||
|
||||
const branchesMenu = wrapper.findAll('.sidebar-menu li').find(li => li.text() === '分支管理')
|
||||
await branchesMenu.trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const rows = wrapper.findAll('.config-table tbody tr')
|
||||
expect(rows.map(r => r.findAll('td').slice(0, 2).map(td => td.text()))).toEqual([
|
||||
['main', '分支'], ['dev', '分支'], ['v3.2.0', 'Tag'],
|
||||
])
|
||||
|
||||
await wrapper.find('select').setValue('tag')
|
||||
await wrapper.find('input[placeholder="输入 Tag 名称"]').setValue('v3.3.0')
|
||||
await wrapper.findAll('.btn-primary').find(b => b.text() === '添加 Tag').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
await rows[2].find('.action-btn.delete').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(calls).toEqual([
|
||||
['POST', '/api/config/tags', { name: 'v3.3.0' }],
|
||||
['DELETE', '/api/config/tags/v3.2.0', undefined],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,12 +41,17 @@
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>代码分支</label>
|
||||
<label>代码分支 / Tag</label>
|
||||
<select v-model="form.branch">
|
||||
<option v-for="b in branches" :key="b" :value="b">{{ b }}</option>
|
||||
<optgroup label="分支">
|
||||
<option v-for="b in branches" :key="b" :value="b">{{ b }}</option>
|
||||
</optgroup>
|
||||
<optgroup v-if="tags.length" label="Tag">
|
||||
<option v-for="t in tags" :key="`tag:${t}`" :value="t">{{ t }}</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div v-if="supportsObfuscation" class="form-group">
|
||||
<label>代码混淆</label>
|
||||
<div class="checkbox-group">
|
||||
<input type="checkbox" id="obfuscation" v-model="form.obfuscation">
|
||||
@@ -156,17 +161,22 @@ import { useRoute } from 'vue-router'
|
||||
|
||||
const getToken = inject('getToken')
|
||||
|
||||
const currentProject = inject('currentProject', ref(''))
|
||||
const authFetch = (url, options = {}) => {
|
||||
const token = getToken()
|
||||
if (token) {
|
||||
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
||||
}
|
||||
if (currentProject.value) {
|
||||
options.headers = { ...options.headers, 'X-Project': currentProject.value }
|
||||
}
|
||||
return fetch(url, options)
|
||||
}
|
||||
|
||||
const apps = ref({})
|
||||
const schemes = ref({})
|
||||
const branches = ref(['main'])
|
||||
const tags = ref([])
|
||||
const tasks = ref([])
|
||||
const selectedServer = ref('')
|
||||
const serverEnvironments = computed(() => {
|
||||
@@ -176,6 +186,9 @@ const filteredApps = computed(() => {
|
||||
return Object.entries(apps.value).filter(([, app]) => app.server === selectedServer.value)
|
||||
})
|
||||
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 certificates = selectedApp.value?.certificates || {}
|
||||
return ['Ad_Hoc', 'App_Store'].filter(buildType => Boolean(certificates[buildType]))
|
||||
@@ -314,15 +327,18 @@ onUnmounted(() => {
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
const [appsRes, schemesRes, branchesRes, tasksRes] = await Promise.all([
|
||||
const [appsRes, schemesRes, branchesRes, tagsRes, tasksRes] = await Promise.all([
|
||||
authFetch('/api/apps'),
|
||||
authFetch('/api/schemes'),
|
||||
authFetch('/api/branches'),
|
||||
authFetch('/api/tags'),
|
||||
authFetch('/api/tasks'),
|
||||
])
|
||||
apps.value = await appsRes.json()
|
||||
schemes.value = await schemesRes.json()
|
||||
branches.value = await branchesRes.json()
|
||||
const tagList = await tagsRes.json()
|
||||
tags.value = Array.isArray(tagList) ? tagList : []
|
||||
const allTasks = await tasksRes.json()
|
||||
|
||||
// 从历史页跳转过来时,读取 taskId 查询参数
|
||||
@@ -364,7 +380,7 @@ const submitTask = async () => {
|
||||
const res = await authFetch('/api/tasks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form.value),
|
||||
body: JSON.stringify({ ...form.value, obfuscation: supportsObfuscation.value && form.value.obfuscation }),
|
||||
})
|
||||
if (res.ok) {
|
||||
const task = await res.json()
|
||||
@@ -436,7 +452,7 @@ const errorCategoryHint = (cat) => {
|
||||
provisioning: '描述文件问题:描述文件过期、不匹配或未安装',
|
||||
compilation: '代码编译错误:请检查代码语法和类型引用',
|
||||
dependency: '依赖问题:Pod 依赖缺失或版本不兼容',
|
||||
git: '代码拉取失败:请检查分支是否存在',
|
||||
git: '代码拉取失败:请检查分支或 Tag 是否存在',
|
||||
config: '配置替换失败:请检查打包配置',
|
||||
build: '构建配置错误:请检查 Scheme 和 Workspace 配置',
|
||||
unknown: '打包失败:请查看详细日志排查原因',
|
||||
@@ -497,7 +513,7 @@ const errorCategoryHint = (cat) => {
|
||||
.download-link { color: #1890ff; text-decoration: none; }
|
||||
.download-link:hover { text-decoration: underline; }
|
||||
.qr-section { text-align: center; padding: 16px; background: #fafafa; border-radius: 8px; }
|
||||
.qr-image { width: 180px; height: 180px; border: 1px solid #f0f0f0; border-radius: 8px; }
|
||||
.qr-image { width: 180px; height: 180px; object-fit: contain; border: 1px solid #f0f0f0; border-radius: 8px; }
|
||||
.qr-hint { margin-top: 8px; font-size: 13px; color: #999; }
|
||||
.error-msg { color: #ff4d4f; font-size: 13px; word-break: break-all; }
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
<div v-else class="admin-page">
|
||||
<div class="sidebar">
|
||||
<h3>配置管理</h3>
|
||||
<div v-if="currentProjectInfo" class="sidebar-project">当前项目:{{ currentProjectInfo.name }}</div>
|
||||
<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 === 'servers' }" @click="tab = 'servers'">服务器环境</li>
|
||||
<li :class="{ active: tab === 'apps' }" @click="tab = 'apps'">Apps 配置</li>
|
||||
@@ -20,6 +22,38 @@
|
||||
</ul>
|
||||
</div>
|
||||
<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'">
|
||||
<h2>用户管理</h2>
|
||||
@@ -65,20 +99,22 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th>环境名称</th>
|
||||
<th>API 地址</th>
|
||||
<th v-if="isReadoorProject">API 地址</th>
|
||||
<th>App ID 前缀</th>
|
||||
<th>Associated Domains</th>
|
||||
<th>Universal Link</th>
|
||||
<th v-if="isReadoorProject">Associated Domains</th>
|
||||
<th v-if="isReadoorProject">Universal Link</th>
|
||||
<th v-for="field in serverFields" :key="field.key">{{ field.label }}</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(server, name) in servers" :key="name">
|
||||
<td><strong>{{ name }}</strong></td>
|
||||
<td>{{ server.api }}</td>
|
||||
<td v-if="isReadoorProject">{{ server.api }}</td>
|
||||
<td>{{ server.app_id_prefix }}</td>
|
||||
<td>{{ server.assDom }}</td>
|
||||
<td>{{ server.universalLink }}</td>
|
||||
<td v-if="isReadoorProject">{{ server.assDom }}</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">
|
||||
<button class="action-btn" @click="openServerModal(name, server)">编辑</button>
|
||||
<button class="action-btn delete" @click="deleteServer(name)">删除</button>
|
||||
@@ -98,7 +134,8 @@
|
||||
<th>ID</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>
|
||||
</tr>
|
||||
@@ -108,7 +145,8 @@
|
||||
<td>{{ id }}</td>
|
||||
<td>{{ app.name }}</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 class="action-btns">
|
||||
<button class="action-btn" @click="openAppModal(id, app)">编辑</button>
|
||||
@@ -152,36 +190,42 @@
|
||||
<div v-if="tab === 'branches'">
|
||||
<h2>分支管理</h2>
|
||||
<p style="color: #666; margin-bottom: 16px; font-size: 14px;">
|
||||
管理可打包的代码分支,打包时从对应分支目录获取源码。
|
||||
版本轨道决定该分支使用哪一套版本号:上架(master/develop 共用,App_Store 打包构建号自增)、自测(feature 用,构建号不自增)。
|
||||
管理可打包的代码分支和 Tag,打包时从对应分支或 Tag 获取源码。
|
||||
每个分支 / Tag 各有一套独立的版本号,版本轨道决定构建号行为:上架(App_Store 打包构建号自增)、自测(构建号不自增)。新增 Tag 默认为上架。
|
||||
</p>
|
||||
<div style="display: flex; gap: 12px; margin-bottom: 16px;">
|
||||
<input v-model="newBranch" type="text" placeholder="输入分支名称" style="flex: 1; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px;">
|
||||
<button class="btn btn-primary" style="width: auto; padding: 10px 24px;" @click="addBranch">添加分支</button>
|
||||
<select v-model="newRefType" style="width: auto; padding: 10px 12px;">
|
||||
<option value="branch">分支</option>
|
||||
<option value="tag">Tag</option>
|
||||
</select>
|
||||
<input v-model="newBranch" type="text" :placeholder="newRefType === 'tag' ? '输入 Tag 名称' : '输入分支名称'" style="flex: 1; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 6px; font-size: 14px;">
|
||||
<button class="btn btn-primary" style="width: auto; padding: 10px 24px;" @click="addBranch">{{ newRefType === 'tag' ? '添加 Tag' : '添加分支' }}</button>
|
||||
</div>
|
||||
<table class="config-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>分支名称</th>
|
||||
<th>名称</th>
|
||||
<th>类型</th>
|
||||
<th>版本轨道</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="b in branches" :key="b">
|
||||
<td><strong>{{ b }}</strong></td>
|
||||
<tr v-for="r in buildRefs" :key="`${r.type}:${r.name}`">
|
||||
<td><strong>{{ r.name }}</strong></td>
|
||||
<td>{{ r.type === 'tag' ? 'Tag' : '分支' }}</td>
|
||||
<td>
|
||||
<select :value="branchTrack[b] || 'feature'" style="width: auto; padding: 4px 8px;" @change="setBranchTrack(b, $event.target.value)">
|
||||
<option value="release">上架(master/develop)</option>
|
||||
<option value="feature">自测(feature)</option>
|
||||
<select :value="branchKind(r.name)" style="width: auto; padding: 4px 8px;" @change="setBranchTrack(r.name, $event.target.value)">
|
||||
<option value="release">上架(App_Store 打包构建号自增)</option>
|
||||
<option value="feature">自测(构建号不自增)</option>
|
||||
</select>
|
||||
</td>
|
||||
<td class="action-btns">
|
||||
<button class="action-btn delete" @click="deleteBranch(b)">删除</button>
|
||||
<button class="action-btn delete" @click="deleteBranch(r)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!branches.length">
|
||||
<td colspan="3" style="text-align: center; color: #999;">暂无分支配置</td>
|
||||
<tr v-if="!buildRefs.length">
|
||||
<td colspan="4" style="text-align: center; color: #999;">暂无分支配置</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -241,7 +285,8 @@
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>远程路径</label>
|
||||
<input v-model="uploadConfig.webdav.base_path" type="text" placeholder="/ios-builds">
|
||||
<input v-model="uploadConfig.webdav.base_path" type="text" placeholder="/iOS">
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">文件直接上传到此目录,不会自动追加 ios-builds/iOS;填 / 表示下载根目录</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>公开访问地址</label>
|
||||
@@ -268,6 +313,16 @@
|
||||
<label>加签密钥(可选)</label>
|
||||
<input v-model="uploadConfig.dingtalk.secret" type="password" placeholder="留空则不加签">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Ad_Hoc @ 开发人员手机号(可选)</label>
|
||||
<textarea v-model="dingtalkAtMobiles" rows="3" placeholder="每行一个手机号,或用逗号分隔;留空则不 @ 人"></textarea>
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">须是钉钉账号绑定的手机号,Ad_Hoc 打包完成的通知会 @ 这些人。</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>App_Store @ 开发人员手机号(可选)</label>
|
||||
<textarea v-model="dingtalkAtMobilesAppStore" rows="3" placeholder="每行一个手机号,或用逗号分隔;留空则不 @ 人"></textarea>
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">App_Store 打包完成的通知会 @ 这些人。</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -279,36 +334,31 @@
|
||||
<div v-if="tab === 'build'">
|
||||
<h2>打包设置</h2>
|
||||
<div style="max-width: 500px;">
|
||||
<h4 class="section-title">上架版本号(master / develop)</h4>
|
||||
<div class="form-group">
|
||||
<label>App_Ver(应用版本)</label>
|
||||
<input type="text" v-model="versions.release.app_ver" placeholder="2.180.0" @input="onAppVerInput('release')">
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">格式:主版本.次版本.修订号。master 与 develop 共用这一套版本号。</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Build_Ver(构建号)</label>
|
||||
<input type="text" v-model="versions.release.build_ver" placeholder="2.180.0.0">
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||
四段数字,前三位须与 App_Ver 一致。修改 App_Ver 会自动切换为该版本号已记录的构建号;
|
||||
每个版本号的构建号独立递增,App_Store 打包时自动 +1。一般无需手动修改。
|
||||
<template v-for="t in branchTracks" :key="t.name">
|
||||
<h4 class="section-title">
|
||||
{{ t.kind === 'release' ? '上架版本号' : '自测版本号' }}({{ t.branches.join(' / ') }})
|
||||
</h4>
|
||||
<div class="form-group">
|
||||
<label>App_Ver(应用版本)</label>
|
||||
<input type="text" v-model="versions[t.name].app_ver" placeholder="2.180.0" @input="onAppVerInput(t.name)">
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||
格式:主版本.次版本.修订号。该版本号只用于 {{ t.branches.join(' / ') }}(轨道 {{ t.name }}),与其它分支 / Tag 互不影响。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-primary" style="width: auto; padding: 10px 32px; margin-bottom: 24px;" @click="saveVersions('release')">保存上架版本号</button>
|
||||
|
||||
<h4 class="section-title">自测版本号(feature 分支)</h4>
|
||||
<div class="form-group">
|
||||
<label>App_Ver(应用版本)</label>
|
||||
<input type="text" v-model="versions.feature.app_ver" placeholder="2.180.0" @input="onAppVerInput('feature')">
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">与上架版本号各自独立,互不影响。</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Build_Ver(构建号)</label>
|
||||
<input type="text" v-model="versions.feature.build_ver" placeholder="2.180.0.0">
|
||||
<div style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||
仅供自测,打包时<strong>不会自动递增</strong>,始终使用这里填写的值(默认 .0)。需要区分时请手动修改。
|
||||
<div class="form-group">
|
||||
<label>Build_Ver(构建号)</label>
|
||||
<input type="text" v-model="versions[t.name].build_ver" placeholder="2.180.0.0">
|
||||
<div v-if="t.kind === 'release'" style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||
四段数字,前三位须与 App_Ver 一致。修改 App_Ver 会自动切换为该版本号已记录的构建号;
|
||||
每个版本号的构建号独立递增,App_Store 打包时自动 +1。一般无需手动修改。
|
||||
</div>
|
||||
<div v-else style="font-size: 12px; color: #999; margin-top: 4px;">
|
||||
四段数字,前三位须与 App_Ver 一致。自测轨打包时<strong>不会自动递增</strong>,
|
||||
始终使用这里填写的值(默认 .0)。需要区分时请手动修改。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-primary" style="width: auto; padding: 10px 32px; margin-bottom: 24px;" @click="saveVersions('feature')">保存自测版本号</button>
|
||||
<button class="btn btn-primary" style="width: auto; padding: 10px 32px; margin-bottom: 24px;" @click="saveVersions(t.name)">保存 {{ t.branches.join(' / ') }} 版本号</button>
|
||||
</template>
|
||||
|
||||
<template v-if="isAdmin">
|
||||
<h4 class="section-title">打包参数</h4>
|
||||
@@ -401,17 +451,23 @@
|
||||
<label>环境名称 *</label>
|
||||
<input v-model="serverForm.name" type="text" placeholder="例如:测试环境" :disabled="!!editingServerName">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>API 地址 *</label>
|
||||
<input v-model="serverForm.api" type="text" placeholder="https://api3-dev.readoor.cn">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Associated Domains</label>
|
||||
<input v-model="serverForm.assDom" type="text" placeholder="applinks:dev-data1.readoor.cn">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Universal Link</label>
|
||||
<input v-model="serverForm.universalLink" type="text" placeholder="https://dev-data1.readoor.cn">
|
||||
<template v-if="isReadoorProject">
|
||||
<div class="form-group">
|
||||
<label>API 地址 *</label>
|
||||
<input v-model="serverForm.api" type="text" placeholder="https://api3-dev.readoor.cn">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Associated Domains</label>
|
||||
<input v-model="serverForm.assDom" type="text" placeholder="applinks:dev-data1.readoor.cn">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<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 class="form-group">
|
||||
<label>App ID 前缀</label>
|
||||
@@ -455,7 +511,7 @@
|
||||
<input v-model.number="appForm.app_id_prefix_override" type="number" min="1" placeholder="仅特殊 App 使用">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div v-if="isReadoorProject" class="form-row">
|
||||
<div class="form-group">
|
||||
<label>AppGuid *</label>
|
||||
<input v-model="appForm.AppGuid" type="text" placeholder="应用唯一标识">
|
||||
@@ -466,7 +522,15 @@
|
||||
</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>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
@@ -488,6 +552,12 @@
|
||||
<input v-model="appForm.weixinpay" type="text" placeholder="wx...">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label>企业微信 Schema</label>
|
||||
<input v-model="appForm.wxworkSchema" type="text" placeholder="不填则不写入 Info.plist(与微信登录 AppID 相同)">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label>腾讯 AppID</label>
|
||||
@@ -498,6 +568,7 @@
|
||||
<input v-model="appForm.AlivcLicenseKey" type="text">
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 证书配置 -->
|
||||
<h4 class="section-title">证书配置</h4>
|
||||
@@ -524,7 +595,7 @@
|
||||
<label>Provisioning Profile 名称</label>
|
||||
<input v-model="appForm.certificates[certType].pro" type="text" placeholder="/Users/.../xxx.mobileprovision">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<div v-if="isReadoorProject" class="form-group">
|
||||
<label>主题目录</label>
|
||||
<select v-if="appSkins.length"
|
||||
:value="appSkins.some(s => s.name.replace('.zip', '') === appForm.certificates[certType].theme) ? appForm.certificates[certType].theme : ''"
|
||||
@@ -544,6 +615,7 @@
|
||||
</div>
|
||||
|
||||
<!-- 皮肤包管理 -->
|
||||
<template v-if="isReadoorProject">
|
||||
<h4 class="section-title" style="margin-top: 20px;">皮肤包管理</h4>
|
||||
<div class="skins-section">
|
||||
<div v-if="!appForm.upload_key" class="skins-hint">请先保存 APP 后再上传皮肤包</div>
|
||||
@@ -571,6 +643,7 @@
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<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>
|
||||
@@ -579,6 +652,118 @@
|
||||
</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">×</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">钉钉 @ 人员(留空使用全局名单)</h4>
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label>Ad_Hoc @ 手机号</label>
|
||||
<textarea v-model="projectForm.at_mobiles_text" rows="3" class="code-textarea" placeholder="每行一个,或用逗号分隔"></textarea>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>App_Store @ 手机号</label>
|
||||
<textarea v-model="projectForm.at_mobiles_app_store_text" rows="3" class="code-textarea" placeholder="每行一个,或用逗号分隔"></textarea>
|
||||
</div>
|
||||
</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 编辑弹窗 -->
|
||||
<div v-if="showSchemeModal" class="modal-overlay" @click.self="showSchemeModal = false">
|
||||
<div class="modal-content">
|
||||
@@ -616,6 +801,16 @@ const isLoggedIn = inject('isLoggedIn')
|
||||
const isAdmin = inject('isAdmin')
|
||||
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 showUserModal = ref(false)
|
||||
@@ -625,40 +820,73 @@ const passwordTarget = ref(null)
|
||||
const newPassword = ref('')
|
||||
|
||||
// 带认证的 fetch 封装
|
||||
const currentProject = inject('currentProject', ref(''))
|
||||
const authFetch = (url, options = {}) => {
|
||||
const token = getToken()
|
||||
if (token) {
|
||||
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
||||
}
|
||||
if (currentProject.value) {
|
||||
options.headers = { ...options.headers, 'X-Project': currentProject.value }
|
||||
}
|
||||
return fetch(url, options)
|
||||
}
|
||||
const apps = ref({})
|
||||
const schemes = ref({})
|
||||
const servers = ref({})
|
||||
const branches = ref([])
|
||||
const tags = ref([])
|
||||
const newBranch = ref('')
|
||||
const newRefType = ref('branch') // 新增的是分支还是 Tag
|
||||
// 分支管理表格:分支在前,Tag 在后
|
||||
const buildRefs = computed(() => [
|
||||
...branches.value.map(name => ({ name, type: 'branch' })),
|
||||
...tags.value.map(name => ({ name, type: 'tag' })),
|
||||
])
|
||||
const buildSettings = ref({})
|
||||
// 两条版本轨道:release(master/develop,上架用)与 feature(自测用),各自独立
|
||||
const versions = ref({
|
||||
release: { app_ver: '', build_ver: '' },
|
||||
feature: { app_ver: '', build_ver: '' },
|
||||
})
|
||||
const buildMap = ref({ release: {}, feature: {} })
|
||||
const branchTrack = ref({})
|
||||
// 版本轨道:每个分支一条独立轨道,轨道名即分支名(master/main 沿用历史名 release)。
|
||||
// 轨道类型 kind 决定构建号行为:release=上架、App_Store 打包自增;feature=自测、不自增。
|
||||
const versions = ref({}) // 轨道名 -> { app_ver, build_ver }
|
||||
const buildMap = ref({}) // 轨道名 -> { App_Ver: 已用构建号 }
|
||||
const trackKind = ref({}) // 轨道名 -> release | feature
|
||||
const branchTrack = ref({}) // 分支名 -> 轨道名
|
||||
|
||||
const applyVersions = (data) => {
|
||||
const tracks = data.tracks || {}
|
||||
for (const track of ['release', 'feature']) {
|
||||
const item = tracks[track] || {}
|
||||
buildMap.value[track] = item.build_map || {}
|
||||
versions.value[track] = { app_ver: item.app_ver || '', build_ver: item.build_ver || '' }
|
||||
const nextVersions = {}
|
||||
const nextMap = {}
|
||||
const nextKind = {}
|
||||
for (const [name, item] of Object.entries(tracks)) {
|
||||
nextVersions[name] = { app_ver: item.app_ver || '', build_ver: item.build_ver || '' }
|
||||
nextMap[name] = item.build_map || {}
|
||||
nextKind[name] = item.kind || 'release'
|
||||
}
|
||||
versions.value = nextVersions
|
||||
buildMap.value = nextMap
|
||||
trackKind.value = nextKind
|
||||
branchTrack.value = data.branch_track || {}
|
||||
}
|
||||
|
||||
// 分支所属轨道的类型(供分支管理里的下拉框显示)
|
||||
const branchKind = (branch) => trackKind.value[branchTrack.value[branch]] || 'feature'
|
||||
|
||||
// 打包设置里按分支分块展示版本号;多个分支共用一条轨道时只显示一块
|
||||
const branchTracks = computed(() => {
|
||||
const seen = new Set()
|
||||
const refs = [...branches.value, ...tags.value]
|
||||
return refs
|
||||
.map(b => branchTrack.value[b])
|
||||
.filter(name => name && versions.value[name] && !seen.has(name) && seen.add(name))
|
||||
.map(name => ({
|
||||
name,
|
||||
kind: trackKind.value[name] || 'release',
|
||||
branches: refs.filter(b => branchTrack.value[b] === name),
|
||||
}))
|
||||
})
|
||||
|
||||
// 修改 App_Ver 时,自动把 Build_Ver 切换为该版本号已记录的构建号(新版本号则为 .0)
|
||||
const onAppVerInput = (track) => {
|
||||
const appVer = (versions.value[track].app_ver || '').trim()
|
||||
const appVer = (versions.value[track]?.app_ver || '').trim()
|
||||
if (/^\d+\.\d+\.\d+$/.test(appVer)) {
|
||||
const n = Number((buildMap.value[track] || {})[appVer] || 0)
|
||||
versions.value[track].build_ver = `${appVer}.${n}`
|
||||
@@ -667,6 +895,21 @@ const onAppVerInput = (track) => {
|
||||
const uploadConfig = ref({ mode: 'oss', oss: {}, webdav: {}, dingtalk: {} })
|
||||
const jsonContent = ref('{}')
|
||||
|
||||
// 钉钉 @ 手机号:配置里存字符串数组,输入框按逗号/换行分隔编辑。
|
||||
// Ad_Hoc 与 App_Store 各一份名单。
|
||||
const dingtalkAtMobilesModel = (key) => computed({
|
||||
get: () => (uploadConfig.value.dingtalk?.[key] || []).join('\n'),
|
||||
set: (val) => {
|
||||
if (!uploadConfig.value.dingtalk) uploadConfig.value.dingtalk = {}
|
||||
uploadConfig.value.dingtalk[key] = val
|
||||
.split(/[\s,,]+/)
|
||||
.map(s => s.trim())
|
||||
.filter(Boolean)
|
||||
},
|
||||
})
|
||||
const dingtalkAtMobiles = dingtalkAtMobilesModel('at_mobiles')
|
||||
const dingtalkAtMobilesAppStore = dingtalkAtMobilesModel('at_mobiles_app_store')
|
||||
|
||||
const showServerModal = ref(false)
|
||||
const editingServerName = ref(null)
|
||||
const serverForm = ref({ name: '', api: '', assDom: '', universalLink: '', app_id_prefix: null })
|
||||
@@ -700,26 +943,137 @@ const loadData = async () => {
|
||||
return
|
||||
}
|
||||
|
||||
const [appsRes, schemesRes, serversRes, branchesRes, 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/schemes'),
|
||||
authFetch('/api/config/servers'),
|
||||
authFetch('/api/config/branches'),
|
||||
authFetch('/api/config/tags'),
|
||||
authFetch('/api/config/build'),
|
||||
authFetch('/api/config/upload'),
|
||||
authFetch('/api/config'),
|
||||
authFetch('/api/config/versions'),
|
||||
authFetch('/api/users'),
|
||||
authFetch('/api/config/projects'),
|
||||
])
|
||||
apps.value = await appsRes.json()
|
||||
schemes.value = await schemesRes.json()
|
||||
servers.value = await serversRes.json()
|
||||
branches.value = await branchesRes.json()
|
||||
const tagList = await tagsRes.json()
|
||||
tags.value = Array.isArray(tagList) ? tagList : []
|
||||
buildSettings.value = await buildRes.json()
|
||||
uploadConfig.value = await uploadRes.json()
|
||||
jsonContent.value = JSON.stringify(await configRes.json(), null, 2)
|
||||
applyVersions(await versionsRes.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 splitMobiles = text => (text || '').split(/[\s,,]+/).map(s => s.trim()).filter(Boolean)
|
||||
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: [],
|
||||
dingtalk_at: { at_mobiles: [], at_mobiles_app_store: [] },
|
||||
}
|
||||
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'),
|
||||
at_mobiles_text: (p.dingtalk_at?.at_mobiles || []).join('\n'),
|
||||
at_mobiles_app_store_text: (p.dingtalk_at?.at_mobiles_app_store || []).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),
|
||||
dingtalk_at: {
|
||||
at_mobiles: splitMobiles(form.at_mobiles_text),
|
||||
at_mobiles_app_store: splitMobiles(form.at_mobiles_app_store_text),
|
||||
},
|
||||
...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)
|
||||
}
|
||||
}
|
||||
|
||||
// 用户管理
|
||||
@@ -817,8 +1171,13 @@ const openServerModal = (name = null, server = null) => {
|
||||
}
|
||||
|
||||
const saveServer = async () => {
|
||||
if (!serverForm.value.name || !serverForm.value.api) {
|
||||
alert('请填写必填字段:环境名称、API 地址')
|
||||
const missing = [
|
||||
...(!serverForm.value.name ? ['环境名称'] : []),
|
||||
...(isReadoorProject.value && !serverForm.value.api ? ['API 地址'] : []),
|
||||
...missingRequiredFields(serverFields.value, serverForm.value),
|
||||
]
|
||||
if (missing.length) {
|
||||
alert(`请填写必填字段:${missing.join('、')}`)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -883,6 +1242,7 @@ const openAppModal = (id = null, app = null) => {
|
||||
UniversalLink: '',
|
||||
weixinlogin: '',
|
||||
weixinpay: '',
|
||||
wxworkSchema: '',
|
||||
tencent: '',
|
||||
AlivcLicenseKey: '',
|
||||
app_id_prefix_override: '',
|
||||
@@ -1021,8 +1381,13 @@ const normalizeTencentAppId = () => {
|
||||
}
|
||||
|
||||
const saveApp = async () => {
|
||||
if (!appForm.value.name || !appForm.value.AppGuid) {
|
||||
alert('请填写必填字段:App 名称、AppGuid')
|
||||
const missing = [
|
||||
...(!appForm.value.name ? ['App 名称'] : []),
|
||||
...(isReadoorProject.value && !appForm.value.AppGuid ? ['AppGuid'] : []),
|
||||
...missingRequiredFields(appFields.value, appForm.value),
|
||||
]
|
||||
if (missing.length) {
|
||||
alert(`请填写必填字段:${missing.join('、')}`)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1130,12 +1495,12 @@ const deleteScheme = async (id) => {
|
||||
await loadData()
|
||||
}
|
||||
|
||||
// 分支管理
|
||||
// 分支管理(分支与 Tag 共用一张表)
|
||||
const addBranch = async () => {
|
||||
const name = newBranch.value.trim()
|
||||
if (!name) return
|
||||
try {
|
||||
const res = await authFetch('/api/config/branches', {
|
||||
const res = await authFetch(newRefType.value === 'tag' ? '/api/config/tags' : '/api/config/branches', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name }),
|
||||
@@ -1162,17 +1527,20 @@ const setBranchTrack = async (name, track) => {
|
||||
const err = await res.json()
|
||||
throw new Error(err.detail || '修改失败')
|
||||
}
|
||||
branchTrack.value = { ...branchTrack.value, [name]: track }
|
||||
// 切到上架轨可能新建了轨道,重新拉取版本号
|
||||
applyVersions(await (await authFetch('/api/config/versions')).json())
|
||||
} catch (e) {
|
||||
alert('修改失败: ' + e.message)
|
||||
await loadData()
|
||||
}
|
||||
}
|
||||
|
||||
const deleteBranch = async (name) => {
|
||||
if (!confirm(`确定删除分支「${name}」?`)) return
|
||||
const deleteBranch = async ({ name, type }) => {
|
||||
const isTag = type === 'tag'
|
||||
if (!confirm(`确定删除${isTag ? ' Tag ' : '分支'}「${name}」?`)) return
|
||||
try {
|
||||
const res = await authFetch(`/api/config/branches/${encodeURIComponent(name)}`, { method: 'DELETE' })
|
||||
const base = isTag ? '/api/config/tags' : '/api/config/branches'
|
||||
const res = await authFetch(`${base}/${encodeURIComponent(name)}`, { method: 'DELETE' })
|
||||
if (!res.ok) throw new Error('删除失败')
|
||||
await loadData()
|
||||
} catch (e) {
|
||||
@@ -1190,7 +1558,7 @@ const saveBuildSettings = async () => {
|
||||
alert('设置已保存')
|
||||
}
|
||||
|
||||
const saveVersions = async (track = 'release') => {
|
||||
const saveVersions = async (track) => {
|
||||
try {
|
||||
const res = await authFetch('/api/config/versions', {
|
||||
method: 'PUT',
|
||||
@@ -1293,6 +1661,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-content { background: white; border-radius: 12px; padding: 24px; width: 500px; max-height: 80vh; overflow-y: auto; }
|
||||
.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 h3 { font-size: 16px; margin: 0; }
|
||||
.modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
<img v-if="task.build_type === 'Ad_Hoc' && task.qr_code_path"
|
||||
:src="task.qr_code_path" alt="QR" class="qr-thumb"
|
||||
@click="showQrPreview(task)">
|
||||
<button v-if="task.build_type === 'App_Store'" class="download-link" @click="downloadIpa(task.id)">下载 IPA</button>
|
||||
<button v-if="task.build_type === 'App_Store'" class="download-link" :disabled="!!downloadingIds[task.id]" @click="downloadIpa(task.id)">{{ downloadingIds[task.id] ? '下载中...' : '下载 IPA' }}</button>
|
||||
</template>
|
||||
<span v-else class="text-muted">-</span>
|
||||
</td>
|
||||
@@ -110,7 +110,7 @@
|
||||
<span :class="['build-type-badge', logTask?.build_type === 'App_Store' ? 'badge-appstore' : 'badge-adhoc']">{{ logTask?.build_type }}</span>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
<span class="meta-label">分支</span>
|
||||
<span class="meta-label">{{ logTask?.ref_type === 'tag' ? 'Tag' : '分支' }}</span>
|
||||
<span class="meta-value">{{ logTask?.branch || '-' }}</span>
|
||||
</div>
|
||||
<div class="meta-item">
|
||||
@@ -159,17 +159,21 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, nextTick, onUnmounted, inject } from 'vue'
|
||||
import { ref, reactive, computed, onMounted, nextTick, onUnmounted, inject } from 'vue'
|
||||
|
||||
const getToken = inject('getToken', () => '')
|
||||
const isAdmin = inject('isAdmin', ref(false))
|
||||
const tasks = ref([])
|
||||
|
||||
const currentProject = inject('currentProject', ref(''))
|
||||
const authFetch = (url, options = {}) => {
|
||||
const token = getToken()
|
||||
if (token) {
|
||||
options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` }
|
||||
}
|
||||
if (currentProject.value) {
|
||||
options.headers = { ...options.headers, 'X-Project': currentProject.value }
|
||||
}
|
||||
return fetch(url, options)
|
||||
}
|
||||
const filterStatus = ref('')
|
||||
@@ -182,6 +186,7 @@ const logContainer = ref(null)
|
||||
const showVerboseLogs = ref(false)
|
||||
const qrPreview = ref(null)
|
||||
const showSuperseded = ref(false)
|
||||
const downloadingIds = reactive({})
|
||||
let logWs = null
|
||||
|
||||
const getAppVersion = (task) => {
|
||||
@@ -308,11 +313,41 @@ onUnmounted(() => {
|
||||
if (logWs) { logWs.close(); logWs = null }
|
||||
})
|
||||
|
||||
const downloadDsym = (taskId) => {
|
||||
window.open(`/api/tasks/${taskId}/dsym`)
|
||||
const triggerBlobDownload = (blob, filename) => {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename || ''
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const filenameFromDisposition = (res, fallback) => {
|
||||
const cd = res.headers.get('content-disposition') || ''
|
||||
const match = cd.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i)
|
||||
return match ? decodeURIComponent(match[1]) : fallback
|
||||
}
|
||||
|
||||
const downloadDsym = async (taskId) => {
|
||||
try {
|
||||
const res = await authFetch(`/api/tasks/${taskId}/dsym`)
|
||||
if (!res.ok) throw new Error()
|
||||
if ((res.headers.get('content-type') || '').includes('application/json')) {
|
||||
const { url } = await res.json()
|
||||
window.open(url, '_blank')
|
||||
} else {
|
||||
triggerBlobDownload(await res.blob(), filenameFromDisposition(res, 'dsym.zip'))
|
||||
}
|
||||
} catch {
|
||||
alert('下载失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const downloadIpa = async (taskId) => {
|
||||
if (downloadingIds[taskId]) return
|
||||
downloadingIds[taskId] = true
|
||||
try {
|
||||
const res = await authFetch(`/api/tasks/${taskId}/download-link`)
|
||||
if (!res.ok) throw new Error()
|
||||
@@ -320,11 +355,19 @@ const downloadIpa = async (taskId) => {
|
||||
window.open(url, '_blank')
|
||||
} catch {
|
||||
alert('下载失败,请稍后重试')
|
||||
} finally {
|
||||
delete downloadingIds[taskId]
|
||||
}
|
||||
}
|
||||
|
||||
const downloadObfMaps = (taskId) => {
|
||||
window.open(`/api/tasks/${taskId}/obfuscation-maps`)
|
||||
const downloadObfMaps = async (taskId) => {
|
||||
try {
|
||||
const res = await authFetch(`/api/tasks/${taskId}/obfuscation-maps`)
|
||||
if (!res.ok) throw new Error()
|
||||
triggerBlobDownload(await res.blob(), filenameFromDisposition(res, 'obfuscation_maps.zip'))
|
||||
} catch {
|
||||
alert('下载失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const deleteTask = async (taskId) => {
|
||||
@@ -524,8 +567,10 @@ const errorCategoryLabel = (cat) => {
|
||||
.btn-close-log:hover { border-color: #1890ff; color: #1890ff; }
|
||||
.download-link { color: #1890ff; text-decoration: none; font-size: 13px; border: none; background: none; cursor: pointer; padding: 0; }
|
||||
.download-link:hover { text-decoration: underline; }
|
||||
.download-link:disabled { color: #999; cursor: default; }
|
||||
.download-link:disabled:hover { text-decoration: none; }
|
||||
.text-muted { color: #999; font-size: 13px; }
|
||||
.qr-thumb { width: 40px; height: 40px; cursor: pointer; border-radius: 4px; border: 1px solid #e8e8e8; }
|
||||
.qr-thumb { width: 40px; height: 40px; object-fit: cover; cursor: pointer; border-radius: 4px; border: 1px solid #e8e8e8; }
|
||||
.qr-thumb:hover { border-color: #1890ff; }
|
||||
.btn-danger { color: #ff4d4f; border-color: #ff4d4f; }
|
||||
.btn-danger:hover { background: #ff4d4f; color: white; }
|
||||
@@ -535,7 +580,7 @@ const errorCategoryLabel = (cat) => {
|
||||
.qr-preview-modal .modal-header { display: flex; justify-content: center; align-items: center; position: relative; margin-bottom: 16px; }
|
||||
.qr-preview-modal .modal-close { position: absolute; right: 0; top: 50%; transform: translateY(-50%); background: none; border: none; font-size: 20px; cursor: pointer; color: #999; }
|
||||
.qr-preview-modal .modal-close:hover { color: #333; }
|
||||
.qr-preview-img { width: 260px; height: 260px; border: 1px solid #f0f0f0; border-radius: 8px; margin: 16px 0; }
|
||||
.qr-preview-img { width: 260px; height: 260px; object-fit: contain; border: 1px solid #f0f0f0; border-radius: 8px; margin: 16px 0; }
|
||||
.qr-preview-info { text-align: left; padding: 12px 16px; background: #fafafa; border-radius: 8px; }
|
||||
.qr-preview-info p { margin: 6px 0; font-size: 13px; color: #555; }
|
||||
</style>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<div class="header-row"><h2>操作日志</h2><div><select v-model.number="days" @change="load"><option :value="7">近 7 天</option><option :value="30">近 30 天</option><option :value="90">近 90 天</option></select><button @click="exportCsv">导出 CSV</button></div></div>
|
||||
<div class="cards"><div><strong>{{ summary.total || 0 }}</strong><span>操作总数</span></div><div><strong>{{ summary.action_counts?.build_created || 0 }}</strong><span>发起打包</span></div><div><strong>{{ summary.action_counts?.ipa_download_requested || 0 }}</strong><span>发起 IPA 下载</span></div></div>
|
||||
<div class="columns"><section><h3>活跃用户</h3><p v-for="item in summary.top_users || []" :key="item.name">{{ item.name }} <b>{{ item.count }}</b></p></section><section><h3>App 操作量</h3><p v-for="item in summary.top_apps || []" :key="item.name">{{ item.name }} <b>{{ item.count }}</b></p></section></div>
|
||||
<table><thead><tr><th>时间</th><th>用户</th><th>操作</th><th>App</th><th>资源</th><th>IP</th></tr></thead><tbody><tr v-for="log in logs" :key="log.id"><td>{{ formatTime(log.created_at) }}</td><td>{{ log.username }}</td><td>{{ actionText(log.action) }}</td><td>{{ log.app_name || '-' }}</td><td>{{ log.resource_type || '-' }}</td><td>{{ log.client_ip || '-' }}</td></tr><tr v-if="!logs.length"><td colspan="6">暂无操作记录</td></tr></tbody></table>
|
||||
<table><thead><tr><th>时间</th><th>用户</th><th>操作</th><th>App</th><th>资源</th><th>版本</th></tr></thead><tbody><tr v-for="log in logs" :key="log.id"><td>{{ formatTime(log.created_at) }}</td><td>{{ log.username }}</td><td>{{ actionText(log.action) }}</td><td>{{ log.app_name || '-' }}</td><td>{{ log.resource_type || '-' }}</td><td>{{ log.action === 'ipa_download_requested' ? (log.version || '-') : '-' }}</td></tr><tr v-if="!logs.length"><td colspan="6">暂无操作记录</td></tr></tbody></table>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# 打包产物 WebDAV 部署说明
|
||||
|
||||
文件服务器上的下载目录为 `/home/appmgr/app-downloads`,已创建 `Android` 和 `iOS` 子目录。Nginx DAV 模块已编译启用;`httpd-tools` 尚未安装。当前 SSH 用户 `appmgr` 不在 sudoers 中,安装软件和创建密码文件需使用 root 或有 sudo 权限的账号。
|
||||
|
||||
## 安装并创建 WebDAV 账号
|
||||
|
||||
在文件服务器执行:
|
||||
|
||||
```bash
|
||||
dnf install -y httpd-tools
|
||||
htpasswd -c /etc/nginx/app-downloads.htpasswd build-uploader
|
||||
```
|
||||
|
||||
`htpasswd` 会交互式询问密码。`build-uploader` 是 WebDAV 账号,不是 Linux 登录账号。`-c` 仅在首次创建密码文件时使用;后续添加账号时去掉 `-c`,以免覆盖已有账号。
|
||||
|
||||
## Nginx 配置
|
||||
|
||||
将 `nginx-webdav.conf.example` 保存为 `/etc/nginx/conf.d/app-downloads.conf`。示例按现有文件服务器内网地址 `172.1.110.13` 和 iOS 打包服务器来源 `172.1.110.180` 编写。把 Android 打包服务器访问时的来源 IP 也加入 `allow`。外层 Nginx 的下载域名应反代到 `http://172.1.110.13:8081`,并保留原始 URI;防火墙应只允许外层 Nginx 访问 8081。
|
||||
|
||||
检查并重载:
|
||||
|
||||
```bash
|
||||
nginx -t
|
||||
systemctl reload nginx
|
||||
```
|
||||
|
||||
内网 WebDAV 使用 HTTP,Basic Auth 凭据会在内网链路上传输。8080 应通过防火墙限制为打包服务器来源地址。请确认 `172.1.110.13` 和构建服务器地址确实只在受控网络内路由;172 私有网段是 `172.16.0.0/12`。
|
||||
|
||||
## 打包服务后台配置
|
||||
|
||||
在 iOS 打包服务「上传配置」页选择 WebDAV:
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| 服务器地址 | `http://172.1.110.13:8080` |
|
||||
| 用户名 | `build-uploader` |
|
||||
| 密码 | 创建账号时输入的密码 |
|
||||
| 远程路径 | `/iOS` |
|
||||
| 公开访问地址 | `https://你的外网下载域名` |
|
||||
|
||||
当前 WebDAV 实现将文件直接放在配置的远程目录中,只使用产物文件名,不再附加 `ios-builds/iOS`。因此 `/iOS` 对应文件系统 `/home/appmgr/app-downloads/iOS`,公开链接为 `https://你的外网下载域名/iOS/文件名`。外层 Nginx 必须保留该 URI 并代理到 8081。
|
||||
|
||||
Android 打包服务应将 APK 上传到 `/Android`,公开链接形如 `https://你的外网下载域名/Android/文件名.apk`。Android 的上传和删除配置由对应的 Android 打包服务负责;当前 iOS 项目发布 IPA、plist、安装页和二维码。
|
||||
|
||||
## 验证
|
||||
|
||||
分别从打包服务器发起一次测试上传,使用外网 HTTPS 域名打开生成的链接,再从对应前台删除测试构建并确认文件已删除。Ad Hoc iOS 安装还需要有效的 HTTPS 下载域名、manifest、签名和设备 UDID。
|
||||
|
||||
参考:[Nginx DAV 模块文档](https://nginx.org/en/docs/http/ngx_http_dav_module.html)
|
||||
@@ -0,0 +1,49 @@
|
||||
# 保存为 /etc/nginx/conf.d/app-downloads.conf。
|
||||
# 文件服务器内网地址:172.1.110.13
|
||||
# 请将 Android 打包服务器来源 IP 也加入 WebDAV allow 列表。
|
||||
|
||||
# 内网 WebDAV:构建服务器通过 PUT 上传、DELETE 删除。
|
||||
server {
|
||||
listen 172.1.110.13:8080;
|
||||
server_name _;
|
||||
|
||||
root /home/appmgr/app-downloads;
|
||||
client_max_body_size 5g;
|
||||
client_body_timeout 300s;
|
||||
|
||||
auth_basic "Build Artifacts";
|
||||
auth_basic_user_file /etc/nginx/app-downloads.htpasswd;
|
||||
|
||||
# iOS 打包服务器;将 Android 打包服务器来源 IP 也加入 allow 列表。
|
||||
allow 172.1.110.180;
|
||||
deny all;
|
||||
|
||||
location / {
|
||||
dav_methods PUT DELETE MKCOL;
|
||||
create_full_put_path on;
|
||||
dav_access user:rw group:r;
|
||||
autoindex off;
|
||||
|
||||
# 兼容当前 iOS 打包服务 MKCOL 请求尾部斜杠。
|
||||
if ($request_method = MKCOL) {
|
||||
rewrite ^(.*[^/])$ $1/ break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 内层静态文件服务:由外层 Nginx 反向代理;不要对公网开放 8081。
|
||||
server {
|
||||
listen 172.1.110.13:8081;
|
||||
server_name _;
|
||||
|
||||
root /home/appmgr/app-downloads;
|
||||
autoindex off;
|
||||
|
||||
location / {
|
||||
dav_methods off;
|
||||
limit_except GET HEAD {
|
||||
deny all;
|
||||
}
|
||||
try_files $uri =404;
|
||||
}
|
||||
}
|
||||
+110
-18
@@ -229,15 +229,22 @@ def test_update_versions_rejects_invalid_app_version(client, tmp_config):
|
||||
|
||||
|
||||
def test_versions_tracks_are_independent(client, tmp_config):
|
||||
# 两条轨道的 App_Ver 各自独立,互不影响
|
||||
# 每个分支一条轨道(main/master 为 release,其余即分支名),App_Ver 各自独立
|
||||
assert client.post("/api/config/branches", json={"name": "feature/login"}).status_code == 200
|
||||
assert client.put("/api/config/versions", json={"track": "release", "app_ver": "2.196.0"}).status_code == 200
|
||||
assert client.put("/api/config/versions", json={"track": "feature", "app_ver": "2.100.0"}).status_code == 200
|
||||
assert client.put("/api/config/versions", json={"track": "dev", "app_ver": "2.198.0"}).status_code == 200
|
||||
assert client.put("/api/config/versions", json={"track": "feature/login", "app_ver": "2.100.0"}).status_code == 200
|
||||
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["branch_track"] == {"main": "release", "dev": "dev", "feature/login": "feature/login"}
|
||||
assert data["tracks"]["release"]["app_ver"] == "2.196.0"
|
||||
assert data["tracks"]["feature"]["app_ver"] == "2.100.0"
|
||||
assert data["tracks"]["feature"]["build_ver"] == "2.100.0.0"
|
||||
# 顶层字段镜像 release 轨,兼容旧客户端
|
||||
assert data["tracks"]["dev"]["app_ver"] == "2.198.0"
|
||||
assert data["tracks"]["feature/login"]["app_ver"] == "2.100.0"
|
||||
assert data["tracks"]["feature/login"]["build_ver"] == "2.100.0.0"
|
||||
assert data["tracks"]["release"]["kind"] == "release"
|
||||
assert data["tracks"]["feature/login"]["kind"] == "feature"
|
||||
# 顶层字段镜像主上架轨(第一个上架分支),兼容旧客户端
|
||||
assert data["primary_track"] == "release"
|
||||
assert data["app_ver"] == "2.196.0"
|
||||
|
||||
|
||||
@@ -246,7 +253,8 @@ def test_update_versions_rejects_unknown_track(client, tmp_config):
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_legacy_versions_migrate_to_release_track(client, tmp_config):
|
||||
def test_legacy_versions_split_per_branch(client, tmp_config):
|
||||
"""最旧的单轨配置:拆成每个分支一条轨,各自沿用原来的已用构建号"""
|
||||
import json
|
||||
with open(tmp_config, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
@@ -255,28 +263,78 @@ def test_legacy_versions_migrate_to_release_track(client, tmp_config):
|
||||
json.dump(cfg, f)
|
||||
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["tracks"]["release"] == {
|
||||
"app_ver": "2.195.0",
|
||||
"build_ver": "2.195.0.7",
|
||||
"build_map": {"2.195.0": 7},
|
||||
# main 留在 release 轨,dev 拆出自己的轨,两者都带着原来的已用构建号
|
||||
assert data["branch_track"] == {"main": "release", "dev": "dev"}
|
||||
for track in ("release", "dev"):
|
||||
assert data["tracks"][track] == {
|
||||
"kind": "release",
|
||||
"app_ver": "2.195.0",
|
||||
"build_ver": "2.195.0.7",
|
||||
"build_map": {"2.195.0": 7},
|
||||
}
|
||||
# 拆分后各轨独立:改 release 不影响 dev
|
||||
assert client.put("/api/config/versions", json={"track": "release", "app_ver": "2.196.0"}).status_code == 200
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["tracks"]["release"]["app_ver"] == "2.196.0"
|
||||
assert data["tracks"]["dev"]["app_ver"] == "2.195.0"
|
||||
|
||||
|
||||
def test_legacy_shared_tracks_split_per_branch(client, tmp_config):
|
||||
"""旧的共用轨:master 留在 release 轨,其余分支(含自测分支)各拆出自己的轨"""
|
||||
import json
|
||||
with open(tmp_config, "r", encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
cfg["branches"] = ["main", "dev", "feature/login", "feature/pay"]
|
||||
cfg["versions"] = {"tracks": {
|
||||
"release": {"app_ver": "2.195.0", "build_map": {"2.195.0": 4}},
|
||||
"feature": {"app_ver": "2.100.0", "build_map": {}},
|
||||
}}
|
||||
cfg["branch_track"] = {
|
||||
"main": "release", "dev": "release",
|
||||
"feature/login": "feature", "feature/pay": "feature",
|
||||
}
|
||||
# feature 轨以同一 App_Ver 初始化,构建号从 .0 起
|
||||
assert data["tracks"]["feature"]["app_ver"] == "2.195.0"
|
||||
assert data["tracks"]["feature"]["build_ver"] == "2.195.0.0"
|
||||
with open(tmp_config, "w", encoding="utf-8") as f:
|
||||
json.dump(cfg, f)
|
||||
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["branch_track"] == {
|
||||
"main": "release", "dev": "dev",
|
||||
"feature/login": "feature/login", "feature/pay": "feature/pay",
|
||||
}
|
||||
for track in ("release", "dev"):
|
||||
assert data["tracks"][track]["kind"] == "release"
|
||||
assert data["tracks"][track]["build_ver"] == "2.195.0.4"
|
||||
for track in ("feature/login", "feature/pay"):
|
||||
assert data["tracks"][track]["kind"] == "feature"
|
||||
assert data["tracks"][track]["app_ver"] == "2.100.0"
|
||||
|
||||
# 自测分支的版本号各自独立
|
||||
assert client.put("/api/config/versions", json={"track": "feature/login", "app_ver": "2.101.0"}).status_code == 200
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["tracks"]["feature/login"]["app_ver"] == "2.101.0"
|
||||
assert data["tracks"]["feature/pay"]["app_ver"] == "2.100.0"
|
||||
|
||||
|
||||
def test_branch_track_defaults_and_override(client, tmp_config):
|
||||
assert client.post("/api/config/branches", json={"name": "develop"}).status_code == 200
|
||||
assert client.post("/api/config/branches", json={"name": "feature/login"}).status_code == 200
|
||||
|
||||
tracks = client.get("/api/config/versions").json()["branch_track"]
|
||||
assert tracks["develop"] == "release"
|
||||
assert tracks["feature/login"] == "feature"
|
||||
data = client.get("/api/config/versions").json()
|
||||
# 每个分支一条自己的轨道,类型按分支名推断
|
||||
assert data["branch_track"]["develop"] == "develop"
|
||||
assert data["branch_track"]["feature/login"] == "feature/login"
|
||||
assert data["tracks"]["develop"]["kind"] == "release"
|
||||
assert data["tracks"]["feature/login"]["kind"] == "feature"
|
||||
|
||||
# 手动改归属
|
||||
# 手动改类型:轨道名不变,只改构建号是否自增
|
||||
resp = client.put("/api/config/branches/track", json={"branch": "feature/login", "track": "release"})
|
||||
assert resp.status_code == 200
|
||||
assert client.get("/api/config/versions").json()["branch_track"]["feature/login"] == "release"
|
||||
assert resp.json()["track"] == "feature/login"
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["tracks"]["feature/login"]["kind"] == "release"
|
||||
|
||||
assert client.put("/api/config/branches/track", json={"branch": "feature/login", "track": "feature"}).status_code == 200
|
||||
assert client.get("/api/config/versions").json()["tracks"]["feature/login"]["kind"] == "feature"
|
||||
|
||||
assert client.put("/api/config/branches/track", json={"branch": "nope", "track": "release"}).status_code == 404
|
||||
assert client.put("/api/config/branches/track", json={"branch": "develop", "track": "beta"}).status_code == 400
|
||||
@@ -287,3 +345,37 @@ def test_delete_branch_with_slash_in_name(client, tmp_config):
|
||||
resp = client.delete("/api/config/branches/feature%2Flogin")
|
||||
assert resp.status_code == 200
|
||||
assert "feature/login" not in client.get("/api/config/branches").json()
|
||||
|
||||
|
||||
def test_tags_crud_and_default_release_track(client, tmp_config):
|
||||
"""Tag 与分支分开存放,默认建一条同名上架轨,可切换类型、可删除"""
|
||||
assert client.get("/api/config/tags").json() == []
|
||||
resp = client.post("/api/config/tags", json={"name": "v3.2.0"})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["track"] == "v3.2.0"
|
||||
assert client.get("/api/config/tags").json() == ["v3.2.0"]
|
||||
assert client.get("/api/tags").json() == ["v3.2.0"]
|
||||
assert "v3.2.0" not in client.get("/api/config/branches").json()
|
||||
|
||||
data = client.get("/api/config/versions").json()
|
||||
assert data["branch_track"]["v3.2.0"] == "v3.2.0"
|
||||
assert data["tracks"]["v3.2.0"]["kind"] == "release"
|
||||
# 主上架轨仍按分支判断,Tag 不会抢占
|
||||
assert data["primary_track"] == "release"
|
||||
|
||||
assert client.put("/api/config/branches/track", json={"branch": "v3.2.0", "track": "feature"}).status_code == 200
|
||||
assert client.get("/api/config/versions").json()["tracks"]["v3.2.0"]["kind"] == "feature"
|
||||
|
||||
assert client.delete("/api/config/tags/v3.2.0").status_code == 200
|
||||
assert client.get("/api/config/tags").json() == []
|
||||
assert "v3.2.0" not in client.get("/api/config/versions").json()["branch_track"]
|
||||
assert client.delete("/api/config/tags/v3.2.0").status_code == 404
|
||||
|
||||
|
||||
def test_tag_and_branch_names_must_not_collide(client, tmp_config):
|
||||
assert client.post("/api/config/tags", json={"name": ""}).status_code == 400
|
||||
assert client.post("/api/config/tags", json={"name": "main"}).status_code == 400
|
||||
assert client.post("/api/config/tags", json={"name": "release/v1"}).status_code == 200
|
||||
assert client.post("/api/config/tags", json={"name": "release/v1"}).status_code == 400
|
||||
assert client.post("/api/config/branches", json={"name": "release/v1"}).status_code == 400
|
||||
assert client.delete("/api/config/tags/release%2Fv1").status_code == 200
|
||||
|
||||
@@ -38,6 +38,23 @@ def test_create_task_default_branch(mock_queue, client, tmp_config):
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["branch"] == "main"
|
||||
assert resp.json()["ref_type"] == "branch"
|
||||
|
||||
|
||||
@patch("backend.services.build_queue.build_queue")
|
||||
def test_create_task_from_tag(mock_queue, client, tmp_config):
|
||||
"""选择已配置的 Tag 打包时,任务记录为 tag 类型"""
|
||||
mock_queue.submit = AsyncMock()
|
||||
assert client.post("/api/config/tags", json={"name": "v3.2.0"}).status_code == 200
|
||||
resp = client.post("/api/tasks", json={
|
||||
"app_id": "1",
|
||||
"build_type": "Ad_Hoc",
|
||||
"scheme_id": "1",
|
||||
"branch": "v3.2.0",
|
||||
})
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["branch"] == "v3.2.0"
|
||||
assert resp.json()["ref_type"] == "tag"
|
||||
|
||||
|
||||
@patch("backend.services.build_queue.build_queue")
|
||||
|
||||
+156
-34
@@ -55,6 +55,17 @@ def tmp_dirs(tmp_path):
|
||||
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"):
|
||||
"""创建 mock 进程,支持 async for stdout"""
|
||||
proc = AsyncMock()
|
||||
@@ -87,7 +98,7 @@ async def test_update_source_clone_no_remote(tmp_path, log_streamer):
|
||||
source_dir = tmp_path / "branches" / "main"
|
||||
|
||||
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")
|
||||
|
||||
|
||||
@@ -112,6 +123,25 @@ async def test_update_source_existing(tmp_path, log_streamer):
|
||||
assert call_count == 4 # fetch, checkout, reset, clean
|
||||
|
||||
|
||||
async def test_update_source_tag_checks_out_detached(tmp_path, log_streamer):
|
||||
"""Tag 打包:拉取 Tag 后以游离 HEAD 检出 refs/tags/<tag>,不依赖同名远程分支"""
|
||||
source_dir = tmp_path / "workspace"
|
||||
source_dir.mkdir()
|
||||
(source_dir / ".git").mkdir()
|
||||
|
||||
with patch("backend.services.build_service.get_git_remote_url", return_value=""):
|
||||
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
|
||||
await update_source("t1", source_dir, "v3.2.0", "tag")
|
||||
|
||||
git_args = [call.args[3:] for call in mock_exec.call_args_list]
|
||||
assert git_args == [
|
||||
("fetch", "origin", "--tags", "--force"),
|
||||
("checkout", "--detach", "refs/tags/v3.2.0"),
|
||||
("reset", "--hard", "refs/tags/v3.2.0"),
|
||||
("clean", "-ffdx"),
|
||||
]
|
||||
|
||||
|
||||
async def test_update_source_fetch_failure(tmp_path, log_streamer):
|
||||
"""fetch 失败时抛异常"""
|
||||
source_dir = tmp_path / "branches" / "dev"
|
||||
@@ -133,15 +163,28 @@ async def test_prepare_source_snapshot_serializes_shared_source(tmp_dirs, log_st
|
||||
source_dir, build_dir_parent = tmp_dirs
|
||||
task = MagicMock(branch="main")
|
||||
|
||||
with patch("backend.services.build_service.get_git_remote_url", return_value="git@github.com:test/repo.git"), \
|
||||
patch("backend.services.build_service.get_shared_source_dir", return_value=source_dir), \
|
||||
with _patch_project_source(source_dir), \
|
||||
patch("backend.services.build_service.BUILD_BASE_DIR", build_dir_parent), \
|
||||
patch("backend.services.build_service.update_source", new_callable=AsyncMock), \
|
||||
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"):
|
||||
build_dir, commit = await prepare_source_snapshot("t1", task)
|
||||
|
||||
assert build_dir.exists()
|
||||
assert commit == "abc123"
|
||||
assert mock_update.call_args.args[2:] == ("main", "branch")
|
||||
|
||||
|
||||
async def test_prepare_source_snapshot_passes_tag_ref_type(tmp_dirs, log_streamer):
|
||||
source_dir, build_dir_parent = tmp_dirs
|
||||
task = MagicMock(id="tag-task", branch="v3.2.0", ref_type="tag")
|
||||
|
||||
with _patch_project_source(source_dir), \
|
||||
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.get_source_commit", new_callable=AsyncMock, return_value="abc123"):
|
||||
await prepare_source_snapshot("t1", task)
|
||||
|
||||
assert mock_update.call_args.args[2:] == ("v3.2.0", "tag")
|
||||
|
||||
|
||||
# ---- copy_source_code ----
|
||||
@@ -232,6 +275,7 @@ async def test_run_pod_install_patches_afnetworking(tmp_path, log_streamer):
|
||||
source_dir.mkdir(parents=True)
|
||||
source_file = source_dir / "AFHTTPSessionManager.m"
|
||||
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()):
|
||||
await run_pod_install("t1", tmp_path)
|
||||
@@ -239,6 +283,18 @@ async def test_run_pod_install_patches_afnetworking(tmp_path, log_streamer):
|
||||
assert "netinet6/in6.h" not in source_file.read_text()
|
||||
|
||||
|
||||
async def test_run_pod_install_uses_xcode_subdirectory(tmp_path, log_streamer):
|
||||
"""工程在仓库子目录时,在 Podfile 所在的子目录执行 pod install。"""
|
||||
sub = tmp_path / "Demo"
|
||||
sub.mkdir()
|
||||
(sub / "Podfile").write_text("pod 'SnapKit'")
|
||||
|
||||
with patch("asyncio.create_subprocess_exec", return_value=_make_mock_process()) as mock_exec:
|
||||
await run_pod_install("t1", tmp_path, {"workspace": "Demo/App.xcworkspace", "project": ""})
|
||||
|
||||
assert mock_exec.call_args.kwargs["cwd"] == str(sub)
|
||||
|
||||
|
||||
async def test_build_project_passes_scheme_as_exec_argument(tmp_path, log_streamer):
|
||||
"""Scheme 中的 shell 特殊字符只能作为 xcodebuild 参数,不能被执行。"""
|
||||
build_dir = tmp_path / "build"
|
||||
@@ -306,7 +362,41 @@ async def test_generate_config(tmp_path, log_streamer):
|
||||
assert saved["APPID"] == "guid-123"
|
||||
|
||||
|
||||
def test_resolve_provisioning_profile_extracts_name_and_team(tmp_path):
|
||||
@pytest.mark.parametrize("app_fields, appid, expected_id, expected_label", [
|
||||
([{"key": "APPID", "label": "APPID"}], "1587365345", "1587365345", "APPID"),
|
||||
([{"key": "APPID", "label": "APPID"}], "", "dy_app", "App 标识"),
|
||||
([], "", "dy_app", "App 标识"),
|
||||
])
|
||||
async def test_generate_config_generic_project_identifier(
|
||||
tmp_path, log_streamer, app_fields, appid, expected_id, expected_label,
|
||||
):
|
||||
"""通用项目没有 AppGuid,以第一个 App 字段作为产物文件名和通知中的 App 标识"""
|
||||
build_dir = tmp_path / "build"
|
||||
build_dir.mkdir()
|
||||
|
||||
task = MagicMock()
|
||||
task.project_id = "dyauction"
|
||||
task.app_id = "1"
|
||||
task.scheme_id = "1"
|
||||
task.build_type = "Ad_Hoc"
|
||||
task.obfuscation = False
|
||||
|
||||
mock_config = {
|
||||
"patcher": "generic",
|
||||
"app_fields": app_fields,
|
||||
"apps": {"1": {"name": "朵云轩", "server": "正式环境", "APPID": appid, "upload_key": "dy_app",
|
||||
"certificates": {}}},
|
||||
"schemes": {"1": {"name": "DyAuction", "ossFloder": "dy"}},
|
||||
}
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config):
|
||||
result = await generate_config("t1", task, build_dir)
|
||||
|
||||
assert result["APPID"] == expected_id
|
||||
assert result["APPID_LABEL"] == expected_label
|
||||
|
||||
|
||||
|
||||
profile_path = tmp_path / "profile.mobileprovision"
|
||||
profile_path.write_bytes(b"signed profile")
|
||||
decoded = plistlib.dumps({"Name": "a4YX061_adHoc", "TeamIdentifier": ["MG4Z7FU83W"]})
|
||||
@@ -315,14 +405,23 @@ def test_resolve_provisioning_profile_extracts_name_and_team(tmp_path):
|
||||
assert _resolve_provisioning_profile(str(profile_path)) == ("a4YX061_adHoc", "MG4Z7FU83W")
|
||||
|
||||
|
||||
def _versions_config(release: dict, feature: dict) -> dict:
|
||||
def _versions_config(tracks: dict) -> dict:
|
||||
"""构造带版本轨道的配置;tracks 为 轨道名 -> {kind, app_ver, build_map}。"""
|
||||
return {
|
||||
"apps": {"1": {"name": "App", "certificates": {}}},
|
||||
"schemes": {"1": {"name": "sch", "ossFloder": "f"}},
|
||||
"versions": {"tracks": {"release": release, "feature": feature}},
|
||||
"versions": {"tracks": tracks},
|
||||
}
|
||||
|
||||
|
||||
def _release(app_ver: str, build_map: dict = None) -> dict:
|
||||
return {"kind": "release", "app_ver": app_ver, "build_map": build_map or {}}
|
||||
|
||||
|
||||
def _feature(app_ver: str, build_map: dict = None) -> dict:
|
||||
return {"kind": "feature", "app_ver": app_ver, "build_map": build_map or {}}
|
||||
|
||||
|
||||
async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
|
||||
"""从服务配置读取版本号,不依赖分支源码脚本"""
|
||||
build_dir = tmp_path / "build"
|
||||
@@ -335,10 +434,7 @@ async def test_generate_config_uses_saved_version(tmp_path, log_streamer):
|
||||
task.obfuscation = False
|
||||
task.branch = "master"
|
||||
|
||||
mock_config = _versions_config(
|
||||
{"app_ver": "3.0.1", "build_map": {}},
|
||||
{"app_ver": "9.9.9", "build_map": {}},
|
||||
)
|
||||
mock_config = _versions_config({"release": _release("3.0.1"), "feature": _feature("9.9.9")})
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config):
|
||||
result = await generate_config("t1", task, build_dir)
|
||||
@@ -356,10 +452,10 @@ async def test_generate_config_appstore_increments_per_version(tmp_path, log_str
|
||||
obfuscation=False, branch="master")
|
||||
|
||||
# 2.195.0 已打到 .5,切到 2.196.0 后又回退到 2.195.0
|
||||
mock_config = _versions_config(
|
||||
{"app_ver": "2.195.0", "build_map": {"2.195.0": 5, "2.196.0": 3}},
|
||||
{"app_ver": "2.195.0", "build_map": {}},
|
||||
)
|
||||
mock_config = _versions_config({
|
||||
"release": _release("2.195.0", {"2.195.0": 5, "2.196.0": 3}),
|
||||
"feature": _feature("2.195.0"),
|
||||
})
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||
patch("backend.routers.config.save_config") as save_mock:
|
||||
@@ -373,39 +469,64 @@ async def test_generate_config_appstore_increments_per_version(tmp_path, log_str
|
||||
save_mock.assert_called()
|
||||
|
||||
|
||||
async def test_generate_config_develop_shares_release_track(tmp_path, log_streamer):
|
||||
"""develop 与 master 共用 release 轨的版本号与构建号序列"""
|
||||
async def test_generate_config_release_branches_are_independent(tmp_path, log_streamer):
|
||||
"""master 与 develop 各用自己的轨道,版本号与构建号互不影响"""
|
||||
build_dir = tmp_path / "build"
|
||||
build_dir.mkdir()
|
||||
|
||||
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||
obfuscation=False, branch="develop")
|
||||
|
||||
mock_config = _versions_config(
|
||||
{"app_ver": "2.195.0", "build_map": {"2.195.0": 5}},
|
||||
{"app_ver": "2.100.0", "build_map": {}},
|
||||
)
|
||||
mock_config = _versions_config({
|
||||
"release": _release("2.195.0", {"2.195.0": 5}), # master
|
||||
"develop": _release("2.196.0", {"2.196.0": 1}),
|
||||
"feature": _feature("2.100.0"),
|
||||
})
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||
patch("backend.routers.config.save_config"):
|
||||
result = await generate_config("t1", task, build_dir)
|
||||
|
||||
assert result["VERSION"] == "2.195.0"
|
||||
assert result["BUILD_VERSION"] == "2.195.0.6"
|
||||
assert result["VERSION"] == "2.196.0"
|
||||
assert result["BUILD_VERSION"] == "2.196.0.2"
|
||||
# master 的 release 轨完全不受影响
|
||||
assert mock_config["versions"]["tracks"]["release"]["build_map"] == {"2.195.0": 5}
|
||||
|
||||
|
||||
async def test_generate_config_build_no_skips_other_release_track(tmp_path, log_streamer):
|
||||
"""两个上架分支临时用同一 App_Ver 时,构建号跨轨道取最大值 +1,避免 App Store 重号"""
|
||||
build_dir = tmp_path / "build"
|
||||
build_dir.mkdir()
|
||||
|
||||
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||
obfuscation=False, branch="develop")
|
||||
|
||||
mock_config = _versions_config({
|
||||
"release": _release("2.196.0", {"2.196.0": 7}), # master
|
||||
"develop": _release("2.196.0", {"2.196.0": 2}),
|
||||
"feature": _feature("2.100.0"),
|
||||
})
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||
patch("backend.routers.config.save_config"):
|
||||
result = await generate_config("t1", task, build_dir)
|
||||
|
||||
assert result["BUILD_VERSION"] == "2.196.0.8"
|
||||
assert mock_config["versions"]["tracks"]["develop"]["build_map"]["2.196.0"] == 8
|
||||
|
||||
|
||||
async def test_generate_config_feature_branch_never_increments(tmp_path, log_streamer):
|
||||
"""feature 分支用自己的版本号,且构建号永不自增(即使是 App_Store 打包)"""
|
||||
"""自测分支用自己那条轨道的版本号,且构建号永不自增(即使是 App_Store 打包)"""
|
||||
build_dir = tmp_path / "build"
|
||||
build_dir.mkdir()
|
||||
|
||||
task = MagicMock(app_id="1", scheme_id="1", build_type="App_Store",
|
||||
obfuscation=False, branch="feature/login")
|
||||
|
||||
mock_config = _versions_config(
|
||||
{"app_ver": "2.195.0", "build_map": {"2.195.0": 5}},
|
||||
{"app_ver": "2.100.0", "build_map": {}},
|
||||
)
|
||||
mock_config = _versions_config({
|
||||
"release": _release("2.195.0", {"2.195.0": 5}),
|
||||
"feature/login": _feature("2.100.0"),
|
||||
})
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config), \
|
||||
patch("backend.routers.config.save_config") as save_mock:
|
||||
@@ -413,7 +534,7 @@ async def test_generate_config_feature_branch_never_increments(tmp_path, log_str
|
||||
|
||||
assert result["VERSION"] == "2.100.0"
|
||||
assert result["BUILD_VERSION"] == "2.100.0.0"
|
||||
assert mock_config["versions"]["tracks"]["feature"]["build_map"] == {}
|
||||
assert mock_config["versions"]["tracks"]["feature/login"]["build_map"] == {}
|
||||
save_mock.assert_not_called()
|
||||
|
||||
|
||||
@@ -425,11 +546,12 @@ async def test_generate_config_branch_track_override(tmp_path, log_streamer):
|
||||
task = MagicMock(app_id="1", scheme_id="1", build_type="Ad_Hoc",
|
||||
obfuscation=False, branch="release/2.196")
|
||||
|
||||
mock_config = _versions_config(
|
||||
{"app_ver": "2.196.0", "build_map": {}},
|
||||
{"app_ver": "2.100.0", "build_map": {}},
|
||||
)
|
||||
mock_config["branch_track"] = {"release/2.196": "feature"}
|
||||
mock_config = _versions_config({
|
||||
"release": _release("2.196.0"),
|
||||
"feature/login": _feature("2.100.0"),
|
||||
})
|
||||
# release/2.196 按名字本应是上架轨,显式指到 feature/login 那条轨道
|
||||
mock_config["branch_track"] = {"release/2.196": "feature/login"}
|
||||
|
||||
with patch("backend.routers.config.load_config", return_value=mock_config):
|
||||
result = await generate_config("t1", task, build_dir)
|
||||
|
||||
@@ -4,6 +4,7 @@ from unittest.mock import patch
|
||||
|
||||
from backend.services.distribution import (
|
||||
_artifact_stem,
|
||||
_upload_webdav,
|
||||
delete_published_artifacts,
|
||||
_write_distribution_files,
|
||||
_write_download_page,
|
||||
@@ -86,6 +87,11 @@ def test_adhoc_distribution_uploads_qrcode(tmp_path):
|
||||
".ipa", ".plist", ".html", ".png",
|
||||
]
|
||||
|
||||
# 桌面端钉钉会把图片裁成横向比例,二维码需放在 3:2 的横向画布上
|
||||
from PIL import Image
|
||||
with Image.open(tmp_path / "build" / "distribution" / "100_2_0_0_dev_adhoc.png") as image:
|
||||
assert image.width == round(image.height * 1.5)
|
||||
|
||||
|
||||
def test_delete_adhoc_artifacts_deletes_all_remote_files():
|
||||
config = {"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main", "BUILD_TYPE": "Ad_Hoc", "OSS_FLODER": "readoor"}
|
||||
@@ -122,6 +128,86 @@ def test_delete_uses_saved_url_for_legacy_artifact_name():
|
||||
]
|
||||
|
||||
|
||||
def test_webdav_upload_uses_configured_directory_without_oss_path(tmp_path, monkeypatch):
|
||||
ipa = tmp_path / "build.ipa"
|
||||
ipa.write_bytes(b"ipa")
|
||||
calls = {"mkcol": [], "put": []}
|
||||
|
||||
class FakeResponse:
|
||||
status_code = 201
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **_kwargs): pass
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *_args): pass
|
||||
def request(self, method, url):
|
||||
calls["mkcol"].append((method, url))
|
||||
return FakeResponse()
|
||||
def put(self, url, content):
|
||||
calls["put"].append((url, content))
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr("backend.services.distribution.httpx.Client", FakeClient)
|
||||
result = _upload_webdav(
|
||||
{
|
||||
"webdav": {
|
||||
"server_url": "http://dav.example.com",
|
||||
"username": "u",
|
||||
"password": "p",
|
||||
"base_path": "/iOS/",
|
||||
"public_url": "https://download.example.com",
|
||||
},
|
||||
},
|
||||
[(ipa, "ios-builds/iOS/legacy-path.ipa")],
|
||||
)
|
||||
|
||||
assert calls["mkcol"] == [("MKCOL", "http://dav.example.com/iOS/")]
|
||||
assert calls["put"] == [("http://dav.example.com/iOS/build.ipa", b"ipa")]
|
||||
assert result[".ipa"] == "https://download.example.com/iOS/build.ipa"
|
||||
|
||||
|
||||
def test_delete_webdav_artifacts_uses_path_from_published_url():
|
||||
config = {
|
||||
"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main",
|
||||
"BUILD_TYPE": "Ad_Hoc", "OSS_FLODER": "legacy-oss-folder",
|
||||
}
|
||||
upload = {
|
||||
"mode": "webdav",
|
||||
"webdav": {
|
||||
"base_path": "/Android",
|
||||
"public_url": "https://download.example.com",
|
||||
},
|
||||
}
|
||||
with patch("backend.services.distribution._delete_webdav") as delete:
|
||||
delete_published_artifacts(
|
||||
config, upload,
|
||||
"https://download.example.com/Android/build.html",
|
||||
)
|
||||
|
||||
assert delete.call_args.args[1] == [
|
||||
"Android/build.ipa",
|
||||
"Android/build.plist",
|
||||
"Android/build.html",
|
||||
"Android/build.png",
|
||||
]
|
||||
|
||||
|
||||
def test_delete_webdav_dsym_uses_published_url():
|
||||
config = {"APPID": "100", "VERSION": "2.0.0.0", "SOURCE_BRANCH": "main"}
|
||||
upload = {
|
||||
"mode": "webdav",
|
||||
"webdav": {
|
||||
"base_path": "/iOS",
|
||||
"public_url": "https://download.example.com",
|
||||
},
|
||||
}
|
||||
with patch("backend.services.distribution._delete_webdav") as delete:
|
||||
from backend.services.distribution import delete_published_dsym
|
||||
delete_published_dsym(config, upload, "https://download.example.com/iOS/build.dSYM.zip")
|
||||
|
||||
assert delete.call_args.args[1] == ["iOS/build.dSYM.zip"]
|
||||
|
||||
|
||||
def test_oss_download_url_is_short_lived_and_uses_actual_object_key(monkeypatch):
|
||||
class FakeBucket:
|
||||
def __init__(self, *_args, **_kwargs): pass
|
||||
|
||||
@@ -66,6 +66,20 @@ def test_download_dsym_nonexistent_task(client, tmp_config):
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
def test_download_dsym_remote_fallback(client, tmp_config):
|
||||
"""本地文件已被清理,但保存了远端地址时应返回远端下载链接(而非直接重定向,
|
||||
因为该接口需要认证信息,浏览器无法直接跳转到 302 目标)"""
|
||||
task_id = _create_task_with_files(
|
||||
client, tmp_config,
|
||||
dsym_path="/tmp/nonexistent.dSYM",
|
||||
dsym_url="https://oss.example.com/ios-builds/iOS/app_1_0_0_main_adhoc.dSYM.zip",
|
||||
)
|
||||
with patch("backend.services.distribution.get_published_dsym_url", return_value="https://signed.example.com/app.dSYM.zip?signature=1"):
|
||||
resp = client.get(f"/api/tasks/{task_id}/dsym")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["url"] == "https://signed.example.com/app.dSYM.zip?signature=1"
|
||||
|
||||
|
||||
# ---- 混淆映射表下载 ----
|
||||
|
||||
def test_download_obfuscation_maps_not_exist(client, tmp_config):
|
||||
|
||||
@@ -35,6 +35,90 @@ def test_dingtalk_payload_matches_autopacking_content():
|
||||
assert "" in text
|
||||
|
||||
|
||||
def test_dingtalk_payload_uses_project_identifier_label():
|
||||
payload = build_dingtalk_payload(
|
||||
{**_build_config(), "APPID": "1587365345", "APPID_LABEL": "APPID"},
|
||||
"https://download.example.com/app.html",
|
||||
)
|
||||
|
||||
text = payload["markdown"]["text"]
|
||||
assert "**APPID:** 1587365345" in text
|
||||
assert "App Guid" not in text
|
||||
|
||||
|
||||
|
||||
payload = build_dingtalk_payload(
|
||||
_build_config(),
|
||||
"https://download.example.com/app.html",
|
||||
at_mobiles=["13800000000", " 13900000001 ", "13800000000", ""],
|
||||
)
|
||||
|
||||
# 去重去空后写入 at.atMobiles,并在正文追加 @手机号(钉钉 markdown 必需)
|
||||
assert payload["at"]["atMobiles"] == ["13800000000", "13900000001"]
|
||||
assert "@13800000000" in payload["markdown"]["text"]
|
||||
assert "@13900000001" in payload["markdown"]["text"]
|
||||
|
||||
|
||||
def test_dingtalk_payload_without_at_mobiles_has_empty_at():
|
||||
payload = build_dingtalk_payload(_build_config(), "https://download.example.com/app.html")
|
||||
assert payload["at"]["atMobiles"] == []
|
||||
assert "@" not in payload["markdown"]["text"]
|
||||
|
||||
|
||||
def test_dingtalk_notification_forwards_at_mobiles():
|
||||
response = MagicMock(status_code=200)
|
||||
response.json.return_value = {"errcode": 0}
|
||||
with patch("backend.services.notification.httpx.post", return_value=response) as post:
|
||||
send_dingtalk_notification(
|
||||
{
|
||||
"enabled": True,
|
||||
"webhook_url": "https://example.com/robot",
|
||||
"at_mobiles": ["13800000000", "13900000001"],
|
||||
},
|
||||
_build_config(),
|
||||
"https://download.example.com/app.html",
|
||||
)
|
||||
|
||||
sent = post.call_args.kwargs["json"]
|
||||
assert sent["at"]["atMobiles"] == ["13800000000", "13900000001"]
|
||||
assert "@13800000000" in sent["markdown"]["text"]
|
||||
|
||||
|
||||
def test_dingtalk_payload_app_store_heading_and_no_qr():
|
||||
config = {**_build_config(), "BUILD_TYPE": "App_Store"}
|
||||
# App_Store 流程不传二维码地址(publish_ipa 返回空串)
|
||||
payload = build_dingtalk_payload(
|
||||
config, "https://oss.example.com/readoor/iOS/app_2_197_1.ipa"
|
||||
)
|
||||
text = payload["markdown"]["text"]
|
||||
# 标题保留「打包」二字,避免命中钉钉自定义关键词拦截
|
||||
assert "## 【iOS】App_Store 打包信息" in text
|
||||
assert "**iOS 下载链接:** https://oss.example.com/readoor/iOS/app_2_197_1.ipa" in text
|
||||
assert "![image]" not in text
|
||||
|
||||
|
||||
def test_dingtalk_notification_app_store_uses_own_at_list():
|
||||
response = MagicMock(status_code=200)
|
||||
response.json.return_value = {"errcode": 0}
|
||||
dingtalk_config = {
|
||||
"enabled": True,
|
||||
"webhook_url": "https://example.com/robot",
|
||||
"at_mobiles": ["13800000000"],
|
||||
"at_mobiles_app_store": ["13911111111", "13922222222"],
|
||||
}
|
||||
with patch("backend.services.notification.httpx.post", return_value=response) as post:
|
||||
send_dingtalk_notification(
|
||||
dingtalk_config,
|
||||
{**_build_config(), "BUILD_TYPE": "App_Store"},
|
||||
"https://oss.example.com/app.ipa",
|
||||
)
|
||||
|
||||
sent = post.call_args.kwargs["json"]
|
||||
assert sent["at"]["atMobiles"] == ["13911111111", "13922222222"]
|
||||
assert "## 【iOS】App_Store 打包信息" in sent["markdown"]["text"]
|
||||
assert "@13800000000" not in sent["markdown"]["text"]
|
||||
|
||||
|
||||
def test_dingtalk_notification_skips_when_disabled():
|
||||
with patch("backend.services.notification.httpx.post") as post:
|
||||
assert send_dingtalk_notification({}, _build_config(), "https://download.example.com/app") is False
|
||||
@@ -58,3 +142,21 @@ def test_dingtalk_notification_sends_markdown():
|
||||
def test_dingtalk_notification_requires_webhook_when_enabled():
|
||||
with pytest.raises(NotificationError, match="Webhook"):
|
||||
send_dingtalk_notification({"enabled": True}, _build_config(), "https://download.example.com/app")
|
||||
|
||||
|
||||
def test_project_at_mobiles_override_global_per_build_type():
|
||||
from backend.services.notification import merge_project_at_mobiles
|
||||
|
||||
global_config = {"enabled": True, "at_mobiles": ["111"], "at_mobiles_app_store": ["222"]}
|
||||
merged = merge_project_at_mobiles(global_config, {"at_mobiles": ["333", "333", " "], "at_mobiles_app_store": []})
|
||||
|
||||
assert merged["at_mobiles"] == ["333"]
|
||||
assert merged["at_mobiles_app_store"] == ["222"] # 项目未配置,沿用全局
|
||||
assert global_config["at_mobiles"] == ["111"] # 不修改全局配置
|
||||
|
||||
|
||||
def test_project_at_mobiles_missing_keeps_global():
|
||||
from backend.services.notification import merge_project_at_mobiles
|
||||
|
||||
global_config = {"at_mobiles": ["111"]}
|
||||
assert merge_project_at_mobiles(global_config, None) == global_config
|
||||
|
||||
@@ -33,7 +33,9 @@ def test_apply_project_config_without_branch_autopacking(tmp_path):
|
||||
"<string>applinks:old</string>\n", encoding="utf-8"
|
||||
)
|
||||
with (build_dir / "readoor" / "3.0" / "readoor31.plist").open("wb") as f:
|
||||
plistlib.dump({"CFBundleURLTypes": []}, f)
|
||||
plistlib.dump({"CFBundleURLTypes": [
|
||||
{"CFBundleURLName": "wxwork", "CFBundleURLSchemes": ["1"]},
|
||||
]}, f)
|
||||
|
||||
theme = tmp_path / "theme" / "AppIcon.appiconset"
|
||||
theme.mkdir(parents=True)
|
||||
@@ -42,6 +44,7 @@ def test_apply_project_config_without_branch_autopacking(tmp_path):
|
||||
config = {
|
||||
"VERSION": "2.0.0", "BUILD_VERSION": "2.0.0.1", "APPID": "guid",
|
||||
"API": "https://api.example.com", "weixinpay": "wx-pay", "APPID_NAME": "Test",
|
||||
"wxworkSchema": "wx1234567890abcdef",
|
||||
"BUNDLE_ID": "com.example.test", "TEAM_ID": "TEAM", "PROVISIONING_NAME": "profile",
|
||||
"ASSOCIATED_DOMAINS": "applinks:example.com", "THEME": str(theme.parent), "BUILD_TYPE": "Ad_Hoc",
|
||||
"CERTIFICATE": "Apple Distribution",
|
||||
@@ -58,3 +61,53 @@ def test_apply_project_config_without_branch_autopacking(tmp_path):
|
||||
assert "iPhone Developer" not in project_content
|
||||
assert (build_dir / "exportOptions.plist").exists()
|
||||
assert (logo / "icon-1024.png").read_bytes() == b"icon"
|
||||
with (build_dir / "readoor" / "3.0" / "readoor31.plist").open("rb") as f:
|
||||
url_types = plistlib.load(f)["CFBundleURLTypes"]
|
||||
wxwork = next(i for i in url_types if i["CFBundleURLName"] == "wxwork")
|
||||
assert wxwork["CFBundleURLSchemes"] == ["wx1234567890abcdef"]
|
||||
|
||||
|
||||
def _make_minimal_project(build_dir):
|
||||
"""构造 apply_project_config 所需的最小工程骨架,返回关键文件路径。"""
|
||||
project = build_dir / "readoor.xcodeproj"
|
||||
swift = build_dir / "readoor" / "3.0" / "AppConfig"
|
||||
entitlements_dir = build_dir / "readoor" / "3.0"
|
||||
for path in [project, swift, entitlements_dir]:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
(project / "project.pbxproj").write_text(
|
||||
"MARKETING_VERSION = 1.0;\nCURRENT_PROJECT_VERSION = 1;\n"
|
||||
'CODE_SIGN_IDENTITY = "iPhone Developer";\n'
|
||||
'"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(swift / "RDAppConfiguration.swift").write_text(
|
||||
'let RD_APP_GUID: String = "old"\nlet RD_API_DOMAIN: String = "old"\n'
|
||||
'let RD_WECHAT_PAY_ID: String = "old"\nlet RD_SOURCE_VERSION: String = "old"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(entitlements_dir / "readoor31.entitlements").write_text(
|
||||
"<string>applinks:old</string>\n", encoding="utf-8"
|
||||
)
|
||||
return entitlements_dir / "readoor31.plist"
|
||||
|
||||
|
||||
def test_wxwork_schema_removed_when_not_configured(tmp_path):
|
||||
build_dir = tmp_path / "build"
|
||||
plist_path = _make_minimal_project(build_dir)
|
||||
with plist_path.open("wb") as f:
|
||||
plistlib.dump({"CFBundleURLTypes": [
|
||||
{"CFBundleURLName": "wxwork", "CFBundleURLSchemes": ["1"]},
|
||||
]}, f)
|
||||
|
||||
config = {
|
||||
"VERSION": "2.0.0", "BUILD_VERSION": "2.0.0.1", "APPID": "guid",
|
||||
"API": "https://api.example.com", "APPID_NAME": "Test",
|
||||
"ASSOCIATED_DOMAINS": "applinks:example.com", "BUILD_TYPE": "Ad_Hoc",
|
||||
"CERTIFICATE": "Apple Distribution",
|
||||
}
|
||||
|
||||
apply_project_config(build_dir, config)
|
||||
|
||||
with plist_path.open("rb") as f:
|
||||
url_types = plistlib.load(f)["CFBundleURLTypes"]
|
||||
assert all(i.get("CFBundleURLName") != "wxwork" for i in url_types)
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
"""多项目配置测试"""
|
||||
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
|
||||
|
||||
|
||||
def test_project_dingtalk_at_saved_and_returned(client, dy_project, tmp_config):
|
||||
resp = client.put("/api/config/projects/dyauction",
|
||||
json={"dingtalk_at": {"at_mobiles": "13800000001,13800000002\n13800000001"}})
|
||||
assert resp.status_code == 200, resp.text
|
||||
dy = _root(tmp_config)["projects"]["dyauction"]
|
||||
assert dy["dingtalk_at"] == {"at_mobiles": ["13800000001", "13800000002"], "at_mobiles_app_store": []}
|
||||
|
||||
listed = {p["id"]: p for p in client.get("/api/config/projects").json()}
|
||||
assert listed["dyauction"]["dingtalk_at"]["at_mobiles"] == ["13800000001", "13800000002"]
|
||||
assert listed["readoor"]["dingtalk_at"] == {"at_mobiles": [], "at_mobiles_app_store": []}
|
||||
|
||||
|
||||
def test_project_dingtalk_at_must_be_object(client, dy_project):
|
||||
resp = client.put("/api/config/projects/dyauction", json={"dingtalk_at": ["138"]})
|
||||
assert resp.status_code == 400
|
||||
Reference in New Issue
Block a user