From 3fbc83cf5f27574ccec4207c2ec948bf89c9e810 Mon Sep 17 00:00:00 2001 From: us Date: Mon, 16 Nov 2026 17:56:48 +0300 Subject: [PATCH] fix: make GUI system clean succeed on Go caches, rustup and SwiftPM - scanner skips the Go module cache (pkg/mod with cache/download), so its modules are no longer listed as projects with deletable bin dirs - robust removes retry with the parent's owner write bit when we own a read-only dir (Go module cache is 0555), then restore its mode - allow exactly `rustup toolchain remove` and `swift package purge-cache` - per-project DerivedData SourcePackages is a plain delete; purge-cache only cleans the global SwiftPM cache - an item removed earlier in the same batch reports "Already removed" when its path is gone under home, instead of an error - resolve tools from ~/.cargo/bin, Homebrew, bun and Go dirs and pass that PATH to children: a Finder-launched app now finds rustup, so the default toolchain is marked active instead of deletable --- crates/null-e-core/src/cleaners/ios_deps.rs | 4 +- crates/null-e-core/src/cleaners/runtimes.rs | 2 +- crates/null-e-core/src/fsutil.rs | 156 +++++++++++++++++++- crates/null-e-core/src/scanner/parallel.rs | 49 ++++++ plans/gui-clean-failures.md | 36 +++++ tauri/src/commands/cleaners.rs | 44 +++++- 6 files changed, 279 insertions(+), 12 deletions(-) create mode 100644 plans/gui-clean-failures.md diff --git a/crates/null-e-core/src/cleaners/ios_deps.rs b/crates/null-e-core/src/cleaners/ios_deps.rs index 35729df..9f74807 100644 --- a/crates/null-e-core/src/cleaners/ios_deps.rs +++ b/crates/null-e-core/src/cleaners/ios_deps.rs @@ -191,7 +191,9 @@ impl IosDependencyCleaner { last_modified: get_mtime(&entry.path()), description: Cow::Borrowed("Swift Package Manager downloaded packages. Will be re-downloaded."), safe_to_delete: SafetyLevel::SafeWithCost, - clean_command: Some("swift package purge-cache".to_string()), + // Plain delete of this project's folder: `swift package + // purge-cache` only cleans the global SwiftPM cache. + clean_command: None, }); } } diff --git a/crates/null-e-core/src/cleaners/runtimes.rs b/crates/null-e-core/src/cleaners/runtimes.rs index fdcf2b9..14361f6 100644 --- a/crates/null-e-core/src/cleaners/runtimes.rs +++ b/crates/null-e-core/src/cleaners/runtimes.rs @@ -937,7 +937,7 @@ impl RuntimesCleaner { /// Detect rustup active toolchain fn detect_rustup_active(&self) -> Option { - Command::new("rustup") + Command::new(crate::fsutil::resolve_tool("rustup")) .args(["default"]) .output() .ok() diff --git a/crates/null-e-core/src/fsutil.rs b/crates/null-e-core/src/fsutil.rs index 6d51352..58e38af 100644 --- a/crates/null-e-core/src/fsutil.rs +++ b/crates/null-e-core/src/fsutil.rs @@ -10,7 +10,7 @@ //! module also exposes. use std::fs::Metadata; -use std::path::Path; +use std::path::{Path, PathBuf}; /// On-disk allocated bytes for a single file's metadata (`st_blocks * 512` on Unix). /// @@ -364,7 +364,97 @@ pub fn try_clear_user_immutable(_path: &Path) -> bool { false } -/// Remove a single file, clearing a user immutable flag and retrying once on `EPERM`. +/// Directories to search for developer tools: `PATH`, then the usual install locations. +/// +/// A GUI app launched from Finder inherits a minimal `PATH` (`/usr/bin:/bin:/usr/sbin:/sbin`), so +/// tools in `~/.cargo/bin`, Homebrew or `~/.bun/bin` are not found by name. +pub fn tool_search_dirs() -> Vec { + let home = dirs::home_dir(); + let mut dirs: Vec = std::env::var_os("PATH") + .map(|p| std::env::split_paths(&p).collect()) + .unwrap_or_default(); + let extra = [ + std::env::var_os("CARGO_HOME").map(|c| PathBuf::from(c).join("bin")), + home.as_ref().map(|h| h.join(".cargo/bin")), + Some(PathBuf::from("/opt/homebrew/bin")), + Some(PathBuf::from("/usr/local/bin")), + home.as_ref().map(|h| h.join(".bun/bin")), + home.as_ref().map(|h| h.join("go/bin")), + Some(PathBuf::from("/usr/local/go/bin")), + ]; + for dir in extra.into_iter().flatten() { + if !dirs.contains(&dir) { + dirs.push(dir); + } + } + dirs +} + +/// `PATH` value for a child process: [`tool_search_dirs`] joined, so `#!/usr/bin/env node` +/// scripts such as npm also find their interpreter. +pub fn tool_search_path() -> std::ffi::OsString { + std::env::join_paths(tool_search_dirs()).unwrap_or_default() +} + +/// Resolve a developer tool binary by name; falls back to the bare name so errors stay readable. +pub fn resolve_tool(name: &str) -> PathBuf { + find_tool_in(&tool_search_dirs(), name).unwrap_or_else(|| PathBuf::from(name)) +} + +/// First executable file called `name` in `dirs`. +fn find_tool_in(dirs: &[PathBuf], name: &str) -> Option { + dirs.iter() + .map(|d| d.join(name)) + .find(|p| is_executable_file(p)) +} + +#[cfg(unix)] +fn is_executable_file(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} + +#[cfg(not(unix))] +fn is_executable_file(path: &Path) -> bool { + path.is_file() +} + +/// Retry `op` with the parent directory of `path` given its owner write bit, then put the old mode +/// back. +/// +/// Unlinking needs write permission on the parent, not on the entry. Tools such as the Go module +/// cache leave their trees read-only (0555), so every delete inside them fails with `EACCES`. +/// Returns `None` (and changes nothing) unless we own the parent and it lacks the bit. +#[cfg(unix)] +fn retry_with_parent_writable( + path: &Path, + op: impl Fn(&Path) -> std::io::Result<()>, +) -> Option> { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let parent = path.parent()?; + let meta = std::fs::symlink_metadata(parent).ok()?; + // SAFETY: geteuid is always safe and never fails. + let euid = unsafe { libc::geteuid() }; + let mode = meta.mode() & 0o7777; + if !meta.is_dir() || meta.uid() != euid || mode & 0o200 != 0 { + return None; + } + std::fs::set_permissions(parent, std::fs::Permissions::from_mode(mode | 0o200)).ok()?; + let result = op(path); + let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(mode)); + Some(result) +} + +#[cfg(not(unix))] +fn retry_with_parent_writable( + _path: &Path, + _op: impl Fn(&Path) -> std::io::Result<()>, +) -> Option> { + None +} + +/// Remove a single file, retrying once after clearing a user immutable flag (`EPERM`) or with the +/// parent's owner write bit restored (`EACCES`). pub fn remove_file_robust(path: &Path) -> std::io::Result<()> { match std::fs::remove_file(path) { Ok(()) => Ok(()), @@ -375,12 +465,19 @@ pub fn remove_file_robust(path: &Path) -> std::io::Result<()> { return std::fs::remove_file(path); } } + if e.kind() == std::io::ErrorKind::PermissionDenied { + if let Some(result) = retry_with_parent_writable(path, |p| std::fs::remove_file(p)) + { + return result; + } + } Err(e) } } } -/// Remove an (empty) directory, clearing a user immutable flag and retrying once on `EPERM`. +/// Remove an (empty) directory, retrying once after clearing a user immutable flag (`EPERM`) or +/// with the parent's owner write bit restored (`EACCES`). pub fn remove_dir_robust(path: &Path) -> std::io::Result<()> { match std::fs::remove_dir(path) { Ok(()) => Ok(()), @@ -391,6 +488,11 @@ pub fn remove_dir_robust(path: &Path) -> std::io::Result<()> { return std::fs::remove_dir(path); } } + if e.kind() == std::io::ErrorKind::PermissionDenied { + if let Some(result) = retry_with_parent_writable(path, |p| std::fs::remove_dir(p)) { + return result; + } + } Err(e) } } @@ -468,6 +570,54 @@ mod tests { use super::*; use tempfile::TempDir; + #[cfg(unix)] + #[test] + fn find_tool_skips_non_executable_and_searches_in_order() { + use std::os::unix::fs::PermissionsExt; + let temp = TempDir::new().unwrap(); + let (first, second) = (temp.path().join("a"), temp.path().join("b")); + for (dir, mode) in [(&first, 0o644), (&second, 0o755)] { + std::fs::create_dir_all(dir).unwrap(); + let tool = dir.join("tool"); + std::fs::write(&tool, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(mode)).unwrap(); + } + let dirs = vec![first, second.clone()]; + + assert_eq!(find_tool_in(&dirs, "tool"), Some(second.join("tool"))); + assert_eq!(find_tool_in(&dirs, "missing"), None); + } + + #[test] + fn tool_search_dirs_include_cargo_bin() { + // A Finder-launched GUI has no ~/.cargo/bin on PATH; it must still be searched. + let cargo_bin = dirs::home_dir().unwrap().join(".cargo/bin"); + assert!(tool_search_dirs().contains(&cargo_bin)); + } + + #[cfg(unix)] + #[test] + fn robust_removes_work_inside_read_only_dirs() { + use std::os::unix::fs::PermissionsExt; + let temp = TempDir::new().unwrap(); + // Go module cache shape: read-only module dir holding a read-only bin dir. + let module = temp.path().join("mod@v1.0.0"); + let bin = module.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let file = bin.join("tool"); + std::fs::write(&file, b"x").unwrap(); + for d in [&bin, &module] { + std::fs::set_permissions(d, std::fs::Permissions::from_mode(0o555)).unwrap(); + } + + remove_file_robust(&file).expect("file in a 0555 dir should be removed"); + remove_dir_robust(&bin).expect("empty dir in a 0555 dir should be removed"); + assert!(!bin.exists()); + // The parent keeps its read-only mode: the write bit is put back after the retry. + let mode = std::fs::metadata(&module).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o555); + } + #[test] fn disk_space_returns_something_for_temp() { let temp = TempDir::new().unwrap(); diff --git a/crates/null-e-core/src/scanner/parallel.rs b/crates/null-e-core/src/scanner/parallel.rs index 38b037c..1a01e7c 100644 --- a/crates/null-e-core/src/scanner/parallel.rs +++ b/crates/null-e-core/src/scanner/parallel.rs @@ -76,6 +76,12 @@ impl ParallelScanner { return false; } + // Skip the Go module cache (`$GOPATH/pkg/mod`): its modules carry go.mod files and + // would be reported as projects. The caches module cleans it as a whole. + if e.depth() > 0 && is_go_module_cache(e.path()) { + return false; + } + // Skip hidden directories if configured if skip_hidden && e.depth() > 0 && name.starts_with('.') { // But allow some important hidden dirs @@ -260,11 +266,54 @@ impl Scanner for ParallelScanner { } } +/// Whether `path` is a Go module cache root: `.../pkg/mod` holding Go's `cache/download` store. +/// The marker keeps a project's own `pkg/mod` package dir scannable. +fn is_go_module_cache(path: &Path) -> bool { + path.file_name().is_some_and(|n| n == "mod") + && path + .parent() + .and_then(|p| p.file_name()) + .is_some_and(|n| n == "pkg") + && path.join("cache/download").is_dir() +} + #[cfg(test)] mod tests { use super::*; use tempfile::TempDir; + fn setup_go_module(root: &Path) { + let module = root.join("pkg/mod/github.com/x/y@v1.0.0"); + std::fs::create_dir_all(module.join("bin")).unwrap(); + std::fs::write(module.join("go.mod"), "module github.com/x/y\n").unwrap(); + std::fs::write(module.join("bin/tool"), "binary").unwrap(); + } + + fn scan_project_count(root: &Path) -> usize { + let registry = Arc::new(PluginRegistry::with_builtins()); + let scanner = ParallelScanner::new(registry); + scanner.scan(&ScanConfig::new(root)).unwrap().projects.len() + } + + #[test] + fn test_scan_skips_go_module_cache() { + let temp = TempDir::new().unwrap(); + let gopath = temp.path().join("go"); + setup_go_module(&gopath); + std::fs::create_dir_all(gopath.join("pkg/mod/cache/download")).unwrap(); + + assert_eq!(scan_project_count(temp.path()), 0); + } + + #[test] + fn test_scan_keeps_project_pkg_mod_dir() { + // A repo's own pkg/mod package dir (no Go cache marker) is still scanned. + let temp = TempDir::new().unwrap(); + setup_go_module(&temp.path().join("repo")); + + assert_eq!(scan_project_count(temp.path()), 1); + } + fn setup_node_project(path: &Path) { std::fs::write(path.join("package.json"), r#"{"name": "test"}"#).unwrap(); std::fs::create_dir(path.join("node_modules")).unwrap(); diff --git a/plans/gui-clean-failures.md b/plans/gui-clean-failures.md new file mode 100644 index 0000000..6adfa8c --- /dev/null +++ b/plans/gui-clean-failures.md @@ -0,0 +1,36 @@ +# GUI clean failures (v0.4.3 report) + +Summary: a full GUI clean reported 10 failures. Five root causes, all fixed in one PR. + +1. Go module cache scanned as projects: `~/go/pkg/mod/.../v2@x/bin` listed as Go build output. +2. Read-only dirs (Go module cache is 0555) make every file delete fail with EACCES. +3. `rustup toolchain remove` and `swift package purge-cache` refused by the GUI allow-list. +4. Per-project `DerivedData/*/SourcePackages` item carries `swift package purge-cache`, which + cleans the global SwiftPM cache, not that folder. +5. An item already removed earlier in the same batch fails with "System item not found". + +## Changes + +| # | File | Change | +|---|------|--------| +| 1 | `crates/null-e-core/src/scanner/parallel.rs` | skip `.../pkg/mod` holding `cache/download` (Go module cache; the caches module owns it) | +| 2 | `crates/null-e-core/src/fsutil.rs` | on `PermissionDenied`, if we own the parent and it lacks the owner write bit, add it, retry once, restore the old mode | +| 3 | `tauri/src/commands/cleaners.rs` | allow exactly `rustup toolchain remove` and `swift package purge-cache` (prefix list, not whole binaries) | +| 4 | `crates/null-e-core/src/cleaners/ios_deps.rs` | per-project SourcePackages item: `clean_command: None` (plain path delete) | +| 5 | `tauri/src/commands/cleaners.rs` | item not re-detected and its path is NotFound under home: success, 0 bytes, "Already removed" | +| 6 | `fsutil.rs`, `runtimes.rs`, `cleaners.rs` | `resolve_tool` / `tool_search_path`: a Finder-launched app finds tools in `~/.cargo/bin`, Homebrew, bun, Go, and children get that PATH. `rustup default` now resolves, so the default toolchain is marked active instead of deletable | + +Review: two rounds (code-reviewer). Round 1 found 4 issues (placeholder Docker paths, `pkg/mod` false +positives, mode left changed, PATH in a Finder-launched app); all fixed and confirmed in round 2. + +## Verify + +- Unit tests: scanner skips `pkg/mod`; `remove_file_robust` deletes a file inside a 0555 dir. +- `cargo test --workspace`, `cargo clippy --workspace -- -D warnings`, `cargo fmt --check`. +- Real run: build the CLI, scan a temp tree holding a fake `go/pkg/mod/x@v1/{go.mod,bin}`: not listed. + +## Risks + +- Fix 2 changes a parent dir's mode only when we own it and only to add `u+w`; the dir is being + emptied anyway. Root-owned dirs are untouched (still NeedsAdmin). +- Fix 3: both binaries run with no shell and only with commands from our own detection. diff --git a/tauri/src/commands/cleaners.rs b/tauri/src/commands/cleaners.rs index db25c7d..e7eb0b6 100644 --- a/tauri/src/commands/cleaners.rs +++ b/tauri/src/commands/cleaners.rs @@ -160,11 +160,21 @@ const ALLOWED_ACTION_BINARIES: &[&str] = &[ "dscacheutil", ]; +/// Multi-purpose tools allowed only for one exact subcommand (e.g. never `rustup self uninstall`). +const ALLOWED_ACTION_PREFIXES: &[&[&str]] = &[ + &["rustup", "toolchain", "remove"], + &["swift", "package", "purge-cache"], +]; + fn command_is_allowed(cmd: &str) -> bool { - cmd.split_whitespace() - .next() - .map(|bin| ALLOWED_ACTION_BINARIES.contains(&bin)) - .unwrap_or(false) + let parts: Vec<&str> = cmd.split_whitespace().collect(); + let Some(bin) = parts.first() else { + return false; + }; + ALLOWED_ACTION_BINARIES.contains(bin) + || ALLOWED_ACTION_PREFIXES + .iter() + .any(|prefix| parts.starts_with(prefix)) } /// Result of running a typed system action. @@ -190,10 +200,29 @@ pub async fn run_system_action( ) -> Result { tokio::task::spawn_blocking(move || { let (items, _skipped) = collect_cleanable_items(); - let item = items + let Some(item) = items .into_iter() .find(|i| i.path.to_string_lossy() == path && i.name == name) - .ok_or_else(|| format!("System item not found: {} ({})", name, path))?; + else { + // An earlier action in the same batch (a parent cache, an official command) may have + // removed it already: that is the goal, not a failure. Only a real NotFound under the + // home dir counts; placeholder paths (Docker's /var/lib/docker) and unreadable ones + // keep the error. + let gone = matches!( + std::fs::symlink_metadata(&path), + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ); + let under_home = + dirs::home_dir().is_some_and(|h| std::path::Path::new(&path).starts_with(h)); + if gone && under_home { + return Ok(SystemActionResultDto { + success: true, + bytes_freed: 0, + message: "Already removed".to_string(), + }); + } + return Err(format!("System item not found: {} ({})", name, path)); + }; let target = item.path.clone(); @@ -244,7 +273,8 @@ fn run_allowed_command(cmd: &str) -> Result<(), String> { if parts.is_empty() { return Err("Empty command".to_string()); } - let output = Command::new(parts[0]) + let output = Command::new(null_e_core::fsutil::resolve_tool(parts[0])) + .env("PATH", null_e_core::fsutil::tool_search_path()) .args(&parts[1..]) .output() .map_err(|e| e.to_string())?;