@infly/libs 2.0.54 → 2.1.1
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 +121 -3
- package/adapters/webpack/auto-export.js +52 -52
- package/bin/cli.js +12 -0
- package/build/build-utils/command.js +57 -57
- package/build/build-utils/git.js +254 -254
- package/build/build-utils/preview.js +78 -78
- package/build/build-utils/webhook-single.js +136 -136
- package/build/docker/compose-command.js +73 -73
- package/build/docker/compose-release.js +19 -12
- package/build/docker/deployment/deploy.sh +30 -0
- package/build/docker/deployment/health-check.sh +28 -0
- package/build/docker/deployment/promote-image.sh +63 -0
- package/build/docker/deployment/release.sh +74 -0
- package/build/docker/deployment-bundle.js +87 -0
- package/build/docker/target-release.js +263 -0
- package/build/project-files.js +47 -47
- package/cli/progress.js +2 -0
- package/cli/select-option.js +64 -30
- package/core/async/concurrency.js +29 -29
- package/package.json +1 -1
- package/script/git-automation/submodule-utils.js +16 -16
- package/workspace/config.js +144 -144
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
set -euo pipefail
|
|
3
|
+
bundle_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
|
|
4
|
+
source "$bundle_dir/config.sh"
|
|
5
|
+
[[ $# -gt 0 ]] || { echo '需要组件=正式镜像参数' >&2; exit 2; }
|
|
6
|
+
cd "$project_dir"
|
|
7
|
+
for file in "$compose_file" "$secret_env_file" "$release_env_file" "$bundle_dir/docker-compose.release.yml"; do
|
|
8
|
+
[[ -f "$file" ]] || { echo "部署缺少文件: $file" >&2; exit 1; }
|
|
9
|
+
done
|
|
10
|
+
# 先持有目录锁再读基线,避免前后端两个任务同时发布时使用过期基线。
|
|
11
|
+
mkdir "$lock_dir" 2>/dev/null || { echo "已有发布任务持有锁: $project_dir/$lock_dir" >&2; exit 1; }
|
|
12
|
+
next_env=""
|
|
13
|
+
cleanup() { [[ -z "$next_env" ]] || rm -f -- "$next_env"; rmdir "$lock_dir" 2>/dev/null || true; }
|
|
14
|
+
trap cleanup EXIT
|
|
15
|
+
current_images=()
|
|
16
|
+
next_images=()
|
|
17
|
+
selected_indexes=()
|
|
18
|
+
selected_services=()
|
|
19
|
+
for i in "${!component_names[@]}"; do
|
|
20
|
+
key=${image_keys[$i]}
|
|
21
|
+
[[ "$(grep -c "^${key}=" "$release_env_file" || true)" == 1 ]] || { echo "基线必须包含唯一 $key" >&2; exit 1; }
|
|
22
|
+
image=$(grep "^${key}=" "$release_env_file"); image=${image#*=}
|
|
23
|
+
suffix=${image#"${repositories[$i]}"}
|
|
24
|
+
[[ "$image" != "$suffix" && ( "$suffix" =~ ^:[0-9a-f]{12}$ || "$suffix" =~ ^@sha256:[0-9a-f]{64}$ ) ]] || {
|
|
25
|
+
echo "当前基线不是配置仓库的不可变镜像: $key" >&2; exit 1;
|
|
26
|
+
}
|
|
27
|
+
current_images+=("$image"); next_images+=("$image")
|
|
28
|
+
done
|
|
29
|
+
for pair in "$@"; do
|
|
30
|
+
[[ "$pair" == *=* ]] || { echo '参数必须是组件=镜像' >&2; exit 2; }
|
|
31
|
+
name=${pair%%=*}; image=${pair#*=}; found=false
|
|
32
|
+
for i in "${!component_names[@]}"; do
|
|
33
|
+
[[ "$name" == "${component_names[$i]}" ]] || continue
|
|
34
|
+
found=true
|
|
35
|
+
for selected in "${selected_indexes[@]}"; do [[ "$selected" != "$i" ]] || { echo '组件重复' >&2; exit 2; }; done
|
|
36
|
+
suffix=${image#"${repositories[$i]}:"}
|
|
37
|
+
[[ "$suffix" != "$image" && "$suffix" =~ ^[0-9a-f]{12}$ ]] || { echo "只接受本组件正式 commit 镜像: $name" >&2; exit 1; }
|
|
38
|
+
next_images[$i]=$image
|
|
39
|
+
selected_indexes+=("$i")
|
|
40
|
+
read -r -a group <<< "${service_groups[$i]}"
|
|
41
|
+
selected_services+=("${group[@]}")
|
|
42
|
+
done
|
|
43
|
+
[[ "$found" == true ]] || { echo "未配置的组件: $name" >&2; exit 2; }
|
|
44
|
+
done
|
|
45
|
+
umask 077
|
|
46
|
+
mkdir -p .release-history
|
|
47
|
+
previous_env=$(mktemp ".release-history/deploy-${target}-$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX.env")
|
|
48
|
+
cp -- "$release_env_file" "$previous_env"
|
|
49
|
+
chmod 600 "$previous_env"
|
|
50
|
+
next_env=$(mktemp "${release_env_file}.next.XXXXXX")
|
|
51
|
+
# 发布环境文件仅保存配置声明的镜像,敏感值仍由独立环境文件提供。
|
|
52
|
+
for i in "${!image_keys[@]}"; do printf '%s=%s\n' "${image_keys[$i]}" "${next_images[$i]}"; done > "$next_env"
|
|
53
|
+
compose=(docker compose --env-file "$secret_env_file" --env-file "$next_env" -f "$compose_file" -f "$bundle_dir/docker-compose.release.yml")
|
|
54
|
+
"${compose[@]}" config --quiet
|
|
55
|
+
"${compose[@]}" pull "${selected_services[@]}"
|
|
56
|
+
for i in "${selected_indexes[@]}"; do
|
|
57
|
+
image=${next_images[$i]}; short=${image##*:}
|
|
58
|
+
full=$(docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' "$image")
|
|
59
|
+
[[ "$full" =~ ^[0-9a-f]{40}$ && "${full:0:12}" == "$short" ]] || { echo "镜像 revision 校验失败: $image" >&2; exit 1; }
|
|
60
|
+
done
|
|
61
|
+
mv -f -- "$next_env" "$release_env_file"
|
|
62
|
+
next_env=""
|
|
63
|
+
compose=(docker compose --env-file "$secret_env_file" --env-file "$release_env_file" -f "$compose_file" -f "$bundle_dir/docker-compose.release.yml")
|
|
64
|
+
rollback() {
|
|
65
|
+
echo "发布失败,恢复基线: $previous_env" >&2
|
|
66
|
+
cp -- "$previous_env" "$release_env_file"
|
|
67
|
+
chmod 600 "$release_env_file"
|
|
68
|
+
if ! "${compose[@]}" up -d --no-deps "${selected_services[@]}" || ! bash "$bundle_dir/health-check.sh"; then
|
|
69
|
+
echo "自动回滚未通过验证,需人工恢复: $project_dir/$previous_env" >&2
|
|
70
|
+
fi
|
|
71
|
+
}
|
|
72
|
+
if ! "${compose[@]}" up -d --no-deps "${selected_services[@]}"; then rollback; exit 1; fi
|
|
73
|
+
if ! bash "$bundle_dir/health-check.sh"; then rollback; exit 1; fi
|
|
74
|
+
echo "发布成功: $target; 上一版本记录: $project_dir/$previous_env"
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const path = require("node:path");
|
|
3
|
+
|
|
4
|
+
const quote = (value) => "'" + String(value).replaceAll("'", "'\\''") + "'";
|
|
5
|
+
const array = (name, values) => `${name}=(${values.map(quote).join(" ")})`;
|
|
6
|
+
function required(value, name, pattern) {
|
|
7
|
+
if (typeof value !== "string" || !value || (pattern && !pattern.test(value))) throw new Error(`部署配置无效: ${name}`);
|
|
8
|
+
return value;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function renderDeploymentConfig(config, target) {
|
|
12
|
+
const profile = config?.targets?.[target];
|
|
13
|
+
const deploy = profile?.deployment;
|
|
14
|
+
if (!deploy || deploy.ready !== true) throw new Error(`平台 ${target} 尚未完成人工服务器核验,禁止生产发布`);
|
|
15
|
+
const components = Object.entries(profile.components || {});
|
|
16
|
+
if (!components.length) throw new Error("部署必须配置 components");
|
|
17
|
+
const repositories = [], keys = [], serviceGroups = [];
|
|
18
|
+
for (const [name, component] of components) {
|
|
19
|
+
required(name, "component", /^[a-z][a-z0-9_-]*$/);
|
|
20
|
+
const repository = required(component.repository, `${name}.repository`, /^[a-z0-9][a-z0-9.:/_-]+$/);
|
|
21
|
+
if (repository.split("/").at(-1).includes(":")) throw new Error("镜像仓库不得带标签");
|
|
22
|
+
repositories.push(repository);
|
|
23
|
+
keys.push(required(component.imageEnv, `${name}.imageEnv`, /^[A-Z][A-Z0-9_]*$/));
|
|
24
|
+
if (!Array.isArray(component.services) || !component.services.length) throw new Error(`${name} 缺少 services`);
|
|
25
|
+
serviceGroups.push(component.services.map((service) => required(service, "service", /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/)).join(" "));
|
|
26
|
+
}
|
|
27
|
+
if (new Set(keys).size !== keys.length) throw new Error("imageEnv 不得重复");
|
|
28
|
+
const allServices = serviceGroups.flatMap((group) => group.split(" "));
|
|
29
|
+
if (new Set(allServices).size !== allServices.length) throw new Error("组件不能重复拥有同一个服务");
|
|
30
|
+
const lines = ["# 由 @infly/libs 根据项目配置生成;只含非敏感参数。",
|
|
31
|
+
`target=${quote(required(target, "target", /^[a-zA-Z0-9_-]+$/))}`,
|
|
32
|
+
`registry=${quote(required(config.registry, "registry", /^[a-zA-Z0-9.:-]+$/))}`,
|
|
33
|
+
`server=${quote(required(deploy.server, "server", /^[a-zA-Z0-9][a-zA-Z0-9.-]*$/))}`,
|
|
34
|
+
`ssh_user=${quote(required(deploy.sshUser, "sshUser", /^[a-z_][a-z0-9_-]*$/))}`,
|
|
35
|
+
`project_dir=${quote(required(deploy.directory, "directory", /^\/(?!$)[a-zA-Z0-9_./-]+$/))}`,
|
|
36
|
+
...[["compose_file", "composeFile"], ["secret_env_file", "secretEnvFile"], ["release_env_file", "releaseEnvFile"]].map(([shell, json]) => {
|
|
37
|
+
const value = required(deploy[json], json, /^[a-zA-Z0-9_./-]+$/);
|
|
38
|
+
if (value.startsWith("/") || value.split("/").includes("..")) throw new Error(`${json} 必须位于部署目录内`);
|
|
39
|
+
return `${shell}=${quote(value)}`;
|
|
40
|
+
}),
|
|
41
|
+
`lock_dir=${quote(required(deploy.lockName || ".infly-release.lock", "lockName", /^\.[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)*$/))}`,
|
|
42
|
+
array("component_names", components.map(([name]) => name)), array("repositories", repositories),
|
|
43
|
+
array("image_keys", keys), array("service_groups", serviceGroups), array("health_services", allServices),
|
|
44
|
+
];
|
|
45
|
+
const health = deploy.health || {};
|
|
46
|
+
if (!Array.isArray(health.urls) || !health.urls.length) throw new Error("必须配置 health.urls");
|
|
47
|
+
for (const url of health.urls) if (!/^https?:\/\//.test(url)) throw new Error("健康检查 URL 必须是 HTTP(S)");
|
|
48
|
+
lines.push(array("health_urls", health.urls));
|
|
49
|
+
for (const [shell, value] of [["health_attempts", health.attempts ?? 12], ["health_interval", health.intervalSeconds ?? 5], ["health_timeout", health.timeoutSeconds ?? 20]]) {
|
|
50
|
+
if (!Number.isInteger(value) || value < 1 || value > 300) throw new Error(`${shell} 必须为 1 至 300 的整数`);
|
|
51
|
+
lines.push(`${shell}=${value}`);
|
|
52
|
+
}
|
|
53
|
+
lines.push("check_application() {");
|
|
54
|
+
for (const check of health.exec || []) {
|
|
55
|
+
if (!allServices.includes(check.service) || !Array.isArray(check.command) || !check.command.length
|
|
56
|
+
|| !check.command.every((arg) => typeof arg === "string" && !arg.includes("\0"))) throw new Error("health.exec 必须绑定已配置服务和命令数组");
|
|
57
|
+
lines.push(` "\${compose[@]}" exec -T ${quote(check.service)} ${check.command.map(quote).join(" ")} || return $?`);
|
|
58
|
+
}
|
|
59
|
+
lines.push(" return 0", "}");
|
|
60
|
+
return lines.join("\n") + "\n";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function createDeploymentBundle(options = {}) {
|
|
64
|
+
const projectDir = path.resolve(options.projectDir || process.cwd());
|
|
65
|
+
const config = options.configObject || (options.config
|
|
66
|
+
? JSON.parse(fs.readFileSync(path.resolve(projectDir, options.config), "utf8"))
|
|
67
|
+
: JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).infly?.docker);
|
|
68
|
+
const rendered = renderDeploymentConfig(config, options.target);
|
|
69
|
+
if (options.dryRun) return { target: options.target, config: rendered };
|
|
70
|
+
const output = path.resolve(projectDir, options.output || ".infly-deploy");
|
|
71
|
+
const relative = path.relative(projectDir, output);
|
|
72
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error("输出必须是项目内独立子目录");
|
|
73
|
+
// 每次生成独立发布包,拒绝覆盖用户文件或上次中断的部署包。
|
|
74
|
+
if (fs.existsSync(output)) throw new Error(`输出目录已存在,请先人工处理: ${output}`);
|
|
75
|
+
const overlay = path.resolve(projectDir, config.targets[options.target].deployment.releaseComposeFile || "");
|
|
76
|
+
const overlayRelative = path.relative(projectDir, overlay);
|
|
77
|
+
if (overlayRelative.startsWith("..") || path.isAbsolute(overlayRelative) || !fs.statSync(overlay).isFile()) throw new Error("releaseComposeFile 必须是项目内文件");
|
|
78
|
+
fs.mkdirSync(output, { recursive: true });
|
|
79
|
+
for (const name of ["release.sh", "health-check.sh", "deploy.sh", "promote-image.sh"]) {
|
|
80
|
+
fs.writeFileSync(path.join(output, name), fs.readFileSync(path.join(__dirname, "deployment", name), "utf8").replaceAll("\r\n", "\n"));
|
|
81
|
+
}
|
|
82
|
+
fs.writeFileSync(path.join(output, "config.sh"), rendered, { mode: 0o600 });
|
|
83
|
+
fs.copyFileSync(overlay, path.join(output, "docker-compose.release.yml"));
|
|
84
|
+
return { target: options.target, output };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { renderDeploymentConfig, createDeploymentBundle };
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
const fs = require("node:fs");
|
|
2
|
+
const os = require("node:os");
|
|
3
|
+
const path = require("node:path");
|
|
4
|
+
const { execFileSync } = require("node:child_process");
|
|
5
|
+
const { EXIT_SELECTION, selectOption, selectOptions } = require("../../cli/select-option");
|
|
6
|
+
const { composeRelease } = require("./compose-release");
|
|
7
|
+
const { formatCicdLink } = require("./docker-build-push");
|
|
8
|
+
|
|
9
|
+
async function checkDocker(run, projectDir, buildx = true, dependencies = {}, autoStart = true) {
|
|
10
|
+
const quiet = { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
|
|
11
|
+
try {
|
|
12
|
+
run("docker", ["info"], quiet);
|
|
13
|
+
} catch (error) {
|
|
14
|
+
const detail = String(error.stderr || error.message || "").trim();
|
|
15
|
+
const env = dependencies.env || process.env;
|
|
16
|
+
const platform = dependencies.platform || process.platform;
|
|
17
|
+
if (autoStart && platform === "win32" && !env.CI && !env.JENKINS_URL && !env.DOCKER_HOST
|
|
18
|
+
&& /dockerDesktopLinuxEngine/i.test(detail)) {
|
|
19
|
+
// 只针对明确的本机 Desktop 管道启动软件,不切换 context,也不处理远端服务。
|
|
20
|
+
const log = dependencies.log || console.log;
|
|
21
|
+
log("Docker Desktop Linux 引擎未就绪,正在启动本机 Docker Desktop…");
|
|
22
|
+
run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",
|
|
23
|
+
"Start-Process -FilePath 'C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe' -WindowStyle Hidden"], quiet);
|
|
24
|
+
const sleep = dependencies.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
25
|
+
for (let attempt = 0; attempt < 60; attempt++) {
|
|
26
|
+
await sleep(2000);
|
|
27
|
+
try { run("docker", ["info"], quiet); }
|
|
28
|
+
catch {
|
|
29
|
+
if (attempt % 10 === 9) log(`等待 Docker Linux 引擎就绪…${(attempt + 1) * 2}s`);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
log("Docker 引擎已就绪,继续构建。");
|
|
33
|
+
return checkDocker(run, projectDir, buildx, dependencies, false);
|
|
34
|
+
}
|
|
35
|
+
throw new Error("Docker Desktop 启动后 120 秒内 Linux 引擎仍未就绪,请检查 Docker Desktop 的启动错误后重试。", { cause: error });
|
|
36
|
+
}
|
|
37
|
+
const hint = error.code === "ENOENT"
|
|
38
|
+
? "未找到 Docker CLI,请安装 Docker 并确认 docker 位于 PATH。"
|
|
39
|
+
: /dockerDesktopLinuxEngine/i.test(detail)
|
|
40
|
+
? "无法连接 Docker Desktop Linux 引擎。请打开 Docker Desktop,等待 Linux 引擎启动,再运行 docker info 确认 Server 可访问。"
|
|
41
|
+
: "无法连接 Docker 引擎。请检查 docker context show、DOCKER_HOST 和 Docker 服务状态,再运行 docker info。";
|
|
42
|
+
throw new Error(`${hint}\n${detail}`, { cause: error });
|
|
43
|
+
}
|
|
44
|
+
if (buildx) {
|
|
45
|
+
try { run("docker", ["buildx", "version"], quiet); }
|
|
46
|
+
catch (error) { throw new Error("Docker 引擎已连接,但 Buildx 不可用。请检查 docker buildx version。", { cause: error }); }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function parseReleaseArgs(argv) {
|
|
51
|
+
const options = { push: false };
|
|
52
|
+
const keys = { "--target": "target", "--platform": "target", "--components": "components",
|
|
53
|
+
"--project-dir": "projectDir", "--backend-dir": "backendDir", "--config": "config", "--output": "output",
|
|
54
|
+
"--cicd-url": "cicdUrl" };
|
|
55
|
+
for (let i = 0; i < argv.length; i++) {
|
|
56
|
+
const [flag, ...suffix] = argv[i].split("=");
|
|
57
|
+
if (flag === "--") continue;
|
|
58
|
+
if (["--push", "--no-push", "--dry-run"].includes(flag) && suffix.length === 0) {
|
|
59
|
+
if (flag === "--dry-run") options.dryRun = true;
|
|
60
|
+
else options.push = flag === "--push";
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (!keys[flag]) throw new Error(`不支持的参数: ${argv[i]}`);
|
|
64
|
+
const value = suffix.length ? suffix.join("=") : argv[++i];
|
|
65
|
+
if (!value || value.startsWith("--")) throw new Error(`${flag} 缺少参数值`);
|
|
66
|
+
options[keys[flag]] = flag === "--components" ? value.split(",") : value;
|
|
67
|
+
}
|
|
68
|
+
return options;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function inside(root, relative) {
|
|
72
|
+
if (typeof relative !== "string" || !relative || path.isAbsolute(relative)) throw new Error(`必须配置相对路径: ${relative}`);
|
|
73
|
+
const result = path.resolve(root, relative);
|
|
74
|
+
const offset = path.relative(root, result);
|
|
75
|
+
if (offset === ".." || offset.startsWith(`..${path.sep}`)) throw new Error(`路径越界: ${relative}`);
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function validateComponent(component, name) {
|
|
80
|
+
if (!component || !/^[a-z0-9][a-z0-9._:/-]*$/.test(component.repository || "") || component.repository.includes("@")) {
|
|
81
|
+
throw new Error(`${name} 必须配置有效的镜像 repository(不含标签)`);
|
|
82
|
+
}
|
|
83
|
+
if (component.repository.split("/").at(-1).includes(":")) throw new Error(`${name} repository 不得包含标签`);
|
|
84
|
+
if (!component.expectedRef && !component.source?.branch) throw new Error(`${name} 必须配置 expectedRef 或 source.branch`);
|
|
85
|
+
if (component.source && (!component.source.directory || !component.source.branch || component.source.branch.startsWith("-"))) {
|
|
86
|
+
throw new Error(`${name} source 必须配置 directory 和 branch`);
|
|
87
|
+
}
|
|
88
|
+
inside("/config", component.dockerfile || "Dockerfile");
|
|
89
|
+
inside("/config", component.context || ".");
|
|
90
|
+
if (component.requiredFiles) {
|
|
91
|
+
if (!Array.isArray(component.requiredFiles)) throw new Error(`${name} requiredFiles 必须是数组`);
|
|
92
|
+
for (const file of component.requiredFiles) inside("/config", file);
|
|
93
|
+
}
|
|
94
|
+
if (component.files) {
|
|
95
|
+
if (!Array.isArray(component.files) || component.files.length === 0) throw new Error(`${name} files 必须是非空数组`);
|
|
96
|
+
for (const file of component.files) { inside("/config", file.from); inside("/config", file.to); }
|
|
97
|
+
}
|
|
98
|
+
if (component.check) {
|
|
99
|
+
const { entrypoint, args, addHosts = [] } = component.check;
|
|
100
|
+
if (typeof entrypoint !== "string" || !entrypoint || !Array.isArray(args)
|
|
101
|
+
|| !args.every((arg) => typeof arg === "string") || !Array.isArray(addHosts)
|
|
102
|
+
|| !addHosts.every((host) => typeof host === "string" && host.includes(":"))) {
|
|
103
|
+
throw new Error(`${name} check 必须配置 entrypoint、args 数组及可选 addHosts 数组`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function execute(command, args, options = {}) {
|
|
109
|
+
return execFileSync(command, args, { stdio: "inherit", ...options });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function runTargetRelease(options = {}, dependencies = {}) {
|
|
113
|
+
const projectDir = path.resolve(options.projectDir || process.cwd());
|
|
114
|
+
const config = options.configObject || (options.config
|
|
115
|
+
? JSON.parse(fs.readFileSync(path.resolve(projectDir, options.config), "utf8"))
|
|
116
|
+
: JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8")).infly?.docker);
|
|
117
|
+
const targets = config?.targets;
|
|
118
|
+
if (!targets || !Object.keys(targets).length) throw new Error("请配置 infly.docker.targets");
|
|
119
|
+
const log = dependencies.log || console.log;
|
|
120
|
+
const cicdLink = formatCicdLink(options.cicdUrl);
|
|
121
|
+
const target = options.target || await (dependencies.selectOption || selectOption)("请选择构建平台",
|
|
122
|
+
Object.entries(targets).map(([value, item]) => ({ value, label: item.label || value })));
|
|
123
|
+
if (target === EXIT_SELECTION) return { cancelled: true };
|
|
124
|
+
const profile = targets[target];
|
|
125
|
+
if (profile && !profile.components && profile.file) {
|
|
126
|
+
// 旧目标只有 Compose 文件,保留既有镜像/版本语义,不把前端目标静默升级为前后端生产发布。
|
|
127
|
+
const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
|
|
128
|
+
[{ value: "frontend", label: "前端(Compose)" }]);
|
|
129
|
+
if (components === EXIT_SELECTION) return { cancelled: true };
|
|
130
|
+
if (!Array.isArray(components) || components.length !== 1 || components[0] !== "frontend") {
|
|
131
|
+
throw new Error(`平台 ${target} 只配置了 Compose 前端构建,不支持后端`);
|
|
132
|
+
}
|
|
133
|
+
log(`平台 ${profile.label || target} 使用 Compose 配置中的镜像标签,不自动升级版本;不生成 qc 镜像。`);
|
|
134
|
+
if (!options.dryRun) await checkDocker(dependencies.run || execute, projectDir, false, dependencies);
|
|
135
|
+
return (dependencies.composeRelease || composeRelease)({ projectDir, file: profile.file,
|
|
136
|
+
bump: "none", push: Boolean(options.push), dryRun: Boolean(options.dryRun) });
|
|
137
|
+
}
|
|
138
|
+
if (!profile?.components) throw new Error(`平台 ${target} 未配置 components`);
|
|
139
|
+
const components = options.components || await (dependencies.selectOptions || selectOptions)("请选择构建范围",
|
|
140
|
+
Object.entries(profile.components).map(([value, item]) => ({ value, label: item.label || value })));
|
|
141
|
+
if (components === EXIT_SELECTION) return { cancelled: true };
|
|
142
|
+
if (!Array.isArray(components) || !components.length || new Set(components).size !== components.length) {
|
|
143
|
+
throw new Error("请至少选择一个构建范围,且不能重复");
|
|
144
|
+
}
|
|
145
|
+
const plan = components.map((name) => {
|
|
146
|
+
if (!Object.hasOwn(profile.components, name)) throw new Error(`不支持的构建范围: ${name}`);
|
|
147
|
+
const component = profile.components[name];
|
|
148
|
+
validateComponent(component, name);
|
|
149
|
+
return { name, ...component, source: component.source && { ...component.source,
|
|
150
|
+
directory: path.resolve(projectDir, name === "backend" && options.backendDir ? options.backendDir : component.source.directory) } };
|
|
151
|
+
});
|
|
152
|
+
// dry-run 只解析配置,不联网、不调用 Git/Docker、不创建临时目录。
|
|
153
|
+
if (options.dryRun) { log(JSON.stringify({ target, push: Boolean(options.push), plan }, null, 2)); return { target, plan }; }
|
|
154
|
+
const io = dependencies.fs || fs;
|
|
155
|
+
const run = dependencies.run || execute;
|
|
156
|
+
const capture = (command, args) => String(run(command, args, { cwd: projectDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) || "").trim();
|
|
157
|
+
// 全部组件先预检,缺少独立源码仓时不先推送部分镜像。
|
|
158
|
+
const missing = plan.filter((item) => item.source && !io.existsSync(path.join(item.source.directory, ".git")));
|
|
159
|
+
if (missing.length) {
|
|
160
|
+
for (const item of missing) {
|
|
161
|
+
const source = item.source;
|
|
162
|
+
log(`未找到 ${item.name} 源码仓: ${source.directory}`);
|
|
163
|
+
log(`请在 ${projectDir} 准备源码仓后重新运行:`);
|
|
164
|
+
if (source.url) log(`git clone "${source.url}" "${source.directory}"`);
|
|
165
|
+
log(`git -C "${source.directory}" fetch origin "${source.branch}"`);
|
|
166
|
+
const overrides = `${options.backendDir ? ` --backend-dir "${options.backendDir}"` : ""}${options.config ? ` --config "${options.config}"` : ""}`;
|
|
167
|
+
log(`infly-libs docker:release --project-dir "${projectDir}" --target ${target} --components ${components.join(",")}${overrides} ${options.push ? "--push" : "--no-push"}`);
|
|
168
|
+
}
|
|
169
|
+
return { target, missingSources: missing.map((item) => item.name) };
|
|
170
|
+
}
|
|
171
|
+
await checkDocker(run, projectDir, true, dependencies);
|
|
172
|
+
const results = [];
|
|
173
|
+
for (const item of plan) {
|
|
174
|
+
let tempRoot;
|
|
175
|
+
let worktree;
|
|
176
|
+
let sourceDir = projectDir;
|
|
177
|
+
try {
|
|
178
|
+
if (item.source) {
|
|
179
|
+
run("git", ["-C", item.source.directory, "fetch", "origin"], { cwd: projectDir });
|
|
180
|
+
tempRoot = io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
|
|
181
|
+
const candidate = path.join(tempRoot, "source");
|
|
182
|
+
run("git", ["-C", item.source.directory, "worktree", "add", "--detach", candidate, `origin/${item.source.branch}`], { cwd: projectDir });
|
|
183
|
+
worktree = candidate;
|
|
184
|
+
sourceDir = worktree;
|
|
185
|
+
}
|
|
186
|
+
const git = (...args) => capture("git", ["-C", sourceDir, ...args]);
|
|
187
|
+
if (git("status", "--porcelain", "--untracked-files=all")) throw new Error(`${item.name} 仓库存在未提交改动`);
|
|
188
|
+
const commit = git("rev-parse", "HEAD").toLowerCase();
|
|
189
|
+
const expectedRef = item.source ? `origin/${item.source.branch}` : item.expectedRef;
|
|
190
|
+
if (!/^[a-f0-9]{40}$/.test(commit) || commit !== git("rev-parse", `${expectedRef}^{commit}`).toLowerCase()) {
|
|
191
|
+
throw new Error(`${item.name} HEAD 与 ${expectedRef} 不一致,请先核对并 fetch 对应仓库`);
|
|
192
|
+
}
|
|
193
|
+
let context = inside(sourceDir, item.context || ".");
|
|
194
|
+
let dockerfile = inside(sourceDir, item.dockerfile || "Dockerfile");
|
|
195
|
+
for (const file of item.requiredFiles || []) {
|
|
196
|
+
if (!io.existsSync(inside(sourceDir, file))) throw new Error(`缺少必需构建产物: ${file}`);
|
|
197
|
+
}
|
|
198
|
+
if (item.files) {
|
|
199
|
+
tempRoot ||= io.mkdtempSync(path.join(os.tmpdir(), "infly-image-"));
|
|
200
|
+
context = path.join(tempRoot, "context");
|
|
201
|
+
io.mkdirSync(context, { recursive: true });
|
|
202
|
+
for (const file of item.files) {
|
|
203
|
+
const from = inside(sourceDir, file.from);
|
|
204
|
+
const to = inside(context, file.to);
|
|
205
|
+
// 仅复制配置声明的产物,避免把整个 monorepo 发送给 Docker。
|
|
206
|
+
io.mkdirSync(path.dirname(to), { recursive: true });
|
|
207
|
+
io.cpSync(from, to, { recursive: true, dereference: false });
|
|
208
|
+
}
|
|
209
|
+
dockerfile = inside(context, item.dockerfile || "Dockerfile");
|
|
210
|
+
}
|
|
211
|
+
if (!io.existsSync(dockerfile)) throw new Error(`缺少 Dockerfile: ${dockerfile}`);
|
|
212
|
+
const short = commit.slice(0, 12);
|
|
213
|
+
const image = `${item.repository}:qc-${short}`;
|
|
214
|
+
run("docker", ["buildx", "build", "--load", "--file", dockerfile,
|
|
215
|
+
"--label", `org.opencontainers.image.revision=${commit}`, "--label", `org.opencontainers.image.version=${short}`,
|
|
216
|
+
"--label", `com.infly.platform=${target}`, "--tag", image, context], { cwd: projectDir });
|
|
217
|
+
if (capture("docker", ["image", "inspect", "--format", '{{ index .Config.Labels "org.opencontainers.image.revision" }}', image]) !== commit) {
|
|
218
|
+
throw new Error(`${item.name} 镜像 revision 校验失败`);
|
|
219
|
+
}
|
|
220
|
+
if (item.check) {
|
|
221
|
+
const hosts = (item.check.addHosts || []).flatMap((host) => ["--add-host", host]);
|
|
222
|
+
run("docker", ["run", "--rm", ...hosts, "--entrypoint", item.check.entrypoint, image, ...item.check.args], { cwd: projectDir });
|
|
223
|
+
}
|
|
224
|
+
if (options.push) run("docker", ["push", image], { cwd: projectDir });
|
|
225
|
+
log(`${item.name}_commit=${commit}`);
|
|
226
|
+
log(`${item.name}=${image}`);
|
|
227
|
+
results.push({ component: item.name, commit, image, pushed: Boolean(options.push) });
|
|
228
|
+
} finally {
|
|
229
|
+
// 只移除本次创建的隔离 worktree;清理失败保留目录供人工恢复,绝不清空开发工作区。
|
|
230
|
+
if (worktree) run("git", ["-C", item.source.directory, "worktree", "remove", "--force", worktree], { cwd: projectDir });
|
|
231
|
+
if (tempRoot) io.rmSync(tempRoot, { recursive: true, force: true });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// 构建结果汇总(排版与 build:docker 保持一致:✅ 完成 + 可用标签 + 可选发布系统链接)。
|
|
236
|
+
// 构建时已逐组件打印 frontend_commit= 等机器行,供失败前人工留档;这里汇总为可直接复制到
|
|
237
|
+
// Jenkins 发布 Job 的参数区块。
|
|
238
|
+
if (results.length) {
|
|
239
|
+
const pushNote = options.push
|
|
240
|
+
? "本次新建 qc 隔离镜像;正式标签由 Jenkins 校验后晋升"
|
|
241
|
+
: "本次新建 qc 隔离镜像(仅本地,未推送)";
|
|
242
|
+
log("");
|
|
243
|
+
log("\x1b[0;34m==========================================");
|
|
244
|
+
log("✅ 完成");
|
|
245
|
+
log("==========================================\x1b[0m");
|
|
246
|
+
log(`可用标签(${pushNote}):`);
|
|
247
|
+
for (const r of results) {
|
|
248
|
+
log(` ${r.component}=${r.image} (commit 精确版本)`);
|
|
249
|
+
}
|
|
250
|
+
log("");
|
|
251
|
+
log("发布参数(复制到 Jenkins 发布 Job 对应输入框):");
|
|
252
|
+
for (const r of results) {
|
|
253
|
+
log(` ${r.component}_commit=${r.commit}`);
|
|
254
|
+
}
|
|
255
|
+
if (cicdLink) {
|
|
256
|
+
log("");
|
|
257
|
+
log(cicdLink);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return { target, results };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
module.exports = { parseReleaseArgs, runTargetRelease };
|
package/build/project-files.js
CHANGED
|
@@ -3,53 +3,53 @@ const path = require("path");
|
|
|
3
3
|
|
|
4
4
|
// 兼容旧 tools/file-process.js 的 __dirname 路径语义。
|
|
5
5
|
const legacyToolsDir = path.resolve(__dirname, "../tools");
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* 覆盖写入构建脚本
|
|
9
|
-
* @param {String} filePath - 覆盖文件路径
|
|
10
|
-
* @param {Array | Object} scriptsList - 写入脚本配置
|
|
11
|
-
* @param {String} 更新字段值
|
|
12
|
-
*/
|
|
13
|
-
function scriptWrite(filePath, scriptsList, updateKey = "scripts") {
|
|
14
|
-
const pkg = JSON.parse(fs.readFileSync(filePath));
|
|
15
|
-
pkg[updateKey] = pkg[updateKey] || {};
|
|
16
|
-
if (Array.isArray(scriptsList)) {
|
|
17
|
-
scriptsList.forEach(item => {
|
|
18
|
-
if (pkg[updateKey][item.key]) {
|
|
19
|
-
pkg[updateKey][`origin:${item.key}`] = pkg[updateKey][item.key];
|
|
20
|
-
}
|
|
21
|
-
pkg[updateKey][item.key] = item.value;
|
|
22
|
-
});
|
|
23
|
-
} else if (typeof scriptsList === "object") {
|
|
24
|
-
pkg[updateKey] = scriptsList;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* 获取文件绝对路径
|
|
32
|
-
* @param {String} filePath - 文件路径
|
|
33
|
-
* @returns
|
|
34
|
-
*/
|
|
35
|
-
function targetProjectFileResolve(filePath) {
|
|
36
|
-
// 初始脚本自动执行路径会自动读取node_modules
|
|
37
|
-
const projectRoot = process.cwd();
|
|
38
|
-
const absoluteProjectRoot = projectRoot.replace(/\\node_modules.*$/g, "");
|
|
39
|
-
return path.resolve(absoluteProjectRoot, filePath);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* 获取文件绝对路径
|
|
44
|
-
* @param {String} filePath - 文件路径
|
|
45
|
-
* @returns
|
|
46
|
-
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 覆盖写入构建脚本
|
|
9
|
+
* @param {String} filePath - 覆盖文件路径
|
|
10
|
+
* @param {Array | Object} scriptsList - 写入脚本配置
|
|
11
|
+
* @param {String} 更新字段值
|
|
12
|
+
*/
|
|
13
|
+
function scriptWrite(filePath, scriptsList, updateKey = "scripts") {
|
|
14
|
+
const pkg = JSON.parse(fs.readFileSync(filePath));
|
|
15
|
+
pkg[updateKey] = pkg[updateKey] || {};
|
|
16
|
+
if (Array.isArray(scriptsList)) {
|
|
17
|
+
scriptsList.forEach(item => {
|
|
18
|
+
if (pkg[updateKey][item.key]) {
|
|
19
|
+
pkg[updateKey][`origin:${item.key}`] = pkg[updateKey][item.key];
|
|
20
|
+
}
|
|
21
|
+
pkg[updateKey][item.key] = item.value;
|
|
22
|
+
});
|
|
23
|
+
} else if (typeof scriptsList === "object") {
|
|
24
|
+
pkg[updateKey] = scriptsList;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 获取文件绝对路径
|
|
32
|
+
* @param {String} filePath - 文件路径
|
|
33
|
+
* @returns
|
|
34
|
+
*/
|
|
35
|
+
function targetProjectFileResolve(filePath) {
|
|
36
|
+
// 初始脚本自动执行路径会自动读取node_modules
|
|
37
|
+
const projectRoot = process.cwd();
|
|
38
|
+
const absoluteProjectRoot = projectRoot.replace(/\\node_modules.*$/g, "");
|
|
39
|
+
return path.resolve(absoluteProjectRoot, filePath);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 获取文件绝对路径
|
|
44
|
+
* @param {String} filePath - 文件路径
|
|
45
|
+
* @returns
|
|
46
|
+
*/
|
|
47
47
|
function currentProjectFileResolve(filePath) {
|
|
48
48
|
return path.join(legacyToolsDir, filePath);
|
|
49
49
|
}
|
|
50
|
-
|
|
51
|
-
module.exports = {
|
|
52
|
-
scriptWrite,
|
|
53
|
-
targetProjectFileResolve,
|
|
54
|
-
currentProjectFileResolve
|
|
55
|
-
};
|
|
50
|
+
|
|
51
|
+
module.exports = {
|
|
52
|
+
scriptWrite,
|
|
53
|
+
targetProjectFileResolve,
|
|
54
|
+
currentProjectFileResolve
|
|
55
|
+
};
|
package/cli/progress.js
CHANGED
|
@@ -14,6 +14,7 @@ function createProgressReporter(options = {}) {
|
|
|
14
14
|
status: "检查状态",
|
|
15
15
|
deinit: "停用模块",
|
|
16
16
|
init: "模块加载",
|
|
17
|
+
remote: "更新远端",
|
|
17
18
|
};
|
|
18
19
|
const labels = { ...defaultLabels, ...options.labels };
|
|
19
20
|
return (event) => {
|
|
@@ -44,6 +45,7 @@ function formatSwitchSummary(name, totalMs, dependencyResult, timings) {
|
|
|
44
45
|
status: "状态",
|
|
45
46
|
deinit: "停用",
|
|
46
47
|
init: "加载",
|
|
48
|
+
remote: "远端",
|
|
47
49
|
install: "依赖",
|
|
48
50
|
};
|
|
49
51
|
const phases = Object.entries(labels)
|
package/cli/select-option.js
CHANGED
|
@@ -1,46 +1,79 @@
|
|
|
1
1
|
// CLI 交互选择适配,业务选项由调用方注入。
|
|
2
2
|
const EXIT_SELECTION = "__exit__";
|
|
3
|
-
|
|
4
|
-
function isReadlineClosedError(error) {
|
|
5
|
-
return error?.code === "ERR_USE_AFTER_CLOSE";
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
function makePromptCancellationSafe(prompt) {
|
|
9
|
-
const unsafeStop = prompt.stop;
|
|
10
|
-
if (typeof unsafeStop !== "function") return;
|
|
11
|
-
|
|
12
|
-
prompt.removeListener("close", unsafeStop);
|
|
13
|
-
const safeStop = () => {
|
|
14
|
-
try {
|
|
15
|
-
unsafeStop();
|
|
16
|
-
} catch (error) {
|
|
17
|
-
if (!isReadlineClosedError(error)) throw error;
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
prompt.stop = safeStop;
|
|
21
|
-
prompt.once("close", safeStop);
|
|
3
|
+
|
|
4
|
+
function isReadlineClosedError(error) {
|
|
5
|
+
return error?.code === "ERR_USE_AFTER_CLOSE";
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function makePromptCancellationSafe(prompt) {
|
|
9
|
+
const unsafeStop = prompt.stop;
|
|
10
|
+
if (typeof unsafeStop !== "function") return;
|
|
11
|
+
|
|
12
|
+
prompt.removeListener("close", unsafeStop);
|
|
13
|
+
const safeStop = () => {
|
|
14
|
+
try {
|
|
15
|
+
unsafeStop();
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (!isReadlineClosedError(error)) throw error;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
prompt.stop = safeStop;
|
|
21
|
+
prompt.once("close", safeStop);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function selectOption(message, choices, dependencies = {}) {
|
|
25
|
+
const stdin = dependencies.stdin || process.stdin;
|
|
26
|
+
const stdout = dependencies.stdout || process.stdout;
|
|
27
|
+
if (!stdin.isTTY || !stdout.isTTY) {
|
|
28
|
+
throw new Error(`${message}: interactive selection requires a TTY; pass an explicit option.`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const Select = dependencies.Select || require("enquirer").Select;
|
|
32
|
+
const prompt = new Select({
|
|
33
|
+
name: "selection",
|
|
34
|
+
message,
|
|
35
|
+
stdin,
|
|
36
|
+
stdout,
|
|
37
|
+
choices: [
|
|
38
|
+
...choices.map((choice) => ({
|
|
39
|
+
name: choice.value,
|
|
40
|
+
message: choice.label,
|
|
41
|
+
})),
|
|
42
|
+
{ name: EXIT_SELECTION, message: "退出" },
|
|
43
|
+
],
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
prompt.once("start", makePromptCancellationSafe);
|
|
47
|
+
try {
|
|
48
|
+
return await prompt.run();
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (!error || error.name === "CancelPromptError" || isReadlineClosedError(error)) {
|
|
51
|
+
return EXIT_SELECTION;
|
|
52
|
+
}
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
22
55
|
}
|
|
23
56
|
|
|
24
|
-
async function
|
|
57
|
+
async function selectOptions(message, choices, dependencies = {}) {
|
|
25
58
|
const stdin = dependencies.stdin || process.stdin;
|
|
26
59
|
const stdout = dependencies.stdout || process.stdout;
|
|
27
60
|
if (!stdin.isTTY || !stdout.isTTY) {
|
|
28
61
|
throw new Error(`${message}: interactive selection requires a TTY; pass an explicit option.`);
|
|
29
62
|
}
|
|
30
63
|
|
|
31
|
-
const
|
|
32
|
-
const prompt = new
|
|
33
|
-
name: "
|
|
64
|
+
const MultiSelect = dependencies.MultiSelect || require("enquirer").MultiSelect;
|
|
65
|
+
const prompt = new MultiSelect({
|
|
66
|
+
name: "selections",
|
|
34
67
|
message,
|
|
68
|
+
indicator: { on: "[√ ]", off: "[ ]" },
|
|
69
|
+
hint: "↑/↓ 移动,空格勾选/取消,回车确认,Ctrl+C 退出(至少选择一项)",
|
|
35
70
|
stdin,
|
|
36
71
|
stdout,
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
{ name: EXIT_SELECTION, message: "退出" },
|
|
43
|
-
],
|
|
72
|
+
min: 1,
|
|
73
|
+
choices: choices.map((choice) => ({
|
|
74
|
+
name: choice.value,
|
|
75
|
+
message: choice.label,
|
|
76
|
+
})),
|
|
44
77
|
});
|
|
45
78
|
|
|
46
79
|
prompt.once("start", makePromptCancellationSafe);
|
|
@@ -58,4 +91,5 @@ module.exports = {
|
|
|
58
91
|
EXIT_SELECTION,
|
|
59
92
|
makePromptCancellationSafe,
|
|
60
93
|
selectOption,
|
|
94
|
+
selectOptions,
|
|
61
95
|
};
|