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
package/src/cli.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import readline from 'node:readline/promises';
|
|
3
|
+
import { c, setColor, parseSize } from './util.js';
|
|
4
|
+
import { tr, setLang, detectLang } from './i18n.js';
|
|
5
|
+
import { scan, loadLast, DETECTORS } from './scan.js';
|
|
6
|
+
import { printReport, printHowToClean } from './report.js';
|
|
7
|
+
import { clean } from './clean.js';
|
|
8
|
+
|
|
9
|
+
export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
10
|
+
|
|
11
|
+
const HELP_ZH = () => `sweepwise —— Mac 开发者磁盘体检
|
|
12
|
+
|
|
13
|
+
用法
|
|
14
|
+
sweepwise 扫描、出报告,然后问你要清理哪些
|
|
15
|
+
sweepwise scan 只扫描出报告(不会删除任何东西)
|
|
16
|
+
sweepwise clean <编号…> 清理上次扫描里的指定项,例如 sweepwise clean 1 3 5-8
|
|
17
|
+
sweepwise clean safe 清理上次扫描里所有绿色(可放心清理)的项
|
|
18
|
+
|
|
19
|
+
选项
|
|
20
|
+
--root <目录> 要扫描的项目目录,可重复;默认 ~/Documents ~/Desktop ~/Downloads ~/code 等
|
|
21
|
+
--min-size <大小> 只列出大于这个大小的项,默认 300M
|
|
22
|
+
--stale-days <天数> 多少天没动算「长期没动」,默认 90
|
|
23
|
+
--only <类别,…> 只扫描某几类:${DETECTORS.map((d) => d.id).join(',')}
|
|
24
|
+
--json 输出 JSON(适合给脚本或 AI 工具读)
|
|
25
|
+
-y, --yes 清理时不再确认
|
|
26
|
+
--delete 直接删除,不放进废纸篓
|
|
27
|
+
--lang <zh|en> 界面语言;默认跟随系统
|
|
28
|
+
--no-color 不用颜色
|
|
29
|
+
-v, --version 显示版本
|
|
30
|
+
-h, --help 显示帮助
|
|
31
|
+
|
|
32
|
+
安全原则
|
|
33
|
+
· 扫描不修改任何文件,也不联网
|
|
34
|
+
· 清理前逐项重新确认(worktree 有没有新改动、日志有没有进程在写)
|
|
35
|
+
· 默认移到废纸篓;能用工具自带命令清理的(npm、docker、git worktree…)就用工具命令
|
|
36
|
+
· 浏览器网站数据只给出操作步骤,不直接删浏览器的文件
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
const HELP_EN = () => `sweepwise — disk checkup for developer Macs
|
|
40
|
+
|
|
41
|
+
Usage
|
|
42
|
+
sweepwise scan, show the report, then ask what to clean
|
|
43
|
+
sweepwise scan scan and report only (never deletes anything)
|
|
44
|
+
sweepwise clean <ids…> clean items from the last scan, e.g. sweepwise clean 1 3 5-8
|
|
45
|
+
sweepwise clean safe clean every green ("safe to clean") item from the last scan
|
|
46
|
+
|
|
47
|
+
Options
|
|
48
|
+
--root <dir> project directory to scan, repeatable; default ~/Documents ~/Desktop ~/Downloads ~/code …
|
|
49
|
+
--min-size <size> only list items larger than this, default 300M
|
|
50
|
+
--stale-days <days> how long untouched counts as idle, default 90
|
|
51
|
+
--only <kind,…> only scan some kinds: ${DETECTORS.map((d) => d.id).join(',')}
|
|
52
|
+
--json print JSON (for scripts and AI agents)
|
|
53
|
+
-y, --yes don't ask for confirmation when cleaning
|
|
54
|
+
--delete delete outright instead of moving to the Trash
|
|
55
|
+
--lang <en|zh> interface language; follows the system by default
|
|
56
|
+
--no-color disable colors
|
|
57
|
+
-v, --version print the version
|
|
58
|
+
-h, --help show this help
|
|
59
|
+
|
|
60
|
+
Safety
|
|
61
|
+
· Scanning never modifies files and makes no network requests
|
|
62
|
+
· Every item is re-checked right before cleaning (new changes in a worktree? a process still writing a log?)
|
|
63
|
+
· Moves to the Trash by default; uses the tool's own command where there is one (npm, docker, git worktree…)
|
|
64
|
+
· Browser website data is never deleted directly — you get the exact settings page to use instead
|
|
65
|
+
`;
|
|
66
|
+
|
|
67
|
+
export function parseArgs(argv) {
|
|
68
|
+
const opts = { roots: [], minSize: 300e6, staleDays: 90, only: [], json: false, yes: false, delete: false, rest: [] };
|
|
69
|
+
for (let i = 0; i < argv.length; i++) {
|
|
70
|
+
const a = argv[i];
|
|
71
|
+
const val = () => {
|
|
72
|
+
if (i + 1 >= argv.length) throw new Error(tr(`${a} 后面需要一个值`, `${a} needs a value`));
|
|
73
|
+
return argv[++i];
|
|
74
|
+
};
|
|
75
|
+
if (a === '-h' || a === '--help') opts.help = true;
|
|
76
|
+
else if (a === '-v' || a === '--version') opts.version = true;
|
|
77
|
+
else if (a === '--root') opts.roots.push(val());
|
|
78
|
+
else if (a === '--min-size') opts.minSize = parseSize(val());
|
|
79
|
+
else if (a === '--stale-days') {
|
|
80
|
+
opts.staleDays = Number(val());
|
|
81
|
+
if (!Number.isFinite(opts.staleDays) || opts.staleDays < 0) throw new Error(tr('--stale-days 需要一个非负数', '--stale-days needs a non-negative number'));
|
|
82
|
+
} else if (a === '--only') opts.only.push(...val().split(','));
|
|
83
|
+
else if (a === '--lang') opts.lang = val();
|
|
84
|
+
else if (a === '--json') opts.json = true;
|
|
85
|
+
else if (a === '-y' || a === '--yes') opts.yes = true;
|
|
86
|
+
else if (a === '--delete') opts.delete = true;
|
|
87
|
+
else if (a === '--no-color') opts.noColor = true;
|
|
88
|
+
else if (a.startsWith('-')) throw new Error(tr(`不认识的选项 ${a}`, `Unknown option ${a}`));
|
|
89
|
+
else opts.rest.push(a);
|
|
90
|
+
}
|
|
91
|
+
const unknown = opts.only.filter((o) => !DETECTORS.some((d) => d.id === o));
|
|
92
|
+
if (unknown.length) throw new Error(tr(`--only 里不认识的类别:${unknown.join(',')}`, `Unknown kind in --only: ${unknown.join(',')}`));
|
|
93
|
+
return opts;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function main(argv) {
|
|
97
|
+
// 语言要最先确定,参数错误提示也要用对语言
|
|
98
|
+
const li = argv.indexOf('--lang');
|
|
99
|
+
setLang(detectLang(li >= 0 ? argv[li + 1] : undefined));
|
|
100
|
+
|
|
101
|
+
if (process.platform !== 'darwin') {
|
|
102
|
+
console.error(tr('sweepwise 目前只支持 macOS。', 'sweepwise currently supports macOS only.'));
|
|
103
|
+
return 1;
|
|
104
|
+
}
|
|
105
|
+
const usage = tr('运行 sweepwise --help 查看用法。', 'Run sweepwise --help for usage.');
|
|
106
|
+
let opts;
|
|
107
|
+
try {
|
|
108
|
+
opts = parseArgs(argv);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.error(`${e.message}\n${usage}`);
|
|
111
|
+
return 2;
|
|
112
|
+
}
|
|
113
|
+
if (opts.noColor || opts.json) setColor(false);
|
|
114
|
+
if (opts.version) {
|
|
115
|
+
console.log(VERSION);
|
|
116
|
+
return 0;
|
|
117
|
+
}
|
|
118
|
+
if (opts.help) {
|
|
119
|
+
console.log(tr(HELP_ZH(), HELP_EN()));
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const [cmd = 'interactive', ...args] = opts.rest;
|
|
124
|
+
|
|
125
|
+
if (cmd === 'clean') {
|
|
126
|
+
const last = await loadLast();
|
|
127
|
+
if (!last) {
|
|
128
|
+
console.error(tr('还没有扫描结果,先运行 sweepwise scan。', 'No scan results yet — run sweepwise scan first.'));
|
|
129
|
+
return 1;
|
|
130
|
+
}
|
|
131
|
+
const ageH = Math.floor((Date.now() - Date.parse(last.createdAt)) / 3.6e6);
|
|
132
|
+
if (ageH >= 24) {
|
|
133
|
+
console.error(tr(`上次扫描是 ${ageH} 小时前,请先重新运行 sweepwise scan。`, `The last scan is ${ageH} hours old — run sweepwise scan again first.`));
|
|
134
|
+
return 1;
|
|
135
|
+
}
|
|
136
|
+
if (!args.length) {
|
|
137
|
+
console.error(tr('请指定要清理的编号,例如 sweepwise clean 1 3 5-8,或 sweepwise clean safe', 'Say what to clean, e.g. sweepwise clean 1 3 5-8 or sweepwise clean safe'));
|
|
138
|
+
return 2;
|
|
139
|
+
}
|
|
140
|
+
await clean(last, args, opts);
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (cmd !== 'scan' && cmd !== 'interactive') {
|
|
145
|
+
console.error(`${tr(`不认识的命令 ${cmd}`, `Unknown command ${cmd}`)}\n${usage}`);
|
|
146
|
+
return 2;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const result = await scan(opts);
|
|
150
|
+
if (opts.json) {
|
|
151
|
+
console.log(JSON.stringify(result, null, 2));
|
|
152
|
+
return 0;
|
|
153
|
+
}
|
|
154
|
+
printReport(result);
|
|
155
|
+
|
|
156
|
+
const canAsk = cmd === 'interactive' && process.stdin.isTTY && process.stdout.isTTY && result.findings.length;
|
|
157
|
+
if (!canAsk) {
|
|
158
|
+
console.log('');
|
|
159
|
+
printHowToClean();
|
|
160
|
+
return 0;
|
|
161
|
+
}
|
|
162
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
163
|
+
const q = tr(
|
|
164
|
+
`\n输入要清理的编号(如 1 3 5-8;${c.green('safe')} = 全部绿色项),直接回车退出:`,
|
|
165
|
+
`\nEnter item numbers to clean (e.g. 1 3 5-8; ${c.green('safe')} = all green items), or press Enter to quit: `,
|
|
166
|
+
);
|
|
167
|
+
const ans = (await rl.question(q)).trim();
|
|
168
|
+
rl.close();
|
|
169
|
+
if (!ans) {
|
|
170
|
+
console.log(c.gray(tr('没有清理任何东西。之后也可以用 sweepwise clean <编号> 清理。', 'Nothing cleaned. You can still run sweepwise clean <ids> later.')));
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
await clean(result, [ans], opts);
|
|
174
|
+
return 0;
|
|
175
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// 失控的日志、崩溃/内存转储、下载后忘了删的安装包。
|
|
2
|
+
// 关键判断:日志是否还有进程在写、多久没写了、最后一行写的是什么。
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { run, HOME, home, openBy, ago, daysSince, truncateWidth, pMap, tildify } from '../util.js';
|
|
6
|
+
import { tr } from '../i18n.js';
|
|
7
|
+
import { finding } from '../model.js';
|
|
8
|
+
|
|
9
|
+
export const id = 'bigfile';
|
|
10
|
+
export const label = () => tr('大文件', 'large files');
|
|
11
|
+
|
|
12
|
+
const LOG_RE = /\.(log|out|err)(\.\d+)?$|\.log\.(old|bak|\d+)$/i;
|
|
13
|
+
const DUMP_RE = /\.(hprof|heapsnapshot|dmp|mdmp|core)$|^core(\.\d+)?$/i;
|
|
14
|
+
const INSTALLER_RE = /\.(dmg|pkg|iso|xip)$/i;
|
|
15
|
+
const PRUNE = ['(', '-name', 'node_modules', '-o', '-name', '.git', '-o', '-name', '.Trash', '-o', '-name', 'Library', ')', '-prune', '-o'];
|
|
16
|
+
|
|
17
|
+
export async function detect(ctx) {
|
|
18
|
+
const kb = Math.max(1, Math.floor(ctx.minSize / 1024));
|
|
19
|
+
const files = new Set();
|
|
20
|
+
for (const root of ctx.roots) {
|
|
21
|
+
ctx.tick(id, 0, 0, root);
|
|
22
|
+
const r = await run('find', [root, '-xdev', ...PRUNE, '-type', 'f', '-size', `+${kb}k`, '-print'], { timeout: 900_000 });
|
|
23
|
+
for (const l of r.stdout.split('\n')) if (l) files.add(l);
|
|
24
|
+
}
|
|
25
|
+
const r = await run('find', [HOME, '-maxdepth', '1', '-type', 'f', '-size', `+${kb}k`]);
|
|
26
|
+
for (const l of r.stdout.split('\n')) if (l) files.add(l);
|
|
27
|
+
|
|
28
|
+
const results = await pMap([...files], classify, 6);
|
|
29
|
+
return results.filter(Boolean);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function classify(file) {
|
|
33
|
+
const base = path.basename(file);
|
|
34
|
+
const st = await fs.stat(file).catch(() => null);
|
|
35
|
+
if (!st) return null;
|
|
36
|
+
const bytes = st.blocks * 512; // 实际占用(稀疏文件不会被高估)
|
|
37
|
+
const days = daysSince(st.mtimeMs);
|
|
38
|
+
|
|
39
|
+
if (LOG_RE.test(base)) {
|
|
40
|
+
const pids = await openBy(file);
|
|
41
|
+
const tail = await lastLine(file);
|
|
42
|
+
const details = [];
|
|
43
|
+
let risk;
|
|
44
|
+
let action = { type: 'trash', paths: [file] };
|
|
45
|
+
const ps = pids.join(', ');
|
|
46
|
+
if (pids.length) {
|
|
47
|
+
risk = 'careful';
|
|
48
|
+
details.push(
|
|
49
|
+
tr(`进程 ${ps} 还开着这个文件`, `Still open by process ${ps}`),
|
|
50
|
+
tr('先停掉它再删,否则空间不会释放', "Stop it first — the space isn't freed while it's open"),
|
|
51
|
+
);
|
|
52
|
+
action = {
|
|
53
|
+
type: 'manual',
|
|
54
|
+
hint: tr(`先停止进程 ${ps}(ps -p ${pids[0]} 查看是谁),再删除 ${file}`, `Stop process ${ps} (see which with ps -p ${pids[0]}), then delete ${file}`),
|
|
55
|
+
};
|
|
56
|
+
} else if (days < 1) {
|
|
57
|
+
risk = 'review';
|
|
58
|
+
details.push(tr('今天还有写入', 'Written to today'), tr('没有进程开着它', 'Not open by any process'));
|
|
59
|
+
} else {
|
|
60
|
+
risk = 'safe';
|
|
61
|
+
details.push(tr(`${days} 天没写入`, `Not written for ${days} day${days === 1 ? '' : 's'}`), tr('没有进程开着它', 'Not open by any process'));
|
|
62
|
+
}
|
|
63
|
+
if (tail) details.push(tr('最后一行:', 'Last line: ') + truncateWidth(tail, 70));
|
|
64
|
+
return finding({ category: id, title: tildify(file), tag: tr('日志', 'log'), bytes, risk, details, paths: [file], action, check: { kind: 'log', path: file } });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (DUMP_RE.test(base)) {
|
|
68
|
+
return finding({
|
|
69
|
+
category: id,
|
|
70
|
+
title: tildify(file),
|
|
71
|
+
tag: tr('转储', 'dump'),
|
|
72
|
+
bytes,
|
|
73
|
+
risk: 'safe',
|
|
74
|
+
details: [tr('崩溃或内存转储,问题查完就没用了', 'Crash or heap dump — useless once the issue is investigated'), tr(`生成于 ${ago(st.mtimeMs)}`, `Created ${ago(st.mtimeMs)}`)],
|
|
75
|
+
paths: [file],
|
|
76
|
+
action: { type: 'trash', paths: [file] },
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const inDownloads = [home('Downloads'), home('Desktop'), HOME].includes(path.dirname(file));
|
|
81
|
+
if (INSTALLER_RE.test(base) && inDownloads && days >= 7) {
|
|
82
|
+
return finding({
|
|
83
|
+
category: id,
|
|
84
|
+
title: tildify(file),
|
|
85
|
+
tag: tr('安装包', 'installer'),
|
|
86
|
+
bytes,
|
|
87
|
+
risk: 'review',
|
|
88
|
+
details: [tr('安装包,装完一般可以删', 'Installer — usually not needed after installing'), tr(`下载于 ${ago(st.mtimeMs)}`, `Downloaded ${ago(st.mtimeMs)}`)],
|
|
89
|
+
paths: [file],
|
|
90
|
+
action: { type: 'trash', paths: [file] },
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return null; // 其他大文件(视频、素材…)是用户自己的内容,不碰
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function lastLine(file) {
|
|
97
|
+
let fh;
|
|
98
|
+
try {
|
|
99
|
+
fh = await fs.open(file, 'r');
|
|
100
|
+
const { size } = await fh.stat();
|
|
101
|
+
const len = Math.min(size, 2048);
|
|
102
|
+
const buf = Buffer.alloc(len);
|
|
103
|
+
await fh.read(buf, 0, len, size - len);
|
|
104
|
+
const lines = buf
|
|
105
|
+
.toString('utf8')
|
|
106
|
+
.replace(/\x1b\[[\d;]*m/g, '')
|
|
107
|
+
.split(/\r?\n/)
|
|
108
|
+
.map((l) => l.trim())
|
|
109
|
+
.filter(Boolean);
|
|
110
|
+
// 日志里可能混着二进制内容:只保留最后一段连续的可读文本
|
|
111
|
+
const last = (lines.pop() ?? '').split(/[\u0000-\u0008\u000e-\u001f\u007f�]+/).pop().trim();
|
|
112
|
+
return last.length >= 8 ? last : '';
|
|
113
|
+
} catch {
|
|
114
|
+
return '';
|
|
115
|
+
} finally {
|
|
116
|
+
await fh?.close();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Chromium 系浏览器里各网站占用的本地存储(IndexedDB、旧版文件系统 API、存储桶)。
|
|
2
|
+
// 浏览器设置页往往只显示其中一部分,比如旧版文件系统存储就不计入。
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { run, home, exists, duBytes, pMap, readdirSafe, statSafe, ago, isRunning, formatBytes } from '../util.js';
|
|
6
|
+
import { tr } from '../i18n.js';
|
|
7
|
+
import { finding } from '../model.js';
|
|
8
|
+
|
|
9
|
+
export const id = 'browser';
|
|
10
|
+
export const label = () => tr('浏览器', 'browsers');
|
|
11
|
+
|
|
12
|
+
const BROWSERS = [
|
|
13
|
+
{ name: 'Chrome', dir: 'Library/Application Support/Google/Chrome', scheme: 'chrome', proc: 'Google Chrome.app' },
|
|
14
|
+
{ name: 'Chrome Beta', dir: 'Library/Application Support/Google/Chrome Beta', scheme: 'chrome', proc: 'Google Chrome Beta.app' },
|
|
15
|
+
{ name: 'Chrome Canary', dir: 'Library/Application Support/Google/Chrome Canary', scheme: 'chrome', proc: 'Google Chrome Canary.app' },
|
|
16
|
+
{ name: 'Edge', dir: 'Library/Application Support/Microsoft Edge', scheme: 'edge', proc: 'Microsoft Edge.app' },
|
|
17
|
+
{ name: 'Brave', dir: 'Library/Application Support/BraveSoftware/Brave-Browser', scheme: 'brave', proc: 'Brave Browser.app' },
|
|
18
|
+
{ name: 'Arc', dir: 'Library/Application Support/Arc/User Data', scheme: 'chrome', proc: 'Arc.app' },
|
|
19
|
+
{ name: 'Vivaldi', dir: 'Library/Application Support/Vivaldi', scheme: 'vivaldi', proc: 'Vivaldi.app' },
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
export async function detect(ctx) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const b of BROWSERS) {
|
|
25
|
+
const base = home(b.dir);
|
|
26
|
+
if (!(await exists(base))) continue;
|
|
27
|
+
for (const prof of await readdirSafe(base)) {
|
|
28
|
+
const pdir = path.join(base, prof);
|
|
29
|
+
if (!(await exists(path.join(pdir, 'Preferences')))) continue;
|
|
30
|
+
ctx.tick(id, 0, 0, `${b.name}/${prof}`);
|
|
31
|
+
out.push(...(await scanProfile(b, prof, pdir, ctx)));
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** "https_www.example.com_0" -> "https://www.example.com" */
|
|
38
|
+
export function originFromId(s) {
|
|
39
|
+
const m = s.match(/^([a-z][a-z0-9+.-]*)_(.+)_(\d+)$/i);
|
|
40
|
+
if (!m) return s;
|
|
41
|
+
return `${m[1]}://${m[2]}${m[3] !== '0' ? ':' + m[3] : ''}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 从 File System/Origins 的 LevelDB 日志里解析「目录编号 -> 网站」。 */
|
|
45
|
+
export function parseOriginsDb(buf) {
|
|
46
|
+
const map = {};
|
|
47
|
+
const marker = Buffer.from('ORIGIN:');
|
|
48
|
+
let i = 0;
|
|
49
|
+
while ((i = buf.indexOf(marker, i)) !== -1) {
|
|
50
|
+
const klen = buf[i - 1];
|
|
51
|
+
if (klen > marker.length && klen < 128) {
|
|
52
|
+
const key = buf.subarray(i, i + klen).toString('latin1');
|
|
53
|
+
const vlen = buf[i + klen];
|
|
54
|
+
if (vlen > 0 && vlen < 16) {
|
|
55
|
+
const val = buf.subarray(i + klen + 1, i + klen + 1 + vlen).toString('latin1');
|
|
56
|
+
if (/^\d+$/.test(val)) map[val] = key.slice(marker.length);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
i += marker.length;
|
|
60
|
+
}
|
|
61
|
+
return map;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function normalizeOrigin(s) {
|
|
65
|
+
return s.split('^')[0].replace(/\/$/, '');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function scanProfile(b, prof, pdir, ctx) {
|
|
69
|
+
/** origin -> { idb, fs, buckets, paths[], lastAccess } */
|
|
70
|
+
const sites = new Map();
|
|
71
|
+
const site = (o) => {
|
|
72
|
+
if (!sites.has(o)) sites.set(o, { idb: 0, fs: 0, buckets: 0, paths: [], lastAccess: 0 });
|
|
73
|
+
return sites.get(o);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// 1) IndexedDB
|
|
77
|
+
const idbDir = path.join(pdir, 'IndexedDB');
|
|
78
|
+
const idbEntries = (await readdirSafe(idbDir)).filter((n) => /\.indexeddb\.(leveldb|blob)$/.test(n));
|
|
79
|
+
await pMap(
|
|
80
|
+
idbEntries,
|
|
81
|
+
async (n) => {
|
|
82
|
+
const p = path.join(idbDir, n);
|
|
83
|
+
const bytes = await duBytes(p);
|
|
84
|
+
const s = site(originFromId(n.replace(/\.indexeddb\.(leveldb|blob)$/, '')));
|
|
85
|
+
s.idb += bytes;
|
|
86
|
+
s.paths.push(p);
|
|
87
|
+
},
|
|
88
|
+
6,
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
// 2) 旧版文件系统 API(File System/<编号>)
|
|
92
|
+
const fsDir = path.join(pdir, 'File System');
|
|
93
|
+
let originMap = {};
|
|
94
|
+
for (const n of await readdirSafe(path.join(fsDir, 'Origins'))) {
|
|
95
|
+
if (!/\.(log|ldb)$/.test(n)) continue;
|
|
96
|
+
const buf = await fs.readFile(path.join(fsDir, 'Origins', n)).catch(() => null);
|
|
97
|
+
if (buf) originMap = { ...originMap, ...parseOriginsDb(buf) };
|
|
98
|
+
}
|
|
99
|
+
const fsIds = (await readdirSafe(fsDir)).filter((n) => /^\d+$/.test(n));
|
|
100
|
+
await pMap(
|
|
101
|
+
fsIds,
|
|
102
|
+
async (n) => {
|
|
103
|
+
const p = path.join(fsDir, n);
|
|
104
|
+
const bytes = await duBytes(p);
|
|
105
|
+
const s = site(originMap[n] ? originFromId(originMap[n]) : tr(`未知网站 #${n}`, `Unknown site #${n}`));
|
|
106
|
+
s.fs += bytes;
|
|
107
|
+
s.paths.push(p);
|
|
108
|
+
},
|
|
109
|
+
6,
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
// 3) 存储桶(WebStorage/<id>,由 QuotaManager 数据库记录归属和最后访问时间)
|
|
113
|
+
const quota = path.join(pdir, 'WebStorage', 'QuotaManager');
|
|
114
|
+
if (await exists(quota)) {
|
|
115
|
+
const r = await run('/usr/bin/sqlite3', [
|
|
116
|
+
'-readonly',
|
|
117
|
+
'-separator',
|
|
118
|
+
'\t',
|
|
119
|
+
`file:${quota.replace(/\?/g, '%3f').replace(/#/g, '%23')}?immutable=1`,
|
|
120
|
+
'select id, storage_key, last_accessed from buckets',
|
|
121
|
+
]);
|
|
122
|
+
const rows = r.stdout.split('\n').filter(Boolean).map((l) => l.split('\t'));
|
|
123
|
+
const lastByOrigin = new Map();
|
|
124
|
+
for (const [, key, la] of rows) {
|
|
125
|
+
const o = normalizeOrigin(key);
|
|
126
|
+
const ms = Number(la) / 1000 - 11644473600000; // Chrome 时间:1601 年起的微秒数
|
|
127
|
+
if (ms > (lastByOrigin.get(o) ?? 0)) lastByOrigin.set(o, ms);
|
|
128
|
+
}
|
|
129
|
+
await pMap(
|
|
130
|
+
rows,
|
|
131
|
+
async ([bid, key]) => {
|
|
132
|
+
const p = path.join(pdir, 'WebStorage', bid);
|
|
133
|
+
if (!(await statSafe(p))) return;
|
|
134
|
+
const bytes = await duBytes(p);
|
|
135
|
+
if (bytes < 1e6) return;
|
|
136
|
+
const s = site(normalizeOrigin(key));
|
|
137
|
+
s.buckets += bytes;
|
|
138
|
+
s.paths.push(p);
|
|
139
|
+
},
|
|
140
|
+
6,
|
|
141
|
+
);
|
|
142
|
+
for (const [o, ms] of lastByOrigin) if (sites.has(o)) sites.get(o).lastAccess = ms;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const running = await isRunning(b.proc);
|
|
146
|
+
const out = [];
|
|
147
|
+
for (const [origin, s] of sites) {
|
|
148
|
+
const bytes = s.idb + s.fs + s.buckets;
|
|
149
|
+
if (bytes < ctx.minSize) continue;
|
|
150
|
+
const parts = [];
|
|
151
|
+
if (s.idb) parts.push(`IndexedDB ${formatBytes(s.idb)}`);
|
|
152
|
+
if (s.fs) parts.push(tr(`旧版文件系统 ${formatBytes(s.fs)}`, `legacy FileSystem ${formatBytes(s.fs)}`));
|
|
153
|
+
if (s.buckets) parts.push(tr(`存储桶 ${formatBytes(s.buckets)}`, `storage buckets ${formatBytes(s.buckets)}`));
|
|
154
|
+
const details = [parts.join(' + ')];
|
|
155
|
+
if (s.fs > 1e9) details.push(tr('旧版文件系统那部分浏览器设置页里看不到', "The legacy FileSystem part doesn't show in the browser's settings page"));
|
|
156
|
+
if (s.lastAccess) details.push(tr(`最后访问 ${ago(s.lastAccess)}`, `Last visited ${ago(s.lastAccess)}`));
|
|
157
|
+
if (/\/\/(localhost|127\.0\.0\.1)/.test(origin)) details.push(tr('本地开发站点', 'Local dev site'));
|
|
158
|
+
const isKnown = origin.includes('://');
|
|
159
|
+
const url = `${b.scheme}://settings/content/siteDetails?site=${encodeURIComponent(origin)}`;
|
|
160
|
+
const all = `${b.scheme}://settings/content/all`;
|
|
161
|
+
const hint = isKnown
|
|
162
|
+
? tr(`在 ${b.name} 打开 ${url} ,点「删除数据」`, `Open ${url} in ${b.name} and click "Delete data"`)
|
|
163
|
+
: tr(
|
|
164
|
+
`在 ${b.name} 打开 ${all} 按大小排序删除;或退出 ${b.name} 后删除 ${s.paths.join(' ')}`,
|
|
165
|
+
`Open ${all} in ${b.name} and delete by size, or quit ${b.name} and delete ${s.paths.join(' ')}`,
|
|
166
|
+
);
|
|
167
|
+
out.push({
|
|
168
|
+
...finding({
|
|
169
|
+
category: id,
|
|
170
|
+
title: origin,
|
|
171
|
+
tag: prof === 'Default' ? b.name : `${b.name}/${prof}`,
|
|
172
|
+
bytes,
|
|
173
|
+
risk: 'review',
|
|
174
|
+
details,
|
|
175
|
+
paths: s.paths,
|
|
176
|
+
action: { type: 'manual', hint },
|
|
177
|
+
}),
|
|
178
|
+
browserRunning: running,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// 开发工具缓存。能用工具自带命令清理的就用命令(比如 npm cache clean),否则移到废纸篓。
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { run, home, which, exists, children, duMany, isRunning } from '../util.js';
|
|
4
|
+
import { tr } from '../i18n.js';
|
|
5
|
+
import { finding } from '../model.js';
|
|
6
|
+
|
|
7
|
+
export const id = 'cache';
|
|
8
|
+
export const label = () => tr('开发缓存', 'dev caches');
|
|
9
|
+
|
|
10
|
+
/** 结尾是 /* 的路径表示「这个目录下的所有内容」(保留目录本身)。 */
|
|
11
|
+
async function expand(paths) {
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const p of paths) {
|
|
14
|
+
if (p.endsWith('/*')) out.push(...(await children(p.slice(0, -2))));
|
|
15
|
+
else if (await exists(p)) out.push(p);
|
|
16
|
+
}
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const L = (...p) => home('Library', ...p);
|
|
21
|
+
|
|
22
|
+
async function definitions() {
|
|
23
|
+
const redownload = tr('下次构建会重新下载依赖', 'Dependencies re-download on the next build');
|
|
24
|
+
const models = tr('模型文件,重新下载可能很慢', 'Model files — re-downloading can be slow');
|
|
25
|
+
const appCaches = (app) => ['Cache', 'CachedData', 'CachedExtensionVSIXs', 'GPUCache', 'Code Cache'].map((n) => L('Application Support', app, n));
|
|
26
|
+
|
|
27
|
+
const defs = [
|
|
28
|
+
{ title: tr('npm 缓存', 'npm cache'), paths: [home('.npm', '_cacache')], risk: 'safe', cmd: ['npm', 'cache', 'clean', '--force'] },
|
|
29
|
+
{ title: tr('Yarn 缓存', 'Yarn cache'), paths: [L('Caches', 'Yarn'), home('.yarn', 'berry', 'cache')], risk: 'safe' },
|
|
30
|
+
{ title: tr('Bun 缓存', 'Bun cache'), paths: [home('.bun', 'install', 'cache')], risk: 'safe' },
|
|
31
|
+
{ title: tr('pip 缓存', 'pip cache'), paths: [L('Caches', 'pip')], risk: 'safe' },
|
|
32
|
+
{ title: tr('uv 缓存', 'uv cache'), paths: [home('.cache', 'uv')], risk: 'safe', cmd: ['uv', 'cache', 'clean'] },
|
|
33
|
+
{ title: tr('CocoaPods 缓存', 'CocoaPods cache'), paths: [L('Caches', 'CocoaPods')], risk: 'safe' },
|
|
34
|
+
{
|
|
35
|
+
title: tr('JetBrains IDE 缓存', 'JetBrains IDE caches'),
|
|
36
|
+
paths: [L('Caches', 'JetBrains') + '/*'],
|
|
37
|
+
risk: 'safe',
|
|
38
|
+
proc: 'JetBrains|WebStorm|IntelliJ|PyCharm|PhpStorm|GoLand|CLion|RustRover|Android Studio',
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
title: tr('Electron / node-gyp / TypeScript 缓存', 'Electron / node-gyp / TypeScript caches'),
|
|
42
|
+
paths: [L('Caches', 'electron'), L('Caches', 'electron-builder'), L('Caches', 'node-gyp'), L('Caches', 'typescript')],
|
|
43
|
+
risk: 'safe',
|
|
44
|
+
},
|
|
45
|
+
{ title: tr('Cursor 缓存', 'Cursor caches'), paths: appCaches('Cursor'), risk: 'safe', proc: 'Cursor.app' },
|
|
46
|
+
{ title: tr('VS Code 缓存', 'VS Code caches'), paths: appCaches('Code'), risk: 'safe', proc: 'Visual Studio Code.app' },
|
|
47
|
+
{
|
|
48
|
+
title: tr('Playwright / Puppeteer 浏览器内核', 'Playwright / Puppeteer browsers'),
|
|
49
|
+
paths: [L('Caches', 'ms-playwright'), L('Caches', 'ms-playwright-go'), home('.cache', 'puppeteer')],
|
|
50
|
+
risk: 'review',
|
|
51
|
+
note: tr('跑测试时会重新下载', 'Re-downloaded the next time tests run'),
|
|
52
|
+
},
|
|
53
|
+
{ title: tr('Gradle 缓存', 'Gradle cache'), paths: [home('.gradle', 'caches')], risk: 'review', note: redownload },
|
|
54
|
+
{ title: tr('Maven 本地仓库', 'Maven local repository'), paths: [home('.m2', 'repository')], risk: 'review', note: redownload },
|
|
55
|
+
{ title: tr('Cargo 下载缓存', 'Cargo registry cache'), paths: [home('.cargo', 'registry')], risk: 'review', note: redownload },
|
|
56
|
+
{ title: tr('Hugging Face 模型', 'Hugging Face models'), paths: [home('.cache', 'huggingface')], risk: 'review', note: models },
|
|
57
|
+
{ title: tr('PyTorch Hub 模型', 'PyTorch Hub models'), paths: [home('.cache', 'torch')], risk: 'review', note: models },
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
// pnpm:用 pnpm 自己的 prune,只删没有项目在用的包
|
|
61
|
+
const pnpmNote = tr('只删没有项目在用的包,实际释放会比这里少', 'Only removes packages no project uses — actual savings will be smaller');
|
|
62
|
+
if (await which('pnpm')) {
|
|
63
|
+
const r = await run('pnpm', ['store', 'path'], { timeout: 15_000 });
|
|
64
|
+
const store = r.ok ? r.stdout.trim() : null;
|
|
65
|
+
// store path 指向 v3/v10 子目录,取它的上级以便覆盖旧版本 store
|
|
66
|
+
if (store) defs.push({ title: 'pnpm store', paths: [path.dirname(store)], risk: 'safe', cmd: ['pnpm', 'store', 'prune'], note: pnpmNote });
|
|
67
|
+
} else {
|
|
68
|
+
defs.push({ title: 'pnpm store', paths: [home('.pnpm-store'), L('pnpm', 'store')], risk: 'safe' });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// conda:删除没有环境在用的包和安装包
|
|
72
|
+
for (const base of ['opt/miniconda3', 'miniconda3', 'anaconda3', 'opt/anaconda3', 'miniforge3', 'mambaforge'].map((b) => home(b))) {
|
|
73
|
+
const condaBin = path.join(base, 'bin', 'conda');
|
|
74
|
+
if ((await exists(path.join(base, 'pkgs'))) && (await exists(condaBin))) {
|
|
75
|
+
defs.push({
|
|
76
|
+
title: tr(`conda 包缓存(${path.basename(base)})`, `conda package cache (${path.basename(base)})`),
|
|
77
|
+
paths: [path.join(base, 'pkgs')],
|
|
78
|
+
risk: 'safe',
|
|
79
|
+
cmd: [condaBin, 'clean', '-a', '-y'],
|
|
80
|
+
note: tr('只删没有环境在用的包,实际释放会比这里少', 'Only removes packages no environment uses — actual savings will be smaller'),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (await which('brew')) {
|
|
86
|
+
const r = await run('brew', ['--cache'], { timeout: 15_000 });
|
|
87
|
+
if (r.ok) defs.push({ title: tr('Homebrew 下载缓存', 'Homebrew download cache'), paths: [r.stdout.trim()], risk: 'safe', cmd: ['brew', 'cleanup', '--prune=all'] });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (await which('go')) {
|
|
91
|
+
const r = await run('go', ['env', 'GOMODCACHE'], { timeout: 15_000 });
|
|
92
|
+
if (r.ok && r.stdout.trim()) {
|
|
93
|
+
defs.push({ title: tr('Go 模块缓存', 'Go module cache'), paths: [r.stdout.trim()], risk: 'review', cmd: ['go', 'clean', '-modcache'], note: redownload });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return defs;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function detect(ctx) {
|
|
100
|
+
const out = [];
|
|
101
|
+
const defs = await definitions();
|
|
102
|
+
let i = 0;
|
|
103
|
+
for (const d of defs) {
|
|
104
|
+
ctx.tick(id, ++i, defs.length, d.title);
|
|
105
|
+
const paths = await expand(d.paths);
|
|
106
|
+
if (!paths.length) continue;
|
|
107
|
+
const bytes = await duMany(paths);
|
|
108
|
+
if (bytes < ctx.cacheMin) continue;
|
|
109
|
+
|
|
110
|
+
let risk = d.risk;
|
|
111
|
+
const details = [];
|
|
112
|
+
if (d.note) details.push(d.note);
|
|
113
|
+
if (d.proc && (await isRunning(d.proc))) {
|
|
114
|
+
risk = 'review';
|
|
115
|
+
details.push(tr('相关应用正在运行,建议先退出', 'The app is running — quit it first'));
|
|
116
|
+
}
|
|
117
|
+
let action = { type: 'trash', paths };
|
|
118
|
+
if (d.cmd && ((await which(d.cmd[0])) || d.cmd[0].startsWith('/'))) {
|
|
119
|
+
action = { type: 'command', argv: d.cmd };
|
|
120
|
+
const shown = [path.basename(d.cmd[0]), ...d.cmd.slice(1, 3)].join(' ');
|
|
121
|
+
details.push(tr(`用 ${shown} 清理`, `Cleaned with ${shown}`));
|
|
122
|
+
} else if (!d.note) {
|
|
123
|
+
details.push(tr('删掉后会自动重建', 'Rebuilt automatically when needed'));
|
|
124
|
+
}
|
|
125
|
+
out.push(finding({ category: id, title: d.title, bytes, risk, details, paths, action }));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Cursor 的对话数据库很大时提醒一下(不能直接删)
|
|
129
|
+
const vscdb = L('Application Support', 'Cursor', 'User', 'globalStorage', 'state.vscdb');
|
|
130
|
+
const vbytes = (await exists(vscdb)) ? await duMany([vscdb]) : 0;
|
|
131
|
+
if (vbytes >= 2e9) {
|
|
132
|
+
out.push(
|
|
133
|
+
finding({
|
|
134
|
+
category: id,
|
|
135
|
+
title: tr('Cursor 对话记录数据库', 'Cursor chat history database'),
|
|
136
|
+
bytes: vbytes,
|
|
137
|
+
risk: 'careful',
|
|
138
|
+
details: [
|
|
139
|
+
tr('存着 Cursor 的聊天和设置,不能直接删', "Holds Cursor's chats and settings — don't delete it directly"),
|
|
140
|
+
tr('在 Cursor 里删掉不要的旧对话才会变小', 'It only shrinks when you delete old chats inside Cursor'),
|
|
141
|
+
],
|
|
142
|
+
paths: [vscdb],
|
|
143
|
+
action: {
|
|
144
|
+
type: 'manual',
|
|
145
|
+
hint: tr('在 Cursor 里删除旧的 Agent / Chat 对话;不要直接删除 state.vscdb', 'Delete old Agent / Chat conversations in Cursor; never delete state.vscdb directly'),
|
|
146
|
+
},
|
|
147
|
+
}),
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|