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/CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 — first public release
|
|
4
|
+
|
|
5
|
+
- Scan for AI agent / git worktrees, large git-ignored directories, runaway logs and dumps, browser website data, uninstalled-app leftovers, idle `node_modules`, Xcode data, Docker and developer caches
|
|
6
|
+
- Every item gets a risk level (safe / take a look / careful) and the reasons behind it
|
|
7
|
+
- `clean` re-checks each item before acting, moves files to the Trash by default and uses each tool's own clean command where one exists
|
|
8
|
+
- `--json` output for scripts and AI agents
|
|
9
|
+
- English and Chinese interface, following the system language
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sweepwise contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,115 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sweepwise
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**A disk checkup for developer Macs.** It finds the big chunks of space that generic cleaners can't see or won't judge — and for every item it tells you **whether it's safe to delete, and why**.
|
|
4
|
+
|
|
5
|
+
[中文说明](README.zh-CN.md)
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx sweepwise
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Generic cleaners are good at system caches. On a developer machine, though, the biggest wins usually need context before anyone dares to touch them:
|
|
12
|
+
|
|
13
|
+
| A generic cleaner… | sweepwise… |
|
|
14
|
+
|---|---|
|
|
15
|
+
| sees a 50 GB `.log` file | checks **how long since it was written**, **whether a process still has it open**, and shows **its last line** |
|
|
16
|
+
| sees a directory an AI coding agent left behind | asks git: **uncommitted changes? merged? pushed? still in use?** |
|
|
17
|
+
| clears Chrome's cache | maps IndexedDB and legacy FileSystem storage **back to each website**, including the part Chrome's settings page doesn't show |
|
|
18
|
+
| guesses leftovers by app name | confirms via bundle id and Spotlight that **the app is really gone**, and recognizes **"same app, new bundle id"** |
|
|
19
|
+
| deletes every `node_modules` | only picks projects **idle for months that have a lockfile** |
|
|
20
|
+
|
|
21
|
+
## What a report looks like
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
AI coding agents / git worktrees 7 items · 68.3 GB
|
|
25
|
+
[1] ● 26.4 GB myapp · claude/cinematic-engine Claude Code
|
|
26
|
+
17 uncommitted changes — would be lost · Not merged; 45 unpushed commits (the branch is kept)
|
|
27
|
+
Active just now — may still be in use
|
|
28
|
+
[4] ● 6.9 GB myapp · claude/stickman-skill Claude Code
|
|
29
|
+
No uncommitted changes · Merged into dev · Last active 19 days ago
|
|
30
|
+
|
|
31
|
+
Runaway logs, crash dumps, installers 2 items · 59.3 GB
|
|
32
|
+
[8] ● 59.0 GB ~/work/myapp/.tmp/worker.log log
|
|
33
|
+
Not written for 56 days · Not open by any process
|
|
34
|
+
Last line: [worker] queue error BullMQ could not load the optional 'ioredis' package…
|
|
35
|
+
|
|
36
|
+
Website data stored in browsers 12 items · 31.6 GB
|
|
37
|
+
[26] ● 7.8 GB http://localhost:3000 Chrome
|
|
38
|
+
IndexedDB 7.8 GB · Last visited 18 days ago · Local dev site
|
|
39
|
+
Manual: Open chrome://settings/content/siteDetails?site=http%3A%2F%2Flocalhost%3A3000 in Chrome…
|
|
40
|
+
|
|
41
|
+
Total ● Safe to clean 83.0 GB ● Take a look first 133 GB ● Careful 65.0 GB
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
- 🟢 **Safe to clean** — caches, rebuildable output, merged worktrees with no changes, logs nobody writes to anymore
|
|
45
|
+
- 🟡 **Take a look first** — needs a re-download or reinstall, or might still be useful
|
|
46
|
+
- 🔴 **Careful** — uncommitted work or personal data would be lost
|
|
47
|
+
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
sweepwise # scan → report → ask which item numbers to clean
|
|
52
|
+
sweepwise scan # report only, never deletes anything
|
|
53
|
+
sweepwise clean 4 5 6 # clean items from the last scan
|
|
54
|
+
sweepwise clean 3-8
|
|
55
|
+
sweepwise clean safe # every green item
|
|
56
|
+
sweepwise scan --json # for scripts and AI agents
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Options: `--root <dir>` (repeatable), `--min-size 300M`, `--stale-days 90`, `--only worktree,bigfile`, `--delete` (skip the Trash), `-y`, `--lang en|zh`, `--no-color`.
|
|
60
|
+
|
|
61
|
+
The language follows your system (`--lang`, `SWEEPWISE_LANG`, `LANG`, then the macOS language list).
|
|
62
|
+
|
|
63
|
+
## What it finds
|
|
64
|
+
|
|
65
|
+
| Kind | How it decides | How it cleans |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| AI agent / git worktrees (Claude Code, Cursor, Codex, …) | uncommitted changes, merge and push state, reflog and changed-file times | `git worktree remove` (the branch is kept) |
|
|
68
|
+
| Large git-ignored directories (`.tmp`, `build`, `.next`, `.venv`, …) | `git ls-files --ignored`, with the largest sub-directories listed | Trash |
|
|
69
|
+
| Runaway logs, heap/crash dumps, old installers | open by a process (`lsof`)? how long since the last write? | Trash; logs still being written only get instructions |
|
|
70
|
+
| Website data in Chrome / Edge / Brave / Arc | reads Chrome's Origins and QuotaManager databases for site and last visit | exact settings page link — browser files are never touched |
|
|
71
|
+
| Leftovers from uninstalled apps | bundle id not found among installed apps or in Spotlight; spots old versions | Trash |
|
|
72
|
+
| `node_modules` in idle projects | grouped per repo, judged by git activity and lockfiles | Trash |
|
|
73
|
+
| Xcode: DerivedData, DeviceSupport, unavailable or long-unused simulators, unused runtimes | `simctl` JSON | Trash / `xcrun simctl` |
|
|
74
|
+
| Docker build cache and unused images | `docker system df` | `docker builder/image prune` |
|
|
75
|
+
| Dev caches: npm, pnpm, Yarn, pip, uv, conda, Homebrew, Gradle, Hugging Face, … | known locations | the tool's own clean command, or Trash |
|
|
76
|
+
|
|
77
|
+
## Safety
|
|
78
|
+
|
|
79
|
+
1. **Scanning is read-only and offline.** git runs with `--no-optional-locks`, so it doesn't even refresh the index. Nothing is sent anywhere.
|
|
80
|
+
2. **Every item is re-checked right before cleaning.** A worktree with new changes, a log a process just opened, an app that's back — all skipped.
|
|
81
|
+
3. **The Trash by default** (macOS 15+ uses the built-in `trash`, so "Put Back" works). Where a tool has its own clean command, that's used instead of deleting files.
|
|
82
|
+
4. **Red items are never picked in bulk.** `clean safe` only takes green ones.
|
|
83
|
+
5. **Your content is off-limits.** Videos, assets and other large personal files are never listed.
|
|
84
|
+
|
|
85
|
+
## Real-world numbers
|
|
86
|
+
|
|
87
|
+
On one 1 TB developer Mac that had already been cleaned up once by hand: a ~50-second scan, 70 items — 🟢 83 GB, 🟡 133 GB, 🔴 65 GB. The biggest wins from the manual round were exactly the kind generic cleaners miss:
|
|
88
|
+
|
|
89
|
+
- a log full of the same Redis error, untouched for two months: **55 GB**
|
|
90
|
+
- one website's legacy FileSystem storage in Chrome (Chrome's settings page showed 3 GB): **53 GB**
|
|
91
|
+
- data left behind by an uninstalled chat app: **44 GB**
|
|
92
|
+
- worktrees, chat databases and caches left by AI coding tools: **~100 GB**
|
|
93
|
+
|
|
94
|
+
## Requirements
|
|
95
|
+
|
|
96
|
+
macOS and Node.js 18+. No dependencies: it only uses commands that ship with macOS (`du`, `find`, `git`, `lsof`, `mdfind`, `plutil`, `sqlite3`).
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
npm test # unit + end-to-end tests (node:test, runs against a throwaway fake $HOME)
|
|
102
|
+
node bin/sweepwise.js # run locally
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Roadmap
|
|
106
|
+
|
|
107
|
+
- [ ] HTML report
|
|
108
|
+
- [ ] Menu bar app: warn when space runs low, one-click checkup
|
|
109
|
+
- [ ] Safari / Firefox website data
|
|
110
|
+
- [ ] Claude Code / Cursor skill or MCP server on top of `--json`
|
|
111
|
+
- [ ] Split Service Worker caches per site
|
|
112
|
+
|
|
113
|
+
## License
|
|
114
|
+
|
|
115
|
+
MIT
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# sweepwise
|
|
2
|
+
|
|
3
|
+
**Mac 开发者磁盘体检。** 找出那些普通清理软件看不见、或者不敢判断的大块空间,并告诉你每一项**能不能删、为什么**。
|
|
4
|
+
|
|
5
|
+
[English](README.md)
|
|
6
|
+
|
|
7
|
+
普通清理软件擅长清系统缓存和日志。可开发机上真正的大头,往往要结合上下文判断才敢动:
|
|
8
|
+
|
|
9
|
+
| 普通清理软件 | sweepwise |
|
|
10
|
+
|---|---|
|
|
11
|
+
| 看到一个 50 GB 的 `.log` 文件 | 看它**几天没写入**、**有没有进程还开着它**,并显示**最后一行写了什么** |
|
|
12
|
+
| 看到 AI 编程工具留下的 worktree 目录 | 读 git:**有没有未提交改动、是否已合并、是否已推送、最近还在不在用** |
|
|
13
|
+
| 只能看到 Chrome 的缓存 | 把 IndexedDB、旧版文件系统存储逐个**对应回网站**,还能找出设置页里看不到的那部分 |
|
|
14
|
+
| 按应用名猜残留 | 用 bundle id 和 Spotlight 确认**应用确实已卸载**,还能认出"新版换了 ID 的同一个应用" |
|
|
15
|
+
| 删掉所有 node_modules | 只挑**几个月没动、而且有 lock 文件**的项目 |
|
|
16
|
+
|
|
17
|
+
## 用法
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npx sweepwise # 扫描 → 报告 → 问你要清理哪些编号
|
|
21
|
+
npx sweepwise scan # 只出报告,不删除任何东西
|
|
22
|
+
npx sweepwise clean 4 5 6
|
|
23
|
+
npx sweepwise clean safe # 所有绿色项
|
|
24
|
+
npx sweepwise scan --json # 给脚本或 AI agent 用
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
报告里每一项都有编号、大小、风险颜色和判断理由:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
AI 编程工具 / Git worktree 7 项 · 68.3 GB
|
|
31
|
+
[4] ● 6.9 GB myapp · claude/stickman-skill Claude Code
|
|
32
|
+
没有未提交改动 · 已合并到 dev · 最后活动 19 天前
|
|
33
|
+
[1] ● 26.4 GB myapp · claude/cinematic-engine Claude Code
|
|
34
|
+
17 处未提交改动,删除后会丢失 · 未合并,45 个提交没推送(分支会保留) · 刚刚还在用
|
|
35
|
+
|
|
36
|
+
失控日志、崩溃转储、安装包
|
|
37
|
+
[8] ● 59.0 GB ~/work/myapp/.tmp/worker.log 日志
|
|
38
|
+
56 天没写入 · 没有进程开着它
|
|
39
|
+
最后一行:[worker] queue error BullMQ could not load the optional 'ioredis' package…
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
- 🟢 **可放心清理**:缓存、可重新生成的构建产物、已合并且没有改动的 worktree、停止写入的日志
|
|
43
|
+
- 🟡 **看一眼再删**:需要重新下载或安装、可能还有用的数据
|
|
44
|
+
- 🔴 **谨慎**:会丢失未提交的改动或个人数据
|
|
45
|
+
|
|
46
|
+
常用选项:`--root <目录>`(可重复)、`--min-size 300M`、`--stale-days 90`、`--only worktree,bigfile`、`--delete`(不进废纸篓)、`-y`、`--lang zh|en`。
|
|
47
|
+
|
|
48
|
+
界面语言跟随系统(依次看 `--lang`、`SWEEPWISE_LANG`、`LANG`、macOS 语言设置)。
|
|
49
|
+
|
|
50
|
+
## 能找出的东西
|
|
51
|
+
|
|
52
|
+
| 类别 | 判断依据 | 清理方式 |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| AI 编程工具 / git worktree(Claude Code、Cursor、Codex…) | 未提交改动、合并状态、推送状态、reflog 和改动文件的时间 | `git worktree remove`(分支保留) |
|
|
55
|
+
| 仓库里被 git 忽略的大目录(`.tmp`、`build`、`.next`、`.venv`…) | `git ls-files --ignored`,并列出最大的子目录 | 废纸篓 |
|
|
56
|
+
| 失控日志、内存转储、旧安装包 | 是否被进程打开(`lsof`)、多久没写入 | 废纸篓;正在写的日志只给出提示 |
|
|
57
|
+
| 浏览器网站数据(Chrome / Edge / Brave / Arc) | 解析 Chrome 的 Origins 和 QuotaManager,得到网站和最后访问时间 | 只给出设置页链接,不直接动浏览器文件 |
|
|
58
|
+
| 已卸载应用的残留 | 已安装应用 + Spotlight 都找不到这个 bundle id;识别旧版本 | 废纸篓 |
|
|
59
|
+
| 长期没动的 node_modules | 按仓库分组,看 git 活动和 lock 文件 | 废纸篓 |
|
|
60
|
+
| Xcode:DerivedData、DeviceSupport、失效或很久没用的模拟器、没人用的运行时 | `simctl` 的 JSON 输出 | 废纸篓 / `xcrun simctl` |
|
|
61
|
+
| Docker:构建缓存、没在用的镜像 | `docker system df` | `docker builder/image prune` |
|
|
62
|
+
| 开发缓存:npm、pnpm、yarn、pip、uv、conda、Homebrew、Gradle、Hugging Face… | 已知路径 | 工具自带的清理命令 / 废纸篓 |
|
|
63
|
+
|
|
64
|
+
## 安全设计
|
|
65
|
+
|
|
66
|
+
1. **扫描是只读的,也不联网**:git 命令都带 `--no-optional-locks`,连 index 都不会刷新;不会向任何地方发送数据。
|
|
67
|
+
2. **清理前逐项重新确认**:worktree 是否又有了新改动、日志是否被进程打开、应用是否又装回来了,有变化就跳过。
|
|
68
|
+
3. **默认移到废纸篓**(macOS 15+ 用系统自带的 `trash`,可以"放回原处")。能用工具自带命令清理的,就不直接删文件。
|
|
69
|
+
4. **红色项不会被批量选中**:`clean safe` 只清理绿色项。
|
|
70
|
+
5. **不碰用户内容**:视频、素材之类的大文件不会列出来。
|
|
71
|
+
|
|
72
|
+
## 一台真实开发机上的结果
|
|
73
|
+
|
|
74
|
+
在一台 1 TB 的开发机上(已经用常规方法清理过一轮):扫描用时约 50 秒,找到 70 项,其中 🟢 83 GB、🟡 133 GB、🔴 65 GB。第一轮手动清理时最大的几项,正好都是普通清理软件处理不了的:
|
|
75
|
+
|
|
76
|
+
- 一个停写了 2 个月、内容全是同一条 Redis 报错的日志:**55 GB**
|
|
77
|
+
- 某个网站在 Chrome 旧版文件系统里的存储(Chrome 设置页只显示 3 GB):**53 GB**
|
|
78
|
+
- 卸载微信后留下的数据:**44 GB**
|
|
79
|
+
- AI 编程工具留下的 worktree、对话数据库和缓存:约 **100 GB**
|
|
80
|
+
|
|
81
|
+
## 开发
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm test # 单元测试 + 端到端测试(在临时造的假 $HOME 里跑)
|
|
85
|
+
node bin/sweepwise.js # 本地运行
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
只依赖 Node 18+ 和 macOS 自带的命令(`du`、`find`、`git`、`lsof`、`mdfind`、`plutil`、`sqlite3`)。
|
|
89
|
+
|
|
90
|
+
## 路线图
|
|
91
|
+
|
|
92
|
+
- [ ] 输出 HTML 报告
|
|
93
|
+
- [ ] 菜单栏版:空间不足时提醒,一键体检
|
|
94
|
+
- [ ] Safari / Firefox 网站数据
|
|
95
|
+
- [ ] 作为 Claude Code / Cursor 的 skill 或 MCP 工具,让 agent 直接调用 `--json`
|
|
96
|
+
- [ ] Service Worker 缓存按网站拆分
|
|
97
|
+
|
|
98
|
+
## 许可证
|
|
99
|
+
|
|
100
|
+
MIT
|
package/bin/sweepwise.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../src/cli.js';
|
|
3
|
+
|
|
4
|
+
// 只设置退出码、不调用 process.exit():输出接到管道时(比如 sweepwise scan --json | jq),
|
|
5
|
+
// 立即退出会让还没写完的 stdout 被截断。
|
|
6
|
+
main(process.argv.slice(2)).then(
|
|
7
|
+
(code) => {
|
|
8
|
+
process.exitCode = code ?? 0;
|
|
9
|
+
},
|
|
10
|
+
(err) => {
|
|
11
|
+
console.error(err?.stack || String(err));
|
|
12
|
+
process.exitCode = 1;
|
|
13
|
+
},
|
|
14
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sweepwise",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Disk checkup for developer Macs: finds stale AI-agent worktrees, runaway logs, hidden browser storage, uninstalled-app leftovers and dev caches — and tells you what is safe to delete, and why.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"macos",
|
|
7
|
+
"disk-space",
|
|
8
|
+
"cleanup",
|
|
9
|
+
"cleaner",
|
|
10
|
+
"developer-tools",
|
|
11
|
+
"git-worktree",
|
|
12
|
+
"worktree",
|
|
13
|
+
"claude-code",
|
|
14
|
+
"cursor",
|
|
15
|
+
"codex",
|
|
16
|
+
"node_modules",
|
|
17
|
+
"xcode",
|
|
18
|
+
"docker",
|
|
19
|
+
"cli"
|
|
20
|
+
],
|
|
21
|
+
"author": "hnumaster (https://github.com/hnumaster)",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/hnumaster/sweepwise.git"
|
|
25
|
+
},
|
|
26
|
+
"homepage": "https://github.com/hnumaster/sweepwise#readme",
|
|
27
|
+
"bugs": "https://github.com/hnumaster/sweepwise/issues",
|
|
28
|
+
"type": "module",
|
|
29
|
+
"bin": {
|
|
30
|
+
"sweepwise": "bin/sweepwise.js"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"bin",
|
|
34
|
+
"src",
|
|
35
|
+
"README.zh-CN.md",
|
|
36
|
+
"CHANGELOG.md"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test test/*.test.js"
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=18"
|
|
43
|
+
},
|
|
44
|
+
"os": [
|
|
45
|
+
"darwin"
|
|
46
|
+
],
|
|
47
|
+
"license": "MIT"
|
|
48
|
+
}
|
package/src/clean.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
// 清理:先重新确认(文件还在?worktree 有没有新改动?日志有没有被打开?),再执行。
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import readline from 'node:readline/promises';
|
|
6
|
+
import { c, git, home, exists, formatBytes, freeSpace, openBy, shellQuote, tildify } from './util.js';
|
|
7
|
+
import { tr } from './i18n.js';
|
|
8
|
+
import { RISKS } from './model.js';
|
|
9
|
+
import { save } from './scan.js';
|
|
10
|
+
import { spotlightHasApp } from './detectors/leftovers.js';
|
|
11
|
+
|
|
12
|
+
const s = (n) => (n === 1 ? '' : 's');
|
|
13
|
+
|
|
14
|
+
export function select(findings, tokens) {
|
|
15
|
+
const picked = new Map();
|
|
16
|
+
const errors = [];
|
|
17
|
+
for (const tok of tokens.flatMap((t) => String(t).split(/[\s,,]+/)).filter(Boolean)) {
|
|
18
|
+
if (RISKS[tok]) {
|
|
19
|
+
for (const f of findings) if (f.risk === tok && f.action.type !== 'manual') picked.set(f.id, f);
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
const m = tok.match(/^(\d+)(?:-(\d+))?$/);
|
|
23
|
+
if (!m) {
|
|
24
|
+
errors.push(tr(`看不懂「${tok}」`, `Can't parse "${tok}"`));
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const [a, b] = [Number(m[1]), Number(m[2] ?? m[1])];
|
|
28
|
+
for (let i = Math.min(a, b); i <= Math.max(a, b); i++) {
|
|
29
|
+
const f = findings.find((x) => x.id === i);
|
|
30
|
+
if (f) picked.set(i, f);
|
|
31
|
+
else errors.push(tr(`没有编号 ${i}`, `No item #${i}`));
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return { picked: [...picked.values()].filter((f) => !f.done), errors };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function describeAction(f, del) {
|
|
38
|
+
const a = f.action;
|
|
39
|
+
if (a.type === 'trash') {
|
|
40
|
+
const verb = del ? tr('直接删除', 'Delete') : tr('移到废纸篓', 'Move to Trash:');
|
|
41
|
+
const n = a.paths.length;
|
|
42
|
+
return n === 1 ? `${verb} ${tildify(a.paths[0])}` : tr(`${verb} ${n} 个路径`, `${verb} ${n} paths`);
|
|
43
|
+
}
|
|
44
|
+
if (a.type === 'command') {
|
|
45
|
+
const show = (x) => {
|
|
46
|
+
const t = tildify(x);
|
|
47
|
+
return t.startsWith('~/') ? '~/' + shellQuote(t.slice(2)) : shellQuote(t);
|
|
48
|
+
};
|
|
49
|
+
return tr('运行 ', 'Run: ') + a.argv.map(show).join(' ');
|
|
50
|
+
}
|
|
51
|
+
return tr('需手动:', 'Manual: ') + a.hint;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function clean(result, tokens, opts = {}) {
|
|
55
|
+
const { picked, errors } = select(result.findings, tokens);
|
|
56
|
+
for (const e of errors) console.log(c.yellow(e));
|
|
57
|
+
if (!picked.length) {
|
|
58
|
+
console.log(tr('没有选中可以清理的项。', 'Nothing selected that can be cleaned.'));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const actionable = picked.filter((f) => f.action.type !== 'manual');
|
|
62
|
+
const manual = picked.filter((f) => f.action.type === 'manual');
|
|
63
|
+
|
|
64
|
+
console.log('');
|
|
65
|
+
if (actionable.length) {
|
|
66
|
+
const total = formatBytes(actionable.reduce((a, f) => a + f.bytes, 0));
|
|
67
|
+
const n = actionable.length;
|
|
68
|
+
console.log(c.bold(tr(`将要清理 ${n} 项,共 ${total}:`, `About to clean ${n} item${s(n)}, ${total} in total:`)));
|
|
69
|
+
for (const f of actionable) {
|
|
70
|
+
console.log(` [${f.id}] ${c[RISKS[f.risk].color]('●')} ${formatBytes(f.bytes).padStart(8)} ${f.title}`);
|
|
71
|
+
console.log(c.gray(` ${describeAction(f, opts.delete)}`));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (manual.length) {
|
|
75
|
+
console.log(c.bold('\n' + tr('这几项需要你手动处理:', 'These need to be handled by hand:')));
|
|
76
|
+
for (const f of manual) console.log(` [${f.id}] ${f.title}\n${c.yellow(' ' + f.action.hint)}`);
|
|
77
|
+
}
|
|
78
|
+
if (!actionable.length) return;
|
|
79
|
+
|
|
80
|
+
if (actionable.some((f) => f.risk === 'careful')) {
|
|
81
|
+
console.log(
|
|
82
|
+
c.red(
|
|
83
|
+
'\n' +
|
|
84
|
+
tr(
|
|
85
|
+
'注意:选中的项里有红色(谨慎)项,删除后可能丢失未提交的改动或数据。',
|
|
86
|
+
'Heads up: the selection includes red (careful) items — uncommitted changes or data may be lost.',
|
|
87
|
+
),
|
|
88
|
+
),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
if (opts.delete) {
|
|
92
|
+
console.log(c.red(tr('使用了 --delete:会直接删除,不能从废纸篓恢复。', '--delete is on: items are deleted outright and cannot be restored from the Trash.')));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (!opts.yes) {
|
|
96
|
+
if (!process.stdin.isTTY) {
|
|
97
|
+
console.log(tr('非交互环境下请加 --yes 确认。', 'Not running in an interactive terminal — add --yes to confirm.'));
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
101
|
+
const ans = (await rl.question('\n' + tr('确认执行?(y/N) ', 'Proceed? (y/N) '))).trim().toLowerCase();
|
|
102
|
+
rl.close();
|
|
103
|
+
if (ans !== 'y' && ans !== 'yes') {
|
|
104
|
+
console.log(tr('已取消,什么都没动。', 'Cancelled. Nothing was touched.'));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const before = await freeSpace();
|
|
110
|
+
let trashed = 0;
|
|
111
|
+
console.log('');
|
|
112
|
+
for (const f of actionable) {
|
|
113
|
+
const skip = await revalidate(f);
|
|
114
|
+
if (skip) {
|
|
115
|
+
console.log(`${c.yellow(tr('跳过', 'Skipped'))} [${f.id}] ${f.title}${tr(':', ': ')}${skip}`);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const ok = await execute(f, opts);
|
|
119
|
+
if (ok === true) {
|
|
120
|
+
f.done = true;
|
|
121
|
+
if (f.action.type === 'trash' && !opts.delete) trashed += f.bytes;
|
|
122
|
+
console.log(`${c.green('✓')} [${f.id}] ${f.title} ${c.gray(formatBytes(f.bytes))}`);
|
|
123
|
+
} else {
|
|
124
|
+
console.log(`${c.red('✗')} [${f.id}] ${f.title}${tr(':', ': ')}${ok}`);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
await save(result);
|
|
128
|
+
|
|
129
|
+
const after = await freeSpace();
|
|
130
|
+
console.log('');
|
|
131
|
+
console.log(tr('可用空间:', 'Free space: ') + `${formatBytes(before.free)} → ${c.bold(formatBytes(after.free))}`);
|
|
132
|
+
if (trashed) {
|
|
133
|
+
const t = formatBytes(trashed);
|
|
134
|
+
console.log(c.gray(tr(`另有约 ${t} 在废纸篓里,清空废纸篓后才会真正释放。`, `About ${t} is now in the Trash — empty the Trash to actually free it.`)));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function revalidate(f) {
|
|
139
|
+
const ck = f.check ?? {};
|
|
140
|
+
if (ck.kind === 'worktree') {
|
|
141
|
+
if (!(await exists(ck.path))) return tr('目录已经不在了', 'The directory is gone');
|
|
142
|
+
const st = await git(ck.path, ['status', '--porcelain']);
|
|
143
|
+
if (!st.ok) return tr('读不到 git 状态', "Couldn't read git status");
|
|
144
|
+
const n = st.stdout.split('\n').filter(Boolean).length - (ck.dirty ?? 0);
|
|
145
|
+
if (n > 0) return tr(`扫描之后又多了 ${n} 处改动,请重新扫描`, `${n} new change${s(n)} since the scan — please rescan`);
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
if (ck.kind === 'log') {
|
|
149
|
+
const pids = await openBy(ck.path);
|
|
150
|
+
if (pids.length) return tr(`进程 ${pids.join(', ')} 正在使用它`, `In use by process ${pids.join(', ')}`);
|
|
151
|
+
}
|
|
152
|
+
if (ck.kind === 'leftover' && (await spotlightHasApp(ck.bid, ck.vendorOnly))) {
|
|
153
|
+
return tr('对应的应用又出现了', 'The app is installed again');
|
|
154
|
+
}
|
|
155
|
+
if (f.action.type === 'trash') {
|
|
156
|
+
const alive = [];
|
|
157
|
+
for (const p of f.action.paths) if (await exists(p)) alive.push(p);
|
|
158
|
+
if (!alive.length) return tr('已经不在了', 'Already gone');
|
|
159
|
+
f.action.paths = alive;
|
|
160
|
+
}
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function execute(f, opts) {
|
|
165
|
+
const a = f.action;
|
|
166
|
+
if (a.type === 'trash') return opts.delete ? removeAll(a.paths) : moveToTrash(a.paths);
|
|
167
|
+
if (a.type === 'command') {
|
|
168
|
+
console.log(c.gray('$ ' + a.argv.map((x) => shellQuote(x)).join(' ')));
|
|
169
|
+
const code = await new Promise((resolve) => {
|
|
170
|
+
const p = spawn(a.argv[0], a.argv.slice(1), { stdio: 'inherit' });
|
|
171
|
+
p.on('error', () => resolve(127));
|
|
172
|
+
p.on('close', resolve);
|
|
173
|
+
});
|
|
174
|
+
return code === 0 ? true : tr(`命令退出码 ${code}`, `Command exited with code ${code}`);
|
|
175
|
+
}
|
|
176
|
+
return tr('需要手动处理', 'Needs to be handled by hand');
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function removeAll(paths) {
|
|
180
|
+
try {
|
|
181
|
+
for (const p of paths) await fs.rm(p, { recursive: true, force: true });
|
|
182
|
+
return true;
|
|
183
|
+
} catch (e) {
|
|
184
|
+
return e.message;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function moveToTrash(paths) {
|
|
189
|
+
// macOS 15+ 自带 /usr/bin/trash,能在 Finder 里「放回原处」
|
|
190
|
+
if (!process.env.SWEEPWISE_TRASH_DIR && (await exists('/usr/bin/trash'))) {
|
|
191
|
+
for (let i = 0; i < paths.length; i += 200) {
|
|
192
|
+
const chunk = paths.slice(i, i + 200);
|
|
193
|
+
const res = await new Promise((resolve) => {
|
|
194
|
+
const p = spawn('/usr/bin/trash', chunk, { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
195
|
+
let err = '';
|
|
196
|
+
p.stderr.on('data', (d) => (err += d));
|
|
197
|
+
p.on('error', (e) => resolve(e.message));
|
|
198
|
+
p.on('close', (code) => resolve(code === 0 ? true : err.trim() || `trash exited with code ${code}`));
|
|
199
|
+
});
|
|
200
|
+
if (res !== true) return res;
|
|
201
|
+
}
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
// 兜底(以及测试):直接移动到废纸篓目录,同一个卷上是瞬间完成的重命名
|
|
205
|
+
const trashDir = process.env.SWEEPWISE_TRASH_DIR || home('.Trash');
|
|
206
|
+
try {
|
|
207
|
+
await fs.mkdir(trashDir, { recursive: true });
|
|
208
|
+
for (const p of paths) {
|
|
209
|
+
let dest = path.join(trashDir, path.basename(p));
|
|
210
|
+
if (await exists(dest)) dest += ` ${Date.now()}`;
|
|
211
|
+
await fs.rename(p, dest);
|
|
212
|
+
}
|
|
213
|
+
return true;
|
|
214
|
+
} catch (e) {
|
|
215
|
+
return e.message;
|
|
216
|
+
}
|
|
217
|
+
}
|