fe-deploy-kit 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +368 -2
- package/examples/deploy.config.example.json +24 -0
- package/examples/deploy.config.example.mjs +36 -0
- package/examples/github-actions.yml +64 -0
- package/package.json +57 -4
- package/src/build.js +241 -0
- package/src/cli.js +171 -0
- package/src/commands.js +174 -0
- package/src/config.js +388 -0
- package/src/core/flow.js +463 -0
- package/src/core/fs-ops.js +87 -0
- package/src/core/guard.js +321 -0
- package/src/core/memory-remote.js +196 -0
- package/src/core/remote.js +162 -0
- package/src/deploy.js +118 -0
- package/src/index.js +111 -0
- package/src/logger.js +54 -0
- package/src/prompts.js +67 -0
- package/src/ssh.js +249 -0
- package/src/state.js +79 -0
- package/types/index.d.ts +500 -0
package/src/core/flow.js
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
import { ensureDir, walkTree, removeTree, totalBytes, STAMP_PATTERN } from './fs-ops.js';
|
|
2
|
+
/**
|
|
3
|
+
* 部署编排(与 SSH/网络无关,可在内存文件系统上完整测试)。
|
|
4
|
+
*
|
|
5
|
+
* 目录约定(全部位于 remoteRoot 内部):
|
|
6
|
+
* remoteRoot/.deploy/<app>/staging-<时间戳>/ ← 新版本先传到这里
|
|
7
|
+
* remoteRoot/.deploy/<app>/backups/<时间戳>/ ← 旧版本整目录挪到这里
|
|
8
|
+
* remoteRoot/.deploy/<app>/rollback-<时间戳>/ ← 回滚时被替换下来的版本
|
|
9
|
+
*
|
|
10
|
+
* 切换方式:先把旧文件"移动"到备份目录,再把新文件"移动"到位。
|
|
11
|
+
* 移动是元数据操作,速度快;任何一步失败都会按相反顺序移回去。
|
|
12
|
+
*/
|
|
13
|
+
import { makeStamp, isInside, assertSafeEntryName } from './guard.js';
|
|
14
|
+
import { RemoteError } from './remote.js';
|
|
15
|
+
|
|
16
|
+
export class DeployError extends Error {
|
|
17
|
+
constructor(message, { cause } = {}) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'DeployError';
|
|
20
|
+
if (cause) this.cause = cause;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function metaPaths(config, stamp) {
|
|
25
|
+
const metaDir = `${config.remoteRoot}/.deploy/${config.appName}`;
|
|
26
|
+
return {
|
|
27
|
+
metaDir,
|
|
28
|
+
backupsDir: `${metaDir}/backups`,
|
|
29
|
+
stagingDir: stamp ? `${metaDir}/staging-${stamp}` : null,
|
|
30
|
+
backupDir: stamp ? `${metaDir}/backups/${stamp}` : null,
|
|
31
|
+
rollbackDir: stamp ? `${metaDir}/rollback-${stamp}` : null
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const MAX_LISTED = 12;
|
|
36
|
+
|
|
37
|
+
function listNames(names) {
|
|
38
|
+
if (names.length === 0) return '(无)';
|
|
39
|
+
const shown = names.slice(0, MAX_LISTED).join('、');
|
|
40
|
+
return names.length > MAX_LISTED ? `${shown} 等 ${names.length} 项` : shown;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function readTarget(remote, config) {
|
|
44
|
+
const stat = await remote.stat(config.remotePath);
|
|
45
|
+
if (!stat) return { exists: false, entries: [] };
|
|
46
|
+
if (stat.type !== 'dir') {
|
|
47
|
+
throw new DeployError(`remotePath=${config.remotePath} 已存在但不是目录,停止操作`);
|
|
48
|
+
}
|
|
49
|
+
const entries = await remote.readdir(config.remotePath);
|
|
50
|
+
if (!entries) throw new DeployError(`无法读取 remotePath=${config.remotePath}`);
|
|
51
|
+
return { exists: true, entries };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 连接后的第一道检查:确认 remoteRoot / remotePath 真实存在,
|
|
56
|
+
* 并用 realpath 解析符号链接,确保解析后的路径仍在这个项目范围内。
|
|
57
|
+
*/
|
|
58
|
+
export async function verifyRemoteLayout({ remote, config, createRemotePath = false }) {
|
|
59
|
+
const rootInfo = await remote.stat(config.remoteRoot);
|
|
60
|
+
if (!rootInfo || rootInfo.type !== 'dir') {
|
|
61
|
+
throw new DeployError(`服务器上找不到 remoteRoot=${config.remoteRoot},或者它不是目录,停止操作`);
|
|
62
|
+
}
|
|
63
|
+
const rootReal = await remote.realpath(config.remoteRoot);
|
|
64
|
+
|
|
65
|
+
const targetInfo = await remote.stat(config.remotePath);
|
|
66
|
+
if (!targetInfo) {
|
|
67
|
+
if (!createRemotePath) {
|
|
68
|
+
throw new DeployError(
|
|
69
|
+
`服务器上还没有 remotePath=${config.remotePath}。\n` +
|
|
70
|
+
`首次部署可加参数 --create-remote-path,脚本只会在 remoteRoot=${config.remoteRoot} 下面创建这个目录。`
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return { rootReal, targetReal: null, targetExists: false };
|
|
74
|
+
}
|
|
75
|
+
if (targetInfo.type !== 'dir') {
|
|
76
|
+
throw new DeployError(`remotePath=${config.remotePath} 已存在但不是目录,停止操作`);
|
|
77
|
+
}
|
|
78
|
+
const targetReal = await remote.realpath(config.remotePath);
|
|
79
|
+
if (targetReal === rootReal || !isInside(rootReal, targetReal)) {
|
|
80
|
+
throw new DeployError(
|
|
81
|
+
`安全检查未通过:${config.remotePath} 实际指向 ${targetReal},` +
|
|
82
|
+
`不在 remoteRoot=${config.remoteRoot}(实际 ${rootReal})范围内。可能是符号链接指向了别处。`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
return { rootReal, targetReal, targetExists: true };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 只读的部署前检查:算出要做什么,不做任何修改。
|
|
90
|
+
*/
|
|
91
|
+
export async function planDeploy({ remote, config, localTree, force = false, now = new Date() }) {
|
|
92
|
+
const rootInfo = await remote.stat(config.remoteRoot);
|
|
93
|
+
if (!rootInfo || rootInfo.type !== 'dir') {
|
|
94
|
+
throw new DeployError(`服务器上找不到 remoteRoot=${config.remoteRoot},或者它不是目录,停止操作`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const target = await readTarget(remote, config);
|
|
98
|
+
|
|
99
|
+
const preservedNames = target.entries
|
|
100
|
+
.filter(entry => config.preserve.includes(entry.name))
|
|
101
|
+
.map(entry => entry.name)
|
|
102
|
+
.toSorted((a, b) => a.localeCompare(b));
|
|
103
|
+
const swapNames = target.entries
|
|
104
|
+
.filter(entry => !config.preserve.includes(entry.name))
|
|
105
|
+
.map(entry => entry.name)
|
|
106
|
+
.toSorted((a, b) => a.localeCompare(b));
|
|
107
|
+
|
|
108
|
+
const looksLikeSite = target.entries.some(entry => entry.name === 'index.html' || entry.name === 'ie.html');
|
|
109
|
+
if (target.entries.length > 0 && !looksLikeSite && !force) {
|
|
110
|
+
throw new DeployError(
|
|
111
|
+
`remotePath=${config.remotePath} 里已经有 ${target.entries.length} 个条目,但没有 index.html,` +
|
|
112
|
+
`看起来不像这个前端项目的产物目录。为免误动别人的文件,已停止。\n` +
|
|
113
|
+
`如果确认就是这个目录,请加 --force 重新执行。`
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const stamp = makeStamp(now);
|
|
118
|
+
const paths = metaPaths(config, stamp);
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
stamp,
|
|
122
|
+
targetExists: target.exists,
|
|
123
|
+
targetEntryCount: target.entries.length,
|
|
124
|
+
swapNames,
|
|
125
|
+
preservedNames,
|
|
126
|
+
localFileCount: localTree.files.length,
|
|
127
|
+
localBytes: totalBytes(localTree.files),
|
|
128
|
+
looksLikeSite,
|
|
129
|
+
...paths
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function assertPlanInside(config, plan) {
|
|
134
|
+
for (const key of ['stagingDir', 'backupDir', 'metaDir', 'backupsDir']) {
|
|
135
|
+
const value = plan[key];
|
|
136
|
+
if (typeof value !== 'string' || !isInside(config.remoteRoot, value)) {
|
|
137
|
+
throw new DeployError(`内部错误:${key}=${value} 不在 remoteRoot=${config.remoteRoot} 内`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function uploadTree({ remote, localTree, stagingDir, log }) {
|
|
143
|
+
for (const dir of localTree.dirs) {
|
|
144
|
+
assertSafeEntryName(dir.rel.split('/')[0]);
|
|
145
|
+
await ensureDir(remote, `${stagingDir}/${dir.rel}`, { base: stagingDir });
|
|
146
|
+
}
|
|
147
|
+
let uploaded = 0;
|
|
148
|
+
let bytes = 0;
|
|
149
|
+
for (const file of localTree.files) {
|
|
150
|
+
bytes += await remote.putFile(file.abs, `${stagingDir}/${file.rel}`, { size: file.size });
|
|
151
|
+
uploaded += 1;
|
|
152
|
+
if (uploaded % 25 === 0 || uploaded === localTree.files.length) {
|
|
153
|
+
log(` 上传进度 ${uploaded}/${localTree.files.length}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { uploaded, bytes };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function verifyStaging({ remote, localTree, stagingDir }) {
|
|
160
|
+
const tree = await walkTree(remote, stagingDir);
|
|
161
|
+
const remoteFiles = new Map(tree.files.map(file => [file.rel, file.size]));
|
|
162
|
+
const localMap = new Map(localTree.files.map(file => [file.rel, file.size]));
|
|
163
|
+
const problems = [];
|
|
164
|
+
for (const file of localTree.files) {
|
|
165
|
+
const remoteSize = remoteFiles.get(file.rel);
|
|
166
|
+
if (remoteSize === undefined) problems.push(`缺少文件 ${file.rel}`);
|
|
167
|
+
else if (remoteSize !== file.size)
|
|
168
|
+
problems.push(`大小不一致 ${file.rel}(本地 ${file.size},服务器 ${remoteSize})`);
|
|
169
|
+
}
|
|
170
|
+
const extra = [...remoteFiles.keys()].filter(rel => !localMap.has(rel));
|
|
171
|
+
if (extra.length > 0) problems.push(`多出文件:${listNames(extra)}`);
|
|
172
|
+
if (tree.dirs.length !== localTree.dirs.length) {
|
|
173
|
+
problems.push(`目录数量不一致(本地 ${localTree.dirs.length},服务器 ${tree.dirs.length})`);
|
|
174
|
+
}
|
|
175
|
+
if (problems.length > 0) {
|
|
176
|
+
throw new DeployError(
|
|
177
|
+
`上传后的完整性校验没通过,已停止(网站文件尚未改动):\n - ${problems.slice(0, 10).join('\n - ')}`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return tree;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 反悔:把已经移动的东西按相反顺序移回去。
|
|
185
|
+
* 返回无法恢复的条目,便于如实报告。
|
|
186
|
+
*/
|
|
187
|
+
async function undoSwap({ remote, config, stagingDir, backupDir, movedIn, movedOut }) {
|
|
188
|
+
const failures = [];
|
|
189
|
+
for (const name of movedIn.toReversed()) {
|
|
190
|
+
try {
|
|
191
|
+
await remote.rename(`${config.remotePath}/${name}`, `${stagingDir}/${name}`);
|
|
192
|
+
} catch (err) {
|
|
193
|
+
failures.push(`移回暂存失败 ${name}:${err.message}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
for (const name of movedOut.toReversed()) {
|
|
197
|
+
try {
|
|
198
|
+
await remote.rename(`${backupDir}/${name}`, `${config.remotePath}/${name}`);
|
|
199
|
+
} catch (err) {
|
|
200
|
+
failures.push(`恢复旧文件失败 ${name}:${err.message}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return failures;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const PHASE_LABELS = {
|
|
207
|
+
prepare: '准备目录',
|
|
208
|
+
upload: '上传',
|
|
209
|
+
verify: '完整性校验',
|
|
210
|
+
backup: '备份旧版本',
|
|
211
|
+
switch: '切换版本',
|
|
212
|
+
finalize: '收尾'
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* 真正执行部署(上传 → 校验 → 备份 → 切换)。
|
|
217
|
+
*/
|
|
218
|
+
export async function executeDeploy({ remote, config, localTree, plan, log }) {
|
|
219
|
+
assertPlanInside(config, plan);
|
|
220
|
+
const { remotePath, remoteRoot } = config;
|
|
221
|
+
const stagingDir = plan.stagingDir;
|
|
222
|
+
const backupDir = plan.backupDir;
|
|
223
|
+
|
|
224
|
+
let phase = 'prepare';
|
|
225
|
+
const movedOut = [];
|
|
226
|
+
const movedIn = [];
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
await ensureDir(remote, plan.metaDir, { base: remoteRoot });
|
|
230
|
+
await ensureDir(remote, plan.backupsDir, { base: remoteRoot });
|
|
231
|
+
await ensureDir(remote, stagingDir, { base: remoteRoot });
|
|
232
|
+
|
|
233
|
+
phase = 'upload';
|
|
234
|
+
log(`上传 ${plan.localFileCount} 个文件到暂存目录:${stagingDir}`);
|
|
235
|
+
const { uploaded, bytes } = await uploadTree({ remote, localTree, stagingDir, log });
|
|
236
|
+
log(`上传完成:${uploaded} 个文件,${bytes} 字节`);
|
|
237
|
+
|
|
238
|
+
phase = 'verify';
|
|
239
|
+
log('校验服务器上的文件数量与大小...');
|
|
240
|
+
await verifyStaging({ remote, localTree, stagingDir });
|
|
241
|
+
log('校验通过,暂存目录内容与本地构建一致');
|
|
242
|
+
|
|
243
|
+
if (!plan.targetExists) {
|
|
244
|
+
await ensureDir(remote, remotePath, { base: remoteRoot });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
phase = 'backup';
|
|
248
|
+
if (plan.swapNames.length > 0) {
|
|
249
|
+
await ensureDir(remote, backupDir, { base: remoteRoot });
|
|
250
|
+
log(`备份旧版本到 ${backupDir}`);
|
|
251
|
+
for (const name of plan.swapNames) {
|
|
252
|
+
await remote.rename(`${remotePath}/${name}`, `${backupDir}/${name}`);
|
|
253
|
+
movedOut.push(name);
|
|
254
|
+
}
|
|
255
|
+
} else {
|
|
256
|
+
log('目标目录没有需要备份的旧文件(首次部署)');
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
phase = 'switch';
|
|
260
|
+
log('切换到新版本...');
|
|
261
|
+
const stagingEntries = await remote.readdir(stagingDir);
|
|
262
|
+
if (!stagingEntries) throw new DeployError(`暂存目录不见了:${stagingDir}`);
|
|
263
|
+
const stagingNames = stagingEntries.map(entry => entry.name).toSorted((a, b) => a.localeCompare(b));
|
|
264
|
+
for (const name of stagingNames) {
|
|
265
|
+
await remote.rename(`${stagingDir}/${name}`, `${remotePath}/${name}`);
|
|
266
|
+
movedIn.push(name);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
phase = 'finalize';
|
|
270
|
+
const finalEntries = await remote.readdir(remotePath);
|
|
271
|
+
if (!finalEntries) throw new DeployError(`切换后读不到 ${remotePath}`);
|
|
272
|
+
const finalNames = new Set(finalEntries.map(entry => entry.name));
|
|
273
|
+
const missing = stagingNames.filter(name => !finalNames.has(name));
|
|
274
|
+
if (missing.length > 0) throw new DeployError(`切换后缺少条目:${missing.join('、')}`);
|
|
275
|
+
|
|
276
|
+
if (config.setPermissions) {
|
|
277
|
+
log('设置文件权限:目录 755 / 文件 644');
|
|
278
|
+
await applyPermissions({ remote, config, stagingNames });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
await removeTreeQuietly(remote, stagingDir);
|
|
282
|
+
await pruneBackups({ remote, config, log });
|
|
283
|
+
|
|
284
|
+
return {
|
|
285
|
+
stamp: plan.stamp,
|
|
286
|
+
backupDir: plan.swapNames.length > 0 ? backupDir : null,
|
|
287
|
+
uploadedFiles: plan.localFileCount,
|
|
288
|
+
uploadedBytes: bytes,
|
|
289
|
+
finalEntryCount: finalEntries.length
|
|
290
|
+
};
|
|
291
|
+
} catch (err) {
|
|
292
|
+
if (err instanceof RemoteError && /超出允许范围/.test(err.message)) throw err;
|
|
293
|
+
const partial = phase === 'backup' || phase === 'switch' || phase === 'finalize';
|
|
294
|
+
if (partial) {
|
|
295
|
+
log(`部署在「${PHASE_LABELS[phase]}」阶段失败:${err.message}`);
|
|
296
|
+
log('开始自动回滚,把旧文件移回原位...');
|
|
297
|
+
const failures = await undoSwap({ remote, config, stagingDir, backupDir, movedIn, movedOut });
|
|
298
|
+
if (failures.length === 0) {
|
|
299
|
+
log('回滚完成:网站已恢复为部署前的版本');
|
|
300
|
+
await removeTreeQuietly(remote, stagingDir);
|
|
301
|
+
} else {
|
|
302
|
+
log('回滚没能完全成功,需要人工处理:');
|
|
303
|
+
for (const failure of failures) log(` - ${failure}`);
|
|
304
|
+
log(`旧文件备份位置:${backupDir}`);
|
|
305
|
+
}
|
|
306
|
+
} else {
|
|
307
|
+
await removeTreeQuietly(remote, stagingDir);
|
|
308
|
+
}
|
|
309
|
+
throw err instanceof DeployError ? err : new DeployError(err.message, { cause: err });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function applyPermissions({ remote, config, names }) {
|
|
314
|
+
for (const name of names) {
|
|
315
|
+
const abs = `${config.remotePath}/${name}`;
|
|
316
|
+
const stat = await remote.stat(abs);
|
|
317
|
+
if (stat?.type === 'dir') await chmodTree(remote, abs, 0o755, 0o644);
|
|
318
|
+
else await remote.chmod(abs, 0o644);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function chmodTree(remote, dir, dirMode, fileMode) {
|
|
323
|
+
await remote.chmod(dir, dirMode);
|
|
324
|
+
const entries = await remote.readdir(dir);
|
|
325
|
+
for (const entry of entries ?? []) {
|
|
326
|
+
const abs = `${dir}/${entry.name}`;
|
|
327
|
+
if (entry.type === 'dir') await chmodTree(remote, abs, dirMode, fileMode);
|
|
328
|
+
else await remote.chmod(abs, fileMode);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function removeTreeQuietly(remote, dir) {
|
|
333
|
+
try {
|
|
334
|
+
await removeTree(remote, dir);
|
|
335
|
+
} catch {
|
|
336
|
+
/* 清理失败不影响部署结果,日志里另行提示 */
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** 列出备份的时间戳(新的在前),只读一层目录,用于清理等高频场景。 */
|
|
341
|
+
export async function listBackupStamps({ remote, config }) {
|
|
342
|
+
const { backupsDir } = metaPaths(config);
|
|
343
|
+
const entries = await remote.readdir(backupsDir);
|
|
344
|
+
if (!entries) return [];
|
|
345
|
+
return entries
|
|
346
|
+
.filter(entry => entry.type === 'dir' && STAMP_PATTERN.test(entry.name))
|
|
347
|
+
.map(entry => entry.name)
|
|
348
|
+
.toSorted((a, b) => b.localeCompare(a));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** 列出可用的备份(新的在前),包含文件数和大小(需要遍历,适合 check / list-backups)。 */
|
|
352
|
+
export async function inspectBackups({ remote, config }) {
|
|
353
|
+
const { backupsDir } = metaPaths(config);
|
|
354
|
+
const stamps = await listBackupStamps({ remote, config });
|
|
355
|
+
const backups = [];
|
|
356
|
+
for (const stamp of stamps) {
|
|
357
|
+
const tree = await walkTree(remote, `${backupsDir}/${stamp}`);
|
|
358
|
+
backups.push({
|
|
359
|
+
stamp,
|
|
360
|
+
files: tree.files.length,
|
|
361
|
+
bytes: totalBytes(tree.files),
|
|
362
|
+
mtimeMs: 0
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return backups;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** 只保留最近 keep 份备份(只删 backups 目录里符合时间戳格式的子目录)。 */
|
|
369
|
+
export async function pruneBackups({ remote, config, log }) {
|
|
370
|
+
const stamps = await listBackupStamps({ remote, config });
|
|
371
|
+
const stale = stamps.slice(config.keepBackups);
|
|
372
|
+
if (stale.length === 0) return [];
|
|
373
|
+
const { backupsDir } = metaPaths(config);
|
|
374
|
+
for (const stamp of stale) {
|
|
375
|
+
const dir = `${backupsDir}/${stamp}`;
|
|
376
|
+
if (!STAMP_PATTERN.test(stamp)) continue;
|
|
377
|
+
if (!isInside(config.remoteRoot, dir)) continue;
|
|
378
|
+
await removeTreeQuietly(remote, dir);
|
|
379
|
+
log(`已清理过期备份:${stamp}`);
|
|
380
|
+
}
|
|
381
|
+
return stale;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** 清理 24 小时以前遗留的暂存目录(例如上次部署进程被杀掉)。 */
|
|
385
|
+
export async function cleanupStaleStaging({ remote, config, log, now = Date.now() }) {
|
|
386
|
+
const { metaDir } = metaPaths(config);
|
|
387
|
+
const entries = await remote.readdir(metaDir);
|
|
388
|
+
if (!entries) return [];
|
|
389
|
+
const removed = [];
|
|
390
|
+
for (const entry of entries) {
|
|
391
|
+
if (entry.type !== 'dir') continue;
|
|
392
|
+
if (!/^staging-\d{8}-\d{6}$/.test(entry.name)) continue;
|
|
393
|
+
if (now - (entry.mtimeMs ?? 0) < 24 * 60 * 60 * 1000) continue;
|
|
394
|
+
await removeTreeQuietly(remote, `${metaDir}/${entry.name}`);
|
|
395
|
+
removed.push(entry.name);
|
|
396
|
+
log(`已清理遗留的暂存目录:${entry.name}`);
|
|
397
|
+
}
|
|
398
|
+
return removed;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 回滚到某个备份版本。
|
|
403
|
+
*/
|
|
404
|
+
export async function rollbackRelease({ remote, config, log, targetStamp = null, now = new Date() }) {
|
|
405
|
+
const backups = await inspectBackups({ remote, config });
|
|
406
|
+
if (backups.length === 0) throw new DeployError('服务器上没有可用的备份,无法回滚');
|
|
407
|
+
|
|
408
|
+
const chosen =
|
|
409
|
+
targetStamp && targetStamp !== 'latest' ? backups.find(item => item.stamp === targetStamp) : backups[0];
|
|
410
|
+
if (!chosen) {
|
|
411
|
+
throw new DeployError(`找不到备份 ${targetStamp}。可用备份:${backups.map(item => item.stamp).join('、')}`);
|
|
412
|
+
}
|
|
413
|
+
if (!STAMP_PATTERN.test(chosen.stamp)) throw new DeployError(`备份名不合法:${chosen.stamp}`);
|
|
414
|
+
|
|
415
|
+
const { remotePath } = config;
|
|
416
|
+
const { backupsDir, rollbackDir } = metaPaths(config, makeStamp(now));
|
|
417
|
+
const backupDir = `${backupsDir}/${chosen.stamp}`;
|
|
418
|
+
|
|
419
|
+
const target = await readTarget(remote, config);
|
|
420
|
+
if (!target.exists) throw new DeployError(`remotePath=${remotePath} 不存在,无法回滚`);
|
|
421
|
+
|
|
422
|
+
const swapNames = target.entries
|
|
423
|
+
.filter(entry => !config.preserve.includes(entry.name))
|
|
424
|
+
.map(entry => entry.name)
|
|
425
|
+
.toSorted((a, b) => a.localeCompare(b));
|
|
426
|
+
|
|
427
|
+
log(`回滚到备份 ${chosen.stamp}(${chosen.files} 个文件)`);
|
|
428
|
+
const movedOut = [];
|
|
429
|
+
const movedIn = [];
|
|
430
|
+
try {
|
|
431
|
+
await ensureDir(remote, rollbackDir, { base: config.remoteRoot });
|
|
432
|
+
for (const name of swapNames) {
|
|
433
|
+
await remote.rename(`${remotePath}/${name}`, `${rollbackDir}/${name}`);
|
|
434
|
+
movedOut.push(name);
|
|
435
|
+
}
|
|
436
|
+
const backupEntries = await remote.readdir(backupDir);
|
|
437
|
+
if (!backupEntries) throw new DeployError(`备份目录不见了:${backupDir}`);
|
|
438
|
+
for (const entry of backupEntries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
439
|
+
await remote.rename(`${backupDir}/${entry.name}`, `${remotePath}/${entry.name}`);
|
|
440
|
+
movedIn.push(entry.name);
|
|
441
|
+
}
|
|
442
|
+
await removeTreeQuietly(remote, rollbackDir);
|
|
443
|
+
log('回滚完成');
|
|
444
|
+
return { stamp: chosen.stamp, restoredFiles: movedIn.length, replacedFiles: movedOut.length };
|
|
445
|
+
} catch (err) {
|
|
446
|
+
log(`回滚失败:${err.message},正在恢复现场...`);
|
|
447
|
+
for (const name of movedIn.toReversed()) {
|
|
448
|
+
try {
|
|
449
|
+
await remote.rename(`${remotePath}/${name}`, `${backupDir}/${name}`);
|
|
450
|
+
} catch {
|
|
451
|
+
/* 尽力而为 */
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
for (const name of movedOut.toReversed()) {
|
|
455
|
+
try {
|
|
456
|
+
await remote.rename(`${rollbackDir}/${name}`, `${remotePath}/${name}`);
|
|
457
|
+
} catch {
|
|
458
|
+
/* 尽力而为 */
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
throw err instanceof DeployError ? err : new DeployError(err.message, { cause: err });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { joinInside, assertSafeEntryName, isInside } from './guard.js';
|
|
2
|
+
/**
|
|
3
|
+
* 远程目录的通用操作:建目录、列目录、递归删除。
|
|
4
|
+
* 只依赖 remote 接口(见 remote.mjs),因此可以用内存实现完整测试部署流程。
|
|
5
|
+
*/
|
|
6
|
+
import { RemoteError } from './remote.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 递归确保目录存在。
|
|
10
|
+
* base 是"已经确认存在且允许操作的根",只会从 base 往下创建,避免去 stat 服务器上的 /usr 之类目录。
|
|
11
|
+
*/
|
|
12
|
+
export async function ensureDir(remote, dir, { base = '/' } = {}) {
|
|
13
|
+
if (!isInside(base, dir)) {
|
|
14
|
+
throw new RemoteError(`拒绝创建 ${dir}:不在允许的根目录 ${base} 内`, { path: dir });
|
|
15
|
+
}
|
|
16
|
+
const relative = dir === base ? '' : dir.slice(base === '/' ? 1 : base.length + 1);
|
|
17
|
+
const segments = relative === '' ? [] : relative.split('/');
|
|
18
|
+
let current = base;
|
|
19
|
+
for (const segment of segments) {
|
|
20
|
+
assertSafeEntryName(segment);
|
|
21
|
+
current = current === '/' ? `/${segment}` : `${current}/${segment}`;
|
|
22
|
+
const stat = await remote.stat(current);
|
|
23
|
+
if (!stat) {
|
|
24
|
+
await remote.mkdir(current);
|
|
25
|
+
} else if (stat.type !== 'dir') {
|
|
26
|
+
throw new RemoteError(`${current} 已存在但不是目录,无法继续`, { path: current });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 递归收集目录下所有文件与子目录(相对路径)。 */
|
|
32
|
+
export async function walkTree(remote, baseDir) {
|
|
33
|
+
const files = [];
|
|
34
|
+
const dirs = [];
|
|
35
|
+
|
|
36
|
+
const walk = async (dir, prefix) => {
|
|
37
|
+
const entries = await remote.readdir(dir);
|
|
38
|
+
if (!entries) throw new RemoteError(`目录不存在或不可读:${dir}`, { path: dir });
|
|
39
|
+
for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
|
|
40
|
+
assertSafeEntryName(entry.name);
|
|
41
|
+
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
42
|
+
const abs = joinInside('/', dir, entry.name);
|
|
43
|
+
if (entry.type === 'dir') {
|
|
44
|
+
dirs.push({ rel, path: abs });
|
|
45
|
+
await walk(abs, rel);
|
|
46
|
+
} else {
|
|
47
|
+
files.push({ rel, path: abs, size: entry.size });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
await walk(baseDir, '');
|
|
53
|
+
return { files, dirs };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 递归删除目录(只用于我们自己创建的暂存/备份目录)。 */
|
|
57
|
+
export async function removeTree(remote, dir) {
|
|
58
|
+
const entries = await remote.readdir(dir);
|
|
59
|
+
if (!entries) return;
|
|
60
|
+
for (const entry of entries) {
|
|
61
|
+
const abs = joinInside('/', dir, entry.name);
|
|
62
|
+
if (entry.type === 'dir') {
|
|
63
|
+
await removeTree(remote, abs);
|
|
64
|
+
} else {
|
|
65
|
+
await remote.unlink(abs);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
await remote.rmdir(dir);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function totalBytes(entries) {
|
|
72
|
+
return entries.reduce((sum, entry) => sum + (entry.size ?? 0), 0);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function formatBytes(bytes) {
|
|
76
|
+
if (!Number.isFinite(bytes) || bytes < 0) return '0 B';
|
|
77
|
+
const units = ['B', 'KB', 'MB', 'GB'];
|
|
78
|
+
let value = bytes;
|
|
79
|
+
let unit = 0;
|
|
80
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
81
|
+
value /= 1024;
|
|
82
|
+
unit += 1;
|
|
83
|
+
}
|
|
84
|
+
return `${unit === 0 ? value : value.toFixed(2)} ${units[unit]}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const STAMP_PATTERN = /^\d{8}-\d{6}$/;
|