release-prune.mjs
8.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env node
/**
* 版本目录清理 —— 覆盖式部署的另一面。
*
* 发布是「整目录新增 + 覆盖」:不发 --delete,所以旧版本永远留在部署根上。这是
* 回滚能力的来源,但没有任何机制回收,跑半年后 mfe/ 下会堆几十个 24MB 的目录。
* 主壳以前更糟:assets 直接摊在站点根,hash 文件名让它连「版本」这个概念都没有,
* 只能靠人肉看着删。主壳版本化之后,清理统一成「删整个版本目录」,可枚举、可预演。
*
* node scripts/release/release-prune.mjs --dir /srv/www/console # 只报告
* node scripts/release/release-prune.mjs --dir /srv/www/console --apply --yes
*
* 保留规则(三个条件取并集,任一条命中就不删):
* 1. 清单 manifest.json 当前指向的版本(删了线上立刻坏);
* 2. 站点根 index.html 指向的 host 版本(同上);
* 3. 每个单元按修改时间最新的 --keep 个(默认 3,保证回滚有余量)。
*
* 刻意默认只报告:删除不可逆,而「保守留着」的代价只是硬盘。要真删必须
* --apply 与 --yes 同时给,两个开关是为了让手滑复制粘贴时不会直接删掉线上。
*/
import fs from 'node:fs';
import path from 'node:path';
const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
const paint = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : String(s));
const green = paint('32');
const red = paint('31');
const yellow = paint('33');
const dim = paint('2');
const bold = paint('1');
function die(message) {
console.error(`\n[prune] ${red('✗')} ${message}\n`);
process.exit(1);
}
function parseArgs(argv) {
const flags = new Set(['apply', 'yes', 'help']);
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === '--') continue;
if (!token.startsWith('--')) throw new Error(`无法识别的参数:${token}`);
const eq = token.indexOf('=');
const key = eq > 0 ? token.slice(2, eq) : token.slice(2);
if (flags.has(key)) {
out[key] = true;
continue;
}
const value = eq > 0 ? token.slice(eq + 1) : argv[++i];
if (value === undefined || value.startsWith('--')) throw new Error(`参数 --${key} 缺少取值`);
out[key] = value;
}
return out;
}
const HELP = `
[prune] 清理部署根上的历史版本目录(默认只报告,不删除)
用法:
node scripts/release/release-prune.mjs --dir <部署根> [选项]
参数:
--dir <path> 部署根(含 index.html 与 mfe/ 的那层),必填
--keep <n> 每个单元按时间保留最近 n 个版本,默认 3
--apply 真的删除(不加就是只报告)
--yes 与 --apply 一起用,确认知道删除不可逆
--help 显示本帮助
保留:清单指向的版本、根 index.html 指向的 host 版本、每个单元最近 n 个。
`;
function dirSize(dir) {
let total = 0;
const walk = (p) => {
for (const e of fs.readdirSync(p, { withFileTypes: true })) {
const abs = path.join(p, e.name);
if (e.isDirectory()) walk(abs);
else if (e.isFile()) total += fs.statSync(abs).size;
}
};
walk(dir);
return total;
}
function fmtSize(bytes) {
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)}G`;
if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)}M`;
return `${Math.max(1, Math.round(bytes / 1024))}K`;
}
/** 根 index.html 指向的 host 版本目录名。取不到返回 null(旧结构或没发过主壳)。 */
function hostPinnedVersion(rootDir) {
const file = path.join(rootDir, 'index.html');
if (!fs.existsSync(file)) return null;
const html = fs.readFileSync(file, 'utf8');
const m = html.match(/\/mfe\/host\/([^/"']+)\//);
return m ? m[1] : null;
}
function manifestPinned(rootDir) {
const file = path.join(rootDir, 'mfe', 'manifest.json');
if (!fs.existsSync(file)) return {};
try {
const man = JSON.parse(fs.readFileSync(file, 'utf8'));
const out = {};
for (const [name, entry] of Object.entries(man.subapps ?? {})) {
const m = String(entry?.url ?? '').match(/\/mfe\/[^/]+\/([^/"']+)\/?$/);
if (m) out[name] = m[1];
}
return out;
} catch {
return {};
}
}
function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (e) {
die(e.message);
}
if (args.help) {
console.log(HELP);
return;
}
const dirArg = args.dir ?? process.env.MFE_PRUNE_DIR;
if (!dirArg) die('缺少 --dir <部署根>。用 --help 查看用法。');
const rootDir = path.resolve(dirArg);
if (!fs.existsSync(rootDir)) die(`目录不存在:${rootDir}`);
const mfeDir = path.join(rootDir, 'mfe');
if (!fs.existsSync(mfeDir)) die(`${rootDir} 下没有 mfe/,不像是本项目的部署根,已拒绝。`);
const keep = Math.max(1, Number(args.keep ?? 3) || 3);
const apply = Boolean(args.apply);
if (apply && !args.yes) die('--apply 需要同时给 --yes(删除不可逆,两个开关防手滑)。');
const pinnedHost = hostPinnedVersion(rootDir);
const pinnedApps = manifestPinned(rootDir);
console.log(`\n[prune] ${bold('扫描')} ${dim(rootDir)}`);
console.log(` 每个单元保留最近 ${keep} 个版本`);
console.log(
` 在线引用:host=${pinnedHost ?? '(未识别)'} ` +
`apps=${
Object.entries(pinnedApps)
.map(([k, v]) => `${k}@${v}`)
.join(', ') || '(无)'
}`,
);
console.log('');
const units = [];
for (const entry of fs.readdirSync(mfeDir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (!/^[a-z0-9_-]+$/i.test(entry.name)) continue; // 只认已知形态的单元目录
const unitDir = path.join(mfeDir, entry.name);
const versions = fs
.readdirSync(unitDir, { withFileTypes: true })
.filter(
(e) =>
e.isDirectory() && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(e.name) && !e.name.includes('..'),
)
.map((e) => ({
name: e.name,
dir: path.join(unitDir, e.name),
mtime: fs.statSync(path.join(unitDir, e.name)).mtimeMs,
}))
.sort((a, b) => b.mtime - a.mtime);
if (versions.length === 0) continue;
units.push({ name: entry.name, versions });
}
if (units.length === 0) {
console.log(dim(' mfe/ 下没有任何版本目录,无需清理。\n'));
return;
}
const doomed = [];
for (const unit of units) {
const pinned = unit.name === 'host' ? pinnedHost : pinnedApps[unit.name];
unit.versions.forEach((v, i) => {
const isPinned = v.name === pinned;
const inKeep = i < keep;
if (isPinned || inKeep) return;
doomed.push({ unit: unit.name, ...v });
});
}
for (const unit of units) {
const pinned = unit.name === 'host' ? pinnedHost : pinnedApps[unit.name];
console.log(` ${bold(unit.name)} ${dim(`(${unit.versions.length} 个版本)`)}`);
for (const v of unit.versions) {
const marks = [];
if (v.name === pinned) marks.push(green('在线'));
if (doomed.some((d) => d.unit === unit.name && d.name === v.name)) marks.push(red('将删除'));
console.log(
` ${v.name === pinned ? green('●') : '○'} ${v.name} ${dim(fmtSize(dirSize(v.dir)))} ${
marks.join(' ') || dim('保留')
}`,
);
}
}
if (doomed.length === 0) {
console.log(`\n[prune] 没有可清理的版本目录。\n`);
return;
}
const total = doomed.reduce((s, d) => s + dirSize(d.dir), 0);
console.log('');
console.log(
`[prune] 可清理 ${yellow(String(doomed.length))} 个版本目录,共 ${yellow(fmtSize(total))}`,
);
if (!apply) {
console.log(dim(' 这是预演,未删除任何文件。确认后加 --apply --yes 执行。\n'));
return;
}
let removed = 0;
for (const d of doomed) {
try {
fs.rmSync(d.dir, { recursive: true, force: true });
removed += 1;
console.log(` ${green('✓')} 已删除 mfe/${d.unit}/${d.name}/`);
} catch (err) {
console.log(` ${yellow('!')} 删除失败 mfe/${d.unit}/${d.name}/:${err.message}`);
}
}
console.log(`\n[prune] 完成:删除 ${removed}/${doomed.length} 个,释放约 ${fmtSize(total)}。\n`);
}
main();