@dongnanyang/deploy-cli 0.3.1 → 0.5.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-D65j0B24.js +916 -0
- package/package.json +3 -2
- package/dist/cli-BmCyXTVr.js +0 -437
package/dist/bin.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
const argv = process.argv.slice(2);
|
|
3
3
|
if (argv.length === 0 || argv[0] === "tui") await import("./main.js");
|
|
4
4
|
else {
|
|
5
|
-
const cli = await import("./cli-
|
|
5
|
+
const cli = await import("./cli-D65j0B24.js");
|
|
6
6
|
process.exitCode = await cli.main(argv);
|
|
7
7
|
}
|
|
8
8
|
//#endregion
|
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-CVqFEtQB.js";
|
|
2
|
+
import { readFileSync } from "fs";
|
|
3
|
+
import { resolve } from "path";
|
|
4
|
+
import { accessSync, constants, existsSync as existsSync$1, lstatSync, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { parse } from "yaml";
|
|
7
|
+
import { join as join$1 } from "node:path";
|
|
8
|
+
//#region src/core/exec.ts
|
|
9
|
+
/** 仅 spawn 失败(ENOENT)与超时抛出 */
|
|
10
|
+
var ExecError = class extends Error {
|
|
11
|
+
result;
|
|
12
|
+
constructor(message, result) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "ExecError";
|
|
15
|
+
this.result = result;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/** 超时 SIGTERM 后等待子进程退出的宽限时长,超过则 SIGKILL */
|
|
19
|
+
const KILL_GRACE_MS = 3e3;
|
|
20
|
+
/** 按 \n 切行缓冲,结束时补发无结尾换行的残行 */
|
|
21
|
+
function createLineBuffer(stream, onLine) {
|
|
22
|
+
let buffer = "";
|
|
23
|
+
let text = "";
|
|
24
|
+
/** 回调抛异常跳过该次调用即可,不得影响数据捕获与后续行回调 */
|
|
25
|
+
const emit = (line) => {
|
|
26
|
+
try {
|
|
27
|
+
onLine?.(line, stream);
|
|
28
|
+
} catch {}
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
push(chunk) {
|
|
32
|
+
text += chunk;
|
|
33
|
+
buffer += chunk;
|
|
34
|
+
let index = buffer.indexOf("\n");
|
|
35
|
+
while (index !== -1) {
|
|
36
|
+
const line = buffer.slice(0, index);
|
|
37
|
+
buffer = buffer.slice(index + 1);
|
|
38
|
+
emit(line);
|
|
39
|
+
index = buffer.indexOf("\n");
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
/** flush 残行并返回累计全文 */
|
|
43
|
+
flush() {
|
|
44
|
+
if (buffer.length > 0) {
|
|
45
|
+
emit(buffer);
|
|
46
|
+
buffer = "";
|
|
47
|
+
}
|
|
48
|
+
return text;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** 执行命令并捕获退出码与输出 */
|
|
53
|
+
async function run(cmd, args, opts = {}) {
|
|
54
|
+
const cmdLine = [cmd, ...args].join(" ");
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const child = spawn(cmd, args, {
|
|
57
|
+
cwd: opts.cwd,
|
|
58
|
+
env: opts.env,
|
|
59
|
+
stdio: [
|
|
60
|
+
"ignore",
|
|
61
|
+
"pipe",
|
|
62
|
+
"pipe"
|
|
63
|
+
]
|
|
64
|
+
});
|
|
65
|
+
const out = createLineBuffer("stdout", opts.onLine);
|
|
66
|
+
const err = createLineBuffer("stderr", opts.onLine);
|
|
67
|
+
let settled = false;
|
|
68
|
+
let timedOut = false;
|
|
69
|
+
let timeoutNote = "";
|
|
70
|
+
let killTimer;
|
|
71
|
+
const timeoutTimer = opts.timeoutMs ? setTimeout(() => {
|
|
72
|
+
timedOut = true;
|
|
73
|
+
timeoutNote = `timeout: ${cmdLine}\n`;
|
|
74
|
+
child.kill("SIGTERM");
|
|
75
|
+
killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
|
|
76
|
+
}, opts.timeoutMs) : void 0;
|
|
77
|
+
child.stdout?.setEncoding("utf-8");
|
|
78
|
+
child.stderr?.setEncoding("utf-8");
|
|
79
|
+
child.stdout?.on("data", (chunk) => out.push(chunk));
|
|
80
|
+
child.stderr?.on("data", (chunk) => err.push(chunk));
|
|
81
|
+
child.on("error", (error) => {
|
|
82
|
+
if (settled) return;
|
|
83
|
+
settled = true;
|
|
84
|
+
clearTimeout(timeoutTimer);
|
|
85
|
+
clearTimeout(killTimer);
|
|
86
|
+
const message = `spawn 失败: ${cmdLine}: ${error.message}`;
|
|
87
|
+
reject(new ExecError(message, {
|
|
88
|
+
code: 127,
|
|
89
|
+
stdout: out.flush(),
|
|
90
|
+
stderr: `${message}\n`
|
|
91
|
+
}));
|
|
92
|
+
});
|
|
93
|
+
child.on("close", (code) => {
|
|
94
|
+
if (settled) return;
|
|
95
|
+
settled = true;
|
|
96
|
+
clearTimeout(timeoutTimer);
|
|
97
|
+
clearTimeout(killTimer);
|
|
98
|
+
const result = {
|
|
99
|
+
code: code ?? (timedOut ? 124 : 1),
|
|
100
|
+
stdout: out.flush(),
|
|
101
|
+
stderr: err.flush() + timeoutNote
|
|
102
|
+
};
|
|
103
|
+
if (timedOut) {
|
|
104
|
+
reject(new ExecError(`timeout: ${cmdLine}`, result));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
resolve(result);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
//#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
|
+
//#region src/core/docker.ts
|
|
177
|
+
/** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
|
|
178
|
+
function logsArgs(idOrName, o) {
|
|
179
|
+
const args = ["logs"];
|
|
180
|
+
if (o?.tail !== void 0) args.push("--tail", String(o.tail));
|
|
181
|
+
if (o?.follow) args.push("--follow");
|
|
182
|
+
args.push(idOrName);
|
|
183
|
+
return args;
|
|
184
|
+
}
|
|
185
|
+
/** 失败信息:命令原文 + exit 码 + stderr 摘要 */
|
|
186
|
+
function execFailureMessage(cmd, args, result) {
|
|
187
|
+
const summary = result.stderr.trim().split("\n").filter((line) => line.trim() !== "").slice(0, 3).join(" ");
|
|
188
|
+
return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
|
|
189
|
+
}
|
|
190
|
+
/** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 (l) => void */
|
|
191
|
+
function adaptOnLine(onLine) {
|
|
192
|
+
return onLine ? (line) => onLine(line) : void 0;
|
|
193
|
+
}
|
|
194
|
+
/** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
|
|
195
|
+
function parseContainerLine(line) {
|
|
196
|
+
let raw;
|
|
197
|
+
try {
|
|
198
|
+
raw = JSON.parse(line);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
201
|
+
throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
id: String(raw.ID ?? raw.Id ?? ""),
|
|
205
|
+
name: String(raw.Names ?? ""),
|
|
206
|
+
image: String(raw.Image ?? ""),
|
|
207
|
+
state: String(raw.State ?? ""),
|
|
208
|
+
status: String(raw.Status ?? ""),
|
|
209
|
+
ports: String(raw.Ports ?? "")
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/** 以 shell-out 方式实现的 docker 操作集合 */
|
|
213
|
+
function createDocker(runner = run) {
|
|
214
|
+
return {
|
|
215
|
+
async listContainers(o) {
|
|
216
|
+
const args = ["ps"];
|
|
217
|
+
if (o?.all) args.push("-a");
|
|
218
|
+
if (o?.name) args.push("--filter", `name=${o.name}`);
|
|
219
|
+
args.push("--format", "{{json .}}");
|
|
220
|
+
const result = await runner("docker", args);
|
|
221
|
+
if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
|
|
222
|
+
return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
|
|
223
|
+
},
|
|
224
|
+
async logs(idOrName, o) {
|
|
225
|
+
return await runner("docker", logsArgs(idOrName, o), { onLine: adaptOnLine(o?.onLine) });
|
|
226
|
+
},
|
|
227
|
+
async composeUp(cwd, composeFile, o) {
|
|
228
|
+
const args = [
|
|
229
|
+
"compose",
|
|
230
|
+
"-f",
|
|
231
|
+
composeFile,
|
|
232
|
+
"up",
|
|
233
|
+
"-d"
|
|
234
|
+
];
|
|
235
|
+
if (o?.build) args.push("--build");
|
|
236
|
+
return await runner("docker", args, {
|
|
237
|
+
cwd,
|
|
238
|
+
onLine: adaptOnLine(o?.onLine)
|
|
239
|
+
});
|
|
240
|
+
},
|
|
241
|
+
async composeDown(cwd, composeFile, o) {
|
|
242
|
+
return await runner("docker", [
|
|
243
|
+
"compose",
|
|
244
|
+
"-f",
|
|
245
|
+
composeFile,
|
|
246
|
+
"down"
|
|
247
|
+
], {
|
|
248
|
+
cwd,
|
|
249
|
+
onLine: adaptOnLine(o?.onLine)
|
|
250
|
+
});
|
|
251
|
+
},
|
|
252
|
+
async composeBuild(cwd, composeFile, o) {
|
|
253
|
+
return await runner("docker", [
|
|
254
|
+
"compose",
|
|
255
|
+
"-f",
|
|
256
|
+
composeFile,
|
|
257
|
+
"build"
|
|
258
|
+
], {
|
|
259
|
+
cwd,
|
|
260
|
+
onLine: adaptOnLine(o?.onLine)
|
|
261
|
+
});
|
|
262
|
+
},
|
|
263
|
+
async restart(idOrName) {
|
|
264
|
+
return await runner("docker", ["restart", idOrName]);
|
|
265
|
+
},
|
|
266
|
+
async stop(idOrName) {
|
|
267
|
+
return await runner("docker", ["stop", idOrName]);
|
|
268
|
+
},
|
|
269
|
+
async remove(idOrName, o) {
|
|
270
|
+
const args = ["rm"];
|
|
271
|
+
if (o?.force) args.push("--force");
|
|
272
|
+
args.push(idOrName);
|
|
273
|
+
return await runner("docker", args);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/cli/commands/logs.ts
|
|
279
|
+
const USAGE$4 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
|
|
280
|
+
|
|
281
|
+
选项:
|
|
282
|
+
--tail <行数> 只显示最后 N 行(默认全部)
|
|
283
|
+
--follow 持续跟随日志输出(Ctrl-C 退出)
|
|
284
|
+
|
|
285
|
+
示例:
|
|
286
|
+
deploy-cli logs deploy-cli-test-echo --tail 5
|
|
287
|
+
deploy-cli logs my-app --follow`;
|
|
288
|
+
/** 查看容器日志,逐行输出到 stdout;返回退出码 */
|
|
289
|
+
async function logs(args, options = {}) {
|
|
290
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
291
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
292
|
+
let tail;
|
|
293
|
+
let follow = false;
|
|
294
|
+
const positionals = [];
|
|
295
|
+
for (let i = 0; i < args.length; i++) {
|
|
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
|
+
};
|
|
334
|
+
try {
|
|
335
|
+
const result = await docker.logs(name, {
|
|
336
|
+
...logOpts,
|
|
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
|
+
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;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
|
|
479
|
+
function validateSlug(slug) {
|
|
480
|
+
if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符(禁止路径字符与大写)`);
|
|
481
|
+
}
|
|
482
|
+
function validateSpec(spec) {
|
|
483
|
+
validateSlug(spec.slug);
|
|
484
|
+
if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
|
|
485
|
+
if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
|
|
486
|
+
if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
|
|
487
|
+
}
|
|
488
|
+
/** 失败信息:命令原文 + exit 码 + stderr 摘要(包裹为 ExecError,附完整结果) */
|
|
489
|
+
function execFailure(cmd, args, result, note) {
|
|
490
|
+
const summary = result.stderr.trim().split("\n").filter((line) => line.trim() !== "").slice(0, 3).join(" ");
|
|
491
|
+
return new ExecError(`${note ? `${note}: ` : ""}命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`, result);
|
|
492
|
+
}
|
|
493
|
+
/** 渲染 server 块;withSsl 时要求 certPath/keyPath(acme 需先 requestCert 取得) */
|
|
494
|
+
function renderBlock(spec, withSsl) {
|
|
495
|
+
validateSpec(spec);
|
|
496
|
+
if (withSsl && (!spec.certPath || !spec.keyPath)) throw new Error(`ssl:${spec.ssl} 需要 certPath 与 keyPath(acme 需先 requestCert 取得)`);
|
|
497
|
+
const lines = [];
|
|
498
|
+
lines.push(`# ${CONF_PREFIX}${spec.slug}${CONF_SUFFIX} — 由 deploy-cli 管理,请勿手动修改`);
|
|
499
|
+
lines.push("server {");
|
|
500
|
+
lines.push(" listen 80;");
|
|
501
|
+
if (withSsl) lines.push(" listen 443 ssl;");
|
|
502
|
+
lines.push(` server_name ${spec.serverName};`);
|
|
503
|
+
lines.push("");
|
|
504
|
+
if (withSsl) {
|
|
505
|
+
lines.push(` ssl_certificate ${spec.certPath};`);
|
|
506
|
+
lines.push(` ssl_certificate_key ${spec.keyPath};`);
|
|
507
|
+
lines.push("");
|
|
508
|
+
}
|
|
509
|
+
if (spec.root) {
|
|
510
|
+
lines.push(` root ${spec.root};`);
|
|
511
|
+
lines.push("");
|
|
512
|
+
lines.push(" location / {");
|
|
513
|
+
lines.push(" try_files $uri $uri/ =404;");
|
|
514
|
+
lines.push(" }");
|
|
515
|
+
} else {
|
|
516
|
+
lines.push(" location / {");
|
|
517
|
+
lines.push(` proxy_pass http://${spec.upstream};`);
|
|
518
|
+
lines.push(" proxy_set_header Host $host;");
|
|
519
|
+
lines.push(" proxy_set_header X-Real-IP $remote_addr;");
|
|
520
|
+
lines.push(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;");
|
|
521
|
+
lines.push(" proxy_set_header X-Forwarded-Proto $scheme;");
|
|
522
|
+
lines.push(" }");
|
|
523
|
+
}
|
|
524
|
+
lines.push("}");
|
|
525
|
+
return lines.join("\n") + "\n";
|
|
526
|
+
}
|
|
527
|
+
function createNginx(runner = run, paths) {
|
|
528
|
+
const sitesAvailable = paths?.sitesAvailable ?? (existsSync$1(DEFAULT_SITES_AVAILABLE) ? DEFAULT_SITES_AVAILABLE : DEFAULT_CONF_D);
|
|
529
|
+
const sitesEnabled = paths ? paths.sitesEnabled : existsSync$1(DEFAULT_SITES_AVAILABLE) ? DEFAULT_SITES_ENABLED : void 0;
|
|
530
|
+
const confName = (slug) => `${CONF_PREFIX}${slug}${CONF_SUFFIX}`;
|
|
531
|
+
/**
|
|
532
|
+
* 写盘/回滚流程:新内容写 .conf.new → 旧 conf 备份 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
|
|
533
|
+
* 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
|
|
534
|
+
*/
|
|
535
|
+
async function writeSite(slug, content) {
|
|
536
|
+
const conf = join$1(sitesAvailable, confName(slug));
|
|
537
|
+
const tmp = `${conf}.new`;
|
|
538
|
+
const bak = `${conf}.bak`;
|
|
539
|
+
writeFileSync$1(tmp, content, "utf-8");
|
|
540
|
+
const existed = pathExists(conf);
|
|
541
|
+
if (existed) renameSync(conf, bak);
|
|
542
|
+
renameSync(tmp, conf);
|
|
543
|
+
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
544
|
+
const linkCreated = link ? !pathExists(link) : false;
|
|
545
|
+
if (link && linkCreated) symlinkSync(conf, link);
|
|
546
|
+
const test = await runner("nginx", ["-t"]);
|
|
547
|
+
if (test.code !== 0) {
|
|
548
|
+
if (existed) renameSync(bak, conf);
|
|
549
|
+
else unlinkSync(conf);
|
|
550
|
+
if (link && linkCreated) unlinkSync(link);
|
|
551
|
+
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
|
|
552
|
+
}
|
|
553
|
+
const reload = await runner("nginx", ["-s", "reload"]);
|
|
554
|
+
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
555
|
+
if (existed) unlinkSync(bak);
|
|
556
|
+
}
|
|
557
|
+
async function requestCert(domain) {
|
|
558
|
+
const acmeBin = `${ACME_HOME}/acme.sh`;
|
|
559
|
+
if ((await runner("sh", ["-c", `test -x ${acmeBin}`])).code === 0) {
|
|
560
|
+
const args = [
|
|
561
|
+
"--issue",
|
|
562
|
+
"--nginx",
|
|
563
|
+
"-d",
|
|
564
|
+
domain
|
|
565
|
+
];
|
|
566
|
+
const result = await runner(acmeBin, args);
|
|
567
|
+
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(acmeBin, args, result, `acme.sh 签发失败: ${domain}`);
|
|
568
|
+
return {
|
|
569
|
+
tool: "acme.sh",
|
|
570
|
+
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
571
|
+
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
if ((await runner("sh", ["-c", "command -v certbot"])).code === 0) {
|
|
575
|
+
const args = [
|
|
576
|
+
"--nginx",
|
|
577
|
+
"-d",
|
|
578
|
+
domain,
|
|
579
|
+
"--non-interactive",
|
|
580
|
+
"--agree-tos",
|
|
581
|
+
"--register-unsafely-without-email"
|
|
582
|
+
];
|
|
583
|
+
const result = await runner("certbot", args);
|
|
584
|
+
if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
|
|
585
|
+
return {
|
|
586
|
+
tool: "certbot",
|
|
587
|
+
certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
|
|
588
|
+
keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
|
|
592
|
+
}
|
|
593
|
+
return {
|
|
594
|
+
async applySite(spec) {
|
|
595
|
+
validateSpec(spec);
|
|
596
|
+
if (spec.ssl === "acme") {
|
|
597
|
+
await writeSite(spec.slug, renderBlock(spec, false));
|
|
598
|
+
const cert = await requestCert(spec.serverName);
|
|
599
|
+
await writeSite(spec.slug, renderBlock({
|
|
600
|
+
...spec,
|
|
601
|
+
certPath: cert.certPath,
|
|
602
|
+
keyPath: cert.keyPath
|
|
603
|
+
}, true));
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
|
|
607
|
+
},
|
|
608
|
+
async removeSite(slug) {
|
|
609
|
+
validateSlug(slug);
|
|
610
|
+
const conf = join$1(sitesAvailable, confName(slug));
|
|
611
|
+
if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
|
|
612
|
+
const bak = `${conf}.bak`;
|
|
613
|
+
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
614
|
+
const hadLink = link ? pathExists(link) : false;
|
|
615
|
+
renameSync(conf, bak);
|
|
616
|
+
if (link && hadLink) unlinkSync(link);
|
|
617
|
+
const test = await runner("nginx", ["-t"]);
|
|
618
|
+
if (test.code !== 0) {
|
|
619
|
+
renameSync(bak, conf);
|
|
620
|
+
if (link && hadLink) symlinkSync(conf, link);
|
|
621
|
+
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
|
|
622
|
+
}
|
|
623
|
+
const reload = await runner("nginx", ["-s", "reload"]);
|
|
624
|
+
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, `nginx reload 失败,保留备份 ${bak} 供人工恢复`);
|
|
625
|
+
unlinkSync(bak);
|
|
626
|
+
},
|
|
627
|
+
async listSites() {
|
|
628
|
+
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();
|
|
629
|
+
},
|
|
630
|
+
requestCert
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
//#endregion
|
|
634
|
+
//#region src/cli/commands/nginx.ts
|
|
635
|
+
const USAGE$3 = `用法: deploy-cli nginx <apply|remove|list> [参数]
|
|
636
|
+
|
|
637
|
+
子命令:
|
|
638
|
+
apply <project> [--no-ssl] 按 deploy.yaml 的 nginx 配置写入站点 conf 并启用
|
|
639
|
+
remove <project> 移除站点 conf 与软链
|
|
640
|
+
list 列出 deploy-cli 管理的站点
|
|
641
|
+
|
|
642
|
+
示例:
|
|
643
|
+
deploy-cli nginx apply my-app
|
|
644
|
+
deploy-cli nginx apply my-app --no-ssl
|
|
645
|
+
deploy-cli nginx remove my-app
|
|
646
|
+
deploy-cli nginx list`;
|
|
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
|
+
/** nginx 站点管理:apply / remove / list;返回退出码 */
|
|
665
|
+
async function nginx(args, options = {}) {
|
|
666
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
667
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
668
|
+
const load = options.load ?? loadConfig;
|
|
669
|
+
const api = options.api ?? createNginx();
|
|
670
|
+
const [sub, ...rest] = args;
|
|
671
|
+
if (sub === "-h" || sub === "--help") {
|
|
672
|
+
log(USAGE$3);
|
|
673
|
+
return 0;
|
|
674
|
+
}
|
|
675
|
+
if (sub === void 0) {
|
|
676
|
+
error("缺少子命令");
|
|
677
|
+
error(USAGE$3);
|
|
678
|
+
return 1;
|
|
679
|
+
}
|
|
680
|
+
try {
|
|
681
|
+
switch (sub) {
|
|
682
|
+
case "apply": {
|
|
683
|
+
const unknown = rest.filter((a) => a.startsWith("-") && a !== "--no-ssl");
|
|
684
|
+
if (unknown.length > 0) {
|
|
685
|
+
error(`未知参数: ${unknown.join(" ")}`);
|
|
686
|
+
error(USAGE$3);
|
|
687
|
+
return 1;
|
|
688
|
+
}
|
|
689
|
+
const positional = rest.filter((a) => !a.startsWith("-"));
|
|
690
|
+
const name = positional[0];
|
|
691
|
+
if (name === void 0 || positional.length > 1) {
|
|
692
|
+
error("apply 需要且仅需要一个 <project> 参数");
|
|
693
|
+
error(USAGE$3);
|
|
694
|
+
return 1;
|
|
695
|
+
}
|
|
696
|
+
const noSsl = rest.includes("--no-ssl");
|
|
697
|
+
const row = listProjects(load()).find((r) => r.name === name);
|
|
698
|
+
if (!row) {
|
|
699
|
+
error(`未找到项目: ${name}(先 deploy-cli project add 注册)`);
|
|
700
|
+
return 1;
|
|
701
|
+
}
|
|
702
|
+
if (!row.config) {
|
|
703
|
+
error(`项目配置不可用: ${name}: ${row.error ?? ""}`);
|
|
704
|
+
return 1;
|
|
705
|
+
}
|
|
706
|
+
const spec = buildSpec(row.config, noSsl);
|
|
707
|
+
await api.applySite(spec);
|
|
708
|
+
log(`已应用站点: ${spec.slug}(deploy-cli-${spec.slug}.conf,server_name ${spec.serverName},ssl ${spec.ssl})`);
|
|
709
|
+
return 0;
|
|
710
|
+
}
|
|
711
|
+
case "remove": {
|
|
712
|
+
const name = rest[0];
|
|
713
|
+
if (name === void 0 || rest.length > 1) {
|
|
714
|
+
error("remove 需要且仅需要一个 <project> 参数");
|
|
715
|
+
error(USAGE$3);
|
|
716
|
+
return 1;
|
|
717
|
+
}
|
|
718
|
+
await api.removeSite(name);
|
|
719
|
+
log(`已移除站点配置: deploy-cli-${name}.conf`);
|
|
720
|
+
return 0;
|
|
721
|
+
}
|
|
722
|
+
case "list": {
|
|
723
|
+
if (rest.length > 0) {
|
|
724
|
+
error(`未知参数: ${rest.join(" ")}`);
|
|
725
|
+
error(USAGE$3);
|
|
726
|
+
return 1;
|
|
727
|
+
}
|
|
728
|
+
const sites = await api.listSites();
|
|
729
|
+
log("SLUG");
|
|
730
|
+
for (const slug of sites) log(slug);
|
|
731
|
+
return 0;
|
|
732
|
+
}
|
|
733
|
+
default:
|
|
734
|
+
error(`未知子命令: ${sub}`);
|
|
735
|
+
error(USAGE$3);
|
|
736
|
+
return 1;
|
|
737
|
+
}
|
|
738
|
+
} catch (err) {
|
|
739
|
+
error(err instanceof Error ? err.message : String(err));
|
|
740
|
+
return 1;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
//#endregion
|
|
744
|
+
//#region src/cli/commands/project.ts
|
|
745
|
+
const USAGE$2 = `用法: deploy-cli project <list|add|remove> [参数]
|
|
746
|
+
|
|
747
|
+
子命令:
|
|
748
|
+
list 列出已注册项目(NAME/PATH/TYPE/ERROR)
|
|
749
|
+
add <path> 读取 <path>/deploy.yaml 并注册项目
|
|
750
|
+
remove <name> 注销项目
|
|
751
|
+
|
|
752
|
+
示例:
|
|
753
|
+
deploy-cli project list
|
|
754
|
+
deploy-cli project add ~/my-app
|
|
755
|
+
deploy-cli project remove my-app`;
|
|
756
|
+
/** 项目注册表管理:list / add / remove;返回退出码 */
|
|
757
|
+
async function project(args, options = {}) {
|
|
758
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
759
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
760
|
+
const load = options.load ?? loadConfig;
|
|
761
|
+
const save = options.save ?? saveConfig;
|
|
762
|
+
const [sub, ...rest] = args;
|
|
763
|
+
if (sub === "-h" || sub === "--help") {
|
|
764
|
+
log(USAGE$2);
|
|
765
|
+
return 0;
|
|
766
|
+
}
|
|
767
|
+
if (sub === void 0) {
|
|
768
|
+
error("缺少子命令");
|
|
769
|
+
error(USAGE$2);
|
|
770
|
+
return 1;
|
|
771
|
+
}
|
|
772
|
+
try {
|
|
773
|
+
switch (sub) {
|
|
774
|
+
case "list": {
|
|
775
|
+
if (rest.length > 0) {
|
|
776
|
+
error(`未知参数: ${rest.join(" ")}`);
|
|
777
|
+
error(USAGE$2);
|
|
778
|
+
return 1;
|
|
779
|
+
}
|
|
780
|
+
const rows = listProjects(load());
|
|
781
|
+
log("NAME PATH TYPE ERROR");
|
|
782
|
+
for (const row of rows) log(`${row.name}\t${row.path}\t${row.config?.type ?? "-"}\t${row.error ?? ""}`);
|
|
783
|
+
return 0;
|
|
784
|
+
}
|
|
785
|
+
case "add": {
|
|
786
|
+
const raw = rest[0];
|
|
787
|
+
if (raw === void 0 || rest.length > 1) {
|
|
788
|
+
error("add 需要且仅需要一个 <path> 参数");
|
|
789
|
+
error(USAGE$2);
|
|
790
|
+
return 1;
|
|
791
|
+
}
|
|
792
|
+
const dir = expandPath(raw);
|
|
793
|
+
const cfg = addProject(load(), dir);
|
|
794
|
+
save(cfg);
|
|
795
|
+
const entry = cfg.projects[cfg.projects.length - 1];
|
|
796
|
+
log(`已注册项目: ${entry.name} → ${entry.path}`);
|
|
797
|
+
return 0;
|
|
798
|
+
}
|
|
799
|
+
case "remove": {
|
|
800
|
+
const name = rest[0];
|
|
801
|
+
if (name === void 0 || rest.length > 1) {
|
|
802
|
+
error("remove 需要且仅需要一个 <name> 参数");
|
|
803
|
+
error(USAGE$2);
|
|
804
|
+
return 1;
|
|
805
|
+
}
|
|
806
|
+
save(removeProject(load(), name));
|
|
807
|
+
log(`已注销项目: ${name}`);
|
|
808
|
+
return 0;
|
|
809
|
+
}
|
|
810
|
+
default:
|
|
811
|
+
error(`未知子命令: ${sub}`);
|
|
812
|
+
error(USAGE$2);
|
|
813
|
+
return 1;
|
|
814
|
+
}
|
|
815
|
+
} catch (err) {
|
|
816
|
+
error(err instanceof Error ? err.message : String(err));
|
|
817
|
+
return 1;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
//#endregion
|
|
821
|
+
//#region src/cli/commands/ps.ts
|
|
822
|
+
const USAGE$1 = `用法: deploy-cli ps [--all] [--project <项目名>]
|
|
823
|
+
|
|
824
|
+
选项:
|
|
825
|
+
--all 含已停止的容器
|
|
826
|
+
--project <项目名> 按配置注册表中的项目名过滤容器
|
|
827
|
+
|
|
828
|
+
示例:
|
|
829
|
+
deploy-cli ps
|
|
830
|
+
deploy-cli ps --all
|
|
831
|
+
deploy-cli ps --project my-app`;
|
|
832
|
+
/** 列出容器:NAME\tIMAGE\tSTATE\tPORTS;返回退出码 */
|
|
833
|
+
async function ps(args, options = {}) {
|
|
834
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
835
|
+
const error = options.error ?? ((line) => console.error(line));
|
|
836
|
+
let all = false;
|
|
837
|
+
let projectName;
|
|
838
|
+
for (let i = 0; i < args.length; i++) {
|
|
839
|
+
const arg = args[i];
|
|
840
|
+
if (arg === "-h" || arg === "--help") {
|
|
841
|
+
log(USAGE$1);
|
|
842
|
+
return 0;
|
|
843
|
+
}
|
|
844
|
+
if (arg === "--all") {
|
|
845
|
+
all = true;
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
if (arg === "--project") {
|
|
849
|
+
const value = args[++i];
|
|
850
|
+
if (value === void 0 || value === "") {
|
|
851
|
+
error("缺少 --project 的项目名参数");
|
|
852
|
+
error(USAGE$1);
|
|
853
|
+
return 1;
|
|
854
|
+
}
|
|
855
|
+
projectName = value;
|
|
856
|
+
continue;
|
|
857
|
+
}
|
|
858
|
+
error(`未知参数: ${arg}`);
|
|
859
|
+
error(USAGE$1);
|
|
860
|
+
return 1;
|
|
861
|
+
}
|
|
862
|
+
const docker = options.docker ?? createDocker();
|
|
863
|
+
try {
|
|
864
|
+
let nameFilter;
|
|
865
|
+
if (projectName !== void 0) {
|
|
866
|
+
const project = (options.projects ?? (() => loadConfig().projects))().find((p) => p.name === projectName);
|
|
867
|
+
if (!project) {
|
|
868
|
+
error(`未找到项目: ${projectName}(请检查 ~/.deploy-cli/config.json 的 projects 注册表)`);
|
|
869
|
+
return 1;
|
|
870
|
+
}
|
|
871
|
+
nameFilter = project.name;
|
|
872
|
+
}
|
|
873
|
+
const listOpts = {};
|
|
874
|
+
if (all) listOpts.all = true;
|
|
875
|
+
if (nameFilter) listOpts.name = nameFilter;
|
|
876
|
+
const containers = await docker.listContainers(listOpts);
|
|
877
|
+
log("NAME IMAGE STATE PORTS");
|
|
878
|
+
for (const container of containers) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
|
|
879
|
+
return 0;
|
|
880
|
+
} catch (err) {
|
|
881
|
+
error(err instanceof Error ? err.message : String(err));
|
|
882
|
+
return 1;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
//#endregion
|
|
886
|
+
//#region src/cli/index.ts
|
|
887
|
+
const USAGE = `用法:
|
|
888
|
+
deploy-cli 启动交互式 TUI
|
|
889
|
+
deploy-cli tui 启动交互式 TUI
|
|
890
|
+
deploy-cli doctor 环境自检
|
|
891
|
+
deploy-cli ps 列出容器(--help 看示例)
|
|
892
|
+
deploy-cli logs 查看容器日志(--help 看示例)
|
|
893
|
+
deploy-cli project 项目注册表:list / add / remove(--help 看示例)
|
|
894
|
+
deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)`;
|
|
895
|
+
/** CLI 子命令分发,返回退出码 */
|
|
896
|
+
async function main(argv) {
|
|
897
|
+
const [command] = argv;
|
|
898
|
+
switch (command) {
|
|
899
|
+
case "doctor": return await doctor();
|
|
900
|
+
case "ps": return await ps(argv.slice(1));
|
|
901
|
+
case "logs": return await logs(argv.slice(1));
|
|
902
|
+
case "project": return await project(argv.slice(1));
|
|
903
|
+
case "nginx": return await nginx(argv.slice(1));
|
|
904
|
+
case "help":
|
|
905
|
+
case "--help":
|
|
906
|
+
case "-h":
|
|
907
|
+
console.log(USAGE);
|
|
908
|
+
return 0;
|
|
909
|
+
default:
|
|
910
|
+
console.error(`未知命令: ${command ?? ""}`);
|
|
911
|
+
console.error(USAGE);
|
|
912
|
+
return 1;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
//#endregion
|
|
916
|
+
export { main };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dongnanyang/deploy-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Local CLI TUI for SSH tunnels & deploy scripts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"@vue-tui/runtime": "^0.3.0",
|
|
27
27
|
"@vue-tui/use": "^0.3.0",
|
|
28
28
|
"ssh2": "^1.16.0",
|
|
29
|
-
"vue": "^3.5.0"
|
|
29
|
+
"vue": "^3.5.0",
|
|
30
|
+
"yaml": "^2.9.1"
|
|
30
31
|
},
|
|
31
32
|
"devDependencies": {
|
|
32
33
|
"@vitejs/plugin-vue-jsx": "5.1.5",
|
package/dist/cli-BmCyXTVr.js
DELETED
|
@@ -1,437 +0,0 @@
|
|
|
1
|
-
import { n as loadConfig } from "./config-CVqFEtQB.js";
|
|
2
|
-
import { accessSync, constants } from "node:fs";
|
|
3
|
-
import { spawn } from "node:child_process";
|
|
4
|
-
//#region src/core/exec.ts
|
|
5
|
-
/** 仅 spawn 失败(ENOENT)与超时抛出 */
|
|
6
|
-
var ExecError = class extends Error {
|
|
7
|
-
result;
|
|
8
|
-
constructor(message, result) {
|
|
9
|
-
super(message);
|
|
10
|
-
this.name = "ExecError";
|
|
11
|
-
this.result = result;
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
/** 超时 SIGTERM 后等待子进程退出的宽限时长,超过则 SIGKILL */
|
|
15
|
-
const KILL_GRACE_MS = 3e3;
|
|
16
|
-
/** 按 \n 切行缓冲,结束时补发无结尾换行的残行 */
|
|
17
|
-
function createLineBuffer(stream, onLine) {
|
|
18
|
-
let buffer = "";
|
|
19
|
-
let text = "";
|
|
20
|
-
/** 回调抛异常跳过该次调用即可,不得影响数据捕获与后续行回调 */
|
|
21
|
-
const emit = (line) => {
|
|
22
|
-
try {
|
|
23
|
-
onLine?.(line, stream);
|
|
24
|
-
} catch {}
|
|
25
|
-
};
|
|
26
|
-
return {
|
|
27
|
-
push(chunk) {
|
|
28
|
-
text += chunk;
|
|
29
|
-
buffer += chunk;
|
|
30
|
-
let index = buffer.indexOf("\n");
|
|
31
|
-
while (index !== -1) {
|
|
32
|
-
const line = buffer.slice(0, index);
|
|
33
|
-
buffer = buffer.slice(index + 1);
|
|
34
|
-
emit(line);
|
|
35
|
-
index = buffer.indexOf("\n");
|
|
36
|
-
}
|
|
37
|
-
},
|
|
38
|
-
/** flush 残行并返回累计全文 */
|
|
39
|
-
flush() {
|
|
40
|
-
if (buffer.length > 0) {
|
|
41
|
-
emit(buffer);
|
|
42
|
-
buffer = "";
|
|
43
|
-
}
|
|
44
|
-
return text;
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
/** 执行命令并捕获退出码与输出 */
|
|
49
|
-
async function run(cmd, args, opts = {}) {
|
|
50
|
-
const cmdLine = [cmd, ...args].join(" ");
|
|
51
|
-
return new Promise((resolve, reject) => {
|
|
52
|
-
const child = spawn(cmd, args, {
|
|
53
|
-
cwd: opts.cwd,
|
|
54
|
-
env: opts.env,
|
|
55
|
-
stdio: [
|
|
56
|
-
"ignore",
|
|
57
|
-
"pipe",
|
|
58
|
-
"pipe"
|
|
59
|
-
]
|
|
60
|
-
});
|
|
61
|
-
const out = createLineBuffer("stdout", opts.onLine);
|
|
62
|
-
const err = createLineBuffer("stderr", opts.onLine);
|
|
63
|
-
let settled = false;
|
|
64
|
-
let timedOut = false;
|
|
65
|
-
let timeoutNote = "";
|
|
66
|
-
let killTimer;
|
|
67
|
-
const timeoutTimer = opts.timeoutMs ? setTimeout(() => {
|
|
68
|
-
timedOut = true;
|
|
69
|
-
timeoutNote = `timeout: ${cmdLine}\n`;
|
|
70
|
-
child.kill("SIGTERM");
|
|
71
|
-
killTimer = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
|
|
72
|
-
}, opts.timeoutMs) : void 0;
|
|
73
|
-
child.stdout?.setEncoding("utf-8");
|
|
74
|
-
child.stderr?.setEncoding("utf-8");
|
|
75
|
-
child.stdout?.on("data", (chunk) => out.push(chunk));
|
|
76
|
-
child.stderr?.on("data", (chunk) => err.push(chunk));
|
|
77
|
-
child.on("error", (error) => {
|
|
78
|
-
if (settled) return;
|
|
79
|
-
settled = true;
|
|
80
|
-
clearTimeout(timeoutTimer);
|
|
81
|
-
clearTimeout(killTimer);
|
|
82
|
-
const message = `spawn 失败: ${cmdLine}: ${error.message}`;
|
|
83
|
-
reject(new ExecError(message, {
|
|
84
|
-
code: 127,
|
|
85
|
-
stdout: out.flush(),
|
|
86
|
-
stderr: `${message}\n`
|
|
87
|
-
}));
|
|
88
|
-
});
|
|
89
|
-
child.on("close", (code) => {
|
|
90
|
-
if (settled) return;
|
|
91
|
-
settled = true;
|
|
92
|
-
clearTimeout(timeoutTimer);
|
|
93
|
-
clearTimeout(killTimer);
|
|
94
|
-
const result = {
|
|
95
|
-
code: code ?? (timedOut ? 124 : 1),
|
|
96
|
-
stdout: out.flush(),
|
|
97
|
-
stderr: err.flush() + timeoutNote
|
|
98
|
-
};
|
|
99
|
-
if (timedOut) {
|
|
100
|
-
reject(new ExecError(`timeout: ${cmdLine}`, result));
|
|
101
|
-
return;
|
|
102
|
-
}
|
|
103
|
-
resolve(result);
|
|
104
|
-
});
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
//#endregion
|
|
108
|
-
//#region src/cli/commands/doctor.ts
|
|
109
|
-
const SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
110
|
-
const MIN_NODE_MAJOR = 20;
|
|
111
|
-
/** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
|
|
112
|
-
const PROBE_TIMEOUT_MS = 1e4;
|
|
113
|
-
async function probe(runner, cmd, args) {
|
|
114
|
-
try {
|
|
115
|
-
const result = await runner(cmd, args, { timeoutMs: PROBE_TIMEOUT_MS });
|
|
116
|
-
const detail = (result.code === 0 ? result.stdout || result.stderr : result.stderr || result.stdout).trim().split("\n")[0] ?? "";
|
|
117
|
-
return {
|
|
118
|
-
ok: result.code === 0,
|
|
119
|
-
detail
|
|
120
|
-
};
|
|
121
|
-
} catch (error) {
|
|
122
|
-
return {
|
|
123
|
-
ok: false,
|
|
124
|
-
detail: error instanceof Error ? error.message : String(error)
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
function defaultCanWrite(path) {
|
|
129
|
-
try {
|
|
130
|
-
accessSync(path, constants.W_OK);
|
|
131
|
-
return true;
|
|
132
|
-
} catch {
|
|
133
|
-
return false;
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
/** 环境自检:返回退出码(存在失败项 1,否则 0;警告不影响退出码) */
|
|
137
|
-
async function doctor(options = {}) {
|
|
138
|
-
const runner = options.runner ?? run;
|
|
139
|
-
const log = options.log ?? ((line) => console.log(line));
|
|
140
|
-
const canWrite = options.canWrite ?? defaultCanWrite;
|
|
141
|
-
let failed = false;
|
|
142
|
-
const pass = (line) => log(`[✓] ${line}`);
|
|
143
|
-
const fail = (line) => {
|
|
144
|
-
failed = true;
|
|
145
|
-
log(`[✗] ${line}`);
|
|
146
|
-
};
|
|
147
|
-
const warn = (line) => log(`[警告] ${line}`);
|
|
148
|
-
log("deploy-cli doctor 环境自检");
|
|
149
|
-
if (Number(process.versions.node.split(".")[0]) >= MIN_NODE_MAJOR) pass(`Node.js v${process.versions.node}`);
|
|
150
|
-
else fail(`Node.js v${process.versions.node} 过低,需要 >= ${MIN_NODE_MAJOR}`);
|
|
151
|
-
const dockerVersion = await probe(runner, "docker", ["--version"]);
|
|
152
|
-
if (!dockerVersion.ok) fail(`docker 不可用(docker --version 失败): ${dockerVersion.detail}`);
|
|
153
|
-
else {
|
|
154
|
-
pass(`docker 可用(${dockerVersion.detail})`);
|
|
155
|
-
const dockerInfo = await probe(runner, "docker", ["info"]);
|
|
156
|
-
if (dockerInfo.ok) pass("docker daemon 运行中");
|
|
157
|
-
else fail(`docker daemon 未运行(docker info 失败): ${dockerInfo.detail}`);
|
|
158
|
-
}
|
|
159
|
-
const nginx = await probe(runner, "nginx", ["-v"]);
|
|
160
|
-
if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
|
|
161
|
-
else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
|
|
162
|
-
if (canWrite(SITES_AVAILABLE)) pass(`${SITES_AVAILABLE} 可写`);
|
|
163
|
-
else fail(`${SITES_AVAILABLE} 不可写`);
|
|
164
|
-
const acme = await probe(runner, "acme.sh", ["--version"]);
|
|
165
|
-
const certbot = await probe(runner, "certbot", ["--version"]);
|
|
166
|
-
const certTools = [acme.ok && "acme.sh", certbot.ok && "certbot"].filter(Boolean).join(" / ");
|
|
167
|
-
if (certTools) pass(`证书工具可用(${certTools})`);
|
|
168
|
-
else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
|
|
169
|
-
return failed ? 1 : 0;
|
|
170
|
-
}
|
|
171
|
-
//#endregion
|
|
172
|
-
//#region src/core/docker.ts
|
|
173
|
-
/** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
|
|
174
|
-
function logsArgs(idOrName, o) {
|
|
175
|
-
const args = ["logs"];
|
|
176
|
-
if (o?.tail !== void 0) args.push("--tail", String(o.tail));
|
|
177
|
-
if (o?.follow) args.push("--follow");
|
|
178
|
-
args.push(idOrName);
|
|
179
|
-
return args;
|
|
180
|
-
}
|
|
181
|
-
/** 失败信息:命令原文 + exit 码 + stderr 摘要 */
|
|
182
|
-
function execFailureMessage(cmd, args, result) {
|
|
183
|
-
const summary = result.stderr.trim().split("\n").filter((line) => line.trim() !== "").slice(0, 3).join(" ");
|
|
184
|
-
return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
|
|
185
|
-
}
|
|
186
|
-
/** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 (l) => void */
|
|
187
|
-
function adaptOnLine(onLine) {
|
|
188
|
-
return onLine ? (line) => onLine(line) : void 0;
|
|
189
|
-
}
|
|
190
|
-
/** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
|
|
191
|
-
function parseContainerLine(line) {
|
|
192
|
-
let raw;
|
|
193
|
-
try {
|
|
194
|
-
raw = JSON.parse(line);
|
|
195
|
-
} catch (error) {
|
|
196
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
197
|
-
throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
|
|
198
|
-
}
|
|
199
|
-
return {
|
|
200
|
-
id: String(raw.ID ?? raw.Id ?? ""),
|
|
201
|
-
name: String(raw.Names ?? ""),
|
|
202
|
-
image: String(raw.Image ?? ""),
|
|
203
|
-
state: String(raw.State ?? ""),
|
|
204
|
-
status: String(raw.Status ?? ""),
|
|
205
|
-
ports: String(raw.Ports ?? "")
|
|
206
|
-
};
|
|
207
|
-
}
|
|
208
|
-
/** 以 shell-out 方式实现的 docker 操作集合 */
|
|
209
|
-
function createDocker(runner = run) {
|
|
210
|
-
return {
|
|
211
|
-
async listContainers(o) {
|
|
212
|
-
const args = ["ps"];
|
|
213
|
-
if (o?.all) args.push("-a");
|
|
214
|
-
if (o?.name) args.push("--filter", `name=${o.name}`);
|
|
215
|
-
args.push("--format", "{{json .}}");
|
|
216
|
-
const result = await runner("docker", args);
|
|
217
|
-
if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
|
|
218
|
-
return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
|
|
219
|
-
},
|
|
220
|
-
async logs(idOrName, o) {
|
|
221
|
-
return await runner("docker", logsArgs(idOrName, o), { onLine: adaptOnLine(o?.onLine) });
|
|
222
|
-
},
|
|
223
|
-
async composeUp(cwd, composeFile, o) {
|
|
224
|
-
const args = [
|
|
225
|
-
"compose",
|
|
226
|
-
"-f",
|
|
227
|
-
composeFile,
|
|
228
|
-
"up",
|
|
229
|
-
"-d"
|
|
230
|
-
];
|
|
231
|
-
if (o?.build) args.push("--build");
|
|
232
|
-
return await runner("docker", args, {
|
|
233
|
-
cwd,
|
|
234
|
-
onLine: adaptOnLine(o?.onLine)
|
|
235
|
-
});
|
|
236
|
-
},
|
|
237
|
-
async composeDown(cwd, composeFile, o) {
|
|
238
|
-
return await runner("docker", [
|
|
239
|
-
"compose",
|
|
240
|
-
"-f",
|
|
241
|
-
composeFile,
|
|
242
|
-
"down"
|
|
243
|
-
], {
|
|
244
|
-
cwd,
|
|
245
|
-
onLine: adaptOnLine(o?.onLine)
|
|
246
|
-
});
|
|
247
|
-
},
|
|
248
|
-
async composeBuild(cwd, composeFile, o) {
|
|
249
|
-
return await runner("docker", [
|
|
250
|
-
"compose",
|
|
251
|
-
"-f",
|
|
252
|
-
composeFile,
|
|
253
|
-
"build"
|
|
254
|
-
], {
|
|
255
|
-
cwd,
|
|
256
|
-
onLine: adaptOnLine(o?.onLine)
|
|
257
|
-
});
|
|
258
|
-
},
|
|
259
|
-
async restart(idOrName) {
|
|
260
|
-
return await runner("docker", ["restart", idOrName]);
|
|
261
|
-
},
|
|
262
|
-
async stop(idOrName) {
|
|
263
|
-
return await runner("docker", ["stop", idOrName]);
|
|
264
|
-
},
|
|
265
|
-
async remove(idOrName, o) {
|
|
266
|
-
const args = ["rm"];
|
|
267
|
-
if (o?.force) args.push("--force");
|
|
268
|
-
args.push(idOrName);
|
|
269
|
-
return await runner("docker", args);
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
//#endregion
|
|
274
|
-
//#region src/cli/commands/logs.ts
|
|
275
|
-
const USAGE$2 = `用法: deploy-cli logs <容器名> [--tail <行数>] [--follow]
|
|
276
|
-
|
|
277
|
-
选项:
|
|
278
|
-
--tail <行数> 只显示最后 N 行(默认全部)
|
|
279
|
-
--follow 持续跟随日志输出(Ctrl-C 退出)
|
|
280
|
-
|
|
281
|
-
示例:
|
|
282
|
-
deploy-cli logs deploy-cli-test-echo --tail 5
|
|
283
|
-
deploy-cli logs my-app --follow`;
|
|
284
|
-
/** 查看容器日志,逐行输出到 stdout;返回退出码 */
|
|
285
|
-
async function logs(args, options = {}) {
|
|
286
|
-
const log = options.log ?? ((line) => console.log(line));
|
|
287
|
-
const error = options.error ?? ((line) => console.error(line));
|
|
288
|
-
let tail;
|
|
289
|
-
let follow = false;
|
|
290
|
-
const positionals = [];
|
|
291
|
-
for (let i = 0; i < args.length; i++) {
|
|
292
|
-
const arg = args[i];
|
|
293
|
-
if (arg === "-h" || arg === "--help") {
|
|
294
|
-
log(USAGE$2);
|
|
295
|
-
return 0;
|
|
296
|
-
}
|
|
297
|
-
if (arg === "--tail") {
|
|
298
|
-
const value = args[++i];
|
|
299
|
-
const parsed = Number(value);
|
|
300
|
-
if (value === void 0 || value === "" || !Number.isInteger(parsed) || parsed < 0) {
|
|
301
|
-
error(`--tail 需要非负整数参数: ${value ?? ""}`);
|
|
302
|
-
error(USAGE$2);
|
|
303
|
-
return 1;
|
|
304
|
-
}
|
|
305
|
-
tail = parsed;
|
|
306
|
-
continue;
|
|
307
|
-
}
|
|
308
|
-
if (arg === "--follow") {
|
|
309
|
-
follow = true;
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
if (arg.startsWith("-")) {
|
|
313
|
-
error(`未知参数: ${arg}`);
|
|
314
|
-
error(USAGE$2);
|
|
315
|
-
return 1;
|
|
316
|
-
}
|
|
317
|
-
positionals.push(arg);
|
|
318
|
-
}
|
|
319
|
-
if (positionals.length !== 1) {
|
|
320
|
-
error(positionals.length === 0 ? "缺少容器名参数" : `只支持一个容器名参数: ${positionals.join(" ")}`);
|
|
321
|
-
error(USAGE$2);
|
|
322
|
-
return 1;
|
|
323
|
-
}
|
|
324
|
-
const name = positionals[0];
|
|
325
|
-
const docker = options.docker ?? createDocker();
|
|
326
|
-
const logOpts = {
|
|
327
|
-
tail,
|
|
328
|
-
follow
|
|
329
|
-
};
|
|
330
|
-
try {
|
|
331
|
-
const result = await docker.logs(name, {
|
|
332
|
-
...logOpts,
|
|
333
|
-
onLine: (line) => log(line)
|
|
334
|
-
});
|
|
335
|
-
if (result.code !== 0) {
|
|
336
|
-
error(execFailureMessage("docker", logsArgs(name, logOpts), result));
|
|
337
|
-
return 1;
|
|
338
|
-
}
|
|
339
|
-
return 0;
|
|
340
|
-
} catch (err) {
|
|
341
|
-
error(err instanceof Error ? err.message : String(err));
|
|
342
|
-
return 1;
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
//#endregion
|
|
346
|
-
//#region src/cli/commands/ps.ts
|
|
347
|
-
const USAGE$1 = `用法: deploy-cli ps [--all] [--project <项目名>]
|
|
348
|
-
|
|
349
|
-
选项:
|
|
350
|
-
--all 含已停止的容器
|
|
351
|
-
--project <项目名> 按配置注册表中的项目名过滤容器
|
|
352
|
-
|
|
353
|
-
示例:
|
|
354
|
-
deploy-cli ps
|
|
355
|
-
deploy-cli ps --all
|
|
356
|
-
deploy-cli ps --project my-app`;
|
|
357
|
-
/** 列出容器:NAME\tIMAGE\tSTATE\tPORTS;返回退出码 */
|
|
358
|
-
async function ps(args, options = {}) {
|
|
359
|
-
const log = options.log ?? ((line) => console.log(line));
|
|
360
|
-
const error = options.error ?? ((line) => console.error(line));
|
|
361
|
-
let all = false;
|
|
362
|
-
let projectName;
|
|
363
|
-
for (let i = 0; i < args.length; i++) {
|
|
364
|
-
const arg = args[i];
|
|
365
|
-
if (arg === "-h" || arg === "--help") {
|
|
366
|
-
log(USAGE$1);
|
|
367
|
-
return 0;
|
|
368
|
-
}
|
|
369
|
-
if (arg === "--all") {
|
|
370
|
-
all = true;
|
|
371
|
-
continue;
|
|
372
|
-
}
|
|
373
|
-
if (arg === "--project") {
|
|
374
|
-
const value = args[++i];
|
|
375
|
-
if (value === void 0 || value === "") {
|
|
376
|
-
error("缺少 --project 的项目名参数");
|
|
377
|
-
error(USAGE$1);
|
|
378
|
-
return 1;
|
|
379
|
-
}
|
|
380
|
-
projectName = value;
|
|
381
|
-
continue;
|
|
382
|
-
}
|
|
383
|
-
error(`未知参数: ${arg}`);
|
|
384
|
-
error(USAGE$1);
|
|
385
|
-
return 1;
|
|
386
|
-
}
|
|
387
|
-
const docker = options.docker ?? createDocker();
|
|
388
|
-
try {
|
|
389
|
-
let nameFilter;
|
|
390
|
-
if (projectName !== void 0) {
|
|
391
|
-
const project = (options.projects ?? (() => loadConfig().projects))().find((p) => p.name === projectName);
|
|
392
|
-
if (!project) {
|
|
393
|
-
error(`未找到项目: ${projectName}(请检查 ~/.deploy-cli/config.json 的 projects 注册表)`);
|
|
394
|
-
return 1;
|
|
395
|
-
}
|
|
396
|
-
nameFilter = project.name;
|
|
397
|
-
}
|
|
398
|
-
const listOpts = {};
|
|
399
|
-
if (all) listOpts.all = true;
|
|
400
|
-
if (nameFilter) listOpts.name = nameFilter;
|
|
401
|
-
const containers = await docker.listContainers(listOpts);
|
|
402
|
-
log("NAME IMAGE STATE PORTS");
|
|
403
|
-
for (const container of containers) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
|
|
404
|
-
return 0;
|
|
405
|
-
} catch (err) {
|
|
406
|
-
error(err instanceof Error ? err.message : String(err));
|
|
407
|
-
return 1;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
//#endregion
|
|
411
|
-
//#region src/cli/index.ts
|
|
412
|
-
const USAGE = `用法:
|
|
413
|
-
deploy-cli 启动交互式 TUI
|
|
414
|
-
deploy-cli tui 启动交互式 TUI
|
|
415
|
-
deploy-cli doctor 环境自检
|
|
416
|
-
deploy-cli ps 列出容器(--help 看示例)
|
|
417
|
-
deploy-cli logs 查看容器日志(--help 看示例)`;
|
|
418
|
-
/** CLI 子命令分发,返回退出码 */
|
|
419
|
-
async function main(argv) {
|
|
420
|
-
const [command] = argv;
|
|
421
|
-
switch (command) {
|
|
422
|
-
case "doctor": return await doctor();
|
|
423
|
-
case "ps": return await ps(argv.slice(1));
|
|
424
|
-
case "logs": return await logs(argv.slice(1));
|
|
425
|
-
case "help":
|
|
426
|
-
case "--help":
|
|
427
|
-
case "-h":
|
|
428
|
-
console.log(USAGE);
|
|
429
|
-
return 0;
|
|
430
|
-
default:
|
|
431
|
-
console.error(`未知命令: ${command ?? ""}`);
|
|
432
|
-
console.error(USAGE);
|
|
433
|
-
return 1;
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
//#endregion
|
|
437
|
-
export { main };
|