sweepwise 0.0.0-stage → 0.1.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/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +114 -2
- package/README.zh-CN.md +100 -0
- package/bin/sweepwise.js +14 -0
- package/package.json +46 -4
- package/src/clean.js +217 -0
- package/src/cli.js +175 -0
- package/src/detectors/bigfiles.js +118 -0
- package/src/detectors/browsers.js +182 -0
- package/src/detectors/caches.js +151 -0
- package/src/detectors/docker.js +71 -0
- package/src/detectors/ignored.js +93 -0
- package/src/detectors/leftovers.js +163 -0
- package/src/detectors/nodeModules.js +94 -0
- package/src/detectors/worktrees.js +176 -0
- package/src/detectors/xcode.js +136 -0
- package/src/i18n.js +32 -0
- package/src/model.js +49 -0
- package/src/report.js +109 -0
- package/src/repos.js +107 -0
- package/src/scan.js +122 -0
- package/src/util.js +238 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Xcode 构建缓存、设备支持文件、模拟器和模拟器运行时。
|
|
2
|
+
import { run, home, which, children, duMany, isRunning, ago, daysSince } from '../util.js';
|
|
3
|
+
import { tr, list } from '../i18n.js';
|
|
4
|
+
import { finding } from '../model.js';
|
|
5
|
+
|
|
6
|
+
export const id = 'xcode';
|
|
7
|
+
export const label = () => 'Xcode';
|
|
8
|
+
|
|
9
|
+
const X = (...p) => home('Library', 'Developer', ...p);
|
|
10
|
+
const s = (n) => (n === 1 ? '' : 's');
|
|
11
|
+
|
|
12
|
+
export async function detect(ctx) {
|
|
13
|
+
if (!(await which('xcrun'))) return [];
|
|
14
|
+
const out = [];
|
|
15
|
+
const xcodeRunning = await isRunning('Xcode.app/Contents/MacOS/Xcode');
|
|
16
|
+
|
|
17
|
+
const dd = await children(X('Xcode', 'DerivedData'));
|
|
18
|
+
const ddBytes = await duMany(dd);
|
|
19
|
+
if (ddBytes >= ctx.cacheMin) {
|
|
20
|
+
out.push(
|
|
21
|
+
finding({
|
|
22
|
+
category: id,
|
|
23
|
+
title: 'Xcode DerivedData',
|
|
24
|
+
bytes: ddBytes,
|
|
25
|
+
risk: xcodeRunning ? 'review' : 'safe',
|
|
26
|
+
details: [
|
|
27
|
+
tr('构建缓存,Xcode 会重新生成', 'Build cache — Xcode regenerates it'),
|
|
28
|
+
xcodeRunning ? tr('Xcode 正在运行,建议先退出', 'Xcode is running — quit it first') : null,
|
|
29
|
+
],
|
|
30
|
+
paths: dd,
|
|
31
|
+
action: { type: 'trash', paths: dd },
|
|
32
|
+
}),
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const ds = [];
|
|
37
|
+
for (const os of ['iOS', 'macOS', 'watchOS', 'tvOS', 'visionOS']) ds.push(...(await children(X('Xcode', `${os} DeviceSupport`))));
|
|
38
|
+
const dsBytes = await duMany(ds);
|
|
39
|
+
if (dsBytes >= ctx.cacheMin) {
|
|
40
|
+
out.push(
|
|
41
|
+
finding({
|
|
42
|
+
category: id,
|
|
43
|
+
title: tr('真机调试支持文件(DeviceSupport)', 'Device support files (DeviceSupport)'),
|
|
44
|
+
bytes: dsBytes,
|
|
45
|
+
risk: 'safe',
|
|
46
|
+
details: [
|
|
47
|
+
tr(`${ds.length} 个系统版本`, `${ds.length} OS version${s(ds.length)}`),
|
|
48
|
+
tr('下次连接真机时会重新生成', 'Regenerated the next time a device is connected'),
|
|
49
|
+
],
|
|
50
|
+
paths: ds,
|
|
51
|
+
action: { type: 'trash', paths: ds },
|
|
52
|
+
}),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
ctx.tick(id, 0, 0, tr('模拟器', 'simulators'));
|
|
57
|
+
const r = await run('xcrun', ['simctl', 'list', 'devices', '-j'], { timeout: 60_000 });
|
|
58
|
+
const usedRuntimes = new Set();
|
|
59
|
+
if (r.ok) {
|
|
60
|
+
const devices = JSON.parse(r.stdout).devices || {};
|
|
61
|
+
const unavailable = [];
|
|
62
|
+
const stale = [];
|
|
63
|
+
for (const [runtime, devs] of Object.entries(devices)) {
|
|
64
|
+
for (const d of devs) {
|
|
65
|
+
const size = (d.dataPathSize || 0) + (d.logPathSize || 0);
|
|
66
|
+
if (d.isAvailable === false) {
|
|
67
|
+
unavailable.push({ ...d, size });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
usedRuntimes.add(runtime);
|
|
71
|
+
const last = d.lastBootedAt ? Date.parse(d.lastBootedAt) : null;
|
|
72
|
+
if ((last === null || daysSince(last) >= ctx.staleDays) && size >= 200e6) stale.push({ ...d, size, last });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const ub = unavailable.reduce((a, d) => a + d.size, 0);
|
|
76
|
+
if (unavailable.length && ub >= ctx.cacheMin) {
|
|
77
|
+
const n = unavailable.length;
|
|
78
|
+
out.push(
|
|
79
|
+
finding({
|
|
80
|
+
category: id,
|
|
81
|
+
title: tr(`失效的模拟器 ${n} 个`, `${n} unavailable simulator${s(n)}`),
|
|
82
|
+
bytes: ub,
|
|
83
|
+
risk: 'safe',
|
|
84
|
+
details: [tr('对应的 iOS 运行时已经没有了,这些模拟器已经开不起来', "Their runtime is gone — these simulators can't boot anymore")],
|
|
85
|
+
paths: unavailable.map((d) => d.dataPath).filter(Boolean),
|
|
86
|
+
action: { type: 'command', argv: ['xcrun', 'simctl', 'delete', 'unavailable'] },
|
|
87
|
+
}),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
const sb = stale.reduce((a, d) => a + d.size, 0);
|
|
91
|
+
if (stale.length && sb >= ctx.cacheMin) {
|
|
92
|
+
const n = stale.length;
|
|
93
|
+
const names = list(stale.slice(0, 4).map((d) => d.name)) + (n > 4 ? ' …' : '');
|
|
94
|
+
out.push(
|
|
95
|
+
finding({
|
|
96
|
+
category: id,
|
|
97
|
+
title: tr(`长期没启动的模拟器 ${n} 个`, `${n} simulator${s(n)} not booted in a long time`),
|
|
98
|
+
bytes: sb,
|
|
99
|
+
risk: 'review',
|
|
100
|
+
details: [
|
|
101
|
+
tr(`${ctx.staleDays} 天以上没启动:${names}`, `Not booted for ${ctx.staleDays}+ days: ${names}`),
|
|
102
|
+
tr('里面装的测试 App 和数据会一起删', 'Installed test apps and their data go with them'),
|
|
103
|
+
],
|
|
104
|
+
paths: stale.map((d) => d.dataPath).filter(Boolean),
|
|
105
|
+
action: { type: 'command', argv: ['xcrun', 'simctl', 'delete', ...stale.map((d) => d.udid)] },
|
|
106
|
+
}),
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 没有任何模拟器在用的 iOS 运行时(单个 7~9 GB)
|
|
112
|
+
const rr = await run('xcrun', ['simctl', 'runtime', 'list', '-j'], { timeout: 60_000 });
|
|
113
|
+
if (rr.ok) {
|
|
114
|
+
for (const rt of Object.values(JSON.parse(rr.stdout || '{}'))) {
|
|
115
|
+
if (!rt.deletable || usedRuntimes.has(rt.runtimeIdentifier)) continue;
|
|
116
|
+
if ((rt.sizeBytes || 0) < ctx.cacheMin) continue;
|
|
117
|
+
const name = rt.runtimeIdentifier.split('.').pop();
|
|
118
|
+
out.push(
|
|
119
|
+
finding({
|
|
120
|
+
category: id,
|
|
121
|
+
title: tr(`模拟器运行时 ${name}(${rt.build})`, `Simulator runtime ${name} (${rt.build})`),
|
|
122
|
+
bytes: rt.sizeBytes,
|
|
123
|
+
risk: 'review',
|
|
124
|
+
details: [
|
|
125
|
+
tr('没有模拟器在用它', 'No simulator uses it'),
|
|
126
|
+
rt.lastUsedAt ? tr(`最后使用 ${ago(Date.parse(rt.lastUsedAt))}`, `Last used ${ago(Date.parse(rt.lastUsedAt))}`) : null,
|
|
127
|
+
tr('需要时可在 Xcode 设置里重新下载', 'Re-download it from Xcode settings when needed'),
|
|
128
|
+
],
|
|
129
|
+
paths: [rt.path].filter(Boolean),
|
|
130
|
+
action: { type: 'command', argv: ['xcrun', 'simctl', 'runtime', 'delete', rt.identifier] },
|
|
131
|
+
}),
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
package/src/i18n.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// 中英双语。每处文字都写成 tr('中文', 'English'),启动时按用户语言选一种。
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
|
|
4
|
+
let lang = 'en';
|
|
5
|
+
|
|
6
|
+
export const tr = (zh, en) => (lang === 'zh' ? zh : en);
|
|
7
|
+
export const getLang = () => lang;
|
|
8
|
+
export function setLang(l) {
|
|
9
|
+
lang = l === 'zh' ? 'zh' : 'en';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const pick = (s) => (/^zh/i.test(s) ? 'zh' : 'en');
|
|
13
|
+
|
|
14
|
+
/** 优先级:--lang > SWEEPWISE_LANG > LC_ALL / LC_MESSAGES / LANG > macOS 系统语言 > 英文 */
|
|
15
|
+
export function detectLang(flag, env = process.env) {
|
|
16
|
+
if (flag) return pick(flag);
|
|
17
|
+
if (env.SWEEPWISE_LANG) return pick(env.SWEEPWISE_LANG);
|
|
18
|
+
const loc = env.LC_ALL || env.LC_MESSAGES || env.LANG;
|
|
19
|
+
if (loc && loc !== 'C' && loc !== 'POSIX') return pick(loc);
|
|
20
|
+
try {
|
|
21
|
+
const out = execFileSync('defaults', ['read', '-g', 'AppleLanguages'], { encoding: 'utf8', timeout: 2000 });
|
|
22
|
+
const m = out.match(/\(\s*"?([\w-]+)"?/);
|
|
23
|
+
if (m) return pick(m[1]);
|
|
24
|
+
} catch {}
|
|
25
|
+
return 'en';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 1 day / 2 days */
|
|
29
|
+
export const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
30
|
+
|
|
31
|
+
/** 中文用顿号,英文用逗号 */
|
|
32
|
+
export const list = (items) => items.join(tr('、', ', '));
|
package/src/model.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// 扫描结果的数据模型。每个发现(finding)都说明:是什么、多大、风险多高、为什么、怎么清理。
|
|
2
|
+
import { tr } from './i18n.js';
|
|
3
|
+
|
|
4
|
+
export const RISKS = {
|
|
5
|
+
safe: { color: 'green', rank: 0, get label() { return tr('可放心清理', 'Safe to clean'); } },
|
|
6
|
+
review: { color: 'yellow', rank: 1, get label() { return tr('看一眼再删', 'Take a look first'); } },
|
|
7
|
+
careful: { color: 'red', rank: 2, get label() { return tr('谨慎', 'Careful'); } },
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export const CATEGORIES = [
|
|
11
|
+
{ key: 'worktree', get title() { return tr('AI 编程工具 / Git worktree', 'AI coding agents / git worktrees'); } },
|
|
12
|
+
{ key: 'ignored', get title() { return tr('仓库里被 git 忽略的大目录', 'Large git-ignored directories in repos'); } },
|
|
13
|
+
{ key: 'bigfile', get title() { return tr('失控日志、崩溃转储、安装包', 'Runaway logs, crash dumps, installers'); } },
|
|
14
|
+
{ key: 'browser', get title() { return tr('浏览器里的网站数据', 'Website data stored in browsers'); } },
|
|
15
|
+
{ key: 'leftover', get title() { return tr('已卸载应用的残留数据', 'Leftovers from uninstalled apps'); } },
|
|
16
|
+
{ key: 'node_modules', get title() { return tr('长期没动的项目里的 node_modules', 'node_modules in long-idle projects'); } },
|
|
17
|
+
{ key: 'xcode', get title() { return tr('Xcode 和模拟器', 'Xcode & simulators'); } },
|
|
18
|
+
{ key: 'docker', get title() { return 'Docker'; } },
|
|
19
|
+
{ key: 'cache', get title() { return tr('开发工具缓存', 'Developer tool caches'); } },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {{type:'trash', paths:string[]} | {type:'command', argv:string[]} | {type:'manual', hint:string}} Action
|
|
24
|
+
* @typedef {{
|
|
25
|
+
* id?: number, key: string, category: string, title: string, tag?: string,
|
|
26
|
+
* bytes: number, risk: 'safe'|'review'|'careful', details: string[],
|
|
27
|
+
* paths: string[], action: Action, check?: object
|
|
28
|
+
* }} Finding
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
export function finding(f) {
|
|
32
|
+
if (!RISKS[f.risk]) throw new Error(`unknown risk ${f.risk}`);
|
|
33
|
+
return {
|
|
34
|
+
key: f.key ?? `${f.category}:${(f.paths ?? [])[0] ?? f.title}`,
|
|
35
|
+
category: f.category,
|
|
36
|
+
title: f.title,
|
|
37
|
+
tag: f.tag,
|
|
38
|
+
bytes: Math.max(0, Math.round(f.bytes || 0)),
|
|
39
|
+
risk: f.risk,
|
|
40
|
+
details: (f.details ?? []).filter(Boolean),
|
|
41
|
+
paths: f.paths ?? [],
|
|
42
|
+
action: f.action,
|
|
43
|
+
check: f.check,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function maxRisk(a, b) {
|
|
48
|
+
return RISKS[a].rank >= RISKS[b].rank ? a : b;
|
|
49
|
+
}
|
package/src/report.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { c, formatBytes, padStart, strWidth, truncateWidth } from './util.js';
|
|
2
|
+
import { tr } from './i18n.js';
|
|
3
|
+
import { CATEGORIES, RISKS } from './model.js';
|
|
4
|
+
|
|
5
|
+
const dot = (risk) => c[RISKS[risk].color]('●');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 折行:优先在「 · 」处断开;单条太长时按词(英文)或按字(中文)断开。
|
|
9
|
+
* 比宽度还长的单词(比如设置页 URL)单独占一行、完整保留,方便复制。
|
|
10
|
+
*/
|
|
11
|
+
export function wrap(text, width, indent) {
|
|
12
|
+
const lines = [];
|
|
13
|
+
let line = '';
|
|
14
|
+
const flush = () => {
|
|
15
|
+
if (line.trim()) lines.push(line.trimEnd());
|
|
16
|
+
line = '';
|
|
17
|
+
};
|
|
18
|
+
for (const part of text.split(' · ')) {
|
|
19
|
+
const sep = line ? ' · ' : '';
|
|
20
|
+
if (strWidth(line + sep + part) <= width) {
|
|
21
|
+
line += sep + part;
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
flush();
|
|
25
|
+
if (strWidth(part) <= width) {
|
|
26
|
+
line = part;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
for (const tok of part.match(/[⺀-]|[^\s⺀-]+|\s+/g) ?? []) {
|
|
30
|
+
if (!line && !tok.trim()) continue;
|
|
31
|
+
if (line && strWidth(line + tok) > width) {
|
|
32
|
+
flush();
|
|
33
|
+
if (!tok.trim()) continue;
|
|
34
|
+
}
|
|
35
|
+
line += tok;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
flush();
|
|
39
|
+
return lines.map((l) => indent + l);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function totals(findings) {
|
|
43
|
+
const t = { safe: 0, review: 0, careful: 0 };
|
|
44
|
+
for (const f of findings) if (!f.done) t[f.risk] += f.bytes;
|
|
45
|
+
return t;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function printReport(result, out = console.log) {
|
|
49
|
+
const cols = Math.max(60, Math.min(process.stdout.columns || 100, 120));
|
|
50
|
+
const { disk, findings } = result;
|
|
51
|
+
const secs = Math.round(result.elapsedMs / 1000);
|
|
52
|
+
out('');
|
|
53
|
+
out(c.bold(tr('sweepwise · Mac 开发者磁盘体检', 'sweepwise · disk checkup for developer Macs')));
|
|
54
|
+
out(
|
|
55
|
+
c.gray(
|
|
56
|
+
tr(
|
|
57
|
+
`磁盘已用 ${formatBytes(disk.used)} / 共 ${formatBytes(disk.total)},可用 ${formatBytes(disk.free)} · 扫描用时 ${secs} 秒`,
|
|
58
|
+
`Disk: ${formatBytes(disk.used)} used of ${formatBytes(disk.total)}, ${formatBytes(disk.free)} free · scanned in ${secs}s`,
|
|
59
|
+
),
|
|
60
|
+
),
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
if (!findings.length) {
|
|
64
|
+
out('\n' + tr('没有发现值得清理的大项目。', 'Nothing big enough to be worth cleaning.'));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const indent = ' '.repeat(18);
|
|
69
|
+
for (const cat of CATEGORIES) {
|
|
70
|
+
const items = findings.filter((f) => f.category === cat.key);
|
|
71
|
+
if (!items.length) continue;
|
|
72
|
+
const sum = formatBytes(items.reduce((a, f) => a + f.bytes, 0));
|
|
73
|
+
out('');
|
|
74
|
+
out(c.bold(cat.title) + c.gray(tr(` ${items.length} 项 · ${sum}`, ` ${items.length} item${items.length === 1 ? '' : 's'} · ${sum}`)));
|
|
75
|
+
for (const f of items) {
|
|
76
|
+
const idStr = padStart(`[${f.id}]`, 5);
|
|
77
|
+
const size = padStart(formatBytes(f.bytes), 8);
|
|
78
|
+
const tag = f.tag ? c.gray(` ${f.tag}`) : '';
|
|
79
|
+
const done = f.done ? c.gray(tr(' (已处理)', ' (done)')) : '';
|
|
80
|
+
const title = truncateWidth(f.title, cols - 20 - strWidth(f.tag ?? '') - 2);
|
|
81
|
+
out(`${c.gray(idStr)} ${dot(f.risk)} ${c.bold(size)} ${title}${tag}${done}`);
|
|
82
|
+
const detail = f.details.join(' · ');
|
|
83
|
+
if (detail) for (const l of wrap(detail, cols - indent.length, indent)) out(c.gray(l));
|
|
84
|
+
if (f.action?.type === 'manual') {
|
|
85
|
+
for (const l of wrap(tr('需手动:', 'Manual: ') + f.action.hint, cols - indent.length, indent)) out(c.yellow(l));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const t = totals(findings);
|
|
91
|
+
out('');
|
|
92
|
+
out(
|
|
93
|
+
`${tr('合计', 'Total')} ${dot('safe')} ${RISKS.safe.label} ${c.bold(formatBytes(t.safe))} ` +
|
|
94
|
+
`${dot('review')} ${RISKS.review.label} ${c.bold(formatBytes(t.review))} ` +
|
|
95
|
+
`${dot('careful')} ${RISKS.careful.label} ${c.bold(formatBytes(t.careful))}`,
|
|
96
|
+
);
|
|
97
|
+
if (result.errors?.length) out(c.gray(tr('部分检查没完成:', 'Some checks did not finish: ') + result.errors.join(tr(';', '; '))));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function printHowToClean(out = console.log) {
|
|
101
|
+
out(
|
|
102
|
+
c.gray(
|
|
103
|
+
tr(
|
|
104
|
+
'清理:sweepwise clean 1 3 5-8 · 所有绿色项:sweepwise clean safe · 默认移到废纸篓,加 --delete 直接删除',
|
|
105
|
+
'Clean: sweepwise clean 1 3 5-8 · all green items: sweepwise clean safe · moves to Trash by default; --delete skips the Trash',
|
|
106
|
+
),
|
|
107
|
+
),
|
|
108
|
+
);
|
|
109
|
+
}
|
package/src/repos.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// 找出本机的 Git 仓库和它们的 worktree,供多个检测器共用。
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { run, git, home, exists, progress } from './util.js';
|
|
5
|
+
import { tr } from './i18n.js';
|
|
6
|
+
|
|
7
|
+
/** AI 编程工具在仓库外存放 worktree 的位置。 */
|
|
8
|
+
export const AGENT_HOMES = [
|
|
9
|
+
[home('.cursor', 'worktrees'), 'Cursor'],
|
|
10
|
+
[home('.codex', 'worktrees'), 'Codex'],
|
|
11
|
+
[home('.claude', 'worktrees'), 'Claude Code'],
|
|
12
|
+
[home('.windsurf', 'worktrees'), 'Windsurf'],
|
|
13
|
+
[home('conductor', 'workspaces'), 'Conductor'],
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
/** 仓库内部由 AI 工具创建 worktree 的目录片段。 */
|
|
17
|
+
const IN_REPO_AGENT_DIRS = [
|
|
18
|
+
['/.claude/worktrees/', 'Claude Code'],
|
|
19
|
+
['/.cursor/worktrees/', 'Cursor'],
|
|
20
|
+
['/.codex/worktrees/', 'Codex'],
|
|
21
|
+
['/.conductor/', 'Conductor'],
|
|
22
|
+
['/.worktrees/', null],
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
export function agentOf(p) {
|
|
26
|
+
for (const [dir, name] of AGENT_HOMES) if (p.startsWith(dir + '/')) return name;
|
|
27
|
+
for (const [frag, name] of IN_REPO_AGENT_DIRS) if (p.includes(frag)) return name;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function parseWorktreeList(out) {
|
|
32
|
+
const items = [];
|
|
33
|
+
let cur = null;
|
|
34
|
+
for (const line of out.split('\n')) {
|
|
35
|
+
if (line.startsWith('worktree ')) {
|
|
36
|
+
cur = { path: line.slice('worktree '.length) };
|
|
37
|
+
items.push(cur);
|
|
38
|
+
} else if (!cur) {
|
|
39
|
+
continue;
|
|
40
|
+
} else if (line.startsWith('HEAD ')) cur.head = line.slice(5);
|
|
41
|
+
else if (line.startsWith('branch ')) cur.branch = line.slice(7).replace(/^refs\/heads\//, '');
|
|
42
|
+
else if (line === 'detached') cur.detached = true;
|
|
43
|
+
else if (line === 'bare') cur.bare = true;
|
|
44
|
+
else if (line.startsWith('locked')) cur.locked = true;
|
|
45
|
+
else if (line.startsWith('prunable')) cur.prunable = true;
|
|
46
|
+
}
|
|
47
|
+
return items;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 读取 worktree 目录里的 .git 文件,返回 gitdir(不存在则 null)。 */
|
|
51
|
+
export async function readGitdirFile(dir) {
|
|
52
|
+
try {
|
|
53
|
+
const txt = await fs.readFile(path.join(dir, '.git'), 'utf8');
|
|
54
|
+
const m = txt.match(/^gitdir:\s*(.+)$/m);
|
|
55
|
+
return m ? path.resolve(dir, m[1].trim()) : null;
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function createRepoIndex(ctx) {
|
|
62
|
+
let promise;
|
|
63
|
+
return () => (promise ??= build(ctx));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function build(ctx) {
|
|
67
|
+
progress(tr('查找 Git 仓库…', 'Finding git repositories…'));
|
|
68
|
+
const repoSet = new Set();
|
|
69
|
+
for (const root of ctx.roots) {
|
|
70
|
+
const r = await run('find', [
|
|
71
|
+
root, '-maxdepth', '6',
|
|
72
|
+
'(', '-name', 'node_modules', '-o', '-name', '.Trash', '-o', '-name', 'Library', ')', '-prune',
|
|
73
|
+
'-o', '-name', '.git', '-type', 'd', '-print',
|
|
74
|
+
]);
|
|
75
|
+
for (const line of r.stdout.split('\n')) if (line.endsWith('/.git')) repoSet.add(path.dirname(line));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 仓库外的 AI 工具 worktree:顺着 .git 文件找回主仓库
|
|
79
|
+
const agentDirs = [];
|
|
80
|
+
for (const [base] of AGENT_HOMES) {
|
|
81
|
+
if (!(await exists(base))) continue;
|
|
82
|
+
const r = await run('find', [base, '-maxdepth', '3', '-name', '.git', '-prune', '-print']);
|
|
83
|
+
for (const line of r.stdout.split('\n').filter(Boolean)) {
|
|
84
|
+
const dir = path.dirname(line);
|
|
85
|
+
const gitdir = await readGitdirFile(dir);
|
|
86
|
+
agentDirs.push({ dir, gitdir });
|
|
87
|
+
const m = gitdir && gitdir.match(/^(.*)\/\.git\/worktrees\/[^/]+$/);
|
|
88
|
+
if (m && (await exists(m[1]))) repoSet.add(m[1]);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const repos = [];
|
|
93
|
+
const worktreePaths = new Set();
|
|
94
|
+
for (const repo of [...repoSet].sort()) {
|
|
95
|
+
const r = await git(repo, ['worktree', 'list', '--porcelain']);
|
|
96
|
+
if (!r.ok) continue;
|
|
97
|
+
const list = parseWorktreeList(r.stdout);
|
|
98
|
+
if (!list.length || list[0].bare) continue;
|
|
99
|
+
// 主仓库是 list[0];如果发现的是某个 worktree 的主仓库路径不一致(比如软链接),以 git 的为准
|
|
100
|
+
repos.push({ path: list[0].path, main: list[0], linked: list.slice(1) });
|
|
101
|
+
for (const wt of list.slice(1)) worktreePaths.add(wt.path);
|
|
102
|
+
}
|
|
103
|
+
// 去重(同一个仓库可能通过不同路径发现)
|
|
104
|
+
const seen = new Set();
|
|
105
|
+
const uniq = repos.filter((r) => (seen.has(r.path) ? false : seen.add(r.path)));
|
|
106
|
+
return { repos: uniq, worktreePaths, agentDirs };
|
|
107
|
+
}
|
package/src/scan.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { home, exists, freeSpace, progress, progressDone, isInside } from './util.js';
|
|
4
|
+
import { CATEGORIES } from './model.js';
|
|
5
|
+
import { tr, getLang } from './i18n.js';
|
|
6
|
+
import { createRepoIndex } from './repos.js';
|
|
7
|
+
import * as worktrees from './detectors/worktrees.js';
|
|
8
|
+
import * as ignored from './detectors/ignored.js';
|
|
9
|
+
import * as bigfiles from './detectors/bigfiles.js';
|
|
10
|
+
import * as browsers from './detectors/browsers.js';
|
|
11
|
+
import * as leftovers from './detectors/leftovers.js';
|
|
12
|
+
import * as nodeModules from './detectors/nodeModules.js';
|
|
13
|
+
import * as xcode from './detectors/xcode.js';
|
|
14
|
+
import * as docker from './detectors/docker.js';
|
|
15
|
+
import * as caches from './detectors/caches.js';
|
|
16
|
+
|
|
17
|
+
export const DETECTORS = [worktrees, ignored, bigfiles, browsers, leftovers, nodeModules, xcode, docker, caches];
|
|
18
|
+
|
|
19
|
+
const DEFAULT_ROOTS = [
|
|
20
|
+
'Documents', 'Desktop', 'Downloads', 'code', 'Code', 'projects', 'Projects', 'dev', 'Developer',
|
|
21
|
+
'src', 'workspace', 'work', 'repos', 'git', 'github', 'Sites',
|
|
22
|
+
];
|
|
23
|
+
|
|
24
|
+
export const LAST_SCAN = home('Library', 'Caches', 'sweepwise', 'last-scan.json');
|
|
25
|
+
|
|
26
|
+
export async function defaultRoots() {
|
|
27
|
+
const out = [];
|
|
28
|
+
for (const r of DEFAULT_ROOTS) {
|
|
29
|
+
const p = home(r);
|
|
30
|
+
// 大小写不敏感的文件系统上 code / Code 是同一个目录
|
|
31
|
+
if ((await exists(p)) && !out.some((o) => o.toLowerCase() === p.toLowerCase())) out.push(await fs.realpath(p));
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function scan(opts) {
|
|
37
|
+
const started = Date.now();
|
|
38
|
+
const roots = opts.roots?.length ? opts.roots.map((r) => path.resolve(r)) : await defaultRoots();
|
|
39
|
+
const selected = opts.only?.length ? DETECTORS.filter((d) => opts.only.includes(d.id)) : DETECTORS;
|
|
40
|
+
|
|
41
|
+
const status = new Map(selected.map((d) => [d.id, '…']));
|
|
42
|
+
let lastRender = 0;
|
|
43
|
+
const render = (force) => {
|
|
44
|
+
if (!force && Date.now() - lastRender < 120) return;
|
|
45
|
+
lastRender = Date.now();
|
|
46
|
+
const pending = [...status].filter(([, s]) => s !== 'done');
|
|
47
|
+
const parts = pending.slice(0, 3).map(([id, s]) => `${DETECTORS.find((d) => d.id === id).label()} ${s}`);
|
|
48
|
+
const n = `${selected.length - pending.length}/${selected.length}`;
|
|
49
|
+
progress(tr(`扫描中(${n})`, `Scanning (${n})`) + ` ${parts.join(' · ')}`);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const ctx = {
|
|
53
|
+
roots,
|
|
54
|
+
minSize: opts.minSize,
|
|
55
|
+
cacheMin: Math.min(opts.minSize, 200e6),
|
|
56
|
+
staleDays: opts.staleDays,
|
|
57
|
+
tick(id, i, n, note) {
|
|
58
|
+
status.set(id, n ? `${i}/${n}` : note ? String(note).split('/').pop() : '…');
|
|
59
|
+
render();
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
ctx.repoIndex = createRepoIndex(ctx);
|
|
63
|
+
|
|
64
|
+
const errors = [];
|
|
65
|
+
const results = await Promise.all(
|
|
66
|
+
selected.map(async (d) => {
|
|
67
|
+
try {
|
|
68
|
+
return await d.detect(ctx);
|
|
69
|
+
} catch (e) {
|
|
70
|
+
errors.push(`${d.label()}${tr(':', ': ')}${e.message}`);
|
|
71
|
+
return [];
|
|
72
|
+
} finally {
|
|
73
|
+
status.set(d.id, 'done');
|
|
74
|
+
render(true);
|
|
75
|
+
}
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
progressDone();
|
|
79
|
+
|
|
80
|
+
const findings = dedupe(results.flat());
|
|
81
|
+
const order = Object.fromEntries(CATEGORIES.map((c, i) => [c.key, i]));
|
|
82
|
+
findings.sort((a, b) => order[a.category] - order[b.category] || b.bytes - a.bytes);
|
|
83
|
+
findings.forEach((f, i) => (f.id = i + 1));
|
|
84
|
+
|
|
85
|
+
const result = {
|
|
86
|
+
tool: 'sweepwise',
|
|
87
|
+
version: 1,
|
|
88
|
+
lang: getLang(),
|
|
89
|
+
createdAt: new Date().toISOString(),
|
|
90
|
+
elapsedMs: Date.now() - started,
|
|
91
|
+
roots,
|
|
92
|
+
disk: await freeSpace(),
|
|
93
|
+
findings,
|
|
94
|
+
errors,
|
|
95
|
+
};
|
|
96
|
+
await save(result);
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 如果一条发现的所有路径都在另一条发现的某个路径里面,就去掉它(避免重复计算)。 */
|
|
101
|
+
export function dedupe(findings) {
|
|
102
|
+
return findings.filter(
|
|
103
|
+
(f) =>
|
|
104
|
+
!f.paths.length ||
|
|
105
|
+
!findings.some(
|
|
106
|
+
(g) => g !== f && g.paths.length && f.paths.every((p) => g.paths.some((q) => isInside(p, q))),
|
|
107
|
+
),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function save(result) {
|
|
112
|
+
await fs.mkdir(path.dirname(LAST_SCAN), { recursive: true });
|
|
113
|
+
await fs.writeFile(LAST_SCAN, JSON.stringify(result, null, 2));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function loadLast() {
|
|
117
|
+
try {
|
|
118
|
+
return JSON.parse(await fs.readFile(LAST_SCAN, 'utf8'));
|
|
119
|
+
} catch {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|