@supersdk/supercli 0.3.3-staging.45 → 0.3.3-staging.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/artifactIntegrity.js +158 -2
- package/dist/build/artifactIntegrity.js.map +1 -1
- package/dist/build/projectBuild.js +335 -0
- package/dist/build/projectBuild.js.map +1 -0
- package/dist/cli.js +0 -2
- package/dist/cli.js.map +1 -1
- package/dist/commands/add.js +35 -29
- package/dist/commands/add.js.map +1 -1
- package/dist/commands/build.js +407 -105
- package/dist/commands/build.js.map +1 -1
- package/dist/commands/init.js +22 -29
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/register.js +62 -217
- package/dist/commands/register.js.map +1 -1
- package/dist/config/appConfig.js +36 -163
- package/dist/config/appConfig.js.map +1 -1
- package/dist/config/superConfig.js +213 -185
- package/dist/config/superConfig.js.map +1 -1
- package/dist/deploy/manifest.js +189 -167
- package/dist/deploy/manifest.js.map +1 -1
- package/dist/deploy/preflight.js +15 -16
- package/dist/deploy/preflight.js.map +1 -1
- package/dist/deploy/runAdapter.js +7 -4
- package/dist/deploy/runAdapter.js.map +1 -1
- package/dist/docker/dockerCli.js +72 -77
- package/dist/docker/dockerCli.js.map +1 -1
- package/dist/template/README.md +26 -94
- package/dist/template/android/gradle/supersdk-config-reader.gradle +13 -62
- package/dist/template/android/scripts/build.sh +11 -0
- package/dist/template/ios/project.yml +1 -1
- package/dist/template/ios/scripts/build.sh +19 -0
- package/dist/template/ios/scripts/render_project.py +60 -0
- package/dist/template/ios/supersdk-default.config.json +6 -0
- package/dist/template/service/scripts/build.sh +11 -0
- package/dist/template/super.json +22 -14
- package/dist/template/template_manifest.json +3 -7
- package/dist/template/web/package.json +8 -0
- package/dist/template/web/scripts/build.sh +8 -0
- package/dist/template/web/scripts/web_package.py +490 -0
- package/dist/template/web/src/js/app.js +2 -2
- package/dist/util/shell.js +3 -3
- package/dist/workspace/config.js +3 -79
- package/dist/workspace/config.js.map +1 -1
- package/dist/workspace/identity.js +6 -15
- package/dist/workspace/identity.js.map +1 -1
- package/dist/workspace/projectIdentity.js +2 -7
- package/dist/workspace/projectIdentity.js.map +1 -1
- package/dist/workspace/template.js +205 -77
- package/dist/workspace/template.js.map +1 -1
- package/package.json +3 -1
- package/dist/commands/config.js +0 -170
- package/dist/commands/config.js.map +0 -1
- package/dist/template/scripts/android_snapshot_canary.py +0 -145
- package/dist/template/scripts/build_android.sh +0 -382
- package/dist/template/scripts/build_ios.sh +0 -331
- package/dist/template/scripts/build_service.sh +0 -89
- package/dist/template/scripts/build_site.sh +0 -57
- package/dist/template/scripts/lib/workspace.sh +0 -43
- package/dist/template/scripts/serve_web.py +0 -78
- package/dist/template/scripts/super_build_orchestrator.py +0 -344
- package/dist/template/scripts/supersdk_template.py +0 -1394
- package/dist/template/scripts/web_host_validator.py +0 -103
- package/dist/template/scripts/web_package.py +0 -296
- package/dist/template/scripts/ws03_shared_schema_merge_guard.py +0 -73
- package/dist/template/super_build.sh +0 -70
- package/dist/workspace/inspect.js +0 -275
- package/dist/workspace/inspect.js.map +0 -1
|
@@ -1,1394 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
import argparse
|
|
3
|
-
import ipaddress
|
|
4
|
-
import json
|
|
5
|
-
import os
|
|
6
|
-
import re
|
|
7
|
-
import shlex
|
|
8
|
-
import sys
|
|
9
|
-
import uuid
|
|
10
|
-
import hashlib
|
|
11
|
-
from pathlib import Path
|
|
12
|
-
from urllib.parse import urlparse
|
|
13
|
-
|
|
14
|
-
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
-
from web_host_validator import HostValidationError, normalize_host
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
# 🔴 引擎版本。这份脚本被 vendored 进**每一个**生成出来的工作空间,生成物里没有版本标记
|
|
19
|
-
# 就无法回答「这份 managed config 是哪一版引擎写的」。用户升级 CLI 后在老仓库里跑
|
|
20
|
-
# `supercli add`,CLI 写出新 schema、仓库自带的老引擎报「schemaVersion 必须是 N」——
|
|
21
|
-
# 那条错指向用户自己的配置文件,完全指不到真正的原因(工程模板过期了)。
|
|
22
|
-
# 版本号写进 managed config 纯为溯源;`engine-check` 子命令据此给出可执行的升级提示。
|
|
23
|
-
ENGINE_VERSION = "4.0.0"
|
|
24
|
-
|
|
25
|
-
MANAGED_BY = "supersdk-template"
|
|
26
|
-
# 每个项目目录下的 `.supersdk/managed/config.json` 有自己的 snake_case `schema_version`,
|
|
27
|
-
# 与根配置文件的 `schemaVersion` 是**两份**契约,各自独立演进。
|
|
28
|
-
MANAGED_CONFIG_SCHEMA_VERSION = 4
|
|
29
|
-
MANAGED_CONFIG_KEYS = (
|
|
30
|
-
"managed_by",
|
|
31
|
-
"schema_version",
|
|
32
|
-
"engine_version",
|
|
33
|
-
"spid",
|
|
34
|
-
"project_id",
|
|
35
|
-
"name",
|
|
36
|
-
"platform",
|
|
37
|
-
"dir",
|
|
38
|
-
"version",
|
|
39
|
-
"sdk",
|
|
40
|
-
"platform_config",
|
|
41
|
-
)
|
|
42
|
-
|
|
43
|
-
# 工作空间根配置:一个 workspace = 一个 spid,`super.json` 所在目录即工作空间根。
|
|
44
|
-
CONFIG_FILENAME = "super.json"
|
|
45
|
-
CONFIG_SCHEMA_VERSION = 4
|
|
46
|
-
LEGACY_CONFIG_FILENAMES = ("supersdk.json", "supersdk.yaml", "supersdk.yml", "super-site.yml")
|
|
47
|
-
|
|
48
|
-
# 首批项目类型。`type` 是普通字符串字段,加新类型只要加一个 build_<type>.sh 与一段投影,
|
|
49
|
-
# 不需要动 schema 版本;但**未知类型一律 fail-closed**,否则 plan 会给出一个根本不存在的
|
|
50
|
-
# helper 路径,直到 build 阶段才炸。
|
|
51
|
-
PROJECT_TYPES = ("android", "ios", "site", "service")
|
|
52
|
-
TYPE_ORDER = {name: index for index, name in enumerate(PROJECT_TYPES)}
|
|
53
|
-
|
|
54
|
-
# 每个项目条目允许的键。身份键(package / bundleId)只出现在项目里:
|
|
55
|
-
# 永不继承、永不推导,推导出来的身份等于把第三方 App 发到别人的反向域名下。
|
|
56
|
-
COMMON_PROJECT_KEYS = {"projectId", "type", "dir", "name", "version", "sdk"}
|
|
57
|
-
TYPE_PROJECT_KEYS = {
|
|
58
|
-
"android": {"package"},
|
|
59
|
-
"ios": {"bundleId", "spmMode"},
|
|
60
|
-
"site": {"deploy", "offline", "build"},
|
|
61
|
-
"service": {"deploy", "build"},
|
|
62
|
-
}
|
|
63
|
-
# 打错的身份键必须给定向诊断,而不是泛泛的 "unknown key"。
|
|
64
|
-
PROJECT_KEY_ALIASES = {
|
|
65
|
-
"ios": {"bundle_id": "bundleId", "bundleID": "bundleId", "bundle-id": "bundleId"},
|
|
66
|
-
"android": {"applicationId": "package", "package_name": "package", "packageName": "package"},
|
|
67
|
-
"site": {"host": "offline.host", "sites": "deploy"},
|
|
68
|
-
"service": {},
|
|
69
|
-
}
|
|
70
|
-
SITE_OFFLINE_KEYS = {"host"}
|
|
71
|
-
SITE_BUILD_KEYS = {"outputDir"}
|
|
72
|
-
SERVICE_BUILD_KEYS = {"context", "dockerfile", "platform", "argsFromEnv"}
|
|
73
|
-
DEPLOY_COMMON_KEYS = {"envTarget", "slug", "env", "name"}
|
|
74
|
-
SERVICE_DEPLOY_KEYS = {
|
|
75
|
-
"port", "cpuMilli", "memoryMiB", "maxScale", "databaseConnection", "runtimeEnvFromEnv", "secretsFromEnv"
|
|
76
|
-
}
|
|
77
|
-
ENV_REFERENCE_KEYS = {"name", "sourceEnv"}
|
|
78
|
-
VERSION_KEYS = {"name", "code"}
|
|
79
|
-
SDK_KEYS = {"androidVersion", "iosPackageUrl", "iosVersion"}
|
|
80
|
-
SDK_PROJECTION = {
|
|
81
|
-
"android": {"mock": ("androidVersion",), "real": ("androidVersion",)},
|
|
82
|
-
"ios": {"mock": (), "real": ("iosPackageUrl", "iosVersion")},
|
|
83
|
-
"site": {"mock": (), "real": ()},
|
|
84
|
-
"service": {"mock": (), "real": ()},
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
ANDROID_NAMESPACE = "com.supersdk.simple"
|
|
88
|
-
ANDROID_VERSION_RE = r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-.][A-Za-z0-9]+)*$"
|
|
89
|
-
IOS_VERSION_PATTERN = r"^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$"
|
|
90
|
-
SPID_PATTERN = r"[a-z0-9]{8}"
|
|
91
|
-
BUNDLE_ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9][A-Za-z0-9-]*)+"
|
|
92
|
-
JAVA_PACKAGE_PATTERN = r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+"
|
|
93
|
-
|
|
94
|
-
DEFAULT_VERSION_NAME = "1.0.0"
|
|
95
|
-
DEFAULT_VERSION_CODE = 1
|
|
96
|
-
MISSING = object()
|
|
97
|
-
|
|
98
|
-
# 退役根键。每一条都给**定向**诊断,而不是被「未知键原样保留」的规则带过去。
|
|
99
|
-
# v1 关键字先于 schemaVersion 检查(它们的诊断与 schemaVersion 无关);
|
|
100
|
-
# v2 关键字在 schemaVersion 之后检查,因为对 v2 文档来说 migrate 提示才是更有用的那条。
|
|
101
|
-
RETIRED_ROOT_KEYS = {
|
|
102
|
-
"schema_version": f"retired schema v1 key; use camelCase schemaVersion: {CONFIG_SCHEMA_VERSION}",
|
|
103
|
-
"app_id": "retired key; rename it to spid",
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
# environment 是本轮最重要的一条:它是**运行时 init 参数**,编译期根本不需要。
|
|
107
|
-
RETIRED_V2_ROOT_KEYS = {
|
|
108
|
-
"environment": (
|
|
109
|
-
"retired key; environment is a runtime init parameter, not build configuration. "
|
|
110
|
-
"Delete it from super.json: SuperSDK.init(context, spid, provider) defaults to prod, "
|
|
111
|
-
"and the bundled demo apps switch environment at runtime"
|
|
112
|
-
),
|
|
113
|
-
"android": 'retired schema v2 key; it is now an entry in projects[]: {"type": "android", "dir": "android", ...}',
|
|
114
|
-
"ios": 'retired schema v2 key; it is now an entry in projects[]: {"type": "ios", "dir": "ios", ...}',
|
|
115
|
-
"web": 'retired schema v2 key; it is now an entry in projects[]: {"type": "site", "dir": "web", ...}',
|
|
116
|
-
"sites": 'retired schema v2 key; each entry moved verbatim into the site project deploy[] array',
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
# 每个必填字段都在:少一个字段的迁移提示,对照抄的人就是死路。
|
|
120
|
-
MIGRATION_TEMPLATE = """{
|
|
121
|
-
"schemaVersion": 4,
|
|
122
|
-
"spid": "demo0001",
|
|
123
|
-
"name": "SuperSDK Simple",
|
|
124
|
-
"version": {
|
|
125
|
-
"name": "1.0.0",
|
|
126
|
-
"code": 1
|
|
127
|
-
},
|
|
128
|
-
"sdk": {
|
|
129
|
-
"androidVersion": "1.0.0.57-SNAPSHOT"
|
|
130
|
-
},
|
|
131
|
-
"projects": [
|
|
132
|
-
{
|
|
133
|
-
"projectId": "android",
|
|
134
|
-
"type": "android",
|
|
135
|
-
"dir": "android",
|
|
136
|
-
"name": "SuperSDK Simple",
|
|
137
|
-
"package": "com.example.app"
|
|
138
|
-
},
|
|
139
|
-
{
|
|
140
|
-
"projectId": "ios",
|
|
141
|
-
"type": "ios",
|
|
142
|
-
"dir": "ios",
|
|
143
|
-
"name": "SuperSDK Simple",
|
|
144
|
-
"bundleId": "com.example.app",
|
|
145
|
-
"spmMode": "mock"
|
|
146
|
-
},
|
|
147
|
-
{
|
|
148
|
-
"projectId": "web",
|
|
149
|
-
"type": "site",
|
|
150
|
-
"dir": "web",
|
|
151
|
-
"name": "SuperSDK Simple Web",
|
|
152
|
-
"offline": {
|
|
153
|
-
"host": "app.example.com"
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
]
|
|
157
|
-
}
|
|
158
|
-
"""
|
|
159
|
-
|
|
160
|
-
# 写盘键序:根键 + 项目条目内部键。CLI 侧 serializeAppConfig 用同一套顺序,
|
|
161
|
-
# 两边写出的字节形态必须一致,否则 git diff 里会出现整文件重排。
|
|
162
|
-
#
|
|
163
|
-
# 🔴 这个不变式是**被测出来的**,不是靠这段注释维持的:常量在 Python 与 TypeScript 里各写
|
|
164
|
-
# 一份,曾经真的漂过(这里排 deploy/offline 在前,CLI 侧排 version/sdk 在前),而当时的注释
|
|
165
|
-
# 照样宣称「两边一致」—— 一句拦不住漂移的注释,只会让下一个人去改错的那一边。
|
|
166
|
-
# **这份元组是源**,supercli/src/config/appConfig.ts 逐字抄它;改这里必须同步改那边,
|
|
167
|
-
# 由 tests/test_template_foundation.py::test_key_order_matches_the_cli_serializer 兜底。
|
|
168
|
-
# 项目条目键序的语义:先身份(type/dir/name),再平台身份字段,再站点侧的 deploy/offline,
|
|
169
|
-
# 最后是可覆盖的默认值(version/sdk)。
|
|
170
|
-
ROOT_KEY_ORDER = ("schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects")
|
|
171
|
-
PROJECT_KEY_ORDER = (
|
|
172
|
-
"projectId", "type", "dir", "name", "package", "bundleId", "spmMode", "build", "deploy", "offline", "version", "sdk"
|
|
173
|
-
)
|
|
174
|
-
NESTED_KEY_ORDER = {
|
|
175
|
-
"version": ("name", "code"),
|
|
176
|
-
"sdk": ("androidVersion", "iosPackageUrl", "iosVersion"),
|
|
177
|
-
"offline": ("host",),
|
|
178
|
-
"build": ("outputDir", "context", "dockerfile", "platform", "argsFromEnv"),
|
|
179
|
-
}
|
|
180
|
-
DEPLOY_KEY_ORDER = (
|
|
181
|
-
"envTarget", "slug", "name", "env", "port", "cpuMilli", "memoryMiB", "maxScale", "databaseConnection",
|
|
182
|
-
"runtimeEnvFromEnv", "secretsFromEnv",
|
|
183
|
-
)
|
|
184
|
-
PROJECT_ID_PATTERN = r"[a-z][a-z0-9-]{0,63}"
|
|
185
|
-
ENV_TARGET_PATTERN = r"[a-z][a-z0-9-]{0,31}"
|
|
186
|
-
ENV_NAME_PATTERN = r"[A-Za-z_][A-Za-z0-9_]*"
|
|
187
|
-
DEPLOY_SLUG_PATTERN = r"[a-z0-9]{1,32}"
|
|
188
|
-
DEPLOY_ENV_PATTERN = r"[a-z0-9]{1,10}"
|
|
189
|
-
RESERVED_DEPLOY_SLUGS = {"stg", "site"}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
class ConfigError(Exception):
|
|
193
|
-
def __init__(self, field, message):
|
|
194
|
-
super().__init__(f"{field}: {message}")
|
|
195
|
-
self.field = field
|
|
196
|
-
self.message = message
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
def helper_path():
|
|
200
|
-
return Path(__file__).resolve()
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
def migrate_command(source=None, target=None):
|
|
204
|
-
"""Return the real, copy-pasteable v3 -> v4 migration command."""
|
|
205
|
-
source_arg = shlex.quote(str(source)) if source is not None else "supersdk.json"
|
|
206
|
-
target_arg = shlex.quote(str(target)) if target is not None else "super.json"
|
|
207
|
-
return f"python3 {shlex.quote(str(helper_path()))} migrate --from {source_arg} --to {target_arg}"
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
def config_file_state(target_path):
|
|
211
|
-
"""判定已存在的 supersdk.json,让提示永远不会覆盖真值。
|
|
212
|
-
|
|
213
|
-
返回 ("missing" | "valid" | "invalid", reason)。直接解析目标文件,不走 load_config(),
|
|
214
|
-
否则会再次触发 legacy 扫描。
|
|
215
|
-
"""
|
|
216
|
-
if not target_path.is_file():
|
|
217
|
-
return "missing", ""
|
|
218
|
-
try:
|
|
219
|
-
validate_config(read_config_document(target_path), config_path=target_path)
|
|
220
|
-
except ConfigError as exc:
|
|
221
|
-
return "invalid", exc.message
|
|
222
|
-
return "valid", ""
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
def migration_hint(legacy_path, target_path):
|
|
226
|
-
legacy = shlex.quote(str(legacy_path))
|
|
227
|
-
target = shlex.quote(str(target_path))
|
|
228
|
-
skeleton = f"cat > {target} <<'SUPERSDK_JSON'\n{MIGRATION_TEMPLATE}SUPERSDK_JSON\n"
|
|
229
|
-
header = (
|
|
230
|
-
f"legacy config {legacy_path} is not supported; the template reads standard JSON "
|
|
231
|
-
f"{CONFIG_FILENAME} (schemaVersion {CONFIG_SCHEMA_VERSION}) only.\n"
|
|
232
|
-
)
|
|
233
|
-
state, reason = config_file_state(target_path)
|
|
234
|
-
if state == "valid":
|
|
235
|
-
# 这里唯一安全的动作:真实配置已经在位,发 `cat >` 骨架会把 spid/package/bundleId/host
|
|
236
|
-
# 全部替换成默认值。
|
|
237
|
-
return (
|
|
238
|
-
header
|
|
239
|
-
+ f"your {target_path} is already in place and valid, so nothing needs to be written; "
|
|
240
|
-
"the legacy file is the only leftover. Copy-paste to remove it:\n"
|
|
241
|
-
+ f"rm {legacy}\n"
|
|
242
|
-
)
|
|
243
|
-
if state == "invalid":
|
|
244
|
-
return (
|
|
245
|
-
header
|
|
246
|
-
+ f"{target_path} exists but is not usable ({reason}), so back it up before replacing it. "
|
|
247
|
-
"Copy-paste to migrate, then replace every value with the one from the legacy file "
|
|
248
|
-
"(the legacy file is deleted last because it is the source of those values):\n"
|
|
249
|
-
+ f"cp {target} {shlex.quote(str(target_path) + '.bak')}\n"
|
|
250
|
-
+ skeleton
|
|
251
|
-
+ f"rm {legacy}\n"
|
|
252
|
-
)
|
|
253
|
-
return (
|
|
254
|
-
header
|
|
255
|
-
+ "Copy-paste to migrate, then replace every value with the one from the legacy file "
|
|
256
|
-
"(the new file is written first and the legacy file is deleted last, because the legacy "
|
|
257
|
-
"file is the source of those values):\n"
|
|
258
|
-
+ skeleton
|
|
259
|
-
+ f"rm {legacy}\n"
|
|
260
|
-
)
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
def reject_duplicate_keys(pairs):
|
|
264
|
-
mapping = {}
|
|
265
|
-
for key, value in pairs:
|
|
266
|
-
if key in mapping:
|
|
267
|
-
raise ConfigError(key, "duplicate key")
|
|
268
|
-
mapping[key] = value
|
|
269
|
-
return mapping
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
def reject_json_constant(name):
|
|
273
|
-
# stdlib json 接受 NaN/Infinity/-Infinity,supercli 的 JSON.parse 不接受。
|
|
274
|
-
# 两边必须以同一种方式读同一个文件,所以这里也拒。
|
|
275
|
-
raise ConfigError(CONFIG_FILENAME, f"{name} is not standard JSON; use a number, string, or null")
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
def read_config_document(config_path):
|
|
279
|
-
"""读并解析一个配置文件。不做 legacy 扫描,因此可重入。"""
|
|
280
|
-
config_path = Path(config_path)
|
|
281
|
-
if not config_path.is_file():
|
|
282
|
-
raise ConfigError(CONFIG_FILENAME, f"not found: {config_path}")
|
|
283
|
-
try:
|
|
284
|
-
text = config_path.read_text(encoding="utf-8")
|
|
285
|
-
except (OSError, UnicodeDecodeError) as exc:
|
|
286
|
-
raise ConfigError(CONFIG_FILENAME, f"unreadable: {exc}") from exc
|
|
287
|
-
try:
|
|
288
|
-
return json.loads(text, object_pairs_hook=reject_duplicate_keys, parse_constant=reject_json_constant)
|
|
289
|
-
except ConfigError:
|
|
290
|
-
raise
|
|
291
|
-
except json.JSONDecodeError as exc:
|
|
292
|
-
raise ConfigError(CONFIG_FILENAME, f"invalid JSON at line {exc.lineno} column {exc.colno}: {exc.msg}") from exc
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
def load_config(path):
|
|
296
|
-
config_path = Path(path)
|
|
297
|
-
target_path = config_path.parent / CONFIG_FILENAME
|
|
298
|
-
# 对退役方言硬失败,而不是猜一份等价的 JSON。
|
|
299
|
-
if config_path.name in LEGACY_CONFIG_FILENAMES or config_path.suffix.lower() in (".yaml", ".yml"):
|
|
300
|
-
raise ConfigError(config_path.name, migration_hint(config_path, target_path))
|
|
301
|
-
for legacy_name in LEGACY_CONFIG_FILENAMES:
|
|
302
|
-
legacy_path = config_path.parent / legacy_name
|
|
303
|
-
if legacy_path.is_file():
|
|
304
|
-
raise ConfigError(legacy_name, migration_hint(legacy_path, target_path))
|
|
305
|
-
return read_config_document(config_path)
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
def require_mapping(value, field):
|
|
309
|
-
if not isinstance(value, dict):
|
|
310
|
-
raise ConfigError(field, "must be a JSON object")
|
|
311
|
-
return value
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
def require_string(value, field, allow_empty=False):
|
|
315
|
-
if value is None:
|
|
316
|
-
raise ConfigError(field, "must not be empty")
|
|
317
|
-
if not isinstance(value, str):
|
|
318
|
-
raise ConfigError(field, "must be a string")
|
|
319
|
-
if not allow_empty and value.strip() == "":
|
|
320
|
-
raise ConfigError(field, "must not be empty")
|
|
321
|
-
return value
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
def validate_android_version(value, field="sdk.androidVersion"):
|
|
325
|
-
if not isinstance(value, str) or not re.fullmatch(ANDROID_VERSION_RE, value.strip()):
|
|
326
|
-
raise ConfigError(field, f"must match {ANDROID_VERSION_RE}")
|
|
327
|
-
return value.strip()
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
def validate_version_code(value, field="version.code"):
|
|
331
|
-
if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > 2147483647:
|
|
332
|
-
raise ConfigError(field, "must be a positive 32-bit integer")
|
|
333
|
-
return value
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
def is_positive_int(value):
|
|
337
|
-
return not isinstance(value, bool) and isinstance(value, int) and value > 0
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
def validate_ios_package_url(value, field="sdk.iosPackageUrl"):
|
|
341
|
-
if value is None or not isinstance(value, str) or value.strip() == "":
|
|
342
|
-
raise ConfigError(field, "must be an HTTPS URL or spmMode must be mock")
|
|
343
|
-
parsed = urlparse(value)
|
|
344
|
-
if parsed.scheme != "https" or not parsed.netloc:
|
|
345
|
-
raise ConfigError(field, "must be an HTTPS URL")
|
|
346
|
-
host = (parsed.hostname or "").lower()
|
|
347
|
-
if (
|
|
348
|
-
host in {"localhost", "127.0.0.1", "0.0.0.0", "::1", "example.com", "example.org"}
|
|
349
|
-
or host.endswith(".localhost")
|
|
350
|
-
or host.endswith(".local")
|
|
351
|
-
or host.endswith(".example.com")
|
|
352
|
-
or host.endswith(".example.org")
|
|
353
|
-
or "example.invalid" in host
|
|
354
|
-
):
|
|
355
|
-
raise ConfigError(field, "must not be a placeholder or local URL")
|
|
356
|
-
try:
|
|
357
|
-
address = ipaddress.ip_address(host)
|
|
358
|
-
except ValueError:
|
|
359
|
-
address = None
|
|
360
|
-
if address and (address.is_private or address.is_loopback or address.is_link_local or address.is_unspecified):
|
|
361
|
-
raise ConfigError(field, "must not be a placeholder or local URL")
|
|
362
|
-
return value
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
def validate_ios_version(value, field="sdk.iosVersion"):
|
|
366
|
-
if not isinstance(value, str) or not re.fullmatch(IOS_VERSION_PATTERN, value):
|
|
367
|
-
raise ConfigError(field, f"must match {IOS_VERSION_PATTERN}")
|
|
368
|
-
return value
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
def validate_sdk_namespace(raw_sdk, field):
|
|
372
|
-
"""只做**形状**校验(键名/标量),值的合法性留给按项目的 scope。"""
|
|
373
|
-
if raw_sdk is MISSING:
|
|
374
|
-
raw_sdk = {}
|
|
375
|
-
sdk = require_mapping(raw_sdk, field)
|
|
376
|
-
for key, value in sdk.items():
|
|
377
|
-
if not isinstance(key, str):
|
|
378
|
-
raise ConfigError(field, "keys must be strings")
|
|
379
|
-
if key not in SDK_KEYS:
|
|
380
|
-
raise ConfigError(f"{field}.{key}", "unknown key")
|
|
381
|
-
if isinstance(value, (dict, list)):
|
|
382
|
-
raise ConfigError(f"{field}.{key}", "must be a scalar")
|
|
383
|
-
return sdk
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
def validate_version_namespace(raw_version, field):
|
|
387
|
-
if raw_version is MISSING:
|
|
388
|
-
raw_version = {}
|
|
389
|
-
version = require_mapping(raw_version, field)
|
|
390
|
-
for key in version:
|
|
391
|
-
if key not in VERSION_KEYS:
|
|
392
|
-
raise ConfigError(f"{field}.{key}", "unknown key")
|
|
393
|
-
if "name" in version:
|
|
394
|
-
require_string(version["name"], f"{field}.name")
|
|
395
|
-
if "code" in version:
|
|
396
|
-
validate_version_code(version["code"], f"{field}.code")
|
|
397
|
-
return version
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
def resolve_version(version, field):
|
|
401
|
-
"""把一份 version 对象归一成 {name, code}。整值替换后的兜底默认值在这里生效。"""
|
|
402
|
-
version_name = version.get("name", DEFAULT_VERSION_NAME)
|
|
403
|
-
version_name = require_string(version_name, f"{field}.name")
|
|
404
|
-
version_code = validate_version_code(version.get("code", DEFAULT_VERSION_CODE), f"{field}.code")
|
|
405
|
-
return {"name": version_name, "code": version_code}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
def validate_cli_owned_keys(raw):
|
|
409
|
-
if "orgId" in raw and (
|
|
410
|
-
not isinstance(raw["orgId"], str) or not re.fullmatch(r"[1-9][0-9]*", raw["orgId"])
|
|
411
|
-
):
|
|
412
|
-
raise ConfigError("orgId", "must be a positive decimal string")
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
def normalize_project_dir(value, field):
|
|
416
|
-
"""项目目录:相对、无 `..`、至少一段、不吞工作空间根。"""
|
|
417
|
-
raw = require_string(value, field)
|
|
418
|
-
if "\\" in raw:
|
|
419
|
-
raise ConfigError(field, "must use forward slashes")
|
|
420
|
-
if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
|
|
421
|
-
raise ConfigError(field, "must be relative to the workspace root")
|
|
422
|
-
parts = raw.split("/")
|
|
423
|
-
if not parts or any(part == "" for part in parts):
|
|
424
|
-
raise ConfigError(field, "must name a subdirectory of the workspace root")
|
|
425
|
-
for part in parts:
|
|
426
|
-
if part in (".", ".."):
|
|
427
|
-
raise ConfigError(field, "must not contain . or .. segments")
|
|
428
|
-
return "/".join(parts)
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
def assert_dirs_are_disjoint(entries):
|
|
432
|
-
"""dir 全局唯一,且不得互为祖先。
|
|
433
|
-
|
|
434
|
-
这是**工作空间级**不变式,与选了哪个项目无关:两个项目共用一个目录,
|
|
435
|
-
第二次注入会静默覆盖第一次的 managed config。
|
|
436
|
-
"""
|
|
437
|
-
seen = {}
|
|
438
|
-
for index, entry in entries:
|
|
439
|
-
directory = entry["dir"]
|
|
440
|
-
if directory in seen:
|
|
441
|
-
raise ConfigError(
|
|
442
|
-
f"projects[{index}].dir",
|
|
443
|
-
f"duplicates projects[{seen[directory]}].dir ({directory}); every project needs its own directory",
|
|
444
|
-
)
|
|
445
|
-
seen[directory] = index
|
|
446
|
-
ordered = sorted(seen.items(), key=lambda item: item[0].split("/"))
|
|
447
|
-
for (first, first_index), (second, second_index) in zip(ordered, ordered[1:]):
|
|
448
|
-
first_parts = first.split("/")
|
|
449
|
-
second_parts = second.split("/")
|
|
450
|
-
if second_parts[: len(first_parts)] == first_parts:
|
|
451
|
-
raise ConfigError(
|
|
452
|
-
f"projects[{second_index}].dir",
|
|
453
|
-
f"{second} is nested inside projects[{first_index}].dir ({first}); project directories must be disjoint",
|
|
454
|
-
)
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
def assert_project_ids_unique(shapes):
|
|
458
|
-
seen = {}
|
|
459
|
-
for shape in shapes:
|
|
460
|
-
project_id = shape["projectId"]
|
|
461
|
-
if project_id in seen:
|
|
462
|
-
raise ConfigError(
|
|
463
|
-
f"projects[{shape['index']}].projectId",
|
|
464
|
-
f"duplicates projects[{seen[project_id]}].projectId ({project_id})",
|
|
465
|
-
)
|
|
466
|
-
seen[project_id] = shape["index"]
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
def read_project_shape(entry, index):
|
|
470
|
-
"""只读出选择所需的最小信息(projectId / type / dir),其余校验按 selected 分流。"""
|
|
471
|
-
if not isinstance(entry, dict):
|
|
472
|
-
raise ConfigError(f"projects[{index}]", "must be a JSON object")
|
|
473
|
-
project_type = entry.get("type")
|
|
474
|
-
if project_type is None:
|
|
475
|
-
raise ConfigError(f"projects[{index}].type", f"is required; one of {', '.join(PROJECT_TYPES)}")
|
|
476
|
-
project_type = require_string(project_type, f"projects[{index}].type")
|
|
477
|
-
project_id = require_string(entry.get("projectId"), f"projects[{index}].projectId")
|
|
478
|
-
if not re.fullmatch(PROJECT_ID_PATTERN, project_id):
|
|
479
|
-
raise ConfigError(f"projects[{index}].projectId", f"must match ^{PROJECT_ID_PATTERN}$")
|
|
480
|
-
directory = normalize_project_dir(entry.get("dir"), f"projects[{index}].dir")
|
|
481
|
-
return {"index": index, "projectId": project_id, "type": project_type, "dir": directory, "raw": entry}
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
def select_project_shapes(shapes, platform="all", project=None):
|
|
485
|
-
selected = shapes
|
|
486
|
-
if project is not None:
|
|
487
|
-
wanted = require_string(project, "--project")
|
|
488
|
-
selected = [shape for shape in selected if shape["projectId"] == wanted]
|
|
489
|
-
if not selected:
|
|
490
|
-
known = ", ".join(shape["projectId"] for shape in shapes) or "<none>"
|
|
491
|
-
raise ConfigError("--project", f"no project with projectId {wanted}; configured projectIds: {known}")
|
|
492
|
-
if platform != "all" and selected[0]["type"] != platform:
|
|
493
|
-
raise ConfigError("--project", f"{wanted} is a {selected[0]['type']} project, not {platform}")
|
|
494
|
-
if platform != "all":
|
|
495
|
-
selected = [shape for shape in selected if shape["type"] == platform]
|
|
496
|
-
return selected
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
def validate_project(shape, root_name, workspace_version, workspace_sdk):
|
|
500
|
-
entry = shape["raw"]
|
|
501
|
-
index = shape["index"]
|
|
502
|
-
directory = shape["dir"]
|
|
503
|
-
project_id = shape["projectId"]
|
|
504
|
-
project_type = shape["type"]
|
|
505
|
-
label = f"projects[{directory}]"
|
|
506
|
-
|
|
507
|
-
if project_type not in PROJECT_TYPES:
|
|
508
|
-
raise ConfigError(f"projects[{index}].type", f"unknown project type {project_type!r}; expected one of {', '.join(PROJECT_TYPES)}")
|
|
509
|
-
|
|
510
|
-
allowed = COMMON_PROJECT_KEYS | TYPE_PROJECT_KEYS[project_type]
|
|
511
|
-
aliases = PROJECT_KEY_ALIASES[project_type]
|
|
512
|
-
for key in entry:
|
|
513
|
-
if key in aliases:
|
|
514
|
-
raise ConfigError(f"{label}.{aliases[key]}", f"use canonical {aliases[key]}")
|
|
515
|
-
if key not in allowed:
|
|
516
|
-
raise ConfigError(f"{label}.{key}", f"unknown key for {project_type} projects")
|
|
517
|
-
|
|
518
|
-
# version / sdk:workspace 级默认 + 项目级覆盖,**整值替换,不做深合并**。
|
|
519
|
-
if "version" in entry:
|
|
520
|
-
override = validate_version_namespace(entry.get("version"), f"{label}.version")
|
|
521
|
-
missing = sorted(VERSION_KEYS - set(override))
|
|
522
|
-
if missing:
|
|
523
|
-
raise ConfigError(
|
|
524
|
-
f"{label}.version",
|
|
525
|
-
"replaces the workspace version wholesale (values are not merged), so it must set both "
|
|
526
|
-
f"name and code; missing: {', '.join(missing)}",
|
|
527
|
-
)
|
|
528
|
-
version = resolve_version(override, f"{label}.version")
|
|
529
|
-
else:
|
|
530
|
-
version = dict(workspace_version)
|
|
531
|
-
|
|
532
|
-
sdk = dict(validate_sdk_namespace(entry.get("sdk"), f"{label}.sdk")) if "sdk" in entry else dict(workspace_sdk)
|
|
533
|
-
|
|
534
|
-
name = entry.get("name")
|
|
535
|
-
if name is not None:
|
|
536
|
-
name = require_string(name, f"{label}.name")
|
|
537
|
-
if name != name.strip():
|
|
538
|
-
raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
|
|
539
|
-
maximum = 50 if project_type in {"site", "service"} else 100
|
|
540
|
-
if len(name) > maximum:
|
|
541
|
-
raise ConfigError(f"{label}.name", f"must be 1..{maximum} characters")
|
|
542
|
-
|
|
543
|
-
if project_type == "android":
|
|
544
|
-
platform_config = validate_android_project(label, entry, name, root_name, sdk)
|
|
545
|
-
elif project_type == "ios":
|
|
546
|
-
platform_config = validate_ios_project(label, entry, name, root_name, sdk)
|
|
547
|
-
elif project_type == "site":
|
|
548
|
-
platform_config = validate_site_project(label, entry)
|
|
549
|
-
else:
|
|
550
|
-
platform_config = validate_service_project(label, entry)
|
|
551
|
-
|
|
552
|
-
mode = platform_config.get("spmMode", "mock")
|
|
553
|
-
projected_sdk = {key: sdk[key] for key in project_sdk(project_type, mode) if key in sdk}
|
|
554
|
-
|
|
555
|
-
return {
|
|
556
|
-
"projectId": project_id,
|
|
557
|
-
"type": project_type,
|
|
558
|
-
"dir": directory,
|
|
559
|
-
"name": name,
|
|
560
|
-
"version": version,
|
|
561
|
-
"sdk": projected_sdk,
|
|
562
|
-
"platformConfig": platform_config,
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
def require_project_name(label, name, root_name, project_type, target):
|
|
567
|
-
if name is not None and name.strip() != "":
|
|
568
|
-
if name != name.strip():
|
|
569
|
-
raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
|
|
570
|
-
if any(ord(char) < 32 for char in name):
|
|
571
|
-
raise ConfigError(f"{label}.name", f"must be a {target} without control characters")
|
|
572
|
-
maximum = 50 if project_type in {"site", "service"} else 100
|
|
573
|
-
if len(name) > maximum:
|
|
574
|
-
raise ConfigError(f"{label}.name", f"must be 1..{maximum} characters")
|
|
575
|
-
return name
|
|
576
|
-
hint = (
|
|
577
|
-
"the workspace-level name is a description and is never projected as an App label, "
|
|
578
|
-
"so it will not be used here"
|
|
579
|
-
if root_name is not None
|
|
580
|
-
else "it is never derived from spid or from the project directory"
|
|
581
|
-
)
|
|
582
|
-
raise ConfigError(f"{label}.name", f"is required for {project_type} projects and is the {target}; {hint}")
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
def validate_android_project(label, entry, name, root_name, sdk):
|
|
586
|
-
require_project_name(label, name, root_name, "android", "Android app label")
|
|
587
|
-
package_name = entry.get("package")
|
|
588
|
-
if package_name is None:
|
|
589
|
-
raise ConfigError(f"{label}.package", "is required for android projects and is never derived")
|
|
590
|
-
package_name = require_string(package_name, f"{label}.package")
|
|
591
|
-
if not re.fullmatch(JAVA_PACKAGE_PATTERN, package_name):
|
|
592
|
-
raise ConfigError(f"{label}.package", "must be a Java package")
|
|
593
|
-
if package_name == ANDROID_NAMESPACE:
|
|
594
|
-
raise ConfigError(f"{label}.package", f"must differ from fixed namespace {ANDROID_NAMESPACE}")
|
|
595
|
-
validate_android_version(sdk.get("androidVersion"), f"{label}.sdk.androidVersion")
|
|
596
|
-
return {"package": package_name}
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
def validate_ios_project(label, entry, name, root_name, sdk):
|
|
600
|
-
require_project_name(label, name, root_name, "ios", "iOS display name")
|
|
601
|
-
bundle_id = entry.get("bundleId")
|
|
602
|
-
if bundle_id is None:
|
|
603
|
-
raise ConfigError(f"{label}.bundleId", "is required for ios projects and is never derived")
|
|
604
|
-
bundle_id = require_string(bundle_id, f"{label}.bundleId")
|
|
605
|
-
if not re.fullmatch(BUNDLE_ID_PATTERN, bundle_id):
|
|
606
|
-
raise ConfigError(f"{label}.bundleId", "must be a bundle identifier")
|
|
607
|
-
|
|
608
|
-
spm_mode = entry.get("spmMode", "mock")
|
|
609
|
-
if not isinstance(spm_mode, str) or spm_mode not in {"mock", "real"}:
|
|
610
|
-
raise ConfigError(f"{label}.spmMode", "must be mock or real")
|
|
611
|
-
if spm_mode == "mock":
|
|
612
|
-
for key in ("iosPackageUrl", "iosVersion"):
|
|
613
|
-
if key in sdk:
|
|
614
|
-
raise ConfigError(f"{label}.sdk.{key}", "not allowed when spmMode is mock")
|
|
615
|
-
else:
|
|
616
|
-
validate_ios_package_url(sdk.get("iosPackageUrl"), f"{label}.sdk.iosPackageUrl")
|
|
617
|
-
validate_ios_version(sdk.get("iosVersion"), f"{label}.sdk.iosVersion")
|
|
618
|
-
return {"bundleId": bundle_id, "spmMode": spm_mode}
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
def validate_site_project(label, entry):
|
|
622
|
-
validate_deploy_targets(label, entry.get("deploy", MISSING), "site")
|
|
623
|
-
|
|
624
|
-
build = require_mapping(entry.get("build", {}), f"{label}.build")
|
|
625
|
-
reject_unknown_keys(build, SITE_BUILD_KEYS, f"{label}.build")
|
|
626
|
-
output_dir = normalize_project_relative_path(build.get("outputDir", "dist"), f"{label}.build.outputDir")
|
|
627
|
-
|
|
628
|
-
offline = require_mapping(entry.get("offline", {}), f"{label}.offline")
|
|
629
|
-
for key in offline:
|
|
630
|
-
if key not in SITE_OFFLINE_KEYS:
|
|
631
|
-
raise ConfigError(f"{label}.offline.{key}", "unknown key")
|
|
632
|
-
host = offline.get("host")
|
|
633
|
-
if host is not None:
|
|
634
|
-
host = require_string(host, f"{label}.offline.host")
|
|
635
|
-
try:
|
|
636
|
-
host = normalize_host(host)
|
|
637
|
-
except HostValidationError as exc:
|
|
638
|
-
raise ConfigError(f"{label}.offline.host", str(exc)) from exc
|
|
639
|
-
return {"host": host, "outputDir": output_dir}
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
def reject_unknown_keys(value, allowed, field):
|
|
643
|
-
for key in value:
|
|
644
|
-
if key not in allowed:
|
|
645
|
-
raise ConfigError(f"{field}.{key}", "unknown key")
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
def normalize_project_relative_path(value, field, allow_dot=False):
|
|
649
|
-
raw = require_string(value, field)
|
|
650
|
-
if raw == "." and allow_dot:
|
|
651
|
-
return raw
|
|
652
|
-
if "\\" in raw or raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
|
|
653
|
-
raise ConfigError(field, "must be a relative POSIX path")
|
|
654
|
-
parts = raw.split("/")
|
|
655
|
-
if not parts or any(part in ("", ".", "..") for part in parts):
|
|
656
|
-
raise ConfigError(field, "must stay within the project directory")
|
|
657
|
-
return "/".join(parts)
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
def validate_env_references(raw, field):
|
|
661
|
-
if raw is MISSING:
|
|
662
|
-
return []
|
|
663
|
-
if not isinstance(raw, list):
|
|
664
|
-
raise ConfigError(field, "must be an array")
|
|
665
|
-
seen = set()
|
|
666
|
-
result = []
|
|
667
|
-
for index, item in enumerate(raw):
|
|
668
|
-
item_field = f"{field}[{index}]"
|
|
669
|
-
item = require_mapping(item, item_field)
|
|
670
|
-
reject_unknown_keys(item, ENV_REFERENCE_KEYS, item_field)
|
|
671
|
-
name = require_string(item.get("name"), f"{item_field}.name")
|
|
672
|
-
source = require_string(item.get("sourceEnv"), f"{item_field}.sourceEnv")
|
|
673
|
-
if not re.fullmatch(ENV_NAME_PATTERN, name) or not re.fullmatch(ENV_NAME_PATTERN, source):
|
|
674
|
-
raise ConfigError(item_field, "name and sourceEnv must be environment variable names")
|
|
675
|
-
if name in seen:
|
|
676
|
-
raise ConfigError(f"{item_field}.name", "duplicates a platform environment variable name")
|
|
677
|
-
seen.add(name)
|
|
678
|
-
result.append({"name": name, "sourceEnv": source})
|
|
679
|
-
return result
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
def validate_deploy_targets(label, raw, project_type):
|
|
683
|
-
if raw is MISSING:
|
|
684
|
-
return []
|
|
685
|
-
if not isinstance(raw, list):
|
|
686
|
-
raise ConfigError(f"{label}.deploy", "must be an array")
|
|
687
|
-
result = []
|
|
688
|
-
seen = set()
|
|
689
|
-
for index, target in enumerate(raw):
|
|
690
|
-
field = f"{label}.deploy[{index}]"
|
|
691
|
-
target = require_mapping(target, field)
|
|
692
|
-
allowed = DEPLOY_COMMON_KEYS | (SERVICE_DEPLOY_KEYS if project_type == "service" else set())
|
|
693
|
-
reject_unknown_keys(target, allowed, field)
|
|
694
|
-
env_target = require_string(target.get("envTarget"), f"{field}.envTarget")
|
|
695
|
-
if not re.fullmatch(ENV_TARGET_PATTERN, env_target):
|
|
696
|
-
raise ConfigError(f"{field}.envTarget", f"must match ^{ENV_TARGET_PATTERN}$")
|
|
697
|
-
if env_target in seen:
|
|
698
|
-
raise ConfigError(f"{field}.envTarget", "must be unique within the project")
|
|
699
|
-
seen.add(env_target)
|
|
700
|
-
slug = require_string(target.get("slug"), f"{field}.slug")
|
|
701
|
-
if not re.fullmatch(DEPLOY_SLUG_PATTERN, slug) or slug in RESERVED_DEPLOY_SLUGS:
|
|
702
|
-
raise ConfigError(f"{field}.slug", "must be 1..32 lowercase letters or digits and not a reserved slug")
|
|
703
|
-
env = require_string(target.get("env"), f"{field}.env")
|
|
704
|
-
if not re.fullmatch(DEPLOY_ENV_PATTERN, env):
|
|
705
|
-
raise ConfigError(f"{field}.env", "must be 1..10 lowercase letters or digits")
|
|
706
|
-
if "name" in target:
|
|
707
|
-
target_name = require_string(target["name"], f"{field}.name")
|
|
708
|
-
if target_name != target_name.strip() or len(target_name) > 50:
|
|
709
|
-
raise ConfigError(f"{field}.name", "must be 1..50 characters without surrounding whitespace")
|
|
710
|
-
for key, upper in (("port", 65535), ("cpuMilli", 4000), ("memoryMiB", 8192), ("maxScale", 10)):
|
|
711
|
-
if key in target and (not is_positive_int(target[key]) or target[key] > upper):
|
|
712
|
-
raise ConfigError(f"{field}.{key}", f"must be an integer from 1 to {upper}")
|
|
713
|
-
if "databaseConnection" in target and target["databaseConnection"] is not None:
|
|
714
|
-
require_string(target["databaseConnection"], f"{field}.databaseConnection")
|
|
715
|
-
if project_type == "service":
|
|
716
|
-
runtime_refs = validate_env_references(target.get("runtimeEnvFromEnv", MISSING), f"{field}.runtimeEnvFromEnv")
|
|
717
|
-
secret_refs = validate_env_references(target.get("secretsFromEnv", MISSING), f"{field}.secretsFromEnv")
|
|
718
|
-
runtime_names = {reference["name"] for reference in runtime_refs}
|
|
719
|
-
duplicate_names = sorted(runtime_names & {reference["name"] for reference in secret_refs})
|
|
720
|
-
if duplicate_names:
|
|
721
|
-
raise ConfigError(field, "duplicates platform environment variable name across runtimeEnvFromEnv/secretsFromEnv: " + ", ".join(duplicate_names))
|
|
722
|
-
result.append(target)
|
|
723
|
-
return result
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
def validate_service_project(label, entry):
|
|
727
|
-
if "build" not in entry:
|
|
728
|
-
raise ConfigError(f"{label}.build", "is required for service projects")
|
|
729
|
-
build = require_mapping(entry["build"], f"{label}.build")
|
|
730
|
-
reject_unknown_keys(build, SERVICE_BUILD_KEYS, f"{label}.build")
|
|
731
|
-
context = normalize_project_relative_path(build.get("context", "."), f"{label}.build.context", allow_dot=True)
|
|
732
|
-
dockerfile = normalize_project_relative_path(build.get("dockerfile", "Dockerfile"), f"{label}.build.dockerfile")
|
|
733
|
-
platform = require_string(build.get("platform", "linux/amd64"), f"{label}.build.platform")
|
|
734
|
-
if platform != "linux/amd64":
|
|
735
|
-
raise ConfigError(f"{label}.build.platform", "must be linux/amd64 for this engine version")
|
|
736
|
-
args_from_env = build.get("argsFromEnv", [])
|
|
737
|
-
if not isinstance(args_from_env, list) or any(
|
|
738
|
-
not isinstance(item, str) or not re.fullmatch(ENV_NAME_PATTERN, item) for item in args_from_env
|
|
739
|
-
):
|
|
740
|
-
raise ConfigError(f"{label}.build.argsFromEnv", "must be an array of environment variable names")
|
|
741
|
-
if len(set(args_from_env)) != len(args_from_env):
|
|
742
|
-
raise ConfigError(f"{label}.build.argsFromEnv", "must not contain duplicates")
|
|
743
|
-
validate_deploy_targets(label, entry.get("deploy", MISSING), "service")
|
|
744
|
-
return {"context": context, "dockerfile": dockerfile, "platform": platform, "argsFromEnv": args_from_env}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
def check_root_envelope(raw, config_path=None):
|
|
748
|
-
"""根信封:退役键 + schemaVersion。定位项目和全量校验都要先过这一关。"""
|
|
749
|
-
if not isinstance(raw, dict):
|
|
750
|
-
raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
|
|
751
|
-
|
|
752
|
-
for key, reason in RETIRED_ROOT_KEYS.items():
|
|
753
|
-
if key in raw:
|
|
754
|
-
raise ConfigError(key, reason)
|
|
755
|
-
|
|
756
|
-
allowed_root = set(ROOT_KEY_ORDER)
|
|
757
|
-
for key in raw:
|
|
758
|
-
if key not in allowed_root:
|
|
759
|
-
raise ConfigError(key, "unknown key")
|
|
760
|
-
|
|
761
|
-
schema_version = raw.get("schemaVersion")
|
|
762
|
-
if isinstance(schema_version, bool) or not isinstance(schema_version, int) or schema_version != CONFIG_SCHEMA_VERSION:
|
|
763
|
-
message = f"must be {CONFIG_SCHEMA_VERSION}"
|
|
764
|
-
if schema_version == 3 and not isinstance(schema_version, bool):
|
|
765
|
-
message += (
|
|
766
|
-
f"; this file is schema v3. schemaVersion {CONFIG_SCHEMA_VERSION} is breaking and there is no "
|
|
767
|
-
"backward compatibility. Run `supercli config migrate --from supersdk.json --to super.json`."
|
|
768
|
-
)
|
|
769
|
-
raise ConfigError("schemaVersion", message)
|
|
770
|
-
|
|
771
|
-
for key, reason in RETIRED_V2_ROOT_KEYS.items():
|
|
772
|
-
if key in raw:
|
|
773
|
-
raise ConfigError(key, reason)
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
def read_project_shapes(raw):
|
|
777
|
-
"""读出所有项目的 type/dir,并校验工作空间级不变式(目录唯一且互不嵌套)。"""
|
|
778
|
-
if "projects" not in raw:
|
|
779
|
-
raise ConfigError("projects", "is required; add one with `supercli add <android|ios|site> <dir>`")
|
|
780
|
-
entries = raw.get("projects")
|
|
781
|
-
if not isinstance(entries, list):
|
|
782
|
-
raise ConfigError("projects", "must be an array")
|
|
783
|
-
shapes = [read_project_shape(entry, index) for index, entry in enumerate(entries)]
|
|
784
|
-
assert_dirs_are_disjoint([(shape["index"], shape) for shape in shapes])
|
|
785
|
-
assert_project_ids_unique(shapes)
|
|
786
|
-
return shapes
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
def no_selection_error(dirs, platform):
|
|
790
|
-
if not dirs:
|
|
791
|
-
return ConfigError("projects", "is empty; add one with `supercli add <android|ios|site> <dir>`")
|
|
792
|
-
scope = f"type {platform}" if platform != "all" else "this workspace"
|
|
793
|
-
return ConfigError("--platform", f"no project matches {scope}; configured directories: {', '.join(dirs)}")
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
def resolve_shapes(config_path, platform="all", project=None):
|
|
797
|
-
"""只回答「该进哪个目录」。
|
|
798
|
-
|
|
799
|
-
🔴 故意**不**做 per-project 全量校验:build_<type>.sh 只是想定位自己的项目目录,
|
|
800
|
-
拿这个问题去触发 bundleId/package 校验,会把 helper 自己更精确的诊断
|
|
801
|
-
(比如「managed config 里的 bundleId 缺失」)永远挡在后面。
|
|
802
|
-
"""
|
|
803
|
-
raw = load_config(config_path)
|
|
804
|
-
check_root_envelope(raw, config_path)
|
|
805
|
-
shapes = read_project_shapes(raw)
|
|
806
|
-
selected = select_project_shapes(shapes, platform, project)
|
|
807
|
-
if not selected:
|
|
808
|
-
raise no_selection_error([shape["dir"] for shape in shapes], platform)
|
|
809
|
-
return selected
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
def validate_config(raw, selected=None, project=None, config_path=None):
|
|
813
|
-
"""校验根配置。
|
|
814
|
-
|
|
815
|
-
🔴 `selected`(平台/类型)与 `project`(目录)现在**真的**限定 per-project 校验的范围:
|
|
816
|
-
v2 里 selected 只影响 web.host 归一化,iOS spmMode、android.package 格式、sdk.* 一律
|
|
817
|
-
无条件执行 —— 一个坏的 iosPackageUrl 会让 `--platform android` 也失败。v3 起所有
|
|
818
|
-
per-project 校验一律 scope 到 selected,这是**有意的放宽**。
|
|
819
|
-
工作空间级不变式(schemaVersion / spid / dir 唯一性)仍然无条件执行。
|
|
820
|
-
"""
|
|
821
|
-
platform = selected or "all"
|
|
822
|
-
check_root_envelope(raw, config_path)
|
|
823
|
-
validate_cli_owned_keys(raw)
|
|
824
|
-
|
|
825
|
-
spid = require_string(raw.get("spid"), "spid")
|
|
826
|
-
if not re.fullmatch(SPID_PATTERN, spid):
|
|
827
|
-
raise ConfigError("spid", f"must match ^{SPID_PATTERN}$")
|
|
828
|
-
|
|
829
|
-
root_name = raw.get("name")
|
|
830
|
-
if root_name is not None:
|
|
831
|
-
root_name = require_string(root_name, "name")
|
|
832
|
-
if root_name != root_name.strip() or len(root_name) > 100:
|
|
833
|
-
raise ConfigError("name", "must be 1..100 characters without surrounding whitespace")
|
|
834
|
-
|
|
835
|
-
# workspace 级 version/sdk 的**形状**无条件校验(它是工作空间级字段,与选谁无关);
|
|
836
|
-
# sdk 里各个值的合法性(androidVersion 格式、real 模式的 url/version)因类型而异,
|
|
837
|
-
# 留给按项目的 scope。
|
|
838
|
-
workspace_version = resolve_version(validate_version_namespace(raw.get("version", MISSING), "version"), "version")
|
|
839
|
-
workspace_sdk = validate_sdk_namespace(raw.get("sdk", MISSING), "sdk")
|
|
840
|
-
|
|
841
|
-
shapes = read_project_shapes(raw)
|
|
842
|
-
selected_shapes = select_project_shapes(shapes, platform, project)
|
|
843
|
-
all_projects = [validate_project(shape, root_name, workspace_version, workspace_sdk) for shape in shapes]
|
|
844
|
-
selected_ids = {shape["projectId"] for shape in selected_shapes}
|
|
845
|
-
projects = [item for item in all_projects if item["projectId"] in selected_ids]
|
|
846
|
-
|
|
847
|
-
target_owners = {}
|
|
848
|
-
for index, entry in enumerate(raw["projects"]):
|
|
849
|
-
for target_index, target in enumerate(entry.get("deploy", [])):
|
|
850
|
-
if not isinstance(target, dict) or "slug" not in target or "env" not in target:
|
|
851
|
-
continue
|
|
852
|
-
key = (target["slug"], target["env"])
|
|
853
|
-
if key in target_owners:
|
|
854
|
-
raise ConfigError(
|
|
855
|
-
f"projects[{index}].deploy[{target_index}]",
|
|
856
|
-
f"duplicates platform target slug/env owned by {target_owners[key]}",
|
|
857
|
-
)
|
|
858
|
-
target_owners[key] = f"projects[{index}].deploy[{target_index}]"
|
|
859
|
-
|
|
860
|
-
return {
|
|
861
|
-
"schemaVersion": CONFIG_SCHEMA_VERSION,
|
|
862
|
-
"engineVersion": ENGINE_VERSION,
|
|
863
|
-
"spid": spid,
|
|
864
|
-
"orgId": raw.get("orgId"),
|
|
865
|
-
"name": root_name,
|
|
866
|
-
"version": workspace_version,
|
|
867
|
-
"sdk": dict(workspace_sdk),
|
|
868
|
-
"projects": projects,
|
|
869
|
-
"projectDirs": [shape["dir"] for shape in shapes],
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
def load_and_validate(config_path, selected=None, project=None):
|
|
874
|
-
return validate_config(load_config(config_path), selected, project, config_path=config_path)
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
def require_selection(normalized, platform, project):
|
|
878
|
-
if normalized["projects"]:
|
|
879
|
-
return normalized["projects"]
|
|
880
|
-
raise no_selection_error(normalized["projectDirs"], platform)
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
def target_path(root, project):
|
|
884
|
-
return Path(root) / project["dir"] / ".supersdk" / "managed" / "config.json"
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
def project_sdk(platform, mode="mock"):
|
|
888
|
-
if platform not in SDK_PROJECTION:
|
|
889
|
-
raise ConfigError("platform", f"unknown platform: {platform}")
|
|
890
|
-
if mode not in SDK_PROJECTION[platform]:
|
|
891
|
-
raise ConfigError("sdk", f"unknown projection mode: {mode}")
|
|
892
|
-
return list(SDK_PROJECTION[platform][mode])
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
def target_content(normalized, project):
|
|
896
|
-
return {
|
|
897
|
-
"managed_by": MANAGED_BY,
|
|
898
|
-
"schema_version": MANAGED_CONFIG_SCHEMA_VERSION,
|
|
899
|
-
"engine_version": ENGINE_VERSION,
|
|
900
|
-
"spid": normalized["spid"],
|
|
901
|
-
"project_id": project["projectId"],
|
|
902
|
-
"name": project["name"],
|
|
903
|
-
"platform": project["type"],
|
|
904
|
-
"dir": project["dir"],
|
|
905
|
-
"version": project["version"],
|
|
906
|
-
"sdk": project["sdk"],
|
|
907
|
-
"platform_config": project["platformConfig"],
|
|
908
|
-
}
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
def test_fail_point(name):
|
|
912
|
-
# 原子写回滚的内部回归钩子,不是对外功能。
|
|
913
|
-
if os.environ.get("SUPERSDK_TEMPLATE_TEST_MODE") != "1":
|
|
914
|
-
return 0
|
|
915
|
-
raw = os.environ.get(name, "0") or "0"
|
|
916
|
-
try:
|
|
917
|
-
value = int(raw)
|
|
918
|
-
except ValueError as exc:
|
|
919
|
-
raise ConfigError(name, "must be an integer") from exc
|
|
920
|
-
if value < 0:
|
|
921
|
-
raise ConfigError(name, "must be non-negative")
|
|
922
|
-
return value
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
def is_managed_or_empty(path):
|
|
926
|
-
if not path.exists():
|
|
927
|
-
return True
|
|
928
|
-
if path.stat().st_size == 0:
|
|
929
|
-
return True
|
|
930
|
-
try:
|
|
931
|
-
return json.loads(path.read_text(encoding="utf-8")).get("managed_by") == MANAGED_BY
|
|
932
|
-
except OSError as exc:
|
|
933
|
-
raise ConfigError(str(path), f"cannot inspect target: {exc}") from exc
|
|
934
|
-
except (json.JSONDecodeError, UnicodeDecodeError, AttributeError):
|
|
935
|
-
return False
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
def build_write_plan(root, normalized):
|
|
939
|
-
return [
|
|
940
|
-
(target_path(root, project), json.dumps(target_content(normalized, project), indent=2, sort_keys=True) + "\n")
|
|
941
|
-
for project in normalized["projects"]
|
|
942
|
-
]
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
def inject(root, config, platform, project, force, dry_run):
|
|
946
|
-
root_path = Path(root)
|
|
947
|
-
normalized = load_and_validate(config, platform, project)
|
|
948
|
-
require_selection(normalized, platform, project)
|
|
949
|
-
plan = build_write_plan(root, normalized)
|
|
950
|
-
if dry_run:
|
|
951
|
-
refused = [str(path) for path, _ in plan if not force and not is_managed_or_empty(path)]
|
|
952
|
-
print(
|
|
953
|
-
json.dumps(
|
|
954
|
-
{
|
|
955
|
-
"would_abort": bool(refused),
|
|
956
|
-
"would_write": [] if refused else [str(path) for path, _ in plan],
|
|
957
|
-
"would_refuse": refused,
|
|
958
|
-
},
|
|
959
|
-
indent=2,
|
|
960
|
-
sort_keys=True,
|
|
961
|
-
)
|
|
962
|
-
)
|
|
963
|
-
return
|
|
964
|
-
refused = [str(path) for path, _ in plan if not force and not is_managed_or_empty(path)]
|
|
965
|
-
if refused:
|
|
966
|
-
raise ConfigError("refuse", "refuse overwrite unmanaged file(s): " + ", ".join(refused))
|
|
967
|
-
|
|
968
|
-
temp_files = []
|
|
969
|
-
backups = {}
|
|
970
|
-
replaced = []
|
|
971
|
-
created_dirs = set()
|
|
972
|
-
run_id = f"{os.getpid()}.{uuid.uuid4().hex}"
|
|
973
|
-
fail_after = test_fail_point("SUPERSDK_TEMPLATE_TEST_FAIL_REPLACE_AFTER")
|
|
974
|
-
fail_at = test_fail_point("SUPERSDK_TEMPLATE_TEST_FAIL_REPLACE_AT")
|
|
975
|
-
try:
|
|
976
|
-
for path, content in plan:
|
|
977
|
-
directory = path.parent
|
|
978
|
-
while directory != root_path and directory != directory.parent:
|
|
979
|
-
if not directory.exists():
|
|
980
|
-
created_dirs.add(directory)
|
|
981
|
-
directory = directory.parent
|
|
982
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
983
|
-
temp = path.with_name(f".{path.name}.tmp.{run_id}")
|
|
984
|
-
if temp.exists():
|
|
985
|
-
raise OSError(f"sidecar already exists: {temp}")
|
|
986
|
-
temp.write_text(content, encoding="utf-8")
|
|
987
|
-
temp_files.append(temp)
|
|
988
|
-
|
|
989
|
-
for index, (path, _) in enumerate(plan, start=1):
|
|
990
|
-
backup = path.with_name(f".{path.name}.bak.{run_id}")
|
|
991
|
-
if backup.exists():
|
|
992
|
-
raise OSError(f"sidecar already exists: {backup}")
|
|
993
|
-
if path.exists():
|
|
994
|
-
os.replace(path, backup)
|
|
995
|
-
backups[path] = backup
|
|
996
|
-
else:
|
|
997
|
-
backups[path] = None
|
|
998
|
-
if fail_at and index >= fail_at:
|
|
999
|
-
raise OSError("simulated replace syscall failure")
|
|
1000
|
-
os.replace(temp_files[index - 1], path)
|
|
1001
|
-
replaced.append(path)
|
|
1002
|
-
if fail_after and index >= fail_after:
|
|
1003
|
-
raise OSError("simulated replace failure")
|
|
1004
|
-
except Exception as exc:
|
|
1005
|
-
rollback_errors = []
|
|
1006
|
-
|
|
1007
|
-
def remember(action, target, error):
|
|
1008
|
-
rollback_errors.append(f"{action} {target}: {error}")
|
|
1009
|
-
|
|
1010
|
-
for path in replaced:
|
|
1011
|
-
try:
|
|
1012
|
-
if path.exists():
|
|
1013
|
-
path.unlink()
|
|
1014
|
-
except Exception as rollback_exc:
|
|
1015
|
-
remember("remove", path, rollback_exc)
|
|
1016
|
-
for path, backup in backups.items():
|
|
1017
|
-
try:
|
|
1018
|
-
if backup is not None and backup.exists():
|
|
1019
|
-
os.replace(backup, path)
|
|
1020
|
-
except Exception as rollback_exc:
|
|
1021
|
-
remember("restore", path, rollback_exc)
|
|
1022
|
-
for temp in temp_files:
|
|
1023
|
-
try:
|
|
1024
|
-
if temp.exists():
|
|
1025
|
-
temp.unlink()
|
|
1026
|
-
except Exception as rollback_exc:
|
|
1027
|
-
remember("remove", temp, rollback_exc)
|
|
1028
|
-
for directory in sorted(created_dirs, key=lambda item: len(str(item)), reverse=True):
|
|
1029
|
-
try:
|
|
1030
|
-
directory.rmdir()
|
|
1031
|
-
except OSError:
|
|
1032
|
-
pass
|
|
1033
|
-
if rollback_errors:
|
|
1034
|
-
print(f"write failed; rollback incomplete: {exc}; {'; '.join(rollback_errors)}", file=sys.stderr)
|
|
1035
|
-
else:
|
|
1036
|
-
print(f"write failed; rolled back: {exc}", file=sys.stderr)
|
|
1037
|
-
raise SystemExit(1)
|
|
1038
|
-
|
|
1039
|
-
cleanup_errors = []
|
|
1040
|
-
for backup in backups.values():
|
|
1041
|
-
if backup is not None and backup.exists():
|
|
1042
|
-
try:
|
|
1043
|
-
backup.unlink()
|
|
1044
|
-
except Exception as cleanup_exc:
|
|
1045
|
-
cleanup_errors.append(f"remove {backup}: {cleanup_exc}")
|
|
1046
|
-
if cleanup_errors:
|
|
1047
|
-
print(f"warning: backup cleanup incomplete: {'; '.join(cleanup_errors)}", file=sys.stderr)
|
|
1048
|
-
print(json.dumps({"written": [str(path) for path, _ in plan], "skipped": [], "refused": []}, indent=2, sort_keys=True))
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
def print_plan(root, config, platform, project):
|
|
1052
|
-
normalized = load_and_validate(config, platform, project)
|
|
1053
|
-
require_selection(normalized, platform, project)
|
|
1054
|
-
for item in normalized["projects"]:
|
|
1055
|
-
helper = Path(root) / "scripts" / ("build_" + item["type"] + ".sh")
|
|
1056
|
-
print(f"projectId={item['projectId']} type={item['type']} dir={item['dir']} helper={helper} mode=plan")
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
def print_resolve(config, platform, project):
|
|
1060
|
-
"""给 build_<type>.sh 用:把「哪个项目」定下来,零歧义或者 fail-closed。"""
|
|
1061
|
-
print(resolve_single(config, platform, project))
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
def resolve_single(config, platform, project):
|
|
1065
|
-
projects = resolve_shapes(config, platform, project)
|
|
1066
|
-
if len(projects) > 1:
|
|
1067
|
-
ids = ", ".join(item["projectId"] for item in projects)
|
|
1068
|
-
raise ConfigError(
|
|
1069
|
-
"--project",
|
|
1070
|
-
f"{len(projects)} {platform} projects are configured ({ids}); pass --project <projectId> to pick one",
|
|
1071
|
-
)
|
|
1072
|
-
return projects[0]["dir"]
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
def engine_check(root, config):
|
|
1076
|
-
"""比对已落盘 managed config 里的引擎版本与本脚本常量,不一致只 warn,不阻断。"""
|
|
1077
|
-
try:
|
|
1078
|
-
normalized = load_and_validate(config)
|
|
1079
|
-
except ConfigError:
|
|
1080
|
-
# 真正的命令会给出更好的诊断;这里保持安静,不抢话。
|
|
1081
|
-
return
|
|
1082
|
-
stale = []
|
|
1083
|
-
for directory in normalized["projectDirs"]:
|
|
1084
|
-
managed = Path(root) / directory / ".supersdk" / "managed" / "config.json"
|
|
1085
|
-
if not managed.is_file():
|
|
1086
|
-
continue
|
|
1087
|
-
try:
|
|
1088
|
-
payload = json.loads(managed.read_text(encoding="utf-8"))
|
|
1089
|
-
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
|
|
1090
|
-
continue
|
|
1091
|
-
if payload.get("managed_by") != MANAGED_BY:
|
|
1092
|
-
continue
|
|
1093
|
-
recorded = payload.get("engine_version")
|
|
1094
|
-
if recorded != ENGINE_VERSION:
|
|
1095
|
-
stale.append((directory, recorded))
|
|
1096
|
-
if stale:
|
|
1097
|
-
details = ", ".join(f"{directory} (engine {recorded or 'unrecorded'})" for directory, recorded in stale)
|
|
1098
|
-
print(
|
|
1099
|
-
f"warning: managed config was produced by a different template engine than {ENGINE_VERSION}: {details}. "
|
|
1100
|
-
"Re-run ./super_build.sh --build to reproject it.",
|
|
1101
|
-
file=sys.stderr,
|
|
1102
|
-
)
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
def order_keys(document, order):
|
|
1106
|
-
"""按固定键序重排;未知键按原有相对顺序追加在末尾(未知键必须原样保留)。
|
|
1107
|
-
|
|
1108
|
-
累加器用 `dict` 之外的 `Object.create(null)` 等价物:Python 里普通 dict 没有原型
|
|
1109
|
-
污染问题,但「未知键原样保留」这条纪律与 CLI 侧完全一致。
|
|
1110
|
-
"""
|
|
1111
|
-
ordered = {}
|
|
1112
|
-
for key in order:
|
|
1113
|
-
if key in document:
|
|
1114
|
-
ordered[key] = document[key]
|
|
1115
|
-
for key in document:
|
|
1116
|
-
if key not in order:
|
|
1117
|
-
ordered[key] = document[key]
|
|
1118
|
-
return ordered
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
def serialize_config(document):
|
|
1122
|
-
out = {}
|
|
1123
|
-
for key, value in order_keys(document, ROOT_KEY_ORDER).items():
|
|
1124
|
-
if key in NESTED_KEY_ORDER and isinstance(value, dict):
|
|
1125
|
-
out[key] = order_keys(value, NESTED_KEY_ORDER[key])
|
|
1126
|
-
elif key == "projects" and isinstance(value, list):
|
|
1127
|
-
out[key] = [serialize_project(item) for item in value]
|
|
1128
|
-
else:
|
|
1129
|
-
out[key] = value
|
|
1130
|
-
return json.dumps(out, indent=2, ensure_ascii=False) + "\n"
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
def serialize_project(entry):
|
|
1134
|
-
if not isinstance(entry, dict):
|
|
1135
|
-
return entry
|
|
1136
|
-
out = {}
|
|
1137
|
-
for key, value in order_keys(entry, PROJECT_KEY_ORDER).items():
|
|
1138
|
-
if key in NESTED_KEY_ORDER and isinstance(value, dict):
|
|
1139
|
-
out[key] = order_keys(value, NESTED_KEY_ORDER[key])
|
|
1140
|
-
elif key == "deploy" and isinstance(value, list):
|
|
1141
|
-
out[key] = [serialize_deploy_target(item) for item in value]
|
|
1142
|
-
else:
|
|
1143
|
-
out[key] = value
|
|
1144
|
-
return out
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
def serialize_deploy_target(item):
|
|
1148
|
-
if not isinstance(item, dict):
|
|
1149
|
-
return item
|
|
1150
|
-
ordered = order_keys(item, DEPLOY_KEY_ORDER)
|
|
1151
|
-
for key in ("runtimeEnvFromEnv", "secretsFromEnv"):
|
|
1152
|
-
if isinstance(ordered.get(key), list):
|
|
1153
|
-
ordered[key] = [order_keys(ref, ("name", "sourceEnv")) if isinstance(ref, dict) else ref for ref in ordered[key]]
|
|
1154
|
-
return ordered
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
def collect_v3_unknown_paths(raw):
|
|
1158
|
-
"""Enumerate every v3 field that cannot be represented by the strict v4 schema."""
|
|
1159
|
-
unknown = []
|
|
1160
|
-
if not isinstance(raw, dict):
|
|
1161
|
-
return ["$"]
|
|
1162
|
-
root_allowed = {"schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects"}
|
|
1163
|
-
unknown.extend(f"$.{key}" for key in raw if key not in root_allowed)
|
|
1164
|
-
for field, allowed in (("version", VERSION_KEYS), ("sdk", SDK_KEYS)):
|
|
1165
|
-
value = raw.get(field)
|
|
1166
|
-
if isinstance(value, dict):
|
|
1167
|
-
unknown.extend(f"$.{field}.{key}" for key in value if key not in allowed)
|
|
1168
|
-
projects = raw.get("projects")
|
|
1169
|
-
if not isinstance(projects, list):
|
|
1170
|
-
return unknown
|
|
1171
|
-
for index, project in enumerate(projects):
|
|
1172
|
-
if not isinstance(project, dict):
|
|
1173
|
-
continue
|
|
1174
|
-
project_type = project.get("type")
|
|
1175
|
-
allowed = (COMMON_PROJECT_KEYS - {"projectId", "build"}) | TYPE_PROJECT_KEYS.get(project_type, set())
|
|
1176
|
-
if project_type == "site":
|
|
1177
|
-
allowed -= {"build"}
|
|
1178
|
-
unknown.extend(f"$.projects[{index}].{key}" for key in project if key not in allowed)
|
|
1179
|
-
for field, nested_allowed in (("version", VERSION_KEYS), ("sdk", SDK_KEYS)):
|
|
1180
|
-
value = project.get(field)
|
|
1181
|
-
if isinstance(value, dict):
|
|
1182
|
-
unknown.extend(
|
|
1183
|
-
f"$.projects[{index}].{field}.{key}" for key in value if key not in nested_allowed
|
|
1184
|
-
)
|
|
1185
|
-
offline = project.get("offline")
|
|
1186
|
-
if isinstance(offline, dict):
|
|
1187
|
-
unknown.extend(f"$.projects[{index}].offline.{key}" for key in offline if key not in SITE_OFFLINE_KEYS)
|
|
1188
|
-
deploy = project.get("deploy")
|
|
1189
|
-
if isinstance(deploy, list):
|
|
1190
|
-
for target_index, target in enumerate(deploy):
|
|
1191
|
-
if isinstance(target, dict):
|
|
1192
|
-
allowed_target = {"slug", "name", "env", "dir"}
|
|
1193
|
-
unknown.extend(
|
|
1194
|
-
f"$.projects[{index}].deploy[{target_index}].{key}"
|
|
1195
|
-
for key in target if key not in allowed_target
|
|
1196
|
-
)
|
|
1197
|
-
build = project.get("build")
|
|
1198
|
-
if "build" in allowed and isinstance(build, dict):
|
|
1199
|
-
nested_allowed = SERVICE_BUILD_KEYS if project_type == "service" else SITE_BUILD_KEYS
|
|
1200
|
-
unknown.extend(
|
|
1201
|
-
f"$.projects[{index}].build.{key}" for key in build if key not in nested_allowed
|
|
1202
|
-
)
|
|
1203
|
-
return sorted(unknown)
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
def migrate_document(raw, config_dir=None):
|
|
1207
|
-
"""Convert a strict schema-v3 document to schema v4 without guessing identities."""
|
|
1208
|
-
del config_dir
|
|
1209
|
-
if not isinstance(raw, dict):
|
|
1210
|
-
raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
|
|
1211
|
-
version = raw.get("schemaVersion")
|
|
1212
|
-
if isinstance(version, bool) or not isinstance(version, int) or version != 3:
|
|
1213
|
-
raise ConfigError("schemaVersion", "migrate reads schemaVersion 3 documents only")
|
|
1214
|
-
unknown = collect_v3_unknown_paths(raw)
|
|
1215
|
-
if unknown:
|
|
1216
|
-
raise ConfigError("migration", "unknown field(s): " + ", ".join(unknown))
|
|
1217
|
-
|
|
1218
|
-
migrated = {"schemaVersion": 4}
|
|
1219
|
-
for key in ("spid", "orgId", "name", "version", "sdk"):
|
|
1220
|
-
if key in raw:
|
|
1221
|
-
migrated[key] = raw[key]
|
|
1222
|
-
projects = raw.get("projects")
|
|
1223
|
-
if not isinstance(projects, list):
|
|
1224
|
-
raise ConfigError("projects", "must be an array")
|
|
1225
|
-
ids = {}
|
|
1226
|
-
converted = []
|
|
1227
|
-
conflicts = []
|
|
1228
|
-
for index, project in enumerate(projects):
|
|
1229
|
-
if not isinstance(project, dict):
|
|
1230
|
-
raise ConfigError(f"projects[{index}]", "must be a JSON object")
|
|
1231
|
-
directory = normalize_project_dir(project.get("dir"), f"projects[{index}].dir")
|
|
1232
|
-
project_id = Path(directory).name.lower()
|
|
1233
|
-
if not re.fullmatch(PROJECT_ID_PATTERN, project_id):
|
|
1234
|
-
conflicts.append(f"projects[{index}].dir -> invalid projectId {project_id!r}")
|
|
1235
|
-
elif project_id in ids:
|
|
1236
|
-
conflicts.append(f"projects[{index}].dir -> projectId {project_id!r} also from projects[{ids[project_id]}]")
|
|
1237
|
-
ids[project_id] = index
|
|
1238
|
-
entry = {"projectId": project_id}
|
|
1239
|
-
for key, value in project.items():
|
|
1240
|
-
if key != "deploy":
|
|
1241
|
-
entry[key] = value
|
|
1242
|
-
if project.get("type") == "site" and "deploy" in project:
|
|
1243
|
-
deploy = project["deploy"]
|
|
1244
|
-
if not isinstance(deploy, list):
|
|
1245
|
-
raise ConfigError(f"projects[{index}].deploy", "must be an array")
|
|
1246
|
-
targets = []
|
|
1247
|
-
output_dirs = set()
|
|
1248
|
-
env_targets = set()
|
|
1249
|
-
for target_index, target in enumerate(deploy):
|
|
1250
|
-
if not isinstance(target, dict):
|
|
1251
|
-
raise ConfigError(f"projects[{index}].deploy[{target_index}]", "must be a JSON object")
|
|
1252
|
-
env_target = target.get("env")
|
|
1253
|
-
if env_target in env_targets:
|
|
1254
|
-
conflicts.append(f"projects[{index}].deploy[{target_index}].env -> duplicate envTarget {env_target!r}")
|
|
1255
|
-
env_targets.add(env_target)
|
|
1256
|
-
converted_target = {"envTarget": env_target}
|
|
1257
|
-
for key in ("slug", "name", "env"):
|
|
1258
|
-
if key in target:
|
|
1259
|
-
converted_target[key] = target[key]
|
|
1260
|
-
if "dir" in target:
|
|
1261
|
-
output_dirs.add(normalize_project_relative_path(target["dir"], f"projects[{index}].deploy[{target_index}].dir"))
|
|
1262
|
-
targets.append(converted_target)
|
|
1263
|
-
if len(output_dirs) > 1:
|
|
1264
|
-
conflicts.append(f"projects[{index}].deploy[].dir -> multiple site output directories")
|
|
1265
|
-
entry["deploy"] = targets
|
|
1266
|
-
if output_dirs:
|
|
1267
|
-
entry["build"] = {"outputDir": next(iter(output_dirs))}
|
|
1268
|
-
converted.append(entry)
|
|
1269
|
-
if conflicts:
|
|
1270
|
-
raise ConfigError("migration", "ambiguous mapping(s): " + "; ".join(conflicts))
|
|
1271
|
-
migrated["projects"] = converted
|
|
1272
|
-
validate_config(migrated)
|
|
1273
|
-
return migrated, []
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
def canonical_config_text(document):
|
|
1277
|
-
"""The byte-stable semantic representation shared by build and deploy."""
|
|
1278
|
-
validate_config(document)
|
|
1279
|
-
return serialize_config(document)
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
def canonical_config_sha256(document):
|
|
1283
|
-
return hashlib.sha256(canonical_config_text(document).encode("utf-8")).hexdigest()
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
def migrate(source, target, dry_run=False):
|
|
1287
|
-
source_path = Path(source).resolve()
|
|
1288
|
-
target_path = Path(target).resolve()
|
|
1289
|
-
if source_path.parent != target_path.parent:
|
|
1290
|
-
raise ConfigError("migration", "--from and --to must be in the same normalized workspace root")
|
|
1291
|
-
if target_path.exists():
|
|
1292
|
-
raise ConfigError("migration", f"target already exists: {target_path}")
|
|
1293
|
-
migrated, _ = migrate_document(read_config_document(source_path), source_path.parent)
|
|
1294
|
-
text = serialize_config(migrated)
|
|
1295
|
-
if dry_run:
|
|
1296
|
-
sys.stdout.write(text)
|
|
1297
|
-
return 0
|
|
1298
|
-
temp = target_path.with_name(f".{target_path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
|
|
1299
|
-
try:
|
|
1300
|
-
with temp.open("x", encoding="utf-8") as handle:
|
|
1301
|
-
handle.write(text)
|
|
1302
|
-
handle.flush()
|
|
1303
|
-
os.fsync(handle.fileno())
|
|
1304
|
-
# Hard-link install is atomic and no-clobber: unlike os.replace(), it
|
|
1305
|
-
# cannot overwrite a user file created after the exists() preflight.
|
|
1306
|
-
try:
|
|
1307
|
-
os.link(temp, target_path)
|
|
1308
|
-
except FileExistsError as exc:
|
|
1309
|
-
raise ConfigError("migration", f"target already exists: {target_path}") from exc
|
|
1310
|
-
except OSError as exc:
|
|
1311
|
-
raise ConfigError("migration", f"could not install target atomically: {exc}") from exc
|
|
1312
|
-
temp.unlink()
|
|
1313
|
-
try:
|
|
1314
|
-
directory_fd = os.open(str(target_path.parent), os.O_RDONLY)
|
|
1315
|
-
try:
|
|
1316
|
-
os.fsync(directory_fd)
|
|
1317
|
-
finally:
|
|
1318
|
-
os.close(directory_fd)
|
|
1319
|
-
except OSError:
|
|
1320
|
-
pass
|
|
1321
|
-
finally:
|
|
1322
|
-
if temp.exists():
|
|
1323
|
-
temp.unlink()
|
|
1324
|
-
print(f"migrated {source_path} to {target_path} (schemaVersion 4); source was not modified")
|
|
1325
|
-
return 0
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
def main(argv):
|
|
1329
|
-
parser = argparse.ArgumentParser(description="SuperSDK workspace schema and injection helper")
|
|
1330
|
-
sub = parser.add_subparsers(dest="command", required=True)
|
|
1331
|
-
|
|
1332
|
-
def add_selection(command):
|
|
1333
|
-
command.add_argument("--platform", choices=["all", *PROJECT_TYPES], default="all")
|
|
1334
|
-
command.add_argument("--project", default=None, help="Project directory relative to the workspace root")
|
|
1335
|
-
|
|
1336
|
-
validate = sub.add_parser("validate")
|
|
1337
|
-
validate.add_argument("--config", required=True)
|
|
1338
|
-
add_selection(validate)
|
|
1339
|
-
|
|
1340
|
-
plan = sub.add_parser("plan")
|
|
1341
|
-
plan.add_argument("--root", required=True)
|
|
1342
|
-
plan.add_argument("--config", required=True)
|
|
1343
|
-
add_selection(plan)
|
|
1344
|
-
|
|
1345
|
-
inject_cmd = sub.add_parser("inject")
|
|
1346
|
-
inject_cmd.add_argument("--root", required=True)
|
|
1347
|
-
inject_cmd.add_argument("--config", required=True)
|
|
1348
|
-
add_selection(inject_cmd)
|
|
1349
|
-
inject_cmd.add_argument("--force", action="store_true")
|
|
1350
|
-
inject_cmd.add_argument("--dry-run", action="store_true")
|
|
1351
|
-
|
|
1352
|
-
resolve = sub.add_parser("resolve")
|
|
1353
|
-
resolve.add_argument("--config", required=True)
|
|
1354
|
-
add_selection(resolve)
|
|
1355
|
-
|
|
1356
|
-
check = sub.add_parser("engine-check")
|
|
1357
|
-
check.add_argument("--root", required=True)
|
|
1358
|
-
check.add_argument("--config", required=True)
|
|
1359
|
-
|
|
1360
|
-
migrate_cmd = sub.add_parser("migrate")
|
|
1361
|
-
migrate_cmd.add_argument("--from", dest="source", required=True)
|
|
1362
|
-
migrate_cmd.add_argument("--to", dest="target", required=True)
|
|
1363
|
-
migrate_cmd.add_argument("--dry-run", action="store_true")
|
|
1364
|
-
|
|
1365
|
-
args = parser.parse_args(argv)
|
|
1366
|
-
try:
|
|
1367
|
-
if args.command == "validate":
|
|
1368
|
-
normalized = load_and_validate(args.config, args.platform, args.project)
|
|
1369
|
-
# 🔴 显式选择必须 fail closed,与 plan/inject/resolve 同一语义:被问到
|
|
1370
|
-
# 「android 这边配置对不对」时,回一句 `"projects": []` + exit 0 是错的信号。
|
|
1371
|
-
# `--project` 已经在 select_project_shapes 里挡住了,这里补的是 `--platform`。
|
|
1372
|
-
# `--platform all` 不在此列:空 projects[] 是 `supercli init` 之后、`add` 之前
|
|
1373
|
-
# 的合法形态,「还没有项目」不是「配置有问题」。
|
|
1374
|
-
if args.platform != "all":
|
|
1375
|
-
require_selection(normalized, args.platform, args.project)
|
|
1376
|
-
print(json.dumps(normalized, indent=2, sort_keys=True))
|
|
1377
|
-
elif args.command == "plan":
|
|
1378
|
-
print_plan(args.root, args.config, args.platform, args.project)
|
|
1379
|
-
elif args.command == "inject":
|
|
1380
|
-
inject(args.root, args.config, args.platform, args.project, args.force, args.dry_run)
|
|
1381
|
-
elif args.command == "resolve":
|
|
1382
|
-
print_resolve(args.config, args.platform, args.project)
|
|
1383
|
-
elif args.command == "engine-check":
|
|
1384
|
-
engine_check(args.root, args.config)
|
|
1385
|
-
elif args.command == "migrate":
|
|
1386
|
-
return migrate(args.source, args.target, args.dry_run)
|
|
1387
|
-
except ConfigError as exc:
|
|
1388
|
-
print(str(exc), file=sys.stderr)
|
|
1389
|
-
return 1
|
|
1390
|
-
return 0
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
if __name__ == "__main__":
|
|
1394
|
-
raise SystemExit(main(sys.argv[1:]))
|