@dongnanyang/deploy-cli 0.5.3 → 0.6.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/dist/bin.js +1 -1
- package/dist/{cli-T37L9fUN.js → cli-DEqPcFVu.js} +786 -414
- package/package.json +1 -1
|
@@ -1,10 +1,127 @@
|
|
|
1
1
|
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-CVqFEtQB.js";
|
|
2
2
|
import { readFileSync } from "fs";
|
|
3
3
|
import { resolve } from "path";
|
|
4
|
+
import { parse, stringify } from "yaml";
|
|
4
5
|
import { accessSync, constants, existsSync as existsSync$1, lstatSync, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
|
|
6
|
+
import { join as join$1, resolve as resolve$1 } from "node:path";
|
|
5
7
|
import { spawn } from "node:child_process";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
//#region src/core/project.ts
|
|
9
|
+
const VALID_TYPES = [
|
|
10
|
+
"compose",
|
|
11
|
+
"image",
|
|
12
|
+
"static"
|
|
13
|
+
];
|
|
14
|
+
const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
|
|
15
|
+
const VALID_SSL = [
|
|
16
|
+
"none",
|
|
17
|
+
"acme",
|
|
18
|
+
"custom"
|
|
19
|
+
];
|
|
20
|
+
/** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
|
|
21
|
+
var ProjectConfigError = class extends Error {
|
|
22
|
+
field;
|
|
23
|
+
constructor(message, field) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = "ProjectConfigError";
|
|
26
|
+
this.field = field;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
|
|
30
|
+
function loadProject(dir) {
|
|
31
|
+
const yamlPath = resolve(dir, "deploy.yaml");
|
|
32
|
+
let raw;
|
|
33
|
+
try {
|
|
34
|
+
raw = readFileSync(yamlPath, "utf-8");
|
|
35
|
+
} catch (error) {
|
|
36
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
37
|
+
if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
|
|
38
|
+
throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
|
|
39
|
+
}
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = parse(raw);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
45
|
+
}
|
|
46
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
|
|
47
|
+
return validate(parsed);
|
|
48
|
+
}
|
|
49
|
+
/** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 */
|
|
50
|
+
function validate(raw) {
|
|
51
|
+
const name = raw.name;
|
|
52
|
+
if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
|
|
53
|
+
const type = raw.type;
|
|
54
|
+
if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
|
|
55
|
+
if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
|
|
56
|
+
if (type === "image" && (typeof raw.image !== "string" || raw.image === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
57
|
+
if (type === "static" && (typeof raw.root !== "string" || raw.root === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
|
|
58
|
+
if (raw.nginx !== void 0 && raw.nginx !== null) {
|
|
59
|
+
const nginx = raw.nginx;
|
|
60
|
+
if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
|
|
61
|
+
const n = nginx;
|
|
62
|
+
if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
|
|
63
|
+
if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
|
|
64
|
+
}
|
|
65
|
+
const d = raw;
|
|
66
|
+
if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
|
|
67
|
+
return d;
|
|
68
|
+
}
|
|
69
|
+
/** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
|
|
70
|
+
function listProjects(cfg) {
|
|
71
|
+
return cfg.projects.map((project) => {
|
|
72
|
+
try {
|
|
73
|
+
return {
|
|
74
|
+
name: project.name,
|
|
75
|
+
path: project.path,
|
|
76
|
+
config: loadProject(project.path)
|
|
77
|
+
};
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return {
|
|
80
|
+
name: project.name,
|
|
81
|
+
path: project.path,
|
|
82
|
+
config: null,
|
|
83
|
+
error: error instanceof Error ? error.message : String(error)
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig) */
|
|
89
|
+
function addProject(cfg, dir) {
|
|
90
|
+
const config = loadProject(dir);
|
|
91
|
+
const byName = cfg.projects.find((p) => p.name === config.name);
|
|
92
|
+
if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
|
|
93
|
+
const byPath = cfg.projects.find((p) => p.path === dir);
|
|
94
|
+
if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${dir}`);
|
|
95
|
+
const entry = {
|
|
96
|
+
name: config.name,
|
|
97
|
+
path: dir,
|
|
98
|
+
deployDir: "deploy"
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
...cfg,
|
|
102
|
+
projects: [...cfg.projects, entry]
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
|
|
106
|
+
function removeProject(cfg, name) {
|
|
107
|
+
const projects = cfg.projects.filter((p) => p.name !== name);
|
|
108
|
+
if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
|
|
109
|
+
return {
|
|
110
|
+
...cfg,
|
|
111
|
+
projects
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment) */
|
|
115
|
+
function generateCompose(d) {
|
|
116
|
+
if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
|
|
117
|
+
if (typeof d.image !== "string" || d.image === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
118
|
+
const service = { image: d.image };
|
|
119
|
+
if (d.ports && d.ports.length > 0) service.ports = d.ports;
|
|
120
|
+
if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
|
|
121
|
+
if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
|
|
122
|
+
return stringify({ services: { [d.name]: service } });
|
|
123
|
+
}
|
|
124
|
+
//#endregion
|
|
8
125
|
//#region src/core/exec.ts
|
|
9
126
|
/** 仅 spawn 失败(ENOENT)与超时抛出 */
|
|
10
127
|
var ExecError = class extends Error {
|
|
@@ -109,70 +226,6 @@ async function run(cmd, args, opts = {}) {
|
|
|
109
226
|
});
|
|
110
227
|
}
|
|
111
228
|
//#endregion
|
|
112
|
-
//#region src/cli/commands/doctor.ts
|
|
113
|
-
const SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
114
|
-
const MIN_NODE_MAJOR = 20;
|
|
115
|
-
/** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
|
|
116
|
-
const PROBE_TIMEOUT_MS = 1e4;
|
|
117
|
-
async function probe(runner, cmd, args) {
|
|
118
|
-
try {
|
|
119
|
-
const result = await runner(cmd, args, { timeoutMs: PROBE_TIMEOUT_MS });
|
|
120
|
-
const detail = (result.code === 0 ? result.stdout || result.stderr : result.stderr || result.stdout).trim().split("\n")[0] ?? "";
|
|
121
|
-
return {
|
|
122
|
-
ok: result.code === 0,
|
|
123
|
-
detail
|
|
124
|
-
};
|
|
125
|
-
} catch (error) {
|
|
126
|
-
return {
|
|
127
|
-
ok: false,
|
|
128
|
-
detail: error instanceof Error ? error.message : String(error)
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
function defaultCanWrite(path) {
|
|
133
|
-
try {
|
|
134
|
-
accessSync(path, constants.W_OK);
|
|
135
|
-
return true;
|
|
136
|
-
} catch {
|
|
137
|
-
return false;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
/** 环境自检:返回退出码(存在失败项 1,否则 0;警告不影响退出码) */
|
|
141
|
-
async function doctor(options = {}) {
|
|
142
|
-
const runner = options.runner ?? run;
|
|
143
|
-
const log = options.log ?? ((line) => console.log(line));
|
|
144
|
-
const canWrite = options.canWrite ?? defaultCanWrite;
|
|
145
|
-
let failed = false;
|
|
146
|
-
const pass = (line) => log(`[✓] ${line}`);
|
|
147
|
-
const fail = (line) => {
|
|
148
|
-
failed = true;
|
|
149
|
-
log(`[✗] ${line}`);
|
|
150
|
-
};
|
|
151
|
-
const warn = (line) => log(`[警告] ${line}`);
|
|
152
|
-
log("deploy-cli doctor 环境自检");
|
|
153
|
-
if (Number(process.versions.node.split(".")[0]) >= MIN_NODE_MAJOR) pass(`Node.js v${process.versions.node}`);
|
|
154
|
-
else fail(`Node.js v${process.versions.node} 过低,需要 >= ${MIN_NODE_MAJOR}`);
|
|
155
|
-
const dockerVersion = await probe(runner, "docker", ["--version"]);
|
|
156
|
-
if (!dockerVersion.ok) fail(`docker 不可用(docker --version 失败): ${dockerVersion.detail}`);
|
|
157
|
-
else {
|
|
158
|
-
pass(`docker 可用(${dockerVersion.detail})`);
|
|
159
|
-
const dockerInfo = await probe(runner, "docker", ["info"]);
|
|
160
|
-
if (dockerInfo.ok) pass("docker daemon 运行中");
|
|
161
|
-
else fail(`docker daemon 未运行(docker info 失败): ${dockerInfo.detail}`);
|
|
162
|
-
}
|
|
163
|
-
const nginx = await probe(runner, "nginx", ["-v"]);
|
|
164
|
-
if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
|
|
165
|
-
else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
|
|
166
|
-
if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
|
|
167
|
-
else fail(`${SITES_AVAILABLE} 不可写`);
|
|
168
|
-
const acme = await probe(runner, "acme.sh", ["--version"]);
|
|
169
|
-
const certbot = await probe(runner, "certbot", ["--version"]);
|
|
170
|
-
const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
|
|
171
|
-
if (certTools) pass(`证书工具可用(${certTools})`);
|
|
172
|
-
else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
|
|
173
|
-
return failed ? 1 : 0;
|
|
174
|
-
}
|
|
175
|
-
//#endregion
|
|
176
229
|
//#region src/core/docker.ts
|
|
177
230
|
/** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
|
|
178
231
|
function logsArgs(idOrName, o) {
|
|
@@ -182,9 +235,11 @@ function logsArgs(idOrName, o) {
|
|
|
182
235
|
args.push(idOrName);
|
|
183
236
|
return args;
|
|
184
237
|
}
|
|
185
|
-
/** 失败信息:命令原文 + exit 码 + stderr
|
|
238
|
+
/** 失败信息:命令原文 + exit 码 + stderr 摘要(优先 error/fatal/failed 行,无则取尾部 3 行——docker compose 等工具把进度打在 stderr 前部,取前 3 行会挤掉真错误) */
|
|
186
239
|
function execFailureMessage(cmd, args, result) {
|
|
187
|
-
const
|
|
240
|
+
const lines = result.stderr.trim().split("\n").filter((line) => line.trim() !== "");
|
|
241
|
+
const errors = lines.filter((line) => /error|fatal|failed/i.test(line));
|
|
242
|
+
const summary = (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
|
|
188
243
|
return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
|
|
189
244
|
}
|
|
190
245
|
/** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 (l) => void */
|
|
@@ -275,223 +330,44 @@ function createDocker(runner = run) {
|
|
|
275
330
|
};
|
|
276
331
|
}
|
|
277
332
|
//#endregion
|
|
278
|
-
//#region src/
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
if (arg === "--tail") {
|
|
302
|
-
const value = args[++i];
|
|
303
|
-
const parsed = Number(value);
|
|
304
|
-
if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
|
|
305
|
-
error(`--tail 需要非负整数参数: ${value ?? ""}`);
|
|
306
|
-
error(USAGE$4);
|
|
307
|
-
return 1;
|
|
308
|
-
}
|
|
309
|
-
tail = parsed;
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
if (arg === "--follow") {
|
|
313
|
-
follow = true;
|
|
314
|
-
continue;
|
|
315
|
-
}
|
|
316
|
-
if (arg.startsWith("-")) {
|
|
317
|
-
error(`未知参数: ${arg}`);
|
|
318
|
-
error(USAGE$4);
|
|
319
|
-
return 1;
|
|
320
|
-
}
|
|
321
|
-
positionals.push(arg);
|
|
333
|
+
//#region src/core/nginx.ts
|
|
334
|
+
/** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
|
|
335
|
+
const CONF_PREFIX = "deploy-cli-";
|
|
336
|
+
const CONF_SUFFIX = ".conf";
|
|
337
|
+
const SLUG_RE = /^[a-z0-9-]+$/;
|
|
338
|
+
/** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
|
|
339
|
+
const DOMAIN_RE = /^(\*\.)?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
|
|
340
|
+
const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
|
|
341
|
+
const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
|
|
342
|
+
const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
343
|
+
const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
|
|
344
|
+
const DEFAULT_CONF_D = "/etc/nginx/conf.d";
|
|
345
|
+
/** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
|
|
346
|
+
const ACME_HOME = "/root/.acme.sh";
|
|
347
|
+
/** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
|
|
348
|
+
const ACME_RENEW_SKIP = 2;
|
|
349
|
+
/** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
|
|
350
|
+
function pathExists(path) {
|
|
351
|
+
try {
|
|
352
|
+
lstatSync(path);
|
|
353
|
+
return true;
|
|
354
|
+
} catch {
|
|
355
|
+
return false;
|
|
322
356
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
onLine: (line) => log(line)
|
|
338
|
-
});
|
|
339
|
-
if (result.code !== 0) {
|
|
340
|
-
error(execFailureMessage("docker", logsArgs(name, logOpts), result));
|
|
341
|
-
return 1;
|
|
342
|
-
}
|
|
343
|
-
return 0;
|
|
344
|
-
} catch (err) {
|
|
345
|
-
error(err instanceof Error ? err.message : String(err));
|
|
346
|
-
return 1;
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
//#endregion
|
|
350
|
-
//#region src/core/project.ts
|
|
351
|
-
const VALID_TYPES = [
|
|
352
|
-
"compose",
|
|
353
|
-
"image",
|
|
354
|
-
"static"
|
|
355
|
-
];
|
|
356
|
-
const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
|
|
357
|
-
const VALID_SSL = [
|
|
358
|
-
"none",
|
|
359
|
-
"acme",
|
|
360
|
-
"custom"
|
|
361
|
-
];
|
|
362
|
-
/** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
|
|
363
|
-
var ProjectConfigError = class extends Error {
|
|
364
|
-
field;
|
|
365
|
-
constructor(message, field) {
|
|
366
|
-
super(message);
|
|
367
|
-
this.name = "ProjectConfigError";
|
|
368
|
-
this.field = field;
|
|
369
|
-
}
|
|
370
|
-
};
|
|
371
|
-
/** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
|
|
372
|
-
function loadProject(dir) {
|
|
373
|
-
const yamlPath = resolve(dir, "deploy.yaml");
|
|
374
|
-
let raw;
|
|
375
|
-
try {
|
|
376
|
-
raw = readFileSync(yamlPath, "utf-8");
|
|
377
|
-
} catch (error) {
|
|
378
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
379
|
-
if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
|
|
380
|
-
throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
|
|
381
|
-
}
|
|
382
|
-
let parsed;
|
|
383
|
-
try {
|
|
384
|
-
parsed = parse(raw);
|
|
385
|
-
} catch (error) {
|
|
386
|
-
throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
387
|
-
}
|
|
388
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
|
|
389
|
-
return validate(parsed);
|
|
390
|
-
}
|
|
391
|
-
/** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 */
|
|
392
|
-
function validate(raw) {
|
|
393
|
-
const name = raw.name;
|
|
394
|
-
if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
|
|
395
|
-
const type = raw.type;
|
|
396
|
-
if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
|
|
397
|
-
if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
|
|
398
|
-
if (type === "image" && (typeof raw.image !== "string" || raw.image === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
399
|
-
if (type === "static" && (typeof raw.root !== "string" || raw.root === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
|
|
400
|
-
if (raw.nginx !== void 0 && raw.nginx !== null) {
|
|
401
|
-
const nginx = raw.nginx;
|
|
402
|
-
if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
|
|
403
|
-
const n = nginx;
|
|
404
|
-
if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
|
|
405
|
-
if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
|
|
406
|
-
}
|
|
407
|
-
const d = raw;
|
|
408
|
-
if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
|
|
409
|
-
return d;
|
|
410
|
-
}
|
|
411
|
-
/** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
|
|
412
|
-
function listProjects(cfg) {
|
|
413
|
-
return cfg.projects.map((project) => {
|
|
414
|
-
try {
|
|
415
|
-
return {
|
|
416
|
-
name: project.name,
|
|
417
|
-
path: project.path,
|
|
418
|
-
config: loadProject(project.path)
|
|
419
|
-
};
|
|
420
|
-
} catch (error) {
|
|
421
|
-
return {
|
|
422
|
-
name: project.name,
|
|
423
|
-
path: project.path,
|
|
424
|
-
config: null,
|
|
425
|
-
error: error instanceof Error ? error.message : String(error)
|
|
426
|
-
};
|
|
427
|
-
}
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
/** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig) */
|
|
431
|
-
function addProject(cfg, dir) {
|
|
432
|
-
const config = loadProject(dir);
|
|
433
|
-
const byName = cfg.projects.find((p) => p.name === config.name);
|
|
434
|
-
if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
|
|
435
|
-
const byPath = cfg.projects.find((p) => p.path === dir);
|
|
436
|
-
if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${dir}`);
|
|
437
|
-
const entry = {
|
|
438
|
-
name: config.name,
|
|
439
|
-
path: dir,
|
|
440
|
-
deployDir: "deploy"
|
|
441
|
-
};
|
|
442
|
-
return {
|
|
443
|
-
...cfg,
|
|
444
|
-
projects: [...cfg.projects, entry]
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
|
-
/** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
|
|
448
|
-
function removeProject(cfg, name) {
|
|
449
|
-
const projects = cfg.projects.filter((p) => p.name !== name);
|
|
450
|
-
if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
|
|
451
|
-
return {
|
|
452
|
-
...cfg,
|
|
453
|
-
projects
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
//#endregion
|
|
457
|
-
//#region src/core/nginx.ts
|
|
458
|
-
/** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
|
|
459
|
-
const CONF_PREFIX = "deploy-cli-";
|
|
460
|
-
const CONF_SUFFIX = ".conf";
|
|
461
|
-
const SLUG_RE = /^[a-z0-9-]+$/;
|
|
462
|
-
/** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
|
|
463
|
-
const DOMAIN_RE = /^(\*\.)?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
|
|
464
|
-
const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
|
|
465
|
-
const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
|
|
466
|
-
const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
467
|
-
const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
|
|
468
|
-
const DEFAULT_CONF_D = "/etc/nginx/conf.d";
|
|
469
|
-
/** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
|
|
470
|
-
const ACME_HOME = "/root/.acme.sh";
|
|
471
|
-
/** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
|
|
472
|
-
const ACME_RENEW_SKIP = 2;
|
|
473
|
-
/** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
|
|
474
|
-
function pathExists(path) {
|
|
475
|
-
try {
|
|
476
|
-
lstatSync(path);
|
|
477
|
-
return true;
|
|
478
|
-
} catch {
|
|
479
|
-
return false;
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
/** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
|
|
483
|
-
function validateSlug(slug) {
|
|
484
|
-
if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
|
|
485
|
-
}
|
|
486
|
-
function validateSpec(spec) {
|
|
487
|
-
validateSlug(spec.slug);
|
|
488
|
-
if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
|
|
489
|
-
if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
|
|
490
|
-
if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
|
|
491
|
-
if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
|
|
492
|
-
if (spec.upstream !== void 0 && spec.upstream !== "") {
|
|
493
|
-
const match = spec.upstream.match(UPSTREAM_RE);
|
|
494
|
-
if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
|
|
357
|
+
}
|
|
358
|
+
/** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
|
|
359
|
+
function validateSlug(slug) {
|
|
360
|
+
if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
|
|
361
|
+
}
|
|
362
|
+
function validateSpec(spec) {
|
|
363
|
+
validateSlug(spec.slug);
|
|
364
|
+
if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
|
|
365
|
+
if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
|
|
366
|
+
if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
|
|
367
|
+
if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
|
|
368
|
+
if (spec.upstream !== void 0 && spec.upstream !== "") {
|
|
369
|
+
const match = spec.upstream.match(UPSTREAM_RE);
|
|
370
|
+
if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
|
|
495
371
|
}
|
|
496
372
|
if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
|
|
497
373
|
if (spec.certPath) validateAbsPath("certPath", spec.certPath);
|
|
@@ -589,108 +465,544 @@ function createNginx(runner = run, paths) {
|
|
|
589
465
|
rollback();
|
|
590
466
|
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
|
|
591
467
|
}
|
|
592
|
-
let reload;
|
|
593
|
-
try {
|
|
594
|
-
reload = await runner("nginx", ["-s", "reload"]);
|
|
595
|
-
} catch (error) {
|
|
596
|
-
throw error;
|
|
468
|
+
let reload;
|
|
469
|
+
try {
|
|
470
|
+
reload = await runner("nginx", ["-s", "reload"]);
|
|
471
|
+
} catch (error) {
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
475
|
+
if (existed) unlinkSync(bak);
|
|
476
|
+
}
|
|
477
|
+
async function requestCert(domain) {
|
|
478
|
+
const acmeBin = `${ACME_HOME}/acme.sh`;
|
|
479
|
+
if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
|
|
480
|
+
const args = [
|
|
481
|
+
"--issue",
|
|
482
|
+
"--nginx",
|
|
483
|
+
"-d",
|
|
484
|
+
domain
|
|
485
|
+
];
|
|
486
|
+
const result = await runner(acmeBin, args);
|
|
487
|
+
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
|
|
488
|
+
return {
|
|
489
|
+
tool: "acme.sh",
|
|
490
|
+
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
491
|
+
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
|
|
495
|
+
const args = [
|
|
496
|
+
"--nginx",
|
|
497
|
+
"-d",
|
|
498
|
+
domain,
|
|
499
|
+
"--non-interactive",
|
|
500
|
+
"--agree-tos",
|
|
501
|
+
"--register-unsafely-without-email"
|
|
502
|
+
];
|
|
503
|
+
const result = await runner("certbot", args);
|
|
504
|
+
if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
|
|
505
|
+
return {
|
|
506
|
+
tool: "certbot",
|
|
507
|
+
certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
|
|
508
|
+
keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
|
|
512
|
+
}
|
|
513
|
+
return {
|
|
514
|
+
async applySite(spec) {
|
|
515
|
+
validateSpec(spec);
|
|
516
|
+
if (spec.ssl === "acme") {
|
|
517
|
+
await writeSite(spec.slug, renderBlock(spec, false));
|
|
518
|
+
const cert = await requestCert(spec.serverName);
|
|
519
|
+
await writeSite(spec.slug, renderBlock({
|
|
520
|
+
...spec,
|
|
521
|
+
certPath: cert.certPath,
|
|
522
|
+
keyPath: cert.keyPath
|
|
523
|
+
}, true));
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
|
|
527
|
+
},
|
|
528
|
+
async removeSite(slug) {
|
|
529
|
+
validateSlug(slug);
|
|
530
|
+
const conf = join$1(sitesAvailable, confName(slug));
|
|
531
|
+
if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
|
|
532
|
+
const bak = join$1(sitesAvailable, bakName(slug));
|
|
533
|
+
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
534
|
+
const hadLink = link ? pathExists(link) : false;
|
|
535
|
+
renameSync(conf, bak);
|
|
536
|
+
if (link && hadLink) unlinkSync(link);
|
|
537
|
+
const rollback = () => {
|
|
538
|
+
renameSync(bak, conf);
|
|
539
|
+
if (link && hadLink) symlinkSync(conf, link);
|
|
540
|
+
};
|
|
541
|
+
let test;
|
|
542
|
+
try {
|
|
543
|
+
test = await runner("nginx", ["-t"]);
|
|
544
|
+
} catch (error) {
|
|
545
|
+
rollback();
|
|
546
|
+
throw error;
|
|
547
|
+
}
|
|
548
|
+
if (test.code !== 0) {
|
|
549
|
+
rollback();
|
|
550
|
+
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
|
|
551
|
+
}
|
|
552
|
+
let reload;
|
|
553
|
+
try {
|
|
554
|
+
reload = await runner("nginx", ["-s", "reload"]);
|
|
555
|
+
} catch (error) {
|
|
556
|
+
throw error;
|
|
557
|
+
}
|
|
558
|
+
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
559
|
+
unlinkSync(bak);
|
|
560
|
+
},
|
|
561
|
+
async listSites() {
|
|
562
|
+
return readdirSync$1(sitesAvailable).filter((name) => name.startsWith(CONF_PREFIX) && name.endsWith(CONF_SUFFIX)).map((name) => name.slice(11, -5)).filter((slug) => SLUG_RE.test(slug)).sort();
|
|
563
|
+
},
|
|
564
|
+
requestCert
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
//#endregion
|
|
568
|
+
//#region src/core/health.ts
|
|
569
|
+
/** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
|
|
570
|
+
function describeFetchError(error, timeoutMs) {
|
|
571
|
+
const name = error?.name;
|
|
572
|
+
if (name === "TimeoutError" || name === "AbortError") return `timeout: 健康探测超时(${timeoutMs}ms)`;
|
|
573
|
+
const parts = [];
|
|
574
|
+
const seen = /* @__PURE__ */ new Set();
|
|
575
|
+
let current = error;
|
|
576
|
+
while (current instanceof Error && !seen.has(current)) {
|
|
577
|
+
seen.add(current);
|
|
578
|
+
const code = current.code;
|
|
579
|
+
parts.push(code !== void 0 ? `${current.message}(${code})` : current.message);
|
|
580
|
+
const aggregate = current;
|
|
581
|
+
current = current.cause ?? (Array.isArray(aggregate.errors) ? aggregate.errors[0] : void 0);
|
|
582
|
+
}
|
|
583
|
+
return parts.join(": ") || String(error);
|
|
584
|
+
}
|
|
585
|
+
/** HTTP 健康探测(global fetch,默认 5s 超时):2xx → ok;非 2xx/连接拒绝/超时 → ok:false 附 status 或 error */
|
|
586
|
+
async function httpProbe(url, timeoutMs = 5e3) {
|
|
587
|
+
try {
|
|
588
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
589
|
+
if (res.ok) return {
|
|
590
|
+
ok: true,
|
|
591
|
+
status: res.status
|
|
592
|
+
};
|
|
593
|
+
return {
|
|
594
|
+
ok: false,
|
|
595
|
+
status: res.status,
|
|
596
|
+
error: `HTTP ${res.status}`
|
|
597
|
+
};
|
|
598
|
+
} catch (error) {
|
|
599
|
+
return {
|
|
600
|
+
ok: false,
|
|
601
|
+
error: describeFetchError(error, timeoutMs)
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* 容器归属判定(精确名后过滤):docker `--filter name=` 是子串匹配(`app` 会误伤 `myapp`/`application`),
|
|
607
|
+
* 这里要求项目名以完整连字符分段连续出现在容器名中(兼容 compose 的 `<前缀>-<服务名>-<序号>` 命名)。
|
|
608
|
+
* 末段 `-<数字>` 是 compose 副本号而非名字成分,先剥掉再匹配——否则 `...-test-2`(test 的 2 号副本)
|
|
609
|
+
* 会误配名为 `test-2` 的项目;恰以项目名命名的容器(container_name)走全等判定不受剥离影响。
|
|
610
|
+
*/
|
|
611
|
+
function containerBelongsToProject(containerName, projectName) {
|
|
612
|
+
if (projectName === "") return false;
|
|
613
|
+
if (containerName === projectName) return true;
|
|
614
|
+
const segments = containerName.replace(/-\d+$/, "").split("-");
|
|
615
|
+
const want = projectName.split("-");
|
|
616
|
+
for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
|
|
617
|
+
return false;
|
|
618
|
+
}
|
|
619
|
+
/** 项目容器集合:docker name 过滤(子串)+ 精确名后过滤,含已停止容器 */
|
|
620
|
+
async function findProjectContainers(docker, projectName) {
|
|
621
|
+
return (await docker.listContainers({
|
|
622
|
+
all: true,
|
|
623
|
+
name: projectName
|
|
624
|
+
})).filter((c) => containerBelongsToProject(c.name, projectName));
|
|
625
|
+
}
|
|
626
|
+
/** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
|
|
627
|
+
async function probeNginxSite(slug, runner) {
|
|
628
|
+
try {
|
|
629
|
+
return (await createNginx(runner).listSites()).includes(slug);
|
|
630
|
+
} catch {
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
/** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位 */
|
|
635
|
+
async function checkProjectHealth(project, opts) {
|
|
636
|
+
const runner = opts.runner ?? run;
|
|
637
|
+
const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name);
|
|
638
|
+
const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
|
|
639
|
+
const nginxPresent = await probeNginxSite(project.name, runner);
|
|
640
|
+
return {
|
|
641
|
+
name: project.name,
|
|
642
|
+
containers,
|
|
643
|
+
http,
|
|
644
|
+
nginxPresent
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
//#endregion
|
|
648
|
+
//#region src/core/deploy.ts
|
|
649
|
+
/** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
|
|
650
|
+
function buildSpec(d, noSsl) {
|
|
651
|
+
if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
|
|
652
|
+
const ssl = noSsl ? "none" : d.nginx.ssl;
|
|
653
|
+
if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
|
|
654
|
+
const spec = {
|
|
655
|
+
slug: d.name,
|
|
656
|
+
serverName: d.nginx.domain,
|
|
657
|
+
ssl
|
|
658
|
+
};
|
|
659
|
+
if (d.type === "static") spec.root = d.root;
|
|
660
|
+
else {
|
|
661
|
+
if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
|
|
662
|
+
spec.upstream = d.nginx.upstream;
|
|
663
|
+
}
|
|
664
|
+
return spec;
|
|
665
|
+
}
|
|
666
|
+
/** 非零退出码 → 抛失败信息(命令原文 + stderr 摘要,可附提示) */
|
|
667
|
+
function expectOk(result, cmd, args, hint) {
|
|
668
|
+
if (result.code !== 0) throw new Error(`${execFailureMessage(cmd, args, result)}${hint ? `;${hint}` : ""}`);
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* 部署流水线(失败即停):update(git pull) → pre → build → up → nginx → health → post(R10 上线后钩子)。
|
|
672
|
+
* 步骤跳过口径:update 仅 deploy.update==='git-pull' 时执行(缺省/none 跳过);pre/post 无钩子跳过;
|
|
673
|
+
* static 型跳过 build/up(自定义 build 也不跑);image 型无自定义 build 跳过 build(compose 文件在 up 步才生成);
|
|
674
|
+
* nginx 在 applyNginx!==false 且有 nginx 配置时执行;health 在有 healthUrl 或非 static 型时执行。
|
|
675
|
+
* 某步失败(含 Runner reject:spawn 失败/超时)→ 该步 fail 事件 + 后续步骤绝不执行。
|
|
676
|
+
*/
|
|
677
|
+
async function runDeploy(project, opts) {
|
|
678
|
+
const runner = opts.runner ?? run;
|
|
679
|
+
const docker = opts.docker ?? createDocker(runner);
|
|
680
|
+
const emit = opts.onEvent;
|
|
681
|
+
/** 包裹单步:start → fn → ok;fn 抛错 → fail 事件 + 停(返回结果由调用方 return) */
|
|
682
|
+
async function step(name, startLine, fn) {
|
|
683
|
+
emit({
|
|
684
|
+
step: name,
|
|
685
|
+
status: "start",
|
|
686
|
+
line: startLine
|
|
687
|
+
});
|
|
688
|
+
try {
|
|
689
|
+
await fn();
|
|
690
|
+
} catch (error) {
|
|
691
|
+
const line = error instanceof Error ? error.message : String(error);
|
|
692
|
+
emit({
|
|
693
|
+
step: name,
|
|
694
|
+
status: "fail",
|
|
695
|
+
line
|
|
696
|
+
});
|
|
697
|
+
return {
|
|
698
|
+
ok: false,
|
|
699
|
+
failedStep: name
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
emit({
|
|
703
|
+
step: name,
|
|
704
|
+
status: "ok"
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
const gitArgs = [
|
|
708
|
+
"-C",
|
|
709
|
+
opts.cwd,
|
|
710
|
+
"pull"
|
|
711
|
+
];
|
|
712
|
+
if (project.deploy?.update === "git-pull") {
|
|
713
|
+
const stopped = await step("update", `git ${gitArgs.join(" ")}`, async () => {
|
|
714
|
+
expectOk(await runner("git", gitArgs), "git", gitArgs, "非 git 目录或拉取失败;如无需自动更新请改 deploy.update: none");
|
|
715
|
+
});
|
|
716
|
+
if (stopped) return stopped;
|
|
717
|
+
}
|
|
718
|
+
const pre = project.deploy?.pre ?? [];
|
|
719
|
+
if (pre.length > 0) {
|
|
720
|
+
const stopped = await step("pre", void 0, async () => {
|
|
721
|
+
for (const cmd of pre) expectOk(await runner("bash", ["-c", cmd]), "bash", ["-c", cmd]);
|
|
722
|
+
});
|
|
723
|
+
if (stopped) return stopped;
|
|
724
|
+
}
|
|
725
|
+
const composeFile = project.composeFile ?? "docker-compose.yml";
|
|
726
|
+
const customBuild = project.deploy?.build;
|
|
727
|
+
if (project.type !== "static" && (customBuild !== void 0 || project.type === "compose")) {
|
|
728
|
+
const stopped = await step("build", customBuild ?? `docker compose -f ${composeFile} build`, async () => {
|
|
729
|
+
if (customBuild !== void 0) expectOk(await runner("bash", ["-c", customBuild]), "bash", ["-c", customBuild]);
|
|
730
|
+
else expectOk(await docker.composeBuild(opts.cwd, composeFile), "docker", [
|
|
731
|
+
"compose",
|
|
732
|
+
"-f",
|
|
733
|
+
composeFile,
|
|
734
|
+
"build"
|
|
735
|
+
]);
|
|
736
|
+
});
|
|
737
|
+
if (stopped) return stopped;
|
|
738
|
+
}
|
|
739
|
+
if (project.type !== "static") {
|
|
740
|
+
const upFile = project.type === "image" ? "docker-compose.yml" : composeFile;
|
|
741
|
+
const stopped = await step("up", `docker compose -f ${upFile} up -d`, async () => {
|
|
742
|
+
if (project.type === "image") writeFileSync$1(resolve$1(opts.cwd, upFile), generateCompose(project), "utf-8");
|
|
743
|
+
expectOk(await docker.composeUp(opts.cwd, upFile), "docker", [
|
|
744
|
+
"compose",
|
|
745
|
+
"-f",
|
|
746
|
+
upFile,
|
|
747
|
+
"up",
|
|
748
|
+
"-d"
|
|
749
|
+
]);
|
|
750
|
+
});
|
|
751
|
+
if (stopped) return stopped;
|
|
752
|
+
}
|
|
753
|
+
if ((opts.applyNginx ?? true) && project.nginx) {
|
|
754
|
+
const stopped = await step("nginx", void 0, async () => {
|
|
755
|
+
await (opts.nginx ?? createNginx(runner)).applySite(buildSpec(project, false));
|
|
756
|
+
});
|
|
757
|
+
if (stopped) return stopped;
|
|
758
|
+
}
|
|
759
|
+
if (project.healthUrl !== void 0 || project.type !== "static") {
|
|
760
|
+
const stopped = await step("health", project.healthUrl, async () => {
|
|
761
|
+
if (project.healthUrl) {
|
|
762
|
+
const probe = await httpProbe(project.healthUrl);
|
|
763
|
+
if (!probe.ok) throw new Error(`健康探测失败: ${project.healthUrl}: ${probe.error ?? `HTTP ${probe.status}`}`);
|
|
764
|
+
}
|
|
765
|
+
if (project.type !== "static") {
|
|
766
|
+
if (!(await findProjectContainers(docker, project.name)).some((c) => c.state === "running")) throw new Error(`无运行中容器: ${project.name}(docker ps 未见 running 状态容器)`);
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
if (stopped) return stopped;
|
|
770
|
+
}
|
|
771
|
+
const post = project.deploy?.post ?? [];
|
|
772
|
+
if (post.length > 0) {
|
|
773
|
+
const stopped = await step("post", void 0, async () => {
|
|
774
|
+
for (const cmd of post) expectOk(await runner("bash", ["-c", cmd]), "bash", ["-c", cmd]);
|
|
775
|
+
});
|
|
776
|
+
if (stopped) return stopped;
|
|
777
|
+
}
|
|
778
|
+
return { ok: true };
|
|
779
|
+
}
|
|
780
|
+
//#endregion
|
|
781
|
+
//#region src/cli/commands/deploy.ts
|
|
782
|
+
const USAGE$6 = `用法: deploy-cli deploy <project> [--yes] [--no-nginx]
|
|
783
|
+
|
|
784
|
+
选项:
|
|
785
|
+
--yes 非交互环境(无 TTY)下确认执行部署
|
|
786
|
+
--no-nginx 跳过 nginx 站点配置步骤
|
|
787
|
+
|
|
788
|
+
流水线: update(git pull) → pre 钩子 → build → up → nginx → health → post 钩子(失败即停)
|
|
789
|
+
|
|
790
|
+
示例:
|
|
791
|
+
deploy-cli deploy my-app
|
|
792
|
+
deploy-cli deploy my-app --yes
|
|
793
|
+
deploy-cli deploy my-app --yes --no-nginx`;
|
|
794
|
+
/** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail=✗+失败信息 */
|
|
795
|
+
function formatEvent(e) {
|
|
796
|
+
if (e.status === "ok") return `[${e.step}] ✓`;
|
|
797
|
+
if (e.status === "fail") return `[${e.step}] ✗ ${e.line ?? ""}`;
|
|
798
|
+
return `[${e.step}] ${e.line ?? "开始"}`;
|
|
799
|
+
}
|
|
800
|
+
/** 部署流水线命令:deploy <project> [--yes] [--no-nginx];返回退出码 */
|
|
801
|
+
async function deploy(args, options = {}) {
|
|
802
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
803
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
804
|
+
const load = options.load ?? loadConfig;
|
|
805
|
+
let yes = false;
|
|
806
|
+
let noNginx = false;
|
|
807
|
+
const positional = [];
|
|
808
|
+
for (const arg of args) {
|
|
809
|
+
if (arg === "-h" || arg === "--help") {
|
|
810
|
+
log(USAGE$6);
|
|
811
|
+
return 0;
|
|
812
|
+
}
|
|
813
|
+
if (arg === "--yes") {
|
|
814
|
+
yes = true;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
if (arg === "--no-nginx") {
|
|
818
|
+
noNginx = true;
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
if (arg.startsWith("-")) {
|
|
822
|
+
error(`未知参数: ${arg}`);
|
|
823
|
+
error(USAGE$6);
|
|
824
|
+
return 1;
|
|
825
|
+
}
|
|
826
|
+
positional.push(arg);
|
|
827
|
+
}
|
|
828
|
+
const name = positional[0];
|
|
829
|
+
if (name === void 0 || positional.length > 1) {
|
|
830
|
+
error("deploy 需要且仅需要一个 <project> 参数");
|
|
831
|
+
error(USAGE$6);
|
|
832
|
+
return 1;
|
|
833
|
+
}
|
|
834
|
+
if (!(options.isTTY ?? Boolean(process.stdin.isTTY)) && !yes) {
|
|
835
|
+
error("非交互环境(无 TTY)下部署必须显式确认:请加 --yes(deploy-cli deploy <project> --yes)");
|
|
836
|
+
return 1;
|
|
837
|
+
}
|
|
838
|
+
try {
|
|
839
|
+
const row = listProjects(load()).find((r) => r.name === name);
|
|
840
|
+
if (!row) {
|
|
841
|
+
error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
|
|
842
|
+
return 1;
|
|
843
|
+
}
|
|
844
|
+
if (!row.config) {
|
|
845
|
+
error(`项目配置不可用: ${name}: ${row.error ?? ""}`);
|
|
846
|
+
return 1;
|
|
847
|
+
}
|
|
848
|
+
const result = await runDeploy(row.config, {
|
|
849
|
+
cwd: expandPath(row.path),
|
|
850
|
+
onEvent: (e) => log(formatEvent(e)),
|
|
851
|
+
applyNginx: !noNginx,
|
|
852
|
+
runner: options.runner,
|
|
853
|
+
docker: options.docker,
|
|
854
|
+
nginx: options.nginx
|
|
855
|
+
});
|
|
856
|
+
if (!result.ok) {
|
|
857
|
+
error(`部署失败: ${name}(步骤: ${result.failedStep})`);
|
|
858
|
+
return 1;
|
|
859
|
+
}
|
|
860
|
+
log(`部署完成: ${name}`);
|
|
861
|
+
return 0;
|
|
862
|
+
} catch (err) {
|
|
863
|
+
error(err instanceof Error ? err.message : String(err));
|
|
864
|
+
return 1;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
//#endregion
|
|
868
|
+
//#region src/cli/commands/doctor.ts
|
|
869
|
+
const SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
870
|
+
const MIN_NODE_MAJOR = 20;
|
|
871
|
+
/** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
|
|
872
|
+
const PROBE_TIMEOUT_MS = 1e4;
|
|
873
|
+
async function probe(runner, cmd, args) {
|
|
874
|
+
try {
|
|
875
|
+
const result = await runner(cmd, args, { timeoutMs: PROBE_TIMEOUT_MS });
|
|
876
|
+
const detail = (result.code === 0 ? result.stdout || result.stderr : result.stderr || result.stdout).trim().split("\n")[0] ?? "";
|
|
877
|
+
return {
|
|
878
|
+
ok: result.code === 0,
|
|
879
|
+
detail
|
|
880
|
+
};
|
|
881
|
+
} catch (error) {
|
|
882
|
+
return {
|
|
883
|
+
ok: false,
|
|
884
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
function defaultCanWrite(path) {
|
|
889
|
+
try {
|
|
890
|
+
accessSync(path, constants.W_OK);
|
|
891
|
+
return true;
|
|
892
|
+
} catch {
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
/** 环境自检:返回退出码(存在失败项 1,否则 0;警告不影响退出码) */
|
|
897
|
+
async function doctor(options = {}) {
|
|
898
|
+
const runner = options.runner ?? run;
|
|
899
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
900
|
+
const canWrite = options.canWrite ?? defaultCanWrite;
|
|
901
|
+
let failed = false;
|
|
902
|
+
const pass = (line) => log(`[✓] ${line}`);
|
|
903
|
+
const fail = (line) => {
|
|
904
|
+
failed = true;
|
|
905
|
+
log(`[✗] ${line}`);
|
|
906
|
+
};
|
|
907
|
+
const warn = (line) => log(`[警告] ${line}`);
|
|
908
|
+
log("deploy-cli doctor 环境自检");
|
|
909
|
+
if (Number(process.versions.node.split(".")[0]) >= MIN_NODE_MAJOR) pass(`Node.js v${process.versions.node}`);
|
|
910
|
+
else fail(`Node.js v${process.versions.node} 过低,需要 >= ${MIN_NODE_MAJOR}`);
|
|
911
|
+
const dockerVersion = await probe(runner, "docker", ["--version"]);
|
|
912
|
+
if (!dockerVersion.ok) fail(`docker 不可用(docker --version 失败): ${dockerVersion.detail}`);
|
|
913
|
+
else {
|
|
914
|
+
pass(`docker 可用(${dockerVersion.detail})`);
|
|
915
|
+
const dockerInfo = await probe(runner, "docker", ["info"]);
|
|
916
|
+
if (dockerInfo.ok) pass("docker daemon 运行中");
|
|
917
|
+
else fail(`docker daemon 未运行(docker info 失败): ${dockerInfo.detail}`);
|
|
918
|
+
}
|
|
919
|
+
const nginx = await probe(runner, "nginx", ["-v"]);
|
|
920
|
+
if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
|
|
921
|
+
else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
|
|
922
|
+
if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
|
|
923
|
+
else fail(`${SITES_AVAILABLE} 不可写`);
|
|
924
|
+
const acme = await probe(runner, "acme.sh", ["--version"]);
|
|
925
|
+
const certbot = await probe(runner, "certbot", ["--version"]);
|
|
926
|
+
const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
|
|
927
|
+
if (certTools) pass(`证书工具可用(${certTools})`);
|
|
928
|
+
else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
|
|
929
|
+
return failed ? 1 : 0;
|
|
930
|
+
}
|
|
931
|
+
//#endregion
|
|
932
|
+
//#region src/cli/commands/logs.ts
|
|
933
|
+
const USAGE$5 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
|
|
934
|
+
|
|
935
|
+
选项:
|
|
936
|
+
--tail <行数> 只显示最后 N 行(默认全部)
|
|
937
|
+
--follow 持续跟随日志输出(Ctrl-C 退出)
|
|
938
|
+
|
|
939
|
+
示例:
|
|
940
|
+
deploy-cli logs deploy-cli-test-echo --tail 5
|
|
941
|
+
deploy-cli logs my-app --follow`;
|
|
942
|
+
/** 查看容器日志,逐行输出到 stdout;返回退出码 */
|
|
943
|
+
async function logs(args, options = {}) {
|
|
944
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
945
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
946
|
+
let tail;
|
|
947
|
+
let follow = false;
|
|
948
|
+
const positionals = [];
|
|
949
|
+
for (let i = 0; i < args.length; i++) {
|
|
950
|
+
const arg = args[i];
|
|
951
|
+
if (arg === "-h" || arg === "--help") {
|
|
952
|
+
log(USAGE$5);
|
|
953
|
+
return 0;
|
|
954
|
+
}
|
|
955
|
+
if (arg === "--tail") {
|
|
956
|
+
const value = args[++i];
|
|
957
|
+
const parsed = Number(value);
|
|
958
|
+
if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
|
|
959
|
+
error(`--tail 需要非负整数参数: ${value ?? ""}`);
|
|
960
|
+
error(USAGE$5);
|
|
961
|
+
return 1;
|
|
962
|
+
}
|
|
963
|
+
tail = parsed;
|
|
964
|
+
continue;
|
|
597
965
|
}
|
|
598
|
-
if (
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
async function requestCert(domain) {
|
|
602
|
-
const acmeBin = `${ACME_HOME}/acme.sh`;
|
|
603
|
-
if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
|
|
604
|
-
const args = [
|
|
605
|
-
"--issue",
|
|
606
|
-
"--nginx",
|
|
607
|
-
"-d",
|
|
608
|
-
domain
|
|
609
|
-
];
|
|
610
|
-
const result = await runner(acmeBin, args);
|
|
611
|
-
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
|
|
612
|
-
return {
|
|
613
|
-
tool: "acme.sh",
|
|
614
|
-
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
615
|
-
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
616
|
-
};
|
|
966
|
+
if (arg === "--follow") {
|
|
967
|
+
follow = true;
|
|
968
|
+
continue;
|
|
617
969
|
}
|
|
618
|
-
if ((
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
domain,
|
|
623
|
-
"--non-interactive",
|
|
624
|
-
"--agree-tos",
|
|
625
|
-
"--register-unsafely-without-email"
|
|
626
|
-
];
|
|
627
|
-
const result = await runner("certbot", args);
|
|
628
|
-
if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
|
|
629
|
-
return {
|
|
630
|
-
tool: "certbot",
|
|
631
|
-
certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
|
|
632
|
-
keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
|
|
633
|
-
};
|
|
970
|
+
if (arg.startsWith("-")) {
|
|
971
|
+
error(`未知参数: ${arg}`);
|
|
972
|
+
error(USAGE$5);
|
|
973
|
+
return 1;
|
|
634
974
|
}
|
|
635
|
-
|
|
975
|
+
positionals.push(arg);
|
|
636
976
|
}
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
}, true));
|
|
648
|
-
return;
|
|
649
|
-
}
|
|
650
|
-
await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
|
|
651
|
-
},
|
|
652
|
-
async removeSite(slug) {
|
|
653
|
-
validateSlug(slug);
|
|
654
|
-
const conf = join$1(sitesAvailable, confName(slug));
|
|
655
|
-
if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
|
|
656
|
-
const bak = join$1(sitesAvailable, bakName(slug));
|
|
657
|
-
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
658
|
-
const hadLink = link ? pathExists(link) : false;
|
|
659
|
-
renameSync(conf, bak);
|
|
660
|
-
if (link && hadLink) unlinkSync(link);
|
|
661
|
-
const rollback = () => {
|
|
662
|
-
renameSync(bak, conf);
|
|
663
|
-
if (link && hadLink) symlinkSync(conf, link);
|
|
664
|
-
};
|
|
665
|
-
let test;
|
|
666
|
-
try {
|
|
667
|
-
test = await runner("nginx", ["-t"]);
|
|
668
|
-
} catch (error) {
|
|
669
|
-
rollback();
|
|
670
|
-
throw error;
|
|
671
|
-
}
|
|
672
|
-
if (test.code !== 0) {
|
|
673
|
-
rollback();
|
|
674
|
-
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
|
|
675
|
-
}
|
|
676
|
-
let reload;
|
|
677
|
-
try {
|
|
678
|
-
reload = await runner("nginx", ["-s", "reload"]);
|
|
679
|
-
} catch (error) {
|
|
680
|
-
throw error;
|
|
681
|
-
}
|
|
682
|
-
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
683
|
-
unlinkSync(bak);
|
|
684
|
-
},
|
|
685
|
-
async listSites() {
|
|
686
|
-
return readdirSync$1(sitesAvailable).filter((name) => name.startsWith(CONF_PREFIX) && name.endsWith(CONF_SUFFIX)).map((name) => name.slice(11, -5)).filter((slug) => SLUG_RE.test(slug)).sort();
|
|
687
|
-
},
|
|
688
|
-
requestCert
|
|
977
|
+
if (positionals.length !== 1) {
|
|
978
|
+
error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
|
|
979
|
+
error(USAGE$5);
|
|
980
|
+
return 1;
|
|
981
|
+
}
|
|
982
|
+
const name = positionals[0];
|
|
983
|
+
const docker = options.docker ?? createDocker();
|
|
984
|
+
const logOpts = {
|
|
985
|
+
tail,
|
|
986
|
+
follow
|
|
689
987
|
};
|
|
988
|
+
try {
|
|
989
|
+
const result = await docker.logs(name, {
|
|
990
|
+
...logOpts,
|
|
991
|
+
onLine: (line) => log(line)
|
|
992
|
+
});
|
|
993
|
+
if (result.code !== 0) {
|
|
994
|
+
error(execFailureMessage("docker", logsArgs(name, logOpts), result));
|
|
995
|
+
return 1;
|
|
996
|
+
}
|
|
997
|
+
return 0;
|
|
998
|
+
} catch (err) {
|
|
999
|
+
error(err instanceof Error ? err.message : String(err));
|
|
1000
|
+
return 1;
|
|
1001
|
+
}
|
|
690
1002
|
}
|
|
691
1003
|
//#endregion
|
|
692
1004
|
//#region src/cli/commands/nginx.ts
|
|
693
|
-
const USAGE$
|
|
1005
|
+
const USAGE$4 = `用法: deploy-cli nginx <apply|remove|list> [参数]
|
|
694
1006
|
|
|
695
1007
|
子命令:
|
|
696
1008
|
apply <project> [--no-ssl] 按 deploy.yaml 的 nginx 配置写入站点 conf 并启用
|
|
@@ -702,23 +1014,6 @@ const USAGE$3 = `用法: deploy-cli nginx <apply|remove|list> [参数]
|
|
|
702
1014
|
deploy-cli nginx apply my-app --no-ssl
|
|
703
1015
|
deploy-cli nginx remove my-app
|
|
704
1016
|
deploy-cli nginx list`;
|
|
705
|
-
/** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
|
|
706
|
-
function buildSpec(d, noSsl) {
|
|
707
|
-
if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
|
|
708
|
-
const ssl = noSsl ? "none" : d.nginx.ssl;
|
|
709
|
-
if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
|
|
710
|
-
const spec = {
|
|
711
|
-
slug: d.name,
|
|
712
|
-
serverName: d.nginx.domain,
|
|
713
|
-
ssl
|
|
714
|
-
};
|
|
715
|
-
if (d.type === "static") spec.root = d.root;
|
|
716
|
-
else {
|
|
717
|
-
if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
|
|
718
|
-
spec.upstream = d.nginx.upstream;
|
|
719
|
-
}
|
|
720
|
-
return spec;
|
|
721
|
-
}
|
|
722
1017
|
/** nginx 站点管理:apply / remove / list;返回退出码 */
|
|
723
1018
|
async function nginx(args, options = {}) {
|
|
724
1019
|
const log = options.log ?? ((line) => console.log(line));
|
|
@@ -727,12 +1022,12 @@ async function nginx(args, options = {}) {
|
|
|
727
1022
|
const api = options.api ?? createNginx();
|
|
728
1023
|
const [sub, ...rest] = args;
|
|
729
1024
|
if (sub === "-h" || sub === "--help") {
|
|
730
|
-
log(USAGE$
|
|
1025
|
+
log(USAGE$4);
|
|
731
1026
|
return 0;
|
|
732
1027
|
}
|
|
733
1028
|
if (sub === void 0) {
|
|
734
1029
|
error("缺少子命令");
|
|
735
|
-
error(USAGE$
|
|
1030
|
+
error(USAGE$4);
|
|
736
1031
|
return 1;
|
|
737
1032
|
}
|
|
738
1033
|
try {
|
|
@@ -741,14 +1036,14 @@ async function nginx(args, options = {}) {
|
|
|
741
1036
|
const unknown = rest.filter((a) => a.startsWith("-") && a !== "--no-ssl");
|
|
742
1037
|
if (unknown.length > 0) {
|
|
743
1038
|
error(`未知参数: ${unknown.join(" ")}`);
|
|
744
|
-
error(USAGE$
|
|
1039
|
+
error(USAGE$4);
|
|
745
1040
|
return 1;
|
|
746
1041
|
}
|
|
747
1042
|
const positional = rest.filter((a) => !a.startsWith("-"));
|
|
748
1043
|
const name = positional[0];
|
|
749
1044
|
if (name === void 0 || positional.length > 1) {
|
|
750
1045
|
error("apply 需要且仅需要一个 <project> 参数");
|
|
751
|
-
error(USAGE$
|
|
1046
|
+
error(USAGE$4);
|
|
752
1047
|
return 1;
|
|
753
1048
|
}
|
|
754
1049
|
const noSsl = rest.includes("--no-ssl");
|
|
@@ -770,7 +1065,7 @@ async function nginx(args, options = {}) {
|
|
|
770
1065
|
const name = rest[0];
|
|
771
1066
|
if (name === void 0 || rest.length > 1) {
|
|
772
1067
|
error("remove 需要且仅需要一个 <project> 参数");
|
|
773
|
-
error(USAGE$
|
|
1068
|
+
error(USAGE$4);
|
|
774
1069
|
return 1;
|
|
775
1070
|
}
|
|
776
1071
|
await api.removeSite(name);
|
|
@@ -780,7 +1075,7 @@ async function nginx(args, options = {}) {
|
|
|
780
1075
|
case "list": {
|
|
781
1076
|
if (rest.length > 0) {
|
|
782
1077
|
error(`未知参数: ${rest.join(" ")}`);
|
|
783
|
-
error(USAGE$
|
|
1078
|
+
error(USAGE$4);
|
|
784
1079
|
return 1;
|
|
785
1080
|
}
|
|
786
1081
|
const sites = await api.listSites();
|
|
@@ -790,7 +1085,7 @@ async function nginx(args, options = {}) {
|
|
|
790
1085
|
}
|
|
791
1086
|
default:
|
|
792
1087
|
error(`未知子命令: ${sub}`);
|
|
793
|
-
error(USAGE$
|
|
1088
|
+
error(USAGE$4);
|
|
794
1089
|
return 1;
|
|
795
1090
|
}
|
|
796
1091
|
} catch (err) {
|
|
@@ -800,7 +1095,7 @@ async function nginx(args, options = {}) {
|
|
|
800
1095
|
}
|
|
801
1096
|
//#endregion
|
|
802
1097
|
//#region src/cli/commands/project.ts
|
|
803
|
-
const USAGE$
|
|
1098
|
+
const USAGE$3 = `用法: deploy-cli project <list|add|remove> [参数]
|
|
804
1099
|
|
|
805
1100
|
子命令:
|
|
806
1101
|
list 列出已注册项目(NAME/PATH/TYPE/ERROR)
|
|
@@ -819,12 +1114,12 @@ async function project(args, options = {}) {
|
|
|
819
1114
|
const save = options.save ?? saveConfig;
|
|
820
1115
|
const [sub, ...rest] = args;
|
|
821
1116
|
if (sub === "-h" || sub === "--help") {
|
|
822
|
-
log(USAGE$
|
|
1117
|
+
log(USAGE$3);
|
|
823
1118
|
return 0;
|
|
824
1119
|
}
|
|
825
1120
|
if (sub === void 0) {
|
|
826
1121
|
error("缺少子命令");
|
|
827
|
-
error(USAGE$
|
|
1122
|
+
error(USAGE$3);
|
|
828
1123
|
return 1;
|
|
829
1124
|
}
|
|
830
1125
|
try {
|
|
@@ -832,7 +1127,7 @@ async function project(args, options = {}) {
|
|
|
832
1127
|
case "list": {
|
|
833
1128
|
if (rest.length > 0) {
|
|
834
1129
|
error(`未知参数: ${rest.join(" ")}`);
|
|
835
|
-
error(USAGE$
|
|
1130
|
+
error(USAGE$3);
|
|
836
1131
|
return 1;
|
|
837
1132
|
}
|
|
838
1133
|
const rows = listProjects(load());
|
|
@@ -844,7 +1139,7 @@ async function project(args, options = {}) {
|
|
|
844
1139
|
const raw = rest[0];
|
|
845
1140
|
if (raw === void 0 || rest.length > 1) {
|
|
846
1141
|
error("add 需要且仅需要一个 <path> 参数");
|
|
847
|
-
error(USAGE$
|
|
1142
|
+
error(USAGE$3);
|
|
848
1143
|
return 1;
|
|
849
1144
|
}
|
|
850
1145
|
const dir = expandPath(raw);
|
|
@@ -858,7 +1153,7 @@ async function project(args, options = {}) {
|
|
|
858
1153
|
const name = rest[0];
|
|
859
1154
|
if (name === void 0 || rest.length > 1) {
|
|
860
1155
|
error("remove 需要且仅需要一个 <name> 参数");
|
|
861
|
-
error(USAGE$
|
|
1156
|
+
error(USAGE$3);
|
|
862
1157
|
return 1;
|
|
863
1158
|
}
|
|
864
1159
|
save(removeProject(load(), name));
|
|
@@ -867,7 +1162,7 @@ async function project(args, options = {}) {
|
|
|
867
1162
|
}
|
|
868
1163
|
default:
|
|
869
1164
|
error(`未知子命令: ${sub}`);
|
|
870
|
-
error(USAGE$
|
|
1165
|
+
error(USAGE$3);
|
|
871
1166
|
return 1;
|
|
872
1167
|
}
|
|
873
1168
|
} catch (err) {
|
|
@@ -877,7 +1172,7 @@ async function project(args, options = {}) {
|
|
|
877
1172
|
}
|
|
878
1173
|
//#endregion
|
|
879
1174
|
//#region src/cli/commands/ps.ts
|
|
880
|
-
const USAGE$
|
|
1175
|
+
const USAGE$2 = `用法: deploy-cli ps [--all] [--project <项目名>]
|
|
881
1176
|
|
|
882
1177
|
选项:
|
|
883
1178
|
--all 含已停止的容器
|
|
@@ -896,7 +1191,7 @@ async function ps(args, options = {}) {
|
|
|
896
1191
|
for (let i = 0; i < args.length; i++) {
|
|
897
1192
|
const arg = args[i];
|
|
898
1193
|
if (arg === "-h" || arg === "--help") {
|
|
899
|
-
log(USAGE$
|
|
1194
|
+
log(USAGE$2);
|
|
900
1195
|
return 0;
|
|
901
1196
|
}
|
|
902
1197
|
if (arg === "--all") {
|
|
@@ -907,14 +1202,14 @@ async function ps(args, options = {}) {
|
|
|
907
1202
|
const value = args[++i];
|
|
908
1203
|
if (value === void 0 || value === "") {
|
|
909
1204
|
error("缺少 --project 的项目名参数");
|
|
910
|
-
error(USAGE$
|
|
1205
|
+
error(USAGE$2);
|
|
911
1206
|
return 1;
|
|
912
1207
|
}
|
|
913
1208
|
projectName = value;
|
|
914
1209
|
continue;
|
|
915
1210
|
}
|
|
916
1211
|
error(`未知参数: ${arg}`);
|
|
917
|
-
error(USAGE$
|
|
1212
|
+
error(USAGE$2);
|
|
918
1213
|
return 1;
|
|
919
1214
|
}
|
|
920
1215
|
const docker = options.docker ?? createDocker();
|
|
@@ -941,6 +1236,79 @@ async function ps(args, options = {}) {
|
|
|
941
1236
|
}
|
|
942
1237
|
}
|
|
943
1238
|
//#endregion
|
|
1239
|
+
//#region src/cli/commands/status.ts
|
|
1240
|
+
const USAGE$1 = `用法: deploy-cli status [project]
|
|
1241
|
+
|
|
1242
|
+
聚合项目健康状态(容器 / HTTP 探测 / nginx conf):
|
|
1243
|
+
CONTAINERS 运行中/总数 容器(含已停止)
|
|
1244
|
+
HTTP healthUrl 探测结果(2xx=状态码,失败=FAIL,未配置=-)
|
|
1245
|
+
NGINX deploy-cli 站点 conf 在位(✓ 在 / ✗ 不在 / - 未知)
|
|
1246
|
+
|
|
1247
|
+
示例:
|
|
1248
|
+
deploy-cli status
|
|
1249
|
+
deploy-cli status my-app`;
|
|
1250
|
+
/** ProjectHealth → 表格行(CONTAINERS/HTTP/NGINX 三列) */
|
|
1251
|
+
function formatRow(health) {
|
|
1252
|
+
const total = health.containers.length;
|
|
1253
|
+
const running = health.containers.filter((c) => c.state === "running").length;
|
|
1254
|
+
const containers = total === 0 ? "无容器" : `${running}/${total} running`;
|
|
1255
|
+
const http = health.http === void 0 ? "-" : health.http.ok ? String(health.http.status) : "FAIL";
|
|
1256
|
+
const nginx = health.nginxPresent === void 0 ? "-" : health.nginxPresent ? "✓" : "✗";
|
|
1257
|
+
return `${health.name}\t${containers}\t${http}\t${nginx}`;
|
|
1258
|
+
}
|
|
1259
|
+
/** 状态聚合命令:status [project];返回退出码 */
|
|
1260
|
+
async function status(args, options = {}) {
|
|
1261
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
1262
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
1263
|
+
const load = options.load ?? loadConfig;
|
|
1264
|
+
const positional = [];
|
|
1265
|
+
for (const arg of args) {
|
|
1266
|
+
if (arg === "-h" || arg === "--help") {
|
|
1267
|
+
log(USAGE$1);
|
|
1268
|
+
return 0;
|
|
1269
|
+
}
|
|
1270
|
+
if (arg.startsWith("-")) {
|
|
1271
|
+
error(`未知参数: ${arg}`);
|
|
1272
|
+
error(USAGE$1);
|
|
1273
|
+
return 1;
|
|
1274
|
+
}
|
|
1275
|
+
positional.push(arg);
|
|
1276
|
+
}
|
|
1277
|
+
if (positional.length > 1) {
|
|
1278
|
+
error("status 至多接受一个 [project] 参数");
|
|
1279
|
+
error(USAGE$1);
|
|
1280
|
+
return 1;
|
|
1281
|
+
}
|
|
1282
|
+
try {
|
|
1283
|
+
let rows;
|
|
1284
|
+
if (positional.length === 1) {
|
|
1285
|
+
const name = positional[0];
|
|
1286
|
+
const row = listProjects(load()).find((r) => r.name === name);
|
|
1287
|
+
if (!row) {
|
|
1288
|
+
error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
|
|
1289
|
+
return 1;
|
|
1290
|
+
}
|
|
1291
|
+
rows = [row];
|
|
1292
|
+
} else rows = listProjects(load());
|
|
1293
|
+
log("NAME CONTAINERS HTTP NGINX");
|
|
1294
|
+
for (const row of rows) {
|
|
1295
|
+
if (!row.config) {
|
|
1296
|
+
error(`项目配置不可用: ${row.name}: ${row.error ?? ""}`);
|
|
1297
|
+
log(`${row.name}\t配置不可用\t-\t-`);
|
|
1298
|
+
continue;
|
|
1299
|
+
}
|
|
1300
|
+
log(formatRow(await checkProjectHealth(row.config, {
|
|
1301
|
+
docker: options.docker,
|
|
1302
|
+
runner: options.runner
|
|
1303
|
+
})));
|
|
1304
|
+
}
|
|
1305
|
+
return 0;
|
|
1306
|
+
} catch (err) {
|
|
1307
|
+
error(err instanceof Error ? err.message : String(err));
|
|
1308
|
+
return 1;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
//#endregion
|
|
944
1312
|
//#region src/cli/index.ts
|
|
945
1313
|
const USAGE = `用法:
|
|
946
1314
|
deploy-cli 启动交互式 TUI
|
|
@@ -949,7 +1317,9 @@ const USAGE = `用法:
|
|
|
949
1317
|
deploy-cli ps 列出容器(--help 看示例)
|
|
950
1318
|
deploy-cli logs 查看容器日志(--help 看示例)
|
|
951
1319
|
deploy-cli project 项目注册表:list / add / remove(--help 看示例)
|
|
952
|
-
deploy-cli nginx 站点配置:apply / remove / list(--help
|
|
1320
|
+
deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)
|
|
1321
|
+
deploy-cli deploy 执行部署流水线(--help 看示例)
|
|
1322
|
+
deploy-cli status 项目健康状态聚合(--help 看示例)`;
|
|
953
1323
|
/** CLI 子命令分发,返回退出码 */
|
|
954
1324
|
async function main(argv) {
|
|
955
1325
|
const [command] = argv;
|
|
@@ -959,6 +1329,8 @@ async function main(argv) {
|
|
|
959
1329
|
case "logs": return await logs(argv.slice(1));
|
|
960
1330
|
case "project": return await project(argv.slice(1));
|
|
961
1331
|
case "nginx": return await nginx(argv.slice(1));
|
|
1332
|
+
case "deploy": return await deploy(argv.slice(1));
|
|
1333
|
+
case "status": return await status(argv.slice(1));
|
|
962
1334
|
case "help":
|
|
963
1335
|
case "--help":
|
|
964
1336
|
case "-h":
|