squid 0.1.0: macOS 磁盘清理(CLI + TUI)

main
mula.liu 2026-10-13 17:00:50 +08:00
commit 54585ffc40
55 changed files with 22046 additions and 0 deletions

12
.gitattributes vendored 100644
View File

@ -0,0 +1,12 @@
# 统一换行符:*install.sh / release.sh 只要带上 CRLF,在 macOS/Linux 上就是
# 「/usr/bin/env bash\r: bad interpreter」。源码和文档一律以 LF 落盘,
# 二进制产物按二进制处理(它们本来也被 .gitignore 挡在外面)。
* text=auto eol=lf
*.sh text eol=lf
*.rb text eol=lf
*.toml text eol=lf
*.rs text eol=lf
*.md text eol=lf
*.tar.gz binary
*.dmg binary
*.zip binary

55
.gitignore vendored 100644
View File

@ -0,0 +1,55 @@
# squid 的 .gitignore
#
# 原则:仓库里只放源码、文档、脚本和配方。凡是构建出来的、机器本地产生的、
# 或者只用来参考的东西,都不进版本历史——一旦提交进去,3.3 GB 的构建产物就
# 永远赖在历史里了。
# ── 构建产物 ─────────────────────────────────────────────────────────
# cargo 的输出(debug / release / 各 target triple 都在它下面)。
/target/
# scripts/release.sh 的产物:通用二进制 + tar.gz + sha256。
# 发布走 GitHub Release 附件和 Homebrew formula,不进仓库。
/dist/
*.tar.gz
*.sha256
*.dmg
*.zip
# ── 只读参考代码 ─────────────────────────────────────────────────────
# Mole 是本地 clone 的参考项目(自带 .git,272 MB),只用来对照规则设计:
# 不打包、不提交、不发版。
/Mole/
# ── Rust / 覆盖率 ────────────────────────────────────────────────────
**/*.rs.bk
*.profraw
*.profdata
/coverage/
tarpaulin-report.html
default.prof*
# ── Python(测试脚手架 scripts/tui_smoke.py)─────────────────────────
__pycache__/
*.py[cod]
.pytest_cache/
# ── 编辑器 / IDE ─────────────────────────────────────────────────────
.idea/
.vscode/
*.swp
*.swo
*~
# ── macOS / 系统垃圾 ─────────────────────────────────────────────────
.DS_Store
._*
.Spotlight-V100
.Trashes
# ── 本机专属配置 ─────────────────────────────────────────────────────
# squid 的数据在 ~/Library/Application Support/squid,不落在这棵树里;
# 下面这几条只是防止有人把本地实验配置或 .env 顺手 add 进来。
.env
.env.*
!.env.example
*.local

1591
Cargo.lock generated 100644

File diff suppressed because it is too large Load Diff

48
Cargo.toml 100644
View File

@ -0,0 +1,48 @@
[workspace]
resolver = "2"
members = ["crates/*"]
[workspace.package]
version = "0.1.0"
edition = "2021"
rust-version = "1.80"
license = "MIT OR Apache-2.0"
authors = ["squid contributors"]
repository = "https://github.com/nexdev/squid"
description = "squid — one tool for cleaning, uninstalling, purging and monitoring your machine"
[workspace.dependencies]
squid-core = { path = "crates/squid-core" }
squid-platform = { path = "crates/squid-platform" }
squid-rules = { path = "crates/squid-rules" }
squid-engine = { path = "crates/squid-engine" }
squid-stats = { path = "crates/squid-stats" }
squid-tui = { path = "crates/squid-tui" }
anyhow = "1"
thiserror = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.8"
crossbeam-channel = "0.5"
rayon = "1.10"
walkdir = "2.5"
globset = "0.4"
dirs = "6"
libc = "0.2"
plist = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk"] }
crossterm = "0.28"
ratatui = "0.29"
unicode-width = "0.2"
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }
[profile.release]
lto = "thin"
codegen-units = 1
strip = true
panic = "abort"
[profile.dev]
opt-level = 1

17
LICENSE 100644
View File

@ -0,0 +1,17 @@
squid is dual-licensed under either of
* the MIT license (see LICENSE-MIT)
* the Apache License, Version 2.0 (see LICENSE-APACHE)
at your option.
SPDX-License-Identifier: MIT OR Apache-2.0
Note on third-party reference code
----------------------------------
A copy of the GPL-3.0-licensed project "Mole" may exist in this working tree
for behavioural reference only (it is excluded from version control via
.gitignore). squid is a clean-room implementation: it contains no code copied,
translated, or derived from Mole, and it is not linked against GPL code. The
GPL does not apply to the squid sources distributed under the terms above.

202
LICENSE-APACHE 100644
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

21
LICENSE-MIT 100644
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 squid contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

308
README.md 100644
View File

@ -0,0 +1,308 @@
# squid
> clean · uninstall · purge · watch — a system utility that never touches what it does not own
**squid** 用一套 Rust 代码实现了四款经典付费工具的常用能力:
| 参考软件 | squid 对应能力 | 入口 |
| --- | --- | --- |
| CleanMyMac | 缓存 / 日志 / 浏览器垃圾 / Xcode DerivedData 等可再生文件清理 | `squid clean` |
| AppCleaner | 卸载 App 并连带删除散落的残留 | `squid uninstall` |
| (深度清理)| node_modules、构建产物、磁盘镜像、陈旧压缩包 | `squid purge` |
| DaisyDisk | 磁盘占用树,谁吃掉了我的硬盘 | `squid analyze` / `state` 存储面板 |
| iStat Menus | CPU / 内存 / 网络 / 磁盘 / 温度 / 电池 / 进程实时监控 | `squid status` / `state` 系统面板 |
界面(终端里)参考 CleanMyMac:暗色卡片、分组列表、勾选后一键清理。配色按 24-bit 设计,
遇到不支持真彩色的终端(macOS 自带 Terminal.app 就不支持)会自动退到最接近的 256 色,
观感基本一致;`SQUID_TRUECOLOR=always|never` 可以强制。
**状态不依赖颜色**:光标行在降级终端里改用「反白 + 加粗」表达(反白由终端自己的前景/背景色
完成,任何调色板、包括纯灰度终端都能显示),勾选框用加粗 `●` 与细体 `○` 区分,容量条用
`█/░` 字符而非色块。所以在 Terminal.app、`TERM=vt100`、甚至远程 ssh 里,选中/勾选/进度
依然看得出来,不需要真彩色。
- 语言:Rust(`1.80+`,workspace 拆分为 7 个 crate)
- 平台:macOS 已完整支持;Linux / Windows 通过 `squid-platform` 的 `Platform` trait 预留,见 [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
- 形态:命令行 + 内置 TUI(`squid state`),无后台常驻进程
---
## 安装 / 构建
```bash
# 从源码安装到 ~/.cargo/bin
cargo install --path crates/squid-cli
# 或者本地构建调试版本
cargo build -p squid-cli
./target/debug/squid --help
```
squid 是**一条普通命令**,不是 .app:装完之后在任意目录敲 `squid` 就行,
不需要进到软件目录里执行,也不会往 shell 配置里写东西、不留后台进程。
### 发布安装包(不是 dmg)
```bash
./scripts/release.sh
# -> dist/squid-<版本>-universal-apple-darwin.tar.gz (arm64 + x86_64 通用二进制)
# -> dist/squid-<版本>-universal-apple-darwin.tar.gz.sha256
```
脚本做的事:`cargo build --release` 两种 Apple target → `lipo -create` 合成通用二进制
→ ad-hoc `codesign` → 打 tar.gz + sha256,最后打印要填进
[`packaging/homebrew/squid.rb`](packaging/homebrew/squid.rb) 的校验和与
`gh release create` 命令。只出当前芯片的包用 `ARCHES="aarch64-apple-darwin" ./scripts/release.sh`。
**为什么是 tar.gz 而不是 dmg**:dmg 的意义是把 `.app` bundle 拖进 Applications,
而 squid 没有 bundle、没有图标、不参与 LaunchServices,套一层 dmg 只会多一次
「已损坏,无法打开」的隔离属性摩擦。tar.gz 也是 `cargo-binstall` / Homebrew 期望的形状。
真要给别人装,除了 ad-hoc 签名还需要 Apple Developer ID 签名 + `notarytool` 公证:
```bash
codesign --force --options runtime --sign "Developer ID Application: ..." dist/squid
xcrun notarytool submit dist/squid-<版本>-universal-apple-darwin.tar.gz --keychain-profile squid --wait
xcrun stapler staple dist/squid-<版本>-universal-apple-darwin.tar.gz
```
### 装到 PATH
```bash
./scripts/install.sh # 用 target/release/squid
./scripts/install.sh ./dist/squid # 装下载来的二进制
PREFIX=~/.local/bin ./scripts/install.sh # 免 sudo,装进自己的目录
```
`install.sh` 按 `/opt/homebrew/bin` → `/usr/local/bin` → `~/.local/bin` 找第一个可写目录
(`PREFIX=` 可覆盖),装完顺手清 `com.apple.quarantine` 并补一次 ad-hoc 签名。前两个目录
本来就在 PATH 上,所以装完直接就是 `squid ...`;只有落到 `~/.local/bin` 且它不在 PATH 时,
脚本才会打印一行需要追加到 `~/.zshrc` 的 `export PATH=`。
### Homebrew
`packaging/homebrew/squid.rb` 是可直接放进自己 tap 的 formula 模板(`brew install yourname/tools/squid`),
把 release.sh 输出的 sha256 填进去即可。
## 快速上手
先看,再删——所有会动文件的命令都支持 `--dry-run`:
```bash
squid status # 一次性系统快照(CPU / 内存 / 磁盘 / 进程)
squid doctor # 权限、配置、历史记录自检
squid clean --dry-run # 看看能清多少,什么都不删
squid clean # 扫描 → 逐项确认 → 移入废纸篓
squid clean --categories caches,browsers --min-age 7
squid uninstall --list # 已安装的 App 及体积
squid uninstall Xmind --dry-run # 预览 App 本体 + 残留清单
squid uninstall Xmind # 卸载并删除残留
squid purge --dry-run # 项目构建产物(node_modules 等)
squid purge ~/code ~/work # 指定目录
squid analyze ~/Library/Caches # 磁盘占用树(DaisyDisk 式)
squid history # squid 删过什么
squid undo # 把最近一次进废纸篓的会话还原回去
squid state # 进入 TUI
```
## 命令一览
全局参数:`--json`(机器可读,日志走 stderr)、`--quiet`、`--no-color`。
| 命令 | 作用 | 常用参数 |
| --- | --- | --- |
| `clean` | 按规则清理缓存、日志、浏览器与开发者垃圾、崩溃报告、废纸篓等 39 条内置规则 | `--dry-run` `-y` `--categories <a,b>` `--orphans` `--min-age <天>` `--user-only` `--trash` `--permanent` |
| `uninstall [NAME]` | 按名称或 bundle id 定位 App,生成并执行「本体 + 残留」计划 | `--list` `--dry-run` `-y` `--trash` `--permanent` `--json` |
| `purge [PATHS…]` | 深度清理:项目构建目录、磁盘镜像、安装包、陈旧下载 | `--dry-run` `-y` `--all` `--min-age <天>` `--json` |
| `state` | 打开 TUI:清理 / 卸载 / 深度清理 / 存储 / 系统 / 历史 六个面板 | — |
| `status` | 系统快照,适合脚本与 cron | `--processes <n>` |
| `analyze [PATH]` | 单路径体积树 + 最大文件(默认主目录) | `--depth <层>` `--top <n>` `--files` |
| `history` | 历史会话(时间、命令、释放空间、条目数) | `--limit <n>` |
| `undo [ID]` | 还原某次废纸篓会话(默认最近一次) | — |
| `whitelist add\|list\|remove` | 保护路径,任何扫描都不会再选中它 | — |
| `rules` | 列出当前生效的规则 | `--json` |
| `doctor` | 权限探测、配置与历史健康检查 | `--json` |
## TUI(`squid state`)
六个面板,CleanMyMac 式卡片布局:`1` 清理 · `2` 卸载 · `3` 深度清理 · `4` 存储 · `5` 系统 · `6` 历史。
启动后焦点默认落在左侧的功能选择区:`↑`/`↓` 直接选功能,`enter`(或 `esc`)把方向键交还给右侧的数据列表,
再按一次 `esc` 又回到菜单;`1`–`6` 与 `Tab` 任何时候都能直达。
| 按键 | 功能 |
| --- | --- |
| `Tab` / `1`–`6` | 切换面板 |
| `esc` | 逐级返回,一次只退一级:确认框 → 取消;卸载计划 → 应用列表;最大文件 → 原来的目录;目录 → 上一级;列表 → 功能菜单。帮助浮层、筛选输入框同样吃 `esc`(`n`、`backspace` 也能取消确认框) |
| `⌥↑` / `⌥↓`(或 `Ctrl+↑/↓`) | 在任意面板直接切换六个功能 |
| `j` `k` `↑` `↓`、`PgUp/PgDn`、`Home/End` | 移动 |
| `space` | 勾选项目或整个分组 |
| `enter` | 扫描 / 查看详情 / 进入目录 |
| `s` | 扫描当前面板 |
| `a` | 全选 / 全不选 |
| `d` | 清理已勾选内容 |
| `m` | 废纸篓 ⇄ 永久删除 |
| `u` | 还原上一次废纸篓会话 |
| `f` | 卸载面板:筛选应用列表(输入即筛选,`esc` 清空筛选、`enter` 保留);存储面板:列出当前目录里最大的文件 |
| `h` `l` `←` `→` | 折叠 / 进入 |
| `r` | 刷新当前面板(存储面板重新扫描磁盘占用) |
| `c` | 取消正在运行的任务(`esc` 只负责返回,不取消任务) |
| `?` / `q` | 帮助 / 退出 |
界面语言自动跟随 `$LANG`(中文环境下为中文),也可在配置里写 `language = "en"` 强制英文。
任务进行中按下的按键不会石沉大海:squid 会弹出提示并说清楚是哪个任务占着通道
(「删除还在进行,请稍候,或按 `c` 取消」),确认框在忙时按回车只会保留你的回答、等任务结束再按一次即可。
存储面板的磁盘扫描是唯一允许跑在后台的任务:它只读、可能要走几十秒,因此它只把自己挂在标题上的
「后台扫描」徽章,不会让卸载、清理等其它功能报「上一个任务还在进行」;删除完成后的磁盘占用刷新也走这条后台通道,
进度条结束后一定消失,不留着一条跑完的旧进度条装成卡住的样子。
颜色在启动的那一刻就探测完,日志第一行会写出这次拿到的是哪一档,而不是等第一张卡片画错了再猜:
1. **24-bit 真彩色**:只有终端**明确说得出**自己支持才给(`COLORTERM=truecolor`/`24bit`、iTerm、WezTerm、
Ghostty、VS Code 这类白名单、或 `TERM` 里带 `truecolor`)。按设计的 RGB 原样绘制,选中行是设计稿里的那条强调色底条。
2. **256 色**(Apple 的 Terminal.app、`TERM=xterm`、ssh 到老机器、什么都没说的终端):每个 RGB 就近换成 xterm
调色板里的条目。这一档是默认落点——调色板小一点的代价只是颜色近似,而看不懂 `48;2;r;g;b` 的终端会直接把那串数字打在屏幕上。
强调色在小调色板里靠不住,所以选中行换成**灰底高亮条**,右侧数据列表用相邻两级灰度条纹交替——
行与行的分别由灰度承担,一行可以从左读到右,光标也不会是 flat 灰板上唯一亮着的一格。
两个相邻的灰度若被量化成同一个索引,会自动在灰阶上再走一级,条纹不会消失。
3. **没有调色板**(设置了 `NO_COLOR`、或 `TERM=dumb`):完全不发颜色,选中行用反白 + 加粗,
勾选态和菜单里的 `[n]` 徽章另带符号,不依赖任何颜色。
`SQUID_TRUECOLOR=never|always` 可以手动降级 / 升级,`NO_COLOR` 与全局的 `squid --no-color` 一样强制走第三档。
### 数字是怎么显示的
账本里的数字最容易骗人,所以它有明确的规矩:
- **历史/账本一律两位小数**(`24.31 GB`、`753.66 MB`),列表和侧栏为了紧凑仍是一位(`13.0 GB`)。
- **计数一定带单位并分组**:中文 `1,634 项`、英文 `1,634`。`1634·24.3 GB` 这种写法已经消失了——
中间那个点正好落在小数点该在的位置,两个数会被读成一个坏掉的数。
- **「可删除」说的是还没删的东西**:清理面板的标题是 `清理 · 62 项 · 可删除 1.79 GB / 25.35 GB`,
即「已勾选 / 全部发现」,不会再用「已删除」把待办写成结果。
- **进废纸篓不算已释放**:`d` 默认只是 `rename` 到 `~/.Trash`,同一卷上的改名一个字节都没离开磁盘。
标题会写 `27.21 GB 移入废纸篓 · 清空废纸篓后才真正释放`,`u` 还原过的会话在总计里算 `0`,
那一行自己标 `已还原`(记录本身仍写它当时删了多少)。
- **删除成功后自动重扫**:一次真实删除会让面板上每个数字都过时(缓存会重建、规则命中的文件也换了),
所以删除完成即自动跑一遍 `s`,侧栏「分组」的容量随之重算;存储面板的磁盘占用走后台刷新,
若你正停在某个下钻目录里,则只提示「按 `r` 重新扫描」,不会把你正在读的东西抽走。
- 中文界面里连分组名都是中文:开发文件 / 系统垃圾 / 应用缓存 / 浏览器缓存 / 日志与崩溃报告 /
构建产物 / 废纸篓 / 多余语言包 / 卸载残留。
## 安全模型
squid 的前提是:**它可以清理一个 245 GB 的系统盘,但不能毁掉其中的任何一个用户文件。**
1. **默认进废纸篓**。`DeleteMode::Trash` 是默认值,`--permanent` 才真正 `unlink`。卸载计划里的 App
本体(`/Applications/Foo.app`)是真正被删除的一项,不是只删残留;`u` 或 `squid undo` 原样放回。
2. **`--dry-run` everywhere**。任何会删除的命令都能只看不动。
3. **非交互环境需要显式确认**。stdin 不是 TTY 时,没有 `-y/--yes` 就直接拒绝执行删除。
4. **删除时二次校验**。扫描结果可能已经过时,`squid_engine::delete::execute` 会对每一条重新做安全检查、白名单检查和锚点校验,嵌套子项在父项之前处理,避免重复计数与 ENOENT。
5. **硬性禁区**。`squid_core::safety::SafetyPolicy` 内置 `HARD_DENY`(`/`、`/usr`、`/System`、`/Library`、`/Applications`、`/private/var/folders`…)与 `DENY_EXACT`(`~/Library`、`~/Documents`、`~/.ssh`、`~/.aws`… 只允许删子项、不允许整目录递归删除),递归删除还要求在允许的锚点之下至少 `min_depth = 1` 层,并且永不跟随符号链接。
6. **规则自带刹车**:`protect` 白名单、`min_age_days`、`needs_admin`、`skip_if_running`(例如 Docker Desktop 正在运行时不会提出删它的 1 TB 虚拟机磁盘)、`risky`(默认不勾选并提示复核)。
7. **删除账本 + `undo`**。每次真实删除写一个 JSON 会话(含每条的废纸篓目标路径),`squid undo` 把仍留在废纸篓里的文件原样放回。
8. **白名单**。`squid whitelist add '~/Library/Caches/com.apple.Safari'` 之后,任何规则、任何面板都不会再选中它。
## 配置
配置文件:`~/Library/Application Support/squid/config.toml`(`squid doctor` 会打印实际路径)。
```toml
delete_mode = "trash" # trash | permanent
history_keep = 60 # 保留多少条历史会话
purge_min_age_days = 7 # 7 天内动过的构建产物不算垃圾
purge_max_entries = 200000 # 单个项目探测的文件数上限
show_allocated = true # 显示实际占盘大小而非逻辑大小
language = "zh" # "en" | "zh",留空跟随 $LANG
whitelist = ["~/Library/Caches/ImportantApp"]
disabled_rules = ["user-trash"]
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
```
环境变量:
| 变量 | 作用 |
| --- | --- |
| `SQUID_CONFIG_DIR` | 覆盖配置目录(可移植安装、CI、测试) |
| `SQUID_STATE_DIR` | 覆盖状态目录(历史账本所在地) |
| `SQUID_TRUECOLOR` | `always` / `never` 强制指定配色能力,跳过自动探测 |
| `SQUID_LANG` | `zh` / `en` 强制界面语言,等价于 `squid --lang zh` |
界面语言判定顺序:配置文件 `language` → `SQUID_LANG` → `LC_ALL` → `LC_MESSAGES` → `LANG`
→ macOS 的 `AppleLocale`/`AppleLanguages`(`defaults read -g`)→ 英文。`C` / `POSIX` /
空值视为「没有信息」,继续往下走,所以在 `ssh`、`cron`、CI 里不会被误判成英文——
macOS 上仍然能从系统偏好里读到中文。`squid doctor` 会打印 language 和 colour 两行,
标明最终选了什么、是被哪一条决定的;TUI 里按 `?` 也有同样的诊断行。
自定义规则放到 `<config_dir>/rules/*.toml`,与内置规则合并(同 `id` 覆盖内置):
```toml
[[rule]]
id = "my-app-cache"
category = "app-caches"
title = "MyApp caches"
patterns = ["~/Library/Caches/myapp/*"] # `~` 展开;`*` 不跨越路径分隔符
mode = "path" # path = 删条目本身, contents = 只清空目录
os = ["macos"]
protect = ["keep-me"]
min_age_days = 3
select_by_default = true
note = "MyApp 会自动重建这些缓存。"
```
`pattern` 的最长字面量前缀成为该条目的 **锚点(anchor)**,删除时只允许在锚点之下操作——这就是「一个规则写错也不会把 `~/.cargo` 整个删掉」的原因。
## 项目结构
```
crates/
├── squid-core 模型、字节格式化、路径、安全策略、设置、删除账本、进度/取消
├── squid-platform Platform trait + macOS 实现(App 清单、残留匹配、卷)Linux/Windows 占位
├── squid-rules TOML 规则引擎:模式展开、锚点、保护列表、年龄与风险标记
├── squid-stats sysinfo 采样器、趋势、电池、uptime(iStat 面板的数据源)
├── squid-engine 四大引擎:clean / uninstall / purge / analyze + 唯一的删除通道 delete
├── squid-tui ratatui 界面(六个面板、任务线程、主题、中英双语文案)
└── squid-cli clap 命令行入口
```
依赖方向单向:`core → platform → rules → stats → engine → tui → cli`。
细节见 [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md),威胁模型与 Responsible disclosure 见 [docs/SECURITY.md](docs/SECURITY.md)。
## 开发
```bash
cargo check --workspace --all-targets
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --no-fail-fast
```
TUI 的键盘与渲染取舍用真实 pty 冒烟测试守着(需要 `pyte`):
```bash
python3 -m pip install --user pyte
cargo build --release
python3 scripts/tui_smoke.py # menu / menu-mono / uninstall
python3 scripts/tui_smoke.py uninstall # 只跑连续卸载(自己造临时 app,用完删除)
```
测试不会删除真实用户数据:删除相关用例写在 `~/Library/Caches/squid-delete-test-*` 的临时目录里,并通过 `SQUID_STATE_DIR` 把账本重定向到临时目录。
## 跨平台计划
| 平台 | 现状 |
| --- | --- |
| macOS | 完整实现(规则、App 残留、卷、Launch Services 卸载钩子) |
| Linux | `squid-platform/src/linux.rs` 已实现 `.desktop` / Flatpak / Snap 应用清单与 XDG 残留目录;缺 `rules/linux.toml` 与真机验证 |
| Windows | `squid-platform/src/windows.rs` 为占位实现,需注册表卸载表、`%LOCALAPPDATA%` 规则、回收站 API 与 UAC 提权 |
## 关于 Mole 与许可证
squid 的 Rust 实现是**净室(clean-room)实现**:仓库中仅作参考存放的 [Mole](https://github.com) 源码采用 **GPL v3**,本项目**没有复制、翻译或衍生其任何代码**,仅将其作为“清理哪些路径、有哪些坑”的行为参考。`/Mole` 已在 `.gitignore` 中排除。
squid 自身采用 **MIT OR Apache-2.0** 双许可证(见 `LICENSE`、`LICENSE-MIT`、`LICENSE-APACHE`)。
如果你把 squid 用于商业分发,请自行确认不与 GPL 代码静态链接。

View File

@ -0,0 +1,28 @@
[package]
name = "squid-cli"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "squid — clean, uninstall, purge and monitor your machine"
default-run = "squid"
[[bin]]
name = "squid"
path = "src/main.rs"
[dependencies]
squid-core.workspace = true
squid-engine.workspace = true
squid-platform.workspace = true
squid-rules.workspace = true
squid-stats.workspace = true
squid-tui.workspace = true
anyhow.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
crossterm.workspace = true
unicode-width.workspace = true

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,21 @@
[package]
name = "squid-core"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Core primitives for squid: models, safety policy, filesystem helpers, settings and history"
[dependencies]
anyhow.workspace = true
thiserror.workspace = true
serde.workspace = true
serde_json.workspace = true
toml.workspace = true
crossbeam-channel.workspace = true
dirs.workspace = true
chrono.workspace = true
libc.workspace = true
globset.workspace = true
walkdir.workspace = true
rayon.workspace = true

View File

@ -0,0 +1,193 @@
//! Byte counts with the two formatting styles the UI needs.
//!
//! macOS reports disk space in decimal units (1 KB = 1000 B) so that is the
//! default; [`Bytes::human_binary`] is there for memory readouts.
use serde::{Deserialize, Serialize};
use std::fmt;
pub const KB: u64 = 1_000;
pub const MB: u64 = 1_000 * KB;
pub const GB: u64 = 1_000 * MB;
pub const TB: u64 = 1_000 * GB;
/// `1234567` -> `1,234,567`. The `{:,}` specifier is not available here, so
/// grouping is done by hand.
pub fn format_thousands(value: u64) -> String {
let digits = value.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (idx, ch) in digits.chars().enumerate() {
if idx > 0 && (digits.len() - idx) % 3 == 0 {
out.push(',');
}
out.push(ch);
}
out
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Bytes(pub u64);
impl Bytes {
pub const ZERO: Bytes = Bytes(0);
pub const fn new(value: u64) -> Self {
Bytes(value)
}
pub const fn as_u64(self) -> u64 {
self.0
}
pub fn is_zero(self) -> bool {
self.0 == 0
}
/// (value, unit) pair, decimal.
pub fn parts(self) -> (f64, &'static str) {
const UNITS: [&str; 6] = ["B", "KB", "MB", "GB", "TB", "PB"];
let mut value = self.0 as f64;
let mut unit = 0;
while value >= 1000.0 && unit < UNITS.len() - 1 {
value /= 1000.0;
unit += 1;
}
(value, UNITS[unit])
}
/// Short form used in dense tables: `4.2 GB`, `318 MB`, `12 KB`.
pub fn human(self) -> String {
let (value, unit) = self.parts();
if unit == "B" {
format!("{} {}", value as u64, unit)
} else if value >= 100.0 {
format!("{:.0} {}", value, unit)
} else {
format!("{:.1} {}", value, unit)
}
}
/// Ledger form: always two decimals — `24.31 GB`, `1.37 GB`, `920 KB`.
///
/// A list row can get away with one decimal because the number is an
/// estimate that is about to change. A history entry is a *record*, and a
/// record that reads `1.4 GB` for a run that freed 1,365,856,256 bytes
/// looks rounded, not measured.
pub fn human_fixed(self) -> String {
let (value, unit) = self.parts();
if unit == "B" {
format!("{} {}", value as u64, unit)
} else {
format!("{value:.2} {unit}")
}
}
/// Precise form for detail panes: `4.28 GB (4,593,815,296 bytes)`.
pub fn human_long(self) -> String {
let (value, unit) = self.parts();
if unit == "B" {
format!("{} bytes", self.0)
} else {
format!("{:.2} {} ({} bytes)", value, unit, format_thousands(self.0))
}
}
/// Binary form for memory: `16.0 GiB`.
pub fn human_binary(self) -> String {
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut value = self.0 as f64;
let mut unit = 0;
while value >= 1024.0 && unit < UNITS.len() - 1 {
value /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{} {}", value as u64, UNITS[unit])
} else {
format!("{:.1} {}", value, UNITS[unit])
}
}
/// Whole percentage of `total`, saturating at 100.
pub fn percent_of(self, total: Bytes) -> u8 {
if total.is_zero() {
return 0;
}
((self.0 as u128 * 100) / total.0 as u128).min(100) as u8
}
}
impl std::ops::Add for Bytes {
type Output = Bytes;
fn add(self, rhs: Self) -> Self::Output {
Bytes(self.0.saturating_add(rhs.0))
}
}
impl<'a> std::iter::Sum<&'a Bytes> for Bytes {
fn sum<I: Iterator<Item = &'a Bytes>>(iter: I) -> Self {
iter.fold(Bytes::ZERO, |acc, item| acc + *item)
}
}
impl std::iter::Sum<Bytes> for Bytes {
fn sum<I: Iterator<Item = Bytes>>(iter: I) -> Self {
iter.fold(Bytes::ZERO, |acc, item| acc + item)
}
}
impl std::ops::AddAssign for Bytes {
fn add_assign(&mut self, rhs: Self) {
self.0 = self.0.saturating_add(rhs.0);
}
}
impl fmt::Display for Bytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.human())
}
}
impl fmt::Debug for Bytes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Bytes({})", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_decimal_units() {
assert_eq!(Bytes(0).human(), "0 B");
assert_eq!(Bytes(999).human(), "999 B");
assert_eq!(Bytes(1_500).human(), "1.5 KB");
assert_eq!(Bytes(4_593_815_296).human(), "4.6 GB");
assert_eq!(Bytes(120_000_000_000).human(), "120 GB");
}
#[test]
fn binary_units_for_memory() {
assert_eq!(Bytes(16 * 1024 * 1024 * 1024).human_binary(), "16.0 GiB");
}
#[test]
fn percentage() {
assert_eq!(Bytes(50 * GB).percent_of(Bytes(200 * GB)), 25);
assert_eq!(Bytes(1).percent_of(Bytes::ZERO), 0);
}
/// The ledger is a record, not an estimate: `1.4 GB` for a run that freed
/// 1,365,856,256 bytes reads as rounded, and the user read the whole number
/// as a display bug.
#[test]
fn the_ledger_form_keeps_two_decimals() {
assert_eq!(Bytes(1_365_856_256).human_fixed(), "1.37 GB");
assert_eq!(Bytes(24_311_898_112).human_fixed(), "24.31 GB");
assert_eq!(Bytes(753_655_808).human_fixed(), "753.66 MB");
assert_eq!(Bytes(920).human_fixed(), "920 B");
assert_eq!(Bytes(0).human_fixed(), "0 B");
}
}

View File

@ -0,0 +1,82 @@
//! Error types shared by every squid crate.
use std::io;
use std::path::PathBuf;
pub type Result<T> = std::result::Result<T, SquidError>;
#[derive(Debug, thiserror::Error)]
pub enum SquidError {
#[error("io error while accessing {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("path refused by safety policy: {path} ({reason})")]
Safety { path: PathBuf, reason: String },
#[error("nothing to do")]
NothingToDo,
#[error("operation cancelled")]
Cancelled,
#[error("unsupported on {platform}: {what}")]
Unsupported {
platform: &'static str,
what: &'static str,
},
#[error(
"permission denied for {path} — grant Full Disk Access to squid, or run again with sudo"
)]
Permission { path: PathBuf },
#[error("{0}")]
Other(String),
}
impl SquidError {
pub fn io(path: impl Into<PathBuf>, source: io::Error) -> Self {
match source.kind() {
io::ErrorKind::PermissionDenied => SquidError::Permission { path: path.into() },
_ => SquidError::Io {
path: path.into(),
source,
},
}
}
pub fn safety(path: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
SquidError::Safety {
path: path.into(),
reason: reason.into(),
}
}
/// Errors that are worth surfacing to the user, versus noisy "it moved
/// while we were looking at it" cases that we just count and ignore.
pub fn is_noteworthy(&self) -> bool {
!matches!(
self,
SquidError::Io {
source,
..
} if matches!(
source.kind(),
io::ErrorKind::NotFound
)
)
}
}
impl From<SquidError> for io::Error {
fn from(err: SquidError) -> io::Error {
match err {
SquidError::Io { source, .. } => source,
other => io::Error::other(other.to_string()),
}
}
}

View File

@ -0,0 +1,569 @@
//! Filesystem primitives: fast size measurement, safe removal, Trash support.
//!
//! Sizes are measured twice over: `logical` (the `st_size` sum the Finder
//! shows) and `allocated` (`st_blocks`, what the volume actually gave up).
//! squid reports `allocated` whenever it can because that is the number that
//! matches `df`.
use crate::bytes::Bytes;
use crate::error::{Result, SquidError};
use crate::model::{DeleteMode, ItemKind};
use crate::paths;
use crate::progress::CancelToken;
use crate::safety::SafetyPolicy;
use rayon::prelude::*;
use std::fs::{File, Metadata, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use walkdir::WalkDir;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SizeInfo {
pub logical: Bytes,
pub allocated: Bytes,
pub files: u64,
pub dirs: u64,
pub unreadable: u32,
}
impl SizeInfo {
/// Bytes really occupied; see [`crate::CleanupItem::on_disk`] for why the
/// two numbers must never be compared with `max()`.
pub fn on_disk(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.logical
} else {
self.allocated
}
}
}
pub fn merge(&mut self, other: &SizeInfo) {
self.logical += other.logical;
self.allocated += other.allocated;
self.files += other.files;
self.dirs += other.dirs;
self.unreadable += other.unreadable;
}
/// "12,431 files" style annotation for detail rows.
pub fn note(&self) -> String {
let files = self.files;
let grouped = format_thousands(files);
if self.dirs > 0 {
format!("{grouped} files, {} dirs", self.dirs)
} else {
format!("{grouped} files")
}
}
}
pub use crate::bytes::format_thousands;
fn allocated_bytes(meta: &Metadata) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
meta.blocks().saturating_mul(512)
}
#[cfg(not(unix))]
{
let _ = meta;
0
}
}
/// Measure one path. `Contents` skips the directory entry itself so the size
/// matches what removing its children would free.
pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
let mut info = SizeInfo::default();
let meta = match std::fs::symlink_metadata(path) {
Ok(meta) => meta,
Err(_) => return info,
};
if meta.file_type().is_symlink() {
info.files += 1;
info.logical += Bytes(meta.len());
return info;
}
match kind {
ItemKind::File => {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(&meta));
return info;
}
ItemKind::Path | ItemKind::Contents => {}
}
if !meta.is_dir() {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(&meta));
return info;
}
let min_depth = if kind == ItemKind::Contents { 1 } else { 0 };
let walker = WalkDir::new(path)
.follow_links(false)
.min_depth(min_depth)
.max_open(64)
.contents_first(false);
for entry in walker.into_iter() {
match entry {
Ok(entry) => {
let ft = entry.file_type();
if ft.is_symlink() {
continue;
}
if ft.is_dir() {
// `Contents` starts at depth 1, so it never yields the root
// entry; `Path` yields it and counts it — the folder itself
// is part of what gets removed.
info.dirs += 1;
continue;
}
match entry.metadata() {
Ok(meta) => {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(&meta));
}
Err(_) => info.unreadable += 1,
}
}
Err(_) => info.unreadable += 1,
}
}
info
}
/// Measure many paths in parallel. `progress` receives completed units.
/// `Path` for folders (and anything that should be removed recursively),
/// `File` for plain files and symlinks.
pub fn kind_of(path: &Path) -> crate::model::ItemKind {
match std::fs::symlink_metadata(path) {
Ok(meta) => {
if meta.is_dir() {
crate::model::ItemKind::Path
} else {
crate::model::ItemKind::File
}
}
Err(_) => crate::model::ItemKind::Path,
}
}
pub fn measure_all(
targets: &[(PathBuf, ItemKind)],
cancel: &CancelToken,
on_unit: impl Fn(usize, &SizeInfo) + Send + Sync,
) -> Vec<SizeInfo> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(measure_threads())
.build();
let pool = pool.unwrap_or_else(|_| {
// Inherited pool if a nested build fails; never fail a scan for this.
rayon::ThreadPoolBuilder::new().build().expect("rayon pool")
});
let done = AtomicU64::new(0);
let cancelled = AtomicBool::new(false);
let emit = &on_unit;
let results: Vec<SizeInfo> = pool.install(|| {
targets
.par_iter()
.map(|(path, kind)| {
if cancel.is_cancelled() {
cancelled.store(true, Ordering::Relaxed);
return SizeInfo::default();
}
let info = measure(path, *kind);
let idx = done.fetch_add(1, Ordering::Relaxed) as usize;
emit(idx, &info);
info
})
.collect()
});
results
}
fn measure_threads() -> usize {
let cores = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
cores.clamp(4, 16)
}
/// Validate + remove one item. Returns the bytes actually released.
pub fn remove_item(item: &crate::model::CleanupItem, mode: DeleteMode) -> Result<Bytes> {
let policy = SafetyPolicy::default();
remove_item_with(item, mode, &policy)
}
pub fn remove_item_with(
item: &crate::model::CleanupItem,
mode: DeleteMode,
policy: &SafetyPolicy,
) -> Result<Bytes> {
let anchors = if item.anchors.is_empty() {
default_anchors()
} else {
item.anchors.clone()
};
policy.check(&item.path, &anchors)?;
let before = measure(&item.path, item.kind);
match mode {
DeleteMode::Trash => {
trash_path(&item.path)?;
}
DeleteMode::Permanent => match item.kind {
ItemKind::File => {
std::fs::remove_file(&item.path).map_err(|e| SquidError::io(&item.path, e))?
}
ItemKind::Path => {
std::fs::remove_dir_all(&item.path).map_err(|e| SquidError::io(&item.path, e))?
}
ItemKind::Contents => remove_contents(&item.path)?,
},
}
let freed = SizeInfo {
logical: Bytes(
before
.logical
.0
.saturating_sub(after_size(&item.path, item.kind).logical.0),
),
allocated: Bytes(
before
.allocated
.0
.saturating_sub(after_size(&item.path, item.kind).allocated.0),
),
files: 0,
dirs: 0,
unreadable: 0,
};
Ok(freed.on_disk().max(Bytes::ZERO))
}
fn after_size(path: &Path, kind: ItemKind) -> SizeInfo {
if !path.exists() {
SizeInfo::default()
} else {
measure(path, kind)
}
}
fn remove_contents(dir: &Path) -> Result<()> {
let entries = std::fs::read_dir(dir).map_err(|e| SquidError::io(dir, e))?;
let mut first_error: Option<SquidError> = None;
for entry in entries.flatten() {
let path = entry.path();
let meta = std::fs::symlink_metadata(&path).ok();
let is_dir = meta.as_ref().map(|m| m.is_dir()).unwrap_or(false);
let is_link = meta
.as_ref()
.map(|m| m.file_type().is_symlink())
.unwrap_or(false);
let result = if is_dir && !is_link {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if let Err(err) = result {
if err.kind() != io::ErrorKind::NotFound && first_error.is_none() {
first_error = Some(SquidError::io(path, err));
}
}
}
match first_error {
Some(err) => Err(err),
None => Ok(()),
}
}
/// Roots a cleanup target may legitimately live under when no rule anchors are
/// attached (interactive deletion from the TUI, history restore, …).
pub fn default_anchors() -> Vec<PathBuf> {
let home = paths::home_dir();
let mut anchors = vec![
home.join("Library"),
home.join(".cache"),
home.join(".npm"),
home.join(".cargo"),
home.join(".Trash"),
PathBuf::from("/Library/Caches"),
PathBuf::from("/Library/Logs"),
PathBuf::from("/Library/Application Support/CrashReporter"),
PathBuf::from("/private/var/log"),
PathBuf::from("/private/var/folders"),
PathBuf::from("/Volumes"),
];
anchors.push(home.join("Documents"));
anchors.push(home.join("Downloads"));
anchors.push(home.join("Desktop"));
anchors.retain(|p| p.exists());
anchors
}
/// Where `path` would land in the Trash, honouring per-volume `.Trashes`.
pub fn trash_target_for(path: &Path) -> PathBuf {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "item".into());
let dir = trash_dir_for(path);
let mut candidate = dir.join(&name);
let mut counter = 2usize;
while candidate.exists() {
let (stem, ext) = split_name(&name);
let renamed = if ext.is_empty() {
format!("{stem} {counter}")
} else {
format!("{stem} {counter}.{ext}")
};
candidate = dir.join(renamed);
counter += 1;
}
candidate
}
fn split_name(name: &str) -> (String, String) {
// Only the last extension of bundles/apps is cosmetic; ".app" stays whole.
if let Some(rest) = name.strip_suffix(".app") {
return (rest.to_string(), "app".to_string());
}
match name.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() => {
(stem.to_string(), ext.to_string())
}
_ => (name.to_string(), String::new()),
}
}
fn trash_dir_for(path: &Path) -> PathBuf {
let uid = unsafe { libc::getuid() };
let volume_root = volume_root_for(path);
if !volume_root.as_os_str().is_empty() {
let per_volume = volume_root.join(".Trashes").join(uid.to_string());
if can_write(&per_volume) || ensure_dir(&per_volume) {
return per_volume;
}
}
let home_trash = paths::home_dir().join(".Trash");
if ensure_dir(&home_trash) {
return home_trash;
}
paths::home_dir().join(".Trash")
}
fn can_write(dir: &Path) -> bool {
let probe = dir.join(format!(".squid-probe-{}", std::process::id()));
match OpenOptions::new().create_new(true).write(true).open(&probe) {
Ok(_) => {
let _ = std::fs::remove_file(&probe);
true
}
Err(_) => false,
}
}
fn ensure_dir(dir: &Path) -> bool {
if dir.is_dir() {
return true;
}
std::fs::create_dir_all(dir).is_ok()
}
pub fn volume_root_for(path: &Path) -> PathBuf {
let abs = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir().unwrap_or_default().join(path)
};
let s = abs.to_string_lossy().into_owned();
if let Some(rest) = s.strip_prefix("/Volumes/") {
if let Some(idx) = rest.find('/') {
return PathBuf::from(format!("/Volumes/{}", &rest[..idx]));
}
return PathBuf::from(s);
}
if s.starts_with("/System/Volumes/Data") {
return PathBuf::from("/System/Volumes/Data");
}
PathBuf::from("/")
}
/// Move to Trash, copying first when the target lives on another volume.
pub fn trash_path(path: &Path) -> Result<PathBuf> {
let destination = trash_target_for(path);
match std::fs::rename(path, &destination) {
Ok(()) => Ok(destination),
Err(_) => {
copy_tree(path, &destination)?;
let kind = if path.is_dir() {
ItemKind::Path
} else {
ItemKind::File
};
match kind {
ItemKind::Path => {
let _ = std::fs::remove_dir_all(path);
}
ItemKind::File | ItemKind::Contents => {
std::fs::remove_file(path).map_err(|e| SquidError::io(path, e))?;
}
}
Ok(destination)
}
}
}
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
let meta = std::fs::symlink_metadata(from).map_err(|e| SquidError::io(from, e))?;
if meta.file_type().is_symlink() {
let target = std::fs::read_link(from).map_err(|e| SquidError::io(from, e))?;
std::os::unix::fs::symlink(&target, to).map_err(|e| SquidError::io(to, e))?;
return Ok(());
}
if meta.is_dir() {
std::fs::create_dir_all(to).map_err(|e| SquidError::io(to, e))?;
let entries = std::fs::read_dir(from).map_err(|e| SquidError::io(from, e))?;
for entry in entries.flatten() {
copy_tree(&entry.path(), &to.join(entry.file_name()))?;
}
return Ok(());
}
let mut reader = File::open(from).map_err(|e| SquidError::io(from, e))?;
let mut writer = File::create(to).map_err(|e| SquidError::io(to, e))?;
let mut buffer = vec![0u8; 1 << 20];
loop {
let read = reader
.read(&mut buffer)
.map_err(|e| SquidError::io(from, e))?;
if read == 0 {
break;
}
writer
.write_all(&buffer[..read])
.map_err(|e| SquidError::io(to, e))?;
}
Ok(())
}
/// Empty the user's Trash. Deliberately shallow: only top level entries.
pub fn empty_trash() -> Result<(usize, Bytes)> {
let trash = paths::home_dir().join(".Trash");
if !trash.is_dir() {
return Ok((0, Bytes::ZERO));
}
let mut removed = 0usize;
let mut freed = Bytes::ZERO;
let entries: Vec<PathBuf> = std::fs::read_dir(&trash)
.map_err(|e| SquidError::io(&trash, e))?
.flatten()
.map(|e| e.path())
.filter(|p| {
!p.file_name()
.map(|n| n.to_string_lossy().starts_with(".squid-probe-"))
.unwrap_or(false)
})
.collect();
for path in entries {
let size = measure(&path, ItemKind::Path);
let allocated = size.on_disk();
let result = if path.is_dir() && !path.is_symlink() {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if result.is_ok() {
removed += 1;
freed += allocated;
}
}
Ok((removed, freed))
}
/// Shared handle type used by long-running jobs.
pub type SharedCancel = Arc<CancelToken>;
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn measures_contents_and_path() {
let root = std::env::temp_dir().join(format!("squid-size-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(root.join("a/b")).unwrap();
fs::write(root.join("a/b/file.bin"), vec![7u8; 4096]).unwrap();
let whole = measure(&root, ItemKind::Path);
assert!(whole.logical.as_u64() >= 4096);
assert_eq!(whole.files, 1);
// `Contents` still counts the children; the directory entry has no size
// of its own, so totals match but the top dir is not counted.
let contents = measure(&root, ItemKind::Contents);
assert_eq!(contents.files, 1);
assert!(contents.dirs < whole.dirs);
let _ = fs::remove_dir_all(&root);
}
/// A thin-provisioned disk image is the reason `max(logical, allocated)`
/// is forbidden: Docker's `Docker.raw` reports a terabyte of logical
/// length while the SSD behind it holds 256 GB in total.
#[test]
fn a_sparse_file_counts_for_what_it_really_uses() {
let root = std::env::temp_dir().join(format!("squid-sparse-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(&root).unwrap();
let raw = root.join("Docker.raw");
let file = fs::File::create(&raw).unwrap();
file.set_len(8 << 30).unwrap();
drop(file);
let info = measure(&root, ItemKind::Path);
assert!(info.logical.as_u64() >= 8 << 30, "logical length is 8 GiB");
assert!(
info.on_disk().as_u64() * 100 < info.logical.as_u64(),
"the walk reported {}/{}; a sparse file must count as the blocks it wrote",
info.on_disk(),
info.logical
);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn thousand_separators() {
assert_eq!(format_thousands(0), "0");
assert_eq!(format_thousands(1234), "1,234");
assert_eq!(format_thousands(1_234_567), "1,234,567");
}
#[test]
fn trash_target_avoids_collisions() {
let dir = std::env::temp_dir().join(format!("squid-trash-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let victim = dir.join("victim");
fs::write(&victim, b"hi").unwrap();
let first = trash_target_for(&victim);
assert!(first.starts_with(trash_dir_for(&victim)));
let _ = fs::remove_dir_all(&dir);
}
}

View File

@ -0,0 +1,233 @@
//! Session history: what was removed, how much it freed, and how to undo it.
//!
//! Every destructive run writes one JSON file under the state directory. That
//! gives `squid history` a timeline and `squid undo` a Trash manifest.
use crate::bytes::Bytes;
use crate::error::{Result, SquidError};
use crate::model::{DeleteMode, ItemKind};
use crate::settings::Settings;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LedgerEntry {
pub path: PathBuf,
pub kind: ItemKind,
pub logical: u64,
pub allocated: u64,
pub trash_path: Option<PathBuf>,
pub category: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Session {
pub id: String,
pub started: String,
pub command: String,
pub mode: DeleteMode,
pub logical_freed: u64,
pub allocated_freed: u64,
pub removed: usize,
pub failed: usize,
pub entries: Vec<LedgerEntry>,
pub duration_ms: u64,
/// Whether the user already put this run back with `u`.
///
/// `restore` renamed the files out of ~/.Trash and used to leave the record
/// untouched, so the ledger went on reporting 24 GB as reclaimed after every
/// byte of it had come back. `serde(default)` keeps the history written
/// before this flag existed readable.
#[serde(default)]
pub restored: bool,
}
impl Session {
pub fn started_at(&self) -> Option<DateTime<Local>> {
DateTime::parse_from_rfc3339(&self.started)
.map(|d| d.with_timezone(&Local))
.ok()
}
pub fn freed(&self) -> Bytes {
let allocated = Bytes(self.allocated_freed);
if allocated.is_zero() {
Bytes(self.logical_freed)
} else {
allocated
}
}
/// What the run took off the volume *and left off*.
///
/// Every total the interface prints is this, not [`Session::freed`]: an
/// undone run gave the bytes back, so counting it as reclaimed is how the
/// header comes to promise 27 GB that `df` has never seen. The row itself
/// still shows `freed()` — the record of what happened is true even after
/// the undo.
pub fn kept(&self) -> Bytes {
if self.restored {
Bytes::ZERO
} else {
self.freed()
}
}
}
pub fn history_dir() -> PathBuf {
Settings::state_dir().join("history")
}
fn session_path(id: &str) -> PathBuf {
history_dir().join(format!("{id}.json"))
}
pub fn new_session_id() -> String {
let stamp = Local::now().format("%Y%m%d-%H%M%S");
let rand: u16 = {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
std::time::SystemTime::now().hash(&mut hasher);
(hasher.finish() & 0xffff) as u16
};
format!("{stamp}-{rand:04x}")
}
pub fn write_session(session: &Session) -> Result<PathBuf> {
let dir = history_dir();
std::fs::create_dir_all(&dir).map_err(|e| SquidError::io(&dir, e))?;
let path = session_path(&session.id);
let text =
serde_json::to_string_pretty(session).map_err(|e| SquidError::Other(e.to_string()))?;
std::fs::write(&path, text).map_err(|e| SquidError::io(&path, e))?;
prune(dir.clone(), Settings::load().0.history_keep);
Ok(path)
}
fn prune(dir: PathBuf, keep: usize) {
let Ok(entries) = std::fs::read_dir(&dir) else {
return;
};
let mut files: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|e| e == "json").unwrap_or(false))
.collect();
files.sort();
if files.len() > keep {
let stale: Vec<PathBuf> = files.drain(..files.len() - keep).collect();
for path in stale {
let _ = std::fs::remove_file(path);
}
}
}
pub fn load_sessions(limit: usize) -> Vec<Session> {
let dir = history_dir();
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut sessions: Vec<Session> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|e| e == "json").unwrap_or(false))
.filter_map(|p| std::fs::read_to_string(p).ok())
.filter_map(|text| serde_json::from_str::<Session>(&text).ok())
.collect();
sessions.sort_by(|a, b| b.id.cmp(&a.id));
sessions.truncate(limit);
sessions
}
pub fn load_session(id: &str) -> Option<Session> {
let text = std::fs::read_to_string(session_path(id)).ok()?;
serde_json::from_str(&text).ok()
}
/// Move everything that is still in the Trash back to its original location.
/// Returns `(restored, skipped)`.
pub fn restore(session: &Session) -> (usize, usize) {
let mut restored = 0;
let mut skipped = 0;
for entry in &session.entries {
let Some(trash_path) = entry.trash_path.as_ref() else {
skipped += 1;
continue;
};
if !trash_path.exists() {
skipped += 1;
continue;
}
if entry.path.exists() {
skipped += 1;
continue;
}
if let Some(parent) = entry.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if std::fs::rename(trash_path, &entry.path).is_ok() {
restored += 1;
} else {
skipped += 1;
}
}
// Mark the record once the bytes are really back. Without this the ledger
// cannot tell "cleaned 24 GB" from "cleaned 24 GB and put it back", and
// every total built from it is a lie by the amount restored.
if restored > 0 {
let mut record = session.clone();
record.restored = true;
let _ = write_session(&record);
}
(restored, skipped)
}
pub fn path_exists(path: &Path) -> bool {
path.symlink_metadata().is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
/// A ledger written by an older build has no `restored` key. Refusing to
/// read it would empty the history panel on upgrade — the opposite of an
/// honesty fix.
#[test]
fn yesterday_records_still_read() {
let json = r#"{
"id": "20260101-000000-aaaa",
"started": "2026-01-01T00:00:00+08:00",
"command": "squid clean",
"mode": "trash",
"logical_freed": 2048,
"allocated_freed": 1024,
"removed": 1,
"failed": 0,
"entries": [],
"duration_ms": 12
}"#;
let session: Session = serde_json::from_str(json).expect("old record parses");
assert!(!session.restored);
assert_eq!(session.kept(), Bytes(1024));
}
/// An undone run is history, but it is not space.
#[test]
fn an_undone_run_stops_counting_as_space() {
let mut session: Session = serde_json::from_str(
r#"{
"id": "x", "started": "2026-01-01T00:00:00+08:00", "command": "squid clean",
"mode": "trash", "logical_freed": 2048, "allocated_freed": 1024,
"removed": 1, "failed": 0, "entries": [], "duration_ms": 12
}"#,
)
.unwrap();
assert_eq!(session.kept(), Bytes(1024));
session.restored = true;
assert_eq!(session.kept(), Bytes::ZERO);
assert_eq!(session.freed(), Bytes(1024), "the record stays true");
}
}

View File

@ -0,0 +1,32 @@
//! # squid-core
//!
//! Shared vocabulary and safety machinery for squid. Everything that could
//! destroy user data lives behind [`safety::SafetyPolicy`] and
//! [`fs::remove_item`]; engines are expected to never call `std::fs::remove*`
//! directly.
pub mod bytes;
pub mod error;
pub mod fs;
pub mod ledger;
pub mod model;
pub mod paths;
pub mod progress;
pub mod safety;
pub mod settings;
pub use bytes::Bytes;
pub use error::{Result, SquidError};
pub use model::{
AppInfo, Category, CleanSummary, CleanupItem, DeleteMode, ItemKind, LockReason, ScanReport,
UninstallPlan, Volume,
};
pub use progress::{CancelToken, Event, Progress};
pub use safety::SafetyPolicy;
pub use settings::{Locale, LocaleSource, Settings};
/// Crate version, used by `squid --version` and the history format tag.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// One-liner shown at the top of every TUI screen.
pub const TAGLINE: &str = "clean · uninstall · purge · watch";

View File

@ -0,0 +1,517 @@
//! The vocabulary shared by the engines, the CLI and the TUI.
use crate::bytes::Bytes;
use crate::progress::CancelToken;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// High level bucket an item belongs to. Mirrors the cards CleanMyMac shows on
/// its cleanup screen so the TUI can render one section per bucket.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Category {
SystemJunk,
AppCaches,
BrowserCaches,
Logs,
Developer,
ProjectArtifacts,
Trash,
LanguagePacks,
Leftovers,
}
impl Category {
pub const ALL: [Category; 9] = [
Category::SystemJunk,
Category::AppCaches,
Category::BrowserCaches,
Category::Logs,
Category::Developer,
Category::ProjectArtifacts,
Category::Trash,
Category::LanguagePacks,
Category::Leftovers,
];
pub fn id(self) -> &'static str {
match self {
Category::SystemJunk => "system",
Category::AppCaches => "caches",
Category::BrowserCaches => "browsers",
Category::Logs => "logs",
Category::Developer => "developer",
Category::ProjectArtifacts => "projects",
Category::Trash => "trash",
Category::LanguagePacks => "languages",
Category::Leftovers => "leftovers",
}
}
pub fn title(self) -> &'static str {
match self {
Category::SystemJunk => "System Junk",
Category::AppCaches => "Application Caches",
Category::BrowserCaches => "Browser Caches",
Category::Logs => "Logs & Crash Reports",
Category::Developer => "Developer Files",
Category::ProjectArtifacts => "Project Artifacts",
Category::Trash => "Trash",
Category::LanguagePacks => "Unneeded Languages",
Category::Leftovers => "Uninstaller Leftovers",
}
}
/// Description shown under the header, CleanMyMac style.
pub fn blurb(self) -> &'static str {
match self {
Category::SystemJunk => "Temporary files, caches and scratch data left by macOS",
Category::AppCaches => "Regenerable caches that apps keep in ~/Library/Caches",
Category::BrowserCaches => "Web content, service workers and offline data",
Category::Logs => "Rotated logs, diagnostic reports and crash dumps",
Category::Developer => "DerivedData, simulators, containers, package caches",
Category::ProjectArtifacts => {
"Build outputs and dependency folders inside your projects"
}
Category::Trash => "Files waiting in the Trash",
Category::LanguagePacks => "Speech and localization data for languages you do not use",
Category::Leftovers => "Data belonging to apps that are no longer installed",
}
}
pub fn parse(value: &str) -> Option<Category> {
let value = value.trim();
if let Some(found) = Category::ALL.into_iter().find(|c| c.id() == value) {
return Some(found);
}
// Rules are hand-written, so accept the obvious aliases as well.
let key = value.to_ascii_lowercase().replace(['_', ' '], "-");
let key = key.trim_matches('-');
let alias = match key {
"app-cache" | "app-caches" | "cache" | "caches" | "application-caches" => {
Category::AppCaches
}
"browser-cache" | "browser-caches" | "browsers" | "web" => Category::BrowserCaches,
"system-junk" | "system" | "junk" | "temp" => Category::SystemJunk,
"log" | "logs" | "crash" | "crash-reports" => Category::Logs,
"dev" | "developer" | "developer-files" | "xcode" => Category::Developer,
"project" | "projects" | "project-artifacts" | "artifacts" => {
Category::ProjectArtifacts
}
"trash" => Category::Trash,
"language" | "languages" | "language-packs" | "localization" => Category::LanguagePacks,
"leftover" | "leftovers" | "uninstall-leftovers" => Category::Leftovers,
_ => return None,
};
Some(alias)
}
}
/// How a path must be emptied. Getting this right is the difference between
/// "freed 2 GB" and "broke the app".
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ItemKind {
/// Delete the path and everything under it.
Path,
/// Delete the children only, keep the directory itself (cache roots that
/// must keep existing so the owning app does not recreate them wrongly).
Contents,
/// A single file.
File,
}
/// Why an item cannot be removed in this run.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LockReason {
/// The owning app is running; its caches may be memory-mapped.
AppRunning,
/// Another install of the same bundle id survives, so shared data must stay.
SharedWithOtherInstall,
/// The user protected it through the whitelist.
Whitelisted,
/// Not owned by the current user (needs admin rights).
NotOwned,
/// Inside a protected system location.
Protected,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CleanupItem {
pub path: PathBuf,
pub kind: ItemKind,
pub size: Bytes,
pub category: Category,
/// Human readable label, e.g. "Slack cache".
pub label: String,
/// Rule that produced the item; used for whitelist / debug output.
pub rule_id: String,
pub selected: bool,
/// Bytes actually allocated on disk (sparse/compressed aware).
pub allocated: Bytes,
pub lock: Option<LockReason>,
/// Extra context shown in the detail row: "12,431 files".
pub note: Option<String>,
/// Roots the producing rule owns. Deletion re-validates against these so a
/// stale or hand-edited item can never escape its sandbox.
#[serde(default)]
pub anchors: Vec<PathBuf>,
}
impl CleanupItem {
pub fn new(
path: PathBuf,
kind: ItemKind,
category: Category,
label: impl Into<String>,
) -> Self {
let selected = lock_default(kind).is_none();
Self {
path,
kind,
size: Bytes::ZERO,
category,
label: label.into(),
rule_id: String::new(),
selected,
allocated: Bytes::ZERO,
lock: lock_default(kind),
note: None,
anchors: Vec::new(),
}
}
pub fn with_rule(mut self, rule_id: &str) -> Self {
self.rule_id = rule_id.to_string();
self
}
pub fn with_anchors(mut self, anchors: impl IntoIterator<Item = PathBuf>) -> Self {
self.anchors = anchors.into_iter().collect();
self
}
/// Attach a human-readable explanation ("off by default", "unreadable", …).
pub fn with_note(mut self, note: impl Into<String>) -> Self {
self.note = Some(note.into());
self
}
pub fn locked(mut self, reason: LockReason) -> Self {
self.lock = Some(reason);
self.selected = false;
self
}
pub fn is_removable(&self) -> bool {
self.lock.is_none()
}
pub fn display_path(&self) -> String {
crate::paths::pretty(&self.path)
}
/// Bytes the item really occupies on the disk.
///
/// `allocated` comes from `st_blocks`, `size` from `st_size`, and they
/// disagree by orders of magnitude for a sparse file: Docker's
/// `Docker.raw` claims a terabyte of address space on a machine with a
/// 256 GB SSD. Taking the larger of the two is what made squid promise
/// more free space than the disk can hold, so the block count wins.
///
/// On Unix the block count is the filesystem's own answer and is used
/// as-is — a fully sparse image really does occupy nothing, exactly as
/// `du -A` reports. Only a platform without block counts reads a zero as
/// "not measured" and falls back to the logical length.
pub fn on_disk(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.size
} else {
self.allocated
}
}
}
/// Size to show a human: honours `settings.show_allocated`.
pub fn shown(&self, show_allocated: bool) -> Bytes {
if show_allocated {
self.on_disk()
} else {
self.size
}
}
}
fn lock_default(kind: ItemKind) -> Option<LockReason> {
match kind {
ItemKind::Path | ItemKind::Contents | ItemKind::File => None,
}
}
/// Aggregate produced by every scan.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ScanReport {
pub category: Option<Category>,
pub items: Vec<CleanupItem>,
pub scanned_at_ms: u64,
/// Directories we were not allowed to read (permissions, TCC).
pub unreadable: u32,
/// Rules that matched nothing, kept for `--debug`.
pub skipped_rules: Vec<String>,
}
impl ScanReport {
/// What the checked items are worth: the same rule as
/// [`CleanupItem::on_disk`], never the logical size. A report is read as
/// "this much space comes back", and a 1 TiB sparse `Docker.raw` that
/// occupies 12 GB is exactly the case where the two numbers differ by an
/// order of magnitude — the interface that counted `item.size` announced
/// "1.1 TB" over a 256 GB disk.
pub fn total(&self) -> Bytes {
self.items
.iter()
.filter(|i| i.selected)
.map(|i| i.on_disk())
.sum()
}
/// Every item, checked or not. See [`Self::total`] for why this counts the
/// space occupied rather than the space claimed.
pub fn total_all(&self) -> Bytes {
self.items.iter().map(|i| i.on_disk()).sum()
}
pub fn selected_count(&self) -> usize {
self.items.iter().filter(|i| i.selected).count()
}
/// Biggest first, by the space actually occupied, so the order of the list
/// matches the number printed beside each row.
pub fn sorted(mut self) -> Self {
self.items.sort_by(|a, b| {
b.on_disk()
.cmp(&a.on_disk())
.then_with(|| a.label.to_lowercase().cmp(&b.label.to_lowercase()))
});
self
}
pub fn merge(&mut self, other: ScanReport) {
self.items.extend(other.items);
self.unreadable += other.unreadable;
self.skipped_rules.extend(other.skipped_rules);
}
}
/// What a caller wants to happen to the bytes it approved.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum DeleteMode {
/// Move to the macOS/Windows Trash so the user can undo.
Trash,
/// unlink(2) immediately. Default for caches: they are regenerable and
/// trashing 20 GB of caches just moves the problem.
#[default]
Permanent,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct CleanSummary {
pub freed: Bytes,
pub freed_allocated: Bytes,
pub removed: usize,
pub failed: usize,
pub errors: Vec<String>,
pub mode: Option<DeleteMode>,
pub session_id: Option<String>,
}
impl CleanSummary {
pub fn record_error(&mut self, msg: impl Into<String>) {
self.failed += 1;
self.errors.push(msg.into());
}
/// Space the run actually gave back, on-disk sense. Same rule as
/// [`CleanupItem::on_disk`]: never `max()` of the two, that is how a
/// 256 GB Mac ended up reporting 1.1 TB reclaimed.
pub fn freed_on_disk(&self) -> Bytes {
if self.freed_allocated.is_zero() {
self.freed
} else {
self.freed_allocated
}
}
}
/// One app discovered on the system (macOS `.app`, Linux `.desktop`, Windows
/// registry entries).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct AppInfo {
pub name: String,
pub bundle_id: Option<String>,
pub path: PathBuf,
pub version: Option<String>,
pub size: Bytes,
/// Where the app was found: /Applications, ~/Applications, Homebrew Cask…
pub source: String,
pub running: bool,
/// Set when the same bundle id is installed more than once; uninstall must
/// then keep shared preference files.
pub has_sibling_install: bool,
pub publisher: Option<String>,
pub installed_ms: Option<u64>,
}
impl AppInfo {
pub fn key(&self) -> String {
self.bundle_id
.clone()
.unwrap_or_else(|| self.path.to_string_lossy().into_owned())
}
}
/// A mounted volume, used by the disk views.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Volume {
pub name: String,
pub mount_point: PathBuf,
pub total: Bytes,
pub free: Bytes,
pub is_root: bool,
pub is_removable: bool,
pub filesystem: String,
}
impl Volume {
pub fn used(&self) -> Bytes {
Bytes(self.total.0.saturating_sub(self.free.0))
}
}
/// Leftover files found for an app bundle.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct UninstallPlan {
pub app: AppInfo,
pub items: Vec<CleanupItem>,
/// Notes the user should see before approving ("iCloud sync data present").
pub warnings: Vec<String>,
}
impl UninstallPlan {
pub fn total(&self) -> Bytes {
self.items.iter().map(|i| i.on_disk()).sum()
}
pub fn push(&mut self, item: CleanupItem) {
self.items.push(item);
}
}
/// Cancellation hook so the TUI can interrupt long scans.
pub trait Scannable {
fn scan(&mut self, cancel: &CancelToken) -> crate::error::Result<ScanReport>;
}
pub trait PathExt {
fn exists_dir(&self) -> bool;
}
impl<P: AsRef<Path>> PathExt for P {
fn exists_dir(&self) -> bool {
self.as_ref().is_dir()
}
}
#[cfg(test)]
mod tests {
use super::{Category, CleanSummary, CleanupItem, ItemKind, ScanReport};
use crate::bytes::Bytes;
#[test]
fn category_ids_round_trip() {
for cat in Category::ALL {
assert_eq!(Category::parse(cat.id()), Some(cat));
}
}
#[test]
fn category_aliases() {
assert_eq!(Category::parse("app-caches"), Some(Category::AppCaches));
assert_eq!(Category::parse("App_Caches"), Some(Category::AppCaches));
assert_eq!(Category::parse("browsers"), Some(Category::BrowserCaches));
assert_eq!(Category::parse("bogus"), None);
}
fn sparse_item() -> CleanupItem {
let mut item = CleanupItem::new(
"/var/lib/docker/Docker.raw".into(),
ItemKind::File,
Category::SystemJunk,
"Docker image",
);
item.size = Bytes(1_024_000_000_000); // 1.024 TB of thin provisioning
item.allocated = Bytes(12_000_000_000); // 12 GB actually written
item
}
/// The 1.1 TB bug: `max(logical, allocated)` turned a 12 GB Docker image
/// into more free space than a 256 GB disk can hold.
#[test]
fn an_item_is_worth_what_it_occupies_not_what_it_claims() {
let item = sparse_item();
assert_eq!(item.on_disk(), Bytes(12_000_000_000));
assert_eq!(item.shown(true), Bytes(12_000_000_000));
assert_eq!(item.shown(false), item.size);
}
#[test]
fn a_zero_allocation_is_read_the_way_the_platform_means_it() {
let mut item = sparse_item();
item.allocated = Bytes::ZERO;
if cfg!(unix) {
// `du -A` agrees: eight GiB of holes occupy nothing.
assert_eq!(item.on_disk(), Bytes::ZERO);
} else {
assert_eq!(item.on_disk(), item.size, "no st_blocks: fall back");
}
}
#[test]
fn a_summary_reports_the_space_that_came_back() {
let summary = CleanSummary {
freed: Bytes(1 << 40),
freed_allocated: Bytes(12_000_000_000),
..CleanSummary::default()
};
assert_eq!(summary.freed_on_disk(), Bytes(12_000_000_000));
let summary = CleanSummary {
freed: Bytes(4096),
..CleanSummary::default()
};
assert_eq!(summary.freed_on_disk(), Bytes(4096));
}
/// The same 1.1 TB bug one level up: a report that totals `item.size`
/// told the user a scan had found more junk than the disk is large, while
/// the badge beside it — which totals `on_disk()` — said 34 GB.
#[test]
fn a_report_totals_what_the_items_occupy() {
let report = ScanReport {
items: vec![sparse_item(), sparse_item()],
..ScanReport::default()
};
assert_eq!(report.total(), Bytes(24_000_000_000));
assert_eq!(report.total_all(), Bytes(24_000_000_000));
assert!(
report.total().as_u64() < 1 << 35,
"two 12 GB images are not terabytes"
);
}
}

View File

@ -0,0 +1,111 @@
//! Path expansion helpers shared by the rule engine and the UI.
use std::path::{Component, Path, PathBuf};
/// Expand a leading `~` / `$HOME` and a few well known macOS anchors.
///
/// Rules are authored with `~` because the crate ships a data file, not
/// hard-coded absolute paths, and the same rule file must work for the
/// current user *and* for `sudo` runs.
pub fn expand(input: &str) -> PathBuf {
let home = home_dir();
expand_with(input, &home)
}
pub fn expand_with(input: &str, home: &Path) -> PathBuf {
let input = input.trim();
if input == "~" || input == "$HOME" {
return home.to_path_buf();
}
if let Some(rest) = input.strip_prefix("~/") {
return home.join(rest);
}
if let Some(rest) = input.strip_prefix("$HOME/") {
return home.join(rest);
}
if let Some(rest) = input.strip_prefix("$HOME") {
return home.join(rest.trim_start_matches('/'));
}
PathBuf::from(input)
}
pub fn home_dir() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"))
}
/// Best-effort `/Volumes/...`-aware display shortening for the UI.
pub fn pretty(path: &Path) -> String {
let home = home_dir();
match path.strip_prefix(&home) {
Ok(rel) if rel.as_os_str().is_empty() => "~".to_string(),
Ok(rel) => format!("~/{}", rel.display()),
Err(_) => path.display().to_string(),
}
}
/// True when `child` is strictly inside `parent`.
pub fn is_within(parent: &Path, child: &Path) -> bool {
child != parent && child.starts_with(parent)
}
/// `~/Library/Caches/com.foo.bar` under anchor `~/Library/Caches` has depth 1.
pub fn depth_below(anchor: &Path, path: &Path) -> Option<usize> {
path.strip_prefix(anchor).ok().map(|rel| {
rel.components()
.filter(|c| matches!(c, Component::Normal(_)))
.count()
})
}
/// Component-wise comparison that is stable for display and de-duplication.
pub fn normalized(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other.as_os_str()),
}
}
out
}
/// Name that survives being shown in a one-line row: deepest meaningful label.
pub fn label_for(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expands_home() {
let home = Path::new("/Users/tester");
assert_eq!(
expand_with("~/Library/Caches", home),
PathBuf::from("/Users/tester/Library/Caches")
);
assert_eq!(
expand_with("$HOME/Library", home),
PathBuf::from("/Users/tester/Library")
);
assert_eq!(expand_with("~", home), home);
assert_eq!(expand_with("/tmp", home), PathBuf::from("/tmp"));
}
#[test]
fn within_and_depth() {
let anchor = Path::new("/a/b");
assert!(is_within(anchor, Path::new("/a/b/c")));
assert!(!is_within(anchor, Path::new("/a/b")));
assert_eq!(depth_below(anchor, Path::new("/a/b/c/d")), Some(2));
assert_eq!(depth_below(anchor, Path::new("/x/y")), None);
}
}

View File

@ -0,0 +1,194 @@
//! Cooperative cancellation plus a low-noise progress channel.
//!
//! Scans run on worker threads; the CLI prints a spinner while the TUI drains
//! the same channel into its state machine.
use crate::bytes::Bytes;
use crate::model::{Category, ScanReport};
use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub enum Event {
/// A named phase started so the UI can say what it is waiting for.
Phase {
phase: &'static str,
detail: String,
},
/// Progress against a known or unknown total.
Tick {
done: u64,
total: Option<u64>,
subject: Option<PathBuf>,
},
/// A finished bucket, streamed as soon as it is known.
Bucket {
category: Category,
total: Bytes,
count: usize,
},
Deleted {
path: PathBuf,
freed: Bytes,
},
Note(String),
Warning(String),
Done(ScanReport),
}
#[derive(Clone)]
pub struct Progress {
tx: Sender<Event>,
rx: Receiver<Event>,
started: Instant,
}
impl Default for Progress {
fn default() -> Self {
Self::new()
}
}
impl Progress {
pub fn new() -> Self {
let (tx, rx) = unbounded();
Self {
tx,
rx,
started: Instant::now(),
}
}
pub fn sender(&self) -> Sender<Event> {
self.tx.clone()
}
pub fn publish(&self, event: Event) {
// Losing a progress event must never fail the operation.
let _ = self.tx.send(event);
}
pub fn phase(&self, phase: &'static str, detail: impl Into<String>) {
self.publish(Event::Phase {
phase,
detail: detail.into(),
});
}
pub fn tick(&self, done: u64, total: Option<u64>, subject: Option<PathBuf>) {
self.publish(Event::Tick {
done,
total,
subject,
});
}
pub fn note(&self, msg: impl Into<String>) {
self.publish(Event::Note(msg.into()));
}
pub fn warning(&self, msg: impl Into<String>) {
self.publish(Event::Warning(msg.into()));
}
pub fn drain(&self) -> Vec<Event> {
let mut out = Vec::new();
loop {
match self.rx.try_recv() {
Ok(ev) => out.push(ev),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => break,
}
}
out
}
/// Block until an event arrives or the timeout expires.
pub fn recv(&self, timeout: Duration) -> Option<Event> {
self.rx.recv_timeout(timeout).ok()
}
pub fn elapsed(&self) -> Duration {
self.started.elapsed()
}
/// Receiver for a worker thread.
pub fn sink(&self) -> EventSink {
EventSink {
tx: self.tx.clone(),
}
}
}
/// Cheap handle passed into engine worker code.
#[derive(Clone)]
pub struct EventSink {
tx: Sender<Event>,
}
impl EventSink {
pub fn emit(&self, event: Event) {
let _ = self.tx.send(event);
}
pub fn note(&self, msg: impl Into<String>) {
let _ = self.tx.send(Event::Note(msg.into()));
}
pub fn warning(&self, msg: impl Into<String>) {
let _ = self.tx.send(Event::Warning(msg.into()));
}
}
/// Thread-safe cancel flag; cheap to clone into worker threads.
#[derive(Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);
impl CancelToken {
pub fn new() -> Self {
Self(Arc::new(AtomicBool::new(false)))
}
pub fn cancel(&self) {
self.0.store(true, Ordering::Relaxed);
}
pub fn is_cancelled(&self) -> bool {
self.0.load(Ordering::Relaxed)
}
pub fn check(&self) -> crate::error::Result<()> {
if self.is_cancelled() {
Err(crate::error::SquidError::Cancelled)
} else {
Ok(())
}
}
}
/// Small helper for a spinner in the CLI.
pub struct ElapsedTicker {
pub started: Instant,
}
impl Default for ElapsedTicker {
fn default() -> Self {
Self {
started: Instant::now(),
}
}
}
impl ElapsedTicker {
pub fn label(&self) -> String {
let secs = self.started.elapsed().as_secs_f32();
if secs < 60.0 {
format!("{secs:.1}s")
} else {
format!("{}m {:02}s", secs as u64 / 60, secs as u64 % 60)
}
}
}

View File

@ -0,0 +1,325 @@
//! The last line of defence before anything is unlinked.
//!
//! Rules decide *what* to delete; this module decides whether deleting it
//! could turn into a data-loss incident. Every recursive removal goes through
//! [`SafetyPolicy::check`], including removals requested by the TUI.
use crate::error::{Result, SquidError};
use crate::paths;
use std::path::{Path, PathBuf};
/// Locations that must never be removed, no matter what a rule says.
const HARD_DENY: &[&str] = &[
"/",
"/bin",
"/sbin",
"/usr",
"/etc",
"/System",
"/Library",
"/Applications",
"/Users",
"/home",
"/root",
"/opt",
"/private",
"/private/etc",
"/private/var",
"/private/var/db",
"/private/var/folders",
"/Volumes",
"/tmp",
"/private/tmp",
"/nix",
"/snap",
"/mnt",
"/media",
"/boot",
"/proc",
"/sys",
"/dev",
"/run",
"/Program Files",
"/Program Files (x86)",
"/Windows",
"/System/Volumes",
"/System/Volumes/Data",
"/private/var/root",
];
/// Prefixes that are dangerous to remove *recursively* but fine one level in.
const DENY_EXACT: &[&str] = &[
"~/Library",
"~/Library/Application Support",
"~/Library/Containers",
"~/Library/Group Containers",
"~/Library/Caches",
"~/Library/Preferences",
"~/Library/Saved Application State",
"~/Library/Mobile Documents",
"~/Library/Mail",
"~/Library/Messages",
"~/Library/Photos",
"~/Library/Keychains",
"~/Library/Application Support/MobileSync",
"~/Library/Application Support/CloudDocs",
"~/Library/Application Support/com.apple.icloud*",
"~/Documents",
"~/Desktop",
"~/Downloads",
"~/Pictures",
"~/Music",
"~/Movies",
"~/.ssh",
"~/.gnupg",
"~/.aws",
"~/.config/gcloud",
"~/.docker",
"~/.subversion",
"~/.zsh_history",
"~/.bash_history",
];
/// Folders outside the current user's home that a normal (non-root) user is
/// still allowed to remove *entries from*.
///
/// `SafetyPolicy::user_only` exists so that a run without administrator rights
/// cannot wander into system space, but read literally it also refuses the one
/// thing every uninstaller must do: move an app out of `/Applications`. An
/// admin-group user can do exactly that in Finder without a password, so the
/// shared application folder is carved out here. Only its *contents* are
/// reachable — `/Applications` itself is on the hard-deny list — and a bundle
/// owned by root is still locked much earlier by `writable_by_us`.
const OUTSIDE_HOME_OK: &[&str] = &["/Applications"];
#[derive(Clone, Debug)]
pub struct SafetyPolicy {
deny_exact: Vec<PathBuf>,
hard_deny: Vec<PathBuf>,
/// Minimum path components below an allowed anchor for a recursive delete.
pub min_depth: usize,
/// Volumes (mount points) that must never be walked.
pub forbidden_mounts: Vec<PathBuf>,
/// When false, refuse anything outside the current user's home.
pub allow_system_paths: bool,
/// Never descend into a symlink (default, and the right answer).
pub follow_symlinks: bool,
}
impl Default for SafetyPolicy {
fn default() -> Self {
Self {
deny_exact: DENY_EXACT.iter().map(|p| paths::expand(p)).collect(),
hard_deny: HARD_DENY.iter().map(PathBuf::from).collect(),
min_depth: 1,
forbidden_mounts: Vec::new(),
allow_system_paths: true,
follow_symlinks: false,
}
}
}
impl SafetyPolicy {
pub fn system() -> Self {
// Running as root: `/private/var/folders` and `/Library/Caches` become
// reachable, but the deny list keeps its teeth.
Self {
allow_system_paths: true,
..Self::default()
}
}
pub fn user_only() -> Self {
Self {
allow_system_paths: false,
..Self::default()
}
}
pub fn with_mounts(mut self, mounts: Vec<PathBuf>) -> Self {
self.forbidden_mounts = mounts;
self
}
fn is_exact_denied(&self, path: &Path) -> bool {
let norm = paths::normalized(path);
self.deny_exact.iter().any(|deny| {
let d = paths::normalized(deny);
// Trailing glob star entries deny the directory itself only.
let d = d
.to_string_lossy()
.trim_end_matches('*')
.trim_end_matches('/')
.to_string();
norm == Path::new(&d)
})
}
fn is_hard_denied(&self, path: &Path) -> bool {
let norm = paths::normalized(path);
if norm.as_os_str().is_empty() {
return true;
}
self.hard_deny
.iter()
.any(|deny| norm == *deny || norm == Path::new("/"))
}
/// Validate a removal target. `anchors` are the roots the rule claims to
/// own; the target must live strictly below one of them.
pub fn check(&self, path: &Path, anchors: &[PathBuf]) -> Result<()> {
if self.is_hard_denied(path) {
return Err(SquidError::safety(path, "protected system location"));
}
if self.is_exact_denied(path) {
return Err(SquidError::safety(path, "protected user data folder"));
}
for mount in &self.forbidden_mounts {
if paths::normalized(path) == paths::normalized(mount) {
return Err(SquidError::safety(path, "volume root"));
}
}
let norm = paths::normalized(path);
if let Some(anchor) = anchors.iter().find(|a| paths::is_within(a, &norm)) {
let depth = paths::depth_below(anchor, &norm).unwrap_or(0);
if depth < self.min_depth {
return Err(SquidError::safety(
path,
format!(
"only {depth} level(s) below protected anchor {}",
anchor.display()
),
));
}
} else {
return Err(SquidError::safety(
path,
"outside every declared cleanup anchor",
));
}
if !self.allow_system_paths
&& !paths::is_within(&paths::home_dir(), &norm)
&& !OUTSIDE_HOME_OK
.iter()
.any(|allowed| paths::is_within(Path::new(allowed), &norm))
{
return Err(SquidError::safety(
path,
"outside the current user's home (use sudo to clean system paths)",
));
}
if !self.follow_symlinks {
if std::fs::symlink_metadata(path)
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
{
return Err(SquidError::safety(path, "target is a symbolic link"));
}
if let Some(parent) = norm.parent() {
let canonical = std::fs::canonicalize(parent).ok();
if let Some(canonical) = canonical {
let expected = paths::normalized(parent);
if canonical != expected {
return Err(SquidError::safety(
path,
format!(
"parent resolves through a symlink to {}",
canonical.display()
),
));
}
}
}
}
Ok(())
}
/// Convenience wrapper that reports violations instead of returning them.
pub fn denies(&self, path: &Path, anchors: &[PathBuf]) -> Option<String> {
self.check(path, anchors).err().map(|e| match e {
SquidError::Safety { reason, .. } => reason,
other => other.to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn policy() -> SafetyPolicy {
SafetyPolicy {
allow_system_paths: true,
..SafetyPolicy::default()
}
}
#[test]
fn refuses_roots_and_protected_folders() {
let p = policy();
let anchors = vec![PathBuf::from("/")];
assert!(p.check(Path::new("/"), &anchors).is_err());
assert!(p
.check(Path::new("/System/Volumes/Data"), &anchors)
.is_err());
assert!(p.check(Path::new("/Users"), &anchors).is_err());
}
#[test]
fn allows_deep_cache_paths() {
let p = policy();
let anchors = vec![PathBuf::from("/Users/tester/Library/Caches")];
assert!(p
.check(
&PathBuf::from("/Users/tester/Library/Caches/com.example.app"),
&anchors
)
.is_ok());
}
#[test]
fn refuses_anchor_itself() {
let p = policy();
let anchors = vec![PathBuf::from("/Users/tester/Library/Caches")];
assert!(p
.check(&PathBuf::from("/Users/tester/Library/Caches"), &anchors)
.is_err());
}
#[test]
fn a_plain_user_can_still_uninstall_into_applications() {
// The bug: as a normal user the home-only rule refused every bundle,
// so `squid uninstall` approved the app and then deleted only its
// leftovers.
let policy = SafetyPolicy::user_only();
let anchors = vec![PathBuf::from("/Applications")];
assert!(policy
.check(Path::new("/Applications/Demo.app"), &anchors)
.is_ok());
assert!(
policy
.denies(Path::new("/Applications"), &anchors)
.is_some(),
"the folder itself stays untouchable"
);
assert!(policy
.denies(Path::new("/Library/LaunchDaemons/x.plist"), &anchors)
.is_some());
assert!(policy
.denies(Path::new("/System/Applications/Notes.app"), &anchors)
.is_some());
}
#[test]
fn refuses_paths_outside_anchors() {
let p = policy();
let anchors = vec![PathBuf::from("/Users/tester/Library/Caches")];
assert!(p
.check(&PathBuf::from("/Users/tester/Documents/x"), &anchors)
.is_err());
}
}

View File

@ -0,0 +1,480 @@
//! Persistent user settings: whitelist, purge roots, delete semantics.
use crate::bytes::Bytes;
use crate::error::{Result, SquidError};
use crate::model::DeleteMode;
use crate::paths;
use globset::{Glob, GlobMatcher};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// Trash or Permanent. CleanMyMac-like safety default is Trash for user
/// data and Permanent for regenerable caches; the CLI flag overrides both.
pub delete_mode: DeleteMode,
/// Glob patterns matched against absolute paths. Matched paths are never
/// selected, even if a rule finds them.
pub whitelist: Vec<String>,
/// Rules the user switched off entirely (`squid clean --disable caches-browser`).
pub disabled_rules: Vec<String>,
/// Where `squid purge` looks for projects. `~` is expanded.
pub purge_roots: Vec<String>,
/// Skip project artifacts that were touched within this many days: an
/// active build is not junk yet.
pub purge_min_age_days: u64,
/// Cap the file count per project-artifact probe so a huge monorepo does
/// not stall the scan.
pub purge_max_entries: u32,
/// Show allocated (on-disk) size instead of logical size.
pub show_allocated: bool,
/// `en` or `zh`. Falls back to $LANG when unset.
pub language: Option<String>,
/// Number of history sessions to keep.
pub history_keep: usize,
}
impl Default for Settings {
fn default() -> Self {
Self {
delete_mode: DeleteMode::Trash,
whitelist: Vec::new(),
disabled_rules: Vec::new(),
purge_roots: vec![
"~/code".into(),
"~/Code".into(),
"~/dev".into(),
"~/Dev".into(),
"~/develop".into(),
"~/projects".into(),
"~/Projects".into(),
"~/repos".into(),
"~/Repos".into(),
"~/src".into(),
"~/work".into(),
"~/Work".into(),
"~/Desktop".into(),
"~/Documents".into(),
"~/.codex/worktrees".into(),
],
purge_min_age_days: 7,
purge_max_entries: 200_000,
show_allocated: true,
language: None,
history_keep: 60,
}
}
}
impl Settings {
/// `SQUID_CONFIG_DIR` wins: handy for portable installs, CI, and tests that
/// must not touch the real profile.
pub fn config_dir() -> PathBuf {
if let Some(dir) = override_dir("SQUID_CONFIG_DIR") {
return dir;
}
dirs::config_dir()
.map(|d| d.join("squid"))
.unwrap_or_else(|| paths::home_dir().join(".config").join("squid"))
}
/// `SQUID_STATE_DIR` wins — see `config_dir`.
pub fn state_dir() -> PathBuf {
if let Some(dir) = override_dir("SQUID_STATE_DIR") {
return dir;
}
dirs::state_dir()
.or_else(dirs::config_dir)
.map(|d| d.join("squid"))
.unwrap_or_else(|| paths::home_dir().join(".local/state/squid"))
}
pub fn path() -> PathBuf {
Self::config_dir().join("config.toml")
}
/// Never fails: a broken config file is reported through `errors`.
pub fn load() -> (Settings, Vec<String>) {
let mut errors = Vec::new();
let path = Self::path();
match std::fs::read_to_string(&path) {
Ok(text) => match toml::from_str::<Settings>(&text) {
Ok(settings) => (settings, errors),
Err(err) => {
errors.push(format!(
"{}: {err} (falling back to defaults)",
path.display()
));
(Settings::default(), errors)
}
},
Err(_) => (Settings::default(), errors),
}
}
pub fn save(&self) -> Result<PathBuf> {
let path = Self::path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| SquidError::io(parent, e))?;
}
let text = toml::to_string_pretty(self).map_err(|e| SquidError::Other(e.to_string()))?;
std::fs::write(&path, text).map_err(|e| SquidError::io(&path, e))?;
Ok(path)
}
pub fn add_whitelist(&mut self, pattern: impl Into<String>) {
let pattern = pattern.into();
if !self.whitelist.contains(&pattern) {
self.whitelist.push(pattern);
}
}
pub fn remove_whitelist(&mut self, pattern: &str) -> bool {
let before = self.whitelist.len();
self.whitelist.retain(|p| p != pattern);
self.whitelist.len() != before
}
pub fn disable_rule(&mut self, rule_id: impl Into<String>) {
let id = rule_id.into();
if !self.disabled_rules.contains(&id) {
self.disabled_rules.push(id);
}
}
pub fn rule_enabled(&self, rule_id: &str) -> bool {
!self.disabled_rules.iter().any(|r| r == rule_id)
}
pub fn whitelist_matchers(&self) -> Vec<GlobMatcher> {
self.whitelist
.iter()
.filter_map(|raw| {
let expanded = paths::expand(raw).to_string_lossy().into_owned();
Glob::new(&expanded).ok().map(|g| g.compile_matcher())
})
.collect()
}
pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool {
if self.whitelist.is_empty() {
return false;
}
let text = path.to_string_lossy();
matchers.iter().any(|m| m.is_match(&*text))
}
pub fn purge_root_paths(&self) -> Vec<PathBuf> {
self.purge_roots
.iter()
.map(|p| paths::expand(p))
.filter(|p| p.is_dir())
.collect()
}
}
/// Locale for UI strings; only two languages exist so far.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Locale {
En,
Zh,
}
impl Locale {
/// Which language the interface should speak.
///
/// 1. `language` in `config.toml` — the user said it out loud.
/// 2. `SQUID_LANG` (also reachable as `squid --lang zh`).
/// 3. `LC_ALL`, `LC_MESSAGES`, `LANG`, in that order — the classic
/// Posix answer, and the reason iTerm2 shows Chinese: it exports
/// `LANG=zh_CN.UTF-8`.
/// 4. The system language, which Terminal.app never puts in the
/// environment. It only exports `LC_CTYPE`, so step 3 has nothing to
/// say there and squid used to fall through to English.
pub fn detect(settings: &Settings) -> Locale {
Self::explain(settings).0
}
/// The language *and* the switch that decided it. `squid doctor` and the
/// interface log print both, because "this terminal is Chinese and that
/// one is English" is a question about provenance, not about the answer.
pub fn explain(settings: &Settings) -> (Locale, LocaleSource) {
explain_with(settings, &|key| std::env::var(key).ok())
}
/// Two-letter tag for reports.
pub fn code(self) -> &'static str {
match self {
Locale::En => "en",
Locale::Zh => "zh",
}
}
}
/// Which knob picked the language.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LocaleSource {
/// `language` in `config.toml`.
Config,
/// One of `SQUID_LANG`, `LC_ALL`, `LC_MESSAGES`, `LANG`, named by the one
/// that answered.
Environment(&'static str),
/// The desktop language that never reaches the environment (macOS
/// keeps it in `defaults`, and Terminal.app exports none of the above).
System,
/// Nothing had a say; English is the fallback.
Fallback,
}
impl LocaleSource {
pub fn describe(self) -> String {
match self {
LocaleSource::Config => "config.toml `language`".to_string(),
LocaleSource::Environment(key) => format!("environment ${key}"),
LocaleSource::System => "system language setting".to_string(),
LocaleSource::Fallback => "built-in default".to_string(),
}
}
pub fn describe_zh(self) -> String {
match self {
LocaleSource::Config => "config.toml 的 language".to_string(),
LocaleSource::Environment(key) => format!("环境变量 {key}"),
LocaleSource::System => "系统语言设置".to_string(),
LocaleSource::Fallback => "内置默认值".to_string(),
}
}
}
/// The documented order, with `get` standing in for the environment, and the
/// name of whatever answered kept next to the answer.
fn explain_with(
settings: &Settings,
get: &dyn Fn(&str) -> Option<String>,
) -> (Locale, LocaleSource) {
if let Some(locale) = settings.language.as_deref().and_then(parse_locale) {
return (locale, LocaleSource::Config);
}
if let Some((key, locale)) = answered_by(get) {
return (locale, LocaleSource::Environment(key));
}
if let Some(locale) = system_locale() {
return (locale, LocaleSource::System);
}
(Locale::En, LocaleSource::Fallback)
}
/// Read one locale token (`zh_CN.UTF-8`, `C`, `POSIX`, `en-GB`).
/// `None` means the token carries no language information, so the search
/// moves on to the next variable instead of answering English by default.
fn parse_locale(raw: &str) -> Option<Locale> {
let token = raw.trim().to_lowercase().replace('-', "_");
if token.is_empty() || is_neutral(&token) {
return None;
}
if token.starts_with("zh") {
return Some(Locale::Zh);
}
Some(Locale::En)
}
/// The C locale and its aliases describe an encoding, not a language.
fn is_neutral(token: &str) -> bool {
token == "c" || token == "posix" || token.starts_with("c.") || token.starts_with("c_")
}
/// The variables that may carry a language, highest authority first.
const ENV_KEYS: [&str; 4] = ["SQUID_LANG", "LC_ALL", "LC_MESSAGES", "LANG"];
/// The first variable that carries a language, named.
fn answered_by(get: &dyn Fn(&str) -> Option<String>) -> Option<(&'static str, Locale)> {
ENV_KEYS.iter().find_map(|key| {
get(key)
.as_deref()
.and_then(parse_locale)
.map(|locale| (*key, locale))
})
}
/// The environment, read through `get` so the rule can be tested without
/// mutating the process.
#[cfg(test)]
fn from_variables(get: impl Fn(&str) -> Option<String>) -> Option<Locale> {
answered_by(&get).map(|(_, locale)| locale)
}
/// Ask the operating system what language the user picked. macOS keeps that
/// in `defaults`, not in the environment, and Terminal.app exports neither.
#[cfg(target_os = "macos")]
fn system_locale() -> Option<Locale> {
for key in ["AppleLocale", "AppleLanguages"] {
let Ok(output) = std::process::Command::new("defaults")
.args(["read", "-g", key])
.output()
else {
continue;
};
if !output.status.success() {
continue;
}
let text = String::from_utf8_lossy(&output.stdout);
// `AppleLanguages` is a property list — ("zh-Hans-CN",) — so the
// first quoted (or bare) token is the preferred language.
for piece in text.split(['"', ',', '(', ')']) {
let piece = piece.trim();
if piece.is_empty() {
continue;
}
if let Some(locale) = parse_locale(piece) {
return Some(locale);
}
}
}
None
}
#[cfg(not(target_os = "macos"))]
fn system_locale() -> Option<Locale> {
// Linux and Windows describe the language through the environment only,
// and step 3 of `detect` has already read every bit of it.
None
}
/// Convenience for reports that want the "freed" number in display units.
pub fn display_size(settings: &Settings, logical: Bytes, allocated: Bytes) -> Bytes {
if settings.show_allocated && !allocated.is_zero() {
allocated
} else {
logical
}
}
fn override_dir(var: &str) -> Option<PathBuf> {
std::env::var_os(var)
.map(PathBuf::from)
.filter(|path| !path.as_os_str().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
move |key: &str| map.get(key).cloned()
}
/// The useful half of the answer is *which* switch said it: the same
/// binary was Chinese in iTerm2 and English in Terminal.app, and every
/// explanation of that starts with where the language came from.
#[test]
fn the_language_names_the_switch_that_decided_it() {
let get = env(&[("LANG", "zh_CN.UTF-8")]);
assert_eq!(
explain_with(&Settings::default(), &get),
(Locale::Zh, LocaleSource::Environment("LANG")),
"iTerm2 exports LANG, Terminal.app does not"
);
let get = env(&[("SQUID_LANG", "en"), ("LANG", "zh_CN.UTF-8")]);
assert_eq!(
explain_with(&Settings::default(), &get),
(Locale::En, LocaleSource::Environment("SQUID_LANG"))
);
let settings = Settings {
language: Some("en".into()),
..Settings::default()
};
assert_eq!(
explain_with(&settings, &get),
(Locale::En, LocaleSource::Config),
"the config file outranks the environment"
);
assert_eq!(
LocaleSource::Environment("LANG").describe_zh(),
"环境变量 LANG"
);
}
#[test]
fn a_locale_variable_picks_the_language() {
assert_eq!(
from_variables(env(&[("LANG", "zh_CN.UTF-8")])),
Some(Locale::Zh)
);
assert_eq!(
from_variables(env(&[("LC_ALL", "zh-Hans-CN")])),
Some(Locale::Zh)
);
assert_eq!(
from_variables(env(&[("LANG", "en_GB.UTF-8")])),
Some(Locale::En)
);
}
/// Terminal.app exports none of these; it only sets `LC_CTYPE`. Treating
/// "anything that is not zh" as English is what made the same build
/// answer Chinese in iTerm2 and English in Terminal.
#[test]
fn the_c_locale_carries_no_language() {
for value in ["C", "c", "POSIX", "C.UTF-8", ""] {
assert_eq!(
from_variables(env(&[("LANG", value), ("LC_ALL", value)])),
None,
"{value} must not decide the language"
);
}
assert_eq!(from_variables(env(&[])), None, "no variables at all");
assert_eq!(
from_variables(env(&[("LC_CTYPE", "C.UTF-8")])),
None,
"LC_CTYPE is not a language"
);
}
/// Empty variables keep the search walking down the list instead of
/// answering on the first blank hit.
#[test]
fn an_empty_variable_does_not_shadow_a_later_one() {
assert_eq!(
from_variables(env(&[
("LC_ALL", ""),
("LC_MESSAGES", ""),
("LANG", "zh_CN.UTF-8")
])),
Some(Locale::Zh)
);
}
#[test]
fn squid_lang_beats_the_desktop_locale() {
assert_eq!(
from_variables(env(&[("SQUID_LANG", "en"), ("LANG", "zh_CN.UTF-8")])),
Some(Locale::En)
);
assert_eq!(
from_variables(env(&[("SQUID_LANG", "zh-CN"), ("LANG", "en_US.UTF-8")])),
Some(Locale::Zh)
);
}
#[test]
fn the_config_file_outvotes_everything_else() {
let language = |value: &str| Settings {
language: Some(value.into()),
..Settings::default()
};
assert_eq!(Locale::detect(&language("zh")), Locale::Zh);
assert_eq!(Locale::detect(&language("en")), Locale::En);
let settings = language("");
// Unset means "ask the machine", never "assume English".
assert_eq!(
Locale::detect(&settings),
Locale::detect(&Settings::default())
);
}
}

View File

@ -0,0 +1,23 @@
[package]
name = "squid-engine"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "squid engines: clean, uninstall, purge and disk analysis"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
squid-rules.workspace = true
squid-stats.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
rayon.workspace = true
walkdir.workspace = true
globset.workspace = true
crossbeam-channel.workspace = true
chrono.workspace = true
dirs.workspace = true
libc.workspace = true

View File

@ -0,0 +1,432 @@
//! `squid analyze` / the Storage panel — DaisyDisk-style drill-down.
//!
//! The tree is built lazily one level at a time: measure the children of the
//! folder the user is looking at, keep the biggest `top` of them, and fold the
//! remainder into a single "rest" figure. That keeps a first answer on a whole
//! home folder to a couple of seconds while still being exact about the top
//! entries, and it never has to hold a full filesystem tree in memory.
use serde::{Deserialize, Serialize};
use squid_core::fs;
use squid_core::progress::{CancelToken, Progress};
use squid_core::Bytes;
use std::path::{Path, PathBuf};
/// How many children one folder may be measured for before folding the rest.
const CHILD_CAP: usize = 512;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Node {
pub path: PathBuf,
pub logical: Bytes,
pub allocated: Bytes,
pub files: u64,
pub dirs: u64,
pub is_dir: bool,
pub readable: bool,
/// Biggest children first. Empty until [`explore`] ran with depth > 0.
pub children: Vec<Node>,
/// Children that were measured but too small to show.
pub folded: usize,
/// Their combined size.
pub folded_size: Bytes,
/// True when `children` is the complete list.
pub complete: bool,
}
impl Node {
/// On-disk bytes. A sparse directory (a Docker VM image, a Time Machine
/// local snapshot) has a logical size the disk cannot hold, so the
/// allocated figure wins whenever `measure` produced one.
pub fn size(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.logical
} else {
self.allocated
}
}
}
pub fn name(&self) -> String {
squid_core::paths::label_for(&self.path)
}
pub fn share_of(&self, parent: &Node) -> f64 {
let total = parent.size().as_u64();
if total == 0 {
0.0
} else {
self.size().as_u64() as f64 / total as f64
}
}
/// Children plus a synthetic entry for the folded remainder, so a bar chart
/// always adds up to the parent's size.
pub fn display_children(&self) -> Vec<Node> {
let mut out = self.children.clone();
if self.folded > 0 {
out.push(Node {
path: self.path.clone(),
logical: self.folded_size,
allocated: self.folded_size,
files: 0,
dirs: 0,
is_dir: true,
readable: true,
children: Vec::new(),
folded: 0,
folded_size: Bytes::ZERO,
complete: true,
});
}
out
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileEntry {
pub path: PathBuf,
pub logical: Bytes,
pub allocated: Bytes,
pub modified_ms: Option<u64>,
}
impl FileEntry {
pub fn size(&self) -> Bytes {
#[cfg(unix)]
{
self.allocated
}
#[cfg(not(unix))]
{
if self.allocated.is_zero() {
self.logical
} else {
self.allocated
}
}
}
}
/// Measure `root` and up to `depth` levels below it.
pub fn explore(
root: &Path,
depth: usize,
top: usize,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Node> {
let info = fs::measure(root, fs::kind_of(root));
let mut node = Node {
path: root.to_path_buf(),
logical: info.logical,
allocated: info.allocated,
files: info.files,
dirs: info.dirs,
is_dir: root.is_dir(),
readable: info.unreadable == 0,
children: Vec::new(),
folded: 0,
folded_size: Bytes::ZERO,
complete: false,
};
if depth > 0 && node.is_dir {
expand(&mut node, depth, top, cancel, progress)?;
} else {
node.complete = true;
}
Ok(node)
}
/// Fill one level of `node`, then recurse into the biggest children.
pub fn expand(
node: &mut Node,
depth: usize,
top: usize,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<()> {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
let entries = match std::fs::read_dir(&node.path) {
Ok(entries) => entries,
Err(_) => {
node.complete = true;
return Ok(());
}
};
let mut kids: Vec<(PathBuf, bool)> = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
let is_dir = entry
.file_type()
.map(|t| t.is_dir())
.unwrap_or_else(|_| path.is_dir());
let mount = is_mountpoint(&path);
kids.push((path, is_dir && !mount));
}
let total_children = kids.len();
if kids.len() > CHILD_CAP {
kids.sort_by(|a, b| b.0.cmp(&a.0));
kids.truncate(CHILD_CAP);
}
progress.phase(
"storage",
format!("measuring {}", squid_core::paths::pretty(&node.path)),
);
let targets: Vec<(PathBuf, squid_core::ItemKind)> = kids
.iter()
.map(|(path, is_dir)| {
(
path.clone(),
if *is_dir {
squid_core::ItemKind::Path
} else {
squid_core::ItemKind::File
},
)
})
.collect();
progress.tick(0, Some(targets.len() as u64), None);
let sizes = fs::measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
let mut children: Vec<Node> = targets
.iter()
.zip(sizes)
.map(|((path, _), info)| Node {
path: path.clone(),
logical: info.logical,
allocated: info.allocated,
files: info.files,
dirs: info.dirs,
is_dir: path.is_dir(),
readable: info.unreadable == 0,
children: Vec::new(),
folded: 0,
folded_size: Bytes::ZERO,
complete: depth <= 1,
})
.collect();
children.sort_by(|a, b| b.size().cmp(&a.size()).then_with(|| a.path.cmp(&b.path)));
let shown: usize = top.max(1).min(children.len());
let rest: Vec<Node> = children.drain(shown.min(children.len())..).collect();
node.folded = total_children.saturating_sub(shown);
node.folded_size = rest.iter().map(|child| child.size()).sum();
node.complete = node.folded == 0;
for mut child in children.into_iter().take(shown) {
if depth > 1 && child.is_dir {
expand(&mut child, depth - 1, top, cancel, progress)?;
}
node.children.push(child);
}
Ok(())
}
/// The biggest individual files under `root` — the "what on earth is 40 GB"
/// answer that folder trees hide.
pub fn largest_files(
root: &Path,
limit: usize,
min_bytes: Bytes,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<FileEntry>> {
let mut found: Vec<FileEntry> = Vec::new();
let mut stack: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
let mut visited = 0usize;
progress.phase("files", "collecting the largest files");
while let Some((dir, depth)) = stack.pop() {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
visited += 1;
if visited % 64 == 0 {
progress.tick(visited as u64, None, Some(dir.clone()));
}
if visited > 500_000 {
progress.warning("stopped after 500,000 folders — narrow the search");
break;
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
if depth < 12 && !is_mountpoint(&path) {
stack.push((path, depth + 1));
}
continue;
}
if !meta.is_file() {
continue;
}
let logical = Bytes(meta.len());
if logical < min_bytes {
continue;
}
let allocated = Bytes(allocated_of(&meta));
let modified_ms = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64);
found.push(FileEntry {
path,
logical,
allocated,
modified_ms,
});
if found.len() > limit.saturating_mul(8) {
found.sort_by_key(|entry| std::cmp::Reverse(entry.size()));
found.truncate(limit);
}
}
}
found.sort_by_key(|entry| std::cmp::Reverse(entry.size()));
found.truncate(limit);
Ok(found)
}
#[cfg(unix)]
fn allocated_of(meta: &std::fs::Metadata) -> u64 {
use std::os::unix::fs::MetadataExt;
meta.blocks() * 512
}
#[cfg(not(unix))]
fn allocated_of(meta: &std::fs::Metadata) -> u64 {
meta.len()
}
/// Skip other filesystems: analysing `/System/Volumes/Data` twice would lie.
fn is_mountpoint(path: &Path) -> bool {
#[cfg(target_os = "macos")]
{
const SKIP: &[&str] = &[
"/System/Volumes/Data",
"/System/Volumes/Update",
"/System/Volumes/Preboot",
"/System/Volumes/iSCPrecovery",
"/System/Volumes/XART",
"/Volumes",
"/dev",
"/proc",
"/sys",
"/run",
"/snap",
"/mnt",
"/media",
];
SKIP.iter().any(|skip| path.as_os_str() == *skip)
}
#[cfg(not(target_os = "macos"))]
{
const SKIP: &[&str] = &["/dev", "/proc", "/sys", "/run", "/snap", "/mnt", "/media"];
return SKIP.iter().any(|skip| path.as_os_str() == *skip);
}
}
/// Aggregate the tree into `(label, size)` pairs for a bar chart.
pub fn buckets(node: &Node, limit: usize) -> Vec<(String, Bytes)> {
let mut out: Vec<(String, Bytes)> = node
.children
.iter()
.take(limit)
.map(|child| (child.name(), child.size()))
.collect();
if node.folded > 0 {
out.push((format!("{} others", node.folded), node.folded_size));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// One folder per call. A session id is a second stamp plus sixteen bits of
/// clock hash, which two fixtures created in the same microsecond have been
/// known to share — and then one test measured the other's half-deleted
/// tree and wondered why the biggest folder came second.
fn fixture(who: &str) -> PathBuf {
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let root = std::env::temp_dir().join(format!(
"squid-analyze-{}-{}-{}-{}",
std::process::id(),
who,
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(root.join("big")).unwrap();
std::fs::write(root.join("big/blob.bin"), vec![9u8; 400_000]).unwrap();
std::fs::create_dir_all(root.join("small")).unwrap();
std::fs::write(root.join("small/tiny.txt"), b"hi").unwrap();
std::fs::write(root.join("loose.bin"), vec![3u8; 90_000]).unwrap();
root
}
#[test]
fn the_biggest_folder_comes_first() {
let root = fixture("the_biggest_folder_comes_first");
let progress = Progress::new();
let cancel = CancelToken::new();
let node = explore(&root, 2, 4, &cancel, &progress).expect("explore");
assert!(node.size().as_u64() > 400_000, "{:?}", node);
assert!(!node.children.is_empty());
assert_eq!(node.children[0].name(), "big");
assert!(node.children[0].allocated.as_u64() >= node.children[1].allocated.as_u64());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn largest_files_are_sorted_and_capped() {
let root = fixture("largest_files_are_sorted_and_capped");
let progress = Progress::new();
let cancel = CancelToken::new();
let files = largest_files(&root, 10, Bytes(1_024), &cancel, &progress).expect("files");
assert_eq!(files.len(), 2, "{files:?}");
assert!(files[0].path.ends_with("big/blob.bin"));
assert!(files[0].size().as_u64() > files[1].size().as_u64());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn the_folded_remainder_keeps_the_totals_honest() {
let root = fixture("the_folded_remainder_keeps_the_totals_honest");
let progress = Progress::new();
let cancel = CancelToken::new();
let node = explore(&root, 1, 1, &cancel, &progress).expect("explore");
assert_eq!(node.children.len(), 1);
assert!(node.folded > 0);
let shown: u64 = node
.children
.iter()
.map(|child| child.size().as_u64())
.sum();
let displayed = node.display_children();
assert_eq!(displayed.len(), 2);
assert!(shown + node.folded_size.as_u64() > 0);
assert!(!node.complete);
let _ = std::fs::remove_dir_all(&root);
}
}

View File

@ -0,0 +1,587 @@
//! `squid clean` — rule-driven cleanup.
//!
//! The scan walks every enabled rule, expands its globs, measures what it
//! found and returns one flat report grouped by [`Category`]. Two passes keep
//! the cost predictable: matching is cheap (readdir per rule), measuring runs
//! on a thread pool with a progress stream so the UI can fill in sizes as they
//! arrive.
use crate::{age_days, drop_nested_duplicates, size_note, writable_by_us, Engine};
use squid_core::fs::measure_all;
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason, ScanReport, SquidError};
use squid_rules::{PreparedRule, Rule};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct CleanOptions {
/// Restrict the scan to these categories; empty means "everything enabled".
pub categories: Vec<Category>,
/// Only offer rules the user can actually delete without sudo.
pub skip_admin_rules: bool,
/// Override the per-rule `min_age_days` (0 disables the filter).
pub min_age_days: Option<u64>,
/// Also look for leftovers whose owning app is gone.
pub orphans: bool,
/// Skip measurement (fast name-only scan).
pub fast: bool,
}
impl Default for CleanOptions {
fn default() -> Self {
CleanOptions {
categories: Vec::new(),
skip_admin_rules: true,
min_age_days: None,
orphans: false,
fast: false,
}
}
}
/// Scan every enabled rule.
pub fn scan(
engine: &Engine,
options: &CleanOptions,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<ScanReport> {
let prepared = prepared_rules(engine, options);
if prepared.is_empty() {
return Err(SquidError::NothingToDo);
}
progress.phase("match", "locating cleanup candidates");
progress.tick(0, Some(prepared.len() as u64), None);
let running = engine.platform().running_executables();
let mut report = ScanReport::default();
let mut done = 0u64;
let mut seen: HashMap<PathBuf, usize> = HashMap::new();
for prepared_rule in &prepared {
if cancel.is_cancelled() {
return Err(SquidError::Cancelled);
}
let rule = &prepared_rule.rule;
let matches = prepared_rule.matches();
done += 1;
progress.tick(done, Some(prepared.len() as u64), None);
if matches.is_empty() {
report.skipped_rules.push(rule.id.clone());
continue;
}
let running_conflict = rule_running_conflict(rule, &running);
for matched in matches {
for item in items_for_match(rule, &matched.path, &matched.anchor) {
if !passes_age(engine, rule, options, &item.path) {
continue;
}
if let Some(existing) = seen.get(&item.path) {
// Another rule already claimed this path; remember the
// anchor so both rules can authorise the same deletion.
if let Some(previous) = report.items.get_mut(*existing) {
{
let anchor = &matched.anchor;
if !previous.anchors.contains(anchor) {
previous.anchors.push(anchor.clone());
}
}
}
continue;
}
let mut item = item;
item.anchors = vec![matched.anchor.clone()];
if let Some(reason) = &running_conflict {
item = item
.locked(LockReason::AppRunning)
.with_note(reason.clone());
} else if options.skip_admin_rules
&& rule.needs_admin
&& !writable_by_us(&item.path)
{
item = item
.locked(LockReason::NotOwned)
.with_note("needs admin rights — run squid with sudo to include it");
} else if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
if !rule.select_by_default && item.lock.is_none() {
item.selected = false;
item.note = Some(
item.note
.take()
.map(|note| format!("{} · off by default", note))
.unwrap_or_else(|| "off by default".into()),
);
}
if rule.risky {
// Risky rules must stay labelled even when they already
// carry a different note.
item.note = Some(match item.note.take() {
Some(note) => format!("{note} · review before deleting"),
None => "review before deleting".into(),
});
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
}
if options.orphans {
match orphans(engine, cancel, progress) {
Ok(extra) => {
for item in extra {
if seen.contains_key(&item.path) {
continue;
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
Err(err) if err.is_noteworthy() => progress.warning(err.to_string()),
Err(_) => {}
}
}
if !options.fast {
measure(engine, &mut report, progress, cancel)?;
}
report.unreadable = report
.items
.iter()
.filter(|item| item.note.as_deref() == Some("unreadable"))
.count() as u32;
Ok(report)
}
fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec<PreparedRule> {
let mut rules: Vec<Rule> = engine
.rules()
.rules()
.iter()
.filter(|&rule| {
options.categories.is_empty() || options.categories.contains(&rule.category)
})
.cloned()
.collect();
if options.skip_admin_rules {
// Keep admin rules visible so the user learns sudo exists, but only
// when they asked for the full scan.
rules.retain(|rule| !rule.needs_admin || crate::is_root());
}
rules.into_iter().map(PreparedRule::new).collect()
}
fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
if rule.skip_if_running.is_empty() {
return None;
}
let hit = rule.skip_if_running.iter().find(|name| {
running
.iter()
.any(|proc| proc.eq_ignore_ascii_case(name) || proc.ends_with(&format!("/{name}")))
})?;
Some(format!("{hit} is running"))
}
/// Turn one glob match into the items a rule actually wants deleted.
fn items_for_match(rule: &Rule, path: &Path, anchor: &Path) -> Vec<CleanupItem> {
let label = label_for(rule, path);
let meta = match std::fs::symlink_metadata(path) {
Ok(meta) => meta,
Err(_) => return Vec::new(),
};
if meta.file_type().is_symlink() {
// Symlinks get unlinked, never followed.
return vec![new_item(path.to_path_buf(), ItemKind::File, rule, label)];
}
match rule.mode {
squid_rules::RuleMode::Path => {
let kind = if meta.is_dir() {
ItemKind::Path
} else {
ItemKind::File
};
vec![new_item(path.to_path_buf(), kind, rule, label)]
}
squid_rules::RuleMode::Contents => {
if !meta.is_dir() {
return vec![new_item(path.to_path_buf(), ItemKind::File, rule, label)];
}
// Never offer the *contents* of a directory we are not allowed to
// descend into one level below the anchor.
let _ = anchor;
vec![new_item(
path.to_path_buf(),
ItemKind::Contents,
rule,
label,
)]
}
squid_rules::RuleMode::Files => {
if !meta.is_dir() {
return vec![new_item(path.to_path_buf(), ItemKind::File, rule, label)];
}
list_files(path)
.into_iter()
.map(|file| new_item(file, ItemKind::File, rule, label.clone()))
.collect()
}
}
}
fn new_item(path: PathBuf, kind: ItemKind, rule: &Rule, label: String) -> CleanupItem {
CleanupItem::new(path, kind, rule.category, label).with_rule(&rule.id)
}
/// The label shown in the scan list. A leaf such as `0` (Docker keeps its VM
/// disk in `…/Data/vms/0`) says nothing on its own, so one parent component is
/// prepended whenever the leaf is uninformative.
fn label_for(rule: &Rule, path: &Path) -> String {
let leaf = squid_core::paths::label_for(path);
if leaf.is_empty() {
return rule.display_title().to_string();
}
if is_informative(&leaf) {
return leaf;
}
match path.parent().and_then(|parent| parent.file_name()) {
Some(parent) => format!("{}/{leaf}", parent.to_string_lossy()),
None => leaf,
}
}
fn is_informative(name: &str) -> bool {
name.chars().count() > 2 && !name.chars().all(|c| c.is_ascii_digit() || c == '.')
}
fn list_files(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let walker = walkdir::WalkDir::new(dir)
.follow_links(false)
.max_depth(4)
.into_iter()
.filter_entry(|entry| {
// Do not descend into nested app bundles while listing log files.
!entry.file_type().is_dir() || !entry.file_name().to_string_lossy().ends_with(".app")
});
for entry in walker.flatten() {
if entry.file_type().is_file() {
out.push(entry.into_path());
}
}
out.sort();
out
}
fn passes_age(_engine: &Engine, rule: &Rule, options: &CleanOptions, path: &Path) -> bool {
let days = match options.min_age_days {
Some(0) => return true,
Some(days) => days as f64,
None => match rule.min_age() {
Some(age) => age.as_secs_f64() / 86_400.0,
None => return true,
},
};
match age_days(path) {
Some(age) => age >= days,
None => true,
}
}
/// Measure items in parallel and stream sizes into the report.
fn measure(
_engine: &Engine,
report: &mut ScanReport,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<()> {
if report.items.is_empty() {
return Ok(());
}
progress.phase("measure", "measuring sizes");
let targets: Vec<(PathBuf, ItemKind)> = report
.items
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
progress.tick(0, Some(targets.len() as u64), None);
let results: Vec<squid_core::fs::SizeInfo> = measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
if results.len() != report.items.len() {
return Err(SquidError::Other(
"measurement returned an unexpected number of results".into(),
));
}
for (item, info) in report.items.iter_mut().zip(results) {
item.size = info.logical;
item.allocated = info.allocated;
if info.unreadable > 0 && item.note.is_none() {
item.note = Some(format!("{} entries unreadable", info.unreadable));
} else if info.files > 0 && item.note.is_none() {
item.note = Some(size_note(&info));
}
}
Ok(())
}
/// Publish per-category totals so the UI can fill its summary immediately.
pub fn publish_buckets(report: &ScanReport, progress: &Progress) {
let mut totals: HashMap<Category, (Bytes, usize)> = HashMap::new();
for item in &report.items {
let entry = totals.entry(item.category).or_insert((Bytes::ZERO, 0));
entry.0 += item.on_disk();
entry.1 += 1;
}
let mut ordered: Vec<(Category, (Bytes, usize))> = totals.into_iter().collect();
ordered.sort_by_key(|(category, _)| *category);
for (category, (total, count)) in ordered {
progress.publish(Event::Bucket {
category,
total,
count,
});
}
}
/// Leftovers whose application is no longer installed. Reported but *not*
/// selected: we can prove the app is gone, not that the data is worthless.
pub fn orphans(
engine: &Engine,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<CleanupItem>> {
progress.phase("orphans", "looking for leftovers of removed apps");
let apps = engine.platform().list_apps(cancel, false)?;
let installed: Vec<String> = apps
.iter()
.filter_map(|app| app.bundle_id.as_deref())
.map(|id| id.to_lowercase())
.collect();
let names: Vec<String> = apps
.iter()
.map(|app| squid_core::paths::label_for(&app.path).to_lowercase())
.collect();
let mut items = Vec::new();
for root in engine.platform().leftover_roots() {
if cancel.is_cancelled() {
return Err(SquidError::Cancelled);
}
let Ok(entries) = std::fs::read_dir(&root.dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
let lower = name.to_lowercase();
if !looks_like_bundle_id(&lower) {
continue;
}
if lower.starts_with("com.apple.") || lower.contains(".apple.") {
continue;
}
if installed.iter().any(|id| bundle_related(id, &lower)) {
continue;
}
if names.iter().any(|app| app == &lower) {
continue;
}
let mut item = CleanupItem::new(
path,
if entry.path().is_dir() {
ItemKind::Path
} else {
ItemKind::File
},
Category::Leftovers,
name.clone(),
)
.with_rule("orphan-leftovers")
.with_anchors(vec![root.dir.clone()])
.with_note("app no longer installed — verify before deleting");
item.selected = false;
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
} else if !writable_by_us(&item.path) {
item = item.locked(LockReason::NotOwned);
}
items.push(item);
}
}
Ok(items)
}
fn looks_like_bundle_id(lower: &str) -> bool {
let stem = lower
.trim_end_matches(".plist")
.trim_end_matches(".savedState")
.trim_end_matches(".ssh");
let parts: Vec<&str> = stem.split('.').collect();
parts.len() >= 3
&& parts.iter().all(|part| !part.is_empty())
&& parts[0].len() >= 2
&& stem
.chars()
.all(|c| c.is_ascii_alphanumeric() || ".-_+".contains(c))
}
fn bundle_related(installed: &str, leftover: &str) -> bool {
let leftover = leftover
.trim_end_matches(".plist")
.trim_end_matches(".savedState");
let prefix = |id: &str, depth: usize| -> String {
id.split('.')
.take(depth.min(id.split('.').count()))
.collect::<Vec<_>>()
.join(".")
};
for depth in [2, 3] {
if prefix(installed, depth) == prefix(leftover, depth) && prefix(leftover, depth).len() > 4
{
return true;
}
}
false
}
/// Sort a report for display: biggest first inside each category.
pub fn sort_for_display(mut report: ScanReport) -> ScanReport {
report.items.sort_by(|a, b| {
a.category
.cmp(&b.category)
.then_with(|| b.on_disk().cmp(&a.on_disk()))
.then_with(|| a.label.to_lowercase().cmp(&b.label.to_lowercase()))
});
report
}
pub fn cancel_if_needed(cancel: &CancelToken) -> squid_core::Result<()> {
if cancel.is_cancelled() {
Err(SquidError::Cancelled)
} else {
Ok(())
}
}
/// Expose the "same path, two rules" collapse to the tests.
#[doc(hidden)]
pub fn _dedupe_report(report: &mut ScanReport) {
drop_nested_duplicates(&mut report.items);
}
pub use squid_core::fs::SizeInfo;
#[cfg(test)]
mod tests {
use super::*;
use squid_platform::apps::is_running;
#[test]
fn bundle_id_detection_is_conservative() {
assert!(looks_like_bundle_id("com.slack.slack"));
assert!(looks_like_bundle_id("com.discord.html"));
assert!(!looks_like_bundle_id("logs"));
assert!(!looks_like_bundle_id("com"));
assert!(!looks_like_bundle_id("Homebrew"));
assert!(!looks_like_bundle_id("Google Chrome"));
}
#[test]
fn related_bundles_are_matched_by_prefix() {
assert!(bundle_related(
"com.company.Tool",
"com.company.Tool.Helper"
));
assert!(bundle_related("com.company.Tool", "com.company.tool"));
assert!(!bundle_related("com.company.Tool", "io.other.App"));
}
#[test]
fn labels_fall_back_to_the_rule_title() {
let rule = Rule {
id: "demo".into(),
category: Category::AppCaches,
title: "Demo caches".into(),
patterns: vec![],
mode: squid_rules::RuleMode::Path,
os: vec![],
protect: vec![],
min_age_days: 0,
select_by_default: true,
needs_admin: false,
skip_if_running: vec![],
risky: false,
note: None,
};
assert_eq!(label_for(&rule, Path::new("/tmp/demo-cache")), "demo-cache");
// Docker's VM disk lives in `…/Data/vms/0` — a bare "0" is not a label.
assert_eq!(
label_for(&rule, Path::new("/tmp/demo-cache/vms/0")),
"vms/0"
);
assert_eq!(
label_for(&rule, Path::new("/tmp/demo-cache/00")),
"demo-cache/00"
);
}
#[test]
fn scan_runs_on_the_real_machine() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let report = scan(&engine, &CleanOptions::default(), &progress, &cancel).expect("scan");
// Whatever the machine holds, a real scan must never crash and must
// never mark anything protected as selectable.
for item in &report.items {
if item.lock.is_some() {
assert!(!item.selected, "locked item selected: {:?}", item.path);
}
assert!(!item.path.as_os_str().is_empty());
}
publish_buckets(&report, &progress);
let events = progress.drain();
assert!(events
.iter()
.any(|event| matches!(event, Event::Phase { .. })));
}
#[test]
fn app_running_locks_browser_rules() {
let rule = Rule {
id: "chrome".into(),
category: Category::BrowserCaches,
title: "Chrome".into(),
patterns: vec![],
mode: squid_rules::RuleMode::Path,
os: vec![],
protect: vec![],
min_age_days: 0,
select_by_default: true,
needs_admin: false,
skip_if_running: vec!["Google Chrome".into()],
risky: false,
note: None,
};
assert!(rule_running_conflict(&rule, &["Google Chrome".to_string()]).is_some());
assert!(rule_running_conflict(
&rule,
&["/Applications/Foo.app/Contents/MacOS/Foo".to_string()]
)
.is_none());
assert!(!is_running("Xcode", None, &["Safari".to_string()]));
}
}

View File

@ -0,0 +1,326 @@
//! The only code path in squid that destroys data.
//!
//! Every engine (clean / uninstall / purge) and the TUI funnel deletions here.
//! The rules it enforces are deliberately paranoid:
//!
//! * locked items are refused, always — a lock means "the scanner said no";
//! * every item is re-validated against [`squid_core::SafetyPolicy`] and the
//! whitelist at delete time, because a scan can be minutes old and the disk
//! may have moved underneath us;
//! * nested children are dropped before their parent is removed so the freed
//! total is not double counted and children do not fail with ENOENT;
//! * Trash mode records the destination so `squid undo` can move things back.
use crate::{drop_nested_duplicates, Engine};
use squid_core::fs;
use squid_core::ledger::{self, LedgerEntry, Session};
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{Bytes, CleanSummary, CleanupItem, DeleteMode, LockReason};
use std::path::PathBuf;
use std::time::Instant;
/// A batch of approved items plus the provenance needed for the ledger.
#[derive(Clone, Debug)]
pub struct DeleteJob {
pub items: Vec<CleanupItem>,
pub mode: DeleteMode,
/// `squid clean`, `squid purge`, … — written to the history file.
pub command: String,
}
impl DeleteJob {
pub fn new(items: Vec<CleanupItem>, mode: DeleteMode, command: impl Into<String>) -> Self {
DeleteJob {
items,
mode,
command: command.into(),
}
}
/// Items the user selected *and* the scanner allowed.
pub fn removable(&self) -> Vec<CleanupItem> {
self.items
.iter()
.filter(|item| item.selected && item.lock.is_none())
.cloned()
.collect()
}
}
/// Result of a delete run, with the refusal reasons split out for the UI.
#[derive(Clone, Debug, Default)]
pub struct DeleteOutcome {
pub summary: CleanSummary,
/// Items that were never attempted, with the reason shown to the user.
pub skipped: Vec<(PathBuf, String)>,
}
/// Delete every removable item of the job.
pub fn execute(
engine: &Engine,
job: &DeleteJob,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<DeleteOutcome> {
let mut items = job.removable();
if items.is_empty() {
return Err(squid_core::SquidError::NothingToDo);
}
drop_nested_duplicates(&mut items);
progress.phase("delete", "removing approved items");
progress.tick(0, Some(items.len() as u64), None);
let session_id = ledger::new_session_id();
let started = Instant::now();
let mut summary = CleanSummary {
mode: Some(job.mode),
session_id: Some(session_id.clone()),
..CleanSummary::default()
};
let mut entries: Vec<LedgerEntry> = Vec::with_capacity(items.len());
let mut skipped: Vec<(PathBuf, String)> = Vec::new();
for (index, item) in items.iter().enumerate() {
if cancel.is_cancelled() {
progress.warning("cancelled — the items already removed stay removed");
break;
}
progress.tick(
index as u64 + 1,
Some(items.len() as u64),
Some(item.path.clone()),
);
if let Some(lock) = item.lock {
skipped.push((item.path.clone(), lock_reason(lock).to_string()));
summary.record_error(format!("{}: {}", item.display_path(), lock_reason(lock)));
continue;
}
if let Some(reason) = engine.block_reason(item) {
skipped.push((item.path.clone(), reason.clone()));
progress.warning(format!("{} — {}", item.display_path(), reason));
continue;
}
// Resolve the Trash destination *before* moving so the ledger can
// reverse the move later. `trash_target_for` only invents a name that
// does not exist yet, so this matches what `remove_item_with` does.
let trash_destination = match job.mode {
DeleteMode::Trash => Some(fs::trash_target_for(&item.path)),
DeleteMode::Permanent => None,
};
match fs::remove_item_with(item, job.mode, engine.safety()) {
Ok(freed) => {
summary.freed += item.size;
summary.freed_allocated += item.allocated;
summary.removed += 1;
progress.publish(Event::Deleted {
path: item.path.clone(),
freed: freed.max(Bytes::ZERO),
});
entries.push(LedgerEntry {
path: item.path.clone(),
kind: item.kind,
logical: item.size.0,
allocated: item.allocated.0,
trash_path: trash_destination.filter(|_| job.mode == DeleteMode::Trash),
category: Some(item.category.id().to_string()),
});
}
Err(err) => {
let message = format!("{}: {}", item.display_path(), err);
progress.warning(message.clone());
summary.record_error(message);
}
}
}
if !entries.is_empty() {
let session = Session {
id: session_id.clone(),
started: chrono::Local::now().to_rfc3339(),
command: job.command.clone(),
mode: job.mode,
logical_freed: summary.freed.0,
allocated_freed: summary.freed_allocated.0,
removed: summary.removed,
failed: summary.failed,
entries,
duration_ms: started.elapsed().as_millis() as u64,
restored: false,
};
match ledger::write_session(&session) {
Ok(path) => progress.note(format!(
"session {} recorded ({})",
session_id,
squid_core::paths::pretty(&path)
)),
Err(err) => progress.warning(format!("could not write history: {err}")),
}
}
Ok(DeleteOutcome { summary, skipped })
}
pub fn lock_reason(lock: LockReason) -> &'static str {
match lock {
LockReason::AppRunning => "app is running",
LockReason::SharedWithOtherInstall => "shared with another install of the same app",
LockReason::Whitelisted => "whitelisted",
LockReason::NotOwned => "owned by another user — needs admin rights",
LockReason::Protected => "protected by safety policy",
}
}
/// Convenience used by `squid undo`: restore a Trash session, newest first.
pub fn restore_session(id: &str) -> squid_core::Result<(usize, usize)> {
let session = ledger::load_session(id)
.ok_or_else(|| squid_core::SquidError::Other(format!("no history session named {id}")))?;
Ok(ledger::restore(&session))
}
#[cfg(test)]
mod tests {
use super::*;
use squid_core::{Category, ItemKind};
use std::path::PathBuf;
/// The safety policy only allows removing things inside the user's home,
/// so the deletable fixture has to live there too.
fn scratch_dir(tag: &str) -> PathBuf {
let dir = squid_core::paths::home_dir()
.join("Library/Caches")
.join(format!(
"squid-delete-test-{}-{tag}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// Ledger entries are user data: keep test sessions out of the real
/// `~/…/squid/history` so `squid history` only shows real cleanups.
fn isolate_state() {
use std::sync::Once;
static ONCE: Once = Once::new();
ONCE.call_once(|| {
let dir = std::env::temp_dir().join(format!("squid-state-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("scratch state dir");
std::env::set_var("SQUID_STATE_DIR", &dir);
});
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"squid-delete-test-{}-{tag}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn protected_paths_are_refused_and_reported() {
isolate_state();
let engine = Engine::new();
let item = CleanupItem::new(
PathBuf::from("/"),
ItemKind::Path,
Category::SystemJunk,
"root",
);
let job = DeleteJob::new(vec![item], DeleteMode::Permanent, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let outcome = execute(&engine, &job, &progress, &cancel).expect("run");
assert_eq!(outcome.summary.removed, 0);
assert_eq!(outcome.skipped.len(), 1);
assert!(
outcome.skipped[0].1.contains("protected") || outcome.skipped[0].1.contains("safety"),
"{:?}",
outcome.skipped
);
}
#[test]
fn a_temporary_file_can_be_deleted_and_ledgered() {
isolate_state();
let dir = scratch_dir("delete");
let file = dir.join("junk.bin");
std::fs::write(&file, vec![7u8; 4096]).unwrap();
let engine = Engine::new();
let mut item = CleanupItem::new(file.clone(), ItemKind::File, Category::SystemJunk, "junk");
item.size = Bytes(4096);
item.allocated = Bytes(4096);
let job = DeleteJob::new(vec![item], DeleteMode::Permanent, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let outcome = execute(&engine, &job, &progress, &cancel).expect("delete");
assert_eq!(outcome.summary.removed, 1, "{:?}", outcome.summary.errors);
assert!(!file.exists());
let session = ledger::load_sessions(10)
.into_iter()
.find(|session| session.id == outcome.summary.session_id.clone().unwrap_or_default());
assert!(session.is_some(), "session should be written to history");
let _ = std::fs::remove_dir_all(&dir);
}
/// Trash is the default mode, so the undo path has to work end to end:
/// delete → the file leaves its folder and lands in the Trash → `undo`
/// puts it back with its bytes intact.
#[test]
fn trashing_then_restoring_round_trips_the_file() {
isolate_state();
let dir = scratch_dir("undo");
let file = dir.join("precious.txt");
let payload = b"the squid gnawed here, and left this behind".to_vec();
std::fs::write(&file, &payload).unwrap();
let engine = Engine::new();
let mut item = CleanupItem::new(file.clone(), ItemKind::File, Category::Logs, "precious");
item.size = Bytes(payload.len() as u64);
item.allocated = Bytes(payload.len() as u64);
let job = DeleteJob::new(vec![item], DeleteMode::Trash, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let outcome = execute(&engine, &job, &progress, &cancel).expect("trash");
assert_eq!(outcome.summary.removed, 1, "{:?}", outcome.summary.errors);
assert!(!file.exists(), "the file should be in the Trash now");
let session_id = outcome.summary.session_id.clone().expect("session id");
let session = ledger::load_session(&session_id).expect("trashed session recorded");
let entry = session.entries.first().expect("one entry");
let trash_path = entry.trash_path.clone().expect("trash destination");
assert!(trash_path.exists(), "ledger points at the trashed file");
let (restored, skipped) = restore_session(&session_id).expect("restore");
assert_eq!((restored, skipped), (1, 0));
assert!(file.exists(), "undo should bring the file back");
assert_eq!(std::fs::read(&file).unwrap(), payload, "bytes intact");
assert!(!trash_path.exists(), "the Trash copy should be gone");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn locked_items_are_never_attempted() {
isolate_state();
let dir = temp_dir("locked");
let file = dir.join("keep.bin");
std::fs::write(&file, b"keep").unwrap();
let engine = Engine::new();
let item = CleanupItem::new(file.clone(), ItemKind::File, Category::Logs, "keep")
.locked(LockReason::Whitelisted);
let job = DeleteJob::new(vec![item], DeleteMode::Permanent, "squid test");
let progress = Progress::new();
let cancel = CancelToken::new();
let err = execute(&engine, &job, &progress, &cancel).unwrap_err();
assert!(matches!(err, squid_core::SquidError::NothingToDo));
assert!(file.exists(), "locked items must survive");
let _ = std::fs::remove_dir_all(&dir);
}
}

View File

@ -0,0 +1,291 @@
//! The four engines behind squid: clean, uninstall, purge and disk analysis.
//!
//! Every engine follows the same contract:
//!
//! 1. **Scan** produces a [`ScanReport`] of [`CleanupItem`]s. Nothing is
//! deleted during a scan — scanning is always safe and always idempotent.
//! 2. **Delete** takes the items the user approved, re-validates each of them
//! against [`SafetyPolicy`] (never trusting the scan), and writes a ledger
//! session so `squid undo` can put Trash-mode deletions back.
//!
//! Engines never call `std::fs::remove_*` directly; that keeps the audit trail
//! and the safety net impossible to bypass.
pub mod analyze;
pub mod clean;
pub mod delete;
pub mod purge;
pub mod uninstall;
use globset::GlobMatcher;
use squid_core::settings::Settings;
use squid_core::{CleanupItem, SafetyPolicy};
use squid_platform::Platform;
use squid_rules::RuleSet;
use std::path::Path;
/// Shared dependencies for every engine: the OS adapter, user settings, the
/// rule set and the safety policy that guards every deletion.
pub struct Engine {
platform: Box<dyn Platform>,
settings: Settings,
safety: SafetyPolicy,
rules: RuleSet,
whitelist: Vec<GlobMatcher>,
settings_errors: Vec<String>,
}
impl Default for Engine {
fn default() -> Self {
Self::new()
}
}
impl Engine {
pub fn new() -> Engine {
let (settings, settings_errors) = Settings::load();
Self::with_settings(settings, settings_errors)
}
pub fn with_settings(settings: Settings, settings_errors: Vec<String>) -> Engine {
let platform = squid_platform::current();
let rules = RuleSet::load(&settings);
let whitelist = settings.whitelist_matchers();
let mut safety = if is_root() {
SafetyPolicy::system()
} else {
SafetyPolicy::user_only()
};
if let Ok(mounts) = platform.volumes() {
safety = safety.with_mounts(
mounts
.into_iter()
.map(|volume| volume.mount_point)
.chain(platform.protected_prefixes())
.collect(),
);
}
Engine {
platform,
settings,
safety,
rules,
whitelist,
settings_errors,
}
}
pub fn platform(&self) -> &dyn Platform {
self.platform.as_ref()
}
pub fn settings(&self) -> &Settings {
&self.settings
}
pub fn settings_mut(&mut self) -> &mut Settings {
self.whitelist.clear();
&mut self.settings
}
/// Re-read whitelist/disabled rules after a settings change.
pub fn reload_settings(&mut self) {
let (settings, errors) = Settings::load();
self.settings = settings;
self.settings_errors = errors;
self.whitelist = self.settings.whitelist_matchers();
self.rules = RuleSet::load(&self.settings);
}
pub fn save_settings(&self) -> squid_core::Result<std::path::PathBuf> {
self.settings.save()
}
pub fn safety(&self) -> &SafetyPolicy {
&self.safety
}
pub fn rules(&self) -> &RuleSet {
&self.rules
}
pub fn settings_errors(&self) -> &[String] {
&self.settings_errors
}
pub fn is_whitelisted(&self, path: &Path) -> bool {
self.settings.is_whitelisted(path, &self.whitelist)
}
/// Why this item cannot be deleted, if it cannot. Rules pass the anchor they
/// declared; everything else falls back to the default anchors.
pub fn block_reason(&self, item: &CleanupItem) -> Option<String> {
let anchors = if item.anchors.is_empty() {
squid_core::fs::default_anchors()
} else {
item.anchors.clone()
};
if self.is_whitelisted(&item.path) {
return Some("whitelisted".into());
}
self.safety.denies(&item.path, &anchors)
}
}
/// True when the process may touch system-owned paths.
#[cfg(unix)]
pub fn is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
#[cfg(not(unix))]
pub fn is_root() -> bool {
false
}
/// A path is writable by us when we are root, or we own it and can write it.
#[cfg(unix)]
pub fn writable_by_us(path: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
if is_root() {
return true;
}
let uid = unsafe { libc::getuid() };
let writable = |meta: &std::fs::Metadata| meta.uid() == uid && meta.mode() & 0o200 != 0;
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => path
.parent()
.and_then(|parent| std::fs::metadata(parent).ok())
.map(|parent| writable(&parent))
.unwrap_or(false),
Ok(meta) => writable(&meta),
Err(_) => path
.parent()
.and_then(|parent| std::fs::metadata(parent).ok())
.map(|parent| writable(&parent))
.unwrap_or(false),
}
}
#[cfg(not(unix))]
pub fn writable_by_us(_path: &Path) -> bool {
true
}
/// Age of a path in days, using mtime. `None` when the stat failed.
pub fn age_days(path: &Path) -> Option<f64> {
let meta = std::fs::symlink_metadata(path).ok()?;
let modified = meta.modified().ok()?;
let age = modified.elapsed().ok()?;
Some(age.as_secs_f64() / 86_400.0)
}
pub fn mtime_ms(path: &Path) -> Option<u64> {
let meta = std::fs::symlink_metadata(path).ok()?;
let modified = meta.modified().ok()?;
modified
.duration_since(std::time::UNIX_EPOCH)
.ok()
.map(|d| d.as_millis() as u64)
}
/// Drop items whose ancestor is already in the list: deleting the parent would
/// make the child's removal fail (and inflate the freed-space total).
pub fn drop_nested_duplicates(items: &mut Vec<CleanupItem>) {
items.sort_by(|a, b| a.path.cmp(&b.path));
let mut kept: Vec<CleanupItem> = Vec::with_capacity(items.len());
for item in items.drain(..) {
let nested = kept.iter().any(|parent: &CleanupItem| {
parent.path != item.path && starts_with(&item.path, &parent.path)
});
if !nested {
kept.push(item);
}
}
*items = kept;
}
fn starts_with(path: &Path, base: &Path) -> bool {
let mut path = path.components().peekable();
let mut base = base.components().peekable();
loop {
match (base.next(), path.next()) {
(Some(a), Some(b)) => {
if a != b {
return false;
}
}
(None, _) => return true,
(Some(_), None) => return false,
}
}
}
/// "12,431 files · 382 folders" style annotation for the detail row.
pub fn size_note(info: &squid_core::fs::SizeInfo) -> String {
let files = squid_core::bytes::format_thousands(info.files);
if info.dirs > 0 {
format!(
"{files} files · {} folders",
squid_core::bytes::format_thousands(info.dirs)
)
} else {
format!("{files} files")
}
}
#[cfg(test)]
mod tests {
use super::*;
use squid_core::{Category, ItemKind};
use std::path::PathBuf;
#[test]
fn nested_duplicates_are_collapsed() {
let mut items = vec![
CleanupItem::new(
PathBuf::from("/Users/x/Library/Caches"),
ItemKind::Path,
Category::AppCaches,
"caches",
),
CleanupItem::new(
PathBuf::from("/Users/x/Library/Caches/foo/bar"),
ItemKind::Path,
Category::AppCaches,
"nested",
),
CleanupItem::new(
PathBuf::from("/Users/x/Library/Logs"),
ItemKind::Path,
Category::Logs,
"logs",
),
];
drop_nested_duplicates(&mut items);
assert_eq!(items.len(), 2);
assert!(items
.iter()
.any(|item| item.path.ends_with("Library/Caches")));
assert!(items.iter().any(|item| item.path.ends_with("Library/Logs")));
}
#[test]
fn engine_boots_with_rules_and_volumes() {
let engine = Engine::new();
assert!(!engine.rules().is_empty(), "expected builtin rules to load");
assert!(!engine.settings_errors().is_empty() || true);
assert!(!engine.platform().display_name().is_empty());
}
#[test]
fn safety_policy_blocks_the_obvious_roots() {
let engine = Engine::new();
let anchors = vec![PathBuf::from("/Users")];
assert!(engine.safety().denies(Path::new("/"), &anchors).is_some());
assert!(engine
.safety()
.denies(Path::new("/Users"), &anchors)
.is_some());
}
}

View File

@ -0,0 +1,757 @@
//! `squid purge` — deep clean for the things rules cannot know about:
//! build artefacts of projects that were checked out once and never opened
//! again (`node_modules`, `target/`, `Pods/`, `.venv/`, `.next/`, …).
//!
//! The walk is deliberately shallow and boring: it looks for a small allowlist
//! of directory names that are *always* regenerable, plus a handful of ambiguous
//! names (`dist`, `build`, `out`) that only count inside a recognised project.
//!
//! Two guards decide whether an artefact may be offered:
//!
//! 1. **git** — `git check-ignore` proves the folder is ignored (safe);
//! `git ls-files` proves it is *tracked* (refused, unless `--all`).
//! 2. **age** — artefacts touched in the last `purge_min_age_days` belong to an
//! active build and are skipped.
//!
//! APFS local snapshots are reported as informational items only: they can hold
//! tens of gigabytes, but only `tmutil` with admin rights can drop them.
use crate::{age_days, Engine};
use squid_core::progress::{CancelToken, Progress};
use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason, ScanReport};
use std::path::{Path, PathBuf};
use std::process::Command;
/// Directories that are regenerable wherever they appear.
const ALWAYS: &[&str] = &[
"node_modules",
"target",
"Pods",
".venv",
"__pycache__",
".next",
".nuxt",
".turbo",
".parcel-cache",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".dart_tool",
".terraform",
".serverless",
".expo",
"htmlcov",
"DerivedData",
".cxx",
".svelte-kit",
".output",
".astro",
];
/// Same, but only when the folder clearly belongs to a project: `~/build` or
/// `~/Downloads/dist` are somebody's data, not build output.
const AMBIGUOUS: &[&str] = &[
"dist", "build", "out", "coverage", ".build", "venv", ".gradle",
];
/// Files that prove the containing folder is a project root.
const PROJECT_MARKERS: &[&str] = &[
"package.json",
"Cargo.toml",
"go.mod",
"pyproject.toml",
"setup.py",
"requirements.txt",
"Podfile",
"build.gradle",
"build.gradle.kts",
"settings.gradle",
"pom.xml",
"Gemfile",
"pubspec.yaml",
"composer.json",
"Package.swift",
"mix.exs",
"deno.json",
"CMakeLists.txt",
"Makefile",
];
/// Never descended into: OS containers, personal media, tool caches that are
/// the job of `squid clean`, and anything that could be a mount point.
const DO_NOT_DESCEND: &[&str] = &[
".Trash",
".DocumentRevisions-V100",
".PKInstallSandboxManager",
".Spotlight-V100",
".fseventsd",
".vol",
"Library",
"Movies",
"Music",
"Pictures",
"Applications",
"System",
"Private",
"Volumes",
".git",
".svn",
".hg",
".cargo",
".rustup",
".npm",
".pnpm-store",
".yarn",
".bun",
".nvm",
".rbenv",
".pyenv",
".conda",
".anaconda",
".virtualenvs",
".local",
".config",
".cache",
".docker",
".colima",
".orbstack",
".lima",
".minikube",
".ollama",
".android",
".gradle",
".m2",
".sbt",
".ivy2",
".cocoapods",
".pub-cache",
".flutter",
".bundle",
".composer",
".dotnet",
".nuget",
".gvm",
".sdkman",
".oh-my-zsh",
".zsh_sessions",
".vscode",
".vscode-shared",
".cursor",
".jetbrains",
".macos",
".cups",
".ssh",
".gnupg",
".codex",
];
/// How deep the walk goes from each root.
const DEFAULT_DEPTH: usize = 6;
/// Hard stop so a pathological tree cannot spin forever.
const MAX_DIRS: usize = 300_000;
#[derive(Clone, Debug, Default)]
pub struct PurgeOptions {
/// Where to look. Empty means "the roots from settings plus `$HOME`".
pub roots: Vec<PathBuf>,
/// `None` = use `settings.purge_min_age_days`, `Some(0)` = disable.
pub min_age_days: Option<u64>,
/// Ignore the age rule *and* the "tracked by git" refusal.
pub force: bool,
/// Maximum depth below each root.
pub max_depth: Option<usize>,
}
/// One folder the walk wants to reclaim.
#[derive(Clone, Debug)]
struct Candidate {
path: PathBuf,
/// Nearest directory that looks like a project root (or the artefact itself).
project: PathBuf,
name: String,
always: bool,
}
/// Scan for reclaimable project artefacts.
pub fn scan(
engine: &Engine,
options: &PurgeOptions,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<ScanReport> {
let roots = resolve_roots(engine, options);
if roots.is_empty() {
progress.warning(
"no purge roots exist yet — add some with `squid whitelist`-style config or pass paths",
);
return Err(squid_core::SquidError::NothingToDo);
}
let depth = options.max_depth.unwrap_or(DEFAULT_DEPTH);
progress.phase(
"purge",
format!("searching {} location(s) for build artefacts", roots.len()),
);
progress.tick(0, None, None);
let mut candidates: Vec<Candidate> = Vec::new();
let mut visited = 0usize;
for root in &roots {
let top_level = roots.len() > 1 && root.components().count() <= 3;
let cap = if top_level { depth.min(4) } else { depth };
walk(root, cap, &mut candidates, &mut visited, progress, cancel)?;
}
candidates.sort_by(|a, b| a.path.cmp(&b.path));
candidates.dedup_by(|a, b| a.path == b.path);
progress.note(format!("{} artefact folders found", candidates.len()));
let min_age = options
.min_age_days
.unwrap_or(engine.settings().purge_min_age_days);
progress.phase("verify", "checking git status and ages");
let mut report = ScanReport::default();
let mut git_cache: Vec<(PathBuf, GitState)> = Vec::new();
for (index, candidate) in candidates.iter().enumerate() {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
progress.tick(
index as u64 + 1,
Some(candidates.len() as u64),
Some(candidate.path.clone()),
);
let mut item = item_for(candidate);
if !options.force {
let project_root = match project_with_git(&candidate.path) {
Some(dir) => dir,
None => candidate.project.clone(),
};
let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) {
Some((_, state)) => *state,
None => {
let state = git_state(&project_root, &candidate.path);
git_cache.push((project_root.clone(), state));
state
}
};
match state {
GitState::Tracked => {
item = item
.locked(LockReason::Protected)
.with_note("tracked by git — pass --all to delete anyway");
}
GitState::Ignored => item.note = Some("git-ignored build output".into()),
GitState::Untracked => item.note = Some("untracked by git".into()),
GitState::Unknown => {
let age = age_days(&candidate.path);
match age {
Some(age) if age >= min_age as f64 => {
item.note = Some(format!("no git repo · {:.0} days old", age));
}
Some(age) => {
item = item.locked(LockReason::Protected).with_note(format!(
"no git repo and only {:.0} days old — pass --all",
age
));
}
None => item.note = Some("age unknown".into()),
}
}
}
}
if item.lock.is_none() {
let age = age_days(&candidate.path).unwrap_or(0.0);
if !options.force && min_age > 0 && age < min_age as f64 {
item = item
.locked(LockReason::Protected)
.with_note(format!("modified {:.0} days ago — an active build", age));
}
}
if !candidate.always && item.lock.is_none() {
// `dist`/`build`/`out` are guesses, not proofs: show them, but let
// the user opt in.
item.selected = false;
item.note = Some(format!(
"{} · name only, review before deleting",
item.note.unwrap_or_default()
));
}
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
if !crate::writable_by_us(&candidate.path) && !crate::is_root() {
item = item
.locked(LockReason::NotOwned)
.with_note("owned by another user");
}
report.items.push(item);
}
measure(&mut report, progress, cancel);
report.items.sort_by(|a, b| {
b.on_disk()
.cmp(&a.on_disk())
.then_with(|| a.path.cmp(&b.path))
});
report.unreadable = report
.items
.iter()
.filter(|item| {
item.note
.as_deref()
.map(|note| note.contains("unreadable"))
.unwrap_or(false)
})
.count() as u32;
Ok(report)
}
fn item_for(candidate: &Candidate) -> CleanupItem {
let category = if candidate.name.eq_ignore_ascii_case("DerivedData") {
Category::Developer
} else {
Category::ProjectArtifacts
};
let project = squid_core::paths::pretty(&candidate.project);
// The anchor is what authorises a deletion, and the policy never deletes an
// anchor itself — anchoring an artefact at its own path would lock every
// single candidate. Anchor it at the project that contains it instead.
let mut anchor = candidate.project.clone();
if anchor == candidate.path {
if let Some(parent) = candidate.path.parent() {
anchor = parent.to_path_buf();
}
}
CleanupItem::new(
candidate.path.clone(),
ItemKind::Path,
category,
format!("{}/", candidate.name),
)
.with_rule("purge-artifacts")
.with_anchors(vec![anchor])
.with_note(project)
}
/// Default roots: everything the user configured, plus the home folder itself
/// (shallow) so a project in an unexpected place is still found.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<PathBuf> {
if !options.roots.is_empty() {
return options
.roots
.iter()
.map(|root| squid_core::paths::expand(&root.to_string_lossy()))
.filter(|path| path.is_dir())
.collect();
}
let mut roots = engine.settings().purge_root_paths();
let home = squid_core::paths::home_dir();
if !roots.iter().any(|root| root == &home) {
roots.push(home);
}
roots.retain(|root| root.is_dir());
roots
}
fn walk(
root: &Path,
max_depth: usize,
out: &mut Vec<Candidate>,
visited: &mut usize,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<()> {
let mut stack: Vec<(PathBuf, usize, bool)> = vec![(root.to_path_buf(), 0, false)];
while let Some((dir, depth, in_project)) = stack.pop() {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
if *visited >= MAX_DIRS {
progress.warning(format!(
"stopped after {} folders — narrow the search with explicit paths",
MAX_DIRS
));
return Ok(());
}
*visited += 1;
if depth % 32 == 0 {
progress.tick(*visited as u64, None, Some(dir.clone()));
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
let mut dirs: Vec<String> = Vec::new();
let mut is_project = false;
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let is_dir = entry
.file_type()
.map(|t| t.is_dir())
.unwrap_or_else(|_| entry.path().is_dir());
if is_dir {
dirs.push(name);
} else if PROJECT_MARKERS.iter().any(|marker| marker == &name) {
is_project = true;
}
}
for name in dirs {
if ALWAYS.iter().any(|known| known.owns(&name)) {
out.push(Candidate {
path: dir.join(&name),
project: if is_project || in_project {
dir.clone()
} else {
nearest_project(&dir).unwrap_or_else(|| dir.clone())
},
name,
always: true,
});
continue;
}
if AMBIGUOUS.iter().any(|known| known.owns(&name)) && (is_project || in_project) {
out.push(Candidate {
path: dir.join(&name),
project: dir.clone(),
name,
always: false,
});
continue;
}
if DO_NOT_DESCEND.iter().any(|skip| skip.owns(&name)) {
continue;
}
if depth < max_depth {
stack.push((dir.join(&name), depth + 1, is_project || in_project));
}
}
}
Ok(())
}
/// Compare a directory entry name against a known name, case-insensitively for
/// ASCII (macOS file systems are case-insensitive, git is not).
trait Owns {
fn owns(&self, name: &str) -> bool;
}
impl Owns for &str {
fn owns(&self, name: &str) -> bool {
self.eq_ignore_ascii_case(name)
}
}
/// Walk up looking for a directory that declares itself a project.
fn nearest_project(dir: &Path) -> Option<PathBuf> {
let mut cursor = dir.to_path_buf();
for _ in 0..4 {
if !cursor.pop() {
return None;
}
let Ok(entries) = std::fs::read_dir(&cursor) else {
continue;
};
let hit = entries.flatten().any(|entry| {
let name = entry.file_name().to_string_lossy().into_owned();
PROJECT_MARKERS.iter().any(|marker| marker == &name)
});
if hit {
return Some(cursor);
}
}
None
}
/// Nearest ancestor that is a git work tree.
fn project_with_git(artifact: &Path) -> Option<PathBuf> {
let mut cursor = artifact.parent()?.to_path_buf();
loop {
if cursor.join(".git").exists() {
return Some(cursor);
}
if !cursor.pop() {
return None;
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GitState {
/// `git check-ignore` says the folder is ignored — safe to delete.
Ignored,
/// `git ls-files` says content inside the folder is tracked — never delete.
Tracked,
/// Inside a work tree, ignored by git, nothing tracked.
Untracked,
/// No git repository around, or git is unavailable.
Unknown,
}
fn git_state(project: &Path, artifact: &Path) -> GitState {
if !project.join(".git").exists() || project_with_git(artifact).is_none() {
return GitState::Unknown;
}
let ignored = run_git(
project,
&["check-ignore", "-q", &artifact.to_string_lossy()],
);
if ignored == Some(true) {
return GitState::Ignored;
}
let tracked = run_git_raw(project, &["ls-files", "--", &artifact.to_string_lossy()]);
match tracked {
Some(list) if !list.trim().is_empty() => GitState::Tracked,
Some(_) => GitState::Untracked,
None => GitState::Unknown,
}
}
fn run_git(project: &Path, args: &[&str]) -> Option<bool> {
let output = Command::new("git")
.arg("-C")
.arg(project)
.args(args)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
Some(output.status.success())
}
fn run_git_raw(project: &Path, args: &[&str]) -> Option<String> {
let output = Command::new("git")
.arg("-C")
.arg(project)
.args(args)
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
None
}
}
fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
let targets: Vec<(PathBuf, ItemKind)> = report
.items
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
if targets.is_empty() {
return;
}
progress.phase("measure", "measuring artefacts");
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
for (item, info) in report.items.iter_mut().zip(sizes) {
item.size = info.logical;
item.allocated = info.allocated;
if info.unreadable > 0 {
let suffix = format!("{} entries unreadable", info.unreadable);
item.note = Some(match item.note.take() {
Some(note) => format!("{note} · {suffix}"),
None => suffix,
});
}
}
}
/// APFS local snapshots: they can pin tens of gigabytes. Reported, never
/// removed — dropping them needs admin rights and a decision about backups.
/// tmutil prints a `Snapshots for disk /:` banner that is not a snapshot name.
const SNAPSHOT_PREFIX: &str = "com.apple.TimeMachine";
#[derive(Clone, Debug, Default)]
pub struct LocalSnapshot {
pub name: String,
pub size_hint: Bytes,
}
pub fn local_snapshots() -> Vec<LocalSnapshot> {
if !cfg!(target_os = "macos") {
return Vec::new();
}
let output = match Command::new("tmutil")
.arg("listlocalsnapshots")
.arg("/")
.stderr(std::process::Stdio::null())
.output()
{
Ok(output) if output.status.success() => output,
_ => return Vec::new(),
};
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|line| line.starts_with(SNAPSHOT_PREFIX))
.map(|line| LocalSnapshot {
name: line.to_string(),
size_hint: Bytes::ZERO,
})
.collect()
}
/// Human hint for the purge screen.
pub fn snapshot_note(snapshots: &[LocalSnapshot]) -> Option<String> {
if snapshots.is_empty() {
return None;
}
Some(format!(
"{} APFS local snapshot(s) present — remove with `tmutil deletelocalsnapshots <date>` (admin)",
snapshots.len()
))
}
#[cfg(test)]
mod tests {
use super::*;
fn sandbox() -> PathBuf {
let root = std::env::temp_dir().join(format!(
"squid-purge-test-{}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(root.join("demo/node_modules/left-pad")).unwrap();
std::fs::write(root.join("demo/node_modules/left-pad/index.js"), b"x").unwrap();
std::fs::write(root.join("demo/package.json"), b"{}").unwrap();
std::fs::create_dir_all(root.join("demo/dist")).unwrap();
std::fs::write(root.join("demo/dist/index.html"), b"x").unwrap();
std::fs::create_dir_all(root.join("loose/dist")).unwrap();
std::fs::write(root.join("loose/dist/important.pdf"), b"x").unwrap();
std::fs::create_dir_all(root.join("rust/checkme/target/debug")).unwrap();
std::fs::write(root.join("rust/checkme/Cargo.toml"), b"[package]").unwrap();
std::fs::write(root.join("rust/checkme/target/debug/bin"), b"x").unwrap();
root
}
#[test]
fn artefacts_are_found_and_loose_dirs_are_left_alone() {
let root = sandbox();
let settings = squid_core::settings::Settings {
purge_roots: vec![root.to_string_lossy().into_owned()],
..squid_core::settings::Settings::default()
};
let engine = Engine::with_settings(settings, Vec::new());
let progress = Progress::new();
let cancel = CancelToken::new();
let report = scan(
&engine,
&PurgeOptions {
roots: vec![root.clone()],
min_age_days: Some(0),
force: true,
max_depth: Some(6),
},
&progress,
&cancel,
)
.expect("scan");
let names: Vec<String> = report
.items
.iter()
.map(|item| item.path.to_string_lossy().into_owned())
.collect();
assert!(
names.iter().any(|p| p.ends_with("demo/node_modules")),
"{names:?}"
);
assert!(
names.iter().any(|p| p.ends_with("rust/checkme/target")),
"{names:?}"
);
assert!(
names.iter().any(|p| p.ends_with("demo/dist")),
"dist inside a project is an artefact: {names:?}"
);
assert!(
!names.iter().any(|p| p.ends_with("loose/dist")),
"dist outside a project must not be offered: {names:?}"
);
for item in &report.items {
assert_eq!(item.kind, ItemKind::Path);
assert!(!item.anchors.is_empty());
}
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn fresh_artefacts_are_locked_without_force() {
let root = sandbox();
let settings = squid_core::settings::Settings {
purge_roots: vec![root.to_string_lossy().into_owned()],
purge_min_age_days: 30,
..squid_core::settings::Settings::default()
};
let engine = Engine::with_settings(settings, Vec::new());
let progress = Progress::new();
let cancel = CancelToken::new();
let report = scan(
&engine,
&PurgeOptions {
roots: vec![root.clone()],
min_age_days: None,
force: false,
max_depth: Some(6),
},
&progress,
&cancel,
)
.expect("scan");
assert!(!report.items.is_empty());
assert!(
report.items.iter().all(|item| !item.selected),
"brand new artefacts must not be pre-selected"
);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn git_state_understands_an_ignored_folder() {
let root = std::env::temp_dir().join(format!(
"squid-purge-git-{}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
let repo = root.join("repo");
std::fs::create_dir_all(repo.join("src")).unwrap();
std::fs::create_dir_all(repo.join("node_modules/pkg")).unwrap();
std::fs::write(repo.join("package.json"), b"{}").unwrap();
std::fs::write(repo.join("src/main.js"), b"x").unwrap();
std::fs::write(repo.join(".gitignore"), b"node_modules/\n").unwrap();
let init = Command::new("git")
.current_dir(&repo)
.args(["init", "-q"])
.status();
if init.map(|s| s.success()).unwrap_or(false) {
let state = git_state(&repo, &repo.join("node_modules"));
assert_eq!(state, GitState::Ignored);
let tracked = git_state(&repo, &repo.join("src"));
assert_eq!(tracked, GitState::Untracked);
}
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn do_not_descend_covers_the_dangerous_names() {
for name in ["Library", ".Trash", ".git", "Volumes", ".ssh"] {
assert!(
DO_NOT_DESCEND.iter().any(|skip| skip.owns(name)),
"{name} must never be descended into"
);
}
assert!(ALWAYS.iter().any(|known| known.owns("node_modules")));
assert!(AMBIGUOUS.iter().any(|known| known.owns("build")));
assert!(!ALWAYS.iter().any(|known| known.owns("build")));
}
}

View File

@ -0,0 +1,598 @@
//! `squid uninstall` — AppCleaner-style "app plus everything it left behind".
//!
//! The plan is built from two sources: the `.app` bundle itself and a readdir
//! index of the per-app leftover roots (`~/Library/Preferences`,
//! `~/Library/Containers`, `/Library/LaunchDaemons`, …). Matching is by bundle
//! id first — names are ambiguous, reverse-DNS identifiers are not.
//!
//! Nothing is deleted here. [`remove_plan`] hands the approved items to
//! [`crate::delete`], which re-validates every single path.
use crate::delete::{self, DeleteJob, DeleteOutcome};
use crate::Engine;
use squid_core::progress::{CancelToken, Progress};
use squid_core::{
AppInfo, Bytes, Category, CleanupItem, DeleteMode, ItemKind, LockReason, UninstallPlan,
};
use squid_platform::apps::read_bundle;
use squid_platform::leftovers::LeftoverIndex;
use squid_platform::Naming;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Read the installed-app inventory.
pub fn scan_apps(
engine: &Engine,
size_apps: bool,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<Vec<AppInfo>> {
progress.phase("apps", "reading the application inventory");
let apps = engine.platform().list_apps(cancel, size_apps)?;
progress.note(format!("{} applications found", apps.len()));
Ok(apps)
}
/// Look apps up by name, bundle id or `.app` path.
pub fn find(
engine: &Engine,
query: &str,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<AppInfo>> {
let needle = query.trim();
if needle.is_empty() {
return Err(squid_core::SquidError::NothingToDo);
}
let mut apps = scan_apps(engine, false, progress, cancel)?;
// A literal bundle path beats fuzzy matching: `squid uninstall ./Foo.app`.
let as_path = squid_core::paths::expand(needle);
if as_path.extension().map(|e| e == "app").unwrap_or(false) && as_path.is_dir() {
let bundle = read_bundle(&as_path).unwrap_or_default();
let running = engine.platform().running_executables();
if let Some(mut app) =
squid_platform::apps::app_from_bundle(as_path.clone(), "Path", &running, false)
{
app.bundle_id = bundle.bundle_id.or(app.bundle_id);
return Ok(vec![app]);
}
}
let needle_lower = needle.to_lowercase();
let needle_compact = needle_lower.replace([' ', '-', '_'], "");
apps.retain(|app| {
let name = app.name.to_lowercase();
let stem = squid_platform::apps::stem_lower(&app.path);
let id = app.bundle_id.as_deref().unwrap_or_default().to_lowercase();
name == needle_lower
|| stem == needle_lower
|| id == needle_lower
|| name.contains(&needle_lower)
|| stem.contains(&needle_lower)
|| id.contains(&needle_lower)
|| name.replace([' ', '-', '_'], "").contains(&needle_compact)
});
apps.sort_by_key(|app| {
let name = app.name.to_lowercase();
match (
name == needle_lower,
name.starts_with(&needle_lower),
name.contains(&needle_lower),
) {
(true, _, _) => 0,
(_, true, _) => 1,
(_, _, true) => 2,
_ => 3,
}
});
Ok(apps)
}
/// Everything that would be removed for `app`, with locks already applied.
pub fn build_plan(
engine: &Engine,
app: &AppInfo,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<UninstallPlan> {
progress.phase("plan", format!("looking for {} leftovers", app.name));
let mut plan = UninstallPlan {
app: app.clone(),
items: Vec::new(),
warnings: Vec::new(),
};
let system = is_system_app(app);
if system {
plan.warnings.push(
"this app ships with macOS (SIP-protected) — squid will refuse to delete it"
.to_string(),
);
}
if app.running {
plan.warnings.push(format!(
"{} is running — quit it before uninstalling",
app.name
));
}
if app.has_sibling_install {
plan.warnings.push(
"another copy of this bundle id is installed; shared preference files stay behind"
.to_string(),
);
}
// 1. The bundle itself.
let mut bundle_item = CleanupItem::new(
app.path.clone(),
ItemKind::Path,
Category::Leftovers,
app.name.clone(),
)
.with_rule("uninstall-bundle")
.with_anchors(bundle_anchors(&app.path));
bundle_item.note = Some(match app.version.as_deref() {
Some(version) => format!("{} · {}", app.source, version),
None => app.source.clone(),
});
if system {
bundle_item = bundle_item
.locked(LockReason::Protected)
.with_note("system application");
} else if app.running {
bundle_item = bundle_item
.locked(LockReason::AppRunning)
.with_note("quit the app first");
} else if !crate::writable_by_us(&app.path) && !crate::is_root() {
bundle_item = bundle_item
.locked(LockReason::NotOwned)
.with_note("run squid uninstall with sudo to remove this copy");
}
plan.push(bundle_item);
// 2. Leftovers. One readdir pass per root, reused for every match.
let roots = engine.platform().leftover_roots();
let index = LeftoverIndex::build(&roots, cancel);
progress.note(format!(
"indexed {} leftover candidates for {}",
index.entry_count(),
app.name
));
let categories = category_index(&roots);
for matched in index.match_app(app.bundle_id.as_deref(), &app.name) {
if skip_leftover(&matched.path, &app.path) {
continue;
}
let kind = if matched.is_dir {
ItemKind::Path
} else {
ItemKind::File
};
let anchor = anchor_for(&matched.path, &roots);
let category = categories
.iter()
.find(|(dir, _)| matched.path.starts_with(dir))
.map(|(_, category)| *category)
.unwrap_or(Category::Leftovers);
let mut item = CleanupItem::new(
matched.path.clone(),
kind,
category,
describe(&matched.path),
)
.with_rule("uninstall-leftovers")
.with_anchors(anchor);
if let Some(root) = roots
.iter()
.find(|root| matched.path.starts_with(&root.dir) && root.naming == Naming::BundleId)
{
let _ = root;
item.note = Some("matched by bundle id".into());
} else if let Some(id) = app.bundle_id.as_deref() {
let _ = id;
item.note = Some("matched by name".into());
}
if system {
item = item
.locked(LockReason::Protected)
.with_note("system application");
} else if app.running {
item = item
.locked(LockReason::AppRunning)
.with_note("quit the app first");
} else if app.has_sibling_install {
item = item
.locked(LockReason::SharedWithOtherInstall)
.with_note("another install still uses this file");
}
if let Some(kind) = document_store(&matched.path) {
item.note = Some(match kind {
Store::Container => "sandboxed container — may hold saved documents".into(),
Store::AppSupport => "application support — may hold saved documents".into(),
});
plan.warnings.push(format!(
"{} may contain documents you created",
squid_core::paths::pretty(&matched.path)
));
}
if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
plan.push(item);
}
measure(&mut plan, progress, cancel)?;
plan.items.sort_by(|a, b| {
b.on_disk()
.cmp(&a.on_disk())
.then_with(|| a.path.cmp(&b.path))
});
let unique: Vec<String> = std::mem::take(&mut plan.warnings)
.into_iter()
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
plan.warnings = unique;
Ok(plan)
}
fn measure(
plan: &mut UninstallPlan,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<()> {
let targets: Vec<(PathBuf, ItemKind)> = plan
.items
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
for (item, info) in plan.items.iter_mut().zip(sizes) {
item.size = info.logical;
item.allocated = info.allocated;
if info.unreadable > 0 {
item.note = Some(format!("{} entries unreadable", info.unreadable));
}
}
Ok(())
}
/// Delete an approved plan, running the platform lifecycle hooks around it.
pub fn remove_plan(
engine: &Engine,
plan: &UninstallPlan,
mode: DeleteMode,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<DeleteOutcome> {
let prepared = engine.platform().prepare_uninstall(&plan.app);
for note in &prepared.notes {
progress.note(note.clone());
}
for warning in prepared.warnings.iter().chain(plan.warnings.iter()) {
progress.warning(warning.clone());
}
if !prepared.stopped_services.is_empty() {
progress.note(format!(
"stopped {} background service(s)",
prepared.stopped_services.len()
));
}
let job = DeleteJob::new(plan.items.clone(), mode, "squid uninstall");
let outcome = delete::execute(engine, &job, progress, cancel)?;
let removed: Vec<PathBuf> = outcome
.summary
.session_id
.as_deref()
.and_then(squid_core::ledger::load_session)
.map(|session| session.entries.into_iter().map(|e| e.path).collect())
.unwrap_or_default();
let finished = engine.platform().finish_uninstall(&plan.app, &removed);
for note in finished.notes {
progress.note(note);
}
for warning in finished.warnings {
progress.warning(warning);
}
Ok(outcome)
}
/// The safety anchor for the bundle itself.
///
/// [`squid_core::fs::default_anchors`] deliberately has no `/Applications`
/// entry — it is a list of folders squid is *allowed to clean inside of*, and
/// an application folder is not one of them. Reusing it for the bundle made
/// every uninstall skip the `.app` with "outside every declared cleanup
/// anchor" while happily deleting the leftovers, which is the opposite of what
/// the user approved. The honest anchor is the folder that holds this one
/// bundle: nothing deeper, nothing wider. `/Applications` itself stays on the
/// hard-deny list, so the anchor can never be used to remove the folder.
fn bundle_anchors(bundle: &Path) -> Vec<PathBuf> {
match bundle.parent() {
Some(parent) if !parent.as_os_str().is_empty() => vec![parent.to_path_buf()],
_ => Vec::new(),
}
}
/// A leftover path we refuse to offer: inside the bundle, an ancestor of it,
/// or a symlink pointing back into the bundle.
fn skip_leftover(path: &Path, bundle: &Path) -> bool {
if path == bundle {
return true;
}
if path.starts_with(bundle) || bundle.starts_with(path) {
return true;
}
// `~/Library/Preferences/ByHost` and friends can hold folder placeholders.
let leaf = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if leaf.is_empty() || leaf == "." || leaf == ".." {
return true;
}
false
}
/// Prefer the tightest leftover root as the safety anchor, so the policy sees
/// `~/Library/Preferences` rather than `/`.
fn anchor_for(path: &Path, roots: &[squid_platform::LeftoverRoot]) -> Vec<PathBuf> {
let mut best: Option<PathBuf> = None;
for root in roots {
if path.starts_with(&root.dir) {
let better = match &best {
Some(current) => root.dir.components().count() > current.components().count(),
None => true,
};
if better {
best = Some(root.dir.clone());
}
}
}
match best {
Some(dir) => vec![dir],
None => squid_core::fs::default_anchors(),
}
}
fn category_index(roots: &[squid_platform::LeftoverRoot]) -> Vec<(PathBuf, Category)> {
roots
.iter()
.map(|root| {
let text = root.dir.to_string_lossy().to_lowercase();
let category = if text.ends_with("/library/caches") || text.ends_with("/.cache") {
Category::AppCaches
} else if text.ends_with("/library/logs") {
Category::Logs
} else {
root.category
};
(root.dir.clone(), category)
})
.collect()
}
/// Folders that can hold a document the user made, not just program state.
/// Split so the warning says *which* kind of folder it is — calling
/// `~/Library/Application Support/Foo` a "sandboxed container" is just wrong.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Store {
Container,
AppSupport,
}
fn document_store(path: &Path) -> Option<Store> {
let text = path.to_string_lossy();
if text.contains("/Library/Containers/") || text.contains("/Library/Group Containers/") {
Some(Store::Container)
} else if text.contains("/Library/Application Support/") {
Some(Store::AppSupport)
} else {
None
}
}
/// Short human label for a leftover: "Preferences/com.foo.plist".
fn describe(path: &Path) -> String {
let components: Vec<String> = path
.components()
.rev()
.take(2)
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
if components.len() == 2 {
format!("{}/{}", components[1], components[0])
} else {
components
.first()
.cloned()
.unwrap_or_else(|| squid_core::paths::pretty(path))
}
}
pub fn is_system_app(app: &AppInfo) -> bool {
app.path.starts_with("/System")
|| app.source.eq_ignore_ascii_case("macOS Apps")
|| app.name.eq_ignore_ascii_case("Safari")
}
/// Total space a plan would reclaim, preferring the on-disk figure.
pub fn plan_size(plan: &UninstallPlan) -> Bytes {
plan.items.iter().map(|item| item.on_disk()).sum()
}
/// Group a plan by category for the detail screen.
pub fn plan_buckets(plan: &UninstallPlan) -> HashMap<Category, (Bytes, usize)> {
let mut out: HashMap<Category, (Bytes, usize)> = HashMap::new();
for item in &plan.items {
let entry = out.entry(item.category).or_insert((Bytes::ZERO, 0));
entry.0 += item.on_disk();
entry.1 += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_app(path: &str, source: &str) -> AppInfo {
AppInfo {
name: "Demo".into(),
bundle_id: Some("com.example.Demo".into()),
path: PathBuf::from(path),
version: Some("1.0".into()),
size: Bytes(1_000),
source: source.into(),
running: false,
has_sibling_install: false,
publisher: None,
installed_ms: None,
}
}
#[test]
fn the_bundle_itself_passes_the_safety_policy() {
// Regression: uninstall used to approve six items and delete five,
// because the `.app` had no anchor and was dropped in silence.
let policy = squid_core::SafetyPolicy::default();
for bundle in [
"/Applications/Demo.app",
"/Applications/Utilities/Demo.app",
"/Users/tester/Applications/Demo.app",
] {
let anchors = bundle_anchors(Path::new(bundle));
assert_eq!(anchors, vec![Path::new(bundle).parent().unwrap()]);
assert_eq!(
policy.denies(Path::new(bundle), &anchors),
None,
"squid must be able to remove the bundle it promised"
);
}
}
#[test]
fn the_bundle_anchor_still_cannot_reach_protected_folders() {
// Widening the anchor to the folder that holds the bundle must not
// widen what can be destroyed: the folder itself is hard-denied, and a
// SIP bundle anchors to `/System/Applications`, which stays out of
// reach even though the bundle path itself looks harmless.
let policy = squid_core::SafetyPolicy::default();
let anchors = bundle_anchors(Path::new("/Applications/Demo.app"));
assert_eq!(anchors, vec![PathBuf::from("/Applications")]);
assert!(
policy
.denies(Path::new("/Applications"), &anchors)
.is_some(),
"the anchor folder itself must never be removable"
);
assert!(policy
.denies(
Path::new("/System/Applications"),
&bundle_anchors(Path::new("/System/Applications/Notes.app"))
)
.is_some());
}
#[test]
fn leftovers_inside_the_bundle_are_never_double_counted() {
let bundle = Path::new("/Applications/Demo.app");
assert!(skip_leftover(
Path::new("/Applications/Demo.app/Contents/Resources/x"),
bundle
));
assert!(skip_leftover(bundle, bundle));
assert!(skip_leftover(Path::new("/Applications"), bundle));
assert!(!skip_leftover(
Path::new("/Users/x/Library/Preferences/com.example.Demo.plist"),
bundle
));
}
#[test]
fn the_tightest_root_wins() {
let home = squid_core::paths::home_dir();
let roots = vec![
squid_platform::LeftoverRoot {
dir: home.clone(),
naming: Naming::Either,
deep: false,
category: Category::Leftovers,
},
squid_platform::LeftoverRoot {
dir: home.join("Library/Preferences"),
naming: Naming::BundleId,
deep: false,
category: Category::Leftovers,
},
];
let path = home.join("Library/Preferences/com.example.Demo.plist");
let anchors = anchor_for(&path, &roots);
assert_eq!(anchors.len(), 1);
assert!(anchors[0].ends_with("Library/Preferences"));
}
#[test]
fn system_apps_are_recognised() {
assert!(is_system_app(&sample_app(
"/System/Applications/Chess.app",
"macOS Apps"
)));
assert!(!is_system_app(&sample_app(
"/Applications/Demo.app",
"Applications"
)));
}
#[test]
fn a_plan_for_a_missing_app_still_describes_the_bundle() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let app = sample_app("/Applications/SquidDoesNotExist.app", "Applications");
let plan = build_plan(&engine, &app, &progress, &cancel).expect("plan");
assert!(!plan.items.is_empty());
assert_eq!(plan.items[0].path, app.path);
assert!(plan
.items
.iter()
.all(|item| !item.selected || item.lock.is_none()));
}
#[test]
fn a_system_app_plan_is_locked() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let app = sample_app("/System/Applications/Chess.app", "macOS Apps");
let plan = build_plan(&engine, &app, &progress, &cancel).expect("plan");
assert!(plan.items[0].lock.is_some());
assert!(plan
.items
.iter()
.all(|item| !item.selected || item.lock.is_none()));
}
#[test]
fn find_returns_nothing_for_a_nonsense_query() {
let engine = Engine::new();
let progress = Progress::new();
let cancel = CancelToken::new();
let hits = find(
&engine,
"zzz-definitely-not-installed-zzz",
&cancel,
&progress,
)
.expect("find");
assert!(hits.is_empty());
}
}

View File

@ -0,0 +1,19 @@
[package]
name = "squid-platform"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "OS adapters for squid: apps, leftovers, volumes and lifecycle hooks"
[dependencies]
squid-core.workspace = true
serde.workspace = true
libc.workspace = true
dirs.workspace = true
walkdir.workspace = true
plist.workspace = true
rayon.workspace = true
[target.'cfg(unix)'.dependencies]
libc.workspace = true

View File

@ -0,0 +1,169 @@
//! Generic application discovery used by the per-OS adapters.
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes};
use std::path::{Path, PathBuf};
/// Metadata pulled out of a macOS bundle.
#[derive(Clone, Debug, Default)]
pub struct BundleInfo {
pub name: Option<String>,
pub bundle_id: Option<String>,
pub version: Option<String>,
pub short_version: Option<String>,
pub publisher: Option<String>,
pub executable: Option<String>,
}
fn string_field(dict: &plist::Dictionary, key: &str) -> Option<String> {
dict.get(key)
.and_then(|v| v.as_string())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
pub fn read_bundle(app_path: &Path) -> Option<BundleInfo> {
let plist_path = app_path.join("Contents/Info.plist");
let value = plist::Value::from_file(&plist_path).ok()?;
let dict = value.as_dictionary()?;
let info = BundleInfo {
name: string_field(dict, "CFBundleDisplayName")
.or_else(|| string_field(dict, "CFBundleName")),
bundle_id: string_field(dict, "CFBundleIdentifier"),
version: string_field(dict, "CFBundleVersion"),
short_version: string_field(dict, "CFBundleShortVersionString"),
publisher: string_field(dict, "CFBundleGetInfoString").map(|info| {
info.split_whitespace()
.take(3)
.collect::<Vec<_>>()
.join(" ")
}),
executable: string_field(dict, "CFBundleExecutable"),
};
Some(info)
}
/// Walk a source directory looking for `.app` bundles, without descending into
/// the bundles themselves (millions of files we never need to list).
pub fn discover_bundles(dir: &Path, max_depth: usize, cancel: &CancelToken) -> Vec<PathBuf> {
let mut found = Vec::new();
if !dir.is_dir() {
return found;
}
let mut stack: Vec<(PathBuf, usize)> = vec![(dir.to_path_buf(), 0)];
let limit = max_depth.max(1);
while let Some((current, depth)) = stack.pop() {
if cancel.is_cancelled() {
break;
}
let Ok(entries) = std::fs::read_dir(&current) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
let is_dir = entry
.file_type()
.map(|ft| ft.is_dir())
.unwrap_or_else(|_| path.is_dir());
if !is_dir {
continue;
}
if name.ends_with(".app") {
found.push(path);
continue;
}
// Never wander into system frameworks or a volume's Trash.
if matches!(
name.as_str(),
"Contents" | "System" | "Library" | ".Trashes" | "Volumes" | "node_modules"
) {
continue;
}
if depth < limit {
stack.push((path, depth + 1));
}
}
}
found.sort();
found
}
pub fn app_from_bundle(
path: PathBuf,
source: &str,
running: &[String],
measure: bool,
) -> Option<AppInfo> {
let dir_name = path
.file_name()
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_string())
.unwrap_or_default();
if dir_name.is_empty() {
return None;
}
let bundle = read_bundle(&path).unwrap_or_default();
let name = bundle.name.clone().unwrap_or(dir_name.clone());
let mut app = AppInfo {
name,
bundle_id: bundle.bundle_id.clone(),
path: path.clone(),
version: bundle
.short_version
.clone()
.or_else(|| bundle.version.clone()),
size: if measure {
Bytes(
squid_core::fs::measure(&path, squid_core::ItemKind::Path)
.allocated
.as_u64(),
)
} else {
Bytes::ZERO
},
source: source.to_string(),
running: is_running(&dir_name, bundle.executable.as_deref(), running),
has_sibling_install: false,
publisher: bundle.publisher.clone(),
installed_ms: path
.metadata()
.ok()
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64),
};
if app.name.to_lowercase() == "safari" {
// Safari cannot be removed and its caches are managed by the OS.
app.bundle_id = app.bundle_id.or_else(|| Some("com.apple.Safari".into()));
}
Some(app)
}
/// Match "is this app running" against the process executable list.
pub fn is_running(dir_name: &str, executable: Option<&str>, running: &[String]) -> bool {
let mut candidates: Vec<String> = Vec::with_capacity(3);
if let Some(exe) = executable {
candidates.push(exe.to_lowercase());
}
candidates.push(dir_name.to_lowercase());
if dir_name.to_lowercase().ends_with(".app") {
candidates.push(dir_name.to_lowercase().trim_end_matches(".app").to_string());
}
running.iter().any(|proc| {
let proc = proc.to_lowercase();
let leaf = proc.rsplit('/').next().unwrap_or(&proc).to_string();
candidates
.iter()
.any(|c| !c.is_empty() && (leaf == *c || leaf == format!("{c}.app")))
})
}
/// Case-insensitive file-name stem, e.g. `Safari.app` -> `safari`.
pub fn stem_lower(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase())
.unwrap_or_default()
}

View File

@ -0,0 +1,409 @@
//! Finding an app's leftovers the way AppCleaner does: cheap directory
//! indexes plus conservative name matching.
//!
//! The matcher only ever compares a leftover entry against identifiers that
//! belong to *this* app, and refuses every entry on the shared-vendor deny
//! list. False positives here are unrecoverable, so the rules err on the side
//! of "leave it behind and tell the user".
use crate::LeftoverRoot;
use crate::Naming::*;
use squid_core::progress::CancelToken;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
/// Vendor folders and Apple namespaces that must never be treated as leftovers
/// of a single app, no matter how the names line up.
const DENY_NAMES: &[&str] = &[
"google",
"microsoft",
"adobe",
"mozilla",
"oracle",
"java",
"python",
"apache",
"nodejs",
"apple",
"com.apple",
"com.apple.Safari",
"systempreferences",
"com.apple.systempreferences",
"knowledge",
"fonts",
"services",
"quicklook",
"scriptingadditions",
"prefpane",
"crashreporter",
"com.apple.crashreporter",
"syncservices",
"mobilesync",
"cloudservices",
"icloud",
"keychains",
"mail",
"messages",
"photos",
"safari",
"default stored data",
"address book",
"calendars",
"cookies",
"saved application state",
];
/// Names that end a bundle-id-derived file name and are safe to strip.
const KNOWN_SUFFIXES: &[&str] = &[
".plist",
".savedstate",
".saved application state",
".shipit",
".loginitems",
".loginitems-legacy",
".binarycookies",
".sqlite",
".sqlite-wal",
".sqlite-shm",
".lock",
".lockfile",
".cachedast",
".noindex",
".noindex.localized",
".download",
".partial",
".upload",
".downloaded",
".playing",
".mp3",
".png",
".jpg",
".jpeg",
".gif",
".pdf",
".txt",
".json",
".xml",
".log",
];
/// Machine-generated extensions only. The name matcher has no bundle id to
/// lean on, so it never treats a document extension (`.pdf`, `.png`, `.mp3`)
/// as removable just because the file is named after the app.
const NAME_SUFFIXES: &[&str] = &[
"plist",
"savedstate",
"saved application state",
"shipit",
"loginitems",
"loginitems-legacy",
"binarycookies",
"sqlite",
"sqlite-wal",
"sqlite-shm",
"lock",
"lockfile",
"cachedast",
"noindex",
"noindex.localized",
"download",
"partial",
"upload",
"downloaded",
"playing",
"cache",
"log",
"tmp",
];
#[derive(Clone, Debug)]
struct Entry {
path: PathBuf,
lower: String,
is_dir: bool,
}
/// One readdir per leftover root, kept in memory while the user browses.
#[derive(Clone, Debug, Default)]
pub struct LeftoverIndex {
roots: Vec<(LeftoverRoot, Vec<Entry>)>,
entry_count: usize,
}
impl LeftoverIndex {
pub fn build(roots: &[LeftoverRoot], cancel: &CancelToken) -> Self {
let mut index = Self::default();
for root in roots {
let mut entries = Vec::new();
collect(
&root.dir,
if root.deep { 2 } else { 1 },
&mut entries,
cancel,
);
index.entry_count += entries.len();
index.roots.push((root.clone(), entries));
}
index
}
pub fn entry_count(&self) -> usize {
self.entry_count
}
/// Every leftover belonging to `app`. Returns paths plus the root category
/// so the plan can label them.
pub fn match_app(&self, bundle_id: Option<&str>, app_name: &str) -> Vec<Match> {
let mut matches: BTreeSet<(u8, PathBuf)> = BTreeSet::new();
let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
let name_lower = app_name.trim().to_lowercase();
let name_compact = name_lower.replace([' ', '-', '_'], "");
for (root, entries) in &self.roots {
for entry in entries {
if is_denied(&entry.lower) {
continue;
}
let reason = match root.naming {
BundleId => match_bundle_id(&entry.lower, bundle_id).then_some("bundle id"),
AppName => {
match_name(&entry.lower, &name_lower, &name_compact).then_some("name")
}
Either => match_bundle_id(&entry.lower, bundle_id)
.then_some("bundle id")
.or_else(|| {
match_name(&entry.lower, &name_lower, &name_compact).then_some("name")
}),
GroupContainer => match_group(&entry.lower, bundle_id).then_some("group id"),
};
if let Some(reason) = reason {
let rank = if matches!(reason, "bundle id" | "group id") {
0
} else {
1
};
matches.insert((rank, entry.path.clone()));
if entry.is_dir {
// dirs and files are both kept; the flag only drives the
// plan's ItemKind downstream.
dirs.insert(entry.path.clone());
}
}
}
}
matches
.into_iter()
.map(|(_, path)| Match {
is_dir: dirs.contains(&path),
path,
})
.collect()
}
pub fn roots(&self) -> &[(LeftoverRoot, Vec<PathBuf>)] {
// Hand back paths only; callers do not need Entry.
// (Kept as a helper for `squid doctor`.)
&[]
}
}
#[derive(Clone, Debug)]
pub struct Match {
pub path: PathBuf,
pub is_dir: bool,
}
fn collect(dir: &Path, depth: usize, out: &mut Vec<Entry>, cancel: &CancelToken) {
if depth == 0 || cancel.is_cancelled() {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = entry.file_name().to_str().map(|s| s.to_lowercase()) else {
continue;
};
let is_dir = entry
.file_type()
.map(|ft| ft.is_dir())
.unwrap_or_else(|_| path.is_dir());
out.push(Entry {
path: path.clone(),
lower: name,
is_dir,
});
if is_dir && depth > 1 {
collect(&path, depth - 1, out, cancel);
}
}
}
fn is_denied(lower: &str) -> bool {
DENY_NAMES.contains(&lower)
}
/// `com.example.MyApp` matches `com.example.MyApp`, `com.example.MyApp.plist`,
/// `com.example.MyApp.savedState`, `com.example.MyApp.helper` and the reversed
/// container folders that begin with the same id.
fn match_bundle_id(entry: &str, bundle_id: Option<&str>) -> bool {
let Some(bundle_id) = bundle_id else {
return false;
};
let target = bundle_id.trim().to_lowercase();
if target.len() < 4 || target.split('.').count() < 2 {
// Ad-hoc bundle ids ("Safari", "no-bundle-id") are far too loose.
return false;
}
if entry == target {
return true;
}
if let Some(rest) = entry.strip_prefix(&target) {
let mut chars = rest.chars();
let Some(first) = chars.next() else {
return false;
};
// `com.example.appdata` must NOT match `com.example.app`.
let boundary_ok = !first.is_alphanumeric();
if !boundary_ok {
return false;
}
let tail = rest.trim_start_matches(['.', '_', '-', ' ']);
// Allow the known junk suffixes and helper-ish continuations, but keep
// unrelated apps of the same vendor out (`com.foo.bar` vs
// `com.foo.baz`) by requiring the next dot component to be short
// (`.helper`, `.ShipIt`) or the whole tail to be a known suffix.
if has_known_suffix(tail) {
return true;
}
if tail.contains('.') {
let first_component = tail.split('.').next().unwrap_or_default();
return first_component.len() <= 12;
}
return tail.len() <= 12;
}
// Container folders prefixed by a signing/team hash.
if let Some(stripped) = strip_hash_prefix(entry) {
return stripped == target || match_bundle_id(stripped, Some(bundle_id));
}
false
}
/// `5A2F1C9D-1234-ABCD.com.example.app` -> `com.example.app`
fn strip_hash_prefix(entry: &str) -> Option<&str> {
let idx = entry.find(".com.")?;
let prefix = &entry[..idx];
let plausible = prefix.len() <= 40
&& prefix
.chars()
.all(|c| c.is_ascii_hexdigit() || matches!(c, '-' | '.' | '_'));
if plausible {
Some(&entry[idx + 1..])
} else {
None
}
}
fn match_name(entry: &str, name_lower: &str, name_compact: &str) -> bool {
if name_lower.len() < 4 {
return false;
}
// Callers hand us an already-lowercased dir entry; normalise anyway so the
// matcher can never be tripped up by `Slack` vs `slack`.
let entry = entry.trim().to_lowercase();
if entry == name_lower {
return true;
}
let compact_entry = entry.replace([' ', '-', '_'], "");
if compact_entry == name_compact {
return true;
}
if let Some(rest) = entry.strip_prefix(name_lower) {
let first = rest.chars().next();
if !matches!(first, Some('.') | Some(' ') | Some('-') | Some('_')) {
return false;
}
let tail = rest.trim_start_matches(['.', ' ', '-', '_']);
return NAME_SUFFIXES.iter().any(|suf| tail.starts_with(suf));
}
false
}
/// `tail` lost its leading separator above, so the suffix list is trimmed the
/// same way before the comparison — otherwise `.plist` never matches `plist`.
fn has_known_suffix(tail: &str) -> bool {
KNOWN_SUFFIXES.iter().any(|suffix| {
let suffix = suffix.trim_start_matches(['.', ' ', '-', '_']);
!suffix.is_empty() && tail.starts_with(suffix)
})
}
fn match_group(entry: &str, bundle_id: Option<&str>) -> bool {
let Some(bundle_id) = bundle_id else {
return false;
};
let target = bundle_id.trim().to_lowercase();
if entry == target || entry == format!("group.{target}") {
return true;
}
// `group.com.example.app.shared`
if let Some(rest) = entry.strip_prefix(&format!("group.{target}")) {
return rest.is_empty() || !rest.chars().next().unwrap().is_alphanumeric();
}
// Container folders: `group.com.example.app` also appears without prefix
// for some sandboxes.
entry.starts_with(&target)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundle_id_matching() {
let id = "com.slack.Slack";
assert!(match_bundle_id("com.slack.slack", Some(id)));
assert!(match_bundle_id("com.slack.slack.plist", Some(id)));
assert!(match_bundle_id("com.slack.slack.savedstate", Some(id)));
assert!(match_bundle_id("com.slack.slack.shipit", Some(id)));
assert!(match_bundle_id("com.slack.slack.helper", Some(id)));
// Different product of the same vendor.
assert!(!match_bundle_id("com.slack.HockeyApp", Some(id)));
// Prefix that is really a different app.
assert!(!match_bundle_id("com.slack.slackish", Some(id)));
// Too loose to be a bundle id at all.
assert!(!match_bundle_id("slack", Some(id)));
assert!(!match_bundle_id("com.slack.slack.plist", None));
}
#[test]
fn name_matching_is_conservative() {
assert!(match_name("slack", "slack", "slack"));
assert!(match_name("Slack", "slack", "slack"));
assert!(!match_name("com.squirrel.slack.slack", "slack", "slack"));
assert!(match_name("slack.plist", "slack", "slack"));
assert!(!match_name("slackware", "slack", "slack"));
assert!(!match_name("ab", "ab", "ab"));
}
#[test]
fn group_containers() {
assert!(match_group(
"group.com.example.app",
Some("com.example.App")
));
assert!(match_group("com.example.app", Some("com.example.App")));
assert!(!match_group(
"group.com.example.other",
Some("com.example.App")
));
}
#[test]
fn vendor_folders_are_denied() {
assert!(is_denied("google"));
assert!(is_denied("com.apple.Safari"));
assert!(!is_denied("com.google.Chrome"));
}
}

View File

@ -0,0 +1,238 @@
//! OS abstraction. The engines stay OS-agnostic and ask a [`Platform`] for
//! everything that differs between macOS, Linux and Windows.
//!
//! Adding Windows support later means implementing this trait in
//! `windows.rs` (already stubbed) — no engine changes.
use serde::{Deserialize, Serialize};
use squid_core::error::Result;
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Volume};
use std::path::{Path, PathBuf};
pub mod apps;
pub mod leftovers;
pub mod volumes;
#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(windows)]
pub mod windows;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PlatformId {
MacOS,
Linux,
Windows,
Unknown,
}
impl PlatformId {
pub fn as_str(self) -> &'static str {
match self {
PlatformId::MacOS => "macos",
PlatformId::Linux => "linux",
PlatformId::Windows => "windows",
PlatformId::Unknown => "unknown",
}
}
pub fn current() -> PlatformId {
if cfg!(target_os = "macos") {
PlatformId::MacOS
} else if cfg!(target_os = "linux") {
PlatformId::Linux
} else if cfg!(windows) {
PlatformId::Windows
} else {
PlatformId::Unknown
}
}
}
/// A directory that may contain installed applications.
#[derive(Clone, Debug)]
pub struct AppSource {
pub dir: PathBuf,
pub label: String,
/// Scan depth: 1 for `/Applications/*.app`, 2 for nested vendor folders.
pub depth: usize,
pub system: bool,
}
/// A directory that may contain per-app leftovers.
#[derive(Clone, Debug)]
pub struct LeftoverRoot {
pub dir: PathBuf,
/// How entries in this directory are named.
pub naming: Naming,
/// Recursing is dangerous here (e.g. `Application Support`), so matching is
/// always done against the direct children unless this is set.
pub deep: bool,
pub category: squid_core::Category,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Naming {
/// `com.example.App.plist`, `com.example.App`
BundleId,
/// `Safari`, `Slack`
AppName,
/// Either of the two.
Either,
/// `group.com.example.App`
GroupContainer,
}
/// Notes a platform wants the user to see before/after removal.
#[derive(Clone, Debug, Default)]
pub struct LifecycleReport {
pub notes: Vec<String>,
pub stopped_services: Vec<String>,
pub warnings: Vec<String>,
}
pub trait Platform: Send + Sync {
fn id(&self) -> PlatformId;
fn display_name(&self) -> String;
fn os_version(&self) -> String;
fn hardware_model(&self) -> String;
/// Directories to scan for installed applications.
fn app_sources(&self) -> Vec<AppSource>;
/// Full app inventory, sizes included. This is the slow one: `size_apps`
/// lets the UI render names first.
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>>;
/// Directories that may hold leftovers for the given app.
fn leftover_roots(&self) -> Vec<LeftoverRoot>;
/// Platform hook before anything is deleted (stop daemons, unload login
/// items, unregister with Launch Services).
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let _ = app;
LifecycleReport::default()
}
/// Platform hook after deletion (refresh caches, forget pkg receipts).
fn finish_uninstall(&self, app: &AppInfo, removed: &[PathBuf]) -> LifecycleReport {
let _ = (app, removed);
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>>;
/// Absolute prefixes that must never be touched.
fn protected_prefixes(&self) -> Vec<PathBuf> {
Vec::new()
}
/// Process names currently running (cheap snapshot, no full table).
fn running_executables(&self) -> Vec<String>;
/// Human readable "why is this not removable" for a path, if any.
fn inspect_path(&self, path: &Path) -> Option<String> {
let _ = path;
None
}
/// Free space that macOS reports as "purgeable" (caches the OS would drop
/// anyway). 0 where the concept does not exist.
fn purgeable_space(&self, mount: &Path) -> Bytes {
let _ = mount;
Bytes::ZERO
}
/// Open the system Trash (Finder / explorer / xdg-open).
fn reveal_trash(&self) {}
}
/// Concrete adapter for the host we are running on.
pub fn current() -> Box<dyn Platform> {
#[cfg(target_os = "macos")]
{
Box::new(macos::MacOs)
}
#[cfg(target_os = "linux")]
{
Box::new(linux::Linux::default())
}
#[cfg(windows)]
{
Box::new(windows::Windows::default())
}
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
{
Box::new(Unsupported)
}
}
/// Adapter used when the OS is not implemented yet: reports volumes through
/// `df`-style data and refuses app management.
pub struct Unsupported;
impl Platform for Unsupported {
fn id(&self) -> PlatformId {
PlatformId::Unknown
}
fn display_name(&self) -> String {
std::env::consts::OS.to_string()
}
fn os_version(&self) -> String {
std::env::consts::ARCH.to_string()
}
fn hardware_model(&self) -> String {
"unknown".into()
}
fn app_sources(&self) -> Vec<AppSource> {
Vec::new()
}
fn list_apps(&self, _cancel: &CancelToken, _size: bool) -> Result<Vec<AppInfo>> {
Err(squid_core::SquidError::Unsupported {
platform: std::env::consts::OS,
what: "application inventory",
})
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
Vec::new()
}
fn volumes(&self) -> Result<Vec<Volume>> {
Ok(Vec::new())
}
fn running_executables(&self) -> Vec<String> {
Vec::new()
}
}
/// Convenience: is this path owned by the effective user?
pub fn is_user_writable(path: &Path) -> bool {
use std::os::unix::fs::MetadataExt;
match std::fs::metadata(path) {
Ok(meta) => {
let uid = unsafe { libc::getuid() };
if uid == 0 {
return true;
}
meta.uid() == uid && meta.mode() & 0o200 != 0
}
Err(_) => false,
}
}
/// Nearest existing ancestor that exists (for ownership checks on paths that
/// are about to disappear).
pub fn closest_existing(path: &Path) -> PathBuf {
let mut cursor = path.to_path_buf();
loop {
if cursor.exists() {
return cursor;
}
if !cursor.pop() {
return PathBuf::from("/");
}
}
}

View File

@ -0,0 +1,310 @@
//! Linux adapter: `.desktop` entries, Flatpak/Snap awareness, XDG leftovers.
use crate::{AppSource, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId};
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Category, Result, Volume};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Default)]
pub struct Linux;
fn home() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/root"))
}
fn run(program: &str, args: &[&str]) -> Option<String> {
Command::new(program)
.args(args)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}
/// One parsed `.desktop` file.
#[derive(Default, Clone)]
struct DesktopEntry {
name: String,
exec: Option<String>,
startup_wm_class: Option<String>,
icon: Option<String>,
no_display: bool,
}
fn parse_desktop(path: &Path) -> Option<DesktopEntry> {
let text = std::fs::read_to_string(path).ok()?;
let mut entry = DesktopEntry::default();
let mut in_desktop = false;
for line in text.lines() {
let line = line.trim();
if line.starts_with('[') {
in_desktop = line == "[Desktop Entry]";
continue;
}
if !in_desktop {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
match key.trim() {
"Name" if entry.name.is_empty() => entry.name = value.trim().to_string(),
"Exec" => entry.exec = Some(value.trim().to_string()),
"StartupWMClass" => entry.startup_wm_class = Some(value.trim().to_string()),
"Icon" => entry.icon = Some(value.trim().to_string()),
"NoDisplay" => entry.no_display = value.trim().eq_ignore_ascii_case("true"),
_ => {}
}
}
if entry.name.is_empty() {
return None;
}
Some(entry)
}
impl Platform for Linux {
fn id(&self) -> PlatformId {
PlatformId::Linux
}
fn display_name(&self) -> String {
"Linux".to_string()
}
fn os_version(&self) -> String {
std::fs::read_to_string("/etc/os-release")
.ok()
.and_then(|text| {
text.lines()
.find(|l| l.starts_with("PRETTY_NAME="))
.map(|l| {
l.trim_end_matches('"')
.trim_start_matches("PRETTY_NAME=\"")
.to_string()
})
})
.unwrap_or_else(|| format!("Linux {}", std::env::consts::ARCH))
}
fn hardware_model(&self) -> String {
let read = |p: &str| {
std::fs::read_to_string(p)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
let product = read("/sys/class/dmi/id/product_name").unwrap_or_default();
let cpu = std::fs::read_to_string("/proc/cpuinfo")
.ok()
.and_then(|info| {
info.lines()
.find(|l| l.starts_with("model name"))
.and_then(|l| l.split_once(':'))
.map(|(_, v)| v.trim().to_string())
})
.unwrap_or_default();
[product, cpu]
.join(" · ")
.trim_matches('·')
.trim()
.to_string()
}
fn app_sources(&self) -> Vec<AppSource> {
[
("/usr/share/applications", "System", 1, true),
("/usr/local/share/applications", "Local", 1, true),
("~/.local/share/applications", "User", 1, false),
(
"/var/lib/flatpak/exports/share/applications",
"Flatpak",
1,
true,
),
(
"~/.local/share/flatpak/exports/share/applications",
"Flatpak (user)",
1,
false,
),
("/snap", "Snap", 2, true),
]
.into_iter()
.map(|(dir, label, depth, system)| AppSource {
dir: squid_core::paths::expand(dir),
label: label.into(),
depth,
system,
})
.filter(|s| s.dir.is_dir())
.collect()
}
fn list_apps(&self, cancel: &CancelToken, _size_apps: bool) -> Result<Vec<AppInfo>> {
let running = self.running_executables();
let mut by_id: BTreeMap<String, AppInfo> = Default::default();
for source in self.app_sources() {
if source.label == "Snap" {
continue; // handled below through `snap list`
}
let Ok(entries) = std::fs::read_dir(&source.dir) else {
continue;
};
for entry in entries.flatten() {
if cancel.is_cancelled() {
break;
}
let path = entry.path();
if path.extension().map(|e| e != "desktop").unwrap_or(true) {
continue;
}
let Some(desktop) = parse_desktop(&path) else {
continue;
};
if desktop.no_display {
continue;
}
let id = path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let exec_name = desktop
.exec
.as_deref()
.and_then(|exec| exec.split_whitespace().next())
.map(|exe| {
Path::new(exe)
.file_name()
.unwrap_or_default()
.to_string_lossy()
.into_owned()
});
let running_flag = exec_name
.as_deref()
.or(desktop.startup_wm_class.as_deref())
.map(|needle| {
let needle = needle.to_lowercase();
running.iter().any(|p| p.to_lowercase().ends_with(&needle))
})
.unwrap_or(false);
by_id.entry(id.clone()).or_insert_with(|| AppInfo {
name: desktop.name.clone(),
bundle_id: Some(id.clone()),
path: path.clone(),
version: None,
size: Bytes::ZERO,
source: source.label.clone(),
running: running_flag,
has_sibling_install: false,
publisher: desktop.icon.clone(),
installed_ms: None,
});
}
}
if let Some(list) = run(
"flatpak",
&[
"list",
"--app",
"--columns=application,name,size,installation",
],
) {
for line in list.lines().skip(1) {
let cols: Vec<&str> = line.split('\t').collect();
if let Some(id) = cols.first() {
by_id.entry(id.to_string()).or_insert_with(|| AppInfo {
name: cols
.get(1)
.map(|s| s.to_string())
.unwrap_or_else(|| id.to_string()),
bundle_id: Some(id.to_string()),
path: PathBuf::from(format!("flatpak:{id}")),
version: None,
size: cols
.get(2)
.and_then(|s| s.trim().strip_suffix(" B"))
.and_then(|s| s.trim().parse::<u64>().ok())
.map(Bytes)
.unwrap_or_default(),
source: "Flatpak".into(),
running: false,
has_sibling_install: false,
publisher: None,
installed_ms: None,
});
}
}
}
Ok(by_id.into_values().collect())
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
let candidates = [
("~/.config", Naming::AppName),
("~/.cache", Naming::AppName),
("~/.local/share", Naming::AppName),
("~/.local/state", Naming::AppName),
("~/.var/app", Naming::BundleId),
("~/.pki", Naming::AppName),
];
candidates
.into_iter()
.map(|(dir, naming)| LeftoverRoot {
dir: squid_core::paths::expand(dir),
naming,
deep: false,
category: Category::Leftovers,
})
.filter(|c| c.dir.is_dir())
.collect()
}
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let mut report = LifecycleReport::default();
if app.running {
report
.warnings
.push(format!("{} is still running", app.name));
}
if app.source == "Flatpak" {
report
.notes
.push("`flatpak uninstall --unused` is recommended afterwards".into());
}
report
}
fn finish_uninstall(&self, _app: &AppInfo, _removed: &[PathBuf]) -> LifecycleReport {
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>> {
Ok(crate::volumes::volumes_from_mounts(
&crate::volumes::mount_entries(),
))
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
["/etc", "/usr", "/bin", "/sbin", "/boot", "/EFI"]
.iter()
.map(PathBuf::from)
.collect()
}
fn running_executables(&self) -> Vec<String> {
run("ps", &["-axo", "comm="])
.map(|out| out.lines().map(|l| l.trim().to_string()).collect())
.unwrap_or_default()
}
fn reveal_trash(&self) {
let trash = home().join(".local/share/Trash/expunged");
let _ = Command::new("xdg-open")
.arg(home().join(".local/share/Trash/files"))
.spawn();
let _ = trash;
}
}

View File

@ -0,0 +1,354 @@
//! macOS adapter: `.app` bundles, sandbox containers, launch services.
use crate::apps::{app_from_bundle, discover_bundles};
use crate::{AppSource, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId};
use rayon::prelude::*;
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Category, Result, SquidError, Volume};
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Default)]
pub struct MacOs;
const LSREGISTER: &str = "/System/Library/Frameworks/CoreServices.framework/Versions/A/\
Frameworks/LaunchServices.framework/Versions/A/Support/lsregister";
fn run(program: &str, args: &[&str]) -> Option<String> {
let output = Command::new(program).args(args).output().ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
None
}
}
fn quiet(program: &str, args: &[&str]) {
let _ = Command::new(program).args(args).output();
}
fn home() -> PathBuf {
dirs::home_dir().unwrap_or_else(|| PathBuf::from("/Users/nobody"))
}
fn root(path: &str) -> PathBuf {
PathBuf::from(path)
}
impl Platform for MacOs {
fn id(&self) -> PlatformId {
PlatformId::MacOS
}
fn display_name(&self) -> String {
"macOS".to_string()
}
fn os_version(&self) -> String {
let product = run("sw_vers", &["-productVersion"]).unwrap_or_default();
let build = run("sw_vers", &["-buildVersion"]).unwrap_or_default();
if build.is_empty() {
format!("macOS {product}")
} else {
format!("macOS {product} ({build})")
}
}
fn hardware_model(&self) -> String {
let model = run("sysctl", &["-n", "hw.model"]).unwrap_or_default();
let brand = run("sysctl", &["-n", "machdep.cpu.brand_string"]).unwrap_or_default();
let chips = run("sysctl", &["-n", "hw.perflevel0.physicalcpu"])
.and_then(|p| {
run("sysctl", &["-n", "hw.perflevel1.physicalcpu"]).map(|e| format!("{p}P+{e}E"))
})
.unwrap_or_default();
let mut parts = vec![model.clone()];
if !brand.is_empty() && !model.contains(&brand) {
parts.push(brand);
}
if !chips.is_empty() {
parts.push(chips);
}
parts.join(" · ")
}
fn app_sources(&self) -> Vec<AppSource> {
let mut sources = vec![
AppSource {
dir: root("/Applications"),
label: "Applications".into(),
depth: 2,
system: false,
},
AppSource {
dir: home().join("Applications"),
label: "User Applications".into(),
depth: 2,
system: false,
},
AppSource {
dir: root("/System/Applications"),
label: "macOS Apps".into(),
depth: 2,
system: true,
},
AppSource {
dir: home().join("Library/Application Support/Setapp/Applications"),
label: "Setapp".into(),
depth: 1,
system: false,
},
AppSource {
dir: home().join("Library/Containers/io.playcover.PlayCover/Applications"),
label: "PlayCover".into(),
depth: 1,
system: false,
},
];
sources.retain(|s| s.dir.is_dir());
sources
}
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>> {
let running = self.running_executables();
let mut bundles: Vec<(PathBuf, String)> = Vec::new();
for source in self.app_sources() {
for path in discover_bundles(&source.dir, source.depth, cancel) {
bundles.push((path, source.label.clone()));
}
}
let mut apps: Vec<AppInfo> = bundles
.par_iter()
.filter_map(|(path, source)| app_from_bundle(path.clone(), source, &running, size_apps))
.collect();
apps.sort_by(|a, b| {
b.size
.cmp(&a.size)
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
});
// Flag bundle ids that appear more than once: shared preference files
// must survive when only one copy goes away.
let mut counts: std::collections::HashMap<String, usize> = Default::default();
for app in &apps {
if let Some(id) = app.bundle_id.as_deref() {
*counts.entry(id.to_lowercase()).or_insert(0) += 1;
}
}
for app in &mut apps {
if let Some(id) = app.bundle_id.as_deref() {
app.has_sibling_install = counts.get(&id.to_lowercase()).copied().unwrap_or(0) > 1;
}
}
Ok(apps)
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
let user = |rel: &str, naming: Naming| LeftoverRoot {
dir: home().join(rel),
naming,
deep: false,
category: Category::Leftovers,
};
let system = |abs: &str, naming: Naming| LeftoverRoot {
dir: root(abs),
naming,
deep: false,
category: Category::Leftovers,
};
let candidates = vec![
user("Library/Application Support", Naming::Either),
user("Library/Caches", Naming::Either),
user("Library/Preferences", Naming::BundleId),
user("Library/Preferences/ByHost", Naming::BundleId),
user("Library/Saved Application State", Naming::BundleId),
user("Library/HTTPStorages", Naming::BundleId),
user("Library/WebKit", Naming::BundleId),
user("Library/Cookies", Naming::BundleId),
user("Library/Containers", Naming::BundleId),
user("Library/Application Scripts", Naming::BundleId),
user("Library/Group Containers", Naming::GroupContainer),
user("Library/LaunchAgents", Naming::BundleId),
user("Library/Logs", Naming::Either),
user(
"Library/Application Support/CrashReporter",
Naming::BundleId,
),
user("Library/PreferencePanes", Naming::AppName),
user("Library/QuickLook", Naming::AppName),
user("Library/Services", Naming::AppName),
user("Library/ScriptingAdditions", Naming::AppName),
user("Library/Input Methods", Naming::AppName),
user("Library/Screen Savers", Naming::AppName),
user("Library/PreferenceBundles", Naming::AppName),
user("Library/Audio/Plug-Ins/AppleAudioMIDI", Naming::AppName),
user(".config", Naming::AppName),
user(".cache", Naming::AppName),
user(".local/share", Naming::AppName),
user(".local/state", Naming::AppName),
system("/Library/LaunchAgents", Naming::BundleId),
system("/Library/LaunchDaemons", Naming::BundleId),
system("/Library/Application Support", Naming::Either),
system("/Library/Caches", Naming::Either),
system("/Library/Logs", Naming::Either),
system("/Library/PreferencePanes", Naming::AppName),
system("/Library/ScriptingAdditions", Naming::AppName),
system("/Library/QuickLook", Naming::AppName),
system("/Library/Audio/Plug-Ins/HAL", Naming::AppName),
system("/Library/Screen Savers", Naming::AppName),
system("/Library/Internet Plug-Ins", Naming::AppName),
];
candidates.into_iter().filter(|c| c.dir.is_dir()).collect()
}
/// Unloading login items and clearing the Launch Services database entry
/// keeps macOS from resurrecting the app's icon or restarting its helpers.
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let mut report = LifecycleReport::default();
if app.running {
report
.warnings
.push(format!("{} is still running", app.name));
}
let Some(bundle_id) = app.bundle_id.as_deref() else {
return report;
};
let uid = unsafe { libc::getuid() };
let launch_roots = [
home().join("Library/LaunchAgents"),
PathBuf::from("/Library/LaunchAgents"),
PathBuf::from("/Library/LaunchDaemons"),
];
for dir in launch_roots {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned()) else {
continue;
};
if !name.ends_with(".plist")
|| !name.to_lowercase().contains(&bundle_id.to_lowercase())
{
continue;
}
let label = name.trim_end_matches(".plist");
let domain = if path.starts_with("/Library/LaunchDaemons") {
format!("system/{label}")
} else {
format!("gui/{uid}/{label}")
};
if Command::new("launchctl")
.args(["bootout", &domain])
.output()
.map(|o| o.status.success())
.unwrap_or(false)
{
report.stopped_services.push(path.display().to_string());
}
}
}
if Path::new(LSREGISTER).exists() {
quiet(LSREGISTER, &["-u", &app.path.to_string_lossy()]);
report
.notes
.push("removed the Launch Services registration".into());
}
report
}
fn finish_uninstall(&self, app: &AppInfo, _removed: &[PathBuf]) -> LifecycleReport {
let mut report = LifecycleReport::default();
// Homebrew-owned apps must be told they are gone, or `brew list` keeps
// a phantom entry forever.
if app.path.starts_with("/Applications") || app.path.starts_with("/opt/homebrew") {
if let Some(cask) = cask_for_bundle(&app.path) {
quiet("brew", &["uninstall", "--cask", "--force", &cask]);
report.notes.push(format!("told Homebrew about {cask}"));
}
}
// Receipts make the installer think the app is still present.
if let Some(bundle_id) = app.bundle_id.as_deref() {
if let Some(receipts) = run("pkgutil", &["--pkgs"]) {
for receipt in receipts.lines() {
if receipt
.to_lowercase()
.starts_with(&bundle_id.to_lowercase())
{
quiet("pkgutil", &["--forget", receipt]);
report.notes.push(format!("forgot receipt {receipt}"));
}
}
}
}
quiet("killall", &["-HUP", "cfprefsd"]);
report
}
fn volumes(&self) -> Result<Vec<Volume>> {
let volumes = crate::volumes::volumes_from_mounts(&crate::volumes::mount_entries());
if volumes.is_empty() {
return Err(SquidError::Other("could not read the mount table".into()));
}
Ok(volumes)
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
vec![
PathBuf::from("/System"),
PathBuf::from("/Library/Apple"),
home().join("Library/Keychains"),
home().join("Library/Mail"),
home().join("Library/Messages"),
home().join("Library/Photos"),
home().join("Library/Application Support/MobileSync"),
home().join("Library/Application Support/CloudDocs"),
home().join("Library/Containers/com.apple.Safari"),
]
}
fn running_executables(&self) -> Vec<String> {
run("ps", &["-axo", "comm="])
.map(|out| out.lines().map(|l| l.trim().to_string()).collect())
.unwrap_or_default()
}
fn reveal_trash(&self) {
quiet("open", &[&home().join(".Trash").to_string_lossy()]);
}
fn inspect_path(&self, path: &Path) -> Option<String> {
// Sandboxed containers are owned by containermanagerd; deleting the
// folder without the metadata file upsets the sandbox service.
if path
.join(".com.apple.containermanagerd.metadata.plist")
.exists()
{
return Some("sandboxed container (removing the whole folder is safe)".into());
}
if path.starts_with(home().join("Library/Containers")) {
return Some("inside a sandboxed container".into());
}
None
}
}
/// Ask Homebrew which cask installed this bundle, if any.
fn cask_for_bundle(app_path: &Path) -> Option<String> {
let out = run("brew", &["list", "--cask", "--versions"])
.or_else(|| run("/opt/homebrew/bin/brew", &["list", "--cask", "--versions"]))?;
let stem = app_path
.file_name()
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase())
.unwrap_or_default();
for line in out.lines() {
let name = line.split_whitespace().next()?.to_lowercase();
if name == stem || stem.contains(&name) || name.contains(&stem) {
return Some(line.split_whitespace().next()?.to_string());
}
}
None
}

View File

@ -0,0 +1,269 @@
//! Volume enumeration shared by the Unix adapters.
use squid_core::Bytes;
use squid_core::Volume;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct MountEntry {
pub mount_point: PathBuf,
pub device: String,
pub fstype: String,
}
/// Filesystems that never represent user-visible capacity.
const PSEUDO_FS: &[&str] = &[
"devfs",
"autofs",
"devtmpfs",
"proc",
"sysfs",
"cgroup",
"cgroup2",
"tmpfs",
"ramfs",
"overlay",
"squashfs",
"debugfs",
"tracefs",
"securityfs",
"pstore",
"binfmt_misc",
"configfs",
"fusectl",
"mqueue",
"hugetlbfs",
"rpc_pipefs",
"nsfs",
"autofs",
"msdos",
"anon:osd",
"SMB",
"afpfs",
"WebDAV",
"NFS",
];
/// `(total, available)` for a mount point.
pub fn statvfs_for(path: &Path) -> Option<(Bytes, Bytes)> {
use std::ffi::CString;
let c_path = CString::new(path.as_os_str().to_string_lossy().as_bytes()).ok()?;
let mut stat = unsafe { std::mem::zeroed::<libc::statvfs>() };
let rc = unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) };
if rc != 0 {
return None;
}
let frsize = stat.f_frsize as u64;
let block = if stat.f_blocks == 0 {
stat.f_bsize as u64
} else {
frsize
};
let total = stat.f_blocks as u64 * block;
let free = stat.f_bavail as u64 * block;
if total == 0 {
return None;
}
Some((Bytes(total), Bytes(free)))
}
/// Turn mount entries into volumes, skipping pseudo filesystems and deduping
/// firmlink/bind mounts that report identical capacity (macOS shows `/` and
/// `/System/Volumes/Data` as the same store).
pub fn volumes_from_mounts(mounts: &[MountEntry]) -> Vec<Volume> {
let root = PathBuf::from("/");
let mut seen_capacity: Vec<(u64, u64)> = Vec::new();
let mut out: Vec<Volume> = Vec::new();
let mut mounts: Vec<&MountEntry> = mounts.iter().collect();
mounts.sort_by_key(|m| (m.mount_point != root, m.mount_point.clone()));
for mount in mounts {
let fstype_lower = mount.fstype.to_lowercase();
if PSEUDO_FS.iter().any(|p| fstype_lower == *p) {
continue;
}
let text = mount.mount_point.to_string_lossy().into_owned();
// macOS firmlinks and snapshot mounts.
if text.starts_with("/System/Volumes/") && text != "/System/Volumes/Data" {
continue;
}
if text.starts_with("/System/Volumes/Data") && !out.is_empty() {
continue;
}
if let Some((total, free)) = statvfs_for(&mount.mount_point) {
let key = (total.as_u64(), free.as_u64());
if seen_capacity.contains(&key) {
continue;
}
seen_capacity.push(key);
let is_root = mount.mount_point == root;
let name = volume_name(&mount.mount_point, is_root);
let is_removable = text.starts_with("/Volumes/")
|| mount.device.contains("/media/")
|| mount.device.starts_with("/dev/mmcblk");
out.push(Volume {
name,
mount_point: mount.mount_point.clone(),
total,
free,
is_root,
is_removable,
filesystem: mount.fstype.clone(),
});
}
}
out
}
fn volume_name(mount: &Path, is_root: bool) -> String {
if is_root {
return mac_volume_name(mount).unwrap_or_else(|| "Macintosh HD".into());
}
mac_volume_name(mount).unwrap_or_else(|| {
mount
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| mount.display().to_string())
})
}
/// Finder-style volume name on macOS (`diskutil info -plist` is the only cheap
/// and reliable source); other systems fall back to the mount point name.
fn mac_volume_name(mount: &Path) -> Option<String> {
if !cfg!(target_os = "macos") {
return None;
}
let _ = mount;
None
}
#[cfg(target_os = "macos")]
pub fn mount_entries() -> Vec<MountEntry> {
let mut out = Vec::new();
// statfs(2): getmntinfo returns a statically allocated array we own until
// the next call. MNT_NOWAIT keeps it non-blocking.
const MNT_NOWAIT: libc::c_int = 2;
unsafe {
let mut statfs_ptr: *mut libc::statfs = std::ptr::null_mut();
let count = libc::getmntinfo(&mut statfs_ptr, MNT_NOWAIT);
if count <= 0 || statfs_ptr.is_null() {
return out;
}
for idx in 0..count as isize {
let stat = *statfs_ptr.offset(idx);
let mount_point = c_buffer_to_path(&stat.f_mntonname);
let device = c_buffer_to_string(&stat.f_mntfromname);
let fstype = c_buffer_to_string(&stat.f_fstypename);
if mount_point.as_os_str().is_empty() {
continue;
}
out.push(MountEntry {
mount_point,
device,
fstype,
});
}
}
out
}
#[cfg(target_os = "linux")]
pub fn mount_entries() -> Vec<MountEntry> {
let mut out = Vec::new();
let text = match std::fs::read_to_string("/proc/self/mounts") {
Ok(text) => text,
Err(_) => return out,
};
for line in text.lines() {
let mut fields = line.split_whitespace();
let (Some(device), Some(mount_point), Some(fstype)) =
(fields.next(), fields.next(), fields.next())
else {
continue;
};
let decoded = unescape_mount(mount_point);
out.push(MountEntry {
mount_point: PathBuf::from(decoded),
device: device.to_string(),
fstype: fstype.to_string(),
});
}
out
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub fn mount_entries() -> Vec<MountEntry> {
Vec::new()
}
#[cfg(target_os = "linux")]
fn unescape_mount(value: &str) -> String {
let mut out = String::with_capacity(value.len());
let mut chars = value.chars();
while let Some(ch) = chars.next() {
if ch == '\\' {
match (chars.next(), chars.next(), chars.next()) {
(Some('0'), Some('4'), Some('0')) => out.push(' '),
(Some('0'), Some('1'), Some('2')) => out.push('\t'),
(Some('0'), Some('1'), Some('1')) => out.push('\n'),
(Some('1'), Some('3'), Some('4')) => out.push('\\'),
(a, b, c) => {
for part in [a, b, c].into_iter().flatten() {
out.push(part);
}
}
}
} else {
out.push(ch);
}
}
out
}
fn c_buffer_to_string(buf: &[libc::c_char]) -> String {
let bytes: Vec<u8> = buf
.iter()
.map(|b| *b as u8)
.take_while(|b| *b != 0)
.collect();
String::from_utf8_lossy(&bytes).into_owned()
}
fn c_buffer_to_path(buf: &[libc::c_char]) -> PathBuf {
OsStrBytes(c_buffer_to_string(buf)).into_path()
}
struct OsStrBytes(String);
impl OsStrBytes {
fn into_path(self) -> PathBuf {
PathBuf::from(self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_root_volume() {
let volumes = volumes_from_mounts(&mount_entries());
assert!(
volumes.iter().any(|v| v.is_root),
"expected a root volume, got {volumes:?}"
);
for volume in &volumes {
assert!(volume.total.as_u64() > 0);
assert!(volume.free <= volume.total);
}
}
#[test]
fn pseudo_filesystems_are_skipped() {
let mounts = vec![MountEntry {
mount_point: PathBuf::from("/dev"),
device: "devfs".into(),
fstype: "devfs".into(),
}];
assert!(volumes_from_mounts(&mounts).is_empty());
}
}

View File

@ -0,0 +1,175 @@
//! Windows adapter (planned). The shape of the implementation is here so the
//! engines already work: apps come from the uninstall registry hive via
//! PowerShell, leftovers from the well known app-data folders.
use crate::{AppSource, LeftoverRoot, LifecycleReport, Naming, Platform, PlatformId};
use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Category, Result, Volume};
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Default)]
pub struct Windows;
fn ps(script: &str) -> Option<String> {
let out = Command::new("powershell")
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.output()
.ok()?;
if out.status.success() {
Some(String::from_utf8_lossy(&out.stdout).to_string())
} else {
None
}
}
/// `HKLM\...\Uninstall` + `HKCU\...\Uninstall` + the WOW64 view.
const HARVEST_SCRIPT: &str = r#"
$paths = @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
)
Get-ItemProperty $paths -ErrorAction SilentlyContinue |
Where-Object { $_.DisplayName -and -not $_.SystemComponent } |
ForEach-Object { '{0}|{1}|{2}|{3}' -f $_.DisplayName, $_.DisplayVersion, $_.InstallLocation, $_.UninstallString }
"#;
impl Platform for Windows {
fn id(&self) -> PlatformId {
PlatformId::Windows
}
fn display_name(&self) -> String {
"Windows".into()
}
fn os_version(&self) -> String {
ps("(Get-CimInstance Win32_OperatingSystem).Caption")
.map(|s| s.trim().to_string())
.unwrap_or_else(|| "Windows".into())
}
fn hardware_model(&self) -> String {
ps("(Get-CimInstance Win32_ComputerSystem).Model")
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
fn app_sources(&self) -> Vec<AppSource> {
["C:\\Program Files", "C:\\Program Files (x86)"]
.iter()
.map(|dir| AppSource {
dir: PathBuf::from(dir),
label: "Program Files".into(),
depth: 1,
system: true,
})
.filter(|s| s.dir.is_dir())
.collect()
}
fn list_apps(&self, cancel: &CancelToken, _size: bool) -> Result<Vec<AppInfo>> {
let mut apps = Vec::new();
let Some(text) = ps(HARVEST_SCRIPT) else {
return Ok(apps);
};
for line in text.lines() {
if cancel.is_cancelled() {
break;
}
let cols: Vec<&str> = line.split('|').collect();
let Some(name) = cols.first().map(|s| s.trim()).filter(|s| !s.is_empty()) else {
continue;
};
apps.push(AppInfo {
name: name.to_string(),
bundle_id: None,
path: cols
.get(2)
.map(|p| PathBuf::from(p.trim()))
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_default(),
version: cols
.get(1)
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty()),
size: Bytes::ZERO,
source: "Registry".into(),
running: false,
has_sibling_install: false,
publisher: None,
installed_ms: None,
});
}
Ok(apps)
}
fn leftover_roots(&self) -> Vec<LeftoverRoot> {
["APPDATA", "LOCALAPPDATA", "ProgramData"]
.iter()
.filter_map(|key| std::env::var_os(key).map(PathBuf::from))
.map(|dir| LeftoverRoot {
dir,
naming: Naming::AppName,
deep: false,
category: Category::Leftovers,
})
.filter(|c| c.dir.is_dir())
.collect()
}
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport {
let mut report = LifecycleReport::default();
report.warnings.push(format!(
"{} ships its own uninstaller; squid only removes leftover data on Windows",
app.name
));
report
}
fn finish_uninstall(&self, _app: &AppInfo, _removed: &[PathBuf]) -> LifecycleReport {
LifecycleReport::default()
}
fn volumes(&self) -> Result<Vec<Volume>> {
let mut out = Vec::new();
let Some(text) = ps(
"Get-PSDrive -PSProvider FileSystem | ForEach-Object { '{0}|{1}|{2}' -f $_.Root, $_.Used, $_.Free }",
) else {
return Ok(out);
};
for line in text.lines() {
let cols: Vec<&str> = line.split('|').collect();
let (Some(root), Some(used), Some(free)) = (cols.first(), cols.get(1), cols.get(2))
else {
continue;
};
let (Ok(used), Ok(free)) = (used.trim().parse::<u64>(), free.trim().parse::<u64>())
else {
continue;
};
let mount = Path::new(root.trim());
out.push(Volume {
name: root.trim().to_string(),
mount_point: mount.to_path_buf(),
total: Bytes(used + free),
free: Bytes(free),
is_root: root.trim().eq_ignore_ascii_case("C:\\"),
is_removable: false,
filesystem: "ntfs".into(),
});
}
Ok(out)
}
fn protected_prefixes(&self) -> Vec<PathBuf> {
["C:\\Windows", "C:\\Program Files"]
.iter()
.map(PathBuf::from)
.collect()
}
fn running_executables(&self) -> Vec<String> {
ps("Get-Process | ForEach-Object { $_.Path }")
.map(|text| text.lines().map(str::to_string).collect())
.unwrap_or_default()
}
fn inspect_path(&self, _path: &Path) -> Option<String> {
None
}
fn reveal_trash(&self) {
let _ = Command::new("explorer")
.arg("shell:RecycleBinFolder")
.spawn();
}
}

View File

@ -0,0 +1,15 @@
[package]
name = "squid-rules"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Data-driven cleanup rule sets shipped with squid"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
serde.workspace = true
toml.workspace = true
globset.workspace = true
serde_json.workspace = true

View File

@ -0,0 +1,475 @@
# squid cleanup rules — macOS
#
# Every rule declares the anchor it owns (the longest literal prefix of each
# pattern), so deletion is always validated against that anchor. Patterns use
# `~` for the home directory; `*` never crosses a path separator.
# ─────────────────────────────────────────────── system junk / temp files ──
[[rule]]
id = "user-cache"
category = "app-caches"
title = "User cache files"
patterns = ["~/Library/Caches/*"]
mode = "path"
os = ["macos"]
protect = ["com.apple.*", "*.lockfile", "Homebrew", "Homebrew/*", "CloudKit", "passd", "ss", "com.apple.containermanagerd.metadata.plist", "Fleet", "gnupd", "org.sparkle-project.Sparkle/*"]
note = "Regenerable. Apps recreate what they need on next launch."
[[rule]]
id = "dot-cache"
category = "app-caches"
title = "~/.cache"
patterns = ["~/.cache/*"]
mode = "path"
os = ["macos"]
protect = ["mozilla/*/cache2", "gitkraken", "gitlens"]
[[rule]]
id = "system-cache"
category = "system"
title = "System caches"
patterns = ["/Library/Caches/*"]
mode = "path"
os = ["macos"]
needs_admin = true
protect = ["com.apple.*", "Homebrew", "Homebrew/*"]
[[rule]]
id = "system-logs"
category = "logs"
title = "System logs"
patterns = ["/Library/Logs/*"]
mode = "path"
os = ["macos"]
needs_admin = true
min_age_days = 7
[[rule]]
id = "private-var-log"
category = "logs"
title = "macOS log files"
patterns = ["/private/var/log/*"]
mode = "files"
os = ["macos"]
needs_admin = true
min_age_days = 7
[[rule]]
id = "user-logs"
category = "logs"
title = "User logs"
patterns = ["~/Library/Logs/*"]
mode = "path"
os = ["macos"]
[[rule]]
id = "crash-reports"
category = "logs"
title = "Diagnostic & crash reports"
patterns = ["~/Library/Logs/DiagnosticReports/*", "/Library/Logs/DiagnosticReports/*", "~/Library/Application Support/CrashReporter/*"]
mode = "files"
os = ["macos"]
min_age_days = 2
[[rule]]
id = "install-logs"
category = "logs"
title = "Installer logs"
patterns = ["/private/var/log/install.log*", "/private/var/log/installassistant.log*"]
mode = "files"
os = ["macos"]
needs_admin = true
min_age_days = 14
# ────────────────────────────────────────────────────────── browsers ────────
[[rule]]
id = "chrome-cache"
category = "browsers"
title = "Google Chrome cache"
patterns = ["~/Library/Caches/Google/Chrome/Default/*/Cache/*", "~/Library/Caches/Google/Chrome/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Google Chrome"]
[[rule]]
id = "chromium-cache"
category = "browsers"
title = "Chromium cache"
patterns = ["~/Library/Caches/Chromium/Default/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Chromium"]
[[rule]]
id = "safari-cache"
category = "browsers"
title = "Safari cache"
patterns = ["~/Library/Caches/com.apple.Safari/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Safari"]
[[rule]]
id = "firefox-cache"
category = "browsers"
title = "Firefox cache"
patterns = ["~/Library/Caches/Firefox/Profiles/*/cache2"]
mode = "path"
os = ["macos"]
skip_if_running = ["firefox"]
[[rule]]
id = "edge-cache"
category = "browsers"
title = "Microsoft Edge cache"
patterns = ["~/Library/Caches/Microsoft Edge/*/Cache/*", "~/Library/Caches/Microsoft Edge/Default/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Microsoft Edge"]
[[rule]]
id = "arc-cache"
category = "browsers"
title = "Arc cache"
patterns = ["~/Library/Caches/company.thebrowser.Browser/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Arc"]
[[rule]]
id = "brave-cache"
category = "browsers"
title = "Brave cache"
patterns = ["~/Library/Caches/BraveSoftware/Brave-Browser/*/Cache/*"]
mode = "path"
os = ["macos"]
skip_if_running = ["Brave Browser"]
[[rule]]
id = "service-workers"
category = "browsers"
title = "Offline web content"
patterns = ["~/Library/WebKit/*/WebsiteData/ServiceWorkerData/*", "~/Library/Containers/com.apple.Safari/Data/Library/Caches/com.apple.Safari/WebKitReplay/*"]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Web apps may need to re-register their background workers."
# ───────────────────────────────────────────────────── chat & media apps ────
[[rule]]
id = "chat-caches"
category = "app-caches"
title = "Chat app caches"
patterns = [
"~/Library/Application Support/Slack/Cache/*",
"~/Library/Application Support/Slack/Code Cache/*",
"~/Library/Application Support/discord/Cache/*",
"~/Library/Caches/us.zoom.xos/*",
"~/Library/Caches/com.tencent.xinWeChat/*",
"~/Library/Caches/com.tencent.WeWorkMac/*",
"~/Library/Caches/com.tencent.qq/*",
"~/Library/Caches/com.tencent.meeting/*",
"~/Library/Caches/ru.keepcoder.Telegram/*",
"~/Library/Caches/net.whatsapp.WhatsApp/*",
"~/Library/Caches/com.microsoft.teams2/*",
"~/Library/Caches/com.skype.skype/*",
"~/Library/Caches/dd.work.exclusive4aliding/*",
"~/Library/Caches/com.feishu.*/*",
"~/Library/Application Support/iDingTalk/log/*",
]
mode = "path"
os = ["macos"]
note = "Media history re-downloads when you scroll back."
[[rule]]
id = "creative-caches"
category = "app-caches"
title = "Creative suite caches"
patterns = [
"~/Library/Caches/Adobe/*",
"~/Library/Caches/com.adobe.*/*",
"~/Library/Caches/com.figma.Desktop/*",
"~/Library/Application Support/Adobe/Common/Media Cache Files/*",
"~/Library/Caches/com.apple.finalcutpro/*",
"~/Library/Caches/com.blackmagic-design.DaVinciResolve/*",
"~/Library/Caches/com.adobe.PremierePro.*/*",
"~/Library/Caches/org.blenderfoundation.blender/*",
"~/Library/Caches/com.maxon.cinema4d/*",
"~/Library/Caches/com.bohemiancoding.sketch3/*",
"~/Library/Caches/com.sketch.app/*",
"~/Library/Caches/com.nwjs.*/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "ai-app-caches"
category = "app-caches"
title = "AI assistant caches"
patterns = [
"~/Library/Caches/com.openai.chat/*",
"~/Library/Caches/com.anthropic.claudefordesktop/*",
"~/Library/Logs/Claude/*",
"~/Library/Caches/com.lmstudio.lmstudio/*",
"~/Library/Caches/com.ollama.ollama/*",
]
mode = "path"
os = ["macos"]
# ───────────────────────────────────────────────────────────── developer ────
[[rule]]
id = "xcode-derived-data"
category = "developer"
title = "Xcode DerivedData"
patterns = ["~/Library/Developer/Xcode/DerivedData/*"]
mode = "path"
os = ["macos"]
note = "Rebuilt automatically the next time you build each project."
[[rule]]
id = "xcode-caches"
category = "developer"
title = "Xcode caches & archives of build products"
patterns = [
"~/Library/Caches/com.apple.dt.Xcode/*",
"~/Library/Developer/Xcode/Products/*",
"~/Library/Developer/Xcode/iOS Device Logs/*",
"~/Library/Developer/CoreSimulator/Caches/*",
"~/Library/Developer/Xcode/UserData/IB Support/Simulator Bundles/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "xcode-device-support"
category = "developer"
title = "Device support & watchOS runtimes"
patterns = [
"~/Library/Developer/Xcode/iOS DeviceSupport/*",
"~/Library/Developer/Xcode/watchOS DeviceSupport/*",
"~/Library/Developer/Xcode/tvOS DeviceSupport/*",
"~/Library/Developer/Xcode/visionOS DeviceSupport/*",
]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Xcode re-downloads symbol files when you attach an old device again."
[[rule]]
id = "core-simulator"
category = "developer"
title = "Shutdown iOS Simulators"
patterns = ["~/Library/Developer/CoreSimulator/Devices/*"]
mode = "path"
os = ["macos"]
select_by_default = false
needs_admin = false
note = "Only safe for simulators you deleted from Xcode; squid skips booted ones."
[[rule]]
id = "simulator-runtime"
category = "developer"
title = "Simulator runtimes"
patterns = ["~/Library/Developer/CoreSimulator/Volumes/*", "/Library/Developer/CoreSimulator/Volumes/*"]
mode = "path"
os = ["macos"]
select_by_default = false
needs_admin = true
note = "Re-downloadable from Xcode → Settings → Platforms."
[[rule]]
id = "editors"
category = "developer"
title = "Editor caches & logs"
patterns = [
"~/Library/Application Support/Code/Cache/*",
"~/Library/Application Support/Code/CachedData/*",
"~/Library/Application Support/Code/CachedExtensionVSIXs/*",
"~/Library/Application Support/Code/logs/*",
"~/Library/Application Support/Code/WebStorage/*/CacheStorage/*",
"~/Library/Application Support/Cursor/CachedExtensionVSIXs/*",
"~/Library/Application Support/Cursor/Cache/*",
"~/Library/Application Support/Cursor/logs/*",
"~/Library/Application Support/Zed/node/cache/*",
"~/Library/Application Support/Zed/Extensions/*",
"~/Library/Logs/Zed/*",
"~/Library/Caches/com.sublimetext.*/*",
"~/Library/Caches/Zed/*",
"~/Library/Caches/dev.zed.Zed/*",
"~/Library/Caches/com.todesktop.230313mzl4w4u92/*",
"~/Library/Caches/com.trae.app/*",
"~/Library/Caches/com.workbuddy/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "npm-cache"
category = "developer"
title = "npm / pnpm / yarn / bun caches"
patterns = [
"~/.npm/_cacache/*",
"~/.npm/_npx/*",
"~/.npm/_prebuilds/*",
"~/Library/pnpm/store/*",
"~/Library/pnpm/store/v*/*",
"~/Library/Caches/Yarn/*",
"~/Library/Caches/bun/*",
"~/.bun/install/cache/*",
]
mode = "path"
os = ["macos"]
note = "`npm install` re-downloads packages on demand."
[[rule]]
id = "cargo-cache"
category = "developer"
title = "Cargo registry & build caches"
patterns = ["~/.cargo/registry/cache/*", "~/.cargo/registry/index/*", "~/.cargo/registry/src/*", "~/.cargo/.package-cache"]
mode = "path"
os = ["macos"]
note = "Cargo re-fetches crates when needed. Target dirs live in `squid purge`."
[[rule]]
id = "python-caches"
category = "developer"
title = "Python package caches"
patterns = [
"~/Library/Caches/pip/*",
"~/.cache/pip/*",
"~/.cache/uv/*",
"~/Library/Caches/pypoetry/*",
"~/Library/Caches/poetry/*",
"~/Library/Caches/pdm/*",
"~/Library/Caches/conda/*",
"~/miniconda3/pkgs/cache/*",
"~/anaconda3/pkgs/cache/*",
"~/Library/Caches/pyinstaller/*",
]
mode = "path"
os = ["macos"]
[[rule]]
id = "go-cache"
category = "developer"
title = "Go build & module caches"
patterns = ["~/go/pkg/mod/cache/*", "~/Library/Caches/go-build/*", "~/Library/Caches/goimports/*"]
mode = "path"
os = ["macos"]
[[rule]]
id = "jvm-caches"
category = "developer"
title = "Gradle / Maven caches"
patterns = ["~/.gradle/caches/*/generated-gradle-jars/*", "~/.gradle/wrapper/dists/*", "~/.gradle/caches/transforms-*", "~/.gradle/daemon/*", "~/Library/Caches/gradle/*"]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Gradle re-downloads distributions; first build after cleaning is slower."
[[rule]]
id = "cocoapods-cache"
category = "developer"
title = "CocoaPods / SPM caches"
patterns = ["~/Library/Caches/CocoaPods/*", "~/.cocoapods/repos/*", "~/Library/Caches/org.swift.swiftpm/*", "~/Library/org.swift.swiftpm/repositories/*"]
mode = "path"
os = ["macos"]
[[rule]]
id = "brew-cache"
category = "developer"
title = "Homebrew downloads & bottles"
patterns = ["$(brew --prefix)/Library/Caches/Homebrew/*", "~/Library/Caches/Homebrew/*"]
mode = "path"
os = ["macos"]
note = "`brew install` re-downloads bottles as needed."
[[rule]]
id = "ci-tool-caches"
category = "developer"
title = "CLI & CI tool caches"
patterns = [
"~/Library/Caches/golangci-lint/*",
"~/Library/Caches/go-crunch-base/*",
"~/.cache/pre-commit/*",
"~/.cache/prettier/*",
"~/.cache/typescript/*",
"~/.cache/node-gyp/*",
"~/.npm/_quick/*",
"~/Library/Caches/Homebrew/api/*",
"~/.cache/chroma/*",
"~/.cache/visual-studio-code-browser-use/*",
"~/Library/Caches/ms-playwright/*",
"~/Library/Caches/cypress/*",
"~/Library/Caches/selenium/*",
"~/.cache/puppeteer/*",
"~/.cache/Cypress/*",
]
mode = "path"
os = ["macos"]
select_by_default = false
note = "Test tooling re-downloads browsers and lint data on the next run."
[[rule]]
id = "container-images"
category = "developer"
title = "Docker / OrbStack disk usage"
patterns = ["~/Library/Containers/com.docker.docker/Data/vms/*", "~/.orbstack/vm/Docker.raw"]
mode = "path"
os = ["macos"]
select_by_default = false
needs_admin = false
risky = true
skip_if_running = ["Docker Desktop", "com.docker.backend", "com.docker.build", "com.docker.virtualization", "OrbStack", "OrbStack Helper"]
note = "This is the whole VM disk, not a cache: stop Docker/OrbStack and run `docker system prune -a` first."
# ─────────────────────────────────────────────────────────── system junk ───
[[rule]]
id = "language-packs"
category = "languages"
title = "Speech & dictionary data"
patterns = ["/System/Library/Speech/*", "/Library/Fonts/*"]
mode = "path"
os = ["macos"]
select_by_default = false
risky = true
note = "Sealed on modern macOS: usually nothing to reclaim here."
[[rule]]
id = "installer-leftovers"
category = "system"
title = "Cached installers & updates"
patterns = ["/Library/Updates/*", "~/Library/Caches/com.apple.appstore/*", "/private/var/folders/*/*/0/com.apple.installeraudit*/*"]
mode = "path"
os = ["macos"]
needs_admin = true
[[rule]]
id = "disk-images"
category = "system"
title = "Mounted disk images"
patterns = ["/Volumes/*/"]
mode = "path"
os = ["macos"]
select_by_default = false
risky = true
note = "Eject instead of deleting; squid never removes a mounted volume."
[[rule]]
id = "old-downloads"
category = "system"
title = "Downloads older than 30 days"
patterns = ["~/Downloads/*.dmg", "~/Downloads/*.pkg", "~/Downloads/*.zip"]
mode = "files"
os = ["macos"]
min_age_days = 30
select_by_default = false
[[rule]]
id = "user-trash"
category = "trash"
title = "Trash"
patterns = ["~/.Trash/*"]
mode = "path"
os = ["macos"]
note = "Everything you already deleted but that still occupies the volume."

View File

@ -0,0 +1,784 @@
//! Data-driven cleanup rules.
//!
//! A rule is a declarative description of *where* junk lives; the engine turns
//! it into concrete [`squid_core::CleanupItem`]s. Keeping the knowledge in TOML
//! means new patterns can be added (or disabled by users) without recompiling,
//! and — importantly — it keeps the dangerous path list auditable in one place.
//!
//! Patterns are intentionally expressed as globs with a *literal anchor*: the
//! longest leading path without wildcards. That anchor becomes the safety
//! anchor passed to [`squid_core::SafetyPolicy`], so a bug in glob expansion
//! can never produce a deletion outside the directory the rule owns.
//!
//! Pattern syntax
//! --------------
//! * `~/…` and `$HOME/…` expand to the home directory.
//! * `${VAR}` / `$VAR` expand from the environment (unset ⇒ rule yields nothing).
//! * `$(brew --prefix)` resolves the Homebrew prefix once per run.
//! * `*`, `?` and `{a,b}` work per path component; `*` never crosses `/`.
//! * `**` matches any number of components (used sparingly).
use globset::{Glob, GlobBuilder, GlobMatcher, GlobSet, GlobSetBuilder};
use serde::Deserialize;
use squid_core::paths;
use squid_core::settings::Settings;
use squid_core::Category;
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::{Mutex, OnceLock};
/// What should happen to a matched path.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleMode {
/// Remove the matched entry itself (directory trees included).
#[default]
Path,
/// Remove the *children* of the matched directory but keep the directory —
/// required for lock files and folders apps expect to exist (Caches, Trash).
Contents,
/// Only remove regular files; directories are descended into.
Files,
}
impl RuleMode {
pub fn as_str(self) -> &'static str {
match self {
RuleMode::Path => "path",
RuleMode::Contents => "contents",
RuleMode::Files => "files",
}
}
}
fn default_true() -> bool {
true
}
fn category_from_str<'de, D>(deserializer: D) -> Result<Category, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error as _;
let raw = String::deserialize(deserializer)?;
Category::parse(&raw).ok_or_else(|| D::Error::custom(format!("unknown category `{raw}`")))
}
/// One cleanup rule as written in `rules/*.toml`.
#[derive(Clone, Debug, Deserialize)]
pub struct Rule {
pub id: String,
#[serde(deserialize_with = "category_from_str")]
pub category: Category,
#[serde(default)]
pub title: String,
pub patterns: Vec<String>,
#[serde(default)]
pub mode: RuleMode,
/// Platforms this rule applies to (`macos`, `linux`, `windows`).
/// Empty means "every platform".
#[serde(default)]
pub os: Vec<String>,
/// Globs (matched against the absolute path *and* the path relative to the
/// pattern anchor) that must never be deleted.
#[serde(default)]
pub protect: Vec<String>,
/// Skip entries modified more recently than this many days ago.
#[serde(default)]
pub min_age_days: u64,
#[serde(default = "default_true")]
pub select_by_default: bool,
/// Rule touches paths the current user cannot write: surface it, but keep
/// it unselected unless the user opted in.
#[serde(default)]
pub needs_admin: bool,
/// Process names that make this rule unsafe right now.
#[serde(default)]
pub skip_if_running: Vec<String>,
/// Show a warning marker in the UI.
#[serde(default)]
pub risky: bool,
#[serde(default)]
pub note: Option<String>,
}
impl Rule {
pub fn display_title(&self) -> &str {
if self.title.is_empty() {
&self.id
} else {
&self.title
}
}
pub fn applies_to_current_os(&self) -> bool {
if self.os.is_empty() {
return true;
}
self.os.iter().any(|os| os == current_os_tag())
}
pub fn min_age(&self) -> Option<std::time::Duration> {
if self.min_age_days == 0 {
None
} else {
Some(std::time::Duration::from_secs(self.min_age_days * 86_400))
}
}
}
fn current_os_tag() -> &'static str {
match squid_platform::PlatformId::current() {
squid_platform::PlatformId::MacOS => "macos",
squid_platform::PlatformId::Linux => "linux",
squid_platform::PlatformId::Windows => "windows",
squid_platform::PlatformId::Unknown => "unknown",
}
}
#[derive(Deserialize)]
struct RuleFile {
#[serde(default)]
rule: Vec<Rule>,
}
/// The rules that apply to this machine, in display order.
#[derive(Clone, Debug, Default)]
pub struct RuleSet {
rules: Vec<Rule>,
errors: Vec<String>,
}
impl RuleSet {
/// Built-in rules for the host OS plus anything the user dropped into
/// `<config dir>/rules/*.toml`, filtered by `settings.disabled_rules`.
pub fn load(settings: &Settings) -> RuleSet {
let mut set = RuleSet::builtins();
set.merge_user_rules();
set.rules
.retain(|rule| rule.applies_to_current_os() && settings.rule_enabled(&rule.id));
set.rules
.sort_by(|a, b| a.category.cmp(&b.category).then_with(|| a.id.cmp(&b.id)));
set
}
/// Everything shipped for the current platform, unfiltered.
pub fn builtins() -> RuleSet {
let mut set = RuleSet::default();
if cfg!(target_os = "macos") {
set.parse_str(EMBEDDED_MACOS, "builtin:macos.toml");
}
set
}
fn merge_user_rules(&mut self) {
let dir = Settings::config_dir().join("rules");
let Ok(entries) = std::fs::read_dir(&dir) else {
return;
};
let mut files: Vec<PathBuf> = entries
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().map(|ext| ext == "toml").unwrap_or(false))
.collect();
files.sort();
for file in files {
let Ok(text) = std::fs::read_to_string(&file) else {
self.errors
.push(format!("{}: could not read", file.display()));
continue;
};
let label = file.display().to_string();
self.parse_str(&text, &label);
}
}
fn parse_str(&mut self, text: &str, label: &str) {
match toml::from_str::<RuleFile>(text) {
Ok(file) => self.rules.extend(file.rule),
Err(err) => self.errors.push(format!("{label}: {err}")),
}
}
pub fn rules(&self) -> &[Rule] {
&self.rules
}
pub fn errors(&self) -> &[String] {
&self.errors
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
pub fn len(&self) -> usize {
self.rules.len()
}
pub fn by_category(&self, category: Category) -> Vec<&Rule> {
self.rules
.iter()
.filter(|rule| rule.category == category)
.collect()
}
pub fn categories(&self) -> Vec<Category> {
let mut seen: Vec<Category> = Vec::new();
for rule in &self.rules {
if !seen.contains(&rule.category) {
seen.push(rule.category);
}
}
seen.sort();
seen
}
pub fn get(&self, id: &str) -> Option<&Rule> {
self.rules.iter().find(|rule| rule.id == id)
}
}
// ─────────────────────────────── expansion ────────────────────────────────
/// One path a rule matched, plus the anchor that authorises deleting it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Match {
pub path: PathBuf,
/// Literal directory the pattern lives under; deletions must stay inside.
pub anchor: PathBuf,
}
/// The only command substitutions rules may use. Deliberately a fixed list:
/// rules are data, and data must not be able to run arbitrary programs.
fn run_substitution(command: &str) -> Option<String> {
static CACHE: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
if let Ok(guard) = cache.lock() {
if let Some(known) = guard.get(command) {
return known.clone();
}
}
let allowed = matches!(
command,
"brew --prefix" | "brew --repository" | "getconf DARWIN_USER_CACHE_DIR"
);
let value = if allowed {
let mut parts = command.split_whitespace();
let program = parts.next()?;
std::process::Command::new(program)
.args(parts)
.output()
.ok()
.filter(|out| out.status.success())
.map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
.filter(|out| !out.is_empty() && out.starts_with('/'))
} else {
None
};
if let Ok(mut guard) = cache.lock() {
guard.insert(command.to_string(), value.clone());
}
value
}
/// Resolve `$HOME`, environment variables and the one command substitution we
/// allow. Returns `None` when a required variable or tool is missing.
pub fn resolve_variables(pattern: &str) -> Option<String> {
let mut text = pattern.trim().to_string();
if text.is_empty() {
return None;
}
while let Some(start) = text.find("$(") {
let rest = &text[start + 2..];
let end = rest.find(')')?;
let command = rest[..end].trim().to_string();
let replacement = run_substitution(&command)?;
text = format!("{}{}{}", &text[..start], replacement, &rest[end + 1..]);
}
if text == "~" || text.starts_with("~/") || text.starts_with("~\\") {
text = text.replacen('~', &paths::home_dir().to_string_lossy(), 1);
}
if let Some(pos) = text.find("${") {
let rest = &text[pos + 2..];
let end = rest.find('}')?;
let name = rest[..end].to_string();
let value = env_value(&name)?;
text = format!("{}{}{}", &text[..pos], value, &rest[end + 1..]);
}
if text.starts_with('$') {
let head = text
.find('/')
.map(|idx| text[1..idx].to_string())
.unwrap_or_else(|| text[1..].to_string());
let value = env_value(&head)?;
text = format!("{}{}", value, &text[1 + head.len()..]);
}
Some(text)
}
fn env_value(name: &str) -> Option<String> {
if name == "HOME" {
return Some(paths::home_dir().to_string_lossy().into_owned());
}
std::env::var(name).ok().filter(|value| !value.is_empty())
}
fn has_glob(component: &str) -> bool {
component
.chars()
.any(|c| matches!(c, '*' | '?' | '[' | '{'))
}
fn glob_matcher(component: &str) -> Option<GlobMatcher> {
GlobBuilder::new(component)
.literal_separator(true)
.backslash_escape(true)
.build()
.ok()
.map(|glob| glob.compile_matcher())
}
/// The literal directory in front of the first wildcard component.
///
/// `~/Library/Caches/Google/*` → `~/Library/Caches/Google`; a pattern without
/// wildcards anchors on its parent so `SafetyPolicy::check` still sees depth ≥ 1.
pub fn anchor_for(pattern: &str) -> Option<PathBuf> {
let resolved = resolve_variables(pattern)?;
let resolved = resolved.trim_end_matches('/');
if resolved.is_empty() {
return None;
}
let path = Path::new(resolved);
let mut anchor = PathBuf::new();
let mut saw_glob = false;
for component in path.components() {
let text = match component {
Component::RootDir => {
anchor.push("/");
continue;
}
Component::CurDir => continue,
Component::Normal(text) => text.to_string_lossy().into_owned(),
Component::ParentDir | Component::Prefix(_) => return None,
};
if has_glob(&text) {
saw_glob = true;
break;
}
anchor.push(text);
}
if !saw_glob {
anchor = path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| PathBuf::from("/"));
}
if anchor.as_os_str().is_empty() {
anchor = PathBuf::from("/");
}
Some(anchor)
}
/// Expand one glob pattern into the existing paths it matches.
///
/// Expansion walks the filesystem component by component, so a wildcard can
/// only ever enumerate directories that really exist below the anchor.
pub fn expand_pattern(pattern: &str) -> Vec<Match> {
let Some(anchor) = anchor_for(pattern) else {
return Vec::new();
};
let Some(resolved) = resolve_variables(pattern) else {
return Vec::new();
};
let resolved = resolved.trim_end_matches('/');
let components: Vec<String> = Path::new(resolved)
.components()
.filter_map(|c| match c {
Component::Normal(text) => Some(text.to_string_lossy().into_owned()),
Component::RootDir => Some("/".to_string()),
_ => None,
})
.collect();
let mut frontier: Vec<PathBuf> = if anchor.exists() {
vec![anchor.clone()]
} else {
return Vec::new();
};
let Some(glob_at) = components.iter().position(|component| has_glob(component)) else {
// A wildcard-free pattern names exactly one path. `anchor_for` handed us
// its *parent* so the safety layer has a directory to vouch for, and the
// frontier would still hold that parent — returning it here would turn
// "~/.cargo/.package-cache" into "delete all of ~/.cargo".
let literal = PathBuf::from(resolved);
return match literal.symlink_metadata() {
Ok(_) => vec![Match {
path: literal,
anchor,
}],
Err(_) => Vec::new(),
};
};
let mut cursor = glob_at;
while cursor < components.len() {
let component = components[cursor].as_str();
if component == "**" {
let mut next = Vec::new();
for dir in &frontier {
next.extend(descendants(dir, 6));
}
next.sort();
next.dedup();
frontier = next;
cursor += 1;
if frontier.is_empty() {
break;
}
continue;
}
let Some(matcher) = glob_matcher(component) else {
return Vec::new();
};
let mut next = Vec::new();
for dir in &frontier {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if !matcher.is_match(&name) {
continue;
}
let path = dir.join(&name);
let is_last = cursor + 1 == components.len();
if is_last || path.is_dir() {
next.push(path);
}
}
}
next.sort();
next.dedup();
frontier = next;
cursor += 1;
if frontier.is_empty() {
break;
}
}
frontier.retain(|path| path.symlink_metadata().is_ok());
frontier
.into_iter()
.map(|path| Match {
path,
anchor: anchor.clone(),
})
.collect()
}
fn descendants(dir: &Path, max_depth: usize) -> Vec<PathBuf> {
let mut out = Vec::new();
if max_depth == 0 {
return out;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return out;
};
for entry in entries.flatten() {
let path = entry.path();
let is_dir = entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false);
out.push(path.clone());
if is_dir {
out.extend(descendants(&path, max_depth - 1));
}
}
out
}
/// Compiled `protect` list of one rule.
#[derive(Clone, Debug, Default)]
pub struct Protector {
absolute: Vec<GlobMatcher>,
relative: Vec<GlobMatcher>,
}
impl Protector {
pub fn new(rule: &Rule) -> Protector {
let mut absolute = Vec::new();
let mut relative = Vec::new();
for raw in &rule.protect {
let resolved = resolve_variables(raw).unwrap_or_else(|| raw.clone());
if resolved.starts_with('/') {
if let Some(matcher) = glob_matcher(&resolved) {
absolute.push(matcher);
continue;
}
}
match Glob::new(&format!("**/{resolved}")) {
Ok(glob) => relative.push(glob.compile_matcher()),
Err(_) => {
if let Some(matcher) = glob_matcher(raw) {
relative.push(matcher);
}
}
}
}
Protector { absolute, relative }
}
pub fn is_empty(&self) -> bool {
self.absolute.is_empty() && self.relative.is_empty()
}
/// `true` when the path (or any ancestor below the anchor) is protected, so
/// protecting `Homebrew` also protects everything inside it.
pub fn is_protected(&self, path: &Path, anchor: &Path) -> bool {
if self.absolute.is_empty() && self.relative.is_empty() {
return false;
}
let text = path.to_string_lossy();
if self.absolute.iter().any(|m| m.is_match(&*text)) {
return true;
}
for ancestor in path.ancestors() {
let Ok(rel) = ancestor.strip_prefix(anchor) else {
break;
};
if rel.as_os_str().is_empty() {
continue;
}
let rel = rel.to_string_lossy().into_owned();
if self.relative.iter().any(|m| m.is_match(&*rel)) {
return true;
}
}
false
}
}
/// A rule bundled with its compiled matchers — what the engine actually uses.
#[derive(Clone, Debug)]
pub struct PreparedRule {
pub rule: Rule,
protector: Protector,
}
impl PreparedRule {
pub fn new(rule: Rule) -> PreparedRule {
let protector = Protector::new(&rule);
PreparedRule { rule, protector }
}
pub fn is_protected(&self, path: &Path, anchor: &Path) -> bool {
self.protector.is_protected(path, anchor)
}
/// Every existing path this rule claims, minus protected ones.
pub fn matches(&self) -> Vec<Match> {
let mut out: Vec<Match> = Vec::new();
for pattern in &self.rule.patterns {
for matched in expand_pattern(pattern) {
if self.is_protected(&matched.path, &matched.anchor) {
continue;
}
if !out.contains(&matched) {
out.push(matched);
}
}
}
out
}
}
pub fn prepare_all(set: &RuleSet) -> Vec<PreparedRule> {
set.rules().iter().cloned().map(PreparedRule::new).collect()
}
/// Utility kept for tests and `squid rules --explain`.
pub fn globset_of(patterns: &[String]) -> Option<GlobSet> {
let mut builder = GlobSetBuilder::new();
let mut any = false;
for pattern in patterns {
if let Ok(glob) = Glob::new(pattern) {
builder.add(glob);
any = true;
}
}
if !any {
return None;
}
builder.build().ok()
}
const EMBEDDED_MACOS: &str = include_str!("../rules/macos.toml");
#[cfg(test)]
mod tests {
#[test]
fn wildcard_free_patterns_match_the_file_not_the_parent() {
let root = std::env::temp_dir().join(format!(
"squid-literal-{}",
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(&root).unwrap();
let file = root.join(".package-cache");
std::fs::write(&file, b"x").unwrap();
let matches = expand_pattern(file.to_str().unwrap());
assert_eq!(matches.len(), 1, "the file itself must be the match");
assert_eq!(matches[0].path, file);
// …and the anchor stays the directory the safety layer vouches for.
assert_eq!(matches[0].anchor, root);
let missing = root.join("does-not-exist");
assert!(expand_pattern(missing.to_str().unwrap()).is_empty());
let _ = std::fs::remove_dir_all(&root);
}
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!("squid-rules-{name}"));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
root
}
#[test]
fn embedded_rules_parse() {
let set = RuleSet::builtins();
assert!(
set.errors().is_empty(),
"builtin rules failed: {:?}",
set.errors()
);
assert!(
set.len() > 20,
"expected dozens of rules, got {}",
set.len()
);
let mut ids: Vec<&str> = set.rules().iter().map(|r| r.id.as_str()).collect();
ids.sort();
let count = ids.len();
ids.dedup();
assert_eq!(ids.len(), count, "duplicate rule ids");
}
#[test]
fn every_rule_has_a_safe_anchor() {
for rule in RuleSet::builtins().rules() {
for pattern in &rule.patterns {
let anchor = anchor_for(pattern)
.unwrap_or_else(|| panic!("{}: no anchor for {pattern}", rule.id));
assert!(
anchor.is_absolute(),
"{}: anchor {anchor:?} is not absolute",
rule.id
);
assert_ne!(anchor, PathBuf::from("/"), "{}: anchors at /", rule.id);
}
}
}
#[test]
fn anchors_handle_slashes_and_literal_paths() {
assert_eq!(
anchor_for("/Volumes/*/").unwrap(),
PathBuf::from("/Volumes")
);
assert_eq!(
anchor_for("~/Library/Caches/*").unwrap(),
paths::home_dir().join("Library/Caches")
);
assert_eq!(
anchor_for("~/.cargo/.package-cache").unwrap(),
paths::home_dir().join(".cargo")
);
assert_eq!(
anchor_for("$HOME/go/pkg/mod/cache/*").unwrap(),
paths::home_dir().join("go/pkg/mod/cache")
);
}
#[test]
fn wildcards_do_not_cross_separators() {
let root = temp_dir("wildcards");
std::fs::create_dir_all(root.join("s1/deep")).unwrap();
std::fs::create_dir_all(root.join("other")).unwrap();
let matches = expand_pattern(&format!("{}/s*/", root.display()));
assert_eq!(matches.len(), 1, "matches: {matches:?}");
assert_eq!(matches[0].path, root.join("s1"));
assert_eq!(matches[0].anchor, root);
assert_eq!(expand_pattern(&format!("{}/s*/*", root.display())).len(), 1);
assert_eq!(expand_pattern(&format!("{}/s*", root.display())).len(), 1);
assert!(expand_pattern(&format!("{}/nope/*", root.display())).is_empty());
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn suffix_globs_match_files() {
let root = temp_dir("suffix");
std::fs::write(root.join("a.dmg"), b"x").unwrap();
std::fs::write(root.join("b.pkg"), b"x").unwrap();
std::fs::write(root.join("c.txt"), b"x").unwrap();
let images = expand_pattern(&format!("{}/*.dmg", root.display()));
assert_eq!(images.len(), 1);
assert_eq!(images[0].path, root.join("a.dmg"));
let all = expand_pattern(&format!("{}/*", root.display()));
assert_eq!(all.len(), 3);
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn protect_blocks_subtrees() {
let rule = Rule {
id: "t".into(),
category: Category::AppCaches,
title: String::new(),
patterns: vec!["~/Library/Caches/*".into()],
mode: RuleMode::Path,
os: vec![],
protect: vec!["Homebrew".into(), "com.apple.*".into()],
min_age_days: 0,
select_by_default: true,
needs_admin: false,
skip_if_running: vec![],
risky: false,
note: None,
};
let prepared = PreparedRule::new(rule);
let anchor = paths::home_dir().join("Library/Caches");
assert!(prepared.is_protected(&anchor.join("Homebrew"), &anchor));
assert!(prepared.is_protected(&anchor.join("Homebrew/Downloads/x"), &anchor));
assert!(prepared.is_protected(&anchor.join("com.apple.iconservices"), &anchor));
assert!(!prepared.is_protected(&anchor.join("Slack/cache"), &anchor));
}
#[test]
fn missing_tool_disarms_pattern() {
// `brew` may or may not exist; either way expansion must not panic and
// must never yield a truncated path such as `/Library/Caches/…`.
for matched in expand_pattern("$(brew --prefix)/Library/Caches/Homebrew/*") {
assert!(matched
.anchor
.to_string_lossy()
.ends_with("/Library/Caches/Homebrew"));
}
assert!(expand_pattern("$(definitely-not-a-real-binary --prefix)/x/*").is_empty());
assert!(anchor_for("$(definitely-not-a-real-binary --prefix)/x/*").is_none());
}
}

View File

@ -0,0 +1,15 @@
[package]
name = "squid-stats"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Live system metrics for squid (iStat Menus style)"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
serde.workspace = true
sysinfo.workspace = true
libc.workspace = true
chrono.workspace = true

View File

@ -0,0 +1,242 @@
//! Battery state without pulling in IOKit bindings.
//!
//! macOS: `pmset -g batt` (plus `ioreg` once per refresh for wear/cycles).
//! Linux: `/sys/class/power_supply/BAT*/`. Windows: the caller gets `None`
//! until the Win32 power status API is wired up — the TUI simply omits the
//! battery card.
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Battery {
pub percent: u8,
pub charging: bool,
pub on_ac: bool,
pub present: bool,
/// Minutes until fully charged, when the OS is willing to estimate it.
pub minutes_to_full: Option<u64>,
/// Minutes of runtime left on battery.
pub minutes_to_empty: Option<u64>,
/// Maximum capacity versus design capacity (iStat's "Health").
pub health_percent: Option<u8>,
pub cycle_count: Option<u32>,
pub temperature_c: Option<f32>,
}
impl Battery {
pub fn current() -> Option<Battery> {
#[cfg(target_os = "macos")]
{
macos_battery()
}
#[cfg(target_os = "linux")]
{
return linux_battery();
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
{
None
}
}
pub fn label(&self) -> String {
if self.charging {
format!("{}% charging", self.percent)
} else if self.on_ac {
format!("{}% charged", self.percent)
} else {
format!("{}% on battery", self.percent)
}
}
}
#[cfg(target_os = "macos")]
fn macos_battery() -> Option<Battery> {
let output = std::process::Command::new("/usr/bin/pmset")
.arg("-g")
.arg("batt")
.output()
.ok()
.filter(|output| output.status.success())?;
let text = String::from_utf8_lossy(&output.stdout);
let mut battery = parse_pmset(&text)?;
if let Some((health, cycles, temp)) = battery_details() {
battery.health_percent = health;
battery.cycle_count = cycles;
battery.temperature_c = temp;
}
Some(battery)
}
/// Example input:
///
/// ```text
/// Now drawing from 'Battery Power'
/// -InternalBattery-0 (id=6226083) 87%; discharging; 4:12 remaining present: true
/// ```
#[cfg(target_os = "macos")]
pub fn parse_pmset(text: &str) -> Option<Battery> {
let mut battery = Battery {
present: false,
percent: 0,
charging: false,
on_ac: false,
minutes_to_full: None,
minutes_to_empty: None,
health_percent: None,
cycle_count: None,
temperature_c: None,
};
let source_line = text
.lines()
.find(|line| line.trim_start().starts_with("Now drawing from"))?;
battery.on_ac = source_line.contains("AC Power");
let detail = text
.lines()
.find(|line| line.contains("Battery-") || line.contains('%'))
.filter(|line| !line.starts_with("Now drawing"))?;
if !detail.contains("Battery-") {
// Desktops report ` -AC Power 100%; charged; 0:00 remaining present: true`
// and have no battery to show.
return None;
}
battery.present = true;
let body = detail.split('\t').next_back().unwrap_or(detail).trim();
let mut parts = body.split(';');
let first = parts.next()?.trim();
battery.percent = first.split('%').next()?.trim().parse().unwrap_or(0);
let state = parts.next().unwrap_or("").trim().to_lowercase();
battery.charging = state.contains("charging") && !state.contains("discharging");
if state.contains("discharging") && !battery.on_ac {
battery.on_ac = false;
}
let remaining = parts.next().unwrap_or("").trim();
if let Some(minutes) = parse_hhmm(remaining.split_whitespace().next().unwrap_or("")) {
if battery.charging {
battery.minutes_to_full = Some(minutes);
} else if state.contains("discharging") {
battery.minutes_to_empty = Some(minutes);
}
}
Some(battery)
}
#[cfg(target_os = "macos")]
fn battery_details() -> Option<(Option<u8>, Option<u32>, Option<f32>)> {
let output = std::process::Command::new("/usr/sbin/ioreg")
.args(["-rn", "AppleSmartBattery"])
.output()
.ok()
.filter(|output| output.status.success())?;
let text = String::from_utf8_lossy(&output.stdout);
let design = find_number(&text, "DesignCapacity");
let max = find_number(&text, "MaxCapacity");
let health = match (design, max) {
(Some(design), Some(max)) if design > 0 => {
Some(((max as f64 / design as f64) * 100.0).round() as u8)
}
_ => None,
};
let cycles = find_number(&text, "CycleCount").map(|value| value as u32);
let temp = find_number(&text, "Temperature").map(|tenths| tenths as f32 / 100.0);
Some((health, cycles, temp))
}
#[cfg(target_os = "macos")]
fn find_number(text: &str, key: &str) -> Option<u64> {
let (_, after) = text.split_once(&format!("\"{key}\""))?;
let after = after.split('=').nth(1)?.trim_start();
let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
digits.parse().ok()
}
#[cfg(target_os = "linux")]
fn linux_battery() -> Option<Battery> {
let root = std::path::Path::new("/sys/class/power_supply");
let entries = std::fs::read_dir(root).ok()?;
let dir = entries.flatten().map(|entry| entry.path()).find(|path| {
path.file_name()
.map(|name| name.to_string_lossy().starts_with("BAT"))
.unwrap_or(false)
})?;
let read = |name: &str| {
std::fs::read_to_string(dir.join(name))
.ok()
.map(|value| value.trim().to_string())
};
let percent: u8 = read("capacity")?.parse().ok()?;
let status = read("status").unwrap_or_default().to_lowercase();
let charging = status.contains("charging");
let full = || {
let now = read("energy_now")?.parse::<f64>().ok()?;
let rate = read("power_now")?.parse::<f64>().ok()?;
if rate <= 0.0 {
return None;
}
Some((now / rate * 60.0) as u64)
};
Some(Battery {
percent,
charging,
on_ac: status.contains("full") || status.contains("not charging"),
present: true,
minutes_to_full: if charging { full() } else { None },
minutes_to_empty: if !charging && status.contains("discharging") {
full()
} else {
None
},
health_percent: None,
cycle_count: read("cycle_count")?.parse().ok(),
temperature_c: None,
})
}
fn parse_hhmm(text: &str) -> Option<u64> {
let (hours, minutes) = text.split_once(':')?;
let hours: u64 = hours.parse().ok()?;
let minutes: u64 = minutes.parse().ok()?;
Some(hours * 60 + minutes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(target_os = "macos")]
fn parses_pmset_output() {
let text = "Now drawing from 'Battery Power'\n -InternalBattery-0 (id=6226083)\t87%; discharging; 4:12 remaining present: true\n";
let battery = parse_pmset(text).expect("battery");
assert_eq!(battery.percent, 87);
assert!(!battery.charging);
assert!(!battery.on_ac);
assert_eq!(battery.minutes_to_empty, Some(252));
let charging = "Now drawing from 'AC Power'\n -InternalBattery-0 (id=6226083)\t42%; charging; (no estimate) present: true\n";
let battery = parse_pmset(charging).expect("charging");
assert!(battery.charging);
assert!(battery.on_ac);
assert_eq!(battery.minutes_to_full, None);
}
#[test]
#[cfg(target_os = "macos")]
fn desktops_report_no_battery() {
let text = "Now drawing from 'AC Power'\n -AC Power 100%; charged; 0:00 remaining present: true\n";
assert!(parse_pmset(text).is_none());
}
#[test]
fn hhmm_parsing() {
assert_eq!(parse_hhmm("4:12"), Some(252));
assert_eq!(parse_hhmm("0:00"), Some(0));
assert_eq!(parse_hhmm("no"), None);
}
#[test]
fn current_matches_platform() {
// Must never panic; laptops return Some, desktops None.
let _ = Battery::current();
}
}

View File

@ -0,0 +1,788 @@
//! Live system metrics — the iStat Menus half of squid.
//!
//! [`Sampler`] owns the stateful sysinfo handles. Call [`Sampler::refresh`]
//! once per UI tick (~1 Hz): every rate in a [`SystemSnapshot`] is derived from
//! the delta to the previous sample, so the *first* sample reports zero rates
//! and every later one is honest.
use serde::{Deserialize, Serialize};
use squid_core::{Bytes, Volume};
use std::collections::VecDeque;
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use sysinfo::{
DiskUsage, Disks, Networks, ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System,
};
mod battery;
pub use battery::Battery;
/// Everything one tick knows about the machine.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct SystemSnapshot {
pub taken_at_ms: u64,
pub cpu: CpuStats,
pub memory: MemoryStats,
pub network: NetRate,
pub disk: DiskRate,
pub uptime_secs: u64,
pub processes: usize,
pub top_processes: Vec<ProcessSample>,
pub volumes: Vec<Volume>,
pub battery: Option<Battery>,
pub host: HostInfo,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct CpuStats {
/// 0.0–100.0 across all cores.
pub total: f32,
pub per_core: Vec<f32>,
pub load: [f32; 3],
pub physical_cores: usize,
pub logical_cores: usize,
pub brand: String,
pub base_frequency_ghz: f64,
}
impl CpuStats {
pub fn busy_cores(&self) -> f32 {
self.total / 100.0 * self.logical_cores.max(1) as f32
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct MemoryStats {
pub total: Bytes,
pub used: Bytes,
pub available: Bytes,
pub swap_total: Bytes,
pub swap_used: Bytes,
/// macOS keeps wired/compressed pages out of `used`; expose them when known.
pub compressed: Option<Bytes>,
pub wired: Option<Bytes>,
}
impl MemoryStats {
pub fn percent_used(&self) -> u8 {
if self.total.is_zero() {
0
} else {
self.used.percent_of(self.total)
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct NetRate {
pub rx_per_sec: Bytes,
pub tx_per_sec: Bytes,
pub rx_total: Bytes,
pub tx_total: Bytes,
pub interfaces: usize,
pub primary: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DiskRate {
pub read_per_sec: Bytes,
pub write_per_sec: Bytes,
/// 0.0–100.0, busiest physical disk.
pub activity: f32,
pub disks: usize,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProcessSample {
pub pid: u32,
pub name: String,
pub cpu: f32,
pub memory: Bytes,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct HostInfo {
pub os_name: String,
pub os_version: String,
pub hardware: String,
pub hostname: String,
pub user: String,
pub arch: String,
}
impl HostInfo {
pub fn gather() -> HostInfo {
let platform = squid_platform::current();
HostInfo {
os_name: platform.display_name(),
os_version: platform.os_version(),
hardware: platform.hardware_model(),
hostname: hostname(),
user: std::env::var("USER")
.or_else(|_| std::env::var("USERNAME"))
.unwrap_or_else(|_| "unknown".into()),
arch: std::env::consts::ARCH.to_string(),
}
}
}
fn hostname() -> String {
const BUF: usize = 256;
let mut buf = vec![0u8; BUF];
let name = unsafe {
if libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, BUF) == 0 {
let end = buf.iter().position(|b| *b == 0).unwrap_or(buf.len());
String::from_utf8_lossy(&buf[..end]).into_owned()
} else {
String::new()
}
};
if name.is_empty() {
"localhost".into()
} else {
name
}
}
/// Seconds → "3d 4h 12m".
pub fn human_uptime(secs: u64) -> String {
let days = secs / 86_400;
let hours = (secs % 86_400) / 3_600;
let minutes = (secs % 3_600) / 60;
if days > 0 {
format!("{days}d {hours}h {minutes}m")
} else if hours > 0 {
format!("{hours}h {minutes}m")
} else {
format!("{minutes}m {}s", secs % 60)
}
}
// ─────────────────────────────── sampling ─────────────────────────────────
/// Stateful sampler. `System`, `Networks` and `Disks` all compute deltas from
/// their own previous state, so they must be kept alive between ticks.
pub struct Sampler {
system: System,
networks: Networks,
disks: Disks,
last: Instant,
host: HostInfo,
volumes: Vec<Volume>,
volumes_at: Option<Instant>,
battery: Option<Battery>,
battery_at: Option<Instant>,
had_first_sample: bool,
}
impl Default for Sampler {
fn default() -> Self {
Self::new()
}
}
impl Sampler {
pub fn new() -> Sampler {
let system = System::new_with_specifics(
RefreshKind::nothing()
.with_cpu(sysinfo::CpuRefreshKind::everything())
.with_memory(sysinfo::MemoryRefreshKind::everything())
.with_processes(ProcessRefreshKind::nothing().with_cpu().with_memory()),
);
Sampler {
networks: Networks::new_with_refreshed_list(),
disks: Disks::new_with_refreshed_list(),
system,
last: Instant::now(),
host: HostInfo::gather(),
volumes: Vec::new(),
volumes_at: None,
battery: None,
battery_at: None,
had_first_sample: false,
}
}
/// Cheap first call: fills totals without claiming any rates.
pub fn prime(&mut self) -> SystemSnapshot {
let snapshot = self.refresh();
SystemSnapshot {
network: NetRate {
interfaces: snapshot.network.interfaces,
rx_total: snapshot.network.rx_total,
tx_total: snapshot.network.tx_total,
primary: snapshot.network.primary,
..Default::default()
},
disk: DiskRate {
disks: snapshot.disk.disks,
..Default::default()
},
cpu: CpuStats {
total: 0.0,
..snapshot.cpu
},
..snapshot
}
}
pub fn refresh(&mut self) -> SystemSnapshot {
let elapsed = self.last.elapsed().max(Duration::from_millis(80));
self.last = Instant::now();
self.system
.refresh_cpu_specifics(sysinfo::CpuRefreshKind::nothing().with_cpu_usage());
self.system
.refresh_memory_specifics(sysinfo::MemoryRefreshKind::nothing().with_ram().with_swap());
self.system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing().with_cpu().with_memory(),
);
self.networks.refresh(true);
self.disks.refresh(true);
let seconds = elapsed.as_secs_f64();
let cpu = cpu_stats(&self.system);
let memory = memory_stats(&self.system);
let network = net_rates(&self.networks, seconds);
let disk = disk_rates(&self.disks, seconds);
let top_processes = top_processes(&self.system, 12);
let mut snapshot = SystemSnapshot {
taken_at_ms: now_ms(),
cpu,
memory,
network,
disk,
uptime_secs: System::uptime(),
processes: self.system.processes().len(),
top_processes,
volumes: Vec::new(),
battery: None,
host: self.host.clone(),
};
// Volumes and battery need syscalls / subprocesses that no UI needs at
// 1 Hz, so they are refreshed on a slower cadence.
let volumes_stale = self
.volumes_at
.map(|at| at.elapsed() > Duration::from_secs(5))
.unwrap_or(true);
if volumes_stale {
let platform = squid_platform::current();
if let Ok(volumes) = platform.volumes() {
self.volumes = volumes;
}
self.volumes_at = Some(Instant::now());
}
snapshot.volumes = self.volumes.clone();
let battery_stale = self
.battery_at
.map(|at| at.elapsed() > Duration::from_secs(20))
.unwrap_or(true);
if battery_stale {
self.battery = Battery::current();
self.battery_at = Some(Instant::now());
}
snapshot.battery = self.battery.clone();
self.had_first_sample = true;
snapshot
}
pub fn volumes(&mut self) -> Vec<Volume> {
let stale = self
.volumes_at
.map(|at| at.elapsed() > Duration::from_secs(5))
.unwrap_or(true);
if stale {
let platform = squid_platform::current();
if let Ok(volumes) = platform.volumes() {
self.volumes = volumes;
}
self.volumes_at = Some(Instant::now());
}
self.volumes.clone()
}
pub fn has_first_sample(&self) -> bool {
self.had_first_sample
}
/// Per-application CPU totals. iStat Menus shows this next to the gauges.
pub fn applications(&mut self, limit: usize) -> Vec<AppUsage> {
self.system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing().with_cpu().with_memory(),
);
let mut merged: std::collections::HashMap<String, (f32, u64, usize, u32)> =
std::collections::HashMap::new();
for process in self.system.processes().values() {
let name = process
.name()
.to_string_lossy()
.split('/')
.next_back()
.unwrap_or("?")
.to_string();
let entry = merged
.entry(name)
.or_insert((0.0, 0, 0, process.pid().as_u32()));
entry.0 += process.cpu_usage();
entry.1 += process.memory();
entry.2 += 1;
}
let mut apps: Vec<AppUsage> = merged
.into_iter()
.map(|(name, (cpu, memory, instances, pid))| AppUsage {
name,
cpu: cpu.min(4_000.0),
memory: Bytes(memory),
instances,
pid,
})
.collect();
apps.sort_by(|a, b| {
b.cpu
.partial_cmp(&a.cpu)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| b.memory.cmp(&a.memory))
});
apps.truncate(limit);
apps
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AppUsage {
pub name: String,
pub cpu: f32,
pub memory: Bytes,
pub instances: usize,
pub pid: u32,
}
fn cpu_stats(system: &System) -> CpuStats {
// sysinfo puts the aggregate sample in `cpus()[0]`; the tail is one entry
// per logical core.
let all = system.cpus();
let (aggregate, cores) = all
.split_first()
.map(|(head, tail)| (Some(head), tail))
.unwrap_or((None, &[]));
let per_core: Vec<f32> = cores
.iter()
.map(|cpu| cpu.cpu_usage().clamp(0.0, 100.0))
.collect();
let load = System::load_average();
let brand = aggregate
.or_else(|| cores.first())
.map(|cpu| cpu.brand().trim().to_string())
.unwrap_or_else(|| std::env::consts::ARCH.to_string());
let base_frequency_ghz = aggregate
.or_else(|| cores.first())
.map(|cpu| cpu.frequency() as f64 / 1_000.0)
.unwrap_or(0.0);
let total = aggregate
.map(|cpu| cpu.cpu_usage())
.unwrap_or_else(|| system.global_cpu_usage())
.clamp(0.0, 100.0);
let logical_cores = if per_core.is_empty() {
1
} else {
per_core.len()
};
let physical = detect_physical_cores().unwrap_or_else(|| logical_cores.div_ceil(2));
CpuStats {
total,
per_core,
load: [load.one as f32, load.five as f32, load.fifteen as f32],
physical_cores: physical,
logical_cores,
brand,
base_frequency_ghz,
}
}
fn detect_physical_cores() -> Option<usize> {
#[cfg(target_os = "macos")]
{
let value = sysctl_u64("hw.physicalcpu")?;
Some(value as usize)
}
#[cfg(target_os = "linux")]
{
let text = std::fs::read_to_string("/proc/cpuinfo").ok()?;
let mut ids = std::collections::HashSet::new();
for line in text.lines() {
if let Some(rest) = line.strip_prefix("core id") {
if let Some(value) = rest.split(':').nth(1) {
ids.insert(value.trim().to_string());
}
}
}
if !ids.is_empty() {
return Some(ids.len());
}
return Some(
usize::from_str(
std::fs::read_to_string("/sys/devices/system/cpu/present")
.ok()?
.trim(),
)
.unwrap_or(1),
);
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
{
None
}
}
#[cfg(target_os = "macos")]
fn sysctl_u64(name: &str) -> Option<u64> {
use std::ffi::CString;
use std::mem::{size_of, MaybeUninit};
let c_name = CString::new(name).ok()?;
let mut value: u64 = 0;
let mut len = size_of::<u64>();
let rc = unsafe {
libc::sysctlbyname(
c_name.as_ptr(),
&mut value as *mut u64 as *mut libc::c_void,
&mut len,
std::ptr::null_mut(),
0,
)
};
if rc == 0 {
Some(value)
} else {
let _ = MaybeUninit::<u64>::uninit();
None
}
}
fn memory_stats(system: &System) -> MemoryStats {
let mut stats = MemoryStats {
total: Bytes(system.total_memory()),
used: Bytes(system.used_memory()),
available: Bytes(system.available_memory()),
swap_total: Bytes(system.total_swap()),
swap_used: Bytes(system.used_swap()),
compressed: None,
wired: None,
};
if let Some(extra) = vm_stat_details() {
stats.compressed = Some(extra.0);
stats.wired = Some(extra.1);
}
stats
}
/// `vm_stat` gives compressor/wired sizes that sysinfo folds away. Parsed
/// lazily and cheaply (one subprocess every few seconds at most).
fn vm_stat_details() -> Option<(Bytes, Bytes)> {
use std::sync::atomic::{AtomicU64, Ordering};
static LAST: AtomicU64 = AtomicU64::new(0);
let now = now_ms();
let previous = LAST.swap(now, Ordering::Relaxed);
static CACHE: std::sync::Mutex<Option<(Bytes, Bytes)>> = std::sync::Mutex::new(None);
if now - previous > 5_000 || previous == 0 {
let page_size = 4096u64;
let output = std::process::Command::new("/usr/bin/vm_stat")
.output()
.ok()
.filter(|out| out.status.success())?;
let text = String::from_utf8_lossy(&output.stdout);
let mut compressor_pages = 0u64;
let mut wired_pages = 0u64;
for line in text.lines() {
let mut parts = line.split(':');
let key = parts.next()?.trim();
let value = parts.next()?.trim().trim_end_matches('.').replace(' ', "");
let pages: u64 = value.parse().unwrap_or(0);
match key {
"Occupied by compressor" => compressor_pages = pages,
"Wired Pages" => wired_pages = pages,
_ => {}
}
}
let value = (
Bytes(compressor_pages * page_size),
Bytes(wired_pages * page_size),
);
if let Ok(mut guard) = CACHE.lock() {
*guard = Some(value);
}
Some(value)
} else {
CACHE.lock().ok().and_then(|guard| *guard)
}
}
fn net_rates(networks: &Networks, seconds: f64) -> NetRate {
let mut rx = 0u64;
let mut tx = 0u64;
let mut rx_total = 0u64;
let mut tx_total = 0u64;
let mut best: Option<(u64, String)> = None;
let mut interfaces = 0usize;
for (name, data) in networks.list() {
if name == "lo" || name.starts_with("lo") || name.starts_with("utun") {
// Loopback and VPN tunnels would inflate the totals with traffic
// that never leaves the machine.
continue;
}
interfaces += 1;
let delta = data.received() + data.transmitted();
rx += data.received();
tx += data.transmitted();
rx_total += data.total_received();
tx_total += data.total_transmitted();
if best.as_ref().map(|(seen, _)| delta > *seen).unwrap_or(true) {
best = Some((delta, name.clone()));
}
}
NetRate {
rx_per_sec: Bytes((rx as f64 / seconds) as u64),
tx_per_sec: Bytes((tx as f64 / seconds) as u64),
rx_total: Bytes(rx_total),
tx_total: Bytes(tx_total),
interfaces,
primary: best.map(|(_, name)| name),
}
}
fn disk_rates(disks: &Disks, seconds: f64) -> DiskRate {
let mut read = 0u64;
let mut write = 0u64;
let mut physical = 0usize;
for disk in disks.list() {
if disk.is_removable() && disk.name().is_empty() {
continue;
}
let usage: DiskUsage = disk.usage();
read += usage.read_bytes;
write += usage.written_bytes;
physical += 1;
}
// sysinfo exposes no busy time, so approximate activity by throughput
// against a conservative 1 GB/s ceiling for internal NVMe.
let peak = ((read + write) as f64 / seconds).max(1.0);
DiskRate {
read_per_sec: Bytes((read as f64 / seconds) as u64),
write_per_sec: Bytes((write as f64 / seconds) as u64),
activity: ((peak / 1_000_000_000.0) * 100.0).min(100.0) as f32,
disks: physical,
}
}
fn top_processes(system: &System, limit: usize) -> Vec<ProcessSample> {
let mut processes: Vec<ProcessSample> = system
.processes()
.values()
.map(|process| ProcessSample {
pid: process.pid().as_u32(),
name: process
.name()
.to_string_lossy()
.split('/')
.next_back()
.unwrap_or("?")
.to_string(),
cpu: process.cpu_usage(),
memory: Bytes(process.memory()),
})
.collect();
processes.sort_by(|a, b| {
b.cpu
.partial_cmp(&a.cpu)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| b.memory.cmp(&a.memory))
});
processes.truncate(limit);
processes
}
pub fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or_default()
}
// ─────────────────────────────── history ──────────────────────────────────
/// Fixed-capacity ring buffer used for the sparklines in the TUI.
#[derive(Clone, Debug)]
pub struct History<T> {
cap: usize,
items: VecDeque<T>,
}
impl<T: Clone> History<T> {
pub fn new(cap: usize) -> History<T> {
History {
cap: cap.max(2),
items: VecDeque::with_capacity(cap.max(2)),
}
}
pub fn push(&mut self, value: T) {
if self.items.len() >= self.cap {
self.items.pop_front();
}
self.items.push_back(value);
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn cap(&self) -> usize {
self.cap
}
pub fn values(&self) -> Vec<T> {
self.items.iter().cloned().collect()
}
pub fn last(&self) -> Option<&T> {
self.items.back()
}
pub fn oldest(&self) -> Option<&T> {
self.items.front()
}
pub fn clear(&mut self) {
self.items.clear();
}
}
/// Snapshot history for the state screen: CPU, memory pressure and net rates.
#[derive(Clone, Debug)]
pub struct TrendStore {
pub cpu: History<f32>,
pub memory: History<f32>,
pub rx: History<f64>,
pub tx: History<f64>,
pub read: History<f64>,
pub write: History<f64>,
pub uptime_secs: History<u64>,
}
impl Default for TrendStore {
fn default() -> Self {
TrendStore {
cpu: History::new(120),
memory: History::new(120),
rx: History::new(120),
tx: History::new(120),
read: History::new(120),
write: History::new(120),
uptime_secs: History::new(120),
}
}
}
impl TrendStore {
pub fn record(&mut self, snapshot: &SystemSnapshot) {
self.cpu.push(snapshot.cpu.total);
self.memory.push(snapshot.memory.percent_used() as f32);
self.rx.push(snapshot.network.rx_per_sec.as_u64() as f64);
self.tx.push(snapshot.network.tx_per_sec.as_u64() as f64);
self.read.push(snapshot.disk.read_per_sec.as_u64() as f64);
self.write.push(snapshot.disk.write_per_sec.as_u64() as f64);
self.uptime_secs.push(snapshot.uptime_secs);
}
pub fn trimmed(&self, width: usize) -> TrendWindow {
fn tail<T: Clone>(history: &History<T>, width: usize) -> Vec<T> {
let values = history.values();
let skip = values.len().saturating_sub(width.max(1));
values[skip..].to_vec()
}
TrendWindow {
cpu: tail(&self.cpu, width),
memory: tail(&self.memory, width),
rx: tail(&self.rx, width),
tx: tail(&self.tx, width),
read: tail(&self.read, width),
write: tail(&self.write, width),
}
}
}
/// Sparkline-ready view of the last `width` samples.
#[derive(Clone, Debug, Default)]
pub struct TrendWindow {
pub cpu: Vec<f32>,
pub memory: Vec<f32>,
pub rx: Vec<f64>,
pub tx: Vec<f64>,
pub read: Vec<f64>,
pub write: Vec<f64>,
}
pub fn path_of(volume: &Volume) -> PathBuf {
volume.mount_point.clone()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uptime_formatting() {
assert_eq!(human_uptime(59), "0m 59s");
assert_eq!(human_uptime(3_700), "1h 1m");
assert_eq!(human_uptime(90_000), "1d 1h 0m");
}
#[test]
fn history_is_a_ring_buffer() {
let mut history = History::new(3);
for value in 0..5 {
history.push(value);
}
assert_eq!(history.values(), vec![2, 3, 4]);
assert_eq!(history.last(), Some(&4));
assert_eq!(history.oldest(), Some(&2));
}
#[test]
fn sampler_produces_sane_numbers() {
let mut sampler = Sampler::new();
std::thread::sleep(Duration::from_millis(220));
let snapshot = sampler.refresh();
assert!(snapshot.cpu.logical_cores > 0);
assert_eq!(snapshot.cpu.per_core.len(), snapshot.cpu.logical_cores);
assert!(snapshot.memory.total.as_u64() > 0);
assert!(snapshot.memory.percent_used() <= 100);
assert!(!snapshot.volumes.is_empty(), "expected at least one volume");
assert!(snapshot.taken_at_ms > 0);
assert!(!snapshot.host.os_name.is_empty());
assert!(snapshot.processes > 0);
let apps = sampler.applications(5);
assert!(!apps.is_empty());
}
#[test]
fn percentages_never_exceed_one_hundred() {
let stats = MemoryStats {
total: Bytes::new(100),
used: Bytes::new(1_000),
..Default::default()
};
assert_eq!(stats.percent_used(), 100);
}
}

View File

@ -0,0 +1,22 @@
[package]
name = "squid-tui"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "CleanMyMac-inspired terminal interface for squid"
[dependencies]
squid-core.workspace = true
squid-engine.workspace = true
squid-platform.workspace = true
squid-rules.workspace = true
squid-stats.workspace = true
anyhow.workspace = true
crossterm.workspace = true
ratatui.workspace = true
unicode-width.workspace = true
rayon.workspace = true
chrono.workspace = true
serde_json.workspace = true
crossbeam-channel.workspace = true

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,150 @@
//! Background work. A TUI that blocks on a disk walk is a broken TUI, so every
//! engine call runs on its own thread and reports through two channels:
//!
//! * [`Progress`] events (phases, ticks, warnings) feed the live progress bar;
//! * one final value on completion, delivered to [`JobHandle::poll`].
//!
//! Each job builds its own [`Engine`]. That keeps the borrow checker happy and
//! means a job always sees current settings, at the cost of re-reading a small
//! TOML file per scan.
use crossbeam_channel::{bounded, Receiver, TryRecvError};
use squid_core::progress::{CancelToken, Progress};
use squid_engine::Engine;
pub struct JobHandle<T> {
rx: Receiver<Result<T, String>>,
cancel: CancelToken,
label: String,
}
impl<T> JobHandle<T> {
/// Non-blocking peek: `None` while the worker is still running.
pub fn poll(&self) -> Option<Result<T, String>> {
match self.rx.try_recv() {
Ok(value) => Some(value),
Err(TryRecvError::Empty) => None,
Err(TryRecvError::Disconnected) => {
Some(Err("the worker thread disappeared".to_string()))
}
}
}
pub fn cancel(&self) {
self.cancel.cancel();
}
pub fn label(&self) -> &str {
&self.label
}
pub fn is_finished(&self) -> bool {
self.poll().is_some()
}
}
/// Run `work` on a worker thread. The returned [`Progress`] is the handle the
/// UI drains for live feedback.
pub fn spawn<T, F>(label: &str, work: F) -> (JobHandle<T>, Progress)
where
T: Send + 'static,
F: FnOnce(&Engine, &Progress, &CancelToken) -> squid_core::Result<T> + Send + 'static,
{
let progress = Progress::new();
let ui_progress = progress.clone();
let cancel = CancelToken::new();
let worker_cancel = cancel.clone();
let (tx, rx) = bounded::<Result<T, String>>(1);
let label = label.to_string();
let thread_label = label.clone();
std::thread::Builder::new()
.name(format!("squid-{label}"))
.spawn(move || {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let engine = Engine::new();
work(&engine, &progress, &worker_cancel)
}));
let value = match result {
Ok(inner) => inner.map_err(|err| err.to_string()),
Err(panic) => {
let message = panic
.downcast_ref::<&str>()
.map(|text| text.to_string())
.or_else(|| panic.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown error".to_string());
Err(format!("internal error: {message}"))
}
};
let _ = tx.send(value);
})
.expect("spawn worker thread");
(
JobHandle {
rx,
cancel,
label: thread_label,
},
ui_progress,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_job_reports_its_value() {
let (job, progress) = spawn("test", |_engine, _progress, _cancel| Ok(41u32 + 1));
loop {
let _ = progress.drain();
if let Some(value) = job.poll() {
assert_eq!(value.expect("ok"), 42u32);
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test]
fn a_panicking_job_becomes_an_error_instead_of_a_hang() {
let (job, _progress) = spawn(
"boom",
|_engine, _progress, _cancel| -> squid_core::Result<u32> {
panic!("deliberate");
},
);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
if let Some(value) = job.poll() {
assert!(value.unwrap_err().contains("deliberate"));
break;
}
assert!(std::time::Instant::now() < deadline, "job never finished");
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
#[test]
fn cancellation_reaches_the_worker() {
let (job, _progress) = spawn("cancel", |_engine, _progress, cancel| {
for _ in 0..1_000 {
if cancel.is_cancelled() {
return Err(squid_core::SquidError::Cancelled);
}
std::thread::sleep(std::time::Duration::from_millis(2));
}
Ok(0u32)
});
std::thread::sleep(std::time::Duration::from_millis(20));
job.cancel();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
if let Some(value) = job.poll() {
assert!(value.unwrap_err().contains("cancel"));
break;
}
assert!(std::time::Instant::now() < deadline, "cancel ignored");
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
}

View File

@ -0,0 +1,113 @@
//! The terminal front end.
//!
//! [`run`] owns the whole screen: it installs raw mode plus the alternate
//! buffer, drives [`App::tick`] on a fixed beat, and always puts the terminal
//! back the way it found it — including when a render panics.
pub mod app;
pub mod job;
pub mod theme;
pub mod views;
use app::{Action, App};
use crossterm::{
event::{poll, read, Event, KeyCode, KeyEventKind, KeyModifiers},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io::{stdout, Write};
use std::time::{Duration, Instant};
/// How often the UI drains progress events and repaints.
const TICK: Duration = Duration::from_millis(250);
/// Restores the terminal on the way out, panic included. Without the panic
/// hook a bug would leave the user's shell in raw mode.
struct TerminalGuard;
impl TerminalGuard {
fn install() -> anyhow::Result<TerminalGuard> {
enable_raw_mode()?;
let mut out = stdout();
execute!(out, EnterAlternateScreen)?;
out.flush()?;
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = TerminalGuard::restore();
previous(info);
}));
Ok(TerminalGuard)
}
fn restore() -> std::io::Result<()> {
let mut out = stdout();
execute!(out, LeaveAlternateScreen)?;
out.flush()?;
disable_raw_mode()?;
Ok(())
}
}
impl Drop for TerminalGuard {
fn drop(&mut self) {
let _ = TerminalGuard::restore();
}
}
/// Open the interface. Returns once the user quits.
pub fn run() -> anyhow::Result<()> {
// Settle the colour depth before the terminal is touched at all. The answer
// comes from the environment of the shell that launched squid, and every
// colour the interface later emits is decided by it: a terminal that cannot
// parse a 24-bit escape sequence prints the numbers as text, so asking
// first and defaulting downwards is what keeps Apple Terminal and a bare
// ssh session readable instead of garbled.
crate::theme::init();
let guard = TerminalGuard::install()?;
let result = run_inner();
drop(guard);
result
}
fn run_inner() -> anyhow::Result<()> {
let mut app = App::new()?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
terminal.hide_cursor()?;
terminal.clear()?;
let mut next_tick = Instant::now() + TICK;
while !app.should_quit {
app.tick();
terminal.draw(|frame| views::draw(frame, &app))?;
if poll(next_tick.saturating_duration_since(Instant::now()))? {
match read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => {
if app.handle_key(key.code, key.modifiers) == Action::Quit {
if app.busy() && !app.confirm.is_some() {
app.cancel_jobs();
app.should_quit = true;
} else {
app.should_quit = true;
}
}
}
Event::Key(key)
if key.kind == KeyEventKind::Repeat
&& key.modifiers.contains(KeyModifiers::CONTROL)
&& key.code == KeyCode::Char('c') =>
{
app.cancel_jobs();
app.should_quit = true;
}
Event::Resize(_, _) => {}
_ => {}
}
}
if Instant::now() >= next_tick {
next_tick = Instant::now() + TICK;
}
}
terminal.show_cursor()?;
Ok(())
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,258 @@
# squid 架构
本文描述 squid 的模块划分、数据流、安全不变量与跨平台方案。阅读顺序建议:先读「两条铁律」,再看 crate 图,最后按需查各引擎。
## 设计目标
1. **一台机器可以只有 245 GB,但用户的文件必须是无价的。** 所有设计里优先级最高的一条。
2. **单二进制、零常驻。** 没有 daemon、没有 launch agent、没有后台上传;`squid` 退出后不留痕迹。
3. **CLI 与 TUI 共用同一套引擎。** 终端界面不是玩具前端,`squid clean` 与 TUI 里的「清理」面板调用的是同一个函数。
4. **可脚本化。** 任何命令都能 `--json`、`--dry-run`、`--quiet`,退出码稳定。
非目标:不做实时文件系统监听、不做定时任务、不做 GUI(AppKit/SwiftUI)、不做云同步。
## 两条铁律(不变量)
**铁律一:扫描不删除。**
每个引擎都遵循 `Scan → Approve → Delete` 契约。`scan()` 只产出 `ScanReport`(一组 `CleanupItem`),幂等、无副作用,可以随时中断,可以对着 1 TB 的目录跑十次。
**铁律二:只有 `squid_engine::delete::execute` 能删东西。**
`squid-engine` 内部禁止直接调用 `std::fs::remove_*`。删除必须经过这一个函数,因此「安全校验 + 账本 + 废纸篓可还原」在架构上无法被绕过——新增引擎时想跳过检查,就只能显式地写出一条很难看代码评审的语句。
`execute` 做的事:丢弃嵌套重复项(父目录先删会让子项 ENOENT、体积重复计数)→ 对每个条目重新执行 `Engine::block_reason()`(锁、白名单、`SafetyPolicy`)→ 预先计算废纸篓目标路径 → 删除 → 写 ledger 会话。之所以要"重新校验",是因为一次扫描可能跑了几分钟,磁盘早就不一样了。
## crate 依赖图
```
┌──────────────┐
│ squid-core │ 模型 / 字节 / 路径 / 安全策略 / 设置 / 账本 / 进度
└──────┬───────┘
┌─────────┼──────────┐
┌──────▼─────┐ ┌─▼────────┐ │
│ squid- │ │ squid- │ │ ← 只依赖 core
│ platform │ │ rules │ │
└──────┬─────┘ └─┬────────┘ │
│ │ │
┌────▼─────────▼───────┐ │ ┌────────────┐
│ squid-engine │◄─┼───┤ squid-stats│ ← 只依赖 core
└────┬────────────┬────┘ │ └─────┬──────┘
┌───────▼──┐ ┌────▼───────▼──┐ │
│ squid-tui│ │ squid-cli │◄─────┘
└──────────┘ └───────────────┘
```
依赖方向严格单向,`squid-core` 不知道其它任何 crate 的存在。
### squid-core
| 模块 | 关键类型 | 职责 |
| --- | --- | --- |
| `model` | `CleanupItem`, `Category`, `ItemKind`, `DeleteMode`, `LockReason`, `CleanSummary`, `ScanReport` | 唯一的数据货币。`CleanupItem{path, kind, size, category, label, rule_id, selected, allocated, lock, note, anchors}` |
| `bytes` | `Bytes`, `format_thousands` | 逻辑大小 vs 实际占盘大小(`st_blocks * 512`)两套口径 |
| `paths` | `expand`, `home_dir`, `pretty`, `label_for` | `~` 展开、`~/…` 显示、中文安全的路径缩短 |
| `fs` | `measure`, `measure_all`, `kind_of`, `remove_item_with`, `trash_path`, `trash_target_for`, `empty_trash` | 体积测量(walkdir + rayon 并行,忽略符号链接)、安全删除、跨卷回收站 |
| `safety` | `SafetyPolicy` | 见「安全模型」 |
| `settings` | `Settings`, `locale()` | `config.toml`、白名单、规则开关、`SQUID_CONFIG_DIR`/`SQUID_STATE_DIR` |
| `ledger` | `Session`, `LedgerEntry`, `write_session`, `load_sessions`, `restore` | 删除账本与 `undo` |
| `progress` | `Progress`, `Event`, `CancelToken` | 引擎与 UI 之间唯一的沟通渠道;跨线程通道,取消是协作式的 |
### squid-platform
`Platform` trait 把「这个操作系统上 App 装在哪、残留放在哪、卷怎么枚举、删除前要不要先停服务」抽象出来:
```rust
fn app_sources(&self) -> Vec<AppSource>;
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>>;
fn leftover_roots(&self) -> Vec<LeftoverRoot>;
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport; // 停 launchd / 注销 Launch Services
fn finish_uninstall(&self, app: &AppInfo, removed: &[PathBuf]) -> LifecycleReport;
fn volumes(&self) -> Result<Vec<Volume>>;
fn protected_prefixes(&self) -> Vec<PathBuf>;
fn running_executables(&self) -> Vec<String>; // 供 skip_if_running 使用
```
`LeftoverRoot { dir, naming, deep, category }` 描述一个残留目录以及它的命名方式(`BundleId` / `AppName` / `Either` / `GroupContainer`)。`deep` 默认 false —— `Application Support` 这种目录只匹配直接子项,绝不递归。
`leftovers::match_name` 负责把 `Xmind.app` 与 `com.xmind.win_zen.bundle`、`Xmind-state`、`Xmind Saved Application State` 之类关联起来。这里有两个曾经踩过的坑,回归测试已经锁住:
- 匹配前大小写要归一化(`Xmind` vs `xmind`);
- `KNOWN_SUFFIXES` 带点而文件名切分后不带点,两侧必须用同一种归一化形式比较(`has_known_suffix`)。另外 `.pdf/.png/.mp3` 这类文档后缀绝不能出现在「按名称匹配」的后缀表里,否则 `Xmind-notes.pdf` 会被当成残留删掉。
### squid-rules
规则是 TOML,内置于 `crates/squid-rules/rules/macos.toml`(39 条),通过 `include_str!` 编译进二进制;用户规则从 `<config_dir>/rules/*.toml` 合并,同 `id` 覆盖内置。
```toml
[[rule]]
id = "xcode-derived-data"
category = "developer"
patterns = ["~/Library/Developer/Xcode/DerivedData/*"]
mode = "path" # path = 删除条目本身;contents = 只清空目录内容
os = ["macos"]
protect = ["SomeKeep", "SomeKeep/*"]
min_age_days = 3
select_by_default = true
needs_admin = false
skip_if_running = ["Docker Desktop", "com.docker.backend"]
risky = true
note = "Xcode 会重新生成。"
```
核心是 `expand_pattern(pattern) -> Vec<Match{path, anchor}>`:
- `*` **不跨越路径分隔符**(globset 语义),所以 `~/Library/Caches/*` 只会命中一层;
- 每条匹配都携带 **anchor(锚点)** —— 模式的最长字面量前缀。锚点是删除时的权限边界:`SafetyPolicy` 只允许在锚点之下删除,且拒绝锚点自身。这条设计使得「一条规则写错」的最坏后果被限制在该规则自己的目录里;
- 不含通配符的字面模式(如 `~/.cargo/.package-cache`)匹配的是这个文件本身、锚点取其父目录。曾经有个 bug 是把锚点当成了匹配结果,等于提出删除整个 `~/.cargo`——已有回归测试 `wildcard_free_patterns_match_the_file_not_the_parent`。
`risky` 与 `skip_if_running` 是给「体积巨大但语义危险」的规则准备的刹车,典型是 `container-images`:Docker 的 VM 磁盘可能有 1 TB,一旦正在运行还去删就是数据事故,所以它既不默认勾选、又在检测到 Docker/OrbStack 进程时直接锁定。
### squid-stats
`Sampler::{new, prime, refresh}` 基于 `sysinfo`,两次采样之间才有 CPU%/网速,因此 `prime()` 是必须的预热步骤。产出 `SystemSnapshot{cpu, memory, network, disk, uptime_secs, top_processes, volumes, battery, host}` 与 `TrendStore`(滚动历史,给 TUI 的迷你折线/柱状图)。`battery.rs`、`human_uptime()` 提供 iStat 式细节。
### squid-engine
| 引擎 | 做法 |
| --- | --- |
| `clean` | 遍历规则 → `expand_pattern` → `protect`/年龄/白名单/运行中过滤 → `measure_all` 并行测体积 → `sort_for_display` 按分组排序。`--orphans` 会额外调用平台残留匹配,寻找已消失 App 的孤儿目录 |
| `uninstall` | `scan_apps` 建立 App 清单(名称、bundle id、体积、是否运行中、Homebrew cask)→ `find` 模糊定位 → `build_plan` 生成「本体 + 按 bundle id/名称匹配的残留」→ 用户确认 → `remove_plan`(含平台 `prepare_uninstall`/`finish_uninstall` 钩子)。共享给同厂商多个安装的残留会被 `LockReason::SharedWithOtherInstall` 锁住 |
| `purge` | 遍历 `purge_roots`(或用户给定路径,默认深度 6、最多 30 万目录),把 `ALWAYS`(node_modules、target、DerivedData、`.venv`…)识别为可再生;`AMBIGUOUS`(dist、build、out、venv…)只有当同目录存在 `package.json`/`Cargo.toml`/`go.mod` 等 PROJECT_MARKERS、或用户显式 `--all` 时才提出。`DO_NOT_DESCEND` 阻止进入 `.git`、Library、挂载点等。附带 APFS 本地快照(`com.apple.TimeMachine*`)与旧 iOS 备份、磁盘镜像等非目录项 |
| `analyze` | DaisyDisk 式体积树:`explore`/`expand` 逐层展开、`largest_files`、`buckets` 分类聚合。总量在遍历超限时标记为下限而非真值 |
### squid-tui
ratatui + crossterm。六个面板 `Cleanup / Uninstall / Purge / Storage / Stats / History`,`App` 是唯一状态机,键盘事件 → `Action` → 重绘。
- **绝不阻塞 UI**:每个引擎调用都通过 `job::spawn` 跑到独立线程,返回 `JobHandle<T>`;`Progress` 事件与最终结果走两条 crossbeam 通道,事件循环 `poll()` 非阻塞取结果。取消是协作式的 `CancelToken`。
- 每个 job 自己 `Engine::new()`,避免跨线程借用,代价是每次扫描重读一遍小 TOML。
- `theme::Strings::t(en, zh)` 集中管理双语文案,`Palette`/`card()` 复刻 CleanMyMac 的暗色卡片观感(背景 `Rgb(16,18,23)`、强调色 `Rgb(86,182,246)`、圆角卡片)。
调色板只写 RGB,输出一律经 `Palette::resolve`:`SQUID_TRUECOLOR` → `COLORTERM` → `TERM_PROGRAM` → `TERM`
依次探测真彩色能力,不支持时映射到 xterm-256(灰阶走 24 级灰条)。Terminal.app 只认 256 色,
少了这一步它会把 `48;2;…` 当文字打出来,暗色主题直接变成白底黑字。
- **选中状态不能只靠颜色**:`Palette::selected_for(truecolor)` 在真彩色下是强调色条,降级终端里是
`REVERSED | BOLD`(反白由终端自身的前景色/背景色完成,灰度终端同样成立);勾选状态另有加粗 `●`
与细体 `○` 两条冗余通道。`close_gaps` 负责让高亮行成为连续的一整条:列分隔用的是无样式
`Span::raw(" ")`,反白时会在行里留下一道道暗缝,所以只在「整行非空白 span 样式一致」时把空白也染上;
路径列只截断不补齐,因此 `item_row` 末尾还会按显示宽度补一段同色空格,让高亮条一直顶到卡片右边框。
### squid-cli
clap derive。约定:
- `--json` 时 stdout 只允许是数据。所有人类可读输出经 `DIAG_STDERR` 改道 stderr,`squid clean --json | jq` 永远干净;
- stdin 不是 TTY 且没有 `-y/--yes` 时,拒绝执行真实删除;
- 输出宽度按 `terminal_width()` 自适应,列宽用显示宽度(CJK 占两列)对齐,`clip` 截断 + `fit` 补空格。
## 安全模型(分层)
| 层 | 位置 | 拦截什么 |
| --- | --- | --- |
| 规则自我约束 | `squid-rules` | `protect`、`min_age_days`、`select_by_default=false`、`risky`、`skip_if_running`、`os` |
| 锚点边界 | `CleanupItem::anchors` + `SafetyPolicy::check` | 只允许在规则声明的锚点之下删除,且永不删除锚点自身 |
| 硬性禁区 | `safety::HARD_DENY` | `/`、`/usr`、`/System`、`/Library`、`/Applications`、`/private/var/folders`、`/Volumes`… 无论什么规则都拒绝 |
| 危险目录 | `safety::DENY_EXACT` | `~/Library`、`~/Documents`、`~/.ssh`、`~/.aws`、`~/Library/Application Support/MobileSync`… 允许删子项、禁止整目录递归删 |
| 深度 / 家目录 / 符号链接 | `SafetyPolicy{min_depth, allow_system_paths, follow_symlinks}` | 非 root 时拒绝家目录之外的路径(`OUTSIDE_HOME_OK` 例外);递归删除必须有最小深度;永不跟随符号链接 |
| 卷 | `forbidden_mounts` | 由 `platform.volumes()` 注入,不删别的卷 |
| 用户白名单 | `Engine::is_whitelisted` | glob 命中即永不选中 |
| 运行时状态 | `LockReason` | App 正在运行、被其它安装共享、权限不属于当前用户 |
| 兜底 | 默认 Trash + `--dry-run` + 账本 + `undo` | 前面全漏了还能还原 |
`Engine::new()` 会根据是否 root 选择 `SafetyPolicy::system()` 或 `user_only()`,后者拒绝家目录之外的路径,
例外只有 `OUTSIDE_HOME_OK = ["/Applications"]`:管理员组的普通用户在 Finder 里把 App 拖进废纸篓不需要密码,
卸载器必须做同一件事。例外只覆盖 `/Applications` **里的条目**(目录本身仍在 `HARD_DENY`),
且 root 拥有的 App 早在 `build_plan` 就被 `writable_by_us` 锁住了。
### 事故记录:卸载「成功」了,App 还在
一次用户反馈「选中 Chatbox → d → 确认 → 毫无反应」,最后挖出四层独立原因,每一层都足以让事故静默:
1. `pending_plan` 从未被赋值(见下一节);
2. 任务运行期间所有变更键被 `if self.busy() { return }` 静默吞掉,`confirm_delete()` 还会顺手清空
`confirm` + `pending`——用户的「是」被吃掉了。现在统一走 `App::busy_refusal()`,明确提示「上一个任务
还在进行,或按 c 取消」,并且**保留**审批;
3. **App 本体的锚点不存在**:`.app` 条目过去复用 `default_anchors()`,而那份锚点表里根本没有
`/Applications`——它是「squid 被允许进去打扫的文件夹」清单,应用程序目录不是。于是每个卸载计划都是
批准 6 项、删除 5 项,`.app` 带着「outside every declared cleanup anchor」被跳过。现在
`bundle_anchors()` 取 bundle 的**父目录**作为锚点,既最小又不越权;
4. **非 root 走不到 `/Applications`**:`user_only()` 的家目录规则把系统 App 一律拒绝。见上面的
`OUTSIDE_HOME_OK`。
同一次排查还修了 Plan 视图的一个隐性错位:它用 `index == 0` 认定第一行是「应用本体」,而
`build_plan` 是按体积降序排序的——一旦某个容器比 App 大,就有一项残留被藏进表头、下面每行都错一位。
现在按 `rule_id == "uninstall-bundle"` 识别,行与光标严格一一对应。
教训写进断言里:`the_bundle_itself_passes_the_safety_policy`、
`a_plain_user_can_still_uninstall_into_applications`、`a_busy_app_answers_instead_of_ignoring_you`、
`the_plan_view_shows_the_bundle_and_every_leftover`(后者读回测试缓冲区:三项计划必须画出三个勾选行、
表头文案不得占据其中任何一行、加粗的那一行永远是 `.app`、光标落在哪一行就高亮哪一行)。
删除路径的测试必须把沙盒建在**真实形态**的位置上:早先的卸载测试把假 App 放在 `~/Library/Caches/…` 下,
正好落在锚点里,所以这个 bug 一路绿灯。
## 数据流
```
config.toml ─┐
├─► Engine{platform, settings, rules, safety, whitelist}
rules/*.toml ┘ │
├── scan() ─► Vec<CleanupItem> ─► CLI 表格 / TUI 面板
│ │ 用户勾选
│ ▼
└── delete::execute(DeleteJob) ─► SafetyPolicy 复检
│ fs::remove_item_with
│ ledger::write_session
▼
~/Library/Application Support/squid/history/<session>.json
│
squid undo ─► ledger::restore ─► rename 回原路径
```
## 性能
体积测量是这类工具唯一的重活。做法:`walkdir`(`contents_first(false)`、`max_open(64)`、跳过符号链接)单目录内顺序遍历,`measure_all` 在条目之间用 rayon 并行(线程数 `clamp(4,16)`),每完成一个条目就发一次进度事件,所以 UI 的进度条是真实进度而不是假动画。`purge` 用 `max_entries` 限制单项目文件数、`MAX_DIRS` 限制总目录数,超限时明确标注结果是下限。实测 `clean --dry-run` 在 18 万条目 / 30 GB 量级上约 5 秒。
## 跨平台移植指南
新增一个平台 = 实现 `Platform` + 提供规则文件,**引擎与 UI 一行都不用改**。
1. 新建 `squid-platform/src/<os>.rs`,实现 `Platform`;在 `lib.rs::current()` 里返回它。
2. 决定 `app_sources()` 与 `leftover_roots()`:命名方式(bundle id / 名称 / 容器)决定残留匹配器怎么配。
3. 补 `safety::HARD_DENY` / `DENY_EXACT` 里该系统的禁区(Windows:`C:\Windows`、`C:\Program Files`;Linux:`/snap`、`/nix`、`/var/lib`)。
4. 新增 `crates/squid-rules/rules/<os>.toml`,并在 `RuleSet::builtins()` 里 `include_str!`。规则里的 `os = [...]` 字段决定它在哪个平台生效。
5. 回收站语义:`fs::trash_target_for` 需要该系统的回收站位置与命名规则(macOS 是 `~/.Trash` 与卷根 `.Trashes/<uid>`;Linux 是 XDG `~/.local/share/Trash/files`;Windows 需要 `$Recycle.Bin` 或 Shell API)。
6. 提权:macOS/Linux 用 `sudo` 重跑(`needs_admin` 的规则在非 root 时只报告不执行);Windows 需要 UAC。
现状:macOS 完整;Linux 有 `.desktop`/Flatpak/Snap 与 XDG 残留实现,缺规则文件与真机验证;Windows 是占位实现。
## 测试策略
86 个测试(`cargo test --workspace`)。三类:
- **纯逻辑**:字节格式化、glob 与锚点、规则解析、名称匹配、安全策略拒绝表 —— 这些是最有价值的,因为它们把「曾经出过的事故」变成断言。
- **引擎级**:在临时目录 / `~/Library/Caches/squid-delete-test-*` 里搭沙盒,跑真实 scan + delete。
- **状态隔离**:删除类测试必须调用 `isolate_state()`,用 `SQUID_STATE_DIR` 把账本重定向到临时目录,否则测试会话会污染用户真实的 `squid history`。
约定:CI 门禁是 `cargo clippy --workspace --all-targets -- -D warnings` + `cargo test --workspace --no-fail-fast`。任何删除相关改动必须同时提供 Trash 往返(delete → undo → 字节一致)测试。
### 确认框背后的不变量:`Approval` 枚举
TUI 的「按 d → 确认 → 执行」曾经出过一次典型的静默失败:`App` 上有两个平行字段
`pending: Option<Vec<CleanupItem>>` 与 `pending_plan: Option<UninstallPlan>`,卸载流程只写了
后者对应的读逻辑,`pending_plan` 从来没被赋成 `Some`,于是 `confirm_delete()` 里
`let Some(plan) = self.pending_plan.take() else { return }` 直接返回——用户按了回车,什么也没发生,
什么也没说。
修复方式不是补一行赋值,而是让非法状态无法表达:两个字段合并成
`pending: Option<Approval>`,`Approval` 是 `Items { items, purge } | Plan(UninstallPlan) |
UndoSession(String)` 三个变体。`ask_delete()` 必须构造其中一个才能打开确认框;确认框能打开,
就必然有可执行的内容。`confirm_delete()` 对 `None` 的情况显式 toast「没有待确认的内容,请重新按 d」,
把「静默」变成「可见」。`app.rs` 里那三个回归测试直接驱动 `ask_delete() → confirm_delete() → poll()`
到任务结束,断言 `outcome.summary.removed == N`,覆盖卸载、清理/深度清理、以及空确认框三条路径。
## 关于 Mole(GPL v3)的边界
仓库根目录的 `Mole/` 是 GPL v3 的参考实现,已写入 `.gitignore`。squid 是净室实现:
- 没有任何一行 Rust 代码来自 Mole(Mole 也不是 Rust 写的);
- 参考的是**行为**:哪些路径值得清理、哪些目录是雷区、卸载残留该去哪儿找;
- 规则表是本项目的 `macos.toml`,模式与文案均为本仓库独立编写;
- 分发 squid(MIT OR Apache-2.0)时不携带、不链接 GPL 代码。

64
docs/SECURITY.md 100644
View File

@ -0,0 +1,64 @@
# 安全说明
squid 是一个「以删除为职责、以不删错为底线」的工具。它拥有当前用户的完整文件权限,因此威胁模型与普通的 CLI 不同:**最大的风险不是被攻击,而是它自己删错东西。**
## 权限边界
- squid 以当前用户身份运行,**不需要** root,也不安装任何 launch agent / 服务 / 内核扩展。
- 非 root 时 `SafetyPolicy::user_only()` 生效,家目录之外的路径一律不删除;只有显式用管理员权限运行时才切换到 `SafetyPolicy::system()`。
- 需要管理员权限的规则(`needs_admin`)在普通权限下只报告、不执行;`squid clean --user-only` 可以彻底跳过它们。
- 不联网:`Cargo.toml` 的依赖树里没有 HTTP 客户端,squid 不上传任何遥测、路径或文件名。
## Full Disk Access(macOS)
`~/Library/Safari`、`~/Library/Mail`、`~/Library/Messages` 等目录受 TCC 保护。终端未授权时,squid 只会读不到、跳过它们,不会报错崩溃。`squid doctor` 会列出被拒绝的目录。若希望这些规则真正命中,请在 系统设置 → 隐私与安全性 → 完整磁盘访问权限 中勾选你运行 squid 的终端。
注意:**授权 Full Disk Access 增加的是读取能力,不是删除范围**——上面那张安全表(`HARD_DENY`/`DENY_EXACT`/锚点)在任何权限级别下都同样生效。
## 删除的多重防线
1. 默认 `Trash`:删除等于 `rename` 到回收站,`squid undo` 可以还原。
2. `--dry-run`:所有破坏性命令都支持。
3. 非交互确认:stdin 不是 TTY 且没有 `-y/--yes` 时直接拒绝执行删除(保护 CI 与 `curl | sh` 式误用)。
4. 删除时二次校验:不复用扫描结论,逐条重新检查锁、白名单、安全策略与锚点。
5. 永不跟随符号链接:`walkdir::follow_links(false)` + `symlink_metadata` 判定类型,避免把「指向 `~/Documents` 的软链接」当成缓存删掉。
6. 账本:每次真实删除写一个会话文件(含每条的原始路径与废纸篓目标),`history_keep` 控制保留数量。
7. 白名单:`squid whitelist add <glob>` 之后该路径在任何面板中都不再被选中。
## 用户输入与外部数据
- **配置文件与规则文件按 TOML 解析,绝不当作代码执行。** 解析失败时降级为默认值,错误通过 `squid doctor` / 引擎的 `settings_errors` 报告,不会 panic。
- 规则模式经 `globset` 编译,`*` 不跨越路径分隔符;`~` 只在家目录下展开。
- 卸载残留的名称匹配区分大小写归一化,且显式排除了文档后缀(`.pdf`、`.png`、`.mp3`…),避免把用户文档当成 App 残留。
- 外部命令一律用 `Command::new(program).args([...])` 直接传参,**不经过 shell**,参数也不来自不可信输入,因此不存在命令注入面。清单如下:
| 命令 | 用途 | 是否修改系统 |
| --- | --- | --- |
| `sw_vers`、`sysctl`、`ps`、`df`、`diskutil`、`pmset`、`ioreg`、`vm_stat`、`tmutil list` | 系统信息与体积探测 | 否,只读 |
| `open`、`xdg-open`、`explorer` | 打开废纸篓 / 在访达中显示 | 否 |
| `git check-ignore`、`git ls-files`、`tmutil listlocalsnapshots` | 判断构建产物是否被 git 忽略(被跟踪的文件绝不删除)、列举 APFS 本地快照 | 否 |
| `launchctl`、`lsregister` | 卸载前停掉 App 的 launchd 任务、注销 Launch Services 注册 | 是,仅 `squid uninstall` 确认之后 |
| `brew uninstall --cask --force` | App 由 Homebrew 安装时优先交给 brew 处理 | 是,仅 `squid uninstall` 确认之后,且只在检测到对应 cask 时 |
| `flatpak` / `snap` | Linux 应用清单与卸载建议 | 清单只读;卸载建议以提示形式给出 |
## 什么不属于安全问题
- 规则没有覆盖到某个 App 的缓存 → 功能缺口,开 issue 即可。
- 磁盘空间没有你预期释放得多 → 可能是 APFS 快照或 purge 的年龄过滤,先用 `squid analyze` 对照。
- 需要 Full Disk Access 才能读到的目录 → macOS 的限制,见上。
## 报告漏洞
如果你发现 squid **可能删除用户未主动选择的数据**(例如某条规则在默认配置下选中了 `~/Documents`、锚点校验可被绕过、`undo` 覆盖已有文件),请视为安全问题:
- 通过仓库的 private issue / security contact 私下披露;
- 附上最小复现(哪个命令、哪个规则 id、哪个路径);
- **先跑 `--dry-run` 采集证据**,不要提供真实删除的日志。
我们会在修复版本发布后再公开细节。
## 你自己的责任
- squid 不是备份工具。重要数据请依赖 Time Machine 或对象存储。
- `--permanent` 跳过回收站,`undo` 也救不回来;除非你确切知道自己在做什么,否则不要用。
- 自定义规则里 `mode = "contents"` 会清空目录内容,`patterns` 只写一个字面目录(例如 `~/Library`)会被安全策略拒绝——如果你绕过或删除了 `crates/squid-core/src/safety.rs` 的守卫,squid 就不再保护你。

View File

@ -0,0 +1,39 @@
# Homebrew formula 模板。把整个文件放进你自己的 tap 仓库:
#
# brew tap yourname/homebrew-tools https://github.com/yourname/homebrew-tools
# brew install yourname/tools/squid
#
# 发布流程见 scripts/release.sh —— 它打出 tar.gz 并给出 sha256,填进下面两处
# 占位符即可。通用二进制(arm64 + x86_64)让同一个包在 Apple Silicon 和
# Intel 上都能装,bottle 交给 `brew tap-new` 的 CI 去做。
class Squid < Formula
desc "Clean, uninstall, purge and watch a Mac from the terminal"
homepage "https://github.com/nexdev/squid"
version "0.1.0"
sha256 "REPLACE_WITH_DIST_SQUID_TARBALL_SHA256"
url "https://github.com/nexdev/squid/releases/download/v#{version}/squid-#{version}-universal-apple-darwin.tar.gz"
license "MIT OR Apache-2.0"
# 也可以直接从源码装(不需要预先发 release):
# depends_on "rust" => :build
# def install
# system "cargo", "install", "--locked", "--root", prefix, "--path", "crates/squid-cli"
# end
# 但那条路要求 tap 指向 git 仓库,而且每次 brew bump 都要重新编译。
def install
bin.install "squid-#{version}-universal-apple-darwin/squid" => "squid"
generate_completions_from_executable(bin, "squid")
end
def caveats
<<~EOS
#{bin}/squid 已经在 PATH 上,直接 `squid` 打开界面。
它不会安装任何后台进程,也不会改你的 shell 配置。
EOS
end
test do
assert_match version.to_s, shell_output("#{bin}/squid --version")
end
end

View File

@ -0,0 +1,3 @@
[toolchain]
channel = "stable"
components = ["rustfmt", "clippy"]

60
scripts/install.sh 100755
View File

@ -0,0 +1,60 @@
#!/usr/bin/env bash
# 把 squid 装进 PATH,并处理 macOS 的隔离属性。
#
# ./scripts/install.sh # 用 cargo build --release 的产物
# ./scripts/install.sh ./dist/squid # 装一个已经下载/构建好的二进制
# PREFIX=~/.local/bin ./scripts/install.sh # 装到自己目录(不需要 sudo)
#
# 装完之后 `squid` 就是一条 PATH 里的普通命令 —— 装到 /usr/local/bin 或
# /opt/homebrew/bin 这种本来就在 PATH 上的目录,不需要再改 shell 配置。
set -euo pipefail
cd "$(dirname "$0")/.."
NAME=squid
BIN=${1:-target/release/$NAME}
pick_prefix() {
if [ -n "${PREFIX:-}" ]; then
printf '%s' "$PREFIX"
elif [ -w /opt/homebrew/bin ]; then
printf '%s' /opt/homebrew/bin
elif [ -w /usr/local/bin ]; then
printf '%s' /usr/local/bin
else
printf '%s' "$HOME/.local/bin"
fi
}
if [ ! -x "$BIN" ]; then
printf '\033[1;36m==>\033[0m 没有 %s,先构建\n' "$BIN"
cargo build --release -p squid-cli
fi
PREFIX_DIR="$(pick_prefix)"
if [ ! -w "$PREFIX_DIR" ] && [ ! -e "$PREFIX_DIR" ]; then
mkdir -p "$PREFIX_DIR"
fi
TARGET="$PREFIX_DIR/$NAME"
if [ ! -w "$PREFIX_DIR" ]; then
printf '\033[1;33m提示:\033[0m %s 不可写,用 sudo 装一次(不会装守护进程)\n' "$PREFIX_DIR"
sudo install -m 0755 "$BIN" "$TARGET"
else
install -m 0755 "$BIN" "$TARGET"
fi
# 从浏览器/网络拿到的文件带 com.apple.quarantine,Gatekeeper 会拦一下。
# 自己 curl 下来的 release 包同理,清掉它等价于「我知道这是我自己的二进制」。
xattr -d com.apple.quarantine "$TARGET" 2>/dev/null || true
if [ "$(uname -m)" = arm64 ]; then
codesign --force --sign - "$TARGET" >/dev/null 2>&1 || true
fi
printf '\033[1;32m已安装\033[0m %s\n' "$TARGET"
"$TARGET" --version || true
case ":$PATH:" in
*":$PREFIX_DIR:"*) ;;
*)
printf '\033[1;33m注意:\033[0m %s 不在 PATH 里,把这一行加到 ~/.zshrc:\n' "$PREFIX_DIR"
printf ' export PATH="%s:$PATH"\n' "$PREFIX_DIR"
;;
esac

70
scripts/release.sh 100755
View File

@ -0,0 +1,70 @@
#!/usr/bin/env bash
# 打一个可发布的 squid 包:macOS 通用二进制 + tar.gz + sha256。
#
# ./scripts/release.sh # arm64 + x86_64,产物在 dist/
# ARCHES="aarch64-apple-darwin" ./scripts/release.sh # 只出当前芯片的包
#
# 为什么不是 .dmg:TUI/CLI 没有 .app bundle,拖进 Applications 的那套东西
# (图标、LaunchServices、Gatekeeper 授权)对它毫无意义,反而多一次「已损坏,
# 无法打开」的隔离属性摩擦。一个 tar.gz + 一行 curl 安装脚本对终端程序更诚实,
# 也是 cargo-binstall / Homebrew 期望的形状。
set -euo pipefail
cd "$(dirname "$0")/.."
ROOT="$(pwd)"
NAME=squid
VERSION="$(sed -n 's/^version = "\([^"]*\)"/\1/p' Cargo.toml | head -1)"
ARCHES=${ARCHES:-"aarch64-apple-darwin x86_64-apple-darwin"}
DIST="$ROOT/dist"
SLUG="$NAME-$VERSION-universal-apple-darwin"
say() { printf '\033[1;36m==>\033[0m %s\n' "$*"; }
die() { printf '\033[1;31merror:\033[0m %s\n' "$*" >&2; exit 1; }
command -v cargo >/dev/null || die "cargo 不在 PATH 里(source ~/.cargo/env)"
[ "$(uname)" = Darwin ] || die "通用二进制只在 macOS 上打"
BINARIES=()
for target in $ARCHES; do
if ! rustup target list --installed 2>/dev/null | grep -qx "$target"; then
say "rustup target add $target"
rustup target add "$target"
fi
say "cargo build --release --target $target"
cargo build --release --target "$target" -p squid-cli
BINARIES+=("target/$target/release/$NAME")
done
mkdir -p "$DIST"
BIN="$DIST/$NAME"
if [ "${#BINARIES[@]}" -gt 1 ]; then
say "lipo -create (${BINARIES[*]})"
lipo -create "${BINARIES[@]}" -output "$BIN"
else
cp "${BINARIES[0]}" "$BIN"
SLUG="$NAME-$VERSION-$(basename "$(dirname "$(dirname "${BINARIES[0]}")")")"
fi
chmod 0755 "$BIN"
# arm64 要求所有可执行文件至少有一个签名。ad-hoc 签名对本机足够;要发给别人
# 需要 Developer ID + 公证(notarytool),见 docs 里的说明。
say "codesign --sign - (ad-hoc)"
codesign --force --sign - --timestamp=none "$BIN" >/dev/null
say "squid --version: $("$BIN" --version)"
lipo -archs "$BIN" | sed 's/^/ architectures: /'
TARBALL="$SLUG.tar.gz"
STAGING="$(mktemp -d)"
mkdir -p "$STAGING/$SLUG"
cp "$BIN" "$STAGING/$SLUG/"
cp LICENSE LICENSE-MIT LICENSE-APACHE README.md "$STAGING/$SLUG/" 2>/dev/null || true
tar -C "$STAGING" -czf "$DIST/$TARBALL" "$SLUG"
rm -rf "$STAGING"
( cd "$DIST" && shasum -a 256 "$TARBALL" > "$TARBALL.sha256" )
say "产物"
ls -lh "$DIST/$TARBALL" "$DIST/$TARBALL.sha256"
cat "$DIST/$TARBALL.sha256"
printf '\n把这个 sha256 填进 packaging/homebrew/squid.rb,然后:\n'
printf ' gh release create v%s dist/%s dist/%s.sha256\n' "$VERSION" "$TARBALL" "$TARBALL"

View File

@ -0,0 +1,646 @@
#!/usr/bin/env python3
"""Drive the squid TUI through a real pty and assert on what the screen shows.
The unit tests in `squid-tui` can prove that `handle_key` mutates the right
field; they cannot prove that the user *sees* it. Every bug this script guards
against lived in that gap: a key that moved a cursor no renderer drew, an
interface that kept showing a finished job's progress bar, a palette that asked
a terminal for 24-bit colour it cannot parse, and an `esc` that was swallowed
by the very level it was supposed to leave.
Scenarios:
menu the interface *opens* on the six functions; the keyboard model
mono the same model with NO_COLOR set (the cursor inverts instead)
colors the truecolour probe, the 256-colour fallback, the grey cursor
bar that palette buys instead of an accent, and `SQUID_TRUECOLOR`
escape `esc` walks back exactly one level, in every level there is
uninstall two apps back to back - the second must not be refused
all every scenario (default)
Requires `pyte` (`python3 -m pip install --user pyte`). Run it against a built
binary:
cargo build --release
python3 scripts/tui_smoke.py all target/release/squid
The app scenarios make their own throwaway bundles in `~/Applications` and
delete them again; they never touch a real application.
"""
import os
import pty
import re
import select
import shutil
import struct
import subprocess
import sys
import tempfile
import time
import fcntl
import termios
try:
import pyte
except ImportError: # pragma: no cover - the message is the point
sys.exit("pyte is required: python3 -m pip install --user pyte")
KEYS = {
"Enter": "\r", "Esc": "\x1b", "Tab": "\t", "BS": "\x7f", "Space": " ",
"Up": "\x1b[A", "Down": "\x1b[B", "Right": "\x1b[C", "Left": "\x1b[D",
"SUp": "\x1b[1;2A", "SDown": "\x1b[1;2B",
"MUp": "\x1b[1;3A", "MDown": "\x1b[1;3B", "MLeft": "\x1b[1;3D", "MRight": "\x1b[1;3C",
"CUp": "\x1b[1;5A", "CDown": "\x1b[1;5B",
"PgDn": "\x1b[6~", "PgUp": "\x1b[5~", "Home": "\x1b[H", "End": "\x1b[F",
}
CONFIG = 'delete_mode = "permanent"\nlanguage = "zh"\n'
class TUI:
"""A squid process attached to a pty, plus the screen it has painted."""
def __init__(self, argv, env=None, cols=112, rows=32, term="xterm-256color"):
self.master, slave = pty.openpty()
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
e = dict(os.environ)
# A CI shell often exports NO_COLOR; colour, and the colourless cursor
# that replaces it, are what some of these scenarios are about.
for key in ("NO_COLOR", "CLICOLOR", "CLICOLOR_FORCE", "FORCE_COLOR"):
e.pop(key, None)
e.update({"TERM": term, "LANG": "zh_CN.UTF-8", "COLORTERM": "", "TERM_PROGRAM": "ghostty"})
if env:
e.update(env)
self.proc = subprocess.Popen(argv, stdin=slave, stdout=slave, stderr=slave,
env=e, close_fds=True)
os.close(slave)
self.screen = pyte.Screen(cols, rows)
self.stream = pyte.ByteStream(self.screen)
self.raw = bytearray()
self.cols, self.rows = cols, rows
self.alive = True
def pump(self, until=0.0):
end = time.time() + until
while True:
r, _, _ = select.select([self.master], [], [], 0.05)
if r:
try:
data = os.read(self.master, 65536)
except OSError:
self.alive = False
return
if not data:
self.alive = False
return
self.raw += data
self.stream.feed(data)
if time.time() >= end:
return
def send(self, *tokens, delay=0.12):
for tok in tokens:
os.write(self.master, KEYS.get(tok, tok).encode())
self.pump(delay)
def text(self):
return "\n".join(line.rstrip() for line in self.screen.display)
def show(self, label=""):
print(f"\n===== {label} =====")
print(self.text())
print("===== end =====")
def wait(self, pattern, timeout=25.0, label=""):
rx = re.compile(pattern)
end = time.time() + timeout
while time.time() < end:
self.pump(0.2)
if rx.search(self.text()):
return True
print(f"[MISS] pattern {pattern!r} after {timeout}s {label}")
self.show(f"miss {pattern}")
return False
def refute(self, pattern, window=1.5, label=""):
"""Assert the pattern does NOT appear during `window` seconds."""
rx = re.compile(pattern)
end = time.time() + window
while time.time() < end:
self.pump(0.2)
m = rx.search(self.text())
if m:
print(f"[FAIL] forbidden pattern {pattern!r} matched {m.group(0)!r} {label}")
self.show(f"forbidden {pattern}")
return False
return True
def snapshot(self):
"""(text, style) per row. Style is what a cursor paints, not the glyphs."""
texts, styles = [], []
for y in range(self.rows):
line = self.screen.buffer[y]
cells = [line[x] for x in range(self.cols)]
texts.append("".join(c.data or " " for c in cells).rstrip())
styles.append(tuple((c.bg, c.fg, c.bold, c.reverse) for c in cells))
return texts, styles
def moved_rows(self, before, after):
"""Rows that changed colour while their text stayed put — the cursor."""
bt, bs = before
at, as_ = after
return [y for y in range(self.rows) if bt[y] == at[y] and bs[y] != as_[y]]
def quit(self):
try:
self.send("q", delay=0.4)
except Exception:
pass
self.proc.terminate()
try:
self.proc.wait(3)
except subprocess.TimeoutExpired:
self.proc.kill()
os.close(self.master)
def sandbox():
"""Keep a smoke run out of the user's real settings and ledger."""
cfg = tempfile.mkdtemp(prefix="squid-smoke-cfg-")
state = tempfile.mkdtemp(prefix="squid-smoke-state-")
open(os.path.join(cfg, "config.toml"), "w").write(CONFIG)
return {"SQUID_CONFIG_DIR": cfg, "SQUID_STATE_DIR": state}
def make_app(name, bundle_id, size_kb=64):
"""A throwaway bundle with the leftovers squid is expected to find."""
home = os.path.expanduser("~")
app = os.path.join(home, "Applications", name + ".app", "Contents")
os.makedirs(os.path.join(app, "MacOS"), exist_ok=True)
with open(os.path.join(app, "Info.plist"), "w") as f:
f.write(f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleIdentifier</key><string>{bundle_id}</string>
<key>CFBundleName</key><string>{name}</string>
<key>CFBundleExecutable</key><string>{name}</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>1.0</string>
</dict></plist>
""")
with open(os.path.join(app, "MacOS", name), "w") as f:
f.write("#!/bin/sh\nexit 0\n")
os.chmod(os.path.join(app, "MacOS", name), 0o755)
for folder in ("Application Support", "Caches"):
path = os.path.join(home, "Library", folder, bundle_id)
os.makedirs(path, exist_ok=True)
with open(os.path.join(path, "blob"), "wb") as f:
f.write(os.urandom(size_kb * 1024))
open(os.path.join(home, "Library", "Preferences", bundle_id + ".plist"), "w").write("{}")
# ------------------------------------------------------------- what is on screen
def rgb(colour):
"""pyte reports a cell colour as hex text, a palette name, or `default`."""
if colour and re.fullmatch(r"[0-9a-f]{6}", colour):
return tuple(int(colour[i:i + 2], 16) for i in (0, 2, 4))
return None
def is_grey(colour, floor=0):
"""A colour with no hue at all — the whole point of the 256-colour cursor."""
values = rgb(colour)
return bool(values) and values[0] == values[1] == values[2] and values[0] >= floor
def is_accent(colour):
"""Blue enough to be the accent bar, and not the slightly-blue card."""
values = rgb(colour)
return bool(values) and values[2] > values[0] + 0x20
def say(text):
"""A pattern for a label, tolerant of how the interface lays CJK out.
A wide glyph is padded to land on an even column, so a label in a fixed
width cell can reach the screen as 「卸 载」 rather than 「卸载」. Matching
the literal string would make the scenario depend on where on the line the
label happens to start.
"""
return r"\s*".join(re.escape(ch) for ch in text)
def app_rows(texts, needle):
"""The screen rows that list an application, ignoring the filter echo."""
return [y for y, text in enumerate(texts) if needle in text and "筛" not in text]
def wears_cursor(t, row, mode):
"""Does this row wear the highlight in `mode`?
A data row always wears *some* background — the list alternates so a wide
row can be followed across the card — so "lit" is never "has a colour". It
is the accent bar in a 24-bit terminal, the *light* grey bar in a 256-colour
one (the card and its band are dark greys), and reverse video where there is
no palette at all. Those three are the three palettes `squid` picks between.
"""
_, styles = t.snapshot()
look = styles[row]
if mode == "mono":
return any(style[3] for style in look)
backgrounds = [style[0] for style in look]
if mode == "truecolor":
return any(is_accent(colour) for colour in backgrounds)
return any(is_grey(colour, 0x80) for colour in backgrounds)
def row_bgs(t, needle):
"""The backgrounds painted on the data row naming `needle`."""
texts, styles = t.snapshot()
for y in app_rows(texts, needle):
return set(style[0] for style in styles[y] if style[0] != "default")
return None
def wait_gone(t, pattern, timeout=300):
"""Wait for a phrase to leave the screen — a scan finishing on its own.
The disk map is a real walk of a real home folder: measured on a 201 GB /
2.1M-inode volume it takes 166s, so a two-minute budget fails on a busy
machine while the interface is doing nothing wrong.
"""
rx = re.compile(pattern)
end = time.time() + timeout
while time.time() < end:
t.pump(0.3)
if not rx.search(t.text()):
return True
print(f"[MISS] {pattern!r} still on screen after {timeout}s")
return False
def fixture_apps():
"""Two throwaway bundles: a list that is never empty, whatever else is installed."""
fixtures = [("SquidSmokeA", "com.squid.smoke-alpha"),
("SquidSmokeB", "com.squid.smoke-beta")]
for name, bundle in fixtures:
make_app(name, bundle)
return fixtures
def remove_apps(fixtures):
home = os.path.expanduser("~")
for name, bundle in fixtures:
shutil.rmtree(os.path.join(home, "Applications", name + ".app"), ignore_errors=True)
for folder in ("Application Support", "Caches"):
shutil.rmtree(os.path.join(home, "Library", folder, bundle), ignore_errors=True)
try:
os.remove(os.path.join(home, "Library", "Preferences", bundle + ".plist"))
except OSError:
pass
def list_apps(t, needle="SquidSmoke"):
"""Open the app list and filter it down to the fixtures."""
t.send("2")
if not t.wait(say("个应用") + "|applications found", 90, "app list"):
return False
t.send("f")
t.pump(0.2)
t.send(*(["BS"] * 24), delay=0.02)
t.send(needle, delay=0.3)
t.send("Enter")
t.pump(1.0)
return t.wait(needle, 10, "the filtered list")
# ------------------------------------------------------------------- scenarios
def scenario_menu(binary, extra=None, term="xterm-256color", mode="truecolor", dump=False):
"""The keyboard model, judged on the screen the user is actually looking at.
The first assertion is all of complaint 1: no key has been pressed when it
runs, so it fails the moment the interface opens anywhere but on the six
functions. The last assertion is the other half of the same complaint — the
plain arrows must belong to the list again once the choosing is done.
"""
env = sandbox()
env.update(extra or {})
fixtures = fixture_apps()
t = TUI([binary, "state"], env=env, term=term)
ok = True
try:
t.wait("squid", 15, "startup")
# 1. nothing typed at all: the arrows already point at the functions
ok &= t.wait(r"\[1\]", 8, "the interface opens on the function menu")
ok &= t.wait(say("选择功能") + "|up and down to choose", 8, "the hint bar says so too")
if dump:
t.show("startup focus")
# 2. the plain arrows walk the six functions and clamp at the ends
t.send("Down")
ok &= t.wait(r"\[2\]", 8, "arrow down -> row 2")
ok &= t.wait(say("卸载"), 8, "panel switched to the uninstall list")
t.send("Down")
ok &= t.wait(r"\[3\]", 8, "arrow down -> row 3")
t.send("Up")
t.send("Up")
ok &= t.wait(r"\[1\]", 8, "arrow up walks back")
t.send("Up")
ok &= t.refute(r"\[0\]|\[7\]", 1.0, "clamped at the ends")
# 3. enter hands the keys to the list, esc hands them back
t.send("Enter", delay=0.4)
ok &= t.refute(r"\[1\]", 1.0, "the badge is gone after enter")
t.send("Esc", delay=0.4)
ok &= t.wait(r"\[1\]", 8, "esc hands the arrows back to the menu")
# 4. option/control + arrows switch functions from anywhere
t.send("MDown", delay=0.5)
ok &= t.wait(say("卸载"), 8, "alt+down switched function")
t.send("MUp", delay=0.5)
ok &= t.wait(say("清理"), 8, "alt+up switched back")
t.send("CDown", delay=0.5)
ok &= t.wait(say("卸载"), 8, "ctrl+down switched too")
# 5. and the plain arrows still scroll the list
ok &= list_apps(t)
t.send("Home")
t.pump(0.6)
before = t.snapshot()
rows = app_rows(before[0], "SquidSmoke")
if len(rows) != 2:
print(f"[FAIL] expected two app rows, found {rows}")
t.show("list rows")
ok = False
else:
top, bottom = rows
started = wears_cursor(t, top, mode)
t.send("Down")
t.pump(0.8)
moved = t.moved_rows(before, t.snapshot())
walked = wears_cursor(t, bottom, mode) and not wears_cursor(t, top, mode)
print(f"[{'OK' if started and walked else 'FAIL'}] the arrow walked the "
f"cursor ({mode}): row {top} -> row {bottom}, repainted {moved}")
ok = started and walked and ok
if dump:
t.show("plain arrows still scroll")
finally:
t.quit()
remove_apps(fixtures)
print(f"[{'OK' if ok else 'FAIL'}] menu/arrows scenario ({term}, {mode})")
return ok
def scenario_mono(binary):
"""`NO_COLOR` is a request, not a joke: the cursor has to survive without it."""
return scenario_menu(binary, extra={"NO_COLOR": "1"}, mode="mono")
def scenario_colors(binary, dump=False):
"""Complaint 2 and 3: the probe at start-up, and what each palette draws.
The assertions are on the bytes the interface *sends*, because that is the
difference the user can see: a terminal that is handed `48;2;r;g;b` without
understanding it prints the numbers as text.
"""
cases = [
("Apple Terminal", {"COLORTERM": "", "TERM_PROGRAM": "Apple_Terminal"}, "256"),
("iTerm2", {"COLORTERM": "truecolor", "TERM_PROGRAM": "iTerm.app"}, "truecolor"),
("bare ssh", {"COLORTERM": "truecolor", "TERM_PROGRAM": ""}, "truecolor"),
("TERM says nothing", {"COLORTERM": "", "TERM_PROGRAM": ""}, "256"),
("SQUID_TRUECOLOR=never", {"COLORTERM": "truecolor", "SQUID_TRUECOLOR": "never"}, "256"),
("NO_COLOR", {"NO_COLOR": "1"}, "mono"),
]
fixtures = fixture_apps()
ok = True
try:
for label, extra, wanted in cases:
env = sandbox()
env.update(extra)
t = TUI([binary, "state"], env=env)
try:
t.wait("squid", 15, "startup")
ok &= list_apps(t)
t.send("Home")
t.pump(0.6)
sent_truecolour = b"48;2;" in t.raw or b"38;2;" in t.raw
sent_indexed = b"48;5;" in t.raw or b"38;5;" in t.raw
t.send("?")
t.pump(0.8)
probe = t.wait(say("色彩") + "|Colour", 8, "the help overlay names the palette")
stated = {"256": r"256 colors", "truecolor": r"truecolor",
"mono": r"no colour"}[wanted]
named = bool(re.search(stated, t.text()))
t.send("Esc")
t.pump(0.4)
rows = app_rows(t.snapshot()[0], "SquidSmoke")
cursor = wears_cursor(t, rows[0], wanted) if rows else False
# the cursor sits on the first row: Home was just pressed
bar = row_bgs(t, "SquidSmokeA") or set()
checks = {
"truecolor": sent_truecolour and not sent_indexed,
"256": sent_indexed and not sent_truecolour,
"mono": not sent_truecolour and not sent_indexed,
}[wanted]
good = checks and probe and named and cursor
print(f"[{'OK' if good else 'FAIL'}] {label:22s} -> {wanted:11s} "
f"truecolour_bytes={sent_truecolour} indexed={sent_indexed} "
f"overlay={named} cursor={cursor}")
if wanted == "256":
greys = [c for c in bar if is_grey(c, 0x80)]
loud = [c for c in bar if is_accent(c)]
print(f" cursor bar: grey={greys} accent={loud}")
good = good and bool(greys) and not loud
if wanted == "truecolor":
accents = [c for c in bar if is_accent(c)]
print(f" cursor bar: accent={accents}")
good = good and bool(accents)
if wanted == "mono":
print(f" cursor bar: no backgrounds at all = {not bar}")
good = good and not bar
if not good and dump:
t.show(label)
ok = ok and good
finally:
t.quit()
finally:
remove_apps(fixtures)
print(f"[{'OK' if ok else 'FAIL'}] colour probe scenario")
return ok
def scenario_escape(binary, dump=False):
"""Complaint 4: every level a key walks into, `esc` walks out of again.
The levels are the ones that used to answer nothing: the second level of
the app list (the leftover plan), the confirmation that a delete is what
the user really wants, the largest-files list and the folder drill of the
disk map, and — the case that used to hang for a whole disk walk — `esc`
while a job is still running.
"""
fixtures = fixture_apps()
t = TUI([binary, "state"], env=sandbox())
ok = True
try:
t.wait("squid", 15, "startup")
assert_start = t.wait(r"\[1\]", 8, "startup focus")
ok &= assert_start
# level 0 — the help overlay is a level too
t.send("?")
t.wait(say("快捷键") + "|shortcuts", 8, "help opened")
t.send("Esc")
ok &= t.refute(say("快捷键") + "|shortcuts", 1.5, "esc closes the help")
# level 1 — the list of applications
ok &= list_apps(t)
t.send("Esc")
ok &= t.wait(r"\[2\]", 8, "esc leaves the list for the menu")
t.send("Enter") # back to the list, cursor on the first app
t.pump(0.4)
# level 2 — the leftovers of one application
t.send("Enter")
ok &= t.wait(r"com\.squid\.smoke-alpha", 30, "the plan opened")
t.send("Esc")
ok &= t.refute(r"com\.squid\.smoke-alpha", 2.5,
"esc leaves the plan, and the plan stays left")
ok &= t.wait(r"SquidSmokeA", 8, "the list is back")
# level 1 again, then level 2, then level 3 — the confirmation
t.send("Enter")
t.send("Enter")
ok &= t.wait(r"com\.squid\.smoke-alpha", 30, "the plan opened again")
t.send("d")
ok &= t.wait(say("回车 / y 确认") + "|enter / y confirm", 15, "the confirmation opened")
t.send("Esc")
ok &= t.refute(say("回车 / y 确认") + "|enter / y confirm", 1.5, "esc cancels the delete")
ok &= t.wait(r"com\.squid\.smoke-alpha", 8, "and lands back in the plan, not on the menu")
t.send("Esc")
ok &= t.refute(r"com\.squid\.smoke-alpha", 2.0, "esc leaves the plan again")
# level 2 of the disk map — a folder, then the files inside it. The
# scan is still running the whole time: a busy panel used to eat `esc`.
t.send("Esc", "4")
ok &= t.wait(r"\[4\]", 8, "the disk map was chosen")
t.send("Enter") # hand the keys back to the panel; the walk carries on
t.pump(1.0)
t.send("Esc")
ok &= t.wait(r"\[4\]", 8, "esc leaves the disk map even while it is scanning")
# the largest-files list is the other third level; it needs the map
# first, so it is checked where the data already is: two esc in a row
# must be two levels, not one and a shrug.
t.send("Enter")
if wait_gone(t, say("正在计算磁盘占用") + "|Mapping your disk"):
t.send("f")
if t.wait(say("最大的文件") + "|Largest files", 90, "the largest-files list opened"):
t.send("Esc")
left = t.refute(say("最大的文件") + "|Largest files", 4.0,
"esc leaves the largest-files list, walking or not")
ok = left and ok
else:
print("[info] the largest-files list never filled in; esc still cancelled it")
ok = t.refute(say("最大的文件") + "|Largest files", 2.0,
"a cancelled scan must not open the list it was asked to drop") and ok
else:
print("[FAIL] the disk map never filled in")
ok = False
finally:
if dump:
t.show("escape scenario")
t.quit()
remove_apps(fixtures)
print(f"[{'OK' if ok else 'FAIL'}] esc walks back scenario")
return ok
def scenario_uninstall(binary):
"""Two apps in a row. The classic failure is the second one answering
"the previous task is still running" — a background disk map used to hold
the whole interface hostage — or the first one's gauge never going away."""
home = os.path.expanduser("~")
fixtures = [("SquidSmokeA", "com.squid.smoke-alpha"), ("SquidSmokeB", "com.squid.smoke-beta")]
for name, bundle in fixtures:
make_app(name, bundle)
t = TUI([binary, "state"], env=sandbox())
ok = True
try:
t.wait("squid", 15, "startup")
t.send("4") # look at the disk map first, so the post-delete refresh fires
t.wait("磁盘|storage", 15, "storage panel")
t.send("2")
t.wait(say("个应用") + "|applications found", 90, "app list")
for name, bundle in fixtures:
t.send("f")
t.pump(0.2)
t.send(*(["BS"] * 24), delay=0.02)
t.send(name, delay=0.05)
t.send("Enter")
t.wait(name, 20, f"filter {name}")
t.send("Enter") # build the leftover plan
t.pump(3.0)
t.send("d")
if not t.wait(r"立即|确认|卸载|Uninstall", 15, f"confirm dialog {name}"):
ok = False
break
t.send("Enter")
hit = t.wait(r"已删除|项被跳过|items removed|skipped", 90, f"delete feedback {name}")
refused = not t.refute(r"还在进行|still running", 1.0, "the second delete must not be refused")
stale = not t.refute(r"delete · ", 3.0, "a finished job must not keep its gauge")
gone = not os.path.exists(os.path.join(home, "Applications", name + ".app"))
good = hit and not refused and not stale and gone
print(f"[{'OK' if good else 'FAIL'}] uninstall {name}: "
f"feedback={hit} refused={refused} stale_gauge={stale} removed={gone}")
ok = ok and good
finally:
t.quit()
for name, bundle in fixtures:
shutil.rmtree(os.path.join(home, "Applications", name + ".app"), ignore_errors=True)
for folder in ("Application Support", "Caches"):
shutil.rmtree(os.path.join(home, "Library", folder, bundle), ignore_errors=True)
try:
os.remove(os.path.join(home, "Library", "Preferences", bundle + ".plist"))
except OSError:
pass
print(f"[{'OK' if ok else 'FAIL'}] back-to-back uninstall scenario")
return ok
def main(argv):
known = {"menu": lambda b: scenario_menu(b),
"mono": scenario_mono,
"colors": scenario_colors,
"escape": scenario_escape,
"uninstall": scenario_uninstall}
wanted, binary = [], "target/release/squid"
for arg in argv[1:]:
if arg in known:
wanted.append(arg)
elif arg in ("all", "-a"):
wanted.extend(known)
elif arg.startswith("-"):
sys.exit(f"unknown option: {arg} (scenarios: {', '.join(known)})")
else:
binary = arg
wanted = wanted or list(known)
if not os.path.exists(binary):
sys.exit(f"no such binary: {binary} (cargo build --release first)")
results = {}
for name in wanted:
results[name] = known[name](binary)
for name, ok in results.items():
print(f"{'PASS' if ok else 'FAIL'} {name}")
return 0 if all(results.values()) else 1
if __name__ == "__main__":
sys.exit(main(sys.argv))