@infly/libs 2.2.1 → 2.2.3
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/README.md +50 -12
- package/bin/cli.js +10 -0
- package/build/docker/compose-command.js +6 -8
- package/build/docker/config-loader.js +127 -0
- package/build/docker/deployment/deploy.sh +8 -1
- package/build/docker/deployment/release.sh +70 -5
- package/build/docker/deployment-bundle.js +3 -4
- package/build/docker/docker-build-push.js +6 -5
- package/build/docker/release-docker.js +2 -5
- package/build/docker/target-release.js +92 -21
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -131,7 +131,7 @@ infly-libs build:docker --local --health-check --health-timeout=60
|
|
|
131
131
|
infly-libs release:docker --local --health-check --health-timeout=60
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
-
`checks` 中的名称必须对应应用已有的 pnpm script;任一检查、覆盖率文件验证、Sonar Quality Gate 或镜像健康门禁失败,命令都会退出且不会推送镜像。`sonar` 默认为 `true`;设为 `false` 时由 CI 单独负责扫描和 Quality Gate。本地启用 Sonar 时必须通过当前进程环境或应用根目录下被 Git 忽略的 `.env.production.local` 提供 `SONAR_TOKEN`,并确保 `sonar-scanner` CLI 可执行;当前进程环境变量的优先级更高。`release:docker`
|
|
134
|
+
`checks` 中的名称必须对应应用已有的 pnpm script;任一检查、覆盖率文件验证、Sonar Quality Gate 或镜像健康门禁失败,命令都会退出且不会推送镜像。`sonar` 默认为 `true`;设为 `false` 时由 CI 单独负责扫描和 Quality Gate。本地启用 Sonar 时必须通过当前进程环境或应用根目录下被 Git 忽略的 `.env.production.local` 提供 `SONAR_TOKEN`,并确保 `sonar-scanner` CLI 可执行;当前进程环境变量的优先级更高。`release:docker` 会拒绝含未提交文件的应用工作树,固定使用完整 40 位应用 commit 作为镜像标签及 OCI revision/version;普通 `build:docker` 未显式传版本时同样使用完整 commit。应用差异保留在应用配置,通用编排由 `infly-libs` 维护。
|
|
135
135
|
|
|
136
136
|
受控紧急构建可使用 `--emergency` 跳过 `checks`、覆盖率文件校验和 Sonar,但必须提供 8~200 个字符且无控制字符的 `--emergency-reason`,并同时启用 `--standalone --commit-only --health-check`。紧急模式仍执行工作树干净检查、commit/revision 解析、镜像构建、健康检查和推送;缺少任一保护参数会在调用 Docker 前失败。
|
|
137
137
|
|
|
@@ -237,12 +237,12 @@ const components = await selectOptions("请选择构建范围", [
|
|
|
237
237
|
infly-libs docker:compose --target yhqy --bump patch
|
|
238
238
|
```
|
|
239
239
|
|
|
240
|
-
默认从当前目录 `package.json` 的 `infly.docker
|
|
240
|
+
默认从当前目录 `package.json` 的 `infly.docker` 读取目标;该对象可用 `config` 指向项目内 JSON、YAML、JS 配置文件,package 中的少量同名字段作为 override 合并。Compose 与配置路径均以 package 所在项目目录解析;省略 `--target` 时在 TTY 中交互选择。`--config` 外部配置和原有 `--project-dir` + `--file` 直传方式继续兼容。
|
|
241
241
|
|
|
242
242
|
参数约束:
|
|
243
243
|
|
|
244
244
|
- `--target`:选择 `infly.docker.targets` 或外部配置中的目标;非交互环境必须显式传入。
|
|
245
|
-
- `--config`:可选的外部 JS 配置文件,使用 `targets.<name
|
|
245
|
+
- `--config`:可选的外部 JSON、YAML 或 JS 配置文件,使用 `targets.<name>` 结构。
|
|
246
246
|
- `--project-dir` + `--file`:不使用 target 配置时的兼容直传方式,Compose 文件不能越出 `project-dir`。
|
|
247
247
|
- `--bump none|patch`:`none` 保持 Compose 中的镜像版本不变,`patch` 将补丁版本递增;两种模式都要求 Compose 中恰好有一个 `x.y.z` 镜像 tag。
|
|
248
248
|
- `--push`:显式推送;未传时只执行 `docker compose config` 和 `build`。
|
|
@@ -258,7 +258,37 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
|
|
|
258
258
|
|
|
259
259
|
维护归属:公共构建工具;以 `bin/cli.js`、`build/docker/target-release.js` 和 `deployment-bundle.js` 为实现契约。新增配置字段时同步此节及测试。
|
|
260
260
|
|
|
261
|
-
`infly-libs docker:release` 先单选 target,再多选该 target 的 components。构建在执行命令的机器进行。默认不推送;`--push` 构建、验证后先推送不可变
|
|
261
|
+
`infly-libs docker:release` 先单选 target,再多选该 target 的 components。构建在执行命令的机器进行。默认不推送;`--push` 构建、验证后先推送不可变 `<完整40位提交版本>`,再更新 `latest`;`--dry-run` 只解析配置,不联网、不运行 Git/Docker、不创建目录。
|
|
262
|
+
|
|
263
|
+
当 Docker 配置较大时,推荐在 `package.json` 只保留配置入口和真正需要被 Jenkins 直接读取的部署差异:
|
|
264
|
+
|
|
265
|
+
```json
|
|
266
|
+
{
|
|
267
|
+
"infly": {
|
|
268
|
+
"docker": {
|
|
269
|
+
"config": "deploy/docker-platforms.yaml",
|
|
270
|
+
"targets": {
|
|
271
|
+
"demo": {
|
|
272
|
+
"deployment": { "server": "example.com" }
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
外部 YAML 可以定义完整的 `targetPresets` 和 `targets`。组件还可通过 `compose.file`、`compose.service` 直接复用 Compose 中的 `image`、`build.context`、`dockerfile`、`target` 与 `build.args`,避免在 `infly.docker` 重复 Docker 编排:
|
|
281
|
+
|
|
282
|
+
```yaml
|
|
283
|
+
targets:
|
|
284
|
+
demo:
|
|
285
|
+
components:
|
|
286
|
+
frontend:
|
|
287
|
+
compose:
|
|
288
|
+
file: deploy/compose/docker-compose.frontend.demo.yaml
|
|
289
|
+
service: frontend
|
|
290
|
+
expectedRef: origin/master
|
|
291
|
+
```
|
|
262
292
|
|
|
263
293
|
```json
|
|
264
294
|
{
|
|
@@ -279,6 +309,10 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
|
|
|
279
309
|
"backend": {
|
|
280
310
|
"dockerfile": "Dockerfile",
|
|
281
311
|
"context": ".",
|
|
312
|
+
"source": {
|
|
313
|
+
"directory": ["../../services/api", "../api"],
|
|
314
|
+
"url": "https://example.com/api.git"
|
|
315
|
+
},
|
|
282
316
|
"imageEnv": "API_IMAGE",
|
|
283
317
|
"services": ["api", "worker"]
|
|
284
318
|
}
|
|
@@ -318,8 +352,6 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
|
|
|
318
352
|
"backend": {
|
|
319
353
|
"repository": "registry.example.com/demo/api",
|
|
320
354
|
"source": {
|
|
321
|
-
"directory": "../api",
|
|
322
|
-
"url": "https://example.com/api.git",
|
|
323
355
|
"branch": "release/demo"
|
|
324
356
|
}
|
|
325
357
|
}
|
|
@@ -342,10 +374,13 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
|
|
|
342
374
|
```
|
|
343
375
|
|
|
344
376
|
- `files`:从组件源码仓复制到独立临时上下文,仅发送指定产物;配置后 `dockerfile` 相对临时上下文。未配置时 `context`、`dockerfile` 相对组件源码仓。
|
|
377
|
+
- `config`:`infly.docker` 中的外部配置路径,支持 JSON、YAML、JS;外部配置为基础,package 中的同名对象递归覆盖。循环引用和未知格式会直接失败。
|
|
378
|
+
- `compose`:组件构建配置来源,必须指定 `file` 和 `service`。工具从 Compose 服务读取镜像仓库、上下文、Dockerfile、stage 与构建参数;组件显式字段仍可覆盖解析结果。
|
|
379
|
+
- `target` / `buildArgs`:分别映射到 `docker buildx build --target` 和 `--build-arg`;使用 `compose` 时通常无需重复填写。
|
|
345
380
|
- `requiredFiles`:构建前必须存在的源码仓相对路径,例如前端产物的 `index.html`;缺失时停止构建。
|
|
346
|
-
- `source
|
|
381
|
+
- `source`:可选独立源码仓;`directory` 支持单个路径或按优先级排列的候选路径数组,路径均从项目目录解析,采用第一个包含 `.git` 的目录。fetch 后使用指定分支的临时 detached worktree,不切换当前开发分支。交互终端找不到候选仓库时会列出已检查路径、展示路径示例并等待手动输入;取消或非交互环境仍明确说明未执行构建或推送,打印编号化的 clone、fetch 和重跑步骤,全部构建停止,CLI 返回 2。
|
|
347
382
|
- `targetPresets` 与 `targets.*.extends`:可选的具名公共目标配置。preset 可以继续 `extends` 另一个 preset;目标只继承显式指定的 preset,未声明 `extends` 的历史目标不受影响。同名普通对象递归合并;数组、字符串、数字、布尔值和 `null` 由下层整项替换,不按数组下标混合。未知 preset 或循环继承直接失败。本地构建、Compose 发布和部署包生成共用同一解析规则。
|
|
348
|
-
- `releaseScripts
|
|
383
|
+
- `releaseScripts`:可选的组件重跑脚本覆盖。默认从项目 scripts 自动识别严格匹配 `release:<组件>:docker` 的脚本,例如 `release:backend:docker`;源码仓缺失时提示 `pnpm run <脚本> -- --platform ...`。只有脚本名称不遵循约定时才需要显式配置;无匹配时提示通用 `pnpm exec infly-libs docker:release` 命令。
|
|
349
384
|
- 无 `source` 时构建当前项目,要求干净工作树且 HEAD 等于 `expectedRef`。有 `source` 时校验临时工作树对应的 origin 分支。
|
|
350
385
|
- `check`:可选镜像内校验,使用 `entrypoint`、`args` 数组及 `addHosts` 数组;失败不推送。配置命令具有代码执行权限,应与源码一样评审,不能来自不可信输入。
|
|
351
386
|
- `deployment`:仅用于部署包生成;`ready=false` 会阻止生成。可设置 `lockName`,默认 `.infly-release.lock`。服务归属和 imageEnv 必须唯一。
|
|
@@ -356,15 +391,18 @@ Windows 本地构建连接 `dockerDesktopLinuxEngine` 失败时,入口尝试
|
|
|
356
391
|
```bash
|
|
357
392
|
infly-libs docker:release --target demo --components frontend,backend --push
|
|
358
393
|
infly-libs docker:release --platform demo --components backend --backend-dir ../api --no-push
|
|
359
|
-
infly-libs docker:release --project-dir ./deployment --config docker.
|
|
394
|
+
infly-libs docker:release --project-dir ./deployment --config docker.yaml --target demo --components frontend --dry-run
|
|
395
|
+
infly-libs docker:config --project-dir ./deployment
|
|
360
396
|
infly-libs docker:bundle --target demo --output .infly-deploy-123
|
|
361
397
|
infly-libs docker:bundle --target demo --dry-run
|
|
362
398
|
```
|
|
363
399
|
|
|
364
|
-
`--platform` 是 `--target` 的兼容别名;`--config` 读取 JSON 文件,其顶层直接为 docker
|
|
400
|
+
`--platform` 是 `--target` 的兼容别名;`--config` 读取 JSON、YAML 或 JS 文件,其顶层直接为 docker 配置。`docker:config` 输出合并和继承后的单行 JSON,便于不安装 YAML 插件的 Jenkins 使用。CLI 参数优先于项目配置;`--backend-dir` 仅覆盖名为 backend 的组件源码目录,并覆盖整个 `source.directory` 候选数组。
|
|
365
401
|
|
|
366
|
-
|
|
402
|
+
构建成功后逐组件输出完整提交版本、`组件=仓库:<完整40位提交版本>` 和 `组件_latest=仓库:latest` 机器行;每个组件的一次构建同时生成不可变提交标签与 `latest`,启用推送时先推送不可变标签,再更新 `latest`。全部构建结束后打印 `✅ 完成` 汇总块,明确区分“不可变提交版本”和“最新推送镜像(所选平台 registry 的 latest)”。可选 `--cicd-url`(支持等号和空格两种传参形式)只在目标配置 `deployment.ready=true` 时于汇总块尾输出蓝色发布系统链接;未开放部署的平台只提示镜像已推送,不展示可能造成误解的部署入口。“发布系统:”与中文 URL 分为两行,URL 独占一行,OSC 8 显式超链接使用百分号编码后的标准 URL 作为点击目标,确保支持该协议的终端可通过 Ctrl + 鼠标左键完整打开。不传时保持原输出。链接必须是合法 HTTP/HTTPS URL,不含用户名或密码。单组件推送成功且 `--cicd-url` 指向以 `/build` 结尾的 Jenkins 构建地址时,链接会预填“平台”与“镜像版本”参数(`平台 / 完整40位提交版本 / 北京时间`),打开构建页默认即为本次推送镜像;多组件推送或其他地址保持原链接。
|
|
367
403
|
|
|
368
404
|
`docker:bundle` 只生成本地脚本包,不自动部署;输出须是项目内尚不存在的独立子目录。包内包含 config.sh、Compose 覆盖文件和公共 shell 脚本。Jenkins 可直接传入部署项目 `package.json` 声明的精确版本或 caret 范围获取公共包;`docker:bundle` 会在执行时输出实际解析到的 `@infly/libs` 精确版本,供 Jenkins 日志追溯。镜像不需要 Infly 专用版本标签,因此独立项目使用普通 `docker build` 生成的镜像仍可部署。Jenkins 使用既有凭据,调用 `deploy.sh component=repository:commit` 传输并执行。包内仍保留 `promote-image.sh` 供既有 qc 晋升流程兼容使用;低频定制平台直接在本地推送不可变提交标签与 `latest`,Jenkins 不再调用晋升脚本。运行部署脚本会操作服务器,必须由开发者手动触发既定任务。
|
|
369
405
|
|
|
370
|
-
|
|
406
|
+
`docker:release` 不是强制构建入口。独立源码仓可以直接使用 Dockerfile 或 Compose 构建,但若镜像要进入这里生成的部署流程,必须自行保证仓库名、不可变完整 40 位提交标签以及 `org.opencontainers.image.revision`、`org.opencontainers.image.version`、`com.infly.platform` 标签与目标配置一致;公共发布入口只是自动化这些校验和映射。部署侧仅为既有镜像保留旧 12 位标签兼容,新构建不再生成 12 位标签。
|
|
407
|
+
|
|
408
|
+
远端发布持锁后读取全部组件镜像基线,保存 .release-history;配置 `runtimeEnv` 时先从服务器总环境文件按白名单原子生成应用专用文件,再仅更新传入组件的服务(up -d --no-deps)。首次接入可由发布入口显式传入 `--initialize-baseline`:仅在 `deploy.env` 不存在时,从配置声明的运行中服务读取唯一且仓库匹配的 RepoDigest,保存权限受限的 `.onboarding-backup` 接入证据并原子创建基线;已有基线时拒绝覆盖,未显式初始化时仍要求基线预先存在。失败恢复镜像环境文件、应用专用环境文件及选中服务;回滚验证失败明确报错。不创建总环境文件,不创建/修改数据库,不更新未配置的基础设施。服务器不需要 npm/Node,仍需 Bash、Docker Compose 和 curl。
|
package/bin/cli.js
CHANGED
|
@@ -103,6 +103,16 @@ function parseProjectArgs(argv) {
|
|
|
103
103
|
async function main(argv = process.argv.slice(2)) {
|
|
104
104
|
const command = argv[0];
|
|
105
105
|
const commandMap = {
|
|
106
|
+
"docker:config": () => {
|
|
107
|
+
const { parseReleaseArgs } = require("../build/docker/target-release");
|
|
108
|
+
const options = parseReleaseArgs(argv.slice(1));
|
|
109
|
+
const config = require("../build/docker/config-loader").loadDockerConfig({
|
|
110
|
+
projectDir: options.projectDir,
|
|
111
|
+
configPath: options.config,
|
|
112
|
+
});
|
|
113
|
+
console.log(JSON.stringify(config));
|
|
114
|
+
return config;
|
|
115
|
+
},
|
|
106
116
|
"docker:bundle": () => {
|
|
107
117
|
const { parseReleaseArgs } = require("../build/docker/target-release");
|
|
108
118
|
const result = require("../build/docker/deployment-bundle").createDeploymentBundle(parseReleaseArgs(argv.slice(1)));
|
|
@@ -6,13 +6,12 @@ const {
|
|
|
6
6
|
selectOption: defaultSelectOption,
|
|
7
7
|
} = require("../../cli/select-option");
|
|
8
8
|
const { composeRelease: defaultComposeRelease } = require("./compose-release");
|
|
9
|
-
const {
|
|
9
|
+
const { loadDockerConfig } = require("./config-loader");
|
|
10
10
|
|
|
11
11
|
function loadTargetConfig(configPath) {
|
|
12
12
|
const resolvedPath = path.resolve(configPath);
|
|
13
|
-
delete require.cache[require.resolve(resolvedPath)];
|
|
14
13
|
return {
|
|
15
|
-
config:
|
|
14
|
+
config: loadDockerConfig({ projectDir: path.dirname(resolvedPath), configPath: path.basename(resolvedPath) }),
|
|
16
15
|
configDir: path.dirname(resolvedPath),
|
|
17
16
|
};
|
|
18
17
|
}
|
|
@@ -22,10 +21,8 @@ function loadPackageTargetConfig(cwd = process.cwd()) {
|
|
|
22
21
|
if (!fs.existsSync(packagePath)) {
|
|
23
22
|
throw new Error(`Package config not found: ${packagePath}`);
|
|
24
23
|
}
|
|
25
|
-
delete require.cache[require.resolve(packagePath)];
|
|
26
|
-
const packageJson = require(packagePath);
|
|
27
24
|
return {
|
|
28
|
-
config:
|
|
25
|
+
config: loadDockerConfig({ projectDir: path.dirname(packagePath) }),
|
|
29
26
|
configDir: path.dirname(packagePath),
|
|
30
27
|
};
|
|
31
28
|
}
|
|
@@ -40,9 +37,10 @@ async function runComposeCommand(options = {}, dependencies = {}) {
|
|
|
40
37
|
const loaded = options.config
|
|
41
38
|
? loadTargetConfig(options.config)
|
|
42
39
|
: options.configObject
|
|
43
|
-
? { config:
|
|
40
|
+
? { config: loadDockerConfig({ configObject: options.configObject,
|
|
41
|
+
configDir: options.configDir || process.cwd() }), configDir: options.configDir || process.cwd() }
|
|
44
42
|
: loadPackageTargetConfig(options.cwd || process.cwd());
|
|
45
|
-
const config =
|
|
43
|
+
const config = loaded.config;
|
|
46
44
|
const targets = config?.targets;
|
|
47
45
|
if (!targets || Object.keys(targets).length === 0) {
|
|
48
46
|
throw new Error("Docker target config must define at least one target.");
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const path = require("node:path");
|
|
3
|
+
const YAML = require("yaml");
|
|
4
|
+
const { mergeTargetConfig, resolveDockerConfig } = require("./target-config");
|
|
5
|
+
|
|
6
|
+
function readConfigFile(file) {
|
|
7
|
+
const resolved = path.resolve(file);
|
|
8
|
+
const extension = path.extname(resolved).toLowerCase();
|
|
9
|
+
if (extension === ".js" || extension === ".cjs") {
|
|
10
|
+
delete require.cache[require.resolve(resolved)];
|
|
11
|
+
return require(resolved);
|
|
12
|
+
}
|
|
13
|
+
const content = fs.readFileSync(resolved, "utf8");
|
|
14
|
+
if (extension === ".yaml" || extension === ".yml") return YAML.parse(content);
|
|
15
|
+
if (extension === ".json" || path.basename(resolved) === "package.json") return JSON.parse(content);
|
|
16
|
+
throw new Error(`不支持的 Docker 配置格式: ${resolved}`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function expandConfigReference(config, configDir, chain = []) {
|
|
20
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) return config;
|
|
21
|
+
if (config.config == null) return config;
|
|
22
|
+
if (typeof config.config !== "string" || !config.config.trim()) {
|
|
23
|
+
throw new Error("infly.docker.config 必须是非空 JSON/YAML 配置路径");
|
|
24
|
+
}
|
|
25
|
+
const file = path.resolve(configDir, config.config);
|
|
26
|
+
if (chain.includes(file)) throw new Error(`Docker 配置循环引用: ${[...chain, file].join(" -> ")}`);
|
|
27
|
+
const external = expandConfigReference(readConfigFile(file), path.dirname(file), [...chain, file]);
|
|
28
|
+
const inline = { ...config };
|
|
29
|
+
delete inline.config;
|
|
30
|
+
return mergeTargetConfig(external, inline);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function imageRepository(image, name) {
|
|
34
|
+
if (typeof image !== "string" || !image.trim()) throw new Error(`${name} Compose service 缺少 image`);
|
|
35
|
+
const value = image.trim();
|
|
36
|
+
const slash = value.lastIndexOf("/");
|
|
37
|
+
const colon = value.lastIndexOf(":");
|
|
38
|
+
return colon > slash ? value.slice(0, colon) : value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function relativeToProject(projectDir, value, name) {
|
|
42
|
+
const relative = path.relative(projectDir, value);
|
|
43
|
+
if (!relative || relative === ".") return ".";
|
|
44
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
45
|
+
throw new Error(`${name} 必须位于项目目录内`);
|
|
46
|
+
}
|
|
47
|
+
return relative.split(path.sep).join("/");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function composeComponent(projectDir, reference, name) {
|
|
51
|
+
if (!reference || typeof reference.file !== "string" || typeof reference.service !== "string") {
|
|
52
|
+
throw new Error(`${name}.compose 必须配置 file 和 service`);
|
|
53
|
+
}
|
|
54
|
+
const file = path.resolve(projectDir, reference.file);
|
|
55
|
+
relativeToProject(projectDir, file, `${name} compose.file`);
|
|
56
|
+
const compose = readConfigFile(file);
|
|
57
|
+
const service = compose?.services?.[reference.service];
|
|
58
|
+
if (!service) throw new Error(`${name} Compose 中不存在服务: ${reference.service}`);
|
|
59
|
+
const build = service.build;
|
|
60
|
+
if (!build || typeof build !== "object" || Array.isArray(build) || typeof build.context !== "string") {
|
|
61
|
+
throw new Error(`${name} Compose service 必须配置对象形式的 build.context`);
|
|
62
|
+
}
|
|
63
|
+
const context = path.resolve(path.dirname(file), build.context);
|
|
64
|
+
const dockerfile = path.resolve(context, build.dockerfile || "Dockerfile");
|
|
65
|
+
const buildArgs = {};
|
|
66
|
+
for (const [key, raw] of Object.entries(build.args || {})) {
|
|
67
|
+
const match = typeof raw === "string" ? raw.match(/^[$][{][A-Za-z_][A-Za-z0-9_]*:-([^}]*)[}]$/) : null;
|
|
68
|
+
buildArgs[key] = match ? match[1] : raw;
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
repository: imageRepository(service.image, name),
|
|
72
|
+
context: relativeToProject(projectDir, context, `${name} build.context`),
|
|
73
|
+
dockerfile: relativeToProject(projectDir, dockerfile, `${name} build.dockerfile`),
|
|
74
|
+
...(build.target ? { target: build.target } : {}),
|
|
75
|
+
...(Object.keys(buildArgs).length ? { buildArgs } : {}),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function hydrateComposeComponents(config, projectDir) {
|
|
80
|
+
for (const [targetName, target] of Object.entries(config?.targets || {})) {
|
|
81
|
+
for (const [componentName, component] of Object.entries(target.components || {})) {
|
|
82
|
+
if (!component.compose) continue;
|
|
83
|
+
target.components[componentName] = mergeTargetConfig(
|
|
84
|
+
composeComponent(projectDir, component.compose, `${targetName}.${componentName}`),
|
|
85
|
+
component,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return config;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function inferReleaseScripts(scripts) {
|
|
93
|
+
const result = {};
|
|
94
|
+
for (const name of Object.keys(scripts || {})) {
|
|
95
|
+
const match = name.match(/^release:([a-z][a-z0-9_-]*):docker$/);
|
|
96
|
+
if (match) result[match[1]] = name;
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function loadDockerConfig(options = {}) {
|
|
102
|
+
const projectDir = path.resolve(options.projectDir || process.cwd());
|
|
103
|
+
let rawConfig;
|
|
104
|
+
let configDir = projectDir;
|
|
105
|
+
let manifest;
|
|
106
|
+
if (options.configObject) {
|
|
107
|
+
rawConfig = options.configObject;
|
|
108
|
+
configDir = path.resolve(options.configDir || projectDir);
|
|
109
|
+
} else if (options.configPath) {
|
|
110
|
+
const file = path.resolve(projectDir, options.configPath);
|
|
111
|
+
rawConfig = readConfigFile(file);
|
|
112
|
+
configDir = path.dirname(file);
|
|
113
|
+
const manifestFile = path.join(projectDir, "package.json");
|
|
114
|
+
if (fs.existsSync(manifestFile)) manifest = readConfigFile(manifestFile);
|
|
115
|
+
} else {
|
|
116
|
+
manifest = readConfigFile(path.join(projectDir, "package.json"));
|
|
117
|
+
rawConfig = manifest.infly?.docker;
|
|
118
|
+
}
|
|
119
|
+
const expanded = expandConfigReference(rawConfig, configDir);
|
|
120
|
+
const inferred = inferReleaseScripts(manifest?.scripts);
|
|
121
|
+
const withScripts = Object.keys(inferred).length
|
|
122
|
+
? mergeTargetConfig({ releaseScripts: inferred }, expanded)
|
|
123
|
+
: expanded;
|
|
124
|
+
return hydrateComposeComponents(resolveDockerConfig(withScripts), projectDir);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = { composeComponent, expandConfigReference, inferReleaseScripts, loadDockerConfig, readConfigFile };
|
|
@@ -5,6 +5,11 @@ source "$bundle_dir/config.sh"
|
|
|
5
5
|
: "${CCR_USERNAME:?未注入镜像仓库用户名}"
|
|
6
6
|
: "${CCR_PASSWORD:?未注入镜像仓库密码}"
|
|
7
7
|
: "${SSH_KNOWN_HOSTS:?未注入已核验的 SSH host keys}"
|
|
8
|
+
initialize_baseline=false
|
|
9
|
+
if [[ "${1:-}" == "--initialize-baseline" ]]; then
|
|
10
|
+
initialize_baseline=true
|
|
11
|
+
shift
|
|
12
|
+
fi
|
|
8
13
|
[[ $# -gt 0 ]] || { echo '需要组件=正式镜像参数' >&2; exit 2; }
|
|
9
14
|
local_tmp=$(mktemp -d)
|
|
10
15
|
remote_tmp=""
|
|
@@ -25,6 +30,8 @@ umask 077
|
|
|
25
30
|
printf '{"auths":{"%s":{"auth":"%s"}}}\n' "$registry" "$auth_value" > "$local_tmp/config.json"
|
|
26
31
|
scp "${ssh_options[@]}" "$bundle_dir/release.sh" "$bundle_dir/health-check.sh" "$bundle_dir/config.sh" \
|
|
27
32
|
"$bundle_dir/docker-compose.release.yml" "$local_tmp/config.json" "$ssh_target:$remote_tmp/"
|
|
28
|
-
remote_command=(sudo env "DOCKER_CONFIG=$remote_tmp" bash "$remote_tmp/release.sh"
|
|
33
|
+
remote_command=(sudo env "DOCKER_CONFIG=$remote_tmp" bash "$remote_tmp/release.sh")
|
|
34
|
+
if [[ "$initialize_baseline" == true ]]; then remote_command+=(--initialize-baseline); fi
|
|
35
|
+
remote_command+=("$@")
|
|
29
36
|
printf -v remote_quoted '%q ' "${remote_command[@]}"
|
|
30
37
|
ssh "${ssh_options[@]}" "$ssh_target" "$remote_quoted"
|
|
@@ -2,14 +2,20 @@
|
|
|
2
2
|
set -euo pipefail
|
|
3
3
|
bundle_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
|
|
4
4
|
source "$bundle_dir/config.sh"
|
|
5
|
+
initialize_baseline=false
|
|
6
|
+
if [[ "${1:-}" == "--initialize-baseline" ]]; then
|
|
7
|
+
initialize_baseline=true
|
|
8
|
+
shift
|
|
9
|
+
fi
|
|
5
10
|
[[ $# -gt 0 ]] || { echo '需要组件=正式镜像参数' >&2; exit 2; }
|
|
6
11
|
cd "$project_dir"
|
|
7
|
-
for file in "$compose_file" "$secret_env_file" "$
|
|
12
|
+
for file in "$compose_file" "$secret_env_file" "$bundle_dir/docker-compose.release.yml"; do
|
|
8
13
|
[[ -f "$file" ]] || { echo "部署缺少文件: $file" >&2; exit 1; }
|
|
9
14
|
done
|
|
10
15
|
# 先持有目录锁再读基线,避免前后端两个任务同时发布时使用过期基线。
|
|
11
16
|
mkdir "$lock_dir" 2>/dev/null || { echo "已有发布任务持有锁: $project_dir/$lock_dir" >&2; exit 1; }
|
|
12
17
|
next_env=""
|
|
18
|
+
baseline_env_tmp=""
|
|
13
19
|
runtime_env_backup=""
|
|
14
20
|
runtime_env_changed=false
|
|
15
21
|
runtime_env_had_previous=false
|
|
@@ -31,11 +37,65 @@ cleanup() {
|
|
|
31
37
|
local status=$?
|
|
32
38
|
if [[ "$release_complete" != true ]]; then restore_runtime_env || true; fi
|
|
33
39
|
[[ -z "$next_env" ]] || rm -f -- "$next_env"
|
|
40
|
+
[[ -z "$baseline_env_tmp" ]] || rm -f -- "$baseline_env_tmp"
|
|
34
41
|
[[ -z "$runtime_env_backup" ]] || rm -f -- "$runtime_env_backup"
|
|
35
42
|
rmdir "$lock_dir" 2>/dev/null || true
|
|
36
43
|
return "$status"
|
|
37
44
|
}
|
|
38
45
|
trap cleanup EXIT
|
|
46
|
+
initialize_release_baseline() {
|
|
47
|
+
[[ "$initialize_baseline" == true ]] || {
|
|
48
|
+
[[ -f "$release_env_file" ]] || { echo "部署缺少文件: $release_env_file;首次接入请显式选择初始化部署基线" >&2; return 1; }
|
|
49
|
+
return 0
|
|
50
|
+
}
|
|
51
|
+
[[ ! -e "$release_env_file" ]] || { echo "部署基线已存在,拒绝首次初始化覆盖: $project_dir/$release_env_file" >&2; return 1; }
|
|
52
|
+
|
|
53
|
+
local backup_root backup_dir i service container_id image_id repository
|
|
54
|
+
local -a group digests
|
|
55
|
+
backup_root="$project_dir/.onboarding-backup"
|
|
56
|
+
mkdir -p -- "$backup_root"
|
|
57
|
+
chmod 700 -- "$backup_root"
|
|
58
|
+
backup_dir=$(mktemp -d "$backup_root/${target}-$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX")
|
|
59
|
+
chmod 700 -- "$backup_dir"
|
|
60
|
+
cp -- "$compose_file" "$backup_dir/compose.yml"
|
|
61
|
+
cp -- "$secret_env_file" "$backup_dir/secret.env"
|
|
62
|
+
chmod 600 -- "$backup_dir/compose.yml" "$backup_dir/secret.env"
|
|
63
|
+
|
|
64
|
+
local -a base_compose=(docker compose --env-file "$secret_env_file" -f "$compose_file")
|
|
65
|
+
"${base_compose[@]}" ps > "$backup_dir/compose-ps.txt"
|
|
66
|
+
baseline_env_tmp=$(mktemp "${release_env_file}.bootstrap.XXXXXX")
|
|
67
|
+
for i in "${!component_names[@]}"; do
|
|
68
|
+
read -r -a group <<< "${service_groups[$i]}"
|
|
69
|
+
image_id=""
|
|
70
|
+
for service in "${group[@]}"; do
|
|
71
|
+
container_id=$("${base_compose[@]}" ps -q "$service")
|
|
72
|
+
[[ -n "$container_id" ]] || { echo "首次初始化找不到服务容器: $service" >&2; return 1; }
|
|
73
|
+
[[ "$(docker inspect --format '{{.State.Running}}' "$container_id")" == true ]] || {
|
|
74
|
+
echo "首次初始化要求服务正在运行: $service" >&2; return 1;
|
|
75
|
+
}
|
|
76
|
+
printf '%s=%s\n' "$service" "$container_id" >> "$backup_dir/container-ids.txt"
|
|
77
|
+
if [[ -z "$image_id" ]]; then
|
|
78
|
+
image_id=$(docker inspect --format '{{.Image}}' "$container_id")
|
|
79
|
+
elif [[ "$image_id" != "$(docker inspect --format '{{.Image}}' "$container_id")" ]]; then
|
|
80
|
+
echo "同一组件的服务镜像不一致,拒绝初始化: ${component_names[$i]}" >&2
|
|
81
|
+
return 1
|
|
82
|
+
fi
|
|
83
|
+
done
|
|
84
|
+
repository=${repositories[$i]}
|
|
85
|
+
mapfile -t digests < <(docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$image_id" | awk -v prefix="$repository@sha256:" 'index($0, prefix) == 1')
|
|
86
|
+
[[ "${#digests[@]}" == 1 && "${digests[0]}" =~ ^${repository//./\\.}@sha256:[0-9a-f]{64}$ ]] || {
|
|
87
|
+
echo "当前镜像缺少唯一且匹配配置仓库的 RepoDigest: ${component_names[$i]} ($repository)" >&2
|
|
88
|
+
return 1
|
|
89
|
+
}
|
|
90
|
+
printf '%s=%s\n' "${image_keys[$i]}" "${digests[0]}" >> "$baseline_env_tmp"
|
|
91
|
+
done
|
|
92
|
+
chmod 600 -- "$baseline_env_tmp" "$backup_dir/compose-ps.txt" "$backup_dir/container-ids.txt"
|
|
93
|
+
mv -- "$baseline_env_tmp" "$release_env_file"
|
|
94
|
+
baseline_env_tmp=""
|
|
95
|
+
chmod 600 -- "$release_env_file"
|
|
96
|
+
echo "首次部署基线已初始化;接入备份: $backup_dir"
|
|
97
|
+
}
|
|
98
|
+
initialize_release_baseline
|
|
39
99
|
current_images=()
|
|
40
100
|
next_images=()
|
|
41
101
|
selected_indexes=()
|
|
@@ -46,7 +106,7 @@ for i in "${!component_names[@]}"; do
|
|
|
46
106
|
[[ "$(grep -c "^${key}=" "$release_env_file" || true)" == 1 ]] || { echo "基线必须包含唯一 $key" >&2; exit 1; }
|
|
47
107
|
image=$(grep "^${key}=" "$release_env_file"); image=${image#*=}
|
|
48
108
|
suffix=${image#"${repositories[$i]}"}
|
|
49
|
-
[[ "$image" != "$suffix" && ( "$suffix" =~ ^:[0-9a-f]{12}$ || "$suffix" =~ ^@sha256:[0-9a-f]{64}$ ) ]] || {
|
|
109
|
+
[[ "$image" != "$suffix" && ( "$suffix" =~ ^:([0-9a-f]{12}|[0-9a-f]{40})$ || "$suffix" =~ ^@sha256:[0-9a-f]{64}$ ) ]] || {
|
|
50
110
|
echo "当前基线不是配置仓库的不可变镜像: $key" >&2; exit 1;
|
|
51
111
|
}
|
|
52
112
|
current_images+=("$image"); next_images+=("$image")
|
|
@@ -59,7 +119,7 @@ for pair in "$@"; do
|
|
|
59
119
|
found=true
|
|
60
120
|
for selected in "${selected_indexes[@]}"; do [[ "$selected" != "$i" ]] || { echo '组件重复' >&2; exit 2; }; done
|
|
61
121
|
suffix=${image#"${repositories[$i]}:"}
|
|
62
|
-
[[ "$suffix" != "$image" && "$suffix" =~ ^[0-9a-f]{12}$ ]] || { echo "只接受本组件正式 commit
|
|
122
|
+
[[ "$suffix" != "$image" && "$suffix" =~ ^([0-9a-f]{12}|[0-9a-f]{40})$ ]] || { echo "只接受本组件正式 commit 镜像(40 位;兼容旧 12 位): $name" >&2; exit 1; }
|
|
63
123
|
next_images[$i]=$image
|
|
64
124
|
selected_indexes+=("$i")
|
|
65
125
|
selected_components+=("$name")
|
|
@@ -128,9 +188,14 @@ compose=(docker compose --env-file "$secret_env_file" --env-file "$next_env" -f
|
|
|
128
188
|
"${compose[@]}" config --quiet
|
|
129
189
|
"${compose[@]}" pull "${selected_services[@]}"
|
|
130
190
|
for i in "${selected_indexes[@]}"; do
|
|
131
|
-
image=${next_images[$i]};
|
|
191
|
+
image=${next_images[$i]}; tag=${image##*:}
|
|
132
192
|
full=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$image")
|
|
133
|
-
[[ "$full" =~ ^[0-9a-f]{40}$
|
|
193
|
+
[[ "$full" =~ ^[0-9a-f]{40}$ ]] || { echo "镜像 revision 校验失败: $image" >&2; exit 1; }
|
|
194
|
+
if [[ ${#tag} -eq 40 ]]; then
|
|
195
|
+
[[ "$full" == "$tag" ]] || { echo "镜像 revision 与 40 位标签不一致: $image" >&2; exit 1; }
|
|
196
|
+
else
|
|
197
|
+
[[ "${full:0:12}" == "$tag" ]] || { echo "旧 12 位镜像 revision 前缀不一致: $image" >&2; exit 1; }
|
|
198
|
+
fi
|
|
134
199
|
done
|
|
135
200
|
mv -f -- "$next_env" "$release_env_file"
|
|
136
201
|
next_env=""
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const fs = require("node:fs");
|
|
2
2
|
const path = require("node:path");
|
|
3
|
+
const { loadDockerConfig } = require("./config-loader");
|
|
3
4
|
const { resolveDockerConfig } = require("./target-config");
|
|
4
5
|
|
|
5
6
|
const quote = (value) => "'" + String(value).replaceAll("'", "'\\''") + "'";
|
|
@@ -125,10 +126,8 @@ function renderDeploymentConfig(config, target) {
|
|
|
125
126
|
|
|
126
127
|
function createDeploymentBundle(options = {}) {
|
|
127
128
|
const projectDir = path.resolve(options.projectDir || process.cwd());
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
: JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).infly?.docker);
|
|
131
|
-
const config = resolveDockerConfig(rawConfig);
|
|
129
|
+
const config = loadDockerConfig({ projectDir, configPath: options.config,
|
|
130
|
+
configObject: options.configObject, configDir: options.configDir });
|
|
132
131
|
const rendered = renderDeploymentConfig(config, options.target);
|
|
133
132
|
if (options.dryRun) return { target: options.target, config: rendered };
|
|
134
133
|
const output = path.resolve(projectDir, options.output || ".infly-deploy");
|
|
@@ -56,9 +56,9 @@ function formatCicdLink(value, deployParams) {
|
|
|
56
56
|
if (deployParams !== undefined) {
|
|
57
57
|
const { platform, platformLabel, tag, date } = deployParams;
|
|
58
58
|
if (typeof platform !== "string" || !/^[a-z0-9]+$/.test(platform)
|
|
59
|
-
|| typeof tag !== "string" || !/^[0-9a-f]{
|
|
59
|
+
|| typeof tag !== "string" || !/^[0-9a-f]{40}$/.test(tag)
|
|
60
60
|
|| typeof date !== "string" || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(date)) {
|
|
61
|
-
throw new Error("发布系统深链参数必须是合法平台、
|
|
61
|
+
throw new Error("发布系统深链参数必须是合法平台、40 位提交版本和 yyyy-MM-dd HH:mm 时间");
|
|
62
62
|
}
|
|
63
63
|
if (platformLabel !== undefined && (typeof platformLabel !== "string" || !platformLabel.trim()
|
|
64
64
|
|| /[\u0000-\u001f\u007f]/.test(platformLabel))) {
|
|
@@ -300,14 +300,15 @@ async function dockerBuildPush(options = {}) {
|
|
|
300
300
|
const imageName = pkg.name.replace(/^@[^/]+\//, "");
|
|
301
301
|
|
|
302
302
|
// 3. 获取版本号(monorepo 模式取 superproject 的 commit)
|
|
303
|
-
const commitHash = version || execSync("git rev-parse
|
|
303
|
+
const commitHash = version || execSync("git rev-parse HEAD", {
|
|
304
304
|
cwd: contextRoot, encoding: "utf-8",
|
|
305
305
|
}).trim();
|
|
306
306
|
const fullCommit = revision || execSync("git rev-parse HEAD", {
|
|
307
307
|
cwd: contextRoot, encoding: "utf-8",
|
|
308
308
|
}).trim();
|
|
309
|
-
if (!/^[0-9a-f]{
|
|
310
|
-
|
|
309
|
+
if (!/^[0-9a-f]{40}$/i.test(commitHash) || !/^[0-9a-f]{40}$/i.test(fullCommit)
|
|
310
|
+
|| commitHash.toLowerCase() !== fullCommit.toLowerCase()) {
|
|
311
|
+
throw new Error("Docker 镜像版本和 revision 必须是同一个完整 40 位 Git commit hash");
|
|
311
312
|
}
|
|
312
313
|
|
|
313
314
|
// 4. 镜像标签
|
|
@@ -141,11 +141,8 @@ function resolveProjectVersion(projectRoot) {
|
|
|
141
141
|
cwd: projectRoot,
|
|
142
142
|
encoding: "utf-8",
|
|
143
143
|
}).trim();
|
|
144
|
-
const commitHash =
|
|
145
|
-
|
|
146
|
-
encoding: "utf-8",
|
|
147
|
-
}).trim();
|
|
148
|
-
if (!/^[0-9a-f]{7,40}$/i.test(fullCommit) || !/^[0-9a-f]{7,40}$/i.test(commitHash)) {
|
|
144
|
+
const commitHash = fullCommit;
|
|
145
|
+
if (!/^[0-9a-f]{40}$/i.test(fullCommit)) {
|
|
149
146
|
throw new Error("无法从当前项目解析合法的 Git commit hash");
|
|
150
147
|
}
|
|
151
148
|
return { commitHash: commitHash.toLowerCase(), fullCommit: fullCommit.toLowerCase() };
|
|
@@ -2,10 +2,10 @@ const fs = require("node:fs");
|
|
|
2
2
|
const os = require("node:os");
|
|
3
3
|
const path = require("node:path");
|
|
4
4
|
const { execFileSync } = require("node:child_process");
|
|
5
|
-
const { EXIT_SELECTION, selectOption, selectOptions } = require("../../cli/select-option");
|
|
5
|
+
const { EXIT_SELECTION, inputText, selectOption, selectOptions } = require("../../cli/select-option");
|
|
6
6
|
const { composeRelease } = require("./compose-release");
|
|
7
7
|
const { formatCicdLink } = require("./docker-build-push");
|
|
8
|
-
const {
|
|
8
|
+
const { loadDockerConfig } = require("./config-loader");
|
|
9
9
|
|
|
10
10
|
// Jenkins 构建页“镜像版本”与 Webhook 通知均按北京时间展示。
|
|
11
11
|
function beijingDateTime(now = new Date()) {
|
|
@@ -87,17 +87,48 @@ function inside(root, relative) {
|
|
|
87
87
|
return result;
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
function normalizeSourceDirectories(value, name) {
|
|
91
|
+
const directories = Array.isArray(value) ? value : [value];
|
|
92
|
+
if (!directories.length || directories.some((item) => typeof item !== "string" || !item.trim())) {
|
|
93
|
+
throw new Error(`${name} source.directory 必须是非空路径字符串或非空路径数组`);
|
|
94
|
+
}
|
|
95
|
+
return [...new Set(directories.map((item) => item.trim()))];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function resolveSourceDirectories(projectDir, value, name) {
|
|
99
|
+
return normalizeSourceDirectories(value, name).map((directory) => path.resolve(projectDir, directory));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function trimPathInput(value) {
|
|
103
|
+
const trimmed = String(value || "").trim();
|
|
104
|
+
return trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"'))
|
|
105
|
+
|| (trimmed.startsWith("'") && trimmed.endsWith("'")))
|
|
106
|
+
? trimmed.slice(1, -1).trim()
|
|
107
|
+
: trimmed;
|
|
108
|
+
}
|
|
109
|
+
|
|
90
110
|
function validateComponent(component, name) {
|
|
91
111
|
if (!component || !/^[a-z0-9][a-z0-9._:/-]*$/.test(component.repository || "") || component.repository.includes("@")) {
|
|
92
112
|
throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
|
|
93
113
|
}
|
|
94
114
|
if (component.repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
|
|
95
115
|
if (!component.expectedRef && !component.source?.branch) throw new Error(`${name} 必须配置 expectedRef 或 source.branch`);
|
|
96
|
-
if (component.source
|
|
97
|
-
|
|
116
|
+
if (component.source) {
|
|
117
|
+
normalizeSourceDirectories(component.source.directory, name);
|
|
118
|
+
if (!component.source.branch || component.source.branch.startsWith("-")) {
|
|
119
|
+
throw new Error(`${name} source 必须配置合法 branch`);
|
|
120
|
+
}
|
|
98
121
|
}
|
|
99
122
|
inside("/config", component.dockerfile || "Dockerfile");
|
|
100
123
|
inside("/config", component.context || ".");
|
|
124
|
+
if (component.target != null && (typeof component.target !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(component.target))) {
|
|
125
|
+
throw new Error(`${name} target 必须是合法 Docker stage`);
|
|
126
|
+
}
|
|
127
|
+
if (component.buildArgs != null && (!component.buildArgs || typeof component.buildArgs !== "object"
|
|
128
|
+
|| Array.isArray(component.buildArgs) || Object.entries(component.buildArgs).some(([key, value]) =>
|
|
129
|
+
!/^[A-Z_][A-Z0-9_]*$/.test(key) || !["string", "number", "boolean"].includes(typeof value)))) {
|
|
130
|
+
throw new Error(`${name} buildArgs 必须是合法构建参数对象`);
|
|
131
|
+
}
|
|
101
132
|
if (component.requiredFiles) {
|
|
102
133
|
if (!Array.isArray(component.requiredFiles)) throw new Error(`${name} requiredFiles 必须是数组`);
|
|
103
134
|
for (const file of component.requiredFiles) inside("/config", file);
|
|
@@ -122,10 +153,8 @@ function execute(command, args, options = {}) {
|
|
|
122
153
|
|
|
123
154
|
async function runTargetRelease(options = {}, dependencies = {}) {
|
|
124
155
|
const projectDir = path.resolve(options.projectDir || process.cwd());
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
: JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).infly?.docker);
|
|
128
|
-
const config = resolveDockerConfig(rawConfig);
|
|
156
|
+
const config = loadDockerConfig({ projectDir, configPath: options.config,
|
|
157
|
+
configObject: options.configObject, configDir: options.configDir });
|
|
129
158
|
const targets = config?.targets;
|
|
130
159
|
if (!targets || !Object.keys(targets).length) throw new Error("请配置 infly.docker.targets");
|
|
131
160
|
const releaseScripts = config?.releaseScripts || {};
|
|
@@ -155,19 +184,54 @@ async function runTargetRelease(options = {}, dependencies = {}) {
|
|
|
155
184
|
if (!Array.isArray(components) || !components.length || new Set(components).size !== components.length) {
|
|
156
185
|
throw new Error("请至少选择一个构建范围,且不能重复");
|
|
157
186
|
}
|
|
187
|
+
const io = dependencies.fs || fs;
|
|
158
188
|
const plan = components.map((name) => {
|
|
159
189
|
if (!Object.hasOwn(profile.components, name)) throw new Error(`不支持的构建范围: ${name}`);
|
|
160
190
|
const component = profile.components[name];
|
|
161
191
|
validateComponent(component, name);
|
|
162
|
-
return { name, ...component
|
|
163
|
-
|
|
192
|
+
if (!component.source) return { name, ...component };
|
|
193
|
+
const configuredDirectory = name === "backend" && options.backendDir ? options.backendDir : component.source.directory;
|
|
194
|
+
const directoryCandidates = resolveSourceDirectories(projectDir, configuredDirectory, name);
|
|
195
|
+
return { name, ...component, source: { ...component.source,
|
|
196
|
+
directory: directoryCandidates[0], directoryCandidates } };
|
|
164
197
|
});
|
|
165
198
|
// dry-run 只解析配置,不联网、不调用 Git/Docker、不创建临时目录。
|
|
166
199
|
if (options.dryRun) { log(JSON.stringify({ target, push: Boolean(options.push), plan }, null, 2)); return { target, plan }; }
|
|
167
|
-
const io = dependencies.fs || fs;
|
|
168
200
|
const run = dependencies.run || execute;
|
|
169
201
|
const capture = (command, args) => String(run(command, args, { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) || "").trim();
|
|
170
|
-
//
|
|
202
|
+
// 全部组件先预检,数组按顺序采用第一个 Git 仓;交互终端允许补录机器本地路径。
|
|
203
|
+
const stdin = dependencies.stdin || process.stdin;
|
|
204
|
+
const stdout = dependencies.stdout || process.stdout;
|
|
205
|
+
const interactive = dependencies.interactive ?? Boolean(stdin.isTTY && stdout.isTTY);
|
|
206
|
+
for (const item of plan.filter((candidate) => candidate.source)) {
|
|
207
|
+
const matched = item.source.directoryCandidates.find((directory) => io.existsSync(path.join(directory, ".git")));
|
|
208
|
+
if (matched) {
|
|
209
|
+
item.source.directory = matched;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (!interactive) continue;
|
|
213
|
+
log(`未在 ${item.name} 源码候选路径中找到 Git 仓库:`);
|
|
214
|
+
item.source.directoryCandidates.forEach((directory, index) => log(` ${index + 1}. ${directory}`));
|
|
215
|
+
const example = process.platform === "win32" ? "D:\\Repo\\equity_project" : "/opt/src/equity_project";
|
|
216
|
+
log(`请输入源码仓路径,例如:${example}`);
|
|
217
|
+
log(`也可以退出后使用 --backend-dir "${example}" 重新执行。`);
|
|
218
|
+
while (true) {
|
|
219
|
+
const entered = await (dependencies.inputText || inputText)(
|
|
220
|
+
`请输入 ${item.name} 源码 Git 仓库路径(例如 ${example})`,
|
|
221
|
+
{ stdin, stdout },
|
|
222
|
+
);
|
|
223
|
+
if (entered === EXIT_SELECTION) return { cancelled: true };
|
|
224
|
+
const normalized = trimPathInput(entered);
|
|
225
|
+
const candidate = normalized ? path.resolve(projectDir, normalized) : "";
|
|
226
|
+
if (candidate && io.existsSync(path.join(candidate, ".git"))) {
|
|
227
|
+
item.source.directory = candidate;
|
|
228
|
+
item.source.directoryCandidates.push(candidate);
|
|
229
|
+
log(`已使用 ${item.name} 源码仓:${candidate}`);
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
log(`路径不是有效 Git 仓库(缺少 .git):${candidate || "<空>"}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
171
235
|
const missing = plan.filter((item) => item.source && !io.existsSync(path.join(item.source.directory, ".git")));
|
|
172
236
|
if (missing.length) {
|
|
173
237
|
for (const item of missing) {
|
|
@@ -229,12 +293,16 @@ async function runTargetRelease(options = {}, dependencies = {}) {
|
|
|
229
293
|
dockerfile = inside(context, item.dockerfile || "Dockerfile");
|
|
230
294
|
}
|
|
231
295
|
if (!io.existsSync(dockerfile)) throw new Error(`缺少 Dockerfile: ${dockerfile}`);
|
|
232
|
-
const
|
|
233
|
-
const image = `${item.repository}:${short}`;
|
|
296
|
+
const image = `${item.repository}:${commit}`;
|
|
234
297
|
const latestImage = `${item.repository}:latest`;
|
|
235
298
|
// --load 只把当前构建节点平台的镜像载入本地镜像存储;发布流程直接使用单平台镜像。
|
|
236
|
-
|
|
237
|
-
|
|
299
|
+
const buildOptions = ["buildx", "build", "--load", "--file", dockerfile];
|
|
300
|
+
if (item.target) buildOptions.push("--target", item.target);
|
|
301
|
+
for (const [key, value] of Object.entries(item.buildArgs || {})) {
|
|
302
|
+
buildOptions.push("--build-arg", `${key}=${value}`);
|
|
303
|
+
}
|
|
304
|
+
run("docker", [...buildOptions,
|
|
305
|
+
"--label", `org.opencontainers.image.revision=${commit}`, "--label", `org.opencontainers.image.version=${commit}`,
|
|
238
306
|
"--label", `com.infly.platform=${target}`, "--tag", image, "--tag", latestImage, context], { cwd: projectDir });
|
|
239
307
|
if (capture("docker", ["image", "inspect", "--format", '{{ index .Config.Labels "org.opencontainers.image.revision" }}', image]) !== commit) {
|
|
240
308
|
throw new Error(`${item.name} 镜像 revision 校验失败`);
|
|
@@ -263,7 +331,9 @@ async function runTargetRelease(options = {}, dependencies = {}) {
|
|
|
263
331
|
// 输出同时面向本地核对与 Jenkins 下拉部署,避免再手工复制提交参数。
|
|
264
332
|
if (results.length) {
|
|
265
333
|
const pushNote = options.push
|
|
266
|
-
?
|
|
334
|
+
? profile.deployment?.ready === true
|
|
335
|
+
? "已推送不可变提交标签和 latest 最新推送标签,可直接在 Jenkins 选择部署"
|
|
336
|
+
: "已推送不可变提交标签和 latest 最新推送标签;该平台尚未开放 Jenkins 部署"
|
|
267
337
|
: "仅本地生成,未推送镜像";
|
|
268
338
|
log("");
|
|
269
339
|
log("\x1b[0;34m==========================================");
|
|
@@ -274,13 +344,14 @@ async function runTargetRelease(options = {}, dependencies = {}) {
|
|
|
274
344
|
log(` ${r.component}=${r.image} (不可变提交版本)`);
|
|
275
345
|
log(` ${r.component}_latest=${r.latestImage} (最新推送镜像,即所选平台 registry 的 latest)`);
|
|
276
346
|
}
|
|
277
|
-
if (cicdLink) {
|
|
347
|
+
if (cicdLink && profile.deployment?.ready === true) {
|
|
278
348
|
log("");
|
|
279
|
-
//
|
|
349
|
+
// 单组件推送成功后把平台与完整提交预填进 Jenkins 参数,新平台首次部署无需从历史下拉选项挑选;
|
|
280
350
|
// 多组件对应对应多个任务时保持原链接,非 /build 地址由 formatCicdLink 原样返回。
|
|
281
|
-
const deployLink = options.push &&
|
|
351
|
+
const deployLink = options.push && profile.deployment?.ready === true
|
|
352
|
+
&& results.length === 1 && /^[a-z0-9]+$/.test(target)
|
|
282
353
|
? formatCicdLink(options.cicdUrl, { platform: target, platformLabel: profile.label,
|
|
283
|
-
tag: results[0].commit
|
|
354
|
+
tag: results[0].commit,
|
|
284
355
|
date: beijingDateTime((dependencies.now || (() => new Date()))()) })
|
|
285
356
|
: cicdLink;
|
|
286
357
|
log(deployLink);
|