From 54585ffc40c2e2b334fc802d6a8ecc6c74985a6c Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Tue, 13 Oct 2026 17:00:50 +0800 Subject: [PATCH] =?UTF-8?q?squid=200.1.0:=20macOS=20=E7=A3=81=E7=9B=98?= =?UTF-8?q?=E6=B8=85=E7=90=86=EF=BC=88CLI=20+=20TUI=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 12 + .gitignore | 55 + Cargo.lock | 1591 +++++++++++ Cargo.toml | 48 + LICENSE | 17 + LICENSE-APACHE | 202 ++ LICENSE-MIT | 21 + README.md | 308 +++ crates/squid-cli/Cargo.toml | 28 + crates/squid-cli/src/main.rs | 1625 ++++++++++++ crates/squid-core/Cargo.toml | 21 + crates/squid-core/src/bytes.rs | 193 ++ crates/squid-core/src/error.rs | 82 + crates/squid-core/src/fs.rs | 569 ++++ crates/squid-core/src/ledger.rs | 233 ++ crates/squid-core/src/lib.rs | 32 + crates/squid-core/src/model.rs | 517 ++++ crates/squid-core/src/paths.rs | 111 + crates/squid-core/src/progress.rs | 194 ++ crates/squid-core/src/safety.rs | 325 +++ crates/squid-core/src/settings.rs | 480 ++++ crates/squid-engine/Cargo.toml | 23 + crates/squid-engine/src/analyze.rs | 432 +++ crates/squid-engine/src/clean.rs | 587 ++++ crates/squid-engine/src/delete.rs | 326 +++ crates/squid-engine/src/lib.rs | 291 ++ crates/squid-engine/src/purge.rs | 757 ++++++ crates/squid-engine/src/uninstall.rs | 598 +++++ crates/squid-platform/Cargo.toml | 19 + crates/squid-platform/src/apps.rs | 169 ++ crates/squid-platform/src/leftovers.rs | 409 +++ crates/squid-platform/src/lib.rs | 238 ++ crates/squid-platform/src/linux.rs | 310 +++ crates/squid-platform/src/macos.rs | 354 +++ crates/squid-platform/src/volumes.rs | 269 ++ crates/squid-platform/src/windows.rs | 175 ++ crates/squid-rules/Cargo.toml | 15 + crates/squid-rules/rules/macos.toml | 475 ++++ crates/squid-rules/src/lib.rs | 784 ++++++ crates/squid-stats/Cargo.toml | 15 + crates/squid-stats/src/battery.rs | 242 ++ crates/squid-stats/src/lib.rs | 788 ++++++ crates/squid-tui/Cargo.toml | 22 + crates/squid-tui/src/app.rs | 3377 ++++++++++++++++++++++++ crates/squid-tui/src/job.rs | 150 ++ crates/squid-tui/src/lib.rs | 113 + crates/squid-tui/src/theme.rs | 1012 +++++++ crates/squid-tui/src/views.rs | 2292 ++++++++++++++++ docs/ARCHITECTURE.md | 258 ++ docs/SECURITY.md | 64 + packaging/homebrew/squid.rb | 39 + rust-toolchain.toml | 3 + scripts/install.sh | 60 + scripts/release.sh | 70 + scripts/tui_smoke.py | 646 +++++ 55 files changed, 22046 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 crates/squid-cli/Cargo.toml create mode 100644 crates/squid-cli/src/main.rs create mode 100644 crates/squid-core/Cargo.toml create mode 100644 crates/squid-core/src/bytes.rs create mode 100644 crates/squid-core/src/error.rs create mode 100644 crates/squid-core/src/fs.rs create mode 100644 crates/squid-core/src/ledger.rs create mode 100644 crates/squid-core/src/lib.rs create mode 100644 crates/squid-core/src/model.rs create mode 100644 crates/squid-core/src/paths.rs create mode 100644 crates/squid-core/src/progress.rs create mode 100644 crates/squid-core/src/safety.rs create mode 100644 crates/squid-core/src/settings.rs create mode 100644 crates/squid-engine/Cargo.toml create mode 100644 crates/squid-engine/src/analyze.rs create mode 100644 crates/squid-engine/src/clean.rs create mode 100644 crates/squid-engine/src/delete.rs create mode 100644 crates/squid-engine/src/lib.rs create mode 100644 crates/squid-engine/src/purge.rs create mode 100644 crates/squid-engine/src/uninstall.rs create mode 100644 crates/squid-platform/Cargo.toml create mode 100644 crates/squid-platform/src/apps.rs create mode 100644 crates/squid-platform/src/leftovers.rs create mode 100644 crates/squid-platform/src/lib.rs create mode 100644 crates/squid-platform/src/linux.rs create mode 100644 crates/squid-platform/src/macos.rs create mode 100644 crates/squid-platform/src/volumes.rs create mode 100644 crates/squid-platform/src/windows.rs create mode 100644 crates/squid-rules/Cargo.toml create mode 100644 crates/squid-rules/rules/macos.toml create mode 100644 crates/squid-rules/src/lib.rs create mode 100644 crates/squid-stats/Cargo.toml create mode 100644 crates/squid-stats/src/battery.rs create mode 100644 crates/squid-stats/src/lib.rs create mode 100644 crates/squid-tui/Cargo.toml create mode 100644 crates/squid-tui/src/app.rs create mode 100644 crates/squid-tui/src/job.rs create mode 100644 crates/squid-tui/src/lib.rs create mode 100644 crates/squid-tui/src/theme.rs create mode 100644 crates/squid-tui/src/views.rs create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/SECURITY.md create mode 100644 packaging/homebrew/squid.rb create mode 100644 rust-toolchain.toml create mode 100755 scripts/install.sh create mode 100755 scripts/release.sh create mode 100644 scripts/tui_smoke.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..58dc26d --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7c0563b --- /dev/null +++ b/.gitignore @@ -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 diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..989e4d5 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1591 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", + "terminal_size", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix 0.38.44", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.8", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.8", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core 0.62.2", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" +dependencies = [ + "darling", + "indoc", + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "plist" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb" +dependencies = [ + "base64", + "indexmap", + "quick-xml", + "serde", + "time", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "squid-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "clap", + "crossterm", + "serde", + "serde_json", + "squid-core", + "squid-engine", + "squid-platform", + "squid-rules", + "squid-stats", + "squid-tui", + "unicode-width 0.2.0", +] + +[[package]] +name = "squid-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "crossbeam-channel", + "dirs", + "globset", + "libc", + "rayon", + "serde", + "serde_json", + "thiserror", + "toml", + "walkdir", +] + +[[package]] +name = "squid-engine" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "crossbeam-channel", + "dirs", + "globset", + "libc", + "rayon", + "serde", + "serde_json", + "squid-core", + "squid-platform", + "squid-rules", + "squid-stats", + "walkdir", +] + +[[package]] +name = "squid-platform" +version = "0.1.0" +dependencies = [ + "dirs", + "libc", + "plist", + "rayon", + "serde", + "squid-core", + "walkdir", +] + +[[package]] +name = "squid-rules" +version = "0.1.0" +dependencies = [ + "globset", + "serde", + "serde_json", + "squid-core", + "squid-platform", + "toml", +] + +[[package]] +name = "squid-stats" +version = "0.1.0" +dependencies = [ + "chrono", + "libc", + "serde", + "squid-core", + "squid-platform", + "sysinfo", +] + +[[package]] +name = "squid-tui" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "crossbeam-channel", + "crossterm", + "ratatui", + "rayon", + "serde_json", + "squid-core", + "squid-engine", + "squid-platform", + "squid-rules", + "squid-stats", + "unicode-width 0.2.0", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01016da373cd8f7ef12624f796309f5c31ba8d646dd08856c02cd741d823c622" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sysinfo" +version = "0.34.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4b93974b3d3aeaa036504b8eefd4c039dced109171c1ae973f1dc63b2c7e4b2" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "windows", +] + +[[package]] +name = "terminal_size" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" +dependencies = [ + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.8", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" +dependencies = [ + "windows-core 0.57.0", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" +dependencies = [ + "windows-implement 0.57.0", + "windows-interface 0.57.0", + "windows-result 0.1.2", + "windows-targets", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link", + "windows-result 0.4.1", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..6b0f61e --- /dev/null +++ b/Cargo.toml @@ -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 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a2a5fde --- /dev/null +++ b/LICENSE @@ -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. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -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. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..556fc43 --- /dev/null +++ b/LICENSE-MIT @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..864eb52 --- /dev/null +++ b/README.md @@ -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 ` `--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 ` | +| `analyze [PATH]` | 单路径体积树 + 最大文件(默认主目录) | `--depth <层>` `--top ` `--files` | +| `history` | 历史会话(时间、命令、释放空间、条目数) | `--limit ` | +| `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 里按 `?` 也有同样的诊断行。 + +自定义规则放到 `/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 代码静态链接。 diff --git a/crates/squid-cli/Cargo.toml b/crates/squid-cli/Cargo.toml new file mode 100644 index 0000000..932468b --- /dev/null +++ b/crates/squid-cli/Cargo.toml @@ -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 + diff --git a/crates/squid-cli/src/main.rs b/crates/squid-cli/src/main.rs new file mode 100644 index 0000000..459fb7b --- /dev/null +++ b/crates/squid-cli/src/main.rs @@ -0,0 +1,1625 @@ +//! `squid` — one tool for cleaning, uninstalling, purging and watching a Mac. +//! +//! The binary is deliberately thin: every decision about *what* may be deleted +//! is made in `squid-engine`, and every deletion goes through +//! `squid_engine::delete`, which re-checks each path against the safety policy +//! and the ledger. This file only parses arguments, shows progress and asks for +//! confirmation. + +use anyhow::{Context, Result}; +use clap::{Args, Parser, Subcommand}; +use crossterm::tty::IsTty; +use squid_core::progress::{CancelToken, Event, Progress}; +use squid_core::{paths, Bytes, Category, CleanupItem, DeleteMode, Locale, ScanReport, Settings}; +use squid_engine::analyze; +use squid_engine::delete::{self, DeleteJob}; +use squid_engine::{clean, purge, uninstall, Engine}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +// ------------------------------------------------------------------------ CLI + +#[derive(Parser, Debug)] +#[command( + name = "squid", + version, + about = "clean · uninstall · purge · watch — a system utility that never touches what it does not own", + long_about = None, + disable_help_subcommand = true +)] +struct Cli { + #[command(subcommand)] + command: Option, + + /// Machine-readable output where supported + #[arg(long, global = true)] + json: bool, + + /// Only the essential lines + #[arg(long, short = 'q', global = true)] + quiet: bool, + + /// Never emit ANSI colour + #[arg(long, global = true)] + no_color: bool, + + /// Interface language: `zh` or `en`. Overrides the locale the terminal + /// exported, which Terminal.app does not export at all. + #[arg(long, global = true, value_name = "LANG")] + lang: Option, +} + +#[derive(Subcommand, Debug)] +enum Command { + /// Clear caches, logs, browser junk, DerivedData and other regenerable files + Clean(CleanArgs), + /// Remove an application together with everything it left behind + Uninstall(UninstallArgs), + /// Deep clean: node_modules, build folders, disk images, stale archives + Purge(PurgeArgs), + /// Open the interface: disk map, system meters, cleanup, history + State, + /// One-shot system snapshot (scripts, dotfiles, cron) + Status(StatusArgs), + /// Who owns this disk? A size tree for one path + Analyze(AnalyzeArgs), + /// What squid has already removed + History(HistoryArgs), + /// Put a trashed session back + Undo(UndoArgs), + /// Protect a path from every future scan + Whitelist(WhitelistArgs), + /// List the cleanup rules squid knows + Rules, + /// Report permissions, settings and ledger health + Doctor, +} + +#[derive(Args, Debug)] +struct CleanArgs { + /// Show what would go without deleting anything + #[arg(long)] + dry_run: bool, + /// Do not ask + #[arg(long, short = 'y')] + yes: bool, + /// Only these categories (caches, browsers, logs, developer, …) + #[arg(long, value_delimiter = ',')] + categories: Vec, + /// Also look for leftovers of apps that are gone + #[arg(long)] + orphans: bool, + /// Override the per-rule age filter, in days (0 disables it) + #[arg(long)] + min_age: Option, + /// Skip rules that need administrator rights + #[arg(long)] + user_only: bool, + /// Move to Trash (default) + #[arg(long, conflicts_with = "permanent")] + trash: bool, + /// Delete for real, skipping the Trash + #[arg(long, conflicts_with = "trash")] + permanent: bool, +} + +#[derive(Args, Debug)] +struct UninstallArgs { + /// Application name or bundle identifier + name: Option, + /// List installed applications + #[arg(long)] + list: bool, + #[arg(long)] + dry_run: bool, + #[arg(long, short = 'y')] + yes: bool, + #[arg(long, conflicts_with = "permanent")] + trash: bool, + #[arg(long, conflicts_with = "trash")] + permanent: bool, +} + +#[derive(Args, Debug)] +struct PurgeArgs { + /// Where to look; defaults to the configured purge roots + paths: Vec, + #[arg(long)] + dry_run: bool, + #[arg(long, short = 'y')] + yes: bool, + /// Also offer folders that might still be needed + #[arg(long)] + all: bool, + /// Age filter in days (default from settings) + #[arg(long)] + min_age: Option, +} + +#[derive(Args, Debug)] +struct StatusArgs { + /// How many processes to list + #[arg(long, default_value_t = 8)] + processes: usize, +} + +#[derive(Args, Debug)] +struct AnalyzeArgs { + /// Path to measure (default: your home folder) + path: Option, + /// Levels below the root + #[arg(long, default_value_t = 1)] + depth: usize, + /// Children to show per folder + #[arg(long, default_value_t = 24)] + top: usize, + /// Also list the largest files + #[arg(long)] + files: bool, +} + +#[derive(Args, Debug)] +struct HistoryArgs { + #[arg(long, default_value_t = 20)] + limit: usize, +} + +#[derive(Args, Debug)] +struct UndoArgs { + /// Session id; the newest trashed session when omitted + session: Option, +} + +#[derive(Args, Debug)] +struct WhitelistArgs { + #[command(subcommand)] + action: WhitelistAction, +} + +#[derive(Subcommand, Debug)] +enum WhitelistAction { + /// Never offer these paths again + Add { paths: Vec }, + /// Stop protecting these paths + Remove { paths: Vec }, + /// Show the list + List, +} + +static COLOR: AtomicBool = AtomicBool::new(false); +static QUIET: AtomicBool = AtomicBool::new(false); +/// With `--json` stdout is a data stream: every human line is rerouted to +/// stderr so `squid clean --json | jq` never sees a progress message. +static DIAG_STDERR: AtomicBool = AtomicBool::new(false); + +/// One human-readable diagnostic line. +fn diag(code: &str, text: &str) { + if DIAG_STDERR.load(Ordering::Relaxed) { + eprintln!("{}", paint(code, text)); + } else { + println!("{}", paint(code, text)); + } +} + +fn main() { + let code = match run() { + Ok(code) => code, + Err(error) => { + if let Some(inner) = error.downcast_ref::() { + if matches!(inner, squid_core::SquidError::Cancelled) { + eprintln!("{}", paint("90", "cancelled — nothing was changed")); + std::process::exit(130); + } + } + eprintln!("{} {}", paint("31", "squid:"), error); + let mut source = error.source(); + while let Some(cause) = source.take() { + eprintln!("{}", paint("90", &format!(" caused by: {cause}"))); + source = cause.source(); + } + std::process::exit(1); + } + }; + std::process::exit(code); +} + +fn run() -> Result { + let cli = Cli::parse(); + COLOR.store( + !cli.no_color && std::io::stdout().is_tty(), + Ordering::Relaxed, + ); + QUIET.store(cli.quiet, Ordering::Relaxed); + DIAG_STDERR.store(cli.json, Ordering::Relaxed); + // `--lang` is a flag on the whole program, so honour it for the whole + // program: publish it as the one hint every reader already agrees on + // before any command asks what language it should speak. Setting it only + // inside the interface branch made `squid --lang en doctor` answer with + // the language the *terminal* asked for, which reads like a bug. + if let Some(lang) = &cli.lang { + std::env::set_var("SQUID_LANG", lang); + } + + match cli.command { + None | Some(Command::State) => { + if cli.no_color { + // The interface probes for colour when it opens, and + // https://no-color.org is the one promise every program agrees + // on — so `--no-color` is kept by saying it out loud rather + // than by teaching the TUI a second switch of its own. + std::env::set_var("NO_COLOR", "1"); + } + squid_tui::run().context("could not open the interface")?; + Ok(0) + } + Some(Command::Clean(args)) => cmd_clean(args, cli.json), + Some(Command::Uninstall(args)) => cmd_uninstall(args, cli.json), + Some(Command::Purge(args)) => cmd_purge(args, cli.json), + Some(Command::Status(args)) => cmd_status(args, cli.json), + Some(Command::Analyze(args)) => cmd_analyze(args, cli.json), + Some(Command::History(args)) => cmd_history(args, cli.json), + Some(Command::Undo(args)) => cmd_undo(args, cli.json), + Some(Command::Whitelist(args)) => cmd_whitelist(args), + Some(Command::Rules) => cmd_rules(cli.json), + Some(Command::Doctor) => cmd_doctor(), + } +} + +// ---------------------------------------------------------------------- output + +fn paint(code: &str, text: &str) -> String { + if COLOR.load(Ordering::Relaxed) { + format!("\x1b[{code}m{text}\x1b[0m") + } else { + text.to_string() + } +} + +fn shout(code: &str, text: &str) { + if !QUIET.load(Ordering::Relaxed) || code == "31" { + diag(code, text); + } +} + +fn heading(text: &str) { + if QUIET.load(Ordering::Relaxed) { + return; + } + diag("0", ""); + diag("1;36", text); + diag("90", &"─".repeat(text.chars().count().min(64))); +} + +fn shrink(text: &str, width: usize) -> String { + use unicode_width::UnicodeWidthChar; + if text.chars().map(|c| c.width().unwrap_or(0)).sum::() <= width { + return text.to_string(); + } + if width <= 3 { + return ".".repeat(width); + } + let mut budget = width - 3; + let mut out = String::new(); + for ch in text.chars().rev() { + let wide = ch.width().unwrap_or(0); + if wide > budget { + break; + } + budget -= wide; + out.insert(0, ch); + } + format!("...{out}") +} + +fn clip(text: &str, width: usize) -> String { + use unicode_width::UnicodeWidthChar; + if text.chars().map(|c| c.width().unwrap_or(0)).sum::() <= width { + return text.to_string(); + } + let mut budget = width.saturating_sub(1); + let mut out = String::new(); + for ch in text.chars() { + let wide = ch.width().unwrap_or(0); + if wide > budget { + break; + } + budget -= wide; + out.push(ch); + } + out.push('…'); + out +} + +/// [`clip`] plus space padding so the clipped text always occupies exactly +/// `width` display columns. Columns after it stay aligned. +fn fit(text: &str, width: usize) -> String { + use unicode_width::UnicodeWidthChar; + let clipped = clip(text, width); + let used: usize = clipped.chars().map(|c| c.width().unwrap_or(0)).sum(); + let mut out = clipped; + out.push_str(&" ".repeat(width.saturating_sub(used))); + out +} + +/// Visible width of a string, counting CJK glyphs as two columns. +fn display_width(text: &str) -> usize { + use unicode_width::UnicodeWidthChar; + text.chars().map(|c| c.width().unwrap_or(0)).sum() +} + +/// Why this row is greyed out (or what is worth knowing about it). The item's +/// own note names the concrete reason — "no git repo and only 2 days old" — +/// which beats the generic lock label, so the note wins when both exist. +fn why(item: &CleanupItem) -> Option { + if let Some(note) = item.note.as_deref() { + return Some(note.to_string()); + } + item.lock.map(delete::lock_reason).map(str::to_string) +} + +fn row(size: Bytes, label: &str, path: &str, note: Option<&str>) { + if QUIET.load(Ordering::Relaxed) { + return; + } + let terminal = terminal_width(); + let label_cell = fit(label, 30); + let path_width = terminal + .saturating_sub(11 + display_width(&label_cell) + 2) + .max(16); + println!( + " {} {} {}", + paint("33", &format!("{:>9}", size.human())), + paint("1", &label_cell), + paint("90", &shrink(path, path_width)) + ); + if let Some(note) = note { + println!(" {}", paint("90", &format!("↳ {note}"))); + } +} + +fn terminal_width() -> usize { + crossterm::terminal::size() + .map(|(width, _)| width as usize) + .unwrap_or(100) + .clamp(60, 200) +} + +fn ask(question: &str) -> bool { + if !std::io::stdin().is_tty() { + shout( + "33", + "not a terminal — pass --yes to run this without asking", + ); + return false; + } + print!("{} ", paint("1;33", &format!("{question} [y/N]"))); + let _ = std::io::stdout().flush(); + let mut answer = String::new(); + if std::io::stdin().read_line(&mut answer).is_err() { + return false; + } + matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") +} + +// ----------------------------------------------------------- progress plumbing + +/// Run `work` while pumping its progress events to the terminal. +fn with_progress( + label: &str, + work: impl FnOnce(&Engine, &Progress, &CancelToken) -> squid_core::Result, +) -> squid_core::Result { + let label = label.to_owned(); + let engine = Engine::new(); + let progress = Progress::new(); + let cancel = CancelToken::new(); + let printer = progress.clone(); + let stop = Arc::new(AtomicBool::new(false)); + let printer_stop = stop.clone(); + let printer_thread = std::thread::spawn(move || { + let mut frames = label.chars(); + loop { + let stop_now = printer_stop.load(Ordering::Relaxed); + for event in printer.drain() { + match event { + Event::Phase { phase, detail } => { + shout("36", &format!(" {} {phase} — {detail}", bullet())); + } + Event::Tick { + done, + total, + subject, + } => { + if std::io::stdout().is_tty() { + let glyph = frames + .next() + .unwrap_or_else(|| label.chars().next().unwrap_or('#')); + let text = match total { + Some(total) if total > 0 => format!( + " {glyph} {done}/{}", + squid_core::bytes::format_thousands(total) + ), + _ => format!( + " {glyph} {}", + squid_core::bytes::format_thousands(done) + ), + }; + let tail = subject + .as_ref() + .map(|path| shrink(&paths::pretty(path), 40)) + .unwrap_or_default(); + print!("\r\x1b[K{} {}", paint("36", &text), paint("90", &tail)); + let _ = std::io::stdout().flush(); + } + } + Event::Warning(text) => shout("33", &format!(" ! {}", clip(&text, 100))), + Event::Note(text) => shout("90", &format!(" · {}", clip(&text, 100))), + Event::Deleted { path, freed } => { + shout( + "90", + &format!( + " ✓ {} ({})", + shrink(&paths::pretty(&path), 70), + freed.human() + ), + ); + } + Event::Bucket { .. } | Event::Done(_) => {} + } + } + if stop_now { + if std::io::stdout().is_tty() { + print!("\r\x1b[K"); + let _ = std::io::stdout().flush(); + } + break; + } + std::thread::sleep(Duration::from_millis(40)); + } + }); + let result = work(&engine, &progress, &cancel); + stop.store(true, Ordering::Relaxed); + let _ = printer_thread.join(); + result +} + +fn bullet() -> String { + if COLOR.load(Ordering::Relaxed) { + "●".to_string() + } else { + "*".to_string() + } +} + +/// Print a scan the CleanMyMac way: grouped, biggest first, totals last. +fn show_scan(report: &ScanReport, title: &str) { + heading(title); + if report.items.is_empty() { + shout("90", " nothing to remove — this is a good outcome"); + return; + } + let mut categories: Vec = Category::ALL.to_vec(); + categories.retain(|category| report.items.iter().any(|item| item.category == *category)); + categories.sort_by(|a, b| { + let total_of = |category: &Category| -> u64 { + report + .items + .iter() + .filter(|item| item.category == *category) + .map(|item| item.on_disk().as_u64()) + .sum() + }; + total_of(b).cmp(&total_of(a)) + }); + for category in categories { + let items: Vec<&CleanupItem> = report + .items + .iter() + .filter(|item| item.category == category) + .collect(); + let total: Bytes = items.iter().map(|item| item.on_disk()).sum(); + println!( + "{}", + paint( + "1;36", + &format!( + " {} {} · {}", + TRIANGLE, + category.title(), + total.human_long() + ) + ) + ); + for item in items.iter().take(18) { + row( + item.on_disk(), + &item.label, + &item.display_path(), + why(item).as_deref(), + ); + } + if items.len() > 18 { + shout( + "90", + &format!(" … and {} more", items.len() - 18), + ); + } + } + let selected: Bytes = report + .items + .iter() + .filter(|item| item.selected && item.lock.is_none()) + .map(|item| item.on_disk()) + .sum(); + println!(); + shout( + "1", + &format!( + " {} items · {} selected · {}", + report.items.len(), + report + .items + .iter() + .filter(|item| item.selected && item.lock.is_none()) + .count(), + selected.human_long() + ), + ); + if report.unreadable > 0 { + shout( + "90", + &format!(" {} locations could not be read", report.unreadable), + ); + } +} + +const TRIANGLE: &str = "▸"; + +/// The one place anything is ever deleted from. +fn delete_items( + items: Vec, + mode: DeleteMode, + command: &str, +) -> squid_core::Result { + let removable: Vec = items + .into_iter() + .filter(|item| item.selected && item.lock.is_none()) + .collect(); + let job = DeleteJob::new(removable, mode, command); + let count = job.removable().len(); + with_progress("delete", move |engine, progress, cancel| { + if !COLOR.load(Ordering::Relaxed) { + // keep the count alive for the summary line + eprintln!("{}", paint("90", &format!(" removing {count} items"))); + } + delete::execute(engine, &job, progress, cancel) + }) +} + +fn report_outcome(outcome: &delete::DeleteOutcome) { + let summary = &outcome.summary; + heading("Done"); + let freed = summary.freed_on_disk(); + // "24.31 GB freed · moved to Trash" contradicts itself: a rename inside + // one volume frees nothing until the Trash is emptied. Say which of the + // two the number is. + let (verb, where_it_went) = match summary.mode { + Some(DeleteMode::Trash) => ( + "moved", + "into the Trash — still on the disk until you empty it (squid undo restores them)", + ), + Some(DeleteMode::Permanent) => ("freed", "permanently deleted"), + None => ("freed", "done"), + }; + shout( + "1;32", + &format!( + " {} {verb} · {} removed · {}", + freed.human_long(), + summary.removed, + where_it_went + ), + ); + if let Some(session) = &summary.session_id { + shout( + "90", + &format!(" session {session} — squid undo {}", session), + ); + } + for (path, reason) in outcome.skipped.iter().take(8) { + shout( + "33", + &format!(" skipped {} — {reason}", paths::pretty(path)), + ); + } + if summary.failed > 0 { + for error in summary.errors.iter().take(6) { + shout("31", &format!(" ! {error}")); + } + } +} + +fn mode_from(trash: bool, permanent: bool, settings: &Settings) -> DeleteMode { + if permanent { + DeleteMode::Permanent + } else if trash { + DeleteMode::Trash + } else { + settings.delete_mode + } +} + +fn mode_note(mode: DeleteMode) -> &'static str { + match mode { + DeleteMode::Trash => "everything goes to the Trash first — squid undo puts it back", + DeleteMode::Permanent => "permanent deletion: no Trash, no undo", + } +} + +// ----------------------------------------------------------------------- clean + +fn parse_categories(values: &[String]) -> Result> { + let mut out = Vec::new(); + for value in values { + for piece in value.split(',') { + let piece = piece.trim(); + if piece.is_empty() { + continue; + } + let category = Category::parse(piece) + .ok_or_else(|| anyhow::anyhow!("unknown category '{piece}' — try `squid rules`"))?; + out.push(category); + } + } + Ok(out) +} + +fn selected_of(items: &[CleanupItem]) -> (usize, Bytes) { + let chosen: Vec<&CleanupItem> = items + .iter() + .filter(|item| item.selected && item.lock.is_none()) + .collect(); + let size = chosen.iter().map(|item| item.on_disk()).sum(); + (chosen.len(), size) +} + +fn cmd_clean(args: CleanArgs, json: bool) -> Result { + let settings = Engine::new().settings().clone(); + let mode = mode_from(args.trash, args.permanent, &settings); + let categories = parse_categories(&args.categories)?; + let options = clean::CleanOptions { + categories, + skip_admin_rules: args.user_only, + min_age_days: args.min_age, + orphans: args.orphans, + fast: false, + }; + let started = std::time::Instant::now(); + let report = with_progress("scan", move |engine, progress, cancel| { + let report = clean::scan(engine, &options, progress, cancel)?; + clean::publish_buckets(&report, progress); + Ok(clean::sort_for_display(report)) + })?; + + let (count, size) = selected_of(&report.items); + if json && !args.yes { + println!("{}", serde_json::to_string_pretty(&report)?); + return Ok(0); + } + if !args.dry_run { + show_scan(&report, "Cleanup"); + } else { + show_scan(&report, "Cleanup · dry run"); + } + shout( + "90", + &format!(" scanned in {:.1}s", started.elapsed().as_secs_f64()), + ); + + if args.dry_run { + shout("33", " dry run — nothing was deleted"); + return Ok(0); + } + if count == 0 { + shout( + "90", + " nothing is selected; use --dry-run to inspect first", + ); + return Ok(0); + } + shout("90", &format!(" {}", mode_note(mode))); + if !args.yes + && !ask(&format!( + "Delete {count} items ({}), {}", + size.human_long(), + match mode { + DeleteMode::Trash => "to the Trash", + DeleteMode::Permanent => "permanently", + } + )) + { + shout("33", " cancelled — nothing was deleted"); + return Ok(0); + } + let outcome = delete_items(report.items, mode, "squid clean")?; + if json { + println!("{}", serde_json::to_string_pretty(&outcome.summary)?); + } else { + report_outcome(&outcome); + } + Ok(0) +} + +// ------------------------------------------------------------------- uninstall + +fn cmd_uninstall(args: UninstallArgs, json: bool) -> Result { + let settings = Engine::new().settings().clone(); + let mode = mode_from(args.trash, args.permanent, &settings); + + if args.list || args.name.is_none() { + let apps = with_progress("apps", |engine, progress, cancel| { + uninstall::scan_apps(engine, true, progress, cancel) + })?; + if json { + println!("{}", serde_json::to_string_pretty(&apps)?); + return Ok(0); + } + heading(&format!("Applications · {}", apps.len())); + let total: Bytes = apps.iter().map(|app| app.size).sum(); + for app in &apps { + println!( + " {} {} {}{} {}", + paint("33", &format!("{:>9}", app.size.human())), + paint("1", &fit(&app.name, 34)), + paint("90", &fit(app.version.as_deref().unwrap_or("—"), 12)), + if app.running { + paint("33", " running") + } else { + " ".to_string() + }, + paint("90", &shrink(&paths::pretty(&app.path), 44)) + ); + } + println!(); + shout( + "1", + &format!(" {} apps · {}", apps.len(), total.human_long()), + ); + shout("90", " squid uninstall builds a removal plan"); + return Ok(0); + } + + let query = args.name.clone().unwrap_or_default(); + let found = with_progress("find", |engine, progress, cancel| { + uninstall::find(engine, &query, cancel, progress) + })?; + if found.is_empty() { + shout("31", &format!("no application matches '{query}'")); + shout("90", " try `squid uninstall --list`"); + return Ok(1); + } + let app = if found.len() == 1 { + found[0].clone() + } else { + let exact = found + .iter() + .find(|app| app.name.eq_ignore_ascii_case(&query)) + .or_else(|| { + found.iter().find(|app| { + app.bundle_id + .as_deref() + .map(|id| id.eq_ignore_ascii_case(&query)) + .unwrap_or(false) + }) + }) + .cloned(); + match exact { + Some(app) => app, + None => { + heading(&format!("'{query}' matches {} applications", found.len())); + for app in &found { + println!( + " {} {} {}", + paint("33", &format!("{:>9}", app.size.human())), + paint("1", &clip(&app.name, 34)), + paint("90", &shrink(&paths::pretty(&app.path), 50)) + ); + } + shout( + "33", + " be more specific — pass part of the name or the bundle id", + ); + return Ok(1); + } + } + }; + + let plan = with_progress("plan", { + let app = app.clone(); + move |engine, progress, cancel| uninstall::build_plan(engine, &app, progress, cancel) + })?; + + if json && !args.yes { + println!("{}", serde_json::to_string_pretty(&plan)?); + return Ok(0); + } + + heading(&format!("Uninstall · {}", app.name)); + shout("90", &format!(" {}", paths::pretty(&app.path))); + shout( + "90", + &format!( + " {} · {}", + app.bundle_id + .clone() + .unwrap_or_else(|| "no bundle id".into()), + app.version.clone().unwrap_or_else(|| "version ?".into()) + ), + ); + for warning in &plan.warnings { + shout("33", &format!(" ! {warning}")); + } + let (count, size) = selected_of(&plan.items); + for item in &plan.items { + row( + item.on_disk(), + if item.rule_id == "uninstall-bundle" { + "app bundle" + } else { + item.category.title() + }, + &item.display_path(), + why(item).as_deref(), + ); + } + println!(); + shout("1", &format!(" {count} items · {}", size.human_long())); + if args.dry_run { + shout("33", " dry run — nothing was deleted"); + return Ok(0); + } + shout("90", &format!(" {}", mode_note(mode))); + if !args.yes + && !ask(&format!( + "Remove {} and {} leftover items ({})?", + app.name, + count, + size.human_long() + )) + { + shout("33", " cancelled — nothing was deleted"); + return Ok(0); + } + let outcome = with_progress("delete", move |engine, progress, cancel| { + uninstall::remove_plan(engine, &plan, mode, progress, cancel) + })?; + if json { + println!("{}", serde_json::to_string_pretty(&outcome.summary)?); + } else { + report_outcome(&outcome); + } + Ok(0) +} + +// ----------------------------------------------------------------------- purge + +fn cmd_purge(args: PurgeArgs, json: bool) -> Result { + let settings = Engine::new().settings().clone(); + let mode = mode_from(false, false, &settings); + let roots: Vec = args.paths.iter().map(|path| paths::expand(path)).collect(); + let options = purge::PurgeOptions { + roots, + min_age_days: args.min_age, + force: args.all, + max_depth: None, + }; + if json && !args.yes { + let report = with_progress("purge", { + let options = options.clone(); + move |engine, progress, cancel| purge::scan(engine, &options, progress, cancel) + })?; + println!("{}", serde_json::to_string_pretty(&report)?); + return Ok(0); + } + let report = with_progress("purge", move |engine, progress, cancel| { + let mut report = purge::scan(engine, &options, progress, cancel)?; + report.items.sort_by(|a, b| { + b.on_disk() + .cmp(&a.on_disk()) + .then_with(|| a.path.cmp(&b.path)) + }); + Ok(report) + })?; + show_scan( + &report, + if args.dry_run { + "Deep clean · dry run" + } else { + "Deep clean" + }, + ); + let snapshots = purge::local_snapshots(); + if let Some(note) = purge::snapshot_note(&snapshots) { + heading("Time Machine"); + shout("33", &format!(" {note}")); + for snapshot in snapshots.iter().take(6) { + shout("90", &format!(" · {}", snapshot.name)); + } + shout( + "90", + " squid never touches snapshots — that is tmutil's job", + ); + } + let (count, size) = selected_of(&report.items); + if args.dry_run { + shout("33", " dry run — nothing was deleted"); + return Ok(0); + } + if count == 0 { + shout( + "90", + " nothing safe to remove; --all offers the ambiguous folders too", + ); + return Ok(0); + } + shout("90", &format!(" {}", mode_note(mode))); + if !args.yes + && !ask(&format!( + "Delete {count} folders ({}), {}", + size.human_long(), + match mode { + DeleteMode::Trash => "to the Trash", + DeleteMode::Permanent => "permanently", + } + )) + { + shout("33", " cancelled — nothing was deleted"); + return Ok(0); + } + let outcome = delete_items(report.items, mode, "squid purge")?; + if json { + println!("{}", serde_json::to_string_pretty(&outcome.summary)?); + } else { + report_outcome(&outcome); + } + Ok(0) +} + +// ---------------------------------------------------------------------- status + +fn cmd_status(args: StatusArgs, json: bool) -> Result { + let mut sampler = squid_stats::Sampler::new(); + let _ = sampler.prime(); + std::thread::sleep(Duration::from_millis(500)); + let snapshot = sampler.refresh(); + if json { + println!("{}", serde_json::to_string_pretty(&snapshot)?); + return Ok(0); + } + heading(&format!( + "{} · {}", + snapshot.host.hostname, snapshot.host.hardware + )); + let kv = |label: &str, value: String| { + println!(" {:<10} {}", paint("90", label), value); + }; + kv( + "system", + format!( + "{} {} · {}", + snapshot.host.os_name, snapshot.host.os_version, snapshot.host.arch + ), + ); + kv("uptime", squid_stats::human_uptime(snapshot.uptime_secs)); + kv( + "cpu", + format!( + "{}%", + paint( + if snapshot.cpu.total > 80.0 { + "31" + } else { + "32" + }, + &format!("{:.0}", snapshot.cpu.total) + ) + ), + ); + kv( + "load", + format!( + "{:.2} {:.2} {:.2} · {} cores · {}", + snapshot.cpu.load[0], + snapshot.cpu.load[1], + snapshot.cpu.load[2], + snapshot.cpu.logical_cores, + clip(&snapshot.cpu.brand, 28) + ), + ); + kv( + "memory", + format!( + "{} / {} ({}%) · swap {} / {}", + snapshot.memory.used.human(), + snapshot.memory.total.human(), + snapshot.memory.percent_used(), + snapshot.memory.swap_used.human(), + snapshot.memory.swap_total.human() + ), + ); + kv( + "network", + format!( + "↓ {}/s ↑ {}/s · since boot {}", + snapshot.network.rx_per_sec.human(), + snapshot.network.tx_per_sec.human(), + (snapshot.network.rx_total + snapshot.network.tx_total).human() + ), + ); + kv( + "disk", + format!( + "↓ {}/s ↑ {}/s · {:.1}% active", + snapshot.disk.read_per_sec.human(), + snapshot.disk.write_per_sec.human(), + snapshot.disk.activity + ), + ); + if let Some(battery) = &snapshot.battery { + kv("battery", battery.label()); + } + heading("Volumes"); + for volume in &snapshot.volumes { + let used = volume.used(); + let width = 28usize; + let ratio = if volume.total.as_u64() == 0 { + 0.0 + } else { + used.as_u64() as f64 / volume.total.as_u64() as f64 + }; + let filled = (ratio * width as f64).round() as usize; + let bar = format!( + "{}{}", + paint("36", &"█".repeat(filled)), + paint("90", &"░".repeat(width - filled)) + ); + println!( + " {} [{}] {} / {} {}", + paint("1", &fit(&volume.name, 14)), + bar, + paint("32", &used.human()), + volume.total.human(), + paint("90", &format!("{} free", volume.free.human())) + ); + } + heading(&format!("Top processes · {}", args.processes)); + for process in snapshot.top_processes.iter().take(args.processes) { + println!( + " {:>6} {} {:>9} {}", + paint("36", &format!("{:.1}%", process.cpu)), + paint("1", &fit(&process.name, 30)), + paint("33", &process.memory.human()), + paint("90", &format!("pid {}", process.pid)) + ); + } + Ok(0) +} + +// --------------------------------------------------------------------- analyze + +fn cmd_analyze(args: AnalyzeArgs, json: bool) -> Result { + let root = args + .path + .as_deref() + .map(paths::expand) + .unwrap_or_else(paths::home_dir); + if !root.is_dir() { + anyhow::bail!("{} is not a folder", root.display()); + } + let node = with_progress("map", { + let root = root.clone(); + let depth = args.depth; + let top = args.top; + move |engine, progress, cancel| { + let _ = engine; + analyze::explore(&root, depth, top, cancel, progress) + } + })?; + if json { + println!("{}", serde_json::to_string_pretty(&node)?); + return Ok(0); + } + heading(&format!( + "{} · {}", + paths::pretty(&node.path), + node.size().human_long() + )); + print_tree(&node, 0, &node.size()); + if !node.complete { + shout( + "90", + " (the walk hit its limit — the totals are a floor, not the truth)", + ); + } + if args.files { + let files = with_progress("files", { + let root = root.clone(); + move |engine, progress, cancel| { + let _ = engine; + analyze::largest_files(&root, 20, Bytes(10 * 1024 * 1024), cancel, progress) + } + })?; + heading("Largest files"); + for file in &files { + row( + file.size(), + &paths::label_for(&file.path), + &paths::pretty(&file.path), + None, + ); + } + } + Ok(0) +} + +fn print_tree(node: &analyze::Node, depth: usize, total: &Bytes) { + let width = 22usize; + let bar_w = (terminal_width() as i64 - 34 - depth as i64 * 2).clamp(6, 30) as usize; + for child in node.display_children().iter().take(40) { + let size = child.size(); + let ratio = if total.is_zero() { + 0.0 + } else { + size.as_u64() as f64 / total.as_u64() as f64 + }; + let filled = (ratio * bar_w as f64).round() as usize; + let bar = format!( + "{}{}", + paint("35", &"█".repeat(filled)), + paint("90", &"░".repeat(bar_w.saturating_sub(filled))) + ); + println!( + " {}{} [{}] {} {:>4.1}%", + " ".repeat(depth), + paint("1", &fit(&child.name(), width)), + bar, + paint("33", &format!("{:>8}", size.human())), + ratio * 100.0 + ); + if depth + 1 < 2 { + print_tree(child, depth + 1, total); + } + } +} + +// ------------------------------------------------------------- history / undo + +/// What a run did to its bytes, in one word. A run the user restored gets its +/// own label: still calling it "to Trash" after an undo is how the ledger +/// starts telling a story that no longer happened. +fn mode_label(session: &squid_core::ledger::Session) -> &'static str { + if session.restored { + "restored" + } else { + match session.mode { + DeleteMode::Trash => "to Trash", + DeleteMode::Permanent => "for good", + } + } +} + +fn cmd_history(args: HistoryArgs, json: bool) -> Result { + let sessions = squid_core::ledger::load_sessions(args.limit); + if json { + println!("{}", serde_json::to_string_pretty(&sessions)?); + return Ok(0); + } + heading(&format!("History · {} sessions", sessions.len())); + if sessions.is_empty() { + shout( + "90", + &format!( + " nothing yet — the ledger lives in {}", + paths::pretty(&squid_core::ledger::history_dir()) + ), + ); + return Ok(0); + } + let mut freed = Bytes::ZERO; + let mut trashed = Bytes::ZERO; + let mut undone = 0; + for session in &sessions { + // `kept`, not `freed`: a session the user already restored put every + // byte back, and a total that counts it twice overstates the space. + let reclaimed = session.kept(); + freed += reclaimed; + if session.restored { + undone += 1; + } + if session.mode == DeleteMode::Trash { + // A rename into ~/.Trash is on the same volume, so the bytes are + // still on the disk. Counting them as "freed" is how a correct + // number comes to look like a broken one. + trashed += reclaimed; + } + let failures = if session.failed > 0 { + paint("33", &format!(" · {} failed", session.failed)) + } else { + String::new() + }; + println!( + " {} {} {} {} {} {}", + paint( + "90", + &fit( + session + .started + .replace('T', " ") + .split('+') + .next() + .and_then(|stamp| stamp.split('.').next()) + .unwrap_or(&session.started), + 19 + ) + ), + paint("1", &fit(&session.command, 20)), + paint("32", &format!("{:>11}", session.freed().human_fixed())), + paint( + "33", + &format!( + "{:>14} removed", + squid_core::bytes::format_thousands(session.removed as u64) + ), + ), + paint( + "90", + &format!("{}{}", fit(mode_label(session), 9), failures) + ), + paint("90", &shrink(&session.id, 18)) + ); + } + println!(); + shout( + "1", + &format!( + " {} removed across {} sessions", + freed.human_long(), + sessions.len() + ), + ); + if !trashed.is_zero() { + shout( + "90", + &format!( + " {} of it is sitting in the Trash — empty the Trash to actually reclaim it", + trashed.human_long() + ), + ); + } + if undone > 0 { + shout( + "90", + &format!(" {undone} session(s) were restored afterwards and are counted as nothing"), + ); + } + shout( + "90", + &format!(" {}", paths::pretty(&squid_core::ledger::history_dir())), + ); + shout("90", " squid undo restores the newest trashed session"); + Ok(0) +} + +fn cmd_undo(args: UndoArgs, json: bool) -> Result { + let id = match args.session { + Some(id) => id, + None => { + let sessions = squid_core::ledger::load_sessions(40); + match sessions + .iter() + .find(|session| session.mode == DeleteMode::Trash && !session.entries.is_empty()) + { + Some(session) => session.id.clone(), + None => { + shout("33", "no trashed session to restore"); + return Ok(0); + } + } + } + }; + let (restored, skipped) = + delete::restore_session(&id).with_context(|| format!("could not restore session {id}"))?; + if json { + println!( + "{}", + serde_json::json!({ "session": id, "restored": restored, "skipped": skipped }) + ); + } else { + shout( + "1;32", + &format!("{restored} items restored from session {id}"), + ); + if skipped > 0 { + shout( + "90", + &format!("{skipped} could not be put back (path in use)"), + ); + } + } + Ok(0) +} + +// ------------------------------------------------------ whitelist / rules / doctor + +fn cmd_whitelist(args: WhitelistArgs) -> Result { + let (mut settings, errors) = Settings::load(); + for error in errors { + shout("33", &format!("config: {error}")); + } + match args.action { + WhitelistAction::Add { paths: values } => { + if values.is_empty() { + anyhow::bail!("nothing to protect — pass one or more paths or globs"); + } + for value in values { + let pattern = value.replace('~', &paths::home_dir().to_string_lossy()); + shout("32", &format!("protected {pattern}")); + settings.add_whitelist(pattern); + } + } + WhitelistAction::Remove { paths: values } => { + for value in values { + let pattern = value.replace('~', &paths::home_dir().to_string_lossy()); + if settings.remove_whitelist(&pattern) { + shout("33", &format!("unprotected {pattern}")); + } else { + shout("90", &format!("{pattern} was not protected")); + } + } + } + WhitelistAction::List => { + heading("Whitelist"); + if settings.whitelist.is_empty() { + shout("90", " empty — every matching path is offered for review"); + } + for pattern in &settings.whitelist { + println!(" {} {}", paint("32", "●"), pattern); + } + println!(); + shout("90", &format!(" {}", paths::pretty(&Settings::path()))); + return Ok(0); + } + } + let path = settings.save()?; + shout("90", &format!("saved {}", paths::pretty(&path))); + Ok(0) +} + +fn cmd_rules(json: bool) -> Result { + let engine = Engine::new(); + let rules = squid_rules::RuleSet::load(engine.settings()); + if json { + let view: Vec = rules + .rules() + .iter() + .map(|rule| { + serde_json::json!({ + "id": rule.id, + "category": rule.category.id(), + "title": rule.title, + "os": rule.os, + "needs_admin": rule.needs_admin, + "risky": rule.risky, + "note": rule.note, + "min_age_days": rule.min_age_days, + "select_by_default": rule.select_by_default, + "enabled": engine.settings().rule_enabled(&rule.id), + "patterns": rule.patterns, + }) + }) + .collect(); + println!("{}", serde_json::to_string_pretty(&view)?); + return Ok(0); + } + for category in rules.categories() { + let list = rules.by_category(category); + println!(); + println!( + "{}", + paint( + "1;36", + &format!(" {} · {}", category.title(), category.blurb()) + ) + ); + for rule in list { + let enabled = engine.settings().rule_enabled(&rule.id); + let mut flags = Vec::new(); + if !enabled { + flags.push(paint("31", "off")); + } + if rule.needs_admin && !squid_engine::is_root() { + flags.push(paint("33", "admin")); + } + if rule.risky { + flags.push(paint("31", "risky")); + } + if rule.min_age_days > 0 { + flags.push(paint("90", &format!(">{}d", rule.min_age_days))); + } + if !rule.select_by_default { + flags.push(paint("90", "opt-in")); + } + println!( + " {} {:<28} {}", + if enabled { + paint("32", "●") + } else { + paint("31", "○") + }, + rule.id, + paint("90", rule.display_title()) + ); + if !flags.is_empty() { + println!(" {}", flags.join(" ")); + } + } + } + println!(); + shout( + "90", + &format!( + " {} rules · disable one with `squid rules` docs or settings.toml disabled_rules", + rules.len() + ), + ); + for error in rules.errors() { + shout("31", &format!(" ! {error}")); + } + Ok(0) +} + +fn cmd_doctor() -> Result { + let engine = Engine::new(); + let platform = engine.platform(); + heading("squid doctor"); + let kv = |label: &str, value: String| println!(" {:<12} {}", paint("90", label), value); + kv("version", squid_core::VERSION.to_string()); + kv("platform", platform.display_name()); + kv("os", platform.os_version()); + kv("hardware", platform.hardware_model()); + kv( + "privileges", + if squid_engine::is_root() { + paint("33", "root — every path is offered, be careful") + } else { + format!( + "{} (user-owned paths only)", + std::env::var("USER").unwrap_or_else(|_| "standard".into()) + ) + }, + ); + kv( + "config", + format!( + "{} {}", + paths::pretty(&Settings::path()), + if Settings::path().exists() { + "(present)" + } else { + "(defaults — created on first save)" + } + ), + ); + let (locale, source) = Locale::explain(engine.settings()); + kv( + "language", + format!("{} — decided by {}", locale.code(), source.describe()), + ); + // The other half of "it looks wrong in this terminal": squid only paints + // 24-bit colour where the host said it can parse it, so `TERM`/`COLORTERM` + // are worth printing next to the answer they produced. + let mode = squid_tui::theme::color_mode(); + kv( + "colour", + format!( + "{} — probed from TERM={} COLORTERM={} TERM_PROGRAM={}", + mode.label(), + std::env::var("TERM").unwrap_or_else(|_| "(unset)".into()), + std::env::var("COLORTERM").unwrap_or_else(|_| "(unset)".into()), + std::env::var("TERM_PROGRAM").unwrap_or_else(|_| "(unset)".into()), + ), + ); + for error in engine.settings_errors() { + shout("31", &format!(" ! {error}")); + } + let probe = Settings::config_dir().join(".squid-write-probe"); + let writable = std::fs::create_dir_all(Settings::config_dir()).is_ok() + && std::fs::write(&probe, b"ok").is_ok(); + let _ = std::fs::remove_file(&probe); + kv( + "writable", + if writable { + paint("32", "yes — settings and ledger can be written") + } else { + paint("31", "no — check ownership of ~/.config/squid") + }, + ); + let rules = squid_rules::RuleSet::load(engine.settings()); + kv("rules", format!("{} loaded", rules.len())); + kv( + "delete mode", + match engine.settings().delete_mode { + DeleteMode::Trash => "Trash (undo available)", + DeleteMode::Permanent => "permanent", + } + .to_string(), + ); + let sessions = squid_core::ledger::load_sessions(500); + let freed: Bytes = sessions.iter().map(|session| session.freed()).sum(); + kv( + "ledger", + format!( + "{} sessions · {} · {}", + sessions.len(), + freed.human_long(), + paths::pretty(&squid_core::ledger::history_dir()) + ), + ); + let trash = paths::home_dir().join(".Trash"); + kv( + "trash", + if trash.is_dir() { + paint("32", "reachable") + } else { + paint("33", "not a folder — deletions fall back to permanent") + }, + ); + let volumes = platform.volumes().unwrap_or_default(); + kv("volumes", format!("{}", volumes.len())); + for volume in &volumes { + println!( + " {} {}", + paint("1", &fit(&volume.name, 16)), + paint( + "90", + &format!("{} free of {}", volume.free.human(), volume.total.human()) + ) + ); + } + let mut probes = vec![ + paths::home_dir().join("Library/Caches"), + Path::new("/Applications").to_path_buf(), + paths::home_dir().join("Library/Safari"), + paths::home_dir().join("Library/Mail"), + ]; + if let Some(volume) = volumes.iter().find(|volume| volume.is_root) { + probes.push(volume.mount_point.join("Library/Application Support")); + } + let blocked: Vec = probes + .into_iter() + .filter(|path| path.exists() && std::fs::read_dir(path).is_err()) + .map(|path| paths::pretty(&path)) + .collect(); + if blocked.is_empty() { + kv("access", paint("32", "every probe folder is readable")); + } else { + kv( + "access", + paint( + "33", + "some folders are blocked — grant Full Disk Access to your terminal", + ), + ); + for path in blocked { + shout("90", &format!(" {path}")); + } + } + println!(); + shout( + "90", + &format!(" safety: {}", mode_note(engine.settings().delete_mode)), + ); + Ok(0) +} diff --git a/crates/squid-core/Cargo.toml b/crates/squid-core/Cargo.toml new file mode 100644 index 0000000..52c5838 --- /dev/null +++ b/crates/squid-core/Cargo.toml @@ -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 diff --git a/crates/squid-core/src/bytes.rs b/crates/squid-core/src/bytes.rs new file mode 100644 index 0000000..7dbf20f --- /dev/null +++ b/crates/squid-core/src/bytes.rs @@ -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>(iter: I) -> Self { + iter.fold(Bytes::ZERO, |acc, item| acc + *item) + } +} + +impl std::iter::Sum for Bytes { + fn sum>(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"); + } +} diff --git a/crates/squid-core/src/error.rs b/crates/squid-core/src/error.rs new file mode 100644 index 0000000..de5c4c3 --- /dev/null +++ b/crates/squid-core/src/error.rs @@ -0,0 +1,82 @@ +//! Error types shared by every squid crate. + +use std::io; +use std::path::PathBuf; + +pub type Result = std::result::Result; + +#[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, 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, reason: impl Into) -> 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 for io::Error { + fn from(err: SquidError) -> io::Error { + match err { + SquidError::Io { source, .. } => source, + other => io::Error::other(other.to_string()), + } + } +} diff --git a/crates/squid-core/src/fs.rs b/crates/squid-core/src/fs.rs new file mode 100644 index 0000000..bcebfc7 --- /dev/null +++ b/crates/squid-core/src/fs.rs @@ -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 { + 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 = 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 { + let policy = SafetyPolicy::default(); + remove_item_with(item, mode, &policy) +} + +pub fn remove_item_with( + item: &crate::model::CleanupItem, + mode: DeleteMode, + policy: &SafetyPolicy, +) -> Result { + 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 = 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 { + 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 { + 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 = 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; + +#[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); + } +} diff --git a/crates/squid-core/src/ledger.rs b/crates/squid-core/src/ledger.rs new file mode 100644 index 0000000..c6ba4c8 --- /dev/null +++ b/crates/squid-core/src/ledger.rs @@ -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, + pub category: Option, +} + +#[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, + 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::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 { + 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 = 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 = files.drain(..files.len() - keep).collect(); + for path in stale { + let _ = std::fs::remove_file(path); + } + } +} + +pub fn load_sessions(limit: usize) -> Vec { + let dir = history_dir(); + let Ok(entries) = std::fs::read_dir(&dir) else { + return Vec::new(); + }; + let mut sessions: Vec = 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::(&text).ok()) + .collect(); + sessions.sort_by(|a, b| b.id.cmp(&a.id)); + sessions.truncate(limit); + sessions +} + +pub fn load_session(id: &str) -> Option { + 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"); + } +} diff --git a/crates/squid-core/src/lib.rs b/crates/squid-core/src/lib.rs new file mode 100644 index 0000000..11210f4 --- /dev/null +++ b/crates/squid-core/src/lib.rs @@ -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"; diff --git a/crates/squid-core/src/model.rs b/crates/squid-core/src/model.rs new file mode 100644 index 0000000..fcc2e03 --- /dev/null +++ b/crates/squid-core/src/model.rs @@ -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 { + 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, + /// Extra context shown in the detail row: "12,431 files". + pub note: Option, + /// 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, +} + +impl CleanupItem { + pub fn new( + path: PathBuf, + kind: ItemKind, + category: Category, + label: impl Into, + ) -> 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) -> 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) -> 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 { + 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, + pub items: Vec, + 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, +} + +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, + pub mode: Option, + pub session_id: Option, +} + +impl CleanSummary { + pub fn record_error(&mut self, msg: impl Into) { + 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, + pub path: PathBuf, + pub version: Option, + 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, + pub installed_ms: Option, +} + +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, + /// Notes the user should see before approving ("iCloud sync data present"). + pub warnings: Vec, +} + +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; +} + +pub trait PathExt { + fn exists_dir(&self) -> bool; +} + +impl> 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" + ); + } +} diff --git a/crates/squid-core/src/paths.rs b/crates/squid-core/src/paths.rs new file mode 100644 index 0000000..cdbc218 --- /dev/null +++ b/crates/squid-core/src/paths.rs @@ -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 { + 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); + } +} diff --git a/crates/squid-core/src/progress.rs b/crates/squid-core/src/progress.rs new file mode 100644 index 0000000..29cd704 --- /dev/null +++ b/crates/squid-core/src/progress.rs @@ -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, + subject: Option, + }, + /// 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, + rx: Receiver, + 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 { + 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) { + self.publish(Event::Phase { + phase, + detail: detail.into(), + }); + } + + pub fn tick(&self, done: u64, total: Option, subject: Option) { + self.publish(Event::Tick { + done, + total, + subject, + }); + } + + pub fn note(&self, msg: impl Into) { + self.publish(Event::Note(msg.into())); + } + + pub fn warning(&self, msg: impl Into) { + self.publish(Event::Warning(msg.into())); + } + + pub fn drain(&self) -> Vec { + 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 { + 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, +} + +impl EventSink { + pub fn emit(&self, event: Event) { + let _ = self.tx.send(event); + } + + pub fn note(&self, msg: impl Into) { + let _ = self.tx.send(Event::Note(msg.into())); + } + + pub fn warning(&self, msg: impl Into) { + 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); + +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) + } + } +} diff --git a/crates/squid-core/src/safety.rs b/crates/squid-core/src/safety.rs new file mode 100644 index 0000000..3b668d2 --- /dev/null +++ b/crates/squid-core/src/safety.rs @@ -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, + hard_deny: Vec, + /// 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, + /// 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) -> 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 { + 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()); + } +} diff --git a/crates/squid-core/src/settings.rs b/crates/squid-core/src/settings.rs new file mode 100644 index 0000000..71a2a19 --- /dev/null +++ b/crates/squid-core/src/settings.rs @@ -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, + /// Rules the user switched off entirely (`squid clean --disable caches-browser`). + pub disabled_rules: Vec, + /// Where `squid purge` looks for projects. `~` is expanded. + pub purge_roots: Vec, + /// 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, + /// 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) { + let mut errors = Vec::new(); + let path = Self::path(); + match std::fs::read_to_string(&path) { + Ok(text) => match toml::from_str::(&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 { + 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) { + 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) { + 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 { + 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 { + 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, +) -> (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 { + 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) -> 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) -> Option { + 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 { + 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 { + // 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 { + 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 { + let map: HashMap = 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()) + ); + } +} diff --git a/crates/squid-engine/Cargo.toml b/crates/squid-engine/Cargo.toml new file mode 100644 index 0000000..d551d18 --- /dev/null +++ b/crates/squid-engine/Cargo.toml @@ -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 diff --git a/crates/squid-engine/src/analyze.rs b/crates/squid-engine/src/analyze.rs new file mode 100644 index 0000000..6cc5c21 --- /dev/null +++ b/crates/squid-engine/src/analyze.rs @@ -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, + /// 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 { + 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, +} + +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 { + 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 = 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 = 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> { + let mut found: Vec = 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); + } +} diff --git a/crates/squid-engine/src/clean.rs b/crates/squid-engine/src/clean.rs new file mode 100644 index 0000000..bc679d1 --- /dev/null +++ b/crates/squid-engine/src/clean.rs @@ -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, + /// 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, + /// 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 { + 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 = 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 { + let mut rules: Vec = 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 { + 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 { + 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 { + 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 = 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 = 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> { + progress.phase("orphans", "looking for leftovers of removed apps"); + let apps = engine.platform().list_apps(cancel, false)?; + let installed: Vec = apps + .iter() + .filter_map(|app| app.bundle_id.as_deref()) + .map(|id| id.to_lowercase()) + .collect(); + let names: Vec = 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::>() + .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()])); + } +} diff --git a/crates/squid-engine/src/delete.rs b/crates/squid-engine/src/delete.rs new file mode 100644 index 0000000..f6a25f7 --- /dev/null +++ b/crates/squid-engine/src/delete.rs @@ -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, + pub mode: DeleteMode, + /// `squid clean`, `squid purge`, … — written to the history file. + pub command: String, +} + +impl DeleteJob { + pub fn new(items: Vec, mode: DeleteMode, command: impl Into) -> Self { + DeleteJob { + items, + mode, + command: command.into(), + } + } + + /// Items the user selected *and* the scanner allowed. + pub fn removable(&self) -> Vec { + 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 { + 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 = 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); + } +} diff --git a/crates/squid-engine/src/lib.rs b/crates/squid-engine/src/lib.rs new file mode 100644 index 0000000..7d08d95 --- /dev/null +++ b/crates/squid-engine/src/lib.rs @@ -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, + settings: Settings, + safety: SafetyPolicy, + rules: RuleSet, + whitelist: Vec, + settings_errors: Vec, +} + +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) -> 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 { + 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 { + 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 { + 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 { + 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) { + items.sort_by(|a, b| a.path.cmp(&b.path)); + let mut kept: Vec = 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()); + } +} diff --git a/crates/squid-engine/src/purge.rs b/crates/squid-engine/src/purge.rs new file mode 100644 index 0000000..641bb2c --- /dev/null +++ b/crates/squid-engine/src/purge.rs @@ -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, + /// `None` = use `settings.purge_min_age_days`, `Some(0)` = disable. + pub min_age_days: Option, + /// Ignore the age rule *and* the "tracked by git" refusal. + pub force: bool, + /// Maximum depth below each root. + pub max_depth: Option, +} + +/// 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 { + 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 = 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 { + 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, + 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 = 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + if snapshots.is_empty() { + return None; + } + Some(format!( + "{} APFS local snapshot(s) present — remove with `tmutil deletelocalsnapshots ` (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 = 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"))); + } +} diff --git a/crates/squid-engine/src/uninstall.rs b/crates/squid-engine/src/uninstall.rs new file mode 100644 index 0000000..e975d45 --- /dev/null +++ b/crates/squid-engine/src/uninstall.rs @@ -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> { + 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> { + 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 { + 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 = std::mem::take(&mut plan.warnings) + .into_iter() + .collect::>() + .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 { + 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 = 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 { + 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 { + let mut best: Option = 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 { + 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 = 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 { + let mut out: HashMap = 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()); + } +} diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml new file mode 100644 index 0000000..3aa8590 --- /dev/null +++ b/crates/squid-platform/Cargo.toml @@ -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 diff --git a/crates/squid-platform/src/apps.rs b/crates/squid-platform/src/apps.rs new file mode 100644 index 0000000..5647a28 --- /dev/null +++ b/crates/squid-platform/src/apps.rs @@ -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, + pub bundle_id: Option, + pub version: Option, + pub short_version: Option, + pub publisher: Option, + pub executable: Option, +} + +fn string_field(dict: &plist::Dictionary, key: &str) -> Option { + 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 { + 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::>() + .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 { + 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(¤t) 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 { + 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 = 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() +} diff --git a/crates/squid-platform/src/leftovers.rs b/crates/squid-platform/src/leftovers.rs new file mode 100644 index 0000000..d8a6df3 --- /dev/null +++ b/crates/squid-platform/src/leftovers.rs @@ -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_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 { + let mut matches: BTreeSet<(u8, PathBuf)> = BTreeSet::new(); + let mut dirs: BTreeSet = 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)] { + // 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, 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")); + } +} diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs new file mode 100644 index 0000000..15b6d93 --- /dev/null +++ b/crates/squid-platform/src/lib.rs @@ -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, + pub stopped_services: Vec, + pub warnings: Vec, +} + +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; + + /// 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>; + + /// Directories that may hold leftovers for the given app. + fn leftover_roots(&self) -> Vec; + + /// 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>; + + /// Absolute prefixes that must never be touched. + fn protected_prefixes(&self) -> Vec { + Vec::new() + } + + /// Process names currently running (cheap snapshot, no full table). + fn running_executables(&self) -> Vec; + + /// Human readable "why is this not removable" for a path, if any. + fn inspect_path(&self, path: &Path) -> Option { + 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 { + #[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 { + Vec::new() + } + fn list_apps(&self, _cancel: &CancelToken, _size: bool) -> Result> { + Err(squid_core::SquidError::Unsupported { + platform: std::env::consts::OS, + what: "application inventory", + }) + } + fn leftover_roots(&self) -> Vec { + Vec::new() + } + fn volumes(&self) -> Result> { + Ok(Vec::new()) + } + fn running_executables(&self) -> Vec { + 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("/"); + } + } +} diff --git a/crates/squid-platform/src/linux.rs b/crates/squid-platform/src/linux.rs new file mode 100644 index 0000000..55dcbf5 --- /dev/null +++ b/crates/squid-platform/src/linux.rs @@ -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 { + 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, + startup_wm_class: Option, + icon: Option, + no_display: bool, +} + +fn parse_desktop(path: &Path) -> Option { + 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 { + [ + ("/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> { + let running = self.running_executables(); + let mut by_id: BTreeMap = 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::().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 { + 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> { + Ok(crate::volumes::volumes_from_mounts( + &crate::volumes::mount_entries(), + )) + } + + fn protected_prefixes(&self) -> Vec { + ["/etc", "/usr", "/bin", "/sbin", "/boot", "/EFI"] + .iter() + .map(PathBuf::from) + .collect() + } + + fn running_executables(&self) -> Vec { + 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; + } +} diff --git a/crates/squid-platform/src/macos.rs b/crates/squid-platform/src/macos.rs new file mode 100644 index 0000000..a332fb2 --- /dev/null +++ b/crates/squid-platform/src/macos.rs @@ -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 { + 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 { + 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> { + 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 = 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 = 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 { + 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> { + 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 { + 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 { + 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 { + // 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 { + 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 +} diff --git a/crates/squid-platform/src/volumes.rs b/crates/squid-platform/src/volumes.rs new file mode 100644 index 0000000..aad13fa --- /dev/null +++ b/crates/squid-platform/src/volumes.rs @@ -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::() }; + 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 { + let root = PathBuf::from("/"); + let mut seen_capacity: Vec<(u64, u64)> = Vec::new(); + let mut out: Vec = 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 { + if !cfg!(target_os = "macos") { + return None; + } + let _ = mount; + None +} + +#[cfg(target_os = "macos")] +pub fn mount_entries() -> Vec { + 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 { + 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 { + 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 = 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()); + } +} diff --git a/crates/squid-platform/src/windows.rs b/crates/squid-platform/src/windows.rs new file mode 100644 index 0000000..cac9a27 --- /dev/null +++ b/crates/squid-platform/src/windows.rs @@ -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 { + 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 { + ["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> { + 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 { + ["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> { + 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::(), free.trim().parse::()) + 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 { + ["C:\\Windows", "C:\\Program Files"] + .iter() + .map(PathBuf::from) + .collect() + } + fn running_executables(&self) -> Vec { + 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 { + None + } + fn reveal_trash(&self) { + let _ = Command::new("explorer") + .arg("shell:RecycleBinFolder") + .spawn(); + } +} diff --git a/crates/squid-rules/Cargo.toml b/crates/squid-rules/Cargo.toml new file mode 100644 index 0000000..3676011 --- /dev/null +++ b/crates/squid-rules/Cargo.toml @@ -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 diff --git a/crates/squid-rules/rules/macos.toml b/crates/squid-rules/rules/macos.toml new file mode 100644 index 0000000..cce5fae --- /dev/null +++ b/crates/squid-rules/rules/macos.toml @@ -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." diff --git a/crates/squid-rules/src/lib.rs b/crates/squid-rules/src/lib.rs new file mode 100644 index 0000000..126e132 --- /dev/null +++ b/crates/squid-rules/src/lib.rs @@ -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 +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, + + #[serde(default)] + pub mode: RuleMode, + + /// Platforms this rule applies to (`macos`, `linux`, `windows`). + /// Empty means "every platform". + #[serde(default)] + pub os: Vec, + + /// Globs (matched against the absolute path *and* the path relative to the + /// pattern anchor) that must never be deleted. + #[serde(default)] + pub protect: Vec, + + /// 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, + + /// Show a warning marker in the UI. + #[serde(default)] + pub risky: bool, + + #[serde(default)] + pub note: Option, +} + +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 { + 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, +} + +/// The rules that apply to this machine, in display order. +#[derive(Clone, Debug, Default)] +pub struct RuleSet { + rules: Vec, + errors: Vec, +} + +impl RuleSet { + /// Built-in rules for the host OS plus anything the user dropped into + /// `/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 = 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::(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 { + let mut seen: Vec = 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 { + static CACHE: OnceLock>>> = 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 { + 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 { + 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 { + 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 { + 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 { + 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 = 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 = 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 { + 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, + relative: Vec, +} + +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 { + let mut out: Vec = 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 { + set.rules().iter().cloned().map(PreparedRule::new).collect() +} + +/// Utility kept for tests and `squid rules --explain`. +pub fn globset_of(patterns: &[String]) -> Option { + 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()); + } +} diff --git a/crates/squid-stats/Cargo.toml b/crates/squid-stats/Cargo.toml new file mode 100644 index 0000000..37b1359 --- /dev/null +++ b/crates/squid-stats/Cargo.toml @@ -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 diff --git a/crates/squid-stats/src/battery.rs b/crates/squid-stats/src/battery.rs new file mode 100644 index 0000000..3a8a5ca --- /dev/null +++ b/crates/squid-stats/src/battery.rs @@ -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, + /// Minutes of runtime left on battery. + pub minutes_to_empty: Option, + /// Maximum capacity versus design capacity (iStat's "Health"). + pub health_percent: Option, + pub cycle_count: Option, + pub temperature_c: Option, +} + +impl Battery { + pub fn current() -> Option { + #[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 { + 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 { + 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, Option, Option)> { + 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 { + 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 { + 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::().ok()?; + let rate = read("power_now")?.parse::().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 { + 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(); + } +} diff --git a/crates/squid-stats/src/lib.rs b/crates/squid-stats/src/lib.rs new file mode 100644 index 0000000..176f492 --- /dev/null +++ b/crates/squid-stats/src/lib.rs @@ -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, + pub volumes: Vec, + pub battery: Option, + 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, + 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, + pub wired: Option, +} + +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, +} + +#[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, + volumes_at: Option, + battery: Option, + battery_at: Option, + 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 { + 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 { + self.system.refresh_processes_specifics( + ProcessesToUpdate::All, + true, + ProcessRefreshKind::nothing().with_cpu().with_memory(), + ); + let mut merged: std::collections::HashMap = + 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 = 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 = 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 { + #[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 { + 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::(); + 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::::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> = 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 { + let mut processes: Vec = 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 { + cap: usize, + items: VecDeque, +} + +impl History { + pub fn new(cap: usize) -> History { + 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 { + 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, + pub memory: History, + pub rx: History, + pub tx: History, + pub read: History, + pub write: History, + pub uptime_secs: History, +} + +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(history: &History, width: usize) -> Vec { + 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, + pub memory: Vec, + pub rx: Vec, + pub tx: Vec, + pub read: Vec, + pub write: Vec, +} + +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); + } +} diff --git a/crates/squid-tui/Cargo.toml b/crates/squid-tui/Cargo.toml new file mode 100644 index 0000000..236faf1 --- /dev/null +++ b/crates/squid-tui/Cargo.toml @@ -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 diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs new file mode 100644 index 0000000..7b4c284 --- /dev/null +++ b/crates/squid-tui/src/app.rs @@ -0,0 +1,3377 @@ +//! Application state and input handling. +//! +//! The mental model is intentionally small: a panel is a *list of rows*, a row +//! is either a category header or one [`CleanupItem`], and the only mutation a +//! user can make is "selected / not selected". Everything destructive goes +//! through a confirmation dialog and then through [`squid_engine::delete`], +//! which re-validates every path. + +use crate::job::{self, JobHandle}; +use crate::theme::Strings; +use squid_core::ledger::Session; +use squid_core::progress::{CancelToken, Event, Progress}; +use squid_core::{ + AppInfo, Bytes, Category, CleanSummary, CleanupItem, DeleteMode, ScanReport, UninstallPlan, + Volume, +}; +use squid_engine::analyze::Node; +use squid_engine::delete::DeleteJob; +use squid_engine::delete::DeleteOutcome; +use squid_engine::Engine; +use squid_engine::{analyze, clean, delete, purge, uninstall}; +use squid_stats::{Sampler, SystemSnapshot, TrendStore}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::PathBuf; +use std::time::Instant; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Panel { + Cleanup, + Uninstall, + Purge, + Storage, + Stats, + History, +} + +impl Panel { + pub const ALL: [Panel; 6] = [ + Panel::Cleanup, + Panel::Uninstall, + Panel::Purge, + Panel::Storage, + Panel::Stats, + Panel::History, + ]; + + pub fn next(self) -> Panel { + let index = Panel::ALL.iter().position(|p| *p == self).unwrap_or(0); + Panel::ALL[(index + 1) % Panel::ALL.len()] + } + + pub fn prev(self) -> Panel { + let index = Panel::ALL.iter().position(|p| *p == self).unwrap_or(0); + Panel::ALL[(index + Panel::ALL.len() - 1) % Panel::ALL.len()] + } + + pub fn title(self, strings: &Strings) -> String { + match self { + Panel::Cleanup => strings.cleanup(), + Panel::Uninstall => strings.uninstall(), + Panel::Purge => strings.purge(), + Panel::Storage => strings.storage(), + Panel::Stats => strings.system(), + Panel::History => strings.history(), + } + } +} + +/// A row in a scan list. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Line { + Group(Category), + Item(usize), +} + +#[derive(Default)] +pub struct ScanPanel { + pub items: Vec, + pub lines: Vec, + pub collapsed: HashSet, + pub cursor: usize, + pub dirty: bool, + pub scanned_at: Option, + pub buckets: HashMap, + pub summary: Option, + pub skipped: Vec<(PathBuf, String)>, +} + +impl ScanPanel { + /// Re-derive the per-category totals from the items that are actually on + /// the list. + /// + /// The buckets arrive with the scan, but the list can shrink underneath + /// them: a delete prunes the items it removed, and every group header that + /// still printed its pre-delete size made the run look like it had done + /// nothing. Same arithmetic as `clean::publish_buckets`, so a fresh scan + /// and a recompute agree. + pub fn sync_buckets(&mut self) { + if self.items.is_empty() && self.scanned_at.is_none() { + // An empty list is also what a scan looks like before the first + // bucket event lands; that is not "everything went to zero". Once + // a scan has actually happened, an empty list *is* the total. + return; + } + let mut totals: HashMap = HashMap::new(); + for item in &self.items { + let entry = totals.entry(item.category).or_insert((Bytes::ZERO, 0)); + entry.0 += item.on_disk(); + entry.1 += 1; + } + self.buckets = totals; + } + + pub fn rebuild_lines(&mut self) { + self.sync_buckets(); + let mut order: Vec = Category::ALL.to_vec(); + order.sort_by(|a, b| { + let total_of = |category: &Category| -> u64 { + self.items + .iter() + .filter(|item| item.category == *category) + .map(|item| item.on_disk().as_u64()) + .sum() + }; + total_of(b).cmp(&total_of(a)) + }); + let mut lines = Vec::new(); + for category in order { + let mut indexes: Vec = (0..self.items.len()) + .filter(|index| self.items[*index].category == category) + .collect(); + if indexes.is_empty() { + continue; + } + indexes.sort_by(|a, b| { + let left = self.items[*a].on_disk(); + let right = self.items[*b].on_disk(); + right.cmp(&left) + }); + lines.push(Line::Group(category)); + if !self.collapsed.contains(&category) { + lines.extend(indexes.into_iter().map(Line::Item)); + } + } + self.lines = lines; + self.cursor = self.cursor.min(self.lines.len().saturating_sub(1)); + self.dirty = false; + } + + pub fn selected_size(&self) -> Bytes { + self.items + .iter() + .filter(|item| item.selected && item.lock.is_none()) + .map(|item| item.on_disk()) + .sum() + } + + pub fn selected_count(&self) -> usize { + self.items + .iter() + .filter(|item| item.selected && item.lock.is_none()) + .count() + } + + pub fn total_size(&self) -> Bytes { + self.items.iter().map(|item| item.on_disk()).sum() + } + + pub fn toggle_at(&mut self, line: usize) { + match self.lines.get(line) { + Some(Line::Item(index)) => { + if let Some(item) = self.items.get_mut(*index) { + if item.lock.is_none() { + item.selected = !item.selected; + } + } + } + Some(Line::Group(category)) => { + let category = *category; + let target = !self + .items + .iter() + .filter(|item| item.category == category && item.lock.is_none()) + .all(|item| item.selected); + for item in self + .items + .iter_mut() + .filter(|item| item.category == category && item.lock.is_none()) + { + item.selected = target; + } + } + None => {} + } + } + + pub fn toggle_all(&mut self) { + let target = !self + .items + .iter() + .filter(|item| item.lock.is_none()) + .all(|item| item.selected); + for item in self.items.iter_mut() { + if item.lock.is_none() { + item.selected = target; + } + } + } + + pub fn collapse_at(&mut self, line: usize, open: bool) { + if let Some(Line::Group(category)) = self.lines.get(line).copied() { + if open { + self.collapsed.remove(&category); + } else { + self.collapsed.insert(category); + } + self.dirty = true; + } + } + + pub fn load(&mut self, report: ScanReport) { + self.items = report.items; + self.scanned_at = Some(report.scanned_at_ms); + self.dirty = true; + self.rebuild_lines(); + } + + pub fn clear(&mut self) { + self.items.clear(); + self.lines.clear(); + self.buckets.clear(); + self.cursor = 0; + self.dirty = false; + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum UninstallView { + #[default] + List, + Plan, +} + +#[derive(Default)] +pub struct UninstallPanel { + pub apps: Vec, + pub filter: String, + pub cursor: usize, + pub view: UninstallView, + pub plan: Option, + pub lines: Vec, + pub plan_cursor: usize, + pub dirty: bool, + pub summary: Option, +} + +impl UninstallPanel { + pub fn visible(&self) -> Vec { + let needle = self.filter.trim().to_lowercase(); + (0..self.apps.len()) + .filter(|index| { + if needle.is_empty() { + true + } else { + let app = &self.apps[*index]; + app.name.to_lowercase().contains(&needle) + || app + .bundle_id + .as_deref() + .unwrap_or_default() + .to_lowercase() + .contains(&needle) + } + }) + .collect() + } + + pub fn selected_app(&self) -> Option { + let visible = self.visible(); + let raw = *visible.get(self.cursor)?; + self.apps.get(raw).cloned() + } + + pub fn set_plan(&mut self, plan: UninstallPlan) { + self.plan = Some(plan); + self.view = UninstallView::Plan; + self.plan_cursor = 0; + self.rebuild_lines(); + } + + pub fn rebuild_lines(&mut self) { + let Some(plan) = &self.plan else { + self.lines.clear(); + self.dirty = false; + return; + }; + self.lines = (0..plan.items.len()).map(Line::Item).collect(); + self.plan_cursor = self.plan_cursor.min(self.lines.len().saturating_sub(1)); + self.dirty = false; + } + + /// Tick or untick one line of the plan. Returns why the key did nothing, + /// so the caller can say so instead of swallowing the press. + pub fn toggle_plan_at(&mut self, line: usize) -> Option<&'static str> { + let plan = self.plan.as_mut()?; + let mut refused = None; + match self.lines.get(line) { + Some(Line::Item(index)) => { + if let Some(item) = plan.items.get_mut(*index) { + // The bundle itself is the uninstall; keep it immovable. + let is_bundle = item.rule_id == "uninstall-bundle"; + if is_bundle { + refused = Some("bundle"); + } else if item.lock.is_some() { + refused = Some("locked"); + } else { + item.selected = !item.selected; + } + } + } + Some(Line::Group(_)) => { + let target = !plan + .items + .iter() + .filter(|item| item.lock.is_none() && item.rule_id != "uninstall-bundle") + .all(|item| item.selected); + for item in plan.items.iter_mut() { + if item.lock.is_none() && item.rule_id != "uninstall-bundle" { + item.selected = target; + } + } + } + None => {} + } + refused + } + + /// `a` inside a plan: tick or untick every leftover. The bundle keeps its + /// permanent tick — "all" never means "keep the application". + pub fn toggle_all_leftovers(&mut self) { + let Some(plan) = self.plan.as_mut() else { + return; + }; + let target = !plan + .items + .iter() + .filter(|item| item.lock.is_none() && item.rule_id != "uninstall-bundle") + .all(|item| item.selected); + for item in plan.items.iter_mut() { + if item.lock.is_none() && item.rule_id != "uninstall-bundle" { + item.selected = target; + } + } + } + + pub fn plan_selected_size(&self) -> Bytes { + let Some(plan) = &self.plan else { + return Bytes::ZERO; + }; + plan.items + .iter() + .filter(|item| item.selected && item.lock.is_none()) + .map(|item| item.on_disk()) + .sum() + } + + pub fn remove_deleted(&mut self, removed_paths: &[PathBuf]) { + self.apps + .retain(|app| !removed_paths.iter().any(|path| path == &app.path)); + self.plan = None; + self.view = UninstallView::List; + self.lines.clear(); + // The filter existed to find the app that is now gone. Leaving it set + // is how a finished uninstall reads as an empty, dead panel. + self.filter.clear(); + self.cursor = self.cursor.min(self.visible().len().saturating_sub(1)); + } +} + +#[derive(Default)] +pub struct StoragePanel { + pub stack: Vec, + pub cursor: usize, + pub files: Vec, + pub show_files: bool, + pub volumes: Vec, + pub root: PathBuf, + pub scanned: bool, +} + +impl StoragePanel { + pub fn current(&self) -> Option<&Node> { + self.stack.last() + } + + pub fn rows(&self) -> usize { + match self.current() { + Some(node) => node.children.len() + usize::from(node.folded > 0), + None => 0, + } + } + + pub fn child_at(&self, index: usize) -> Option { + let node = self.current()?; + node.display_children().into_iter().nth(index) + } +} + +pub struct StatsPanel { + pub sampler: Sampler, + pub snapshot: Option, + pub trends: TrendStore, + pub cursor: usize, + pub last_refresh: Instant, +} + +impl StatsPanel { + pub fn new() -> StatsPanel { + StatsPanel { + sampler: Sampler::new(), + snapshot: None, + trends: TrendStore::default(), + cursor: 0, + last_refresh: Instant::now(), + } + } + + pub fn refresh(&mut self) { + let snapshot = if self.snapshot.is_none() { + self.sampler.prime() + } else { + self.sampler.refresh() + }; + self.trends.record(&snapshot); + self.snapshot = Some(snapshot); + self.last_refresh = Instant::now(); + } +} + +impl Default for StatsPanel { + fn default() -> Self { + StatsPanel::new() + } +} + +#[derive(Default)] +pub struct HistoryPanel { + pub sessions: Vec, + pub cursor: usize, +} + +impl HistoryPanel { + pub fn reload(&mut self) { + // The same window the header totals are built from, so the session + // count in the header cannot change under the user just because the + // panel refreshed. + self.sessions = squid_core::ledger::load_sessions(200); + self.cursor = self.cursor.min(self.sessions.len().saturating_sub(1)); + } +} + +#[derive(Clone, Debug)] +pub enum ConfirmAction { + Clean, + Purge, + Uninstall, + UndoSession(String), +} + +/// What the user approved, carrying everything needed to carry it out. +/// +/// This used to be two sibling fields — `pending` (items) and `pending_plan` +/// (the app) — and nothing ever filled the plan one. Approving an uninstall +/// therefore fell straight through a `let-else` and the keypress vanished: +/// dialog closed, no toast, no log, app still installed. One enum makes the +/// "uninstall approved but the plan is missing" state unrepresentable. +#[derive(Clone, Debug)] +pub enum Approval { + Items { + items: Vec, + purge: bool, + }, + Plan(UninstallPlan), + UndoSession(String), +} + +#[derive(Clone, Debug)] +pub struct Confirm { + pub title: String, + pub lines: Vec, + pub action: ConfirmAction, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToastKind { + Info, + Good, + Warn, +} + +#[derive(Clone, Debug)] +pub struct Toast { + pub text: String, + pub kind: ToastKind, + pub until: Instant, +} + +/// Everything that can be running at once. Only one job at a time is allowed, +/// which keeps the progress bar honest. +#[derive(Default)] +pub struct Jobs { + pub clean: Option>, + pub purge: Option>, + pub apps: Option>>, + pub plan: Option>, + pub storage: Option>, + pub files: Option>>, + pub delete: Option>, + pub delete_target: Option, +} + +impl Jobs { + pub fn any(&self) -> bool { + self.clean.is_some() + || self.purge.is_some() + || self.apps.is_some() + || self.plan.is_some() + || self.storage.is_some() + || self.files.is_some() + || self.delete.is_some() + } + + /// The work the user asked for with a key. One of these runs at a time, so + /// the progress bar always answers to the key that was pressed. + pub fn foreground(&self) -> bool { + self.clean.is_some() + || self.purge.is_some() + || self.apps.is_some() + || self.plan.is_some() + || self.files.is_some() + || self.delete.is_some() + } + + pub fn occupied(&self, slot: Slot) -> bool { + match slot { + Slot::Clean => self.clean.is_some(), + Slot::Purge => self.purge.is_some(), + Slot::Apps => self.apps.is_some(), + Slot::Plan => self.plan.is_some(), + Slot::Storage => self.storage.is_some(), + Slot::Files => self.files.is_some(), + Slot::Delete => self.delete.is_some(), + } + } + + /// The foreground job worth naming in a refusal. + pub fn foreground_slot(&self) -> Option { + [ + Slot::Delete, + Slot::Clean, + Slot::Purge, + Slot::Apps, + Slot::Plan, + Slot::Files, + ] + .into_iter() + .find(|&slot| self.occupied(slot)) + } +} + +/// One keyboard entry point, one slot. Refusal is decided per slot, never +/// "is anything at all running": a disk map of a home folder takes tens of +/// seconds and used to hold the whole interface hostage, so the second +/// uninstall of a session answered "the previous task is still running". +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Slot { + Clean, + Purge, + Apps, + Plan, + Storage, + Files, + Delete, +} + +pub struct App { + pub engine: Engine, + pub strings: Strings, + pub panel: Panel, + pub should_quit: bool, + pub jobs: Jobs, + pub progress: Option, + pub cancel: Option, + pub phase: String, + pub done: u64, + pub total: Option, + pub subject: Option, + pub log: VecDeque, + pub clean: ScanPanel, + pub purge: ScanPanel, + pub uninstall: UninstallPanel, + pub storage: StoragePanel, + pub stats: StatsPanel, + pub history: HistoryPanel, + pub confirm: Option, + pub toast: Option, + pub help: bool, + pub filtering: bool, + pub reclaimed: Bytes, + /// The part of `reclaimed` that is only *in the Trash*, and therefore still + /// occupying the volume until the Trash is emptied. + pub to_trash: Bytes, + pub sessions: usize, + pub delete_mode: DeleteMode, + /// What the dialog approved, waiting for `confirm_delete` to carry it out. + pub pending: Option, + /// Set while a storage drill-down is running so the result is pushed, + /// not swapped in. + pub pending_drill: bool, + /// The disk walk running *beside* the job the progress bar belongs to. + /// Drained quietly: it may never take over the bar or the phase line. + pub bg: Option, + /// Keyboard focus. `false` means the arrows drive the list, `true` means + /// they drive the six entries in the sidebar. + pub menu: bool, + /// The panel a running scan is filling. Streamed buckets belong to the + /// panel whose key started the walk, not to whichever panel happens to be + /// on screen when one arrives. + pub scan_owner: Option, +} + +/// `(all removed, still in the Trash)` over a stretch of the ledger. +/// +/// Undone runs count for neither: [`Session::kept`] is the only honest summand. +fn totals(sessions: &[squid_core::ledger::Session]) -> (Bytes, Bytes) { + let mut all = Bytes::ZERO; + let mut trash = Bytes::ZERO; + for session in sessions { + let kept = session.kept(); + all += kept; + if session.mode == DeleteMode::Trash { + trash += kept; + } + } + (all, trash) +} + +impl App { + pub fn new() -> squid_core::Result { + let engine = Engine::new(); + let strings = Strings::detect(engine.settings()); + let delete_mode = engine.settings().delete_mode; + // The walk starts where the user's own bytes live. Rooting it at `/` + // made the first thing the panel does a trawl across two million + // inodes — minutes of "computing…" before a single bar — and most of + // that tree is not something this panel can clean anyway. + // `squid analyze` already defaults to the home folder; the panel agrees + // with it, and its heading always names the folder being measured. + let storage_root = squid_core::paths::home_dir(); + let sessions = squid_core::ledger::load_sessions(200); + let (reclaimed, to_trash) = totals(&sessions); + let mut app = App { + engine, + strings, + panel: Panel::Cleanup, + should_quit: false, + jobs: Jobs::default(), + progress: None, + cancel: None, + phase: String::new(), + done: 0, + total: None, + subject: None, + log: VecDeque::new(), + clean: ScanPanel::default(), + purge: ScanPanel::default(), + uninstall: UninstallPanel::default(), + storage: StoragePanel { + root: storage_root, + ..StoragePanel::default() + }, + stats: StatsPanel::new(), + history: HistoryPanel::default(), + confirm: None, + toast: None, + help: false, + filtering: false, + reclaimed, + to_trash, + sessions: sessions.len(), + delete_mode, + pending: None, + pending_drill: false, + bg: None, + // The interface opens where the choice is made. A list of junk + // files is not the first thing anyone should have to ignore before + // they can say which of the six functions they want; the arrows + // start on the sidebar and `esc` hands them to the list. + menu: true, + scan_owner: None, + }; + app.push_log(format!( + "squid {} · {}", + env!("CARGO_PKG_VERSION"), + app.engine.platform().display_name() + )); + for error in app.engine.settings_errors().to_vec() { + app.push_log(format!("config: {error}")); + } + // Ask the terminal what it can paint *now*, before a single cell is + // drawn, rather than finding out from the first card that came out + // wrong. Anything short of 24-bit falls back to the 256-colour palette + // and a terminal with no palette at all to attributes alone. + let colours = crate::theme::init(); + app.push_log(app.strings.t( + &format!("colour · {}", colours.label()), + &format!("色彩 · {}", colours.label()), + )); + // And which switch chose the language: one binary that is Chinese in + // one terminal and English in another is a report nobody can act on + // without knowing where the answer came from. + let (locale, source) = squid_core::Locale::explain(app.engine.settings()); + app.push_log(app.strings.t( + &format!("language · {} ({})", locale.code(), source.describe()), + &format!("语言 · {}({})", locale.code(), source.describe_zh()), + )); + app.storage.volumes = app.engine.platform().volumes().unwrap_or_default(); + app.history.reload(); + app.open_menu(); + Ok(app) + } + + /// Refusing to start a second job while one is running is right; refusing + /// *silently* — or refusing on behalf of an unrelated job — is how a user + /// ends up pressing return twice with nothing on screen. Every long-running + /// entry point asks about *its own* slot and says what it found. + fn busy_refusal(&mut self, slot: Slot) -> bool { + if !self.slot_busy(slot) { + return false; + } + let blocker = self + .jobs + .occupied(slot) + .then_some(slot) + .or_else(|| self.jobs.foreground_slot()) + .unwrap_or(slot); + let name = self.slot_name(blocker); + self.toast( + self.strings.t( + &format!("{name} is still running — wait, or press c to cancel"), + &format!("{name}还在进行,请稍候,或按 c 取消"), + ), + ToastKind::Warn, + ); + true + } + + /// Can this slot start right now? The disk walk is the one job allowed to + /// run beside a foreground job: it is read-only, it is what the storage + /// panel needs, and refusing everything else while it re-walks a home + /// folder is what looked like the interface locking up. + fn slot_busy(&self, slot: Slot) -> bool { + self.jobs.occupied(slot) || (slot != Slot::Storage && self.jobs.foreground()) + } + + fn slot_name(&self, slot: Slot) -> String { + let (en, zh) = match slot { + Slot::Clean => ("clean scan", "清理扫描"), + Slot::Purge => ("deep clean scan", "深度清理扫描"), + Slot::Apps => ("app list", "应用列表"), + Slot::Plan => ("leftover search", "残留搜索"), + Slot::Storage => ("disk scan", "磁盘扫描"), + Slot::Files => ("large-file scan", "大文件扫描"), + Slot::Delete => ("deletion", "删除"), + }; + self.strings.t(en, zh).to_string() + } + + pub fn busy(&self) -> bool { + self.jobs.any() + } + + /// Is the work that fills this panel still on its way? + /// + /// An empty panel has two opposite reasons for being empty — the list is + /// still being read, or there is genuinely nothing there — and they want + /// opposite answers on screen. Saying "未发现应用 / 按 s 重新扫描" while the + /// inventory is still being read sends the user to a key that does nothing, + /// which reads as the interface ignoring them. + pub fn filling(&self, panel: Panel) -> bool { + App::filling_slot(panel) + .map(|slot| self.jobs.occupied(slot)) + .unwrap_or(false) + } + + /// Which job, if any, is the one that populates this panel. + fn filling_slot(panel: Panel) -> Option { + match panel { + Panel::Cleanup => Some(Slot::Clean), + Panel::Purge => Some(Slot::Purge), + Panel::Uninstall => Some(Slot::Apps), + Panel::Storage => Some(Slot::Storage), + Panel::Stats | Panel::History => None, + } + } + + pub fn push_log(&mut self, text: impl Into) { + let text = text.into(); + if self.log.back().map(|last| last == &text).unwrap_or(false) { + return; + } + if self.log.len() >= 200 { + self.log.pop_front(); + } + self.log.push_back(text); + } + + pub fn toast(&mut self, text: impl Into, kind: ToastKind) { + self.toast = Some(Toast { + text: text.into(), + kind, + until: Instant::now() + std::time::Duration::from_secs(4), + }); + } + + /// Called ~4 times a second: drain events, collect finished jobs, refresh + /// the meters. + pub fn tick(&mut self) { + if let Some(progress) = self.progress.clone() { + for event in progress.drain() { + self.apply_event(event); + } + } + if let Some(progress) = self.bg.clone() { + for event in progress.drain() { + self.apply_bg_event(event); + } + } + self.poll_jobs(); + if self.panel == Panel::Stats + && (self.stats.snapshot.is_none() + || self.stats.last_refresh.elapsed().as_secs_f64() > 1.0) + { + self.stats.refresh(); + } + if let Some(toast) = &self.toast { + if toast.until < Instant::now() { + self.toast = None; + } + } + } + + fn apply_event(&mut self, event: Event) { + match event { + Event::Phase { phase, detail } => { + self.phase = format!("{phase} · {detail}"); + self.push_log(format!("{phase}: {detail}")); + } + Event::Tick { + done, + total, + subject, + } => { + self.done = done; + if total.is_some() { + self.total = total; + } + self.subject = subject; + } + Event::Bucket { + category, + total, + count, + } => { + let panel = self.scan_owner.unwrap_or(self.panel); + let panel = match panel { + Panel::Purge => &mut self.purge, + _ => &mut self.clean, + }; + panel.buckets.insert(category, (total, count)); + } + Event::Deleted { path, freed } => { + self.push_log(format!( + "removed {} ({})", + squid_core::paths::pretty(&path), + freed.human() + )); + } + Event::Note(text) => self.push_log(text), + Event::Warning(text) => { + let clipped = crate::theme::truncate(&text, 160, false); + self.push_log(format!("! {clipped}")); + self.toast(clipped, ToastKind::Warn); + } + Event::Done(report) => { + let panel = self.scan_owner.unwrap_or(self.panel); + let panel = match panel { + Panel::Purge => &mut self.purge, + _ => &mut self.clean, + }; + panel.load(report); + } + } + } + + /// A background disk walk shares the log but not the progress bar: its + /// phases belong to nobody, so only its notes and warnings are kept. + fn apply_bg_event(&mut self, event: Event) { + match event { + Event::Note(text) => self.push_log(text), + Event::Warning(text) => { + let clipped = crate::theme::truncate(&text, 160, false); + self.push_log(format!("! {clipped}")); + } + _ => {} + } + } + + fn poll_jobs(&mut self) { + if let Some(handle) = &self.jobs.clean { + if let Some(result) = handle.poll() { + self.jobs.clean = None; + self.scan_owner = None; + self.finish_job(); + self.apply_report(Panel::Cleanup, result); + } + } + if let Some(handle) = &self.jobs.purge { + if let Some(result) = handle.poll() { + self.jobs.purge = None; + self.scan_owner = None; + self.finish_job(); + self.apply_report(Panel::Purge, result); + } + } + if let Some(handle) = &self.jobs.apps { + if let Some(result) = handle.poll() { + self.jobs.apps = None; + self.finish_job(); + match result { + Ok(apps) => { + let count = apps.len(); + self.uninstall.apps = apps; + self.uninstall.cursor = 0; + self.toast( + self.strings.t( + &format!("{count} applications found"), + &format!("发现 {count} 个应用"), + ), + ToastKind::Good, + ); + } + Err(err) => self.toast(err, ToastKind::Warn), + } + } + } + if let Some(handle) = &self.jobs.plan { + if let Some(result) = handle.poll() { + self.jobs.plan = None; + self.finish_job(); + match result { + Ok(plan) => { + let items = plan.items.len(); + let size = plan.items.iter().map(|item| item.on_disk()).sum::(); + self.uninstall.set_plan(plan); + self.toast( + format!( + "{} · {items} · {}", + self.strings.t("leftovers found", "发现残留"), + size.human() + ), + ToastKind::Good, + ); + } + Err(err) => self.toast(err, ToastKind::Warn), + } + } + } + if let Some(handle) = &self.jobs.storage { + if let Some(result) = handle.poll() { + self.jobs.storage = None; + self.bg = None; + self.finish_job(); + match result { + Ok(node) => { + if self.pending_drill { + self.pending_drill = false; + self.storage.stack.push(node); + } else { + self.storage.stack = vec![node]; + } + self.storage.cursor = 0; + self.storage.scanned = true; + self.toast(self.strings.t("scan complete", "扫描完成"), ToastKind::Good); + } + Err(err) => self.toast(err, ToastKind::Warn), + } + } + } + if let Some(handle) = &self.jobs.files { + if let Some(result) = handle.poll() { + self.jobs.files = None; + self.finish_job(); + match result { + Ok(files) => { + self.storage.files = files; + self.storage.show_files = true; + } + Err(err) => self.toast(err, ToastKind::Warn), + } + } + } + if let Some(handle) = &self.jobs.delete { + if let Some(result) = handle.poll() { + let target = self.jobs.delete_target.take().unwrap_or(Panel::Cleanup); + self.jobs.delete = None; + self.finish_job(); + match result { + Ok(outcome) => self.apply_deletion(target, outcome), + Err(err) => self.toast(err, ToastKind::Warn), + } + } + } + } + + /// Re-read the ledger and recompute the two figures the header prints. + /// + /// They were counters: `+= freed` after a delete, and nothing at all after + /// an undo, so putting 24 GB back left the header promising it forever. The + /// ledger is the only thing that knows what actually happened, so both + /// numbers come from it — which also refreshes the history panel with the + /// run that just finished instead of waiting for `r`. + pub fn recount(&mut self) { + self.history.reload(); + let (reclaimed, to_trash) = totals(&self.history.sessions); + self.reclaimed = reclaimed; + self.to_trash = to_trash; + self.sessions = self.history.sessions.len(); + } + + fn finish_job(&mut self) { + if self.jobs.foreground() { + return; + } + // Nothing the user asked for is left. A disk walk that was running + // beside it may as well use the bar now that it is free. + if let Some(progress) = self.bg.take() { + self.progress = Some(progress); + self.phase = "storage".to_string(); + self.done = 0; + self.total = None; + self.subject = None; + return; + } + // A disk walk can still be going, and it must not keep the last job's + // gauge on screen: a bar that reads "delete · 4/4" after the toast + // said "已删除" is indistinguishable from a wedged interface. + self.progress = None; + self.cancel = None; + self.phase.clear(); + self.total = None; + self.done = 0; + self.subject = None; + } + + fn apply_report(&mut self, panel: Panel, result: Result) { + match result { + Ok(report) => { + let items = self.strings.count(report.items.len()); + let size = report.total_all(); + let target = if panel == Panel::Purge { + &mut self.purge + } else { + &mut self.clean + }; + target.load(report); + self.toast( + format!( + "{} · {}", + self.strings + .t(&format!("{items} found"), &format!("发现 {items}")), + size.human_long() + ), + ToastKind::Good, + ); + } + Err(err) => self.toast(err, ToastKind::Warn), + } + } + + fn apply_deletion(&mut self, target: Panel, outcome: DeleteOutcome) { + let summary = outcome.summary.clone(); + for (path, reason) in &outcome.skipped { + self.push_log(format!( + "skipped {} — {reason}", + squid_core::paths::pretty(path) + )); + } + let freed = summary.freed_on_disk(); + // The worker wrote the session before it returned, so the ledger is + // already the truth; read it rather than second-guessing it here. + self.recount(); + let removed_count = self.strings.count(summary.removed); + // 「已删除」 over a run that only renamed files into ~/.Trash is the same + // lie the header used to tell, one screen earlier and one second + // before the user checked `df`. + let trashed = summary.mode == Some(DeleteMode::Trash); + let message = format!( + "{} · {}", + if trashed { + self.strings.t( + &format!("{removed_count} to Trash"), + &format!("移入废纸篓 {removed_count}"), + ) + } else { + self.strings.t( + &format!("{removed_count} removed"), + &format!("已删除 {removed_count}"), + ) + }, + freed.human_fixed() + ); + // A partial run must not look like a clean success: the bug that hid + // "the .app was never deleted" was a green toast counting only the + // leftovers, because a *skipped* item is not counted as a failure. + let skipped = outcome.skipped.len(); + let toast = if skipped == 0 { + message.clone() + } else { + format!( + "{message} · {}", + self.strings.t( + &format!("{skipped} skipped"), + &format!("{skipped} 项被跳过") + ) + ) + }; + self.toast( + toast, + if summary.failed == 0 && skipped == 0 { + ToastKind::Good + } else { + ToastKind::Warn + }, + ); + self.push_log(message); + for error in summary.errors.iter().take(5) { + self.push_log(format!("! {error}")); + } + let removed: Vec = self.removed_paths(&summary); + match target { + Panel::Cleanup => { + self.clean + .items + .retain(|item| !removed.contains(&item.path)); + self.clean.summary = Some(summary.clone()); + self.clean.dirty = true; + self.clean.rebuild_lines(); + } + Panel::Purge => { + self.purge + .items + .retain(|item| !removed.contains(&item.path)); + self.purge.summary = Some(summary.clone()); + self.purge.dirty = true; + self.purge.rebuild_lines(); + } + Panel::Uninstall => { + self.uninstall.remove_deleted(&removed); + self.uninstall.summary = Some(summary.clone()); + } + _ => {} + } + self.storage.volumes = self.engine.platform().volumes().unwrap_or_default(); + self.refresh_storage_after(&removed); + // A cleanup that really removed something just invalidated every number + // on the panel it came from, so scan it again — the same job `s` starts. + // Pruning the list by hand only hides the deleted rows; it cannot know + // that the cache directory rebuilt itself, or that a rule now finds a + // different set of files. + if summary.removed > 0 && matches!(target, Panel::Cleanup | Panel::Purge) { + self.push_log( + self.strings + .t("rescanning after the delete", "清理完成,正在重新扫描"), + ); + self.scan_panel(target, false); + } + } + + /// Keep the disk map honest after a delete without holding the interface + /// hostage: the refresh runs beside whatever the user does next, it is + /// skipped while another walk is already going, and it never throws away a + /// drill-down the user is reading. + fn refresh_storage_after(&mut self, removed: &[PathBuf]) { + if !self.storage.scanned { + return; + } + let touches_map = removed.iter().any(|path| { + path.starts_with(&self.storage.root) || self.storage.root.starts_with(path) + }); + if !touches_map { + return; + } + if self.storage.stack.len() > 1 { + self.push_log(self.strings.t( + "disk map is stale — press r to rescan", + "磁盘占用待刷新 — 按 r 重新扫描", + )); + return; + } + if self.jobs.storage.is_some() { + return; + } + self.start_storage_scan(); + } + + fn removed_paths(&self, summary: &CleanSummary) -> Vec { + summary + .session_id + .as_deref() + .and_then(squid_core::ledger::load_session) + .map(|session| { + session + .entries + .into_iter() + .map(|entry| entry.path) + .collect() + }) + .unwrap_or_default() + } + + // ---------------------------------------------------------------- actions + + pub fn scan(&mut self) { + self.scan_panel(self.panel, true); + } + + /// Start the scan for one panel. `ask` is what makes the `s` key say "one + /// is already running" out loud, while a rescan the interface starts for + /// itself after a delete stays silent and simply steps aside. + fn scan_panel(&mut self, panel: Panel, ask: bool) { + match panel { + Panel::Cleanup => { + if self.slot_busy(Slot::Clean) { + if ask { + self.busy_refusal(Slot::Clean); + } + return; + } + let (handle, progress) = job::spawn("clean", |engine, progress, cancel| { + let report = + clean::scan(engine, &clean::CleanOptions::default(), progress, cancel)?; + clean::publish_buckets(&report, progress); + Ok(clean::sort_for_display(report)) + }); + self.jobs.clean = Some(handle); + self.scan_owner = Some(Panel::Cleanup); + self.clean.clear(); + self.start_progress(progress, "clean"); + } + Panel::Purge => { + if self.slot_busy(Slot::Purge) { + if ask { + self.busy_refusal(Slot::Purge); + } + return; + } + let (handle, progress) = job::spawn("purge", |engine, progress, cancel| { + let report = + purge::scan(engine, &purge::PurgeOptions::default(), progress, cancel)?; + let mut report = report; + report.items.sort_by(|a, b| { + b.on_disk() + .cmp(&a.on_disk()) + .then_with(|| a.path.cmp(&b.path)) + }); + Ok(report) + }); + self.jobs.purge = Some(handle); + self.scan_owner = Some(Panel::Purge); + self.purge.clear(); + self.start_progress(progress, "purge"); + } + Panel::Uninstall => { + if self.slot_busy(Slot::Apps) { + if ask { + self.busy_refusal(Slot::Apps); + } + return; + } + let (handle, progress) = job::spawn("apps", |engine, progress, cancel| { + uninstall::scan_apps(engine, true, progress, cancel) + }); + self.jobs.apps = Some(handle); + self.start_progress(progress, "apps"); + } + Panel::Storage => self.rescan_storage(), + Panel::Stats => self.stats.refresh(), + Panel::History => self.history.reload(), + } + } + + /// Hand the bar to a job and say what it is doing. + fn set_bar(&mut self, progress: Progress, label: &str) { + self.progress = Some(progress); + self.phase = label.to_string(); + self.done = 0; + self.total = None; + self.subject = None; + self.push_log(format!("· {label}")); + } + + /// Hand the bar to a job the user asked for with a key. + /// + /// A disk walk that was holding the bar steps aside into [`App::bg`] + /// instead of losing its handle: dropping it here is what left a finished + /// delete printing its gauge, because the walk kept `jobs.any()` true and + /// the gauge only cleared when *everything* had stopped. + fn start_progress(&mut self, progress: Progress, label: &str) { + if self.jobs.storage.is_some() && self.bg.is_none() && self.progress.is_some() { + self.bg = self.progress.take(); + } + self.set_bar(progress, label); + } + + pub fn rescan_storage(&mut self) { + if self.busy_refusal(Slot::Storage) { + return; + } + self.start_storage_scan(); + } + + /// Start the walk without asking anyone. When the user is already waiting + /// on a job the progress bar stays theirs and the walk reports to the log. + fn start_storage_scan(&mut self) { + let root = self.storage.root.clone(); + let (handle, progress) = job::spawn("storage", move |engine, progress, cancel| { + let _ = engine; + analyze::explore(&root, 1, 24, cancel, progress) + }); + self.jobs.storage = Some(handle); + if self.jobs.foreground() { + self.bg = Some(progress); + self.push_log("· storage"); + } else { + self.set_bar(progress, "storage"); + } + } + + pub fn drill_storage(&mut self) { + if self.busy_refusal(Slot::Storage) { + return; + } + let Some(node) = self.storage.child_at(self.storage.cursor) else { + return; + }; + if !node.is_dir { + self.toast( + self.strings.t("not a folder", "不是文件夹"), + ToastKind::Info, + ); + return; + } + let path = node.path.clone(); + let (handle, progress) = job::spawn("storage", move |engine, progress, cancel| { + let _ = engine; + analyze::explore(&path, 1, 24, cancel, progress) + }); + self.jobs.storage = Some(handle); + if self.jobs.foreground() { + self.bg = Some(progress); + self.push_log("· storage"); + } else { + self.set_bar(progress, "storage"); + } + self.storage.cursor = 0; + self.pending_drill = true; + } + + pub fn up_storage(&mut self) { + if self.pending_drill { + self.abandon(Slot::Storage); + } + if self.storage.stack.len() > 1 { + self.storage.stack.pop(); + self.storage.cursor = 0; + } + } + + pub fn largest_files(&mut self) { + if self.busy_refusal(Slot::Files) { + return; + } + let root = self + .storage + .current() + .map(|node| node.path.clone()) + .unwrap_or_else(|| self.storage.root.clone()); + let (handle, progress) = job::spawn("files", move |engine, progress, cancel| { + let _ = engine; + analyze::largest_files( + &root, + 60, + squid_core::Bytes(20 * 1024 * 1024), + cancel, + progress, + ) + }); + self.jobs.files = Some(handle); + self.start_progress(progress, "files"); + } + + pub fn build_plan(&mut self) { + if self.busy_refusal(Slot::Plan) { + return; + } + let Some(app) = self.uninstall.selected_app() else { + self.toast( + self.strings.t("pick an app first", "先选择一个应用"), + ToastKind::Info, + ); + return; + }; + let name = app.name.clone(); + let (handle, progress) = job::spawn("plan", move |engine, progress, cancel| { + uninstall::build_plan(engine, &app, progress, cancel) + }); + self.jobs.plan = Some(handle); + self.start_progress(progress, &format!("plan · {name}")); + } + + pub fn ask_delete(&mut self) { + if self.confirm.is_some() || self.busy_refusal(Slot::Delete) { + return; + } + // The dialog heading is the *verb the user is approving*, once. The + // first version prefixed every title with "Clean", so an uninstall + // asked for permission to "Clean · Uninstall". + let (items, action, title) = match self.panel { + Panel::Cleanup => ( + self.clean.items.clone(), + ConfirmAction::Clean, + self.strings.t("Clean now", "立即清理"), + ), + Panel::Purge => ( + self.purge.items.clone(), + ConfirmAction::Purge, + self.strings.t("Deep clean now", "立即深度清理"), + ), + Panel::Uninstall => match &self.uninstall.plan { + Some(plan) => ( + plan.items.clone(), + ConfirmAction::Uninstall, + format!("{} · {}", self.strings.uninstall(), plan.app.name), + ), + None => { + self.toast( + self.strings.t( + "press enter to inspect an app first", + "先按回车检查某个应用", + ), + ToastKind::Info, + ); + return; + } + }, + _ => { + self.toast( + self.strings + .t("nothing to clean here", "这里没有可清理的内容"), + ToastKind::Info, + ); + return; + } + }; + let chosen: Vec = items + .into_iter() + .filter(|item| item.selected && item.lock.is_none()) + .collect(); + if chosen.is_empty() { + self.toast( + self.strings + .t("select something first", "先勾选要删除的内容"), + ToastKind::Info, + ); + return; + } + let size: Bytes = chosen.iter().map(|item| item.on_disk()).sum(); + let mode = if self.delete_mode == DeleteMode::Trash { + self.strings.t("moved to Trash", "移入废纸篓") + } else { + self.strings.t("deleted permanently", "永久删除") + }; + let biggest = chosen + .iter() + .take(6) + .map(|item| format!(" {}", item.display_path())) + .collect::>(); + let mut lines = vec![ + format!( + "{} · {}", + self.strings.t( + &format!("{} items", chosen.len()), + &format!("{} 个项目", chosen.len()) + ), + size.human_long() + ), + self.strings + .t(&format!("Mode: {mode}"), &format!("方式:{mode}")), + ]; + lines.extend(biggest); + let plan = self.uninstall.plan.clone(); + let approval = match &action { + ConfirmAction::Uninstall => match plan { + Some(plan) => Approval::Plan(UninstallPlan { + items: chosen.clone(), + ..plan + }), + None => { + self.toast( + self.strings.t( + "the plan is gone, press enter again", + "清单已失效,请重新按回车", + ), + ToastKind::Warn, + ); + return; + } + }, + ConfirmAction::Purge => Approval::Items { + items: chosen, + purge: true, + }, + ConfirmAction::Clean => Approval::Items { + items: chosen, + purge: false, + }, + ConfirmAction::UndoSession(_) => return, + }; + self.pending = Some(approval); + self.confirm = Some(Confirm { + title, + lines, + action, + }); + } +} + +// ------------------------------------------------------------------ commands +// +// The dialog is the only gate between "selected" and "deleted", and even then +// `squid_engine::delete` re-checks every path against the safety policy. + +impl App { + /// Delete what the confirmation dialog was showing. + pub fn confirm_delete(&mut self) { + if self.slot_busy(Slot::Delete) { + // Keep the dialog and the approval: the user said yes, the machine + // is just not free yet. Dropping them here is what made the + // original report read "确定之后什么都没有发生". + self.toast( + self.strings.t( + "still working — press enter again when it is done", + "上一个任务还在进行,等它结束后再按一次回车", + ), + ToastKind::Warn, + ); + return; + } + let Some(approval) = self.pending.take() else { + self.confirm = None; + self.toast( + self.strings.t( + "nothing was approved — press d again", + "没有待确认的内容,请重新按 d", + ), + ToastKind::Warn, + ); + return; + }; + self.confirm = None; + let mode = self.delete_mode; + match approval { + Approval::Items { items, purge } => { + let command = if purge { "squid purge" } else { "squid clean" }.to_string(); + let (handle, progress) = job::spawn("delete", move |engine, progress, cancel| { + let job = DeleteJob::new(items, mode, command); + delete::execute(engine, &job, progress, cancel) + }); + self.jobs.delete = Some(handle); + self.jobs.delete_target = Some(if purge { Panel::Purge } else { Panel::Cleanup }); + self.start_progress(progress, "delete"); + } + Approval::Plan(plan) => { + let name = plan.app.name.clone(); + let (handle, progress) = job::spawn("delete", move |engine, progress, cancel| { + uninstall::remove_plan(engine, &plan, mode, progress, cancel) + }); + self.jobs.delete = Some(handle); + self.jobs.delete_target = Some(Panel::Uninstall); + self.start_progress(progress, &format!("uninstall · {name}")); + } + Approval::UndoSession(id) => match delete::restore_session(&id) { + Ok((restored, skipped)) => { + let text = format!( + "{} · {} skipped", + self.strings.t( + &format!("restored {restored} items"), + &format!("已还原 {restored} 项") + ), + skipped + ); + self.toast(text.clone(), ToastKind::Good); + self.push_log(text); + // The bytes came back, so the header must stop counting + // them; `restore` marked the record as undone for exactly + // this reason. + self.recount(); + } + Err(err) => { + self.toast(err.to_string(), ToastKind::Warn); + } + }, + } + } + + pub fn deny(&mut self) { + self.confirm = None; + self.pending = None; + } + + pub fn toggle_mode(&mut self) { + self.delete_mode = match self.delete_mode { + DeleteMode::Trash => DeleteMode::Permanent, + DeleteMode::Permanent => DeleteMode::Trash, + }; + let text = match self.delete_mode { + DeleteMode::Trash => self.strings.t("Trash", "废纸篓"), + DeleteMode::Permanent => self.strings.t("Permanent", "永久删除"), + }; + self.toast( + self.strings.t( + &format!("Delete mode: {text}"), + &format!("删除方式:{text}"), + ), + ToastKind::Info, + ); + } + + pub fn undo_last(&mut self) { + let Some(session) = self + .history + .sessions + .iter() + .find(|session| !session.entries.is_empty()) + .or_else(|| self.history.sessions.first()) + .cloned() + else { + self.toast( + self.strings.t("nothing to undo", "没有可还原的记录"), + ToastKind::Info, + ); + return; + }; + self.ask_undo(session.id.clone()); + } + + pub fn ask_undo(&mut self, id: String) { + if self.confirm.is_some() { + return; + } + // A restore walks the same folders a delete is walking. + if self.busy_refusal(Slot::Delete) { + return; + } + let session = self + .history + .sessions + .iter() + .find(|item| item.id == id) + .cloned(); + let lines = match session { + Some(session) => vec![ + format!("{} · {}", session.command, session.freed().human_long()), + self.strings.t( + &format!("{} items will come back from Trash", session.entries.len()), + &format!("{} 项将从废纸篓还原", session.entries.len()), + ), + ], + None => vec![id.clone()], + }; + self.pending = Some(Approval::UndoSession(id.clone())); + self.confirm = Some(Confirm { + title: self.strings.t("Undo this session", "还原此会话"), + lines, + action: ConfirmAction::UndoSession(id), + }); + } + + // ------------------------------------------------------------- navigation + + pub fn list_len(&self) -> usize { + match self.panel { + Panel::Cleanup => self.clean.lines.len(), + Panel::Purge => self.purge.lines.len(), + Panel::Uninstall => match self.uninstall.view { + UninstallView::List => self.uninstall.visible().len(), + UninstallView::Plan => self.uninstall.lines.len(), + }, + Panel::Storage => { + if self.storage.show_files { + self.storage.files.len() + } else { + self.storage.rows() + } + } + Panel::Stats => self + .stats + .snapshot + .as_ref() + .map(|snapshot| snapshot.top_processes.len()) + .unwrap_or(0), + Panel::History => self.history.sessions.len(), + } + } + + fn cursor(&self) -> usize { + match self.panel { + Panel::Cleanup => self.clean.cursor, + Panel::Purge => self.purge.cursor, + Panel::Uninstall => match self.uninstall.view { + UninstallView::List => self.uninstall.cursor, + UninstallView::Plan => self.uninstall.plan_cursor, + }, + Panel::Storage => self.storage.cursor, + Panel::Stats => self.stats.cursor, + Panel::History => self.history.cursor, + } + } + + fn set_cursor(&mut self, value: usize) { + match self.panel { + Panel::Cleanup => self.clean.cursor = value, + Panel::Purge => self.purge.cursor = value, + Panel::Uninstall => match self.uninstall.view { + UninstallView::List => self.uninstall.cursor = value, + UninstallView::Plan => self.uninstall.plan_cursor = value, + }, + Panel::Storage => self.storage.cursor = value, + Panel::Stats => self.stats.cursor = value, + Panel::History => self.history.cursor = value, + } + } + + pub fn move_cursor(&mut self, delta: i32) { + let len = self.list_len(); + if len == 0 { + self.set_cursor(0); + return; + } + let current = self.cursor().min(len - 1); + let next = if delta < 0 { + current.saturating_sub((-delta) as usize) + } else { + (current + delta as usize).min(len - 1) + }; + self.set_cursor(next); + } + + pub fn page_cursor(&mut self, step: isize) { + let len = self.list_len(); + if len == 0 { + return; + } + let current = self.cursor() as isize; + let next = (current + step).clamp(0, len as isize - 1) as usize; + self.set_cursor(next); + } + + pub fn jump_end(&mut self) { + let len = self.list_len(); + self.set_cursor(len.saturating_sub(1)); + } + + pub fn toggle(&mut self) { + let cursor = self.cursor(); + match self.panel { + Panel::Cleanup => self.clean.toggle_at(cursor), + Panel::Purge => self.purge.toggle_at(cursor), + Panel::Uninstall => match self.uninstall.view { + UninstallView::List => self.toast( + self.strings.t( + "space toggles items, enter inspects an app", + "空格勾选,回车查看应用", + ), + ToastKind::Info, + ), + UninstallView::Plan => match self.uninstall.toggle_plan_at(cursor) { + Some("bundle") => self.toast( + self.strings.t( + "the application itself is always removed", + "应用本体始终会被删除", + ), + ToastKind::Info, + ), + Some(reason) => self.toast( + self.strings.t( + &format!("this item is locked ({reason})"), + &format!("这一项被锁定了({reason})"), + ), + ToastKind::Info, + ), + None => {} + }, + }, + Panel::Storage | Panel::Stats | Panel::History => {} + } + } + + pub fn toggle_all(&mut self) { + match self.panel { + Panel::Cleanup => self.clean.toggle_all(), + Panel::Purge => self.purge.toggle_all(), + Panel::Uninstall => match self.uninstall.view { + UninstallView::List => {} + UninstallView::Plan => self.uninstall.toggle_all_leftovers(), + }, + _ => {} + } + } + + pub fn collapse(&mut self) { + let cursor = self.cursor(); + match self.panel { + Panel::Cleanup => self.clean.collapse_at(cursor, false), + Panel::Purge => self.purge.collapse_at(cursor, false), + Panel::Uninstall => { + if self.uninstall.view == UninstallView::Plan { + self.leave_plan(); + } + } + // Out of the largest-files list first, and only then out of the + // folder: the two are one level apart, not one gesture apart. + Panel::Storage => { + if self.storage.show_files { + self.leave_files(); + } else { + self.up_storage(); + } + } + _ => {} + } + } + + pub fn expand(&mut self) { + let cursor = self.cursor(); + match self.panel { + Panel::Cleanup => self.clean.collapse_at(cursor, true), + Panel::Purge => self.purge.collapse_at(cursor, true), + Panel::Storage => self.drill_storage(), + _ => {} + } + } + + /// Enter: the one obvious action for whatever is under the cursor. + pub fn primary(&mut self) { + match self.panel { + Panel::Cleanup | Panel::Purge => { + let scan = match self.panel { + Panel::Cleanup => &self.clean, + _ => &self.purge, + }; + if scan.items.is_empty() { + self.scan(); + return; + } + let cursor = self.cursor(); + match scan.lines.get(cursor).copied() { + Some(Line::Group(_)) | None => self.toggle(), + Some(Line::Item(_)) => self.toggle(), + } + } + Panel::Uninstall => match self.uninstall.view { + UninstallView::List => self.build_plan(), + UninstallView::Plan => self.ask_delete(), + }, + Panel::Storage => { + if self.storage.show_files { + self.toast( + self.strings + .t("files are read-only here", "此处文件仅供查看"), + ToastKind::Info, + ); + } else if self.storage.current().is_none() { + self.rescan_storage(); + } else { + self.drill_storage(); + } + } + Panel::Stats => {} + Panel::History => { + let Some(session) = self.history.sessions.get(self.history.cursor).cloned() else { + self.history.reload(); + return; + }; + self.ask_undo(session.id); + } + } + } + + pub fn cancel_jobs(&mut self) { + if let Some(job) = &self.jobs.clean { + job.cancel(); + } + if let Some(job) = &self.jobs.purge { + job.cancel(); + } + if let Some(job) = &self.jobs.apps { + job.cancel(); + } + if let Some(job) = &self.jobs.plan { + job.cancel(); + } + if let Some(job) = &self.jobs.storage { + job.cancel(); + } + if let Some(job) = &self.jobs.files { + job.cancel(); + } + if let Some(job) = &self.jobs.delete { + job.cancel(); + self.push_log("cancelling delete…"); + } + } + + pub fn select_panel(&mut self, panel: Panel) { + if panel == self.panel { + return; + } + self.panel = panel; + self.help = false; + self.filtering = false; + match panel { + Panel::Uninstall if self.uninstall.apps.is_empty() && !self.slot_busy(Slot::Apps) => { + self.scan() + } + Panel::Storage if self.storage.stack.is_empty() && !self.slot_busy(Slot::Storage) => { + self.rescan_storage() + } + Panel::Stats if self.stats.snapshot.is_none() => self.stats.refresh(), + Panel::History => self.history.reload(), + _ => {} + } + } + + pub fn cycle(&mut self, forward: bool) { + let next = if forward { + self.panel.next() + } else { + self.panel.prev() + }; + self.select_panel(next); + } + + // ------------------------------------------------------------------ keys + + pub fn handle_key(&mut self, code: KeyCode, modifiers: KeyModifiers) -> Action { + if modifiers.contains(KeyModifiers::CONTROL) && matches!(code, KeyCode::Char('c')) { + return Action::Quit; + } + if self.filtering { + return self.handle_filter_key(code); + } + if self.confirm.is_some() { + return match code { + KeyCode::Char('y') | KeyCode::Char('Y') | KeyCode::Enter => { + self.confirm_delete(); + Action::Redraw + } + // The dialog promises 「回车 / y 确认 · n / esc 取消」 on screen. + // `esc` used to land in the catch-all below, which redrew and + // left the dialog standing: the way out of a second-level + // confirmation was to press yes. `q` closes it too rather than + // quitting the app from inside a question. + KeyCode::Char('n') + | KeyCode::Char('N') + | KeyCode::Esc + | KeyCode::Backspace + | KeyCode::Char('q') + | KeyCode::Left => { + self.deny(); + self.toast(self.strings.t("cancelled", "已取消"), ToastKind::Warn); + Action::Redraw + } + _ => Action::Redraw, + }; + } + if self.help { + return match code { + KeyCode::Esc + | KeyCode::Char('?') + | KeyCode::Char('h') + | KeyCode::Char('q') + | KeyCode::Enter => { + self.help = false; + Action::Redraw + } + _ => Action::Redraw, + }; + } + if self.menu { + return self.handle_menu_key(code); + } + match code { + KeyCode::Char('q') | KeyCode::Char('Q') => Action::Quit, + KeyCode::Tab => { + self.cycle(true); + Action::Redraw + } + KeyCode::BackTab => { + self.cycle(false); + Action::Redraw + } + KeyCode::Backspace => { + if self.panel == Panel::Storage { + self.up_storage(); + } + Action::Redraw + } + KeyCode::Char(digit @ '1'..='6') => { + let index = (digit as u8 - b'1') as usize; + if let Some(panel) = Panel::ALL.get(index).copied() { + self.select_panel(panel); + } + Action::Redraw + } + // Option/Control + arrow drives the six functions from anywhere, + // because `esc` first is one keystroke too many when you are only + // hopping between panels. Plain arrows stay with the list. + code @ (KeyCode::Up | KeyCode::Down) + if modifiers.intersects(KeyModifiers::ALT | KeyModifiers::CONTROL) => + { + self.step_panel(if code == KeyCode::Down { 1 } else { -1 }); + Action::Redraw + } + KeyCode::Char('j') | KeyCode::Down => { + self.move_cursor(1); + Action::Redraw + } + KeyCode::Char('k') | KeyCode::Up => { + self.move_cursor(-1); + Action::Redraw + } + KeyCode::PageDown => { + self.page_cursor(15); + Action::Redraw + } + KeyCode::PageUp => { + self.page_cursor(-15); + Action::Redraw + } + KeyCode::Home => { + self.set_cursor(0); + Action::Redraw + } + KeyCode::End => { + self.jump_end(); + Action::Redraw + } + KeyCode::Char('h') | KeyCode::Left => { + self.collapse(); + Action::Redraw + } + KeyCode::Char('l') | KeyCode::Right => { + self.expand(); + Action::Redraw + } + KeyCode::Char(' ') => { + self.toggle(); + Action::Redraw + } + KeyCode::Enter => { + self.primary(); + Action::Redraw + } + KeyCode::Char('s') | KeyCode::Char('S') => { + self.scan(); + Action::Redraw + } + KeyCode::Char('d') | KeyCode::Char('x') => { + self.ask_delete(); + Action::Redraw + } + KeyCode::Char('a') | KeyCode::Char('A') => { + self.toggle_all(); + Action::Redraw + } + KeyCode::Char('f') => { + if self.panel == Panel::Uninstall { + self.filtering = true; + self.toast( + self.strings + .t("filter apps — type to search", "筛选应用 — 直接输入"), + ToastKind::Info, + ); + } else if self.panel == Panel::Storage { + // The hint bar has been advertising `f files` on the storage + // panel all along; the key itself did nothing at all. + self.largest_files(); + } + Action::Redraw + } + KeyCode::Char('r') | KeyCode::Char('R') => { + match self.panel { + Panel::History => self.history.reload(), + Panel::Storage => { + self.storage.show_files = false; + self.rescan_storage(); + } + Panel::Stats => self.stats.refresh(), + Panel::Cleanup | Panel::Purge => self.rescan_storage(), + Panel::Uninstall => {} + } + Action::Redraw + } + KeyCode::Char('m') => { + self.toggle_mode(); + Action::Redraw + } + KeyCode::Char('u') | KeyCode::Char('U') => { + if self.panel == Panel::History { + if let Some(session) = self.history.sessions.get(self.history.cursor).cloned() { + self.ask_undo(session.id); + } + } else { + self.undo_last(); + } + Action::Redraw + } + KeyCode::Char('c') if self.busy() => { + self.cancel_jobs(); + self.toast(self.strings.t("cancelling…", "正在取消…"), ToastKind::Warn); + Action::Redraw + } + KeyCode::Esc => { + self.escape(); + Action::Redraw + } + KeyCode::Char('?') => { + self.help = true; + Action::Redraw + } + _ => Action::Redraw, + } + } + + /// `esc` walks back exactly **one** step, because every one of these views + /// is a level the user walked into and expects to walk out of the same way: + /// + /// ```text + /// confirm a delete → the view it was asked from + /// uninstall plan → the list of applications + /// largest files → the folder they were listed from + /// a folder → the folder above it + /// the list → the six functions in the sidebar + /// ``` + /// + /// It used to leap two levels at once on the disk map (files *and* a folder) + /// and to give up entirely inside a confirmation. A long-running job must + /// still never steal the key — a background disk walk used to swallow every + /// `esc` for minutes; `c` is what cancels. + /// + /// The other half of the same complaint is the job that finishes *after* + /// the key: leaving a level also throws away the work that level was + /// waiting on (see [`App::abandon`]), or the view reopens itself and `esc` + /// looks dead. + fn escape(&mut self) { + self.pending = None; + if self.menu { + self.menu = false; + return; + } + match self.panel { + Panel::Uninstall if self.uninstall.view == UninstallView::Plan => self.leave_plan(), + Panel::Storage => { + if self.storage.show_files { + self.leave_files(); + } else if self.pending_drill { + // The folder was asked for and never arrived; `esc` is the + // answer to that request, not a step sideways. + self.abandon(Slot::Storage); + } else if self.storage.stack.len() > 1 { + self.up_storage(); + } else { + self.open_menu(); + } + } + _ => self.open_menu(), + } + } + + /// Leave the plan of an application and hand the list back. + fn leave_plan(&mut self) { + self.uninstall.view = UninstallView::List; + self.uninstall.plan = None; + self.uninstall.lines.clear(); + self.uninstall.plan_cursor = 0; + self.abandon(Slot::Plan); + } + + /// Leave the largest-files list of a folder, second level of the disk map. + fn leave_files(&mut self) { + self.storage.show_files = false; + self.storage.cursor = 0; + self.abandon(Slot::Files); + } + + /// Throw away the work of a level the user has just walked out of. + /// + /// Backing this: a job that finished after `esc` used to repaint the view + /// the key had just left — the leftover plan appeared again, the file list + /// came back, the folder you had escaped from opened itself — which is + /// precisely what "esc does nothing in the second level" looks like from the + /// chair. The worker is told to stop and its handle dropped, so nothing is + /// applied and nothing is toasted about a job the user already abandoned. + fn abandon(&mut self, slot: Slot) { + match slot { + Slot::Plan => { + if let Some(handle) = self.jobs.plan.take() { + handle.cancel(); + } + } + Slot::Files => { + if let Some(handle) = self.jobs.files.take() { + handle.cancel(); + } + } + Slot::Storage => { + self.pending_drill = false; + if let Some(handle) = self.jobs.storage.take() { + handle.cancel(); + } + } + _ => return, + } + self.finish_job(); + } + + /// Give the arrow keys to the six entries in the sidebar. The list keeps + /// its own scroll position, so leaving and coming back is harmless, and + /// `q` still quits from here. + fn open_menu(&mut self) { + self.menu = true; + self.toast( + self.strings.t( + "menu — up and down to choose, enter to go back", + "功能菜单 — 上下键选择,回车返回", + ), + ToastKind::Info, + ); + } + + /// Move the sidebar selection. Clamped rather than wrapping: the list is + /// short and knowing where the end is matters more than the loop. + fn step_panel(&mut self, delta: i32) { + let last = Panel::ALL.len().saturating_sub(1); + let current = Panel::ALL + .iter() + .position(|panel| *panel == self.panel) + .unwrap_or(0) as i32; + let next = (current + delta).clamp(0, last as i32) as usize; + if let Some(panel) = Panel::ALL.get(next).copied() { + self.select_panel(panel); + } + } + + fn handle_menu_key(&mut self, code: KeyCode) -> Action { + match code { + KeyCode::Char('q') | KeyCode::Char('Q') => Action::Quit, + KeyCode::Char('?') => { + self.help = true; + Action::Redraw + } + KeyCode::Up | KeyCode::Char('k') => { + self.step_panel(-1); + Action::Redraw + } + KeyCode::Down | KeyCode::Char('j') => { + self.step_panel(1); + Action::Redraw + } + KeyCode::PageUp => { + self.step_panel(-3); + Action::Redraw + } + KeyCode::PageDown => { + self.step_panel(3); + Action::Redraw + } + KeyCode::Home => { + if let Some(panel) = Panel::ALL.first().copied() { + self.select_panel(panel); + } + Action::Redraw + } + KeyCode::End => { + if let Some(panel) = Panel::ALL.last().copied() { + self.select_panel(panel); + } + Action::Redraw + } + KeyCode::Char(digit @ '1'..='6') => { + let index = (digit as u8 - b'1') as usize; + if let Some(panel) = Panel::ALL.get(index).copied() { + self.select_panel(panel); + } + Action::Redraw + } + KeyCode::Tab => { + self.cycle(true); + Action::Redraw + } + KeyCode::BackTab => { + self.cycle(false); + Action::Redraw + } + KeyCode::Char('c') if self.busy() => { + self.cancel_jobs(); + self.toast(self.strings.t("cancelling…", "正在取消…"), ToastKind::Warn); + Action::Redraw + } + KeyCode::Char('m') => { + self.toggle_mode(); + Action::Redraw + } + KeyCode::Enter + | KeyCode::Esc + | KeyCode::Left + | KeyCode::Right + | KeyCode::Char('h') + | KeyCode::Char('l') => { + self.menu = false; + Action::Redraw + } + // Everything that is not the arrows is an *order*, not a choice of + // where the arrows go. `s` on the very first screen used to be + // swallowed here — the interface now opens on the sidebar, so the + // key the hint bar advertises would have done nothing until the + // user found `esc`. Hand the keys back to the panel and let it + // answer them, the way it did before the sidebar had focus. + code => { + self.menu = false; + self.handle_key(code, KeyModifiers::empty()) + } + } + } + + fn handle_filter_key(&mut self, code: KeyCode) -> Action { + match code { + KeyCode::Esc => { + self.filtering = false; + self.uninstall.filter.clear(); + self.uninstall.cursor = 0; + Action::Redraw + } + KeyCode::Enter => { + self.filtering = false; + Action::Redraw + } + KeyCode::Backspace => { + self.uninstall.filter.pop(); + self.uninstall.cursor = 0; + Action::Redraw + } + KeyCode::Char(ch) if !ch.is_control() => { + self.uninstall.filter.push(ch); + self.uninstall.cursor = 0; + Action::Redraw + } + _ => Action::Redraw, + } + } +} + +/// What the event loop should do after a key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Redraw, + Quit, +} + +use crossterm::event::{KeyCode, KeyModifiers}; + +#[cfg(test)] +mod tests { + use super::*; + use squid_core::ItemKind; + use std::path::Path; + use std::time::{Duration, Instant}; + + /// The ledger is user data: point it at a scratch directory so a test + /// session never shows up in the user's real `squid history`. + fn isolate_state() { + use std::sync::Once; + static ONCE: Once = Once::new(); + ONCE.call_once(|| { + let dir = std::env::temp_dir().join(format!("squid-tui-state-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + std::env::set_var("SQUID_STATE_DIR", dir); + }); + } + + /// A sandbox under `~/Library/Caches`, the way the engine tests do it: + /// that is inside the cleanup anchors *and* inside the home directory, so + /// the safety policy treats these paths exactly like real junk it was + /// asked to delete — no special cases needed. + fn scratch(tag: &str) -> PathBuf { + let dir = squid_core::paths::home_dir() + .join("Library/Caches") + .join(format!( + "squid-tui-test-{}-{tag}-{}", + std::process::id(), + squid_core::ledger::new_session_id() + )); + std::fs::create_dir_all(&dir).expect("scratch dir"); + dir + } + + fn fake_app(dir: &Path) -> (AppInfo, Vec) { + let bundle = dir.join("SquidTest.app"); + let binary = bundle.join("Contents/MacOS/squid-test"); + std::fs::create_dir_all(binary.parent().expect("parent")).expect("bundle"); + std::fs::write(&binary, b"mach-o-ish").expect("binary"); + let prefs = dir.join("Preferences/com.nexsquid.test.plist"); + std::fs::create_dir_all(prefs.parent().expect("prefs dir")).expect("prefs dir"); + std::fs::write(&prefs, b"defaults").expect("prefs"); + + let info = AppInfo { + name: "SquidTest".to_string(), + bundle_id: Some("com.nexsquid.test".to_string()), + path: bundle.clone(), + version: Some("1.0".to_string()), + size: Bytes(0), + source: "test".to_string(), + running: false, + has_sibling_install: false, + publisher: None, + installed_ms: None, + }; + let items = vec![ + CleanupItem::new( + bundle.clone(), + ItemKind::Path, + Category::Leftovers, + "SquidTest", + ), + CleanupItem::new( + prefs.clone(), + ItemKind::File, + Category::Leftovers, + "preferences", + ), + ]; + (info, items) + } + + /// The dialog is the only gate before a delete, so approving it has to + /// actually reach the engine. This is the regression test for the version + /// where an approved uninstall closed the dialog and did nothing at all. + #[test] + fn approving_an_uninstall_really_uninstalls() { + isolate_state(); + let dir = scratch("uninstall"); + let (info, items) = fake_app(&dir); + let bundle = info.path.clone(); + let prefs = items[1].path.clone(); + + let mut app = App::new().expect("app"); + app.delete_mode = DeleteMode::Permanent; + app.panel = Panel::Uninstall; + app.uninstall.view = UninstallView::Plan; + app.uninstall.plan = Some(UninstallPlan { + app: info, + items, + warnings: Vec::new(), + }); + + app.ask_delete(); + assert!(app.confirm.is_some(), "d must open the confirmation dialog"); + assert!( + matches!(app.pending, Some(Approval::Plan(_))), + "the dialog must carry the plan it is approving" + ); + + app.confirm_delete(); + let handle = app + .jobs + .delete + .take() + .expect("confirming must start a delete job"); + let started = Instant::now(); + let outcome = loop { + if let Some(value) = handle.poll() { + break value.expect("delete job"); + } + assert!( + started.elapsed() < Duration::from_secs(60), + "the delete job never reported back" + ); + std::thread::sleep(Duration::from_millis(20)); + }; + assert_eq!( + outcome.summary.removed, 2, + "errors={:?} skipped={:?}", + outcome.summary.errors, outcome.skipped + ); + assert!(!bundle.exists(), "the bundle should be gone"); + assert!( + !prefs.exists(), + "the leftover preference file should be gone" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + /// After the app is gone the panel must not stay filtered down to the one + /// app that used to match — that read as "nothing happened". + #[test] + fn a_finished_uninstall_leaves_the_list_readable() { + let mut app = App::new().expect("app"); + let path = std::path::PathBuf::from("/Applications/SquidTest.app"); + app.uninstall.apps = vec![AppInfo { + name: "SquidTest".into(), + bundle_id: Some("com.example.SquidTest".into()), + path: path.clone(), + version: None, + size: Bytes(0), + source: "test".into(), + running: false, + has_sibling_install: false, + publisher: None, + installed_ms: None, + }]; + app.uninstall.filter = "Squid".into(); + assert_eq!(app.uninstall.visible().len(), 1); + + app.uninstall.remove_deleted(&[path]); + + assert!( + app.uninstall.filter.is_empty(), + "the filter that found the deleted app must be cleared" + ); + assert!(app.uninstall.apps.is_empty()); + assert_eq!(app.uninstall.view, UninstallView::List); + } + + /// Deleting from the Cleanup panel shares the same code path, and the + /// `UndoSession`/`Items` arms must not be able to cross wires. + #[test] + fn approving_a_cleaning_dialog_carries_the_items() { + isolate_state(); + let dir = scratch("clean"); + let file = dir.join("junk.bin"); + std::fs::write(&file, vec![3u8; 2048]).expect("junk"); + + let mut app = App::new().expect("app"); + app.delete_mode = DeleteMode::Permanent; + app.panel = Panel::Cleanup; + let mut item = CleanupItem::new(file.clone(), ItemKind::File, Category::SystemJunk, "junk"); + item.size = Bytes(2048); + app.clean.items = vec![item]; + + app.ask_delete(); + assert!(matches!( + app.pending, + Some(Approval::Items { purge: false, .. }) + )); + app.confirm_delete(); + let handle = app.jobs.delete.take().expect("a delete job"); + let started = Instant::now(); + let outcome = loop { + if let Some(value) = handle.poll() { + break value.expect("delete job"); + } + assert!(started.elapsed() < Duration::from_secs(60)); + std::thread::sleep(Duration::from_millis(20)); + }; + assert_eq!( + outcome.summary.removed, 1, + "errors={:?} skipped={:?}", + outcome.summary.errors, outcome.skipped + ); + assert!(!file.exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Nothing approved, nothing deleted — and the user hears about it rather + /// than watching the dialog disappear in silence. + #[test] + fn confirming_without_an_approval_says_so() { + isolate_state(); + let mut app = App::new().expect("app"); + app.confirm = Some(Confirm { + title: String::new(), + lines: Vec::new(), + action: ConfirmAction::Uninstall, + }); + app.confirm_delete(); + assert!(app.jobs.delete.is_none(), "nothing should have started"); + assert!(app.toast.is_some(), "the user must get feedback"); + } + + /// A job that is still running swallows keys. That part is correct — a + /// second scan while one is walking the disk would be worse — but it has + /// to say so, because "pressed d, nothing happened" is indistinguishable + /// from "the button is broken". + #[test] + fn a_busy_app_answers_instead_of_ignoring_you() { + isolate_state(); + let mut app = App::new().expect("app"); + let (handle, _progress) = crate::job::spawn("test-busy", |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(Vec::::new()) + }); + app.jobs.apps = Some(handle); + assert!(app.busy()); + + app.panel = Panel::Uninstall; + app.ask_delete(); + assert!(app.toast.is_some(), "the refusal must be visible"); + assert!(app.pending.is_none(), "and nothing may be armed behind it"); + assert!(app.confirm.is_none(), "nor may a dialog open"); + + app.jobs.apps = None; + } + + /// Saying yes while the machine is still busy keeps the approval alive: + /// the user's answer is not thrown away, it just has to wait. + #[test] + fn confirming_while_busy_keeps_the_answer() { + isolate_state(); + let mut app = App::new().expect("app"); + let (handle, _progress) = crate::job::spawn("test-busy2", |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(Vec::::new()) + }); + app.jobs.apps = Some(handle); + app.pending = Some(Approval::Items { + items: Vec::new(), + purge: false, + }); + + app.confirm_delete(); + assert!( + app.pending.is_some(), + "a busy machine must not eat the user's yes" + ); + assert!(app.toast.is_some(), "and the wait has to be explained"); + } + /// The refusal names the job it is waiting on. "上一个任务还在进行" with no + /// name sent users to hunt for a task that was only a disk walk. + #[test] + fn a_refusal_names_the_job() { + isolate_state(); + let mut app = App::new().expect("app"); + let (handle, _progress) = crate::job::spawn("apps", |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(Vec::::new()) + }); + app.jobs.apps = Some(handle); + + app.panel = Panel::Uninstall; + app.ask_delete(); + let text = app.toast.take().expect("a reason").text; + assert!( + text.contains("应用列表") || text.contains("app list"), + "the refusal must name the job: {text}" + ); + + if let Some(handle) = app.jobs.apps.take() { + handle.cancel(); + } + } + + fn idle_node(tag: &str) -> Node { + let dir = scratch(tag); + let node = analyze::explore(&dir, 0, 8, &CancelToken::new(), &Progress::new()) + .expect("measure an empty folder"); + let _ = std::fs::remove_dir_all(&dir); + node + } + + /// A disk map of a home folder takes tens of seconds. It used to be "a job" + /// like any other, so the whole interface answered "上一个任务还在进行" while + /// it walked. It is the one job allowed to run beside the one you pressed a + /// key for. + /// "未发现应用" while the inventory is still being read is a lie, and a lie + /// the user can act on: they press `s`, nothing happens (the slot is busy), + /// and the panel looks ignored. The empty state has to know whether the + /// list is on its way. + #[test] + fn an_empty_panel_says_whether_it_is_still_being_filled() { + assert_eq!(App::filling_slot(Panel::Cleanup), Some(Slot::Clean)); + assert_eq!(App::filling_slot(Panel::Uninstall), Some(Slot::Apps)); + assert_eq!(App::filling_slot(Panel::Storage), Some(Slot::Storage)); + assert_eq!(App::filling_slot(Panel::History), None); + + isolate_state(); + let mut app = App::new().expect("app"); + assert!(!app.filling(Panel::Uninstall), "at rest nothing is loading"); + + let (handle, _progress) = crate::job::spawn("apps", move |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(Vec::new()) + }); + app.jobs.apps = Some(handle); + assert!( + app.filling(Panel::Uninstall), + "the app list is on its way, so the panel is not empty yet" + ); + assert!( + !app.filling(Panel::Cleanup), + "a job must not make every panel claim to be working" + ); + if let Some(handle) = app.jobs.apps.take() { + handle.cancel(); + } + } + + #[test] + fn a_disk_scan_leaves_the_other_panels_usable() { + isolate_state(); + let mut app = App::new().expect("app"); + let node = idle_node("map"); + let (handle, _progress) = + crate::job::spawn("storage", move |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(node) + }); + app.jobs.storage = Some(handle); + + assert!(app.slot_busy(Slot::Storage), "the disk slot is taken"); + app.panel = Panel::Uninstall; + app.scan(); + assert!( + app.jobs.apps.is_some(), + "the app list must not wait for the disk map" + ); + + // Two foreground jobs at once is still not allowed — the progress bar + // answers to one key press — and the refusal says which one. + assert!(app.busy_refusal(Slot::Delete)); + let text = app.toast.take().expect("a reason").text; + assert!( + text.contains("应用列表") || text.contains("app list"), + "the refusal must name the foreground job: {text}" + ); + + if let Some(handle) = app.jobs.apps.take() { + handle.cancel(); + } + if let Some(handle) = app.jobs.storage.take() { + handle.cancel(); + } + } + + /// The report this came from: uninstall one app, try the next, be told the + /// previous task is still running. It was the automatic disk-map refresh, + /// and it must now run beside the user instead of in front of them. + #[test] + fn the_map_refresh_after_an_uninstall_does_not_lock_the_next_one() { + isolate_state(); + let dir = scratch("chain"); + let (first, first_items) = fake_app(&dir); + let second_dir = dir.join("second"); + std::fs::create_dir_all(&second_dir).expect("second folder"); + let (second, second_items) = fake_app(&second_dir); + let second_bundle = second.path.clone(); + + let mut app = App::new().expect("app"); + app.delete_mode = DeleteMode::Permanent; + app.storage.root = dir.clone(); + app.storage.scanned = true; + + let outcome = uninstall_one(&mut app, first, first_items); + app.apply_deletion(Panel::Uninstall, outcome); + assert!( + app.jobs.storage.is_some(), + "the disk map has to refresh itself after a delete" + ); + + // The bug: this second call answered "上一个任务还在进行". + let outcome = uninstall_one(&mut app, second, second_items); + app.apply_deletion(Panel::Uninstall, outcome); + assert!( + !second_bundle.exists(), + "the second app must really be gone" + ); + + if let Some(handle) = app.jobs.storage.take() { + handle.cancel(); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// Drive one uninstall the way the keyboard does and hand back the outcome, + /// so a test can chain two of them like a user does. + fn uninstall_one(app: &mut App, info: AppInfo, items: Vec) -> DeleteOutcome { + app.panel = Panel::Uninstall; + app.uninstall.view = UninstallView::Plan; + app.uninstall.plan = Some(UninstallPlan { + app: info, + items, + warnings: Vec::new(), + }); + app.ask_delete(); + assert!( + app.confirm.is_some(), + "nothing may refuse the next uninstall: {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + app.confirm_delete(); + let handle = app + .jobs + .delete + .take() + .expect("the delete must start, not be refused"); + let started = Instant::now(); + loop { + if let Some(value) = handle.poll() { + return value.expect("delete job"); + } + assert!( + started.elapsed() < Duration::from_secs(60), + "the delete job never reported back" + ); + std::thread::sleep(Duration::from_millis(20)); + } + } + + /// The sidebar is a keyboard destination — and it is where the keyboard + /// *starts*. Opening on a list of junk that has to be ignored before the + /// first choice is possible costs a keystroke on every single session. + #[test] + fn the_keyboard_opens_on_the_sidebar() { + isolate_state(); + let mut app = App::new().expect("app"); + assert!(app.menu, "the arrows start on the six functions"); + assert!(app.toast.is_some(), "and the screen says so"); + assert!( + app.log + .iter() + .any(|line| line.contains("colour") || line.contains("色彩")), + "start-up says which colour depth the terminal got: {:?}", + app.log + ); + + // From here on a job is running so no panel jump starts a real scan; + // moving the selection must never be refused because of it. + let (handle, _progress) = crate::job::spawn("apps", |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(Vec::::new()) + }); + app.jobs.apps = Some(handle); + + app.handle_key(KeyCode::Down, KeyModifiers::empty()); + assert_eq!(app.panel, Panel::Uninstall, "down is one entry"); + app.handle_key(KeyCode::Char('j'), KeyModifiers::empty()); + assert_eq!(app.panel, Panel::Purge, "j works too"); + app.handle_key(KeyCode::Up, KeyModifiers::empty()); + assert_eq!(app.panel, Panel::Uninstall, "up walks back"); + for _ in 0..10 { + app.handle_key(KeyCode::Up, KeyModifiers::empty()); + } + assert_eq!(app.panel, Panel::Cleanup, "the menu clamps, never wraps"); + + app.handle_key(KeyCode::Char('3'), KeyModifiers::empty()); + assert_eq!(app.panel, Panel::Purge, "1-6 still jump"); + assert!(app.menu, "and a digit leaves you in the menu"); + + app.handle_key(KeyCode::Enter, KeyModifiers::empty()); + assert!(!app.menu, "enter hands the keys back to the list"); + assert_eq!(app.panel, Panel::Purge, "on the function you chose"); + + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(app.menu, "and esc gives them back to the sidebar"); + + assert!( + matches!( + app.handle_key(KeyCode::Char('q'), KeyModifiers::empty()), + Action::Quit + ), + "q quits from the menu as well" + ); + + if let Some(handle) = app.jobs.apps.take() { + handle.cancel(); + } + } + + /// While the list has focus `esc` still means *back* on the storage panel — + /// the menu must not steal the key the drill-down depends on. + #[test] + fn esc_still_walks_up_the_disk_map() { + isolate_state(); + let mut app = App::new().expect("app"); + app.menu = false; + app.panel = Panel::Storage; + let root = idle_node("up-root"); + let mut child = idle_node("up-child"); + child.path = root.path.join("Library"); + app.storage.stack = vec![root, child]; + + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert_eq!(app.storage.stack.len(), 1, "esc left one folder"); + assert!(!app.menu, "and did not open the menu"); + + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(app.menu, "at the top of the map esc opens the menu"); + } + + /// The screen opens on the sidebar, so the keys the hint bar advertises + /// have to work from there. `s` used to be swallowed by the menu, which + /// left a first-time user staring at 「尚未扫描 — 按 s」 while the one key + /// on the screen did nothing: an order is not a choice of where the + /// arrows go, so anything that is not navigation is handed to the panel. + #[test] + fn an_order_key_is_not_swallowed_by_the_sidebar() { + isolate_state(); + let mut app = App::new().expect("app"); + assert!(app.menu, "the screen opens on the six functions"); + + app.handle_key(KeyCode::Char('s'), KeyModifiers::empty()); + assert!( + app.jobs.clean.is_some(), + "s starts the scan the screen just asked for: {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + assert!(!app.menu, "and the list has the keys while it runs"); + app.cancel_jobs(); + + // Help is a layer of its own: esc peels it off and stops there, + // rather than walking out of the sidebar as well. + app.menu = true; + app.handle_key(KeyCode::Char('?'), KeyModifiers::empty()); + assert!(app.help, "? still opens the help from the menu"); + assert!(app.menu, "and leaves the focus where it was"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(!app.help, "esc closes the help"); + assert!(app.menu, "without walking past it into the list"); + + // A key the sidebar has no use for belongs to the panel on screen. + app.handle_key(KeyCode::Char('a'), KeyModifiers::empty()); + assert!(!app.menu, "a selects; it is not ignored on the way"); + } + + /// Every view below the top level is entered on purpose, so `esc` has to + /// lead back out of it — one level per press. A confirmation that answers + /// to nothing, a plan you can only leave by uninstalling from it, and a + /// disk map that threw away two levels at once are all the same bug: the + /// keyboard walking the user past a screen they meant to step back from. + #[test] + fn esc_walks_back_one_level_at_a_time() { + isolate_state(); + + // The plan of an application goes back to the list of applications. + let mut app = App::new().expect("app"); + app.menu = false; + app.panel = Panel::Uninstall; + let dir = scratch("esc-plan"); + let (info, items) = fake_app(&dir); + app.uninstall.set_plan(UninstallPlan { + app: info, + items, + warnings: Vec::new(), + }); + assert_eq!(app.uninstall.view, UninstallView::Plan, "entered the app"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert_eq!(app.uninstall.view, UninstallView::List, "esc leaves it"); + assert!(!app.menu, "and stops there, on the list of apps"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(app.menu, "the next esc reaches the sidebar"); + + // The confirmation is the one screen that *must* answer to esc. + let mut app = App::new().expect("app"); + app.menu = false; + let dialog = || Confirm { + title: "delete?".to_string(), + lines: vec!["3 items".to_string()], + action: ConfirmAction::Clean, + }; + for key in [KeyCode::Esc, KeyCode::Char('n')] { + app.confirm = Some(dialog()); + app.pending = Some(Approval::Items { + items: Vec::new(), + purge: false, + }); + app.handle_key(key, KeyModifiers::empty()); + assert!(app.confirm.is_none(), "{key:?} must close the dialog"); + assert!(app.pending.is_none(), "with the approval it carried"); + assert!( + app.toast.is_some(), + "and say what happened instead of vanishing" + ); + } + + // Largest files, then the folder it came from, then the menu: three + // presses, one level each. + let mut app = App::new().expect("app"); + app.menu = false; + app.panel = Panel::Storage; + let root = idle_node("back-root"); + let mut child = idle_node("back-child"); + child.path = root.path.join("Library"); + app.storage.stack = vec![root, child]; + app.storage.show_files = true; + + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(!app.storage.show_files, "esc leaves the largest-files list"); + assert_eq!( + app.storage.stack.len(), + 2, + "and does not take the folder along with it" + ); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert_eq!(app.storage.stack.len(), 1, "the next esc leaves the folder"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(app.menu, "the third one reaches the sidebar"); + } + + /// The second half of 「二、三级功能里按 esc 无法取消或回到上级」: the level + /// *was* left, and then the work that level had been waiting for landed and + /// opened it again. Three cases were reported and are all fixed the same + /// way — leaving a level throws its in-flight job away ([`App::abandon`]). + #[test] + fn a_level_that_is_still_building_stays_left() { + isolate_state(); + // Long enough that the orphaned job has certainly answered by the time + // the assertions run: it is its *answer* that must not reach the screen. + const WAIT: Duration = Duration::from_millis(700); + let settle = |app: &mut App| { + let started = Instant::now(); + while started.elapsed() < WAIT { + app.tick(); + std::thread::sleep(Duration::from_millis(20)); + } + }; + + // 1 · the leftover plan of an application. + let mut app = App::new().expect("app"); + app.menu = false; + app.panel = Panel::Uninstall; + app.uninstall.view = UninstallView::Plan; + let (handle, progress) = crate::job::spawn("plan", |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_millis(150)); + Ok(UninstallPlan::default()) + }); + app.jobs.plan = Some(handle); + app.set_bar(progress, "plan"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert_eq!(app.uninstall.view, UninstallView::List, "esc left the plan"); + assert!( + app.jobs.plan.is_none(), + "and stopped waiting for its answer" + ); + settle(&mut app); + assert_eq!( + app.uninstall.view, + UninstallView::List, + "the plan that finished afterwards did not walk back into it" + ); + assert!(app.uninstall.plan.is_none(), "no stray plan was kept"); + assert!(app.progress.is_none(), "nor its progress bar"); + + // 2 · the largest-files list of a folder on the disk map. + let mut app = App::new().expect("app"); + app.menu = false; + app.panel = Panel::Storage; + app.storage.stack = vec![idle_node("abandon-files")]; + app.storage.show_files = true; + let (handle, progress) = crate::job::spawn("files", |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_millis(150)); + Ok(Vec::new()) + }); + app.jobs.files = Some(handle); + app.set_bar(progress, "files"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(!app.storage.show_files, "esc left the list of files"); + settle(&mut app); + assert!( + !app.storage.show_files, + "and the listing that arrived afterwards did not reopen it" + ); + + // 3 · a folder whose scan was still on its way. + let mut app = App::new().expect("app"); + app.menu = false; + app.panel = Panel::Storage; + let here = idle_node("abandon-drill"); + let away = here.path.join("Library"); + app.storage.stack = vec![here]; + let expected = app.storage.stack[0].path.clone(); + let (handle, progress) = crate::job::spawn("storage", move |_, _, _| { + std::thread::sleep(Duration::from_millis(150)); + let mut node = idle_node("abandon-drill-landed"); + node.path = away; + Ok(node) + }); + app.jobs.storage = Some(handle); + app.pending_drill = true; + app.set_bar(progress, "storage"); + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!(!app.pending_drill, "esc called off the drill-down"); + assert!(app.jobs.storage.is_none(), "and its answer"); + settle(&mut app); + assert_eq!( + app.storage.stack[0].path, expected, + "the folder never opened itself" + ); + } + + /// A background disk walk is invisible work; it must not hold the keyboard + /// hostage. `esc` reaches the sidebar through it, and it is not cancelled + /// on the way, because cancelling a scan the user never started is its own + /// kind of "上一个任务还在进行". + #[test] + fn esc_reaches_the_sidebar_through_a_running_disk_walk() { + isolate_state(); + let mut app = App::new().expect("app"); + app.menu = false; + let sentinel = idle_node("esc-walk"); + let (handle, progress) = crate::job::spawn("storage", move |_engine, _progress, cancel| { + std::thread::sleep(Duration::from_millis(250)); + let mut node = sentinel; + node.path = PathBuf::from(format!("cancelled={}", cancel.is_cancelled())); + Ok(node) + }); + app.jobs.storage = Some(handle); + app.set_bar(progress, "storage"); + + app.handle_key(KeyCode::Esc, KeyModifiers::empty()); + assert!( + app.menu, + "esc must open the menu while the map walks: {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + + let handle = app.jobs.storage.take().expect("the walk is still there"); + let started = Instant::now(); + let walked = loop { + if let Some(value) = handle.poll() { + break value.expect("the walk finished"); + } + assert!( + started.elapsed() < Duration::from_secs(5), + "the walk never reported back" + ); + std::thread::sleep(Duration::from_millis(20)); + }; + assert_eq!( + walked.path.to_string_lossy(), + "cancelled=false", + "esc must not cancel the walk on its way past" + ); + } + + /// The gauge answers to the key that was pressed. Once that job is done the + /// bar is cleared or handed to the walk that was waiting — it never keeps + /// printing "delete · 4/4" under a "已删除" toast because an unrelated disk + /// walk is still holding `busy()`. + #[test] + fn a_finished_job_never_leaves_its_gauge_on_screen() { + isolate_state(); + let mut app = App::new().expect("app"); + let node = idle_node("bar"); + let (walk, walk_progress) = + crate::job::spawn("storage", move |_engine, _progress, _cancel| { + std::thread::sleep(Duration::from_secs(30)); + Ok(node) + }); + app.jobs.storage = Some(walk); + app.set_bar(walk_progress, "storage"); + + // Pressing a key takes the bar; the walk steps aside with its handle. + let (other, other_progress) = crate::job::spawn("files", |_engine, _progress, _cancel| { + Ok(Vec::::new()) + }); + app.jobs.files = Some(other); + app.start_progress(other_progress, "files"); + assert!( + app.bg.is_some(), + "the disk walk keeps its events instead of vanishing" + ); + + let started = Instant::now(); + let value = loop { + if let Some(value) = app.jobs.files.as_ref().expect("job").poll() { + break value; + } + assert!(started.elapsed() < Duration::from_secs(5), "job hung"); + std::thread::sleep(Duration::from_millis(10)); + } + .expect("the files job"); + assert!(value.is_empty()); + app.jobs.files = None; + app.finish_job(); + assert_ne!(app.phase, "files", "the finished job's label must go"); + + // And with no walk parked in the background, the bar clears outright. + app.bg = None; + app.phase = "delete".to_string(); + app.progress = Some(Progress::new()); + app.done = 4; + app.finish_job(); + assert!( + app.progress.is_none() && app.phase.is_empty() && app.total.is_none(), + "a bar over a still-running disk walk is a lie: {:?}", + app.phase + ); + + app.jobs.storage.take().expect("walk").cancel(); + } + + /// The six entries in the sidebar answer the arrow keys from anywhere, not + /// only after `esc` — but the plain arrows still drive the list, because a + /// cleanup list you cannot scroll is worse than one more modifier. + #[test] + fn option_arrows_switch_functions_from_anywhere() { + isolate_state(); + let mut app = App::new().expect("app"); + app.menu = false; + assert_eq!(app.panel, Panel::Cleanup); + + app.handle_key(KeyCode::Down, KeyModifiers::ALT); + assert_eq!(app.panel, Panel::Uninstall, "⌥↓ moved down the menu"); + assert!(!app.menu, "and the list kept the keyboard"); + + app.handle_key(KeyCode::Up, KeyModifiers::ALT); + assert_eq!(app.panel, Panel::Cleanup, "⌥↑ moved back up"); + + app.handle_key(KeyCode::Up, KeyModifiers::ALT); + assert_eq!(app.panel, Panel::Cleanup, "the menu clamps, never wraps"); + + app.handle_key(KeyCode::Down, KeyModifiers::CONTROL); + assert_eq!(app.panel, Panel::Uninstall, "ctrl+↓ counts too"); + if let Some(handle) = app.jobs.apps.take() { + handle.cancel(); + } + app.handle_key(KeyCode::Char('1'), KeyModifiers::empty()); + assert_eq!(app.panel, Panel::Cleanup); + + // Plain arrows are still the list's. + let junk = |name: &str| { + CleanupItem::new( + PathBuf::from(format!("/tmp/squid-arrows-{name}")), + ItemKind::File, + Category::SystemJunk, + name, + ) + }; + app.clean.items = vec![junk("one"), junk("two")]; + app.clean.rebuild_lines(); + assert_eq!(app.clean.lines.len(), 3, "one header and two rows"); + app.handle_key(KeyCode::Down, KeyModifiers::empty()); + assert_eq!(app.clean.cursor, 1, "the plain arrow moved one row down"); + app.handle_key(KeyCode::Down, KeyModifiers::empty()); + assert_eq!(app.clean.cursor, 2, "and again"); + assert_eq!(app.panel, Panel::Cleanup, "without switching function"); + } + + fn cached(path: &str, bytes: u64) -> CleanupItem { + let mut item = CleanupItem::new( + path.into(), + ItemKind::Path, + Category::AppCaches, + "app-caches", + ); + item.allocated = Bytes(bytes); + item + } + + /// The "清理完成后,分组的数据不变" bug: the delete pruned `items`, but every + /// group header and sidebar row still read its total from `buckets`, which + /// only ever arrived with the scan. + #[test] + fn a_pruned_list_recomputes_its_group_totals() { + let mut panel = ScanPanel { + items: vec![ + cached("/c/big", 6_000_000_000), + cached("/c/small", 1_000_000_000), + ], + scanned_at: Some(0), + ..ScanPanel::default() + }; + panel.rebuild_lines(); + assert_eq!( + panel.buckets[&Category::AppCaches], + (Bytes(7_000_000_000), 2) + ); + + panel.items.retain(|item| item.path == Path::new("/c/big")); + panel.rebuild_lines(); + assert_eq!( + panel.buckets[&Category::AppCaches], + (Bytes(6_000_000_000), 1), + "the header must follow the rows it counts" + ); + } + + /// A scan in flight has buckets before it has items: an empty list is not + /// evidence that everything went to zero. + #[test] + fn an_empty_list_does_not_erase_the_buckets_of_a_running_scan() { + let mut panel = ScanPanel::default(); + panel + .buckets + .insert(Category::AppCaches, (Bytes(4_000_000_000), 9)); + panel.sync_buckets(); + assert_eq!(panel.buckets.len(), 1); + } + + /// "清理动作完成后,分组的数据不变" — and the answer to it is a fresh scan. + /// Pruning the rows by hand cannot know that a cache rebuilt itself while + /// the user was reading the header, so the panel scans itself again exactly + /// like the `s` key does. + #[test] + fn a_finished_cleanup_scans_itself_again() { + isolate_state(); + let dir = scratch("rescan"); + let file = dir.join("junk.bin"); + std::fs::write(&file, vec![7u8; 4096]).expect("junk"); + + let mut app = App::new().expect("app"); + app.delete_mode = DeleteMode::Permanent; + app.panel = Panel::Cleanup; + let mut item = CleanupItem::new(file.clone(), ItemKind::File, Category::SystemJunk, "junk"); + item.size = Bytes(4096); + app.clean.items = vec![item]; + app.clean.scanned_at = Some(0); + app.clean + .buckets + .insert(Category::SystemJunk, (Bytes(4096), 1)); + app.ask_delete(); + app.confirm_delete(); + let handle = app.jobs.delete.take().expect("a delete job"); + let started = Instant::now(); + let outcome = loop { + if let Some(value) = handle.poll() { + break value.expect("delete job"); + } + assert!(started.elapsed() < Duration::from_secs(60)); + std::thread::sleep(Duration::from_millis(20)); + }; + app.apply_deletion(Panel::Cleanup, outcome); + assert!( + app.jobs.clean.is_some(), + "the panel rescans itself instead of leaving the old totals behind: {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + let handle = app.jobs.clean.take().expect("the rescan job"); + let started = Instant::now(); + let report = loop { + if let Some(value) = handle.poll() { + break value.expect("rescan job"); + } + assert!( + started.elapsed() < Duration::from_secs(120), + "the rescan never reported back" + ); + std::thread::sleep(Duration::from_millis(20)); + }; + assert!( + report.items.iter().all(|item| item.path != file), + "the file that was deleted must not come back" + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/squid-tui/src/job.rs b/crates/squid-tui/src/job.rs new file mode 100644 index 0000000..e06244c --- /dev/null +++ b/crates/squid-tui/src/job.rs @@ -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 { + rx: Receiver>, + cancel: CancelToken, + label: String, +} + +impl JobHandle { + /// Non-blocking peek: `None` while the worker is still running. + pub fn poll(&self) -> Option> { + 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(label: &str, work: F) -> (JobHandle, Progress) +where + T: Send + 'static, + F: FnOnce(&Engine, &Progress, &CancelToken) -> squid_core::Result + Send + 'static, +{ + let progress = Progress::new(); + let ui_progress = progress.clone(); + let cancel = CancelToken::new(); + let worker_cancel = cancel.clone(); + let (tx, rx) = bounded::>(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::().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 { + 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)); + } + } +} diff --git a/crates/squid-tui/src/lib.rs b/crates/squid-tui/src/lib.rs new file mode 100644 index 0000000..91b7e2b --- /dev/null +++ b/crates/squid-tui/src/lib.rs @@ -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 { + 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(()) +} diff --git a/crates/squid-tui/src/theme.rs b/crates/squid-tui/src/theme.rs new file mode 100644 index 0000000..13674d8 --- /dev/null +++ b/crates/squid-tui/src/theme.rs @@ -0,0 +1,1012 @@ +//! Colours, glyphs and the two string tables the interface knows. +//! +//! The layout is a deliberate CleanMyMac homage: dark background, one accent +//! colour, rounded cards, a big number where the space was reclaimed. Only the +//! chrome is translated — data (paths, app names) is never rewritten. + +use ratatui::style::{Color, Modifier, Style}; +use squid_core::settings::{Locale, Settings}; +use std::sync::OnceLock; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lang { + En, + Zh, +} + +#[derive(Clone, Debug)] +pub struct Strings { + pub lang: Lang, +} + +impl Strings { + pub fn detect(settings: &Settings) -> Strings { + Strings { + lang: match Locale::detect(settings) { + Locale::Zh => Lang::Zh, + Locale::En => Lang::En, + }, + } + } + + /// Strings in a chosen language, whatever the terminal and settings say. + /// The layout tests need to measure both languages on one machine. + pub fn for_lang(lang: Lang) -> Strings { + Strings { lang } + } + + pub fn t(&self, en: &str, zh: &str) -> String { + match self.lang { + Lang::En => en.to_string(), + Lang::Zh => zh.to_string(), + } + } + + pub fn cleanup(&self) -> String { + self.t("Cleanup", "清理") + } + + pub fn uninstall(&self) -> String { + self.t("Uninstall", "卸载") + } + + pub fn purge(&self) -> String { + self.t("Purge", "深度清理") + } + + pub fn storage(&self) -> String { + self.t("Storage", "存储空间") + } + + pub fn system(&self) -> String { + self.t("System", "系统状态") + } + + pub fn history(&self) -> String { + self.t("History", "历史") + } + + pub fn scan(&self) -> String { + self.t("Scan", "扫描") + } + + /// The clean header says how much *could* go, not what already went: + /// 「已删除」over a list the user has not acted on yet reads as a report of + /// something that already happened, so the label is 「可删除」. + pub fn deleted(&self) -> String { + self.t("deletable", "可删除") + } + + /// A count with its own shape, so `1634` and `24.3 GB` side by side can + /// never be read as one broken decimal (`1634·24.3 GB`). Chinese gets a + /// unit, English gets digit grouping; both stay short enough for a table. + pub fn count(&self, items: usize) -> String { + let grouped = squid_core::bytes::format_thousands(items as u64); + match self.lang { + Lang::Zh => format!("{grouped} 项"), + Lang::En => grouped, + } + } + + /// The nine group names are ours, not the user's data, so Chinese gets + /// Chinese names: 「Developer Files」 in the middle of an otherwise Chinese + /// sidebar is the one place where the interface looked untranslated. + pub fn category(&self, category: squid_core::Category) -> String { + use squid_core::Category as C; + match self.lang { + Lang::En => category.title().to_string(), + Lang::Zh => match category { + C::SystemJunk => "系统垃圾", + C::AppCaches => "应用缓存", + C::BrowserCaches => "浏览器缓存", + C::Logs => "日志与崩溃报告", + C::Developer => "开发文件", + C::ProjectArtifacts => "构建产物", + C::Trash => "废纸篓", + C::LanguagePacks => "多余语言包", + C::Leftovers => "卸载残留", + } + .to_string(), + } + } + + pub fn free(&self) -> String { + self.t("free", "可用") + } + + pub fn quit(&self) -> String { + self.t("quit", "退出") + } +} + +/// How much colour this terminal may be trusted with. +/// +/// Decided once, at start-up, by [`color_mode`]. Everything below is authored +/// in 24-bit RGB and degraded on the way out, so the design stays a single +/// source of truth whatever the host can paint. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColorMode { + /// 24-bit RGB, exactly as authored. + TrueColor, + /// The xterm 256-colour palette: every RGB value becomes its nearest entry + /// (grey ramp where the colour is a grey, 6×6×6 cube where it is not). + Color256, + /// No usable palette — `NO_COLOR` is set, or the terminal is `dumb` and + /// nothing else vouched for a palette. Colour is dropped entirely and + /// emphasis rides on attributes alone. + Monochrome, +} + +impl ColorMode { + /// The token for the log line the interface opens with. + pub fn label(self) -> &'static str { + match self { + ColorMode::TrueColor => "truecolor", + ColorMode::Color256 => "256 colors", + ColorMode::Monochrome => "no colour", + } + } + + pub fn is_truecolor(self) -> bool { + self == ColorMode::TrueColor + } +} + +/// The colours of the interface. +/// +/// The palette is authored in 24-bit RGB, because that is the design the +/// reference app is built from. Plenty of terminals cannot parse a +/// `48;2;r;g;b` sequence though — Apple Terminal is the one most people meet +/// first, and it paints nothing at all, which turns a dark, calm dashboard +/// into black-on-white noise. Every colour therefore goes through +/// `Palette::resolve`, which quietly swaps in the closest entry of the +/// xterm-256 palette when the host cannot do truecolour. The RGB values stay +/// the single source of truth either way. +pub struct Palette; + +/// The six levels each channel can take in the xterm 6x6x6 colour cube. +const CUBE: [u8; 6] = [0, 95, 135, 175, 215, 255]; + +/// How far apart the channels may be before a colour counts as grey, in which +/// case the 24-step grey ramp matches it far better than the cube does. +const GREY_LIMIT: i16 = 28; + +fn cube_level(channel: u8) -> usize { + CUBE.iter() + .enumerate() + .min_by_key(|(_, step)| (i16::from(channel) - i16::from(**step)).abs()) + .map_or(0, |(index, _)| index) +} + +/// The 256-colour index closest to `rgb`. +fn nearest_index(rgb: (u8, u8, u8)) -> u8 { + let (r, g, b) = rgb; + if (i16::from(r.max(g).max(b)) - i16::from(r.min(g).min(b))) <= GREY_LIMIT { + let mean = ((u16::from(r) + u16::from(g) + u16::from(b)) / 3) as u8; + if (13..=243).contains(&mean) { + let step = (u16::from(mean).saturating_sub(8).min(230) / 10).min(23) as u8; + return 232 + step; + } + } + let index = 16 + 36 * cube_level(r) + 6 * cube_level(g) + cube_level(b); + u8::try_from(index).unwrap_or(255) +} + +fn env_is Option>(get: &F, key: &str, wanted: &[&str]) -> bool { + get(key).is_some_and(|value| wanted.iter().any(|want| value.eq_ignore_ascii_case(want))) +} + +/// Decide whether the host terminal may be trusted with 24-bit colour. +/// +/// 24-bit colour is only ever handed out on a positive statement: the +/// `SQUID_TRUECOLOR` override, then `COLORTERM`, then the name of the terminal +/// program, then a `TERM` that names 24-bit support itself. Anything else gets +/// the 256-colour palette, which every terminal worth the name has had since +/// about 2008 — the safe guess is the smaller palette, because a terminal that +/// is shown a `48;2;r;g;b` sequence it cannot parse prints the numbers as +/// text. `TERM=xterm-256color` is deliberately not a yes: it is exactly what +/// Apple Terminal exports, and that one paints nothing at all. +fn decide_truecolor(get: impl Fn(&str) -> Option) -> bool { + if truecolor_refused(&get) { + return false; + } + if matches!( + get("SQUID_TRUECOLOR").as_deref(), + Some("always") | Some("on") | Some("1") + ) { + return true; + } + let get = &get; + if env_is(get, "COLORTERM", &["truecolor", "24bit"]) { + return true; + } + if env_is(get, "TERM_PROGRAM", &["Apple_Terminal"]) { + return false; + } + if env_is( + get, + "TERM_PROGRAM", + &[ + "iTerm.app", + "WezTerm", + "vscode", + "ghostty", + "Warp", + "Hyper", + "Terminus", + "contour", + "foot", + "rio", + ], + ) { + return true; + } + // A `TERM` that says 256 says nothing about 24-bit; only one that says + // 24-bit is taken as an answer. + let term = get("TERM").unwrap_or_default().to_lowercase(); + term.contains("truecolor") || term.contains("direct") || term.contains("24bit") +} + +/// An explicit `SQUID_TRUECOLOR=never|off|0`. +/// +/// Worth its own question, because the terminal library reaches the same +/// conclusion by a different route (`COLORTERM` is exactly what it reads) and +/// would otherwise argue with the one switch the user set on purpose. Saying +/// "no 24-bit" and being answered with 24-bit is how a remote tmux session +/// ends up printing escape sequences as text. +fn truecolor_refused(get: &impl Fn(&str) -> Option) -> bool { + matches!( + get("SQUID_TRUECOLOR").as_deref(), + Some("never") | Some("off") | Some("0") + ) +} + +/// Would this terminal be given 24-bit colour, with `colours` standing in for +/// what the terminal library itself reports? +fn decide_mode_with(get: &impl Fn(&str) -> Option, colours: u16) -> ColorMode { + // An explicit "no colour, thanks" outranks anything the terminal claims, + // so it is asked before anything else. + if no_colour_wanted(get) { + return ColorMode::Monochrome; + } + // `TERM_PROGRAM` is missing in a bare ssh session or a fresh tmux server, + // yet the terminal may still advertise 24-bit through `TERM=xterm-truecolor` + // or `COLORTERM`. crossterm reads exactly those, and only ever answers with + // its full count when one of them says so. + if decide_truecolor(get) || (colours == u16::MAX && !truecolor_refused(get)) { + return ColorMode::TrueColor; + } + // And if nothing at all said anything good about the palette, it is not + // there: a terminal that will not even name itself gets no colour. + if term_has_no_palette(get) { + return ColorMode::Monochrome; + } + ColorMode::Color256 +} + +/// [`decide_mode_with`] with nothing to report from the terminal library. +#[cfg(test)] +fn decide_mode(get: impl Fn(&str) -> Option) -> ColorMode { + let get = &get; + decide_mode_with(get, 0) +} + +/// `NO_COLOR` (https://no-color.org) means: draw with attributes, not with +/// colour. Any non-empty value counts; an empty one means nothing. +fn no_colour_wanted(get: &impl Fn(&str) -> Option) -> bool { + get("NO_COLOR").is_some_and(|value| !value.trim().is_empty()) +} + +/// A terminal that does not even name itself, or names itself `dumb`, has no +/// palette to speak of — as long as nothing else vouched for one. +fn term_has_no_palette(get: &impl Fn(&str) -> Option) -> bool { + matches!( + get("TERM").unwrap_or_default().to_lowercase().as_str(), + "" | "dumb" | "none" + ) +} + +/// Read the environment once. Called from [`init`] at start-up so the answer +/// is known before a single cell is painted, not lazily halfway through the +/// first frame. +fn probe() -> ColorMode { + let get = |key: &str| std::env::var(key).ok(); + let colours = crossterm::style::available_color_count(); + decide_mode_with(&get, colours) +} + +/// The colour depth of this process, probed once and remembered. +pub fn color_mode() -> ColorMode { + #[cfg(test)] + if let Some(forced) = FORCED.get() { + return *forced; + } + static PROBED: OnceLock = OnceLock::new(); + *PROBED.get_or_init(probe) +} + +/// Pin the palette for the whole process. +/// +/// Rendering tests draw a card and then ask what colour a cell came out in, +/// which is a question about the *host*, and the host is whatever terminal +/// `cargo test` happens to be running in — `NO_COLOR`, `TERM=dumb`, CI, an +/// ssh session. They say which depth they mean instead, and every one of them +/// says the same one, so the answer is settled before the first frame. +#[cfg(test)] +pub fn force_color_mode(mode: ColorMode) { + FORCED.set(mode).ok(); +} + +#[cfg(test)] +static FORCED: OnceLock = OnceLock::new(); + +/// Ask for the colour depth now, rather than on the first colour used. +pub fn init() -> ColorMode { + color_mode() +} + +/// Whether this process will emit 24-bit colour, probed once and remembered. +pub fn truecolor_supported() -> bool { + color_mode().is_truecolor() +} + +impl Palette { + /// The card behind a list, and the band every second row of it wears. + const CARD_RGB: (u8, u8, u8) = (24, 27, 33); + const CARD_ALT_RGB: (u8, u8, u8) = (32, 36, 43); + /// The page the cards sit on. + const PAGE_RGB: (u8, u8, u8) = (16, 18, 23); + /// The grey the cursor row is filled with where there is no accent to use. + const CURSOR_GREY_RGB: (u8, u8, u8) = (168, 176, 190); + + fn resolve(color: Color) -> Color { + Self::resolve_in(color, color_mode()) + } + + /// [`Self::resolve`] with the depth stated, so one process can pin down + /// every rendering at once ([`color_mode`] is cached for its whole life). + fn resolve_in(color: Color, mode: ColorMode) -> Color { + match (color, mode) { + (Color::Rgb(r, g, b), ColorMode::Color256) => Color::Indexed(nearest_index((r, g, b))), + (_, ColorMode::Monochrome) => Color::Reset, + _ => color, + } + } + + /// Ask for a colour rather than storing one, so the host gets the say. + fn rgb(r: u8, g: u8, b: u8) -> Color { + Self::resolve(Color::Rgb(r, g, b)) + } + + fn rgb_in(rgb: (u8, u8, u8), mode: ColorMode) -> Color { + Self::resolve_in(Color::Rgb(rgb.0, rgb.1, rgb.2), mode) + } + + /// The band that follows `previous` in a striped list. + /// + /// Two nearby greys land on the same entry of the 24-step ramp all the + /// time — 24/27/33 and 32/36/43 are both "index 234" — and the stripe would + /// simply not exist. One step further along the ramp is the same idea, only + /// one the host can actually draw. + fn band_after(previous: Color, rgb: (u8, u8, u8)) -> Color { + Self::band_after_in(previous, rgb, color_mode()) + } + + fn band_after_in(previous: Color, rgb: (u8, u8, u8), mode: ColorMode) -> Color { + let color = Self::rgb_in(rgb, mode); + match (color, previous) { + (Color::Indexed(index), Color::Indexed(seen)) if index == seen => { + Color::Indexed(index.saturating_add(1)) + } + _ => color, + } + } + + pub fn accent() -> Color { + Self::rgb(86, 182, 246) + } + + pub fn accent_dim() -> Color { + Self::rgb(56, 116, 165) + } + + pub fn background() -> Color { + Self::rgb_in(Self::PAGE_RGB, color_mode()) + } + + pub fn card_bg() -> Color { + Self::rgb_in(Self::CARD_RGB, color_mode()) + } + + /// The alternating band of a data list. See [`Palette::band_after`] for why + /// this is not just another RGB constant. + pub fn card_bg_alt() -> Color { + Self::band_after(Self::card_bg(), Self::CARD_ALT_RGB) + } + + pub fn text() -> Color { + Self::rgb(224, 228, 236) + } + + pub fn muted_fg() -> Color { + Self::rgb(122, 130, 146) + } + + pub fn good() -> Color { + Self::rgb(94, 214, 154) + } + + pub fn warn() -> Color { + Self::rgb(246, 193, 90) + } + + pub fn bad() -> Color { + Self::rgb(240, 118, 118) + } + + pub fn purple() -> Color { + Self::rgb(167, 139, 250) + } + + pub fn teal() -> Color { + Self::rgb(94, 234, 212) + } + + pub fn base() -> Style { + Style::default().fg(Self::text()).bg(Self::background()) + } + + pub fn card() -> Style { + Style::default().fg(Self::text()).bg(Self::card_bg()) + } + + pub fn title() -> Style { + Style::default() + .fg(Self::accent()) + .bg(Self::background()) + .add_modifier(Modifier::BOLD) + } + + pub fn muted() -> Style { + Style::default().fg(Self::muted_fg()).bg(Self::background()) + } + + /// The row the keyboard is on. + /// + /// Its foreground is authored too: asking for ANSI black would hand the + /// readable half of the highlight to whatever the user happens to have + /// mapped to colour 0, and a light-grey "black" makes the cursor row + /// unreadable on a light-blue bar. Nothing in the theme depends on the + /// user's palette, which is also why 256 colours are matched by number + /// rather than by name. + /// + /// Where the terminal renders 24-bit colour this is the accent bar of the + /// reference design. Where it can only do 256 colours — Apple Terminal, + /// `TERM=xterm`, ssh to an old box — the row is filled with a **grey bar** + /// instead: the same "one row is lit" reading, with no reliance on the + /// accent surviving a palette the size of a crayon box. Where there is no + /// palette at all the row is drawn **inverted**, because reverse video is + /// the one highlight that needs no colour whatsoever. + pub fn selected() -> Style { + Self::selected_for(color_mode()) + } + + /// [`Self::selected`] with the capability stated explicitly, so the tests + /// can pin down every rendering in one process ([`color_mode`] is decided + /// once per process and cached). + pub fn selected_for(mode: ColorMode) -> Style { + match mode { + ColorMode::TrueColor => Style::default() + .fg(Self::rgb_in(Self::PAGE_RGB, mode)) + .bg(Self::accent()) + .add_modifier(Modifier::BOLD), + ColorMode::Color256 => Style::default() + .fg(Self::rgb_in(Self::PAGE_RGB, mode)) + .bg(Self::rgb_in(Self::CURSOR_GREY_RGB, mode)) + .add_modifier(Modifier::BOLD), + ColorMode::Monochrome => { + Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD) + } + } + } + + /// One row of a list on the right of the screen. + /// + /// The cursor row is the highlight; the rows around it alternate between + /// the card and one step lighter, so a row can be followed across a wide + /// card and the data does not sit as one flat grey slab. `index` is the + /// index of the row in the list, not on the screen: the band belongs to + /// the row and stays with it while the list scrolls. + pub fn row(highlight: bool, index: usize) -> Style { + if highlight { + return Self::selected(); + } + let band = if index % 2 == 0 { + Self::card_bg() + } else { + Self::card_bg_alt() + }; + Style::default().fg(Self::text()).bg(band) + } + + /// The list style behind [`Palette::row`]: the widget paints the gaps + /// between cards, the rows paint everything else. + pub fn list() -> Style { + Style::default().bg(Self::card_bg()) + } + + pub fn locked() -> Style { + Style::default().fg(Self::muted_fg()) + } + + /// Colour a usage ratio the way the system monitor does: cool until 70 %, + /// amber until 90 %, red beyond. + pub fn load(ratio: f64) -> Style { + let color = if ratio > 0.9 { + Self::bad() + } else if ratio > 0.7 { + Self::warn() + } else { + Self::good() + }; + Style::default().fg(color).bg(Self::card_bg()) + } + + pub fn size_color(bytes: squid_core::Bytes) -> Style { + let mib = bytes.as_u64() / (1024 * 1024); + if mib >= 1024 { + Style::default().fg(Self::bad()) + } else if mib >= 128 { + Style::default().fg(Self::warn()) + } else { + Style::default().fg(Self::muted_fg()) + } + } +} + +/// Rounded box, the single most recognisable part of the reference UI. +pub fn card(title: &str) -> ratatui::widgets::Block<'static> { + ratatui::widgets::Block::default() + .borders(ratatui::widgets::Borders::ALL) + .border_type(ratatui::widgets::BorderType::Rounded) + .border_style( + Style::default() + .fg(Palette::accent_dim()) + .bg(Palette::background()), + ) + .title_top(format!(" {title} ")) + .title_style(Palette::title()) + .style(Palette::card()) +} + +pub fn flat_block() -> ratatui::widgets::Block<'static> { + ratatui::widgets::Block::default().style(Palette::card()) +} + +/// Checkbox glyph, mirroring the round toggles of the reference app. +pub fn checkbox(selected: bool, locked: bool) -> (&'static str, Style) { + if locked { + ("🔒", Palette::locked()) + } else if selected { + ( + "●", + Style::default() + .fg(Palette::accent()) + .bg(Palette::card_bg()) + .add_modifier(Modifier::BOLD), + ) + } else { + ( + "○", + Style::default() + .fg(Palette::muted_fg()) + .bg(Palette::card_bg()), + ) + } +} + +pub const TRIANGLE_OPEN: &str = "▾"; +pub const TRIANGLE_CLOSED: &str = "▸"; + +/// Fit text to `width` display columns, keeping the tail of paths. +pub fn truncate(text: &str, width: usize, keep_tail: bool) -> String { + use unicode_width::UnicodeWidthChar; + let target = width.max(1); + let width_of = |s: &str| -> usize { s.chars().map(|c| c.width().unwrap_or(0)).sum() }; + if width_of(text) <= target { + return text.to_string(); + } + if target <= 3 { + return ".".repeat(target); + } + let mut out = String::new(); + if keep_tail { + let mut budget = target - 3; + for ch in text.chars().rev() { + let w = ch.width().unwrap_or(0); + if w > budget { + break; + } + budget -= w; + out.insert(0, ch); + } + format!("...{out}") + } else { + let mut budget = target - 1; + for ch in text.chars() { + let w = ch.width().unwrap_or(0); + if w > budget { + break; + } + budget -= w; + out.push(ch); + } + out.push('…'); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncation_respects_the_column_budget() { + let cut = truncate( + "/Users/tester/Library/Caches/com.example.heavy.app", + 20, + true, + ); + assert!(cut.chars().count() <= 20); + assert!(cut.starts_with("...")); + assert!(cut.ends_with("heavy.app")); + let head = truncate("Browser Caches", 8, false); + assert!(head.chars().count() <= 8); + assert!(head.ends_with('…')); + assert_eq!(truncate("short", 40, false), "short"); + } + + #[test] + fn wide_characters_count_as_two_columns() { + let cut = truncate("清理缓存与日志文件", 6, false); + assert!(cut.chars().count() <= 4, "{cut}"); + } + + #[test] + fn the_grey_ramp_catches_the_background_tones() { + assert_eq!(nearest_index((16, 18, 23)), 233); + assert_eq!(nearest_index((24, 27, 33)), 234); + assert_eq!(nearest_index((224, 228, 236)), 254); + assert_eq!(nearest_index((122, 130, 146)), 244); + } + + #[test] + fn saturated_colours_take_the_nearest_cube_entry() { + for rgb in [ + (86, 182, 246), + (94, 214, 154), + (246, 193, 90), + (240, 118, 118), + (167, 139, 250), + (94, 234, 212), + ] { + let index = nearest_index(rgb); + assert!((16..232).contains(&index), "{rgb:?} -> {index}"); + let drift = (i32::from(dequantise(index).0) - i32::from(rgb.0)).abs() + + (i32::from(dequantise(index).1) - i32::from(rgb.1)).abs() + + (i32::from(dequantise(index).2) - i32::from(rgb.2)).abs(); + assert!(drift <= 96, "{rgb:?} -> {index} drifts by {drift}"); + } + } + + fn dequantise(index: u8) -> (u8, u8, u8) { + let index = index - 16; + ( + CUBE[(index / 36) as usize], + CUBE[(index % 36 / 6) as usize], + CUBE[(index % 6) as usize], + ) + } + + #[test] + fn apple_terminal_gets_the_fallback_palette() { + let env = |key: &str| match key { + "TERM" => Some("xterm-256color".to_string()), + "TERM_PROGRAM" => Some("Apple_Terminal".to_string()), + _ => None, + }; + assert!(!decide_truecolor(env)); + assert_eq!(decide_mode(env), ColorMode::Color256); + } + + #[test] + fn modern_terminals_keep_their_full_palette() { + let env = |key: &str| match key { + "TERM" => Some("xterm-256color".to_string()), + "TERM_PROGRAM" => Some("iTerm.app".to_string()), + _ => None, + }; + assert!(decide_truecolor(env)); + let env = |key: &str| (key == "COLORTERM").then(|| "truecolor".to_string()); + assert!(decide_truecolor(env)); + } + + /// ...and a terminal that simply never says anything is not given 24-bit + /// colour on trust. 「不支持 truecolor 就退回 256 色」 is the whole request: + /// the smaller palette is the safe answer, since a terminal that cannot + /// parse a truecolour sequence prints it as text. + #[test] + fn a_silent_terminal_is_not_given_truecolour_on_trust() { + for term in ["xterm", "xterm-color", "screen", "rxvt-unicode", "vt100"] { + let env = move |key: &str| (key == "TERM").then(|| term.to_string()); + assert!(!decide_truecolor(env), "{term} does not advertise 24-bit"); + assert_eq!(decide_mode(env), ColorMode::Color256, "{term}"); + } + // One that does name 24-bit in `TERM` gets it. + let env = |key: &str| (key == "TERM").then(|| "xterm-truecolor".to_string()); + assert!(decide_truecolor(env)); + assert_eq!(decide_mode(env), ColorMode::TrueColor); + } + + /// The answer to 「Terminal.app 里看不出选中,能不能用灰度?」: the cursor row + /// must survive a terminal with no usable palette. + #[test] + fn the_cursor_row_survives_a_colourless_terminal() { + let rich = Palette::selected_for(ColorMode::TrueColor); + assert!( + rich.add_modifier.contains(Modifier::BOLD), + "the accent bar is bold" + ); + assert!( + !rich.add_modifier.contains(Modifier::REVERSED), + "a capable terminal paints a filled bar instead of inverting" + ); + + let plain = Palette::selected_for(ColorMode::Color256); + assert!( + plain.add_modifier.contains(Modifier::BOLD), + "the grey bar is bold, so it is visible in a greyscale theme too" + ); + assert!( + !plain.add_modifier.contains(Modifier::REVERSED), + "256 colours get a real grey bar, not a terminal-dependent inversion" + ); + + // The two states must be distinguishable even if every colour collapses. + let grey = Palette::selected_for(ColorMode::Monochrome); + assert_ne!( + rich.bg, plain.bg, + "the fallback may not be merely a different colour" + ); + assert!( + grey.add_modifier.contains(Modifier::REVERSED), + "with no palette at all the row inverts — reverse video needs no colour" + ); + assert_eq!(grey.bg, None, "and no colour is emitted at all"); + } + + /// Each palette keeps to itself. A 24-bit terminal is handed authored RGB + /// and nothing else, because an index is a request to look the user's own + /// palette up; a 256-colour terminal is handed indices and nothing else, + /// because an RGB triple it cannot parse is printed as text. + #[test] + fn each_palette_stays_inside_its_own_sequences() { + // The palette helpers read the process-wide mode for the colours they + // author themselves, so the mode is pinned before anything is asked. + force_color_mode(ColorMode::TrueColor); + let rich = Palette::selected_for(ColorMode::TrueColor); + assert!( + matches!(rich.bg, Some(Color::Rgb(..))), + "the bar is authored" + ); + assert!( + matches!(rich.fg, Some(Color::Rgb(..))), + "and so is the text on it: {:?}", + rich.fg + ); + + let plain = Palette::selected_for(ColorMode::Color256); + assert!(matches!(plain.bg, Some(Color::Indexed(_)))); + assert!(matches!(plain.fg, Some(Color::Indexed(_)))); + + // Everything the theme can hand out obeys the same rule. + for colour in [ + Palette::resolve_in(Color::Rgb(86, 182, 246), ColorMode::TrueColor), + Palette::resolve_in(Color::Rgb(24, 27, 33), ColorMode::TrueColor), + ] { + assert!(matches!(colour, Color::Rgb(..)), "{colour:?}"); + } + force_color_mode(ColorMode::Color256); + for colour in [ + Palette::resolve_in(Color::Rgb(86, 182, 246), ColorMode::Color256), + Palette::resolve_in(Color::Indexed(33), ColorMode::Color256), + ] { + assert!(matches!(colour, Color::Indexed(_)), "{colour:?}"); + } + + // A named ANSI colour already *is* a palette entry, in 256 colours as + // in 24-bit ones, so there is nothing to translate and nothing to + // garble: it is a `38;5;n` sequence either way, never a triple. + for mode in [ColorMode::TrueColor, ColorMode::Color256] { + assert_eq!( + Palette::resolve_in(Color::LightBlue, mode), + Color::LightBlue, + "{mode:?}" + ); + } + } + + /// 「256 色时右侧的数据要高亮(灰度)显示」: the two bands a list alternates + /// between have to survive the collapse to 256 colours, or the rows read as + /// one flat slab and the cursor row has nothing to stand out from. + #[test] + fn the_two_bands_of_a_list_stay_apart_in_256_colours() { + // The authored greys are one ramp step apart, which is exactly the pair + // that would otherwise land on the same index. + let base = nearest_index(Palette::CARD_RGB); + let alt = nearest_index(Palette::CARD_ALT_RGB); + assert_eq!( + base, alt, + "the test is only worth anything if the naive answer collides" + ); + let card = Palette::resolve_in(Color::Rgb(24, 27, 33), ColorMode::Color256); + let band = Palette::band_after_in(card, Palette::CARD_ALT_RGB, ColorMode::Color256); + assert_ne!(card, band, "the two bands must not be the same colour"); + assert_eq!(band, Color::Indexed(base + 1), "one step up the ramp"); + assert!( + matches!(band, Color::Indexed(_)), + "and stay on the grey ramp: {band:?}" + ); + + // The page, the card, and the band are three different steps. + let page = Palette::resolve_in(Color::Rgb(16, 18, 23), ColorMode::Color256); + for (left, right) in [(page, card), (card, band), (page, band)] { + assert_ne!(left, right, "{left:?} and {right:?} would be one colour"); + } + + // And the cursor row is lit against both of them. + let cursor = Palette::selected_for(ColorMode::Color256).bg; + assert_ne!(cursor, Some(card)); + assert_ne!(cursor, Some(band)); + } + + /// In a terminal with no palette the stripes must not turn into a wall of + /// SGR sequences: colour is dropped, and only the attributes are left. + #[test] + fn a_monochrome_terminal_gets_no_colour_at_all() { + assert_eq!( + Palette::resolve_in(Color::Rgb(86, 182, 246), ColorMode::Monochrome), + Color::Reset + ); + let env = |key: &str| (key == "NO_COLOR").then(|| "1".to_string()); + assert_eq!(decide_mode(env), ColorMode::Monochrome); + let env = |key: &str| (key == "TERM").then(|| "dumb".to_string()); + assert_eq!(decide_mode(env), ColorMode::Monochrome); + // `NO_COLOR` outranks an emphatic yes from the terminal itself. + let env = |key: &str| match key { + "NO_COLOR" => Some("1".to_string()), + "COLORTERM" => Some("truecolor".to_string()), + _ => None, + }; + assert_eq!(decide_mode(env), ColorMode::Monochrome); + // An empty NO_COLOR means nothing, as the convention says. + let env = |key: &str| match key { + "NO_COLOR" => Some("".to_string()), + "COLORTERM" => Some("truecolor".to_string()), + _ => None, + }; + assert_eq!(decide_mode(env), ColorMode::TrueColor); + } + + /// A terminal that reports 24-bit through its library, with nothing in the + /// environment to say so, still gets the full palette. + #[test] + fn the_terminal_library_can_vouch_for_truecolour() { + let env = |key: &str| (key == "TERM").then(|| "screen-256color".to_string()); + assert_eq!(decide_mode_with(&env, u16::MAX), ColorMode::TrueColor); + assert_eq!(decide_mode_with(&env, 256), ColorMode::Color256); + } + + /// Checked vs unchecked is carried by the glyph and its weight, not only by + /// its colour, for the same reason. + #[test] + fn a_checked_box_differs_from_an_empty_one_without_colour() { + let (on, on_style) = checkbox(true, false); + let (off, off_style) = checkbox(false, false); + assert_ne!(on, off, "the glyphs differ"); + assert!( + on_style.add_modifier.contains(Modifier::BOLD), + "the filled box is heavier" + ); + assert!(!off_style.add_modifier.contains(Modifier::BOLD)); + } + + #[test] + fn the_override_outranks_the_probing() { + let env = |key: &str| match key { + "SQUID_TRUECOLOR" => Some("always".to_string()), + "TERM_PROGRAM" => Some("Apple_Terminal".to_string()), + _ => None, + }; + assert!(decide_truecolor(env)); + let env = |key: &str| match key { + "SQUID_TRUECOLOR" => Some("never".to_string()), + "COLORTERM" => Some("truecolor".to_string()), + _ => None, + }; + assert!(!decide_truecolor(env)); + } + + /// The user's `SQUID_TRUECOLOR=never` has to outrank the terminal library + /// too — it reads the very `COLORTERM` that made the library say yes, so + /// asking it afterwards is how the override came to be ignored. + #[test] + fn saying_no_outranks_the_terminal_librarys_yes() { + let env = |key: &str| match key { + "SQUID_TRUECOLOR" => Some("never".to_string()), + "COLORTERM" => Some("truecolor".to_string()), + "TERM" => Some("xterm-256color".to_string()), + _ => None, + }; + assert_eq!( + decide_mode_with(&env, u16::MAX), + ColorMode::Color256, + "the palette drops to 256, which is what the override is for" + ); + let env = |key: &str| match key { + "SQUID_TRUECOLOR" => Some("always".to_string()), + "TERM" => Some("xterm".to_string()), + _ => None, + }; + assert_eq!(decide_mode_with(&env, 0), ColorMode::TrueColor); + } + + #[test] + fn strings_pick_the_requested_language() { + let mut settings = Settings { + language: Some("zh".into()), + ..Settings::default() + }; + let strings = Strings::detect(&settings); + assert_eq!(strings.cleanup(), "清理"); + settings.language = Some("en".into()); + assert_eq!(Strings::detect(&settings).cleanup(), "Cleanup"); + } + + /// `1634·24.3 GB` was read as one broken decimal, and 「已删除」over a list + /// nobody has acted on yet was read as a claim about the past. + #[test] + fn counts_and_labels_cannot_be_mistaken_for_a_size() { + let zh = Strings { lang: Lang::Zh }; + let en = Strings { lang: Lang::En }; + assert_eq!(zh.count(1634), "1,634 项"); + assert_eq!(en.count(1634), "1,634"); + assert_eq!(zh.count(5), "5 项"); + assert_eq!(zh.deleted(), "可删除"); + assert_eq!(en.deleted(), "deletable"); + } + + /// Nine groups, two languages: the Chinese interface must not fall back to + /// English halfway, and a name has to survive the 24-column group row. + #[test] + fn every_group_has_a_name_in_its_own_language() { + use squid_core::Category; + let zh = Strings { lang: Lang::Zh }; + let en = Strings { lang: Lang::En }; + for category in Category::ALL { + let name = zh.category(category); + assert!(!name.is_empty(), "{category:?} lost its name"); + assert!( + name.chars().any(|c| c as u32 > 0x2fff), + "{category:?} is still English in Chinese: {name}" + ); + assert!( + unicode_width::UnicodeWidthStr::width(name.as_str()) <= 24, + "{name} will not fit the group row" + ); + assert_eq!(en.category(category), category.title()); + } + assert_eq!(zh.category(Category::Developer), "开发文件"); + assert_eq!(zh.category(Category::LanguagePacks), "多余语言包"); + } +} diff --git a/crates/squid-tui/src/views.rs b/crates/squid-tui/src/views.rs new file mode 100644 index 0000000..27b243f --- /dev/null +++ b/crates/squid-tui/src/views.rs @@ -0,0 +1,2292 @@ +//! Every pixel of the interface, and nothing else. +//! +//! Nothing in this file mutates [`App`] and nothing touches the disk: it reads +//! state and draws it. The layout follows the reference app — a coloured card +//! per group, one accent colour, a big number for the space you get back. + +use crate::app::{ + App, Confirm, Line as AppLine, Panel, ScanPanel, Toast, ToastKind, UninstallView, +}; +use crate::theme::{ + card as theme_card, checkbox, truncate, Palette, TRIANGLE_CLOSED, TRIANGLE_OPEN, +}; +use ratatui::layout::{Alignment, Constraint, Layout, Rect}; +use ratatui::style::{Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Clear, Gauge, List, ListState, Paragraph, Sparkline, Wrap}; +use ratatui::Frame; +use squid_core::{Bytes, Category, CleanupItem}; +use unicode_width::UnicodeWidthStr; + +// ------------------------------------------------------------------- helpers + +fn block(title: &str) -> Block<'static> { + theme_card(title) +} + +fn plain_block() -> Block<'static> { + Block::default() + .borders(Borders::ALL) + .border_type(ratatui::widgets::BorderType::Rounded) + .border_style(Style::default().fg(Palette::accent_dim())) + .style(Palette::card()) +} + +fn pad(text: &str, width: usize) -> String { + let used = text.width(); + if used >= width { + truncate(text, width, false) + } else { + format!("{text}{}", " ".repeat(width - used)) + } +} + +fn right(text: &str, width: usize) -> String { + let used = text.width(); + if used >= width { + truncate(text, width, false) + } else { + format!("{}{text}", " ".repeat(width - used)) + } +} + +fn spans_width(spans: &[Span<'static>]) -> usize { + spans.iter().map(|span| span.content.width()).sum() +} + +/// Left-aligned spans, then filler, then right-aligned spans. +fn joined(left: Vec>, right: Vec>, width: usize) -> Line<'static> { + let gap = width.saturating_sub(spans_width(&left) + spans_width(&right)); + let mut spans = left; + spans.push(Span::raw(" ".repeat(gap))); + spans.extend(right); + close_gaps(&mut spans); + Line::from(spans) +} + +/// Give the unstyled spans of a row the row's own style. +/// +/// The columns of a row are separated by plain `Span::raw(" ")`, which inherit +/// the card background, and `joined` adds a filler span the same way. On a +/// highlighted row that leaves thin unhighlighted slits through the bar: easy +/// to miss in colour, but in a terminal without a usable palette — where the +/// cursor is drawn as reverse video — the bar would come out striped. When +/// every visible span already agrees on one style, that style *is* the row's +/// style, so the gaps get it too. +fn close_gaps(spans: &mut [Span<'static>]) { + let mut shared: Option