@dongnanyang/deploy-cli 0.5.2 → 0.6.0
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-BHTqsfkl.js → cli-CyS_wzyN.js} +818 -405
- 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) {
|
|
@@ -275,204 +328,29 @@ function createDocker(runner = run) {
|
|
|
275
328
|
};
|
|
276
329
|
}
|
|
277
330
|
//#endregion
|
|
278
|
-
//#region src/
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
const arg = args[i];
|
|
297
|
-
if (arg === "-h" || arg === "--help") {
|
|
298
|
-
log(USAGE$4);
|
|
299
|
-
return 0;
|
|
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);
|
|
322
|
-
}
|
|
323
|
-
if (positionals.length !== 1) {
|
|
324
|
-
error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
|
|
325
|
-
error(USAGE$4);
|
|
326
|
-
return 1;
|
|
327
|
-
}
|
|
328
|
-
const name = positionals[0];
|
|
329
|
-
const docker = options.docker ?? createDocker();
|
|
330
|
-
const logOpts = {
|
|
331
|
-
tail,
|
|
332
|
-
follow
|
|
333
|
-
};
|
|
331
|
+
//#region src/core/nginx.ts
|
|
332
|
+
/** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
|
|
333
|
+
const CONF_PREFIX = "deploy-cli-";
|
|
334
|
+
const CONF_SUFFIX = ".conf";
|
|
335
|
+
const SLUG_RE = /^[a-z0-9-]+$/;
|
|
336
|
+
/** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
|
|
337
|
+
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])?)*$/;
|
|
338
|
+
const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
|
|
339
|
+
const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
|
|
340
|
+
const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
341
|
+
const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
|
|
342
|
+
const DEFAULT_CONF_D = "/etc/nginx/conf.d";
|
|
343
|
+
/** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
|
|
344
|
+
const ACME_HOME = "/root/.acme.sh";
|
|
345
|
+
/** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
|
|
346
|
+
const ACME_RENEW_SKIP = 2;
|
|
347
|
+
/** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
|
|
348
|
+
function pathExists(path) {
|
|
334
349
|
try {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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
|
-
const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
463
|
-
const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
|
|
464
|
-
const DEFAULT_CONF_D = "/etc/nginx/conf.d";
|
|
465
|
-
/** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
|
|
466
|
-
const ACME_HOME = "/root/.acme.sh";
|
|
467
|
-
/** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
|
|
468
|
-
const ACME_RENEW_SKIP = 2;
|
|
469
|
-
/** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
|
|
470
|
-
function pathExists(path) {
|
|
471
|
-
try {
|
|
472
|
-
lstatSync(path);
|
|
473
|
-
return true;
|
|
474
|
-
} catch {
|
|
475
|
-
return false;
|
|
350
|
+
lstatSync(path);
|
|
351
|
+
return true;
|
|
352
|
+
} catch {
|
|
353
|
+
return false;
|
|
476
354
|
}
|
|
477
355
|
}
|
|
478
356
|
/** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
|
|
@@ -482,8 +360,19 @@ function validateSlug(slug) {
|
|
|
482
360
|
function validateSpec(spec) {
|
|
483
361
|
validateSlug(spec.slug);
|
|
484
362
|
if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
|
|
363
|
+
if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
|
|
485
364
|
if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
|
|
365
|
+
if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
|
|
366
|
+
if (spec.upstream !== void 0 && spec.upstream !== "") {
|
|
367
|
+
const match = spec.upstream.match(UPSTREAM_RE);
|
|
368
|
+
if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
|
|
369
|
+
}
|
|
486
370
|
if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
|
|
371
|
+
if (spec.certPath) validateAbsPath("certPath", spec.certPath);
|
|
372
|
+
if (spec.keyPath) validateAbsPath("keyPath", spec.keyPath);
|
|
373
|
+
}
|
|
374
|
+
function validateAbsPath(field, value) {
|
|
375
|
+
if (!ABS_PATH_RE.test(value)) throw new Error(`NginxSiteSpec.${field} 非法: ${JSON.stringify(value)},须为绝对路径且不含 conf 元字符与空白`);
|
|
487
376
|
}
|
|
488
377
|
/** 失败信息:命令原文 + exit 码 + stderr 摘要(包裹为 ExecError,附完整结果) */
|
|
489
378
|
function execFailure(cmd, args, result, note) {
|
|
@@ -533,121 +422,585 @@ function renderBlock(spec, withSsl) {
|
|
|
533
422
|
lines.push(" proxy_set_header X-Forwarded-Proto $scheme;");
|
|
534
423
|
lines.push(" }");
|
|
535
424
|
}
|
|
536
|
-
lines.push("}");
|
|
537
|
-
return lines.join("\n") + "\n";
|
|
425
|
+
lines.push("}");
|
|
426
|
+
return lines.join("\n") + "\n";
|
|
427
|
+
}
|
|
428
|
+
function createNginx(runner = run, paths) {
|
|
429
|
+
const resolved = paths ?? resolveNginxPaths();
|
|
430
|
+
const sitesAvailable = resolved.sitesAvailable;
|
|
431
|
+
const sitesEnabled = resolved.sitesEnabled;
|
|
432
|
+
const confName = (slug) => `${CONF_PREFIX}${slug}${CONF_SUFFIX}`;
|
|
433
|
+
const tmpName = (slug) => `.${confName(slug)}.new`;
|
|
434
|
+
const bakName = (slug) => `.${confName(slug)}.bak`;
|
|
435
|
+
/**
|
|
436
|
+
* 写盘/回滚流程:新内容写隐藏 .conf.new → 旧 conf 备份隐藏 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
|
|
437
|
+
* 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
|
|
438
|
+
*/
|
|
439
|
+
async function writeSite(slug, content) {
|
|
440
|
+
const conf = join$1(sitesAvailable, confName(slug));
|
|
441
|
+
const tmp = join$1(sitesAvailable, tmpName(slug));
|
|
442
|
+
const bak = join$1(sitesAvailable, bakName(slug));
|
|
443
|
+
writeFileSync$1(tmp, content, "utf-8");
|
|
444
|
+
const existed = pathExists(conf);
|
|
445
|
+
if (existed) renameSync(conf, bak);
|
|
446
|
+
renameSync(tmp, conf);
|
|
447
|
+
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
448
|
+
const linkCreated = link ? !pathExists(link) : false;
|
|
449
|
+
if (link && linkCreated) symlinkSync(conf, link);
|
|
450
|
+
const rollback = () => {
|
|
451
|
+
if (existed) renameSync(bak, conf);
|
|
452
|
+
else unlinkSync(conf);
|
|
453
|
+
if (link && linkCreated) unlinkSync(link);
|
|
454
|
+
};
|
|
455
|
+
let test;
|
|
456
|
+
try {
|
|
457
|
+
test = await runner("nginx", ["-t"]);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
rollback();
|
|
460
|
+
throw error;
|
|
461
|
+
}
|
|
462
|
+
if (test.code !== 0) {
|
|
463
|
+
rollback();
|
|
464
|
+
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
|
|
465
|
+
}
|
|
466
|
+
let reload;
|
|
467
|
+
try {
|
|
468
|
+
reload = await runner("nginx", ["-s", "reload"]);
|
|
469
|
+
} catch (error) {
|
|
470
|
+
throw error;
|
|
471
|
+
}
|
|
472
|
+
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
473
|
+
if (existed) unlinkSync(bak);
|
|
474
|
+
}
|
|
475
|
+
async function requestCert(domain) {
|
|
476
|
+
const acmeBin = `${ACME_HOME}/acme.sh`;
|
|
477
|
+
if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
|
|
478
|
+
const args = [
|
|
479
|
+
"--issue",
|
|
480
|
+
"--nginx",
|
|
481
|
+
"-d",
|
|
482
|
+
domain
|
|
483
|
+
];
|
|
484
|
+
const result = await runner(acmeBin, args);
|
|
485
|
+
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
|
|
486
|
+
return {
|
|
487
|
+
tool: "acme.sh",
|
|
488
|
+
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
489
|
+
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
|
|
493
|
+
const args = [
|
|
494
|
+
"--nginx",
|
|
495
|
+
"-d",
|
|
496
|
+
domain,
|
|
497
|
+
"--non-interactive",
|
|
498
|
+
"--agree-tos",
|
|
499
|
+
"--register-unsafely-without-email"
|
|
500
|
+
];
|
|
501
|
+
const result = await runner("certbot", args);
|
|
502
|
+
if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
|
|
503
|
+
return {
|
|
504
|
+
tool: "certbot",
|
|
505
|
+
certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
|
|
506
|
+
keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
|
|
510
|
+
}
|
|
511
|
+
return {
|
|
512
|
+
async applySite(spec) {
|
|
513
|
+
validateSpec(spec);
|
|
514
|
+
if (spec.ssl === "acme") {
|
|
515
|
+
await writeSite(spec.slug, renderBlock(spec, false));
|
|
516
|
+
const cert = await requestCert(spec.serverName);
|
|
517
|
+
await writeSite(spec.slug, renderBlock({
|
|
518
|
+
...spec,
|
|
519
|
+
certPath: cert.certPath,
|
|
520
|
+
keyPath: cert.keyPath
|
|
521
|
+
}, true));
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
|
|
525
|
+
},
|
|
526
|
+
async removeSite(slug) {
|
|
527
|
+
validateSlug(slug);
|
|
528
|
+
const conf = join$1(sitesAvailable, confName(slug));
|
|
529
|
+
if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
|
|
530
|
+
const bak = join$1(sitesAvailable, bakName(slug));
|
|
531
|
+
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
532
|
+
const hadLink = link ? pathExists(link) : false;
|
|
533
|
+
renameSync(conf, bak);
|
|
534
|
+
if (link && hadLink) unlinkSync(link);
|
|
535
|
+
const rollback = () => {
|
|
536
|
+
renameSync(bak, conf);
|
|
537
|
+
if (link && hadLink) symlinkSync(conf, link);
|
|
538
|
+
};
|
|
539
|
+
let test;
|
|
540
|
+
try {
|
|
541
|
+
test = await runner("nginx", ["-t"]);
|
|
542
|
+
} catch (error) {
|
|
543
|
+
rollback();
|
|
544
|
+
throw error;
|
|
545
|
+
}
|
|
546
|
+
if (test.code !== 0) {
|
|
547
|
+
rollback();
|
|
548
|
+
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
|
|
549
|
+
}
|
|
550
|
+
let reload;
|
|
551
|
+
try {
|
|
552
|
+
reload = await runner("nginx", ["-s", "reload"]);
|
|
553
|
+
} catch (error) {
|
|
554
|
+
throw error;
|
|
555
|
+
}
|
|
556
|
+
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
557
|
+
unlinkSync(bak);
|
|
558
|
+
},
|
|
559
|
+
async listSites() {
|
|
560
|
+
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();
|
|
561
|
+
},
|
|
562
|
+
requestCert
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
//#endregion
|
|
566
|
+
//#region src/core/health.ts
|
|
567
|
+
/** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
|
|
568
|
+
function describeFetchError(error, timeoutMs) {
|
|
569
|
+
const name = error?.name;
|
|
570
|
+
if (name === "TimeoutError" || name === "AbortError") return `timeout: 健康探测超时(${timeoutMs}ms)`;
|
|
571
|
+
const parts = [];
|
|
572
|
+
const seen = /* @__PURE__ */ new Set();
|
|
573
|
+
let current = error;
|
|
574
|
+
while (current instanceof Error && !seen.has(current)) {
|
|
575
|
+
seen.add(current);
|
|
576
|
+
const code = current.code;
|
|
577
|
+
parts.push(code !== void 0 ? `${current.message}(${code})` : current.message);
|
|
578
|
+
const aggregate = current;
|
|
579
|
+
current = current.cause ?? (Array.isArray(aggregate.errors) ? aggregate.errors[0] : void 0);
|
|
580
|
+
}
|
|
581
|
+
return parts.join(": ") || String(error);
|
|
582
|
+
}
|
|
583
|
+
/** HTTP 健康探测(global fetch,默认 5s 超时):2xx → ok;非 2xx/连接拒绝/超时 → ok:false 附 status 或 error */
|
|
584
|
+
async function httpProbe(url, timeoutMs = 5e3) {
|
|
585
|
+
try {
|
|
586
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
587
|
+
if (res.ok) return {
|
|
588
|
+
ok: true,
|
|
589
|
+
status: res.status
|
|
590
|
+
};
|
|
591
|
+
return {
|
|
592
|
+
ok: false,
|
|
593
|
+
status: res.status,
|
|
594
|
+
error: `HTTP ${res.status}`
|
|
595
|
+
};
|
|
596
|
+
} catch (error) {
|
|
597
|
+
return {
|
|
598
|
+
ok: false,
|
|
599
|
+
error: describeFetchError(error, timeoutMs)
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* 容器归属判定(精确名后过滤):docker `--filter name=` 是子串匹配(`app` 会误伤 `myapp`/`application`),
|
|
605
|
+
* 这里要求项目名以完整连字符分段连续出现在容器名中(兼容 compose 的 `<前缀>-<服务名>-<序号>` 命名)。
|
|
606
|
+
* 末段 `-<数字>` 是 compose 副本号而非名字成分,先剥掉再匹配——否则 `...-test-2`(test 的 2 号副本)
|
|
607
|
+
* 会误配名为 `test-2` 的项目;恰以项目名命名的容器(container_name)走全等判定不受剥离影响。
|
|
608
|
+
*/
|
|
609
|
+
function containerBelongsToProject(containerName, projectName) {
|
|
610
|
+
if (projectName === "") return false;
|
|
611
|
+
if (containerName === projectName) return true;
|
|
612
|
+
const segments = containerName.replace(/-\d+$/, "").split("-");
|
|
613
|
+
const want = projectName.split("-");
|
|
614
|
+
for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
|
|
615
|
+
return false;
|
|
616
|
+
}
|
|
617
|
+
/** 项目容器集合:docker name 过滤(子串)+ 精确名后过滤,含已停止容器 */
|
|
618
|
+
async function findProjectContainers(docker, projectName) {
|
|
619
|
+
return (await docker.listContainers({
|
|
620
|
+
all: true,
|
|
621
|
+
name: projectName
|
|
622
|
+
})).filter((c) => containerBelongsToProject(c.name, projectName));
|
|
623
|
+
}
|
|
624
|
+
/** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
|
|
625
|
+
async function probeNginxSite(slug, runner) {
|
|
626
|
+
try {
|
|
627
|
+
return (await createNginx(runner).listSites()).includes(slug);
|
|
628
|
+
} catch {
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
/** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位 */
|
|
633
|
+
async function checkProjectHealth(project, opts) {
|
|
634
|
+
const runner = opts.runner ?? run;
|
|
635
|
+
const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name);
|
|
636
|
+
const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
|
|
637
|
+
const nginxPresent = await probeNginxSite(project.name, runner);
|
|
638
|
+
return {
|
|
639
|
+
name: project.name,
|
|
640
|
+
containers,
|
|
641
|
+
http,
|
|
642
|
+
nginxPresent
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
//#endregion
|
|
646
|
+
//#region src/core/deploy.ts
|
|
647
|
+
/** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
|
|
648
|
+
function buildSpec(d, noSsl) {
|
|
649
|
+
if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
|
|
650
|
+
const ssl = noSsl ? "none" : d.nginx.ssl;
|
|
651
|
+
if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
|
|
652
|
+
const spec = {
|
|
653
|
+
slug: d.name,
|
|
654
|
+
serverName: d.nginx.domain,
|
|
655
|
+
ssl
|
|
656
|
+
};
|
|
657
|
+
if (d.type === "static") spec.root = d.root;
|
|
658
|
+
else {
|
|
659
|
+
if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
|
|
660
|
+
spec.upstream = d.nginx.upstream;
|
|
661
|
+
}
|
|
662
|
+
return spec;
|
|
663
|
+
}
|
|
664
|
+
/** 非零退出码 → 抛失败信息(命令原文 + stderr 摘要,可附提示) */
|
|
665
|
+
function expectOk(result, cmd, args, hint) {
|
|
666
|
+
if (result.code !== 0) throw new Error(`${execFailureMessage(cmd, args, result)}${hint ? `;${hint}` : ""}`);
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* 部署流水线(失败即停):update(git pull) → pre → build → up → nginx → health → post(R10 上线后钩子)。
|
|
670
|
+
* 步骤跳过口径:update 仅 deploy.update==='git-pull' 时执行(缺省/none 跳过);pre/post 无钩子跳过;
|
|
671
|
+
* static 型跳过 build/up(自定义 build 也不跑);image 型无自定义 build 跳过 build(compose 文件在 up 步才生成);
|
|
672
|
+
* nginx 在 applyNginx!==false 且有 nginx 配置时执行;health 在有 healthUrl 或非 static 型时执行。
|
|
673
|
+
* 某步失败(含 Runner reject:spawn 失败/超时)→ 该步 fail 事件 + 后续步骤绝不执行。
|
|
674
|
+
*/
|
|
675
|
+
async function runDeploy(project, opts) {
|
|
676
|
+
const runner = opts.runner ?? run;
|
|
677
|
+
const docker = opts.docker ?? createDocker(runner);
|
|
678
|
+
const emit = opts.onEvent;
|
|
679
|
+
/** 包裹单步:start → fn → ok;fn 抛错 → fail 事件 + 停(返回结果由调用方 return) */
|
|
680
|
+
async function step(name, startLine, fn) {
|
|
681
|
+
emit({
|
|
682
|
+
step: name,
|
|
683
|
+
status: "start",
|
|
684
|
+
line: startLine
|
|
685
|
+
});
|
|
686
|
+
try {
|
|
687
|
+
await fn();
|
|
688
|
+
} catch (error) {
|
|
689
|
+
const line = error instanceof Error ? error.message : String(error);
|
|
690
|
+
emit({
|
|
691
|
+
step: name,
|
|
692
|
+
status: "fail",
|
|
693
|
+
line
|
|
694
|
+
});
|
|
695
|
+
return {
|
|
696
|
+
ok: false,
|
|
697
|
+
failedStep: name
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
emit({
|
|
701
|
+
step: name,
|
|
702
|
+
status: "ok"
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
const gitArgs = [
|
|
706
|
+
"-C",
|
|
707
|
+
opts.cwd,
|
|
708
|
+
"pull"
|
|
709
|
+
];
|
|
710
|
+
if (project.deploy?.update === "git-pull") {
|
|
711
|
+
const stopped = await step("update", `git ${gitArgs.join(" ")}`, async () => {
|
|
712
|
+
expectOk(await runner("git", gitArgs), "git", gitArgs, "非 git 目录或拉取失败;如无需自动更新请改 deploy.update: none");
|
|
713
|
+
});
|
|
714
|
+
if (stopped) return stopped;
|
|
715
|
+
}
|
|
716
|
+
const pre = project.deploy?.pre ?? [];
|
|
717
|
+
if (pre.length > 0) {
|
|
718
|
+
const stopped = await step("pre", void 0, async () => {
|
|
719
|
+
for (const cmd of pre) expectOk(await runner("bash", ["-c", cmd]), "bash", ["-c", cmd]);
|
|
720
|
+
});
|
|
721
|
+
if (stopped) return stopped;
|
|
722
|
+
}
|
|
723
|
+
const composeFile = project.composeFile ?? "docker-compose.yml";
|
|
724
|
+
const customBuild = project.deploy?.build;
|
|
725
|
+
if (project.type !== "static" && (customBuild !== void 0 || project.type === "compose")) {
|
|
726
|
+
const stopped = await step("build", customBuild ?? `docker compose -f ${composeFile} build`, async () => {
|
|
727
|
+
if (customBuild !== void 0) expectOk(await runner("bash", ["-c", customBuild]), "bash", ["-c", customBuild]);
|
|
728
|
+
else expectOk(await docker.composeBuild(opts.cwd, composeFile), "docker", [
|
|
729
|
+
"compose",
|
|
730
|
+
"-f",
|
|
731
|
+
composeFile,
|
|
732
|
+
"build"
|
|
733
|
+
]);
|
|
734
|
+
});
|
|
735
|
+
if (stopped) return stopped;
|
|
736
|
+
}
|
|
737
|
+
if (project.type !== "static") {
|
|
738
|
+
const upFile = project.type === "image" ? "docker-compose.yml" : composeFile;
|
|
739
|
+
const stopped = await step("up", `docker compose -f ${upFile} up -d`, async () => {
|
|
740
|
+
if (project.type === "image") writeFileSync$1(resolve$1(opts.cwd, upFile), generateCompose(project), "utf-8");
|
|
741
|
+
expectOk(await docker.composeUp(opts.cwd, upFile), "docker", [
|
|
742
|
+
"compose",
|
|
743
|
+
"-f",
|
|
744
|
+
upFile,
|
|
745
|
+
"up",
|
|
746
|
+
"-d"
|
|
747
|
+
]);
|
|
748
|
+
});
|
|
749
|
+
if (stopped) return stopped;
|
|
750
|
+
}
|
|
751
|
+
if ((opts.applyNginx ?? true) && project.nginx) {
|
|
752
|
+
const stopped = await step("nginx", void 0, async () => {
|
|
753
|
+
await (opts.nginx ?? createNginx(runner)).applySite(buildSpec(project, false));
|
|
754
|
+
});
|
|
755
|
+
if (stopped) return stopped;
|
|
756
|
+
}
|
|
757
|
+
if (project.healthUrl !== void 0 || project.type !== "static") {
|
|
758
|
+
const stopped = await step("health", project.healthUrl, async () => {
|
|
759
|
+
if (project.healthUrl) {
|
|
760
|
+
const probe = await httpProbe(project.healthUrl);
|
|
761
|
+
if (!probe.ok) throw new Error(`健康探测失败: ${project.healthUrl}: ${probe.error ?? `HTTP ${probe.status}`}`);
|
|
762
|
+
}
|
|
763
|
+
if (project.type !== "static") {
|
|
764
|
+
if (!(await findProjectContainers(docker, project.name)).some((c) => c.state === "running")) throw new Error(`无运行中容器: ${project.name}(docker ps 未见 running 状态容器)`);
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
if (stopped) return stopped;
|
|
768
|
+
}
|
|
769
|
+
const post = project.deploy?.post ?? [];
|
|
770
|
+
if (post.length > 0) {
|
|
771
|
+
const stopped = await step("post", void 0, async () => {
|
|
772
|
+
for (const cmd of post) expectOk(await runner("bash", ["-c", cmd]), "bash", ["-c", cmd]);
|
|
773
|
+
});
|
|
774
|
+
if (stopped) return stopped;
|
|
775
|
+
}
|
|
776
|
+
return { ok: true };
|
|
777
|
+
}
|
|
778
|
+
//#endregion
|
|
779
|
+
//#region src/cli/commands/deploy.ts
|
|
780
|
+
const USAGE$6 = `用法: deploy-cli deploy <project> [--yes] [--no-nginx]
|
|
781
|
+
|
|
782
|
+
选项:
|
|
783
|
+
--yes 非交互环境(无 TTY)下确认执行部署
|
|
784
|
+
--no-nginx 跳过 nginx 站点配置步骤
|
|
785
|
+
|
|
786
|
+
流水线: update(git pull) → pre 钩子 → build → up → nginx → health → post 钩子(失败即停)
|
|
787
|
+
|
|
788
|
+
示例:
|
|
789
|
+
deploy-cli deploy my-app
|
|
790
|
+
deploy-cli deploy my-app --yes
|
|
791
|
+
deploy-cli deploy my-app --yes --no-nginx`;
|
|
792
|
+
/** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail=✗+失败信息 */
|
|
793
|
+
function formatEvent(e) {
|
|
794
|
+
if (e.status === "ok") return `[${e.step}] ✓`;
|
|
795
|
+
if (e.status === "fail") return `[${e.step}] ✗ ${e.line ?? ""}`;
|
|
796
|
+
return `[${e.step}] ${e.line ?? "开始"}`;
|
|
797
|
+
}
|
|
798
|
+
/** 部署流水线命令:deploy <project> [--yes] [--no-nginx];返回退出码 */
|
|
799
|
+
async function deploy(args, options = {}) {
|
|
800
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
801
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
802
|
+
const load = options.load ?? loadConfig;
|
|
803
|
+
let yes = false;
|
|
804
|
+
let noNginx = false;
|
|
805
|
+
const positional = [];
|
|
806
|
+
for (const arg of args) {
|
|
807
|
+
if (arg === "-h" || arg === "--help") {
|
|
808
|
+
log(USAGE$6);
|
|
809
|
+
return 0;
|
|
810
|
+
}
|
|
811
|
+
if (arg === "--yes") {
|
|
812
|
+
yes = true;
|
|
813
|
+
continue;
|
|
814
|
+
}
|
|
815
|
+
if (arg === "--no-nginx") {
|
|
816
|
+
noNginx = true;
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (arg.startsWith("-")) {
|
|
820
|
+
error(`未知参数: ${arg}`);
|
|
821
|
+
error(USAGE$6);
|
|
822
|
+
return 1;
|
|
823
|
+
}
|
|
824
|
+
positional.push(arg);
|
|
825
|
+
}
|
|
826
|
+
const name = positional[0];
|
|
827
|
+
if (name === void 0 || positional.length > 1) {
|
|
828
|
+
error("deploy 需要且仅需要一个 <project> 参数");
|
|
829
|
+
error(USAGE$6);
|
|
830
|
+
return 1;
|
|
831
|
+
}
|
|
832
|
+
if (!(options.isTTY ?? Boolean(process.stdin.isTTY)) && !yes) {
|
|
833
|
+
error("非交互环境(无 TTY)下部署必须显式确认:请加 --yes(deploy-cli deploy <project> --yes)");
|
|
834
|
+
return 1;
|
|
835
|
+
}
|
|
836
|
+
try {
|
|
837
|
+
const row = listProjects(load()).find((r) => r.name === name);
|
|
838
|
+
if (!row) {
|
|
839
|
+
error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
|
|
840
|
+
return 1;
|
|
841
|
+
}
|
|
842
|
+
if (!row.config) {
|
|
843
|
+
error(`项目配置不可用: ${name}: ${row.error ?? ""}`);
|
|
844
|
+
return 1;
|
|
845
|
+
}
|
|
846
|
+
const result = await runDeploy(row.config, {
|
|
847
|
+
cwd: expandPath(row.path),
|
|
848
|
+
onEvent: (e) => log(formatEvent(e)),
|
|
849
|
+
applyNginx: !noNginx,
|
|
850
|
+
runner: options.runner,
|
|
851
|
+
docker: options.docker,
|
|
852
|
+
nginx: options.nginx
|
|
853
|
+
});
|
|
854
|
+
if (!result.ok) {
|
|
855
|
+
error(`部署失败: ${name}(步骤: ${result.failedStep})`);
|
|
856
|
+
return 1;
|
|
857
|
+
}
|
|
858
|
+
log(`部署完成: ${name}`);
|
|
859
|
+
return 0;
|
|
860
|
+
} catch (err) {
|
|
861
|
+
error(err instanceof Error ? err.message : String(err));
|
|
862
|
+
return 1;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/cli/commands/doctor.ts
|
|
867
|
+
const SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
868
|
+
const MIN_NODE_MAJOR = 20;
|
|
869
|
+
/** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
|
|
870
|
+
const PROBE_TIMEOUT_MS = 1e4;
|
|
871
|
+
async function probe(runner, cmd, args) {
|
|
872
|
+
try {
|
|
873
|
+
const result = await runner(cmd, args, { timeoutMs: PROBE_TIMEOUT_MS });
|
|
874
|
+
const detail = (result.code === 0 ? result.stdout || result.stderr : result.stderr || result.stdout).trim().split("\n")[0] ?? "";
|
|
875
|
+
return {
|
|
876
|
+
ok: result.code === 0,
|
|
877
|
+
detail
|
|
878
|
+
};
|
|
879
|
+
} catch (error) {
|
|
880
|
+
return {
|
|
881
|
+
ok: false,
|
|
882
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
function defaultCanWrite(path) {
|
|
887
|
+
try {
|
|
888
|
+
accessSync(path, constants.W_OK);
|
|
889
|
+
return true;
|
|
890
|
+
} catch {
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
/** 环境自检:返回退出码(存在失败项 1,否则 0;警告不影响退出码) */
|
|
895
|
+
async function doctor(options = {}) {
|
|
896
|
+
const runner = options.runner ?? run;
|
|
897
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
898
|
+
const canWrite = options.canWrite ?? defaultCanWrite;
|
|
899
|
+
let failed = false;
|
|
900
|
+
const pass = (line) => log(`[✓] ${line}`);
|
|
901
|
+
const fail = (line) => {
|
|
902
|
+
failed = true;
|
|
903
|
+
log(`[✗] ${line}`);
|
|
904
|
+
};
|
|
905
|
+
const warn = (line) => log(`[警告] ${line}`);
|
|
906
|
+
log("deploy-cli doctor 环境自检");
|
|
907
|
+
if (Number(process.versions.node.split(".")[0]) >= MIN_NODE_MAJOR) pass(`Node.js v${process.versions.node}`);
|
|
908
|
+
else fail(`Node.js v${process.versions.node} 过低,需要 >= ${MIN_NODE_MAJOR}`);
|
|
909
|
+
const dockerVersion = await probe(runner, "docker", ["--version"]);
|
|
910
|
+
if (!dockerVersion.ok) fail(`docker 不可用(docker --version 失败): ${dockerVersion.detail}`);
|
|
911
|
+
else {
|
|
912
|
+
pass(`docker 可用(${dockerVersion.detail})`);
|
|
913
|
+
const dockerInfo = await probe(runner, "docker", ["info"]);
|
|
914
|
+
if (dockerInfo.ok) pass("docker daemon 运行中");
|
|
915
|
+
else fail(`docker daemon 未运行(docker info 失败): ${dockerInfo.detail}`);
|
|
916
|
+
}
|
|
917
|
+
const nginx = await probe(runner, "nginx", ["-v"]);
|
|
918
|
+
if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
|
|
919
|
+
else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
|
|
920
|
+
if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
|
|
921
|
+
else fail(`${SITES_AVAILABLE} 不可写`);
|
|
922
|
+
const acme = await probe(runner, "acme.sh", ["--version"]);
|
|
923
|
+
const certbot = await probe(runner, "certbot", ["--version"]);
|
|
924
|
+
const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
|
|
925
|
+
if (certTools) pass(`证书工具可用(${certTools})`);
|
|
926
|
+
else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
|
|
927
|
+
return failed ? 1 : 0;
|
|
538
928
|
}
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
if (test.code !== 0) {
|
|
563
|
-
if (existed) renameSync(bak, conf);
|
|
564
|
-
else unlinkSync(conf);
|
|
565
|
-
if (link && linkCreated) unlinkSync(link);
|
|
566
|
-
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/cli/commands/logs.ts
|
|
931
|
+
const USAGE$5 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
|
|
932
|
+
|
|
933
|
+
选项:
|
|
934
|
+
--tail <行数> 只显示最后 N 行(默认全部)
|
|
935
|
+
--follow 持续跟随日志输出(Ctrl-C 退出)
|
|
936
|
+
|
|
937
|
+
示例:
|
|
938
|
+
deploy-cli logs deploy-cli-test-echo --tail 5
|
|
939
|
+
deploy-cli logs my-app --follow`;
|
|
940
|
+
/** 查看容器日志,逐行输出到 stdout;返回退出码 */
|
|
941
|
+
async function logs(args, options = {}) {
|
|
942
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
943
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
944
|
+
let tail;
|
|
945
|
+
let follow = false;
|
|
946
|
+
const positionals = [];
|
|
947
|
+
for (let i = 0; i < args.length; i++) {
|
|
948
|
+
const arg = args[i];
|
|
949
|
+
if (arg === "-h" || arg === "--help") {
|
|
950
|
+
log(USAGE$5);
|
|
951
|
+
return 0;
|
|
567
952
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
"-d",
|
|
579
|
-
domain
|
|
580
|
-
];
|
|
581
|
-
const result = await runner(acmeBin, args);
|
|
582
|
-
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
|
|
583
|
-
return {
|
|
584
|
-
tool: "acme.sh",
|
|
585
|
-
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
586
|
-
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
587
|
-
};
|
|
953
|
+
if (arg === "--tail") {
|
|
954
|
+
const value = args[++i];
|
|
955
|
+
const parsed = Number(value);
|
|
956
|
+
if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
|
|
957
|
+
error(`--tail 需要非负整数参数: ${value ?? ""}`);
|
|
958
|
+
error(USAGE$5);
|
|
959
|
+
return 1;
|
|
960
|
+
}
|
|
961
|
+
tail = parsed;
|
|
962
|
+
continue;
|
|
588
963
|
}
|
|
589
|
-
if (
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
"-d",
|
|
593
|
-
domain,
|
|
594
|
-
"--non-interactive",
|
|
595
|
-
"--agree-tos",
|
|
596
|
-
"--register-unsafely-without-email"
|
|
597
|
-
];
|
|
598
|
-
const result = await runner("certbot", args);
|
|
599
|
-
if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
|
|
600
|
-
return {
|
|
601
|
-
tool: "certbot",
|
|
602
|
-
certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
|
|
603
|
-
keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
|
|
604
|
-
};
|
|
964
|
+
if (arg === "--follow") {
|
|
965
|
+
follow = true;
|
|
966
|
+
continue;
|
|
605
967
|
}
|
|
606
|
-
|
|
968
|
+
if (arg.startsWith("-")) {
|
|
969
|
+
error(`未知参数: ${arg}`);
|
|
970
|
+
error(USAGE$5);
|
|
971
|
+
return 1;
|
|
972
|
+
}
|
|
973
|
+
positionals.push(arg);
|
|
607
974
|
}
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
}, true));
|
|
619
|
-
return;
|
|
620
|
-
}
|
|
621
|
-
await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
|
|
622
|
-
},
|
|
623
|
-
async removeSite(slug) {
|
|
624
|
-
validateSlug(slug);
|
|
625
|
-
const conf = join$1(sitesAvailable, confName(slug));
|
|
626
|
-
if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
|
|
627
|
-
const bak = join$1(sitesAvailable, bakName(slug));
|
|
628
|
-
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
629
|
-
const hadLink = link ? pathExists(link) : false;
|
|
630
|
-
renameSync(conf, bak);
|
|
631
|
-
if (link && hadLink) unlinkSync(link);
|
|
632
|
-
const test = await runner("nginx", ["-t"]);
|
|
633
|
-
if (test.code !== 0) {
|
|
634
|
-
renameSync(bak, conf);
|
|
635
|
-
if (link && hadLink) symlinkSync(conf, link);
|
|
636
|
-
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
|
|
637
|
-
}
|
|
638
|
-
const reload = await runner("nginx", ["-s", "reload"]);
|
|
639
|
-
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
640
|
-
unlinkSync(bak);
|
|
641
|
-
},
|
|
642
|
-
async listSites() {
|
|
643
|
-
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();
|
|
644
|
-
},
|
|
645
|
-
requestCert
|
|
975
|
+
if (positionals.length !== 1) {
|
|
976
|
+
error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
|
|
977
|
+
error(USAGE$5);
|
|
978
|
+
return 1;
|
|
979
|
+
}
|
|
980
|
+
const name = positionals[0];
|
|
981
|
+
const docker = options.docker ?? createDocker();
|
|
982
|
+
const logOpts = {
|
|
983
|
+
tail,
|
|
984
|
+
follow
|
|
646
985
|
};
|
|
986
|
+
try {
|
|
987
|
+
const result = await docker.logs(name, {
|
|
988
|
+
...logOpts,
|
|
989
|
+
onLine: (line) => log(line)
|
|
990
|
+
});
|
|
991
|
+
if (result.code !== 0) {
|
|
992
|
+
error(execFailureMessage("docker", logsArgs(name, logOpts), result));
|
|
993
|
+
return 1;
|
|
994
|
+
}
|
|
995
|
+
return 0;
|
|
996
|
+
} catch (err) {
|
|
997
|
+
error(err instanceof Error ? err.message : String(err));
|
|
998
|
+
return 1;
|
|
999
|
+
}
|
|
647
1000
|
}
|
|
648
1001
|
//#endregion
|
|
649
1002
|
//#region src/cli/commands/nginx.ts
|
|
650
|
-
const USAGE$
|
|
1003
|
+
const USAGE$4 = `用法: deploy-cli nginx <apply|remove|list> [参数]
|
|
651
1004
|
|
|
652
1005
|
子命令:
|
|
653
1006
|
apply <project> [--no-ssl] 按 deploy.yaml 的 nginx 配置写入站点 conf 并启用
|
|
@@ -659,23 +1012,6 @@ const USAGE$3 = `用法: deploy-cli nginx <apply|remove|list> [参数]
|
|
|
659
1012
|
deploy-cli nginx apply my-app --no-ssl
|
|
660
1013
|
deploy-cli nginx remove my-app
|
|
661
1014
|
deploy-cli nginx list`;
|
|
662
|
-
/** deploy.yaml → NginxSiteSpec(slug=项目 name);custom 型缺 certPath/keyPath 来源,暂不支持 */
|
|
663
|
-
function buildSpec(d, noSsl) {
|
|
664
|
-
if (!d.nginx) throw new Error(`项目 ${d.name} 未配置 nginx(deploy.yaml 缺 nginx 段)`);
|
|
665
|
-
const ssl = noSsl ? "none" : d.nginx.ssl;
|
|
666
|
-
if (ssl === "custom") throw new Error("ssl:custom 需要 certPath/keyPath,deploy.yaml 暂不支持;请改用 ssl:acme 或 ssl:none");
|
|
667
|
-
const spec = {
|
|
668
|
-
slug: d.name,
|
|
669
|
-
serverName: d.nginx.domain,
|
|
670
|
-
ssl
|
|
671
|
-
};
|
|
672
|
-
if (d.type === "static") spec.root = d.root;
|
|
673
|
-
else {
|
|
674
|
-
if (!d.nginx.upstream) throw new Error(`项目 ${d.name} 为 ${d.type} 型,缺少 nginx.upstream(代理目标,如 127.0.0.1:3000)`);
|
|
675
|
-
spec.upstream = d.nginx.upstream;
|
|
676
|
-
}
|
|
677
|
-
return spec;
|
|
678
|
-
}
|
|
679
1015
|
/** nginx 站点管理:apply / remove / list;返回退出码 */
|
|
680
1016
|
async function nginx(args, options = {}) {
|
|
681
1017
|
const log = options.log ?? ((line) => console.log(line));
|
|
@@ -684,12 +1020,12 @@ async function nginx(args, options = {}) {
|
|
|
684
1020
|
const api = options.api ?? createNginx();
|
|
685
1021
|
const [sub, ...rest] = args;
|
|
686
1022
|
if (sub === "-h" || sub === "--help") {
|
|
687
|
-
log(USAGE$
|
|
1023
|
+
log(USAGE$4);
|
|
688
1024
|
return 0;
|
|
689
1025
|
}
|
|
690
1026
|
if (sub === void 0) {
|
|
691
1027
|
error("缺少子命令");
|
|
692
|
-
error(USAGE$
|
|
1028
|
+
error(USAGE$4);
|
|
693
1029
|
return 1;
|
|
694
1030
|
}
|
|
695
1031
|
try {
|
|
@@ -698,14 +1034,14 @@ async function nginx(args, options = {}) {
|
|
|
698
1034
|
const unknown = rest.filter((a) => a.startsWith("-") && a !== "--no-ssl");
|
|
699
1035
|
if (unknown.length > 0) {
|
|
700
1036
|
error(`未知参数: ${unknown.join(" ")}`);
|
|
701
|
-
error(USAGE$
|
|
1037
|
+
error(USAGE$4);
|
|
702
1038
|
return 1;
|
|
703
1039
|
}
|
|
704
1040
|
const positional = rest.filter((a) => !a.startsWith("-"));
|
|
705
1041
|
const name = positional[0];
|
|
706
1042
|
if (name === void 0 || positional.length > 1) {
|
|
707
1043
|
error("apply 需要且仅需要一个 <project> 参数");
|
|
708
|
-
error(USAGE$
|
|
1044
|
+
error(USAGE$4);
|
|
709
1045
|
return 1;
|
|
710
1046
|
}
|
|
711
1047
|
const noSsl = rest.includes("--no-ssl");
|
|
@@ -727,7 +1063,7 @@ async function nginx(args, options = {}) {
|
|
|
727
1063
|
const name = rest[0];
|
|
728
1064
|
if (name === void 0 || rest.length > 1) {
|
|
729
1065
|
error("remove 需要且仅需要一个 <project> 参数");
|
|
730
|
-
error(USAGE$
|
|
1066
|
+
error(USAGE$4);
|
|
731
1067
|
return 1;
|
|
732
1068
|
}
|
|
733
1069
|
await api.removeSite(name);
|
|
@@ -737,7 +1073,7 @@ async function nginx(args, options = {}) {
|
|
|
737
1073
|
case "list": {
|
|
738
1074
|
if (rest.length > 0) {
|
|
739
1075
|
error(`未知参数: ${rest.join(" ")}`);
|
|
740
|
-
error(USAGE$
|
|
1076
|
+
error(USAGE$4);
|
|
741
1077
|
return 1;
|
|
742
1078
|
}
|
|
743
1079
|
const sites = await api.listSites();
|
|
@@ -747,7 +1083,7 @@ async function nginx(args, options = {}) {
|
|
|
747
1083
|
}
|
|
748
1084
|
default:
|
|
749
1085
|
error(`未知子命令: ${sub}`);
|
|
750
|
-
error(USAGE$
|
|
1086
|
+
error(USAGE$4);
|
|
751
1087
|
return 1;
|
|
752
1088
|
}
|
|
753
1089
|
} catch (err) {
|
|
@@ -757,7 +1093,7 @@ async function nginx(args, options = {}) {
|
|
|
757
1093
|
}
|
|
758
1094
|
//#endregion
|
|
759
1095
|
//#region src/cli/commands/project.ts
|
|
760
|
-
const USAGE$
|
|
1096
|
+
const USAGE$3 = `用法: deploy-cli project <list|add|remove> [参数]
|
|
761
1097
|
|
|
762
1098
|
子命令:
|
|
763
1099
|
list 列出已注册项目(NAME/PATH/TYPE/ERROR)
|
|
@@ -776,12 +1112,12 @@ async function project(args, options = {}) {
|
|
|
776
1112
|
const save = options.save ?? saveConfig;
|
|
777
1113
|
const [sub, ...rest] = args;
|
|
778
1114
|
if (sub === "-h" || sub === "--help") {
|
|
779
|
-
log(USAGE$
|
|
1115
|
+
log(USAGE$3);
|
|
780
1116
|
return 0;
|
|
781
1117
|
}
|
|
782
1118
|
if (sub === void 0) {
|
|
783
1119
|
error("缺少子命令");
|
|
784
|
-
error(USAGE$
|
|
1120
|
+
error(USAGE$3);
|
|
785
1121
|
return 1;
|
|
786
1122
|
}
|
|
787
1123
|
try {
|
|
@@ -789,7 +1125,7 @@ async function project(args, options = {}) {
|
|
|
789
1125
|
case "list": {
|
|
790
1126
|
if (rest.length > 0) {
|
|
791
1127
|
error(`未知参数: ${rest.join(" ")}`);
|
|
792
|
-
error(USAGE$
|
|
1128
|
+
error(USAGE$3);
|
|
793
1129
|
return 1;
|
|
794
1130
|
}
|
|
795
1131
|
const rows = listProjects(load());
|
|
@@ -801,7 +1137,7 @@ async function project(args, options = {}) {
|
|
|
801
1137
|
const raw = rest[0];
|
|
802
1138
|
if (raw === void 0 || rest.length > 1) {
|
|
803
1139
|
error("add 需要且仅需要一个 <path> 参数");
|
|
804
|
-
error(USAGE$
|
|
1140
|
+
error(USAGE$3);
|
|
805
1141
|
return 1;
|
|
806
1142
|
}
|
|
807
1143
|
const dir = expandPath(raw);
|
|
@@ -815,7 +1151,7 @@ async function project(args, options = {}) {
|
|
|
815
1151
|
const name = rest[0];
|
|
816
1152
|
if (name === void 0 || rest.length > 1) {
|
|
817
1153
|
error("remove 需要且仅需要一个 <name> 参数");
|
|
818
|
-
error(USAGE$
|
|
1154
|
+
error(USAGE$3);
|
|
819
1155
|
return 1;
|
|
820
1156
|
}
|
|
821
1157
|
save(removeProject(load(), name));
|
|
@@ -824,7 +1160,7 @@ async function project(args, options = {}) {
|
|
|
824
1160
|
}
|
|
825
1161
|
default:
|
|
826
1162
|
error(`未知子命令: ${sub}`);
|
|
827
|
-
error(USAGE$
|
|
1163
|
+
error(USAGE$3);
|
|
828
1164
|
return 1;
|
|
829
1165
|
}
|
|
830
1166
|
} catch (err) {
|
|
@@ -834,7 +1170,7 @@ async function project(args, options = {}) {
|
|
|
834
1170
|
}
|
|
835
1171
|
//#endregion
|
|
836
1172
|
//#region src/cli/commands/ps.ts
|
|
837
|
-
const USAGE$
|
|
1173
|
+
const USAGE$2 = `用法: deploy-cli ps [--all] [--project <项目名>]
|
|
838
1174
|
|
|
839
1175
|
选项:
|
|
840
1176
|
--all 含已停止的容器
|
|
@@ -853,7 +1189,7 @@ async function ps(args, options = {}) {
|
|
|
853
1189
|
for (let i = 0; i < args.length; i++) {
|
|
854
1190
|
const arg = args[i];
|
|
855
1191
|
if (arg === "-h" || arg === "--help") {
|
|
856
|
-
log(USAGE$
|
|
1192
|
+
log(USAGE$2);
|
|
857
1193
|
return 0;
|
|
858
1194
|
}
|
|
859
1195
|
if (arg === "--all") {
|
|
@@ -864,14 +1200,14 @@ async function ps(args, options = {}) {
|
|
|
864
1200
|
const value = args[++i];
|
|
865
1201
|
if (value === void 0 || value === "") {
|
|
866
1202
|
error("缺少 --project 的项目名参数");
|
|
867
|
-
error(USAGE$
|
|
1203
|
+
error(USAGE$2);
|
|
868
1204
|
return 1;
|
|
869
1205
|
}
|
|
870
1206
|
projectName = value;
|
|
871
1207
|
continue;
|
|
872
1208
|
}
|
|
873
1209
|
error(`未知参数: ${arg}`);
|
|
874
|
-
error(USAGE$
|
|
1210
|
+
error(USAGE$2);
|
|
875
1211
|
return 1;
|
|
876
1212
|
}
|
|
877
1213
|
const docker = options.docker ?? createDocker();
|
|
@@ -898,6 +1234,79 @@ async function ps(args, options = {}) {
|
|
|
898
1234
|
}
|
|
899
1235
|
}
|
|
900
1236
|
//#endregion
|
|
1237
|
+
//#region src/cli/commands/status.ts
|
|
1238
|
+
const USAGE$1 = `用法: deploy-cli status [project]
|
|
1239
|
+
|
|
1240
|
+
聚合项目健康状态(容器 / HTTP 探测 / nginx conf):
|
|
1241
|
+
CONTAINERS 运行中/总数 容器(含已停止)
|
|
1242
|
+
HTTP healthUrl 探测结果(2xx=状态码,失败=FAIL,未配置=-)
|
|
1243
|
+
NGINX deploy-cli 站点 conf 在位(✓ 在 / ✗ 不在 / - 未知)
|
|
1244
|
+
|
|
1245
|
+
示例:
|
|
1246
|
+
deploy-cli status
|
|
1247
|
+
deploy-cli status my-app`;
|
|
1248
|
+
/** ProjectHealth → 表格行(CONTAINERS/HTTP/NGINX 三列) */
|
|
1249
|
+
function formatRow(health) {
|
|
1250
|
+
const total = health.containers.length;
|
|
1251
|
+
const running = health.containers.filter((c) => c.state === "running").length;
|
|
1252
|
+
const containers = total === 0 ? "无容器" : `${running}/${total} running`;
|
|
1253
|
+
const http = health.http === void 0 ? "-" : health.http.ok ? String(health.http.status) : "FAIL";
|
|
1254
|
+
const nginx = health.nginxPresent === void 0 ? "-" : health.nginxPresent ? "✓" : "✗";
|
|
1255
|
+
return `${health.name}\t${containers}\t${http}\t${nginx}`;
|
|
1256
|
+
}
|
|
1257
|
+
/** 状态聚合命令:status [project];返回退出码 */
|
|
1258
|
+
async function status(args, options = {}) {
|
|
1259
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
1260
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
1261
|
+
const load = options.load ?? loadConfig;
|
|
1262
|
+
const positional = [];
|
|
1263
|
+
for (const arg of args) {
|
|
1264
|
+
if (arg === "-h" || arg === "--help") {
|
|
1265
|
+
log(USAGE$1);
|
|
1266
|
+
return 0;
|
|
1267
|
+
}
|
|
1268
|
+
if (arg.startsWith("-")) {
|
|
1269
|
+
error(`未知参数: ${arg}`);
|
|
1270
|
+
error(USAGE$1);
|
|
1271
|
+
return 1;
|
|
1272
|
+
}
|
|
1273
|
+
positional.push(arg);
|
|
1274
|
+
}
|
|
1275
|
+
if (positional.length > 1) {
|
|
1276
|
+
error("status 至多接受一个 [project] 参数");
|
|
1277
|
+
error(USAGE$1);
|
|
1278
|
+
return 1;
|
|
1279
|
+
}
|
|
1280
|
+
try {
|
|
1281
|
+
let rows;
|
|
1282
|
+
if (positional.length === 1) {
|
|
1283
|
+
const name = positional[0];
|
|
1284
|
+
const row = listProjects(load()).find((r) => r.name === name);
|
|
1285
|
+
if (!row) {
|
|
1286
|
+
error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
|
|
1287
|
+
return 1;
|
|
1288
|
+
}
|
|
1289
|
+
rows = [row];
|
|
1290
|
+
} else rows = listProjects(load());
|
|
1291
|
+
log("NAME CONTAINERS HTTP NGINX");
|
|
1292
|
+
for (const row of rows) {
|
|
1293
|
+
if (!row.config) {
|
|
1294
|
+
error(`项目配置不可用: ${row.name}: ${row.error ?? ""}`);
|
|
1295
|
+
log(`${row.name}\t配置不可用\t-\t-`);
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
log(formatRow(await checkProjectHealth(row.config, {
|
|
1299
|
+
docker: options.docker,
|
|
1300
|
+
runner: options.runner
|
|
1301
|
+
})));
|
|
1302
|
+
}
|
|
1303
|
+
return 0;
|
|
1304
|
+
} catch (err) {
|
|
1305
|
+
error(err instanceof Error ? err.message : String(err));
|
|
1306
|
+
return 1;
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
//#endregion
|
|
901
1310
|
//#region src/cli/index.ts
|
|
902
1311
|
const USAGE = `用法:
|
|
903
1312
|
deploy-cli 启动交互式 TUI
|
|
@@ -906,7 +1315,9 @@ const USAGE = `用法:
|
|
|
906
1315
|
deploy-cli ps 列出容器(--help 看示例)
|
|
907
1316
|
deploy-cli logs 查看容器日志(--help 看示例)
|
|
908
1317
|
deploy-cli project 项目注册表:list / add / remove(--help 看示例)
|
|
909
|
-
deploy-cli nginx 站点配置:apply / remove / list(--help
|
|
1318
|
+
deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)
|
|
1319
|
+
deploy-cli deploy 执行部署流水线(--help 看示例)
|
|
1320
|
+
deploy-cli status 项目健康状态聚合(--help 看示例)`;
|
|
910
1321
|
/** CLI 子命令分发,返回退出码 */
|
|
911
1322
|
async function main(argv) {
|
|
912
1323
|
const [command] = argv;
|
|
@@ -916,6 +1327,8 @@ async function main(argv) {
|
|
|
916
1327
|
case "logs": return await logs(argv.slice(1));
|
|
917
1328
|
case "project": return await project(argv.slice(1));
|
|
918
1329
|
case "nginx": return await nginx(argv.slice(1));
|
|
1330
|
+
case "deploy": return await deploy(argv.slice(1));
|
|
1331
|
+
case "status": return await status(argv.slice(1));
|
|
919
1332
|
case "help":
|
|
920
1333
|
case "--help":
|
|
921
1334
|
case "-h":
|