From afc87fc64707771d9780a75b4e438b1cf4be83f0 Mon Sep 17 00:00:00 2001 From: Mark Imbriaco Date: Thu, 24 Sep 2026 20:43:52 -0400 Subject: [PATCH 01/17] Set the window class to disktree The desktop entry and the Hyprland rule already name this class. The window never set a Wayland app id, so the class was empty and the rule did not match. --- README.md | 3 ++- crates/disktree-app/src/main.rs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e1c1580..b37c5b7 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,8 @@ tested: ## On Hyprland Hyprland tiles new windows, so disktree opens into whatever tile it is given. -It is designed for a roomy window; float it, or give it a rule: +It is designed for a roomy window; float it, or give it a rule. The window +class is `disktree`. ``` windowrule = float, class:^(disktree)$ diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 22b8265..483adcb 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -91,6 +91,12 @@ fn main() -> Result<()> { ), ..Default::default() }), + // Wayland app id. Hyprland reports it as the window + // class, and the desktop entry's StartupWMClass and + // the documented window rule both match `disktree`. + // Left unset, the class is empty and that rule never + // matches. + app_id: Some("disktree".to_owned()), // Below this the treemap stops being readable, so ask // the compositor not to go there. window_min_size: Some(size(px(900.), px(600.))), From fdb2e42e5e5414c38cc498befba32b8fa94ea065 Mon Sep 17 00:00:00 2001 From: Mark Silverstein Date: Fri, 25 Sep 2026 13:57:48 +0800 Subject: [PATCH 02/17] fix: never delete into a filesystem mounted inside a target remove_dir_all crosses mount boundaries, so permanently deleting a marked directory emptied anything mounted below it (sshfs, NFS, a USB disk, a bind mount) before failing with EBUSY on the mount point. A one-filesystem scan never shows that content, so it was data the user never saw. The plan now refuses a target with a mount point beneath it, and the removal walks the tree itself with openat(O_NOFOLLOW), stopping at a directory on another device or mount (statx mount ID, which also sees same-filesystem bind mounts). Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 5 +- crates/disktree-core/src/removal.rs | 221 +++++++++++++++++++++++++++- 2 files changed, 218 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e1c1580..0ce64fe 100644 --- a/README.md +++ b/README.md @@ -191,8 +191,9 @@ tested: - only paths under the scanned root can be removed; - the filesystem root, the scanned root and your home directory are refused; -- a mount point is refused, since removing it would reach into another - filesystem; +- a mount point is refused, and so is anything with a mount point inside it, + since removing it would reach into another filesystem; permanent deletion + also stops at a device boundary rather than descending into one; - system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, …) are refused even where permissions would allow it: packages own them, and pacman, paccache or `journalctl --vacuum` are the tools; diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index c15ad04..783338a 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -6,8 +6,8 @@ //! //! Two mechanisms are offered: //! -//! * [`RemovalMode::Permanent`] — `rm -rf` semantics, implemented with the -//! standard library rather than by shelling out, so no path ever reaches a +//! * [`RemovalMode::Permanent`] — `rm -rf --one-file-system` semantics, +//! implemented here rather than by shelling out, so no path ever reaches a //! shell and no filename can be misread as an option. //! * [`RemovalMode::Trash`] — move to the desktop trash, using `trash-put`, //! then `gio trash`, then a built-in XDG implementation. The backend is @@ -95,10 +95,14 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { let home = std::env::var_os("HOME").map(PathBuf::from); let mut plan = Plan::default(); let mut accepted: Vec = Vec::new(); + if targets.is_empty() { + return plan; + } + let mounts = mount_points(); for target in targets { let path = normalize(&target.path); - if let Some(reason) = refuse(&path, &root, home.as_deref()) { + if let Some(reason) = refuse(&path, &root, home.as_deref(), &mounts) { plan.blocked.push(Blocked { path: target.path.clone(), reason, @@ -164,7 +168,12 @@ fn system_tree(path: &Path, home: Option<&Path>) -> Option<&'static str> { .copied() } -fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { +fn refuse( + path: &Path, + root: &Path, + home: Option<&Path>, + mounts: &[PathBuf], +) -> Option { if path.parent().is_none() { return Some("the filesystem root cannot be removed".into()); } @@ -188,9 +197,39 @@ fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { .into(), ); } + if let Some(mount) = mount_below(path, mounts) { + return Some(format!( + "{} is mounted inside it: removing it would reach into another \ + filesystem", + mount.display() + )); + } None } +/// Every mount point on this machine, from the mount table. Empty where the +/// table cannot be read; the removal walker still stops at a device boundary. +fn mount_points() -> Vec { + std::fs::read_to_string("/proc/self/mounts") + .map(|table| { + crate::space::parse_mounts(&table) + .into_iter() + .map(|mount| mount.point) + .collect() + }) + .unwrap_or_default() +} + +/// A mount point strictly inside `path`, if there is one. A scan that stays +/// on one filesystem never shows what is mounted there, so the user cannot +/// have meant to remove it. +fn mount_below<'a>(path: &Path, mounts: &'a [PathBuf]) -> Option<&'a Path> { + mounts + .iter() + .find(|mount| mount.as_path() != path && mount.starts_with(path)) + .map(PathBuf::as_path) +} + /// Whether `path` sits on a different device than its parent, i.e. is a /// mount point. Descending into one would delete data the user never marked. #[cfg(unix)] @@ -440,7 +479,26 @@ fn run( }); } -/// `rm -rf` semantics: a symlink is unlinked, never followed. +/// `rm -rf --one-file-system` semantics: a symlink is unlinked, never +/// followed, and nothing on another filesystem is touched. +/// +/// `fs::remove_dir_all` would descend into anything mounted inside `path` and +/// empty it before failing on the mount point itself, so the walk is done here +/// instead: every directory is opened relative to its parent with +/// `O_NOFOLLOW`, and one on a different device or mount stops the removal. +#[cfg(unix)] +pub fn remove_permanently(path: &Path) -> io::Result<()> { + let meta = fs::symlink_metadata(path)?; + if !meta.is_dir() { + return fs::remove_file(path); + } + let dir = open_dir(rustix::fs::CWD, path)?; + let top = Volume::of(&dir)?; + remove_contents(&dir, &top, path)?; + fs::remove_dir(path) +} + +#[cfg(not(unix))] pub fn remove_permanently(path: &Path) -> io::Result<()> { let meta = fs::symlink_metadata(path)?; if meta.is_dir() { @@ -450,6 +508,111 @@ pub fn remove_permanently(path: &Path) -> io::Result<()> { } } +/// Where a directory lives, as far as crossing into another filesystem goes. +#[cfg(unix)] +struct Volume { + device: rustix::fs::Stat, + /// The mount the directory belongs to, where the kernel reports it. A bind + /// mount of the same filesystem keeps its `st_dev`, so the device alone + /// cannot see it. + mount: Option, +} + +#[cfg(unix)] +impl Volume { + fn of(dir: &std::os::fd::OwnedFd) -> io::Result { + Ok(Self { + device: rustix::fs::fstat(dir)?, + mount: mount_id(dir), + }) + } + + fn contains(&self, other: &Self) -> bool { + self.device.st_dev == other.device.st_dev && self.mount == other.mount + } +} + +#[cfg(target_os = "linux")] +fn mount_id(dir: &std::os::fd::OwnedFd) -> Option { + use rustix::fs::{AtFlags, StatxFlags, statx}; + statx(dir, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID) + .ok() + .filter(|stat| stat.stx_mask & StatxFlags::MNT_ID.bits() != 0) + .map(|stat| stat.stx_mnt_id) +} + +#[cfg(all(unix, not(target_os = "linux")))] +const fn mount_id(_dir: &std::os::fd::OwnedFd) -> Option { + None +} + +#[cfg(unix)] +fn open_dir( + parent: impl std::os::fd::AsFd, + name: P, +) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, openat}; + openat( + parent, + name, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) +} + +/// Empty the directory open at `dir`, staying on the volume of `top`. +#[cfg(unix)] +fn remove_contents( + dir: &std::os::fd::OwnedFd, + top: &Volume, + path: &Path, +) -> io::Result<()> { + use rustix::fs::{AtFlags, Dir, FileType, unlinkat}; + use rustix::io::Errno; + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt as _; + + // Names first, then removal: unlinking while a directory stream is open + // on the same directory may skip entries. + let mut entries = Vec::new(); + for entry in Dir::read_from(dir)? { + let entry = entry?; + let name = entry.file_name(); + if name != c"." && name != c".." { + entries.push((name.to_owned(), entry.file_type())); + } + } + + for (name, kind) in entries { + let child_path = path.join(OsStr::from_bytes(name.to_bytes())); + if !matches!(kind, FileType::Directory | FileType::Unknown) { + unlinkat(dir, &name, AtFlags::empty())?; + continue; + } + let child = match open_dir(dir, &name) { + Ok(child) => child, + // Not a directory after all: a symlink, or a file on a + // filesystem that does not report types. + Err(Errno::NOTDIR | Errno::LOOP) => { + unlinkat(dir, &name, AtFlags::empty())?; + continue; + } + Err(error) => return Err(error.into()), + }; + if !top.contains(&Volume::of(&child)?) { + return Err(io::Error::other(format!( + "stopped at {}: another filesystem is mounted there, and \ + nothing on it was touched", + child_path.display() + ))); + } + remove_contents(&child, top, &child_path)?; + drop(child); + unlinkat(dir, &name, AtFlags::REMOVEDIR)?; + } + Ok(()) +} + /// Move one path to the desktop trash. pub fn move_to_trash(path: &Path, backend: TrashBackend) -> io::Result<()> { match backend { @@ -690,6 +853,52 @@ mod tests { } } + #[test] + fn a_target_with_a_mount_inside_is_refused() { + let temp = tree(); + let root = temp.path(); + let mounts = vec![root.join("a/b"), root.join("other")]; + assert_eq!( + mount_below(&root.join("a"), &mounts), + Some(root.join("a/b").as_path()) + ); + assert_eq!(mount_below(&root.join("a/b"), &mounts), None, "itself"); + assert_eq!(mount_below(&root.join("a/one.bin"), &mounts), None); + let reason = + refuse(&root.join("a"), root, None, &mounts).expect("refused"); + assert!(reason.contains("mounted inside"), "{reason}"); + assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None); + } + + #[test] + fn a_home_scan_has_nothing_mounted_below_a_temp_dir() { + let temp = tree(); + assert_eq!(mount_below(temp.path(), &mount_points()), None); + } + + #[test] + fn permanent_removal_takes_nested_trees_and_hidden_files() { + let temp = tree(); + let doomed = temp.path().join("a"); + fs::create_dir_all(doomed.join("b/c/d")).expect("mkdir"); + fs::write(doomed.join("b/c/d/.hidden"), "x").expect("write"); + fs::write(doomed.join("b/c/f"), "x").expect("write"); + remove_permanently(&doomed).expect("remove tree"); + assert!(!doomed.exists()); + assert!(temp.path().join("other").exists()); + } + + #[test] + fn permanent_removal_unlinks_nested_symlinks_without_following_them() { + let temp = tree(); + let outside = TempDir::new().expect("tempdir"); + fs::write(outside.path().join("keep"), "x").expect("write"); + std::os::unix::fs::symlink(outside.path(), temp.path().join("a/link")) + .expect("symlink"); + remove_permanently(&temp.path().join("a")).expect("remove tree"); + assert!(outside.path().join("keep").exists()); + } + #[test] fn permanent_removal_takes_directories_and_leaves_siblings() { let temp = tree(); @@ -908,7 +1117,7 @@ mod tests { None ); let reason = - refuse(Path::new("/etc/hosts"), Path::new("/"), Some(home)); + refuse(Path::new("/etc/hosts"), Path::new("/"), Some(home), &[]); assert!(reason.is_some_and(|reason| reason.contains("/etc"))); } } From 46f0c8fc2f0a1572e95dff621fb09d0d435ccfbe Mon Sep 17 00:00:00 2001 From: Mark Silverstein Date: Fri, 25 Sep 2026 13:57:48 +0800 Subject: [PATCH 03/17] fix: keep a checkout's config from running programs during git status A repository's .git/config can set core.fsmonitor to a program, which git runs on every status; safe.directory does not cover repos the user owns. Selecting a directory now overrides fsmonitor, hooksPath and pager on the command line, which outranks repository config. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/disktree-app/src/git.rs | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index 5c52eb6..d76a7d4 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -76,6 +76,18 @@ fn run(path: &Path, args: &[&str]) -> Option { let output = Command::new("git") .arg("-C") .arg(path) + // A checkout's own config can name programs for git to run: an + // fsmonitor on every `status`, hooks, a pager. Selecting a directory + // in a disk viewer must not execute anything it contains, and a + // command-line `-c` outranks the repository's config. + .args([ + "-c", + "core.fsmonitor=false", + "-c", + "core.hooksPath=/dev/null", + "-c", + "core.pager=cat", + ]) .args(args) // Never prompt, never page, never take a lock for the index refresh. .env("GIT_TERMINAL_PROMPT", "0") @@ -134,4 +146,36 @@ mod tests { assert_eq!(state.changed, 1, "one untracked file"); assert_eq!(state.stashes, 0); } + + #[cfg(unix)] + #[test] + fn a_checkout_cannot_make_git_run_its_programs() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let hook = dir.path().join("hook.sh"); + std::fs::write( + &hook, + format!("#!/bin/sh\ntouch '{}'\n", marker.display()), + ) + .expect("write hook"); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)) + .expect("chmod"); + let git = |args: &[&str]| { + Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(args) + .output() + .is_ok_and(|output| output.status.success()) + }; + if !git(&["init", "-q"]) { + return; // no git on this machine + } + let hook = hook.to_string_lossy(); + assert!(git(&["config", "core.fsmonitor", &hook])); + assert!(state(dir.path()).is_some()); + assert!(!marker.exists(), "the checkout's fsmonitor ran"); + } } From db843bb4f8cb9f3b93dbb63af2d131620a079ada Mon Sep 17 00:00:00 2001 From: Mathias Bogaert Date: Fri, 25 Sep 2026 08:18:29 +0000 Subject: [PATCH 04/17] Back and forward through the directories visited `<` and `>` sit to the left of the Size / Files / Age switch and retrace where you have been, as in a browser: going somewhere new drops what was ahead. Alt-arrows and the mouse's side buttons do the same. Each is disabled when there is nowhere to go. Hovering one shows the card the mosaic shows for a tile, for the directory it leads to, hung below the button rather than over it. History is kept as absolute paths, not crumbs, so a re-scan or a widening cannot point it at other directories; entries a new tree no longer holds are dropped when it lands. A step animates like the move it retraces: growing into a directory below, shrinking out to one above. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- crates/disktree-app/src/state.rs | 175 +++++++++++++++++++++++++++++-- crates/disktree-app/src/tests.rs | 83 +++++++++++++++ crates/disktree-app/src/views.rs | 174 +++++++++++++++++++++++++----- 4 files changed, 403 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index e1c1580..7ef2df9 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,9 @@ Scroll to magnify toward the pointer. The wheel magnifies until the directory under the pointer fills the view, and the next notch goes into it — one continuous motion, with the directory's contents growing into place. Scroll the other way to come back out. Enter goes into the selected directory at any -depth, and Backspace or Escape goes up one level. `+` and `-` magnify without +depth, and Backspace or Escape goes up one level. `<` and `>`, beside the +Size / Files / Age switch, go back and forward through the directories visited, +as do `alt ←` `alt →` and the mouse's side buttons. `+` and `-` magnify without going in; `0` resets. ### Removing @@ -124,6 +126,7 @@ and shows how much free space was actually gained. | `ctrl`-click | mark without moving the selection | | `enter` | open that directory, at any depth | | `⌫` / `esc` | go up one directory | +| `alt ←` `alt →` | back and forward through where you have been | | `←` `↑` `↓` `→` | move between tiles at this level | | `tab` | next largest sibling | | scroll | zoom toward a directory, then go into it | diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 6a2212a..5c9c163 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -26,8 +26,8 @@ use disktree_core::treemap::{ }; use gpui_kit::{ Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, - MouseMoveEvent, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent, Size, - Window, px, size, + MouseMoveEvent, NavigationDirection, Pixels, Point, Render, ScrollDelta, + ScrollWheelEvent, Size, Window, px, size, }; use gpui_omarchy::Status; use rustc_hash::{FxHashMap, FxHashSet}; @@ -297,6 +297,20 @@ struct LayoutKey { filter: u64, } +/// Directories left behind and come back from, for `<` and `>`. +/// +/// Kept as absolute paths, not crumbs: a re-scan or a widening renumbers the +/// tree, and crumbs would then silently point at other directories. +#[derive(Clone, Debug, Default)] +pub struct History { + pub back: Vec, + pub forward: Vec, +} + +/// How many directories back is remembered. Far more than anyone clicks +/// through, and small enough that pruning after a scan costs nothing. +const HISTORY_DEPTH: usize = 100; + /// Result of the removal run, summarised for the final screen. #[derive(Clone, Debug, Default)] pub struct RunSummary { @@ -323,6 +337,10 @@ pub struct Disktree { pub crumbs: Vec, pub selected: Option>, pub hovered: Option>, + pub history: History, + /// The history button under the pointer, `true` for `<`: its card is + /// drawn below it for as long as it is. + pub history_hover: Option, /// The pointer moved more recently than the keyboard navigated. Then the /// tile under the pointer is what Space, X and Enter act on; after an /// arrow or Tab it is the keyboard selection again. @@ -430,6 +448,8 @@ impl Disktree { crumbs: Vec::new(), selected: None, hovered: None, + history: History::default(), + history_hover: None, pointer_active: false, view: View::default(), transition: None, @@ -551,6 +571,7 @@ impl Disktree { self.scan_started = Some(Instant::now()); self.scan_elapsed = None; self.scan_root.clone_from(&above); + self.remember(); let known = Known { path: self.root_path.clone(), tree, @@ -632,6 +653,10 @@ impl Disktree { let epoch = self.scan_epoch; self.progress = ScanSnapshot::default(); self.scan_error = None; + // A new scan starts at its root; where it was is one `<` away. + if !self.crumbs.is_empty() { + self.remember(); + } self.tree = None; self.crumbs.clear(); self.selected = None; @@ -718,6 +743,7 @@ impl Disktree { }); } self.keep_selection_valid(); + self.prune_history(); self.select_largest(cx); } Err(error) => self.scan_error = Some(error.to_string()), @@ -988,6 +1014,7 @@ impl Disktree { if !node.is_dir() || node.children.is_empty() { return; } + self.remember(); self.selected = Some(target.clone()); self.crumbs = target; self.forget_hover(); @@ -1040,18 +1067,27 @@ impl Disktree { /// Ascend to the parent directory, keeping the directory we came from in /// view so the motion reads as zooming out. pub fn ascend(&mut self, cx: &mut Context<'_, Self>) { - let Some(parent_crumbs) = self.parent_crumbs() else { - return; - }; + if let Some(parent_crumbs) = self.parent_crumbs() { + self.ascend_to(parent_crumbs, cx); + } + } + + /// Make `ancestor`, a directory above the current root, the root. + /// + /// The directory we leave shrinks back into its tile when that tile is + /// drawn at the new level; from further up it is too small to track, and + /// the new level simply lands. + fn ascend_to(&mut self, ancestor: Vec, cx: &mut Context<'_, Self>) { + self.remember(); // The region we are looking at now, and where it sits in the layout // we are going back to. let area = self.treemap_size.get(); let child_crumbs = self.crumbs.clone(); let src = self.view.visible_base(area); - self.crumbs.clone_from(&parent_crumbs); + self.crumbs.clone_from(&ancestor); self.forget_hover(); self.cache = None; - self.selected = Some(parent_crumbs); + self.selected = Some(ancestor); self.view = View::IDENTITY; self.transition = self .tile_body(&child_crumbs) @@ -1075,6 +1111,10 @@ impl Disktree { /// it lands immediately, the way selecting a folder does. pub fn go_to(&mut self, crumbs: Vec, cx: &mut Context<'_, Self>) { self.crumb_menu = None; + // A reveal in the directory on screen goes nowhere. + if crumbs != self.crumbs { + self.remember(); + } self.crumbs.clone_from(&crumbs); self.selected = Some(crumbs); self.forget_hover(); @@ -1084,6 +1124,117 @@ impl Disktree { cx.notify(); } + /// Note the directory on screen as one to come back to, before leaving + /// it. A new departure ends whatever was ahead, as in a browser. + fn remember(&mut self) { + if self.tree.is_none() { + return; + } + let here = self.current_path(); + if self.history.back.last() != Some(&here) { + self.history.back.push(here); + } + if self.history.back.len() > HISTORY_DEPTH { + self.history.back.remove(0); + } + self.history.forward.clear(); + } + + /// Drop what a new tree no longer holds: a removed directory, or one + /// outside a new root. What is left always resolves, so `<` and `>` are + /// enabled exactly when they would go somewhere. + fn prune_history(&mut self) { + let mut history = std::mem::take(&mut self.history); + history + .back + .retain(|path| self.crumbs_for_path(path).is_some()); + history + .forward + .retain(|path| self.crumbs_for_path(path).is_some()); + self.history = history; + } + + /// Whether `<` would go anywhere: what drives its button's disabled state. + pub fn can_go_back(&self) -> bool { + self.history_target(true).is_some() + } + + /// Whether `>` would go anywhere. + pub fn can_go_forward(&self) -> bool { + self.history_target(false).is_some() + } + + /// `<`: the directory on screen before this one. + pub fn go_back(&mut self, cx: &mut Context<'_, Self>) { + self.step_history(true, cx); + } + + /// `>`: undo a `<`. + pub fn go_forward(&mut self, cx: &mut Context<'_, Self>) { + self.step_history(false, cx); + } + + /// Where `<` (or `>`) would go, and its place on that stack: the newest + /// entry that is somewhere else. An entry can be where we already are, + /// after a widening that was superseded; it is skipped rather than spend + /// a click on nothing. Every other entry resolves, being pruned whenever + /// a tree lands. + pub fn history_target(&self, back: bool) -> Option<(usize, Vec)> { + self.tree.as_ref()?; + let stack = if back { + &self.history.back + } else { + &self.history.forward + }; + stack.iter().enumerate().rev().find_map(|(at, path)| { + self.crumbs_for_path(path) + .filter(|crumbs| *crumbs != self.crumbs) + .map(|crumbs| (at, crumbs)) + }) + } + + fn step_history(&mut self, back: bool, cx: &mut Context<'_, Self>) { + let Some((at, target)) = self.history_target(back) else { + return; + }; + let here = self.current_path(); + let mut history = std::mem::take(&mut self.history); + let (from, to) = if back { + (&mut history.back, &mut history.forward) + } else { + (&mut history.forward, &mut history.back) + }; + from.truncate(at); + to.push(here); + // The move is an ordinary one, animation and all; it records itself + // like any other, so the stacks are put back afterwards. + self.travel(target, cx); + self.history = history; + cx.notify(); + } + + /// Go to `target` with the motion that fits: grow into a directory + /// below, shrink back out to one above, or land on one beside. + fn travel(&mut self, target: Vec, cx: &mut Context<'_, Self>) { + let enterable = self + .node_at(&target) + .is_some_and(|node| node.is_dir() && !node.children.is_empty()); + if target.len() > self.crumbs.len() + && target.starts_with(&self.crumbs) + && enterable + { + let from = + self.tile_body(&target).map(|rect| self.view.project(rect)); + self.enter(target, from, cx); + } else if target.len() < self.crumbs.len() + && self.crumbs.starts_with(&target) + { + self.ascend_to(target, cx); + } else { + self.go_to(target, cx); + } + } + /// Show `crumbs` in its directory, selected: what a "worth a look" row /// or a found name does. pub fn reveal(&mut self, crumbs: Vec, cx: &mut Context<'_, Self>) { @@ -1962,6 +2113,7 @@ impl Disktree { let key = event.keystroke.key.as_str(); let control = event.keystroke.modifiers.control; let shift = event.keystroke.modifiers.shift; + let alt = event.keystroke.modifiers.alt; // The alert dialog owns Enter and Escape while it is open; a key that // bubbles up to here must not also act on the screen behind it. @@ -2012,6 +2164,9 @@ impl Disktree { } match self.screen { + // Alt-arrows are history in every browser and file manager. + Screen::Explore if alt && key == "left" => self.go_back(cx), + Screen::Explore if alt && key == "right" => self.go_forward(cx), Screen::Explore => self.on_explore_key(key, control, shift, cx), Screen::Review => self.on_review_key(key, cx), Screen::Running => { @@ -2271,6 +2426,12 @@ impl Disktree { self.toggle_mark(&crumbs, cx); } } + MouseButton::Navigate(NavigationDirection::Back) => { + self.go_back(cx); + } + MouseButton::Navigate(NavigationDirection::Forward) => { + self.go_forward(cx); + } _ => {} } } diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 946b06a..ce7052f 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -1165,3 +1165,86 @@ fn marking_a_directory_marks_everything_inside_it(cx: &mut TestAppContext) { update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); assert!(read(&view, cx, |app| app.marks.is_empty())); } + +/// `<` and `>` retrace the directories visited, are disabled when there is +/// nowhere to go, and a fresh move ends what was ahead. +#[gpui_kit::test] +fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) { + use gpui_kit::Modifiers; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + let can = |view: &Entity, cx: &Window| { + read(view, cx, |app| (app.can_go_back(), app.can_go_forward())) + }; + assert_eq!(can(&view, cx), (false, false), "nowhere to go yet"); + + let (junk, deeper, keep) = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + let deeper = child_crumbs(app, &junk, "deeper"); + let keep = child_crumbs(app, &[], "keep"); + app.select(Some(deeper.clone()), cx); + app.descend(cx); + (junk, deeper, keep) + }); + draw(cx); + assert_eq!(can(&view, cx), (true, false)); + + // Hovering `<` shows the card for where it goes, as hovering a tile + // does: here, the scanned root. It hangs below the button, never on it. + let back = cx + .debug_bounds("history-back") + .expect("the button is drawn"); + cx.simulate_mouse_move(back.center(), None, Modifiers::none()); + draw(cx); + let card = cx.debug_bounds("history-tip").expect("the card is shown"); + assert!(card.top() >= back.bottom(), "{card:?} covers {back:?}"); + assert_eq!( + read(&view, cx, |app| app.history_target(true)), + Some((0, Vec::new())) + ); + + let click = |cx: &mut Window, selector: &'static str| { + let bounds = cx.debug_bounds(selector).expect("the button is drawn"); + cx.simulate_click(bounds.center(), Modifiers::none()); + draw(cx); + }; + click(cx, "history-back"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); + assert_eq!(can(&view, cx), (false, true), "back at the start"); + + click(cx, "history-forward"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + assert_eq!(can(&view, cx), (true, false)); + + // Up a level is a move of its own, and the keys retrace it too. + press(cx, "backspace"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); + press(cx, "alt-left"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + press(cx, "alt-left"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); + press(cx, "alt-right"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + + // Going somewhere new from the middle of the history drops what was + // ahead of it, as in a browser. + press(cx, "alt-left"); + update(&view, cx, |app, cx| app.go_to(keep, cx)); + draw(cx); + assert_eq!(can(&view, cx), (true, false), "the forward trail is gone"); + press(cx, "alt-left"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); +} diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index ca7b193..2f785a8 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -688,6 +688,84 @@ fn view_settings( }; let theme = cx.omarchy().clone(); + // Back and forward through the directories visited, beside the choices + // that change how the one on screen is drawn. + let travel = |id: &'static str, + label: &'static str, + enabled: bool, + back: bool, + go: fn(&mut Disktree, &mut Context<'_, Disktree>), + cx: &mut Context<'_, Disktree>| { + let shown = app.history_hover == Some(back); + div() + .id(ElementId::Name(format!("{id}-hover").into())) + .debug_selector(move || id.into()) + .relative() + .on_hover(cx.listener(move |this, hovered: &bool, _, cx| { + // Leaving one button can be reported after entering the + // other; only the button that owns the card takes it away. + if *hovered { + this.history_hover = Some(back); + } else if this.history_hover == Some(back) { + this.history_hover = None; + } + cx.notify(); + })) + .child( + button(id, label, ButtonVariant::Secondary, cx) + .tab_stop(false) + .disabled(!enabled) + // Borderless: glyphs on the bar, not controls in a + // frame. Hover keeps the fill but not the outline it + // would add. + .hover(|style| { + style + .bg(theme.hover_fill()) + .border_color(theme.foreground.opacity(0.)) + }) + .on_click(cx.listener(move |this, _, window, cx| { + go(this, cx); + window.focus(&this.focus, cx); + })), + ) + .when(shown, |this| { + // Anchored to a holder pinned at the button's bottom edge, so + // the card hangs below it and never covers it; deferred so it + // paints over the mosaic. + this.child( + div().absolute().top_full().left_0().child( + deferred( + anchored() + .snap_to_window_with_margin(px(8.)) + .offset(gpui_kit::point(px(0.), px(4.))) + .child(history_card(app, back, cx)), + ) + .with_priority(2), + ), + ) + }) + }; + let history = div() + .flex() + .flex_row() + .items_center() + .child(travel( + "history-back", + "<", + app.can_go_back(), + true, + Disktree::go_back, + cx, + )) + .child(travel( + "history-forward", + ">", + app.can_go_forward(), + false, + Disktree::go_forward, + cx, + )); + let depth = app.layout_options.max_depth; let stepper = |id: &'static str, label: &'static str, @@ -727,6 +805,7 @@ fn view_settings( .items_center() .gap(space::SM) .flex_shrink_0() + .child(history) .child(mode) .child(hidden) .child(apparent) @@ -2592,37 +2671,80 @@ pub fn cursor_tooltip( anchor_y + gap }; - // The same surface treatment as Omarchy's tooltip, square and bordered, - // so an anchored surface of this app does not drift from the system's. - // Translucent so the mosaic stays visible underneath it. - let theme = cx.omarchy(); Some( - div() + card_surface(cx) .absolute() .left(px(x)) .top(px(y)) - .w(size::TOOLTIP) - .flex() - .flex_col() - .gap(space::XS) - .px(space::SM) - .py(space::SM) - .border_1() - .border_color(theme.control_border()) - .bg(theme.background.opacity(0.93)) - .text_color(theme.foreground) - .font_family(theme.font.clone()) - .text_size(text::CAPTION) .child(content), ) } +/// The same surface treatment as Omarchy's tooltip, square and bordered, +/// so an anchored surface of this app does not drift from the system's. +/// Translucent so the mosaic stays visible underneath it. +fn card_surface(cx: &gpui_kit::App) -> Div { + let theme = cx.omarchy(); + div() + .w(size::TOOLTIP) + .flex() + .flex_col() + .gap(space::XS) + .px(space::SM) + .py(space::SM) + .border_1() + .border_color(theme.control_border()) + .bg(theme.background.opacity(0.93)) + .text_color(theme.foreground) + .font_family(theme.font.clone()) + .text_size(text::CAPTION) +} + +/// The card under `<` or `>` while it is hovered: what hovering a tile +/// shows, for the directory the button goes to, so where it leads is known +/// before going. Drawn by the app rather than as a tooltip, which GPUI puts +/// at the pointer, over the button itself. +fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div { + let (label, keys) = if back { + ("Back", "alt \u{2190} back") + } else { + ("Forward", "alt \u{2192} forward") + }; + let card = app + .history_target(back) + .and_then(|(_, crumbs)| node_card(app, &crumbs, keys, cx)); + card_surface(cx) + .debug_selector(|| "history-tip".into()) + .map(|surface| match card { + Some(card) => surface.child(card), + // Nowhere to go: the button is disabled; say what it is for. + None => surface.child(format!("{label} \u{00b7} {keys}")), + }) +} + /// The tooltip content for the hovered tile: everything the tile cannot show. pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ + let crumbs = app.hovered.as_deref()?; + let is_dir = app.node_at(crumbs)?.is_dir(); + let keys = if is_dir { + "space mark · enter open" + } else { + "space mark" + }; + node_card(app, crumbs, keys, cx) +} + +/// What is known about the node at `crumbs`, as a card: name, path, size and +/// share, counts, and badges, with `keys` for what can be done from there. +fn node_card( + app: &Disktree, + crumbs: &[usize], + keys: &str, + cx: &gpui_kit::App, +) -> Option
{ let theme = cx.omarchy(); - let crumbs = app.hovered.clone()?; - let node = app.node_at(&crumbs)?; - let path = app.path_at(&crumbs); + let node = app.node_at(crumbs)?; + let path = app.path_at(crumbs); let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec(); let parent_value = app.node_at(&parent).map_or(0, |node| node.bytes); let marked = path.as_deref().is_some_and(|path| app.marks.contains(path)); @@ -2725,11 +2847,7 @@ pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ div() .text_size(text::CAPTION) .text_color(theme.secondary.opacity(0.7)) - .child(if node.is_dir() { - "space mark · enter open" - } else { - "space mark" - }), + .child(keys.to_string()), ); Some(tip) } @@ -2738,11 +2856,15 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { let theme = cx.omarchy(); // Sentence case, and the tile a key acts on is always the one under the // pointer if the pointer moved last, else the keyboard selection. - let rows: [(&str, &str); 24] = [ + let rows: [(&str, &str); 25] = [ ("space / x", "Mark or unmark the tile you point at"), ("ctrl-click", "Mark without moving the selection"), ("enter", "Open that directory, at any depth"), ("\u{232b} / esc", "Go up one directory"), + ( + "alt \u{2190} / \u{2192}", + "Back or forward through where you have been", + ), ( "\u{2190} \u{2191} \u{2193} \u{2192}", "Move between tiles at this level", From cbdfe1c3320efa2aa89e08e8c8a99b2ac422c8b1 Mon Sep 17 00:00:00 2001 From: Sebastian Sieber Date: Fri, 25 Sep 2026 17:29:55 +0800 Subject: [PATCH 05/17] macOS support: native Trash, APFS-aware scans, a signed app bundle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit disktree built and drew on macOS already, through GPUI's Metal backend, but the Linux plumbing underneath did not carry over. This makes it work well there, without unsafe code, and tightens removal safety for every platform on the way. Trash and removal - On macOS always the system Trash, through NSFileManager (the trash crate): the same move as Finder's, into the item's own disk's Trash. gio/trash-put/XDG would put files in ~/.local/share/Trash, which Finder never shows. - Refuse a directory holding the home directory (/Users is on the same volume as / on macOS) or a system tree (/opt holds /opt/homebrew); add /System, /Library, /private, /opt/homebrew, /cores, /Network. - Refuse a directory with a mount inside it; on macOS the mount list comes from /sbin/mount, read on a background thread. - Permanent deletion walks the tree itself and stops at a mount boundary, like rm -rf --one-file-system (the walker is from #10). - Guards see through /System/Volumes/Data spellings and, on macOS, case. Scanning - Skip /System/Volumes/Data when scanning /: it is /Users, /Applications and the rest again under firmlinks, so / was counted twice. - Whole disk (g, --disk) works: the disk root and device come from statfs. - Never list cloud-only (dataless) iCloud/File Provider folders, which would download them. - Keep a file's identity only when it has more than one name. App - Explain unreadable items when Full Disk Access is missing, with a button to the privacy settings. - A menu bar: Open Folder… (⌘O), Show in Finder (o, ⌘⇧R), Rescan (⌘R), Hide, Quit; closing the window quits; other ⌘ chords are not read as plain letters; help shows ⌘. - Follow the system light/dark appearance when no Omarchy theme exists. - Worth a look knows Xcode DerivedData, DeviceSupport and ~/Library/Logs. - git: skipped without the developer tools (its stub opens a dialog), and never runs a checkout's programs: fsmonitor, hooks and pager off, and no status for a checkout that defines its own filter drivers. Packaging - cargo xtask bundle builds disktree.app and a zip: Info.plist (bundle id io.github.tobi.disktree, macOS 11+), an icon drawn from an SVG on the macOS grid, ad-hoc or Developer ID signing, and --notarize. - make install on macOS puts the app in ~/Applications and links ~/.local/bin/disktree to it. - CI lints, tests and bundles on macOS; the release adds an arm64 macOS zip, signed and notarized when the repository has the Apple secrets. --- .github/workflows/ci.yml | 27 + .github/workflows/release.yml | 89 +++ AGENTS.md | 6 + Cargo.lock | 24 + Makefile | 37 +- README.md | 79 ++- crates/disktree-app/src/app_menu.rs | 97 ++++ crates/disktree-app/src/appearance.rs | 43 ++ crates/disktree-app/src/git.rs | 214 ++++++- crates/disktree-app/src/main.rs | 20 +- crates/disktree-app/src/state.rs | 112 +++- crates/disktree-app/src/tests.rs | 32 ++ crates/disktree-app/src/views.rs | 114 +++- crates/disktree-core/Cargo.toml | 6 + crates/disktree-core/src/access.rs | 49 ++ crates/disktree-core/src/classify.rs | 52 +- crates/disktree-core/src/lib.rs | 1 + crates/disktree-core/src/removal.rs | 772 ++++++++++++++++++++++++-- crates/disktree-core/src/scan.rs | 104 +++- crates/disktree-core/src/space.rs | 155 ++++++ packaging/macos/AppIcon.svg | 24 + packaging/macos/Info.plist.in | 48 ++ xtask/Cargo.toml | 2 +- xtask/src/bundle.rs | 339 +++++++++++ xtask/src/main.rs | 9 +- 25 files changed, 2336 insertions(+), 119 deletions(-) create mode 100644 crates/disktree-app/src/app_menu.rs create mode 100644 crates/disktree-app/src/appearance.rs create mode 100644 crates/disktree-core/src/access.rs create mode 100644 packaging/macos/AppIcon.svg create mode 100644 packaging/macos/Info.plist.in create mode 100644 xtask/src/bundle.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d14d6e..f35f42a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,3 +43,30 @@ jobs: - name: Test run: cargo xtask test + + check-macos: + name: Lint and test (macOS) + # Apple silicon. No system libraries to install, and no Metal toolchain + # either: gpui-kit builds GPUI with runtime shader compilation, so the + # shaders compile when the app starts, not here. + runs-on: macos-15 + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + components: clippy, rustfmt + + - uses: Swatinem/rust-cache@v2 + + - name: Lint + run: cargo xtask lint + + - name: Test + run: cargo xtask test + + # The app bundle, signed ad hoc: catches a broken Info.plist, icon or + # signature before a release does. + - name: Bundle + run: cargo xtask bundle diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed382d8..6de163f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -86,3 +86,92 @@ jobs: gh release create "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" \ --title "disktree ${TAG#v}" --generate-notes fi + + release-macos: + name: Build and publish (macOS) + # After the Linux job, which creates the release: two jobs racing to + # create it would leave one failing. + needs: release + runs-on: macos-15 + env: + # Signing and notarizing happen only when the repository has these + # secrets; without them the app is signed ad hoc, and a downloaded + # copy needs "Open Anyway" in System Settings once. + # MACOS_CERTIFICATE base64 of the Developer ID .p12 + # MACOS_CERTIFICATE_PASSWORD its password + # MACOS_SIGN_IDENTITY "Developer ID Application: Name (TEAMID)" + # NOTARY_KEY_P8 base64 of an App Store Connect API key + # NOTARY_KEY_ID, NOTARY_ISSUER that key's ID and issuer + MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} + MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} + MACOS_SIGN_IDENTITY: ${{ secrets.MACOS_SIGN_IDENTITY }} + NOTARY_KEY_P8: ${{ secrets.NOTARY_KEY_P8 }} + NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }} + NOTARY_ISSUER: ${{ secrets.NOTARY_ISSUER }} + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ inputs.tag || github.ref }} + + - name: Version + id: version + run: | + tag="${{ inputs.tag || github.ref_name }}" + version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) + if [ "$tag" != "v$version" ]; then + echo "tag $tag does not match Cargo.toml version $version" >&2 + exit 1 + fi + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + + - uses: Swatinem/rust-cache@v2 + + - name: Test + run: cargo xtask test + + # A keychain of its own for the certificate, deleted with the runner. + - name: Signing certificate + if: env.MACOS_CERTIFICATE != '' + run: | + keychain="$RUNNER_TEMP/signing.keychain-db" + password=$(uuidgen) + echo "$MACOS_CERTIFICATE" | base64 --decode > "$RUNNER_TEMP/cert.p12" + security create-keychain -p "$password" "$keychain" + security set-keychain-settings -lut 3600 "$keychain" + security unlock-keychain -p "$password" "$keychain" + security import "$RUNNER_TEMP/cert.p12" -k "$keychain" \ + -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign + security set-key-partition-list -S apple-tool:,apple: \ + -s -k "$password" "$keychain" + security list-keychains -d user -s "$keychain" \ + $(security list-keychains -d user | tr -d '"') + rm "$RUNNER_TEMP/cert.p12" + + - name: Bundle + run: | + args=() + if [ -n "$MACOS_CERTIFICATE" ]; then + args+=(--sign "$MACOS_SIGN_IDENTITY") + if [ -n "$NOTARY_KEY_P8" ]; then + echo "$NOTARY_KEY_P8" | base64 --decode \ + > "$RUNNER_TEMP/AuthKey.p8" + export NOTARY_KEY="$RUNNER_TEMP/AuthKey.p8" + args+=(--notarize) + fi + fi + cargo xtask bundle "${args[@]}" + + - name: Publish + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.version.outputs.tag }} + run: | + zip="target/bundle/disktree-${{ steps.version.outputs.version }}-aarch64-macos.zip" + (cd "$(dirname "$zip")" && shasum -a 256 "$(basename "$zip")" \ + > "$(basename "$zip").sha256") + gh release upload "$TAG" "$zip" "$zip.sha256" --clobber diff --git a/AGENTS.md b/AGENTS.md index 30a5414..873bc1d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ make run # build and run, scanning $HOME make install # ~/.local: binary, desktop entry, icon make install PREFIX=/usr/local # system-wide (needs root) make uninstall +make bundle # macOS: target/bundle/disktree.app and its zip make lint # rustfmt --check, then clippy --all-targets -D warnings make test # core and window-harness tests make ci # lint, then test @@ -30,6 +31,11 @@ prefix and the crate version) and `assets/disktree.svg`. Keep the desktop entry's `Categories` to a single main category plus additional ones, or `desktop-file-validate` complains. +On macOS `make install` installs `target/bundle/disktree.app` into +`~/Applications` instead, built by `cargo xtask bundle` from +`packaging/macos/` (the `Info.plist` template and the icon's SVG). The bundle +identifier there keys every macOS permission grant; do not change it lightly. + `cargo xtask lint` is the gate. It must be green before anything is called done, and it must not fix anything: a red local run is the same signal CI gives. diff --git a/Cargo.lock b/Cargo.lock index 4047a24..0ee5df5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1439,6 +1439,7 @@ dependencies = [ "rustc-hash 2.1.3", "rustix", "tempfile", + "trash", ] [[package]] @@ -7071,6 +7072,23 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "trash" +version = "5.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317" +dependencies = [ + "libc", + "log", + "objc2 0.6.4", + "objc2-foundation 0.3.2", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows 0.62.2", +] + [[package]] name = "triomphe" version = "0.1.16" @@ -7228,6 +7246,12 @@ dependencies = [ "serde", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "usvg" version = "0.45.1" diff --git a/Makefile b/Makefile index 1e86866..b3c8fcc 100644 --- a/Makefile +++ b/Makefile @@ -6,19 +6,27 @@ # # make install # ~/.local/bin/disktree # sudo make install PREFIX=/usr/local # system-wide +# +# On macOS it installs disktree.app into ~/Applications instead (APPS to +# change that), plus a `disktree` command in BINDIR that runs the app's +# binary, so both Spotlight and a terminal find it. PREFIX ?= $(HOME)/.local BINDIR ?= $(PREFIX)/bin APPDIR ?= $(PREFIX)/share/applications ICONDIR ?= $(PREFIX)/share/icons/hicolor/scalable/apps +APPS ?= $(HOME)/Applications +BUNDLE = target/bundle/disktree.app +UNAME := $(shell uname -s) + MANIFEST = Cargo.toml CARGO ?= cargo TARGET = target/release/disktree ICON = assets/disktree.svg DESKTOP = packaging/disktree.desktop.in -.PHONY: help build run install uninstall lint test ci fmt clean +.PHONY: help build run install uninstall bundle lint test ci fmt clean help: @echo "disktree" @@ -26,6 +34,8 @@ help: @echo " make build release build" @echo " make run build and run, scanning $$HOME" @echo " make install install to $(PREFIX): binary, desktop entry, icon" + @echo " (macOS: disktree.app into $(APPS))" + @echo " make bundle macOS: build target/bundle/disktree.app and its zip" @echo " make uninstall remove what install put there" @echo " make lint rustfmt --check and clippy -D warnings" @echo " make test core and window-harness tests" @@ -53,6 +63,27 @@ ci: lint test fmt: $(CARGO) xtask fmt-fix +ifeq ($(UNAME),Darwin) +# Replaced whole rather than copied over: a stale file left inside a signed +# bundle breaks its signature. +install: + $(CARGO) xtask bundle + install -d "$(APPS)" "$(BINDIR)" + rm -rf "$(APPS)/disktree.app" + ditto "$(BUNDLE)" "$(APPS)/disktree.app" + ln -sf "$(APPS)/disktree.app/Contents/MacOS/disktree" "$(BINDIR)/disktree" + @echo + @echo "installed:" + @echo " $(APPS)/disktree.app" + @echo " $(BINDIR)/disktree -> the app's binary" + @case ":$$PATH:" in *":$(BINDIR):"*) ;; *) \ + echo; echo "note: $(BINDIR) is not on PATH in this shell";; esac + +uninstall: + rm -rf "$(APPS)/disktree.app" + @if [ -L "$(BINDIR)/disktree" ]; then rm -f "$(BINDIR)/disktree"; fi + @echo "removed" +else install: build install -d $(BINDIR) $(APPDIR) $(ICONDIR) install -m755 $(TARGET) $(BINDIR)/disktree @@ -81,6 +112,10 @@ uninstall: update-desktop-database $(APPDIR) 2>/dev/null || true; \ fi @echo "removed" +endif + +bundle: + $(CARGO) xtask bundle clean: $(CARGO) clean diff --git a/README.md b/README.md index e1c1580..3990695 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,49 @@ removes exactly what was installed. You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI can drive (Vulkan). +### macOS + +Download `disktree-*-aarch64-macos.zip` from the +[latest release](https://github.com/tobi/disktree/releases/latest), unzip it, +and drag `disktree.app` into Applications. Apple silicon and macOS 11 or +newer. A release that was not signed and notarized is stopped by Gatekeeper +the first time: open it once, then choose **Open Anyway** in System Settings +› Privacy & Security. + +Or build it, with Rust 1.97 or newer and Xcode or its Command Line Tools: + +```sh +make install # ~/Applications/disktree.app, and ~/.local/bin/disktree +make uninstall +``` + +To see everything, give disktree **Full Disk Access** in System Settings › +Privacy & Security (the panel offers a button when it is missing), then +reopen it. Without it macOS hides Mail, Messages, Safari, other apps' data +and the Trash, and disktree counts them as unreadable. Started from a +terminal, it is the terminal that needs the access. macOS also asks once +each for Desktop, Documents and Downloads. + +What is different from Linux: + +- **Free space** is what `df` reports. Finder's figure is larger: it counts + purgeable space (caches and local snapshots macOS will clear on its own). +- **Cloned files** (copies APFS shares blocks between, as Finder's Duplicate + makes) are each counted in full, so a total can exceed what deleting them + frees. +- **Time Machine's local snapshots** are not files and do not appear; they + are part of the gap between the scan and the disk's used space. +- **Cloud-only folders** (iCloud Drive, Dropbox and the like, evicted to the + server) are not opened, so a scan never downloads them. + +To sign and notarize a build for others, with a Developer ID certificate in +the keychain and credentials saved by `xcrun notarytool store-credentials`: + +```sh +NOTARY_PROFILE= cargo xtask bundle \ + --sign "Developer ID Application: Name (TEAMID)" --notarize +``` + ## Use ```sh @@ -107,9 +150,11 @@ going in; `0` resets. `c` (or **Review…**) opens the list of everything marked. Unmark anything there, then choose: -- **Move to trash** — the default when a trash is available (`trash-put` from - trash-cli, then `gio trash`, then a built-in XDG trash). Recoverable until - the trash is emptied, so it commits directly. +- **Move to trash** — the default when a trash is available. On macOS that is + the system Trash, the same move as Finder's (on another disk, that disk's + own Trash; network shares often have none). Elsewhere it is `trash-put` + from trash-cli, then `gio trash`, then a built-in XDG trash. Recoverable + until the trash is emptied, so it commits directly. - **Delete permanently** — `rm -rf` semantics. It always asks first, in a dialog that names what goes and how much comes back. @@ -121,7 +166,7 @@ and shows how much free space was actually gained. | key | does | | --- | --- | | `space` / `x` | mark or unmark the tile you point at | -| `ctrl`-click | mark without moving the selection | +| `ctrl`-click (`⌘`-click on macOS) | mark without moving the selection | | `enter` | open that directory, at any depth | | `⌫` / `esc` | go up one directory | | `←` `↑` `↓` `→` | move between tiles at this level | @@ -130,7 +175,7 @@ and shows how much free space was actually gained. | `shift`-scroll | pan the magnified view | | `[` `]` | draw fewer or more levels at once | | `-` `=` `0` | magnify, shrink, reset the view | -| `ctrl =` `ctrl -` `ctrl 0` | interface zoom | +| `ctrl =` `ctrl -` `ctrl 0` (`⌘` on macOS) | interface zoom | | `/` | filter by name: only matches keep their colour; `enter` shows only them, `esc` clears | | `c` | review the marked list | | `t` | rank by size or by file count | @@ -139,9 +184,14 @@ and shows how much free space was actually gained. | `r` | scan again | | `g` | the whole disk | | `p` | show or hide the selection line | +| `o` | show it in Finder or the file manager | | `?` | every key | | `q` | quit | +On macOS the menu bar also has ⌘O to open a folder, ⌘⇧R to show the +selection in Finder, ⌘R to rescan, and ⌘Q, ⌘H and ⌘W (closing the window +quits); other ⌘ chords are left to the system. + On the review screen: `m` trash, `p` permanent, `!` unmark all, `enter` commits, `esc` goes back. @@ -164,7 +214,9 @@ and removes duplicate hardlinks. Click `/` (or any directory above the scanned root) in the trail, press `g`, run `disktree --disk`, or use the launcher's *Scan the whole disk* action. `g` and `--disk` scan the disk your home directory lives on — `/` -on Omarchy. +on Omarchy and on macOS. On macOS the Data volume's second mount, +`/System/Volumes/Data`, is skipped: it is `/Users`, `/Applications` and the +rest again under other names. Widening is memoized: the tree already measured is handed to the wider walk and reused where it is reached, so going from `~` to `/` reads only what is @@ -191,13 +243,22 @@ tested: - only paths under the scanned root can be removed; - the filesystem root, the scanned root and your home directory are refused; -- a mount point is refused, since removing it would reach into another - filesystem; +- a mount point is refused, and so is anything with a mount point inside it, + since removing it would reach into another filesystem; permanent deletion + also stops at a mount boundary rather than descending into one (a btrfs + subvolume that is not mounted goes with its directory, as the scan shows + it); +- a directory holding your home directory or a system tree is refused (on + macOS `/Users` is on the same volume as `/`, and `/opt` holds + `/opt/homebrew`); - system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, …) are refused even where permissions would allow it: packages own them, and pacman, paccache or `journalctl --vacuum` are the tools; - a symlink is unlinked, never followed; -- nothing is passed through a shell — a file called `-rf` is just a file. +- nothing is passed through a shell — a file called `-rf` is just a file; +- selecting a checkout never runs a program it names: git is asked with its + fsmonitor, hooks and pager off, and a checkout that defines its own filter + drivers is not asked for its status at all ("changes unknown"). ## On Hyprland diff --git a/crates/disktree-app/src/app_menu.rs b/crates/disktree-app/src/app_menu.rs new file mode 100644 index 0000000..382844d --- /dev/null +++ b/crates/disktree-app/src/app_menu.rs @@ -0,0 +1,97 @@ +//! The menu bar and the application-wide shortcuts. +//! +//! GPUI adds neither on its own. On macOS an app without them has an empty +//! menu bar and no ⌘Q, so this is where disktree becomes a Mac app; on +//! Linux the desktop owns quitting and there is no menu bar to fill, so only +//! "closing the window quits" applies there. + +use gpui_kit::{App, KeyBinding, Menu, MenuItem, SystemMenuType}; + +pub use menu_actions::*; + +#[allow( + clippy::derive_partial_eq_without_eq, + reason = "GPUI's actions! macro writes the derives, not us" +)] +mod menu_actions { + use gpui_kit::actions; + + actions!( + disktree, + [ + /// Quit the application. + Quit, + /// Hide the application's windows. + Hide, + /// Hide every other application. + HideOthers, + /// Show every application again. + ShowAll, + /// Close the focused window, which quits: there is only one. + CloseWindow, + /// Scan the current root again. + Rescan, + /// Choose a directory to scan. + OpenFolder, + /// Reveal the tile a key acts on in Finder. + ShowInFinder, + ] + ); +} + +/// Install the menus, the shortcuts and the quit-on-close rule. +pub fn install(cx: &mut App) { + // A single-window utility has nothing left to show once its window is + // gone; staying alive would leave a Dock icon with no window behind it. + cx.on_window_closed(|cx, _| { + if cx.windows().is_empty() { + cx.quit(); + } + }) + .detach(); + + if !cfg!(target_os = "macos") { + return; + } + cx.on_action(|_: &Quit, cx| cx.quit()); + cx.on_action(|_: &Hide, cx| cx.hide()); + cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps()); + cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps()); + cx.on_action(|_: &CloseWindow, cx| { + if let Some(window) = cx.active_window() { + let _ = window.update(cx, |_, window, _| window.remove_window()); + } + }); + // `Rescan`, `OpenFolder` and `ShowInFinder` are handled by the window, + // which owns the scan and the selection; see `views::root`. + cx.bind_keys([ + KeyBinding::new("cmd-q", Quit, None), + KeyBinding::new("cmd-h", Hide, None), + KeyBinding::new("alt-cmd-h", HideOthers, None), + KeyBinding::new("cmd-w", CloseWindow, None), + KeyBinding::new("cmd-r", Rescan, None), + KeyBinding::new("cmd-o", OpenFolder, None), + // ⌘R is taken by Rescan, as in a browser; Xcode uses ⌘⇧R-like + // chords for its reveals, and `o` does the same without a modifier. + KeyBinding::new("cmd-shift-r", ShowInFinder, None), + ]); + cx.set_menus([ + Menu::new("disktree").items([ + MenuItem::os_submenu("Services", SystemMenuType::Services), + MenuItem::separator(), + MenuItem::action("Hide disktree", Hide), + MenuItem::action("Hide Others", HideOthers), + MenuItem::action("Show All", ShowAll), + MenuItem::separator(), + MenuItem::action("Quit disktree", Quit), + ]), + Menu::new("File").items([ + MenuItem::action("Open Folder\u{2026}", OpenFolder), + MenuItem::action("Show in Finder", ShowInFinder), + MenuItem::separator(), + MenuItem::action("Rescan", Rescan), + MenuItem::separator(), + MenuItem::action("Close Window", CloseWindow), + ]), + ]); +} diff --git a/crates/disktree-app/src/appearance.rs b/crates/disktree-app/src/appearance.rs new file mode 100644 index 0000000..caa1eb6 --- /dev/null +++ b/crates/disktree-app/src/appearance.rs @@ -0,0 +1,43 @@ +//! Light or dark when there is no Omarchy theme to follow. +//! +//! On Omarchy, gpui-omarchy follows the desktop's theme files. A Mac has none, +//! and gpui-omarchy would then stay on its dark default whatever the system +//! is set to; there the app follows the system appearance instead, with the +//! crate's own dark and light palettes, and switches when it does. + +use std::path::Path; + +use gpui_kit::{App, Window, WindowAppearance}; +use gpui_omarchy::Theme; + +/// Whether the system appearance, rather than an Omarchy theme, decides the +/// colours: on macOS, unless an Omarchy theme is installed there anyway. +pub fn follows_system(home: Option<&Path>) -> bool { + cfg!(target_os = "macos") + && !home.is_some_and(|home| { + [".local/state/omarchy/current", ".config/omarchy/current"] + .iter() + .any(|theme| home.join(theme).exists()) + }) +} + +/// Apply the palette for `appearance`. Applying an explicit theme also stops +/// gpui-omarchy watching for theme files that are not there. +pub fn apply(appearance: WindowAppearance, cx: &mut App) { + let theme = match appearance { + WindowAppearance::Light | WindowAppearance::VibrantLight => { + Theme::flexoki_light() + } + WindowAppearance::Dark | WindowAppearance::VibrantDark => { + Theme::tokyo_night() + } + }; + theme.apply(cx); +} + +/// Follow `window`'s appearance from now on. +pub fn follow(window: &Window) { + window + .observe_window_appearance(|window, cx| apply(window.appearance(), cx)) + .detach(); +} diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index 5c52eb6..84540af 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -12,7 +12,9 @@ use std::process::{Command, Stdio}; #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct GitState { /// Paths `git status --porcelain` lists: changed, staged or untracked. - pub changed: usize, + /// `None` when asking would run a program the checkout names; see + /// [`names_its_own_filters`]. + pub changed: Option, pub stashes: usize, /// Commits ahead of the upstream; `None` when there is no upstream. pub unpushed: Option, @@ -21,7 +23,7 @@ pub struct GitState { impl GitState { /// Nothing would be lost by deleting it. pub const fn is_clean(&self) -> bool { - self.changed == 0 + matches!(self.changed, Some(0)) && self.stashes == 0 && matches!(self.unpushed, Some(0)) } @@ -29,10 +31,10 @@ impl GitState { /// One short line: `clean, no stash`, `3 changed, 1 stash, 2 unpushed`. pub fn summary(&self) -> String { let mut parts = Vec::new(); - parts.push(if self.changed == 0 { - "clean".to_string() - } else { - format!("{} changed", self.changed) + parts.push(match self.changed { + Some(0) => "clean".to_string(), + Some(count) => format!("{count} changed"), + None => "changes unknown".to_string(), }); parts.push(match self.stashes { 0 => "no stash".to_string(), @@ -56,11 +58,19 @@ pub fn is_checkout(path: &Path) -> bool { /// Ask git. `None` when `path` is not a checkout or git is not installed. pub fn state(path: &Path) -> Option { - if !is_checkout(path) { + if !is_checkout(path) || !git_installed() { return None; } - let status = run(path, &["status", "--porcelain=v1", "-z"])?; - let changed = status.split('\0').filter(|line| !line.is_empty()).count(); + let changed = if names_its_own_filters(path) { + None + } else { + // Submodules are other checkouts with configs of their own. + let status = run( + path, + &["status", "--porcelain=v1", "-z", "--ignore-submodules=all"], + )?; + Some(status.split('\0').filter(|line| !line.is_empty()).count()) + }; let stashes = run(path, &["stash", "list"]).map_or(0, |list| list.lines().count()); let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"]) @@ -72,10 +82,90 @@ pub fn state(path: &Path) -> Option { }) } +/// Whether running `git` runs git. On macOS `/usr/bin/git` is there even +/// without the developer tools, as a stub that opens an "install the command +/// line developer tools" dialog, which selecting a checkout must not do. +/// `xcode-select -p` answers without prompting. It names the selected +/// developer directory even after that directory was deleted, so the path +/// must also still be there. Asked once. +fn git_installed() -> bool { + static INSTALLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *INSTALLED.get_or_init(|| { + if !cfg!(target_os = "macos") { + return true; + } + Command::new("xcode-select") + .arg("-p") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .is_ok_and(|output| { + output.status.success() + && Path::new(String::from_utf8_lossy(&output.stdout).trim()) + .is_dir() + }) + }) +} + +/// Whether the checkout's own config defines filter drivers. +/// +/// `git status` runs a file's `clean` filter to compare it with the index, +/// and a downloaded repository can name any program as one in `.git/config` +/// and switch it on from its `.gitattributes`. No `-c` can turn off drivers +/// whose names are not known in advance, so a checkout that defines any is +/// not asked for its status at all. Filters from the user's own config, such +/// as git-lfs, are theirs and still run. Reading config runs nothing; if it +/// cannot be read, the answer is the cautious one. +fn names_its_own_filters(path: &Path) -> bool { + let Some(output) = git( + path, + &[ + "config", + "--show-scope", + "--includes", + "--get-regexp", + r"^filter\.", + ], + ) else { + return true; + }; + match output.status.code() { + // No filter anywhere. + Some(1) => false, + Some(0) => { + String::from_utf8_lossy(&output.stdout).lines().any(|line| { + matches!(line.split('\t').next(), Some("local" | "worktree")) + }) + } + _ => true, + } +} + fn run(path: &Path, args: &[&str]) -> Option { - let output = Command::new("git") + let output = git(path, args)?; + output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +} + +fn git(path: &Path, args: &[&str]) -> Option { + Command::new("git") .arg("-C") .arg(path) + // A checkout's own config can name programs for git to run: an + // fsmonitor on every `status`, hooks, a pager. Selecting a directory + // in a disk viewer must not execute anything it contains, and a + // command-line `-c` outranks the repository's config. (From + // tobi/disktree#10.) + .args([ + "-c", + "core.fsmonitor=false", + "-c", + "core.hooksPath=/dev/null", + "-c", + "core.pager=cat", + ]) .args(args) // Never prompt, never page, never take a lock for the index refresh. .env("GIT_TERMINAL_PROMPT", "0") @@ -83,11 +173,7 @@ fn run(path: &Path, args: &[&str]) -> Option { .stdin(Stdio::null()) .stderr(Stdio::null()) .output() - .ok()?; - output - .status - .success() - .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) + .ok() } #[cfg(test)] @@ -97,21 +183,31 @@ mod tests { #[test] fn summaries_say_what_would_be_lost() { let clean = GitState { + changed: Some(0), unpushed: Some(0), ..GitState::default() }; assert!(clean.is_clean()); assert_eq!(clean.summary(), "clean, no stash"); let busy = GitState { - changed: 3, + changed: Some(3), stashes: 1, unpushed: Some(2), }; assert!(!busy.is_clean()); assert_eq!(busy.summary(), "3 changed, 1 stash, 2 unpushed"); - let local = GitState::default(); + let local = GitState { + changed: Some(0), + ..GitState::default() + }; assert_eq!(local.summary(), "clean, no stash, no upstream"); assert!(!local.is_clean(), "unpushed history could be lost"); + let guarded = GitState { + unpushed: Some(0), + ..GitState::default() + }; + assert_eq!(guarded.summary(), "changes unknown, no stash"); + assert!(!guarded.is_clean(), "unknown is not clean"); } #[test] @@ -131,7 +227,89 @@ mod tests { } std::fs::write(dir.path().join("a.txt"), "hi").expect("write"); let state = state(dir.path()).expect("a checkout"); - assert_eq!(state.changed, 1, "one untracked file"); + assert_eq!(state.changed, Some(1), "one untracked file"); assert_eq!(state.stashes, 0); } + + #[cfg(unix)] + #[test] + fn a_checkout_cannot_make_git_run_its_programs() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let hook = dir.path().join("hook.sh"); + std::fs::write( + &hook, + format!("#!/bin/sh\ntouch '{}'\n", marker.display()), + ) + .expect("write hook"); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)) + .expect("chmod"); + let git = |args: &[&str]| { + Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(args) + .output() + .is_ok_and(|output| output.status.success()) + }; + if !git_installed() || !git(&["init", "-q"]) { + return; // no git on this machine + } + let hook = hook.to_string_lossy(); + assert!(git(&["config", "core.fsmonitor", &hook])); + assert!(state(dir.path()).is_some()); + assert!(!marker.exists(), "the checkout's fsmonitor ran"); + } + + #[cfg(unix)] + #[test] + fn a_checkouts_own_filter_is_never_run() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let filter = dir.path().join("filter.sh"); + // A clean filter reads the file on stdin and writes it back. + std::fs::write( + &filter, + format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display()), + ) + .expect("write filter"); + std::fs::set_permissions( + &filter, + std::fs::Permissions::from_mode(0o755), + ) + .expect("chmod"); + let git = |args: &[&str]| { + Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(["-c", "user.name=t", "-c", "user.email=t@t"]) + .args(args) + .output() + .is_ok_and(|output| output.status.success()) + }; + if !git_installed() || !git(&["init", "-q"]) { + return; // no git on this machine + } + std::fs::write(dir.path().join("file.txt"), "x").expect("write"); + std::fs::write( + dir.path().join(".gitattributes"), + "*.txt filter=evil\n", + ) + .expect("write attributes"); + assert!(git(&["add", "."]) && git(&["commit", "-qm", "one"])); + std::fs::remove_file(&marker).ok(); + let filter = filter.to_string_lossy(); + assert!(git(&["config", "filter.evil.clean", &filter])); + // Same content, new timestamp: git must re-read the file, through + // the filter, to know whether it changed. + std::fs::write(dir.path().join("file.txt"), "x").expect("rewrite"); + + let state = state(dir.path()).expect("a checkout"); + assert_eq!(state.changed, None, "not asked"); + assert!(!marker.exists(), "the checkout's filter ran"); + } } diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 22b8265..067e1e1 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -5,6 +5,8 @@ //! live free-space meter. Marking is non-destructive until the review screen //! is confirmed. +mod app_menu; +mod appearance; mod git; mod marks; mod palette; @@ -65,6 +67,12 @@ fn main() -> Result<()> { .with_assets(gpui_kit::assets::Assets) .run(move |cx| { gpui_omarchy::init(cx); + app_menu::install(cx); + let home = std::env::var_os("HOME").map(PathBuf::from); + let native_look = appearance::follows_system(home.as_deref()); + if native_look { + appearance::apply(cx.window_appearance(), cx); + } let options = args.options.clone(); let root_for_app = root.clone(); let window = cx @@ -82,9 +90,7 @@ fn main() -> Result<()> { "disktree · {}", marks::display_path( &title_root, - std::env::var_os("HOME") - .map(PathBuf::from) - .as_deref(), + home.as_deref(), ) ) .into(), @@ -96,7 +102,10 @@ fn main() -> Result<()> { window_min_size: Some(size(px(900.), px(600.))), ..Default::default() }, - move |_, cx| { + move |window, cx| { + if native_look { + appearance::follow(window); + } cx.new(|cx| { Disktree::new( root_for_app.clone(), @@ -159,6 +168,9 @@ fn parse_args() -> Result { ), }; } + // Launch Services added a process serial number when opening an + // app from Finder until OS X 10.9, and some launchers still do. + other if other.starts_with("-psn_") => {} other if other.starts_with('-') => { anyhow::bail!("unknown option {other}\n\n{USAGE}"); } diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 6a2212a..2251610 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -350,6 +350,8 @@ pub struct Disktree { /// Focus to move on the next occasion a window is in hand. Key handling /// has no window, and opening or closing the dialog must move focus. pub focus_request: Option, + /// What the titlebar says, so it is only set when it changes. + window_title: String, /// The window's `rem` in pixels, read each frame. The mosaic is laid out /// in pixels, so its header band and label thresholds are scaled by this /// to follow interface zoom like the rest of the interface. @@ -393,8 +395,11 @@ pub struct Disktree { git_pending: FxHashSet, /// The device the scanned volume is mounted from. pub device: Option, - /// The top of the disk the home directory lives on: what "Whole disk" - /// scans. + /// Whether macOS lets this process read everything: asked once, since a + /// grant only takes effect after a relaunch. `None` off macOS. + pub full_disk_access: Option, + /// The top of the disk the scanned root lives on: what "Whole disk" + /// scans. Follows the root when a folder is opened. pub disk_root: Option, /// The side panel's width, in rem; dragged from its left edge. pub panel_rems: f32, @@ -453,6 +458,7 @@ impl Disktree { confirm_open: false, confirm_focus: cx.focus_handle(), focus_request: None, + window_title: String::new(), rem: crate::ui::BASE_REM, run: None, run_epoch: 0, @@ -478,6 +484,7 @@ impl Disktree { git: FxHashMap::default(), git_pending: FxHashSet::default(), device: None, + full_disk_access: None, disk_root: None, panel_rems: PANEL_REMS, scan_started: None, @@ -486,11 +493,14 @@ impl Disktree { scanned_at: now_seconds(), }; tree.device = device_for(&tree.root_path); - tree.disk_root = tree + tree.full_disk_access = tree .home .as_deref() - .or(Some(tree.root_path.as_path())) - .and_then(volume_root_for); + .and_then(disktree_core::access::full_disk_access); + // The disk of what is on screen, as `set_root` keeps it: `disktree + // /Volumes/Ext` then `g` measures that drive, like opening it with ⌘O. + tree.disk_root = volume_root_for(&tree.root_path); + disktree_core::removal::prime_mount_points(); tree.start_scan(cx); Self::start_space_ticker(cx); tree @@ -523,6 +533,10 @@ impl Disktree { pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) { self.space = space_info(&root).ok(); self.device = device_for(&root); + // "Whole disk" means the disk of what is on screen, which a new root + // can change: an external drive has its own. + self.disk_root = + volume_root_for(&root).or_else(|| self.disk_root.take()); self.root_path = root; self.screen = Screen::Explore; self.start_scan(cx); @@ -1940,16 +1954,72 @@ impl Disktree { // ── input ─────────────────────────────────────────────────────────── - /// Handle a key press. Returns whether the directory on screen changed, - /// which is what keeps the window title honest. + /// Handle a key press. pub fn on_key_down( &mut self, event: &KeyDownEvent, cx: &mut Context<'_, Self>, - ) -> bool { - let before = self.crumbs.clone(); + ) { self.dispatch_key(event, cx); - self.crumbs != before + } + + /// Whether a menu command may replace the tree: where `r` would, not + /// behind the confirmation, and not under the review list or a removal + /// that is still running. + pub fn can_start_over(&self) -> bool { + self.screen == Screen::Explore && !self.confirm_open + } + + /// Ask for a directory and scan it: an app opened from the Dock has no + /// command line to name one. + pub fn open_folder(cx: &Context<'_, Self>) { + let chosen = cx.prompt_for_paths(gpui_kit::PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Scan".into()), + }); + cx.spawn(async move |this, cx| { + let Ok(Ok(Some(paths))) = chosen.await else { + return; + }; + let Some(path) = paths.into_iter().next() else { + return; + }; + // Canonical, like a root from the command line, so a later + // widening recognises this tree in the wider walk. + let path = path.canonicalize().unwrap_or(path); + // The panel does not block the window: the review list or a + // removal may have started while it was open. + let _ = this.update(cx, |this, cx| { + if this.can_start_over() { + this.set_root(path, cx); + } + }); + }) + .detach(); + } + + /// Show the tile a key acts on in Finder (or the file manager), selected. + pub fn reveal_target(&mut self, cx: &mut Context<'_, Self>) { + let crumbs = + self.action_target().unwrap_or_else(|| self.crumbs.clone()); + let Some(path) = self.path_at(&crumbs) else { + return; + }; + // GPUI's reveal cannot report failure, so check what it can't. + if std::fs::symlink_metadata(&path).is_err() { + self.notice = Some(( + format!( + "{} is no longer on disk", + crate::marks::display_path(&path, self.home.as_deref()) + ), + Status::Warning, + )); + cx.notify(); + return; + } + cx.reveal_path(&path); } /// Every binding, in reading order of the hint bar, so the keys and the @@ -1969,6 +2039,14 @@ impl Disktree { return; } + // ⌘ chords belong to the menu bar (⌘Q, ⌘W, ⌘R) or to the system. + // Read as plain letters they would act twice or by surprise: ⌘D + // would re-scan with apparent sizes, ⌘H would hide *and* toggle. + // Zoom (⌘= ⌘- ⌘0) is handled before this, with a window in hand. + if event.keystroke.modifiers.platform { + return; + } + if self.crumb_menu.is_some() && self.on_menu_key(key, cx) { return; } @@ -2141,6 +2219,7 @@ impl Disktree { self.show_selection = !self.show_selection; cx.notify(); } + "o" if !control => self.reveal_target(cx), "?" => { self.show_help = true; cx.notify(); @@ -2457,6 +2536,19 @@ impl Render for Disktree { ) -> impl gpui_kit::IntoElement { self.rem = window.rem_size().as_f32(); self.tick_transition(window); + // The titlebar names the directory on screen, however it got there: + // a key, a click, a rescan or a folder chosen from the menu. + let title = format!( + "disktree · {}", + crate::marks::display_path( + &self.current_path(), + self.home.as_deref() + ) + ); + if title != self.window_title { + window.set_window_title(&title); + self.window_title = title; + } crate::views::root(self, window, cx) } } diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 946b06a..dffb545 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -466,6 +466,38 @@ fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) { assert!(!read(&view, cx, |app| app.show_help)); } +#[gpui_kit::test] +fn showing_a_tile_that_is_gone_says_so_instead(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + // The selection is .cache, the largest; take it away behind the tree. + std::fs::remove_dir_all(temp.path().join(".cache")).expect("remove"); + press(cx, "o"); + let notice = read(&view, cx, |app| app.notice.clone()); + let (message, _) = notice.expect("a notice"); + assert!(message.contains("no longer on disk"), "{message}"); +} + +#[gpui_kit::test] +fn command_chords_are_not_read_as_plain_letters(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + // ⌘P and ⌘D are the menu bar's or nobody's; read as `p` and `d` they + // would hide the selection and re-scan. + let shown = read(&view, cx, |app| app.show_selection); + press(cx, "cmd-p cmd-d"); + assert_eq!(read(&view, cx, |app| app.show_selection), shown); + assert!(read(&view, cx, |app| app.options.apparent_size)); + press(cx, "p"); + assert_eq!(read(&view, cx, |app| app.show_selection), !shown); +} + #[gpui_kit::test] fn the_treemap_zooms_with_the_wheel_and_resets(cx: &mut TestAppContext) { cx.update(gpui_omarchy::init); diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index ca7b193..fdf7e3c 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -56,23 +56,32 @@ pub fn root( .debug_selector(|| "disktree-root".into()) .track_focus(&app.focus) .key_context("Disktree") - // The listener is the only place with a window in hand, so it is also - // where the titlebar is kept in step with the directory on screen. + .on_action(cx.listener(|this, _: &crate::app_menu::Rescan, _, cx| { + // Where `r` would: not behind the confirmation, and not under + // the review list or a removal that is still running. + if this.can_start_over() { + this.start_scan(cx); + } + })) + .on_action(cx.listener( + |this, _: &crate::app_menu::OpenFolder, _, cx| { + if this.can_start_over() { + Disktree::open_folder(cx); + } + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowInFinder, _, cx| { + this.reveal_target(cx); + }, + )) .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { if this.zoom_interface(event, window) { cx.notify(); return; } - let moved = this.on_key_down(event, cx); + this.on_key_down(event, cx); this.apply_focus(window, cx); - if moved { - let path = this.current_path(); - let title = format!( - "disktree · {}", - crate::marks::display_path(&path, this.home.as_deref()) - ); - window.set_window_title(&title); - } })) .relative() .flex() @@ -899,6 +908,7 @@ fn side_panel( .child(marked_section(app, theme, cx)), ) .children(notice_line(app, theme, cx)) + .children(privacy_line(app, theme, cx)) .child(disk_section(app, theme, cx)) } @@ -1423,6 +1433,60 @@ fn notice_line(app: &Disktree, theme: &Theme, cx: &App) -> Option
{ ) } +/// Why folders were unreadable on macOS, and the one place to fix it. +/// +/// Only once the scan has hit something it could not read and the process is +/// known to lack Full Disk Access: an unreadable folder has other causes, and +/// the hint must not nag when it would not help. A grant needs a relaunch, and +/// started from a terminal it is the terminal that needs it. +fn privacy_line( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + if app.progress.errors == 0 || app.full_disk_access != Some(false) { + return None; + } + let color = theme.warning; + let errors = app.progress.errors; + let noun = if errors == 1 { "item" } else { "items" }; + Some( + div() + .flex() + .flex_col() + .gap(space::SM) + .px(space::SM) + .py(space::SM) + .border_1() + .border_color(color.opacity(0.5)) + .text_size(text::CAPTION) + .child(div().text_color(color).child(format!( + "macOS kept {} {noun} unreadable. Give disktree Full Disk \ + Access, or your terminal if you started it there, then \ + reopen it.", + widgets::human_count(errors) + ))) + .child( + button( + "privacy", + "Open Privacy Settings", + ButtonVariant::Outline, + cx, + ) + .tab_stop(false) + .justify_center() + .on_click(cx.listener( + |this, _, window, cx| { + cx.open_url( + disktree_core::access::FULL_DISK_ACCESS_SETTINGS, + ); + window.focus(&this.focus, cx); + }, + )), + ), + ) +} + /// Free space on the volume now, and after the marks go. fn disk_section( app: &Disktree, @@ -2734,13 +2798,27 @@ pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ Some(tip) } +/// The modifier the help names for clicks and interface zoom. Both are +/// accepted everywhere; this is the one each platform's users reach for, and +/// on macOS ctrl-click is a right-click. +const MODIFIER_CLICK: &str = if cfg!(target_os = "macos") { + "\u{2318}-click" +} else { + "ctrl-click" +}; +const MODIFIER_ZOOM: &str = if cfg!(target_os = "macos") { + "\u{2318} = / - / 0" +} else { + "ctrl = / - / 0" +}; + fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { let theme = cx.omarchy(); // Sentence case, and the tile a key acts on is always the one under the // pointer if the pointer moved last, else the keyboard selection. - let rows: [(&str, &str); 24] = [ + let rows: [(&str, &str); 25] = [ ("space / x", "Mark or unmark the tile you point at"), - ("ctrl-click", "Mark without moving the selection"), + (MODIFIER_CLICK, "Mark without moving the selection"), ("enter", "Open that directory, at any depth"), ("\u{232b} / esc", "Go up one directory"), ( @@ -2752,7 +2830,7 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("shift-scroll", "Pan the magnified view"), ("[ / ]", "Draw fewer or more levels at once"), ("- / = / 0", "Magnify, shrink, or reset the view"), - ("ctrl = / - / 0", "Interface zoom"), + (MODIFIER_ZOOM, "Interface zoom"), ( "/", "Filter by name: only matches keep their colour; enter shows only them", @@ -2764,6 +2842,14 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("d", "Disk usage or apparent size"), ("i", "Include or skip hidden entries"), ("p", "Show or hide the selection line"), + ( + "o", + if cfg!(target_os = "macos") { + "Show it in Finder" + } else { + "Show it in the file manager" + }, + ), ("q", "Quit"), ("", ""), ( diff --git a/crates/disktree-core/Cargo.toml b/crates/disktree-core/Cargo.toml index 21ac328..8b3ef03 100644 --- a/crates/disktree-core/Cargo.toml +++ b/crates/disktree-core/Cargo.toml @@ -17,3 +17,9 @@ rustc-hash = { workspace = true } [dev-dependencies] tempfile = "3" + +# The system trash, through NSFileManager: what Finder's Move to Trash does, +# without asking to control Finder. Only this backend is used; the crate's +# Linux and Windows code is not built. +[target.'cfg(target_os = "macos")'.dependencies] +trash = { version = "5.2.9", default-features = false } diff --git a/crates/disktree-core/src/access.rs b/crates/disktree-core/src/access.rs new file mode 100644 index 0000000..d56e2d9 --- /dev/null +++ b/crates/disktree-core/src/access.rs @@ -0,0 +1,49 @@ +//! What the operating system keeps private from a scan. +//! +//! On macOS a process without Full Disk Access is refused parts of the home +//! directory — Mail, Messages, Safari, other apps' containers, the Trash — +//! with `EPERM`, silently. A disk tool that only counts those as errors +//! leaves the user guessing, so the app asks once whether access is granted +//! and, if not, says why folders were unreadable and where to fix it. + +use std::path::Path; + +/// System Settings, opened at Privacy & Security › Full Disk Access. +pub const FULL_DISK_ACCESS_SETTINGS: &str = + "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"; + +/// Whether this process has Full Disk Access: `Some(false)` when it is +/// refused, `None` where the question does not apply or cannot be answered. +/// +/// The privacy database itself is protected by Full Disk Access, so opening +/// it for reading is the test. It never shows a prompt, unlike touching +/// Desktop or Documents would. +pub fn full_disk_access(home: &Path) -> Option { + if !cfg!(target_os = "macos") { + return None; + } + let database = + home.join("Library/Application Support/com.apple.TCC/TCC.db"); + match std::fs::File::open(database) { + Ok(_) => Some(true), + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + Some(false) + } + Err(_) => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_macos_has_an_answer_and_a_missing_database_is_not_a_refusal() { + let temp = tempfile::TempDir::new().expect("tempdir"); + assert_eq!(full_disk_access(temp.path()), None); + if !cfg!(target_os = "macos") { + let home = std::env::var_os("HOME").expect("HOME is set"); + assert_eq!(full_disk_access(Path::new(&home)), None); + } + } +} diff --git a/crates/disktree-core/src/classify.rs b/crates/disktree-core/src/classify.rs index 2fb4fe6..098e5de 100644 --- a/crates/disktree-core/src/classify.rs +++ b/crates/disktree-core/src/classify.rs @@ -122,9 +122,15 @@ pub fn category_of_name(name: &str) -> Option { | ".espressif" | ".arduino15" | ".config" | ".vscode" | ".zig" | ".rye" | ".conda" | "anaconda3" | "miniconda3" | ".opam" | ".ghcup" | ".stack" | ".julia" | ".dotnet" | ".android" - | ".sdkman" | ".volta" | ".yarn" | ".java" => Category::Toolchain, + | ".sdkman" | ".volta" | ".yarn" | ".java" + // macOS: Xcode's and the simulators' state in ~/Library/Developer. + // Not `Developer` itself: ~/Developer is where Apple puts projects. + | "xcode" | "coresimulator" => Category::Toolchain, "sync" | "dropbox" | "nextcloud" | "google drive" | "onedrive" - | "pclouddrive" | "mega" | ".stversions" => Category::Synced, + | "pclouddrive" | "mega" | ".stversions" + // macOS: iCloud Drive, and the File Provider clients (Dropbox, + // Google Drive, OneDrive) since macOS 12. + | "mobile documents" | "cloudstorage" => Category::Synced, ".git" => Category::Git, "pictures" | "photos" | "music" | "videos" | "movies" | "steam" | "models" | ".ollama" | ".lmstudio" | "games" | "wineprefix" => { @@ -134,7 +140,8 @@ pub fn category_of_name(name: &str) -> Option { | "obsidian" | "public" | "templates" => Category::Documents, ".cache" | "cache" | "caches" | ".ccache" | ".sccache" | "_cacache" | "__pycache__" | "node_modules" | "trash" | ".trash" | "tmp" - | ".tmp" => Category::Cache, + | ".tmp" | "deriveddata" | "ios devicesupport" + | "watchos devicesupport" => Category::Cache, _ => return None, }; Some(category) @@ -155,7 +162,14 @@ pub fn reclaim_of( ".stversions" => Reclaim::SyncHistory, ".pnpm-store" | "pnpm" => Reclaim::PackageStore, "__pycache__" | ".pytest_cache" | ".mypy_cache" | ".ruff_cache" - | ".next" | ".turbo" | ".parcel-cache" => Reclaim::BuildOutput, + | ".next" | ".turbo" | ".parcel-cache" + // Xcode's build products and indexes, rebuilt on the next build. + | "deriveddata" => Reclaim::BuildOutput, + // Symbols Xcode copies off a device it meets, and copies again the + // next time that device is plugged in. + "ios devicesupport" | "watchos devicesupport" => Reclaim::Regenerable, + // ~/Library/Logs, told apart from a project's logs by its neighbour. + "logs" if has_sibling("Application Support") => Reclaim::Temporary, // Too common to trust alone: only a build directory beside a manifest. "target" if has_sibling("Cargo.toml") => Reclaim::BuildOutput, "node_modules" if has_sibling("package.json") => Reclaim::Reinstallable, @@ -425,6 +439,36 @@ mod tests { ); } + #[test] + fn macos_developer_leftovers_are_reclaimable_and_its_risks_are_not() { + let none = |_: &str| false; + assert_eq!( + reclaim_of("DerivedData", Category::Toolchain, none), + Some(Reclaim::BuildOutput) + ); + assert_eq!( + reclaim_of("iOS DeviceSupport", Category::Toolchain, none), + Some(Reclaim::Regenerable) + ); + let library = |name: &str| name == "Application Support"; + assert_eq!( + reclaim_of("Logs", Category::Other, library), + Some(Reclaim::Temporary) + ); + assert_eq!(reclaim_of("logs", Category::Code, none), None); + // Big, but not safe to offer: Archives hold the symbols crash + // reports need, and Backup is an iPhone's only backup. + assert_eq!(reclaim_of("Archives", Category::Toolchain, none), None); + assert_eq!(reclaim_of("Backup", Category::Other, none), None); + assert_eq!( + category_of_name("Mobile Documents"), + Some(Category::Synced) + ); + // ~/Developer holds a user's projects, not a toolchain. + assert_eq!(category_of_name("Developer"), None); + assert_eq!(category_of_name("Xcode"), Some(Category::Toolchain)); + } + #[test] fn the_legend_lists_every_named_category_once() { let mut seen = std::collections::HashSet::new(); diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rs index d7cdb24..872cc8d 100644 --- a/crates/disktree-core/src/lib.rs +++ b/crates/disktree-core/src/lib.rs @@ -5,6 +5,7 @@ //! hardlink de-duplication, aspect-ratio layout, and what may be deleted — can //! be built and tested without GPUI, a display, or a GPU. +pub mod access; pub mod classify; pub mod filter; pub mod insights; diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index c15ad04..f328a2e 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -6,12 +6,14 @@ //! //! Two mechanisms are offered: //! -//! * [`RemovalMode::Permanent`] — `rm -rf` semantics, implemented with the -//! standard library rather than by shelling out, so no path ever reaches a +//! * [`RemovalMode::Permanent`] — `rm -rf --one-file-system` semantics, +//! implemented here rather than by shelling out, so no path ever reaches a //! shell and no filename can be misread as an option. -//! * [`RemovalMode::Trash`] — move to the desktop trash, using `trash-put`, -//! then `gio trash`, then a built-in XDG implementation. The backend is -//! detected once and named in the UI so the user knows what actually happens. +//! * [`RemovalMode::Trash`] — move to the desktop trash. On macOS that is +//! always the system Trash, through `NSFileManager`. Elsewhere it is +//! `trash-put`, then `gio trash`, then a built-in XDG implementation. The +//! backend is detected once and named in the UI so the user knows what +//! actually happens. use std::fs; use std::io; @@ -92,13 +94,19 @@ impl Plan { /// looking at is the only thing they consented to act on. pub fn plan(targets: &[Target], root: &Path) -> Plan { let root = normalize(root); - let home = std::env::var_os("HOME").map(PathBuf::from); let mut plan = Plan::default(); let mut accepted: Vec = Vec::new(); + if targets.is_empty() { + return plan; + } + let mounts = mount_points(); + // Once per plan, not per target: the review screen plans every frame. + let home = std::env::var_os("HOME").map(|home| Home::of(Path::new(&home))); + for target in targets { let path = normalize(&target.path); - if let Some(reason) = refuse(&path, &root, home.as_deref()) { + if let Some(reason) = refuse(&path, &root, home.as_ref(), &mounts) { plan.blocked.push(Blocked { path: target.path.clone(), reason, @@ -129,13 +137,19 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { plan } -/// Why this path must not be removed, if it must not. /// Trees the operating system owns. A whole-disk scan shows them, because /// they are part of what fills the disk, but files there belong to packages -/// and removing them by hand breaks the system; pacman, paccache and -/// `journalctl --vacuum` are the right tools. Refused even where -/// permissions would allow it, and even inside them. -const SYSTEM_TREES: [&str; 14] = [ +/// and removing them by hand breaks the system; pacman, paccache, +/// `journalctl --vacuum` or `brew cleanup` are the right tools. Refused even +/// where permissions would allow it, and even inside them. +/// +/// One list for every platform: a macOS tree never exists on Linux, and the +/// other way round, so the extra entries cost nothing. On macOS `/etc`, +/// `/var` and `/tmp` are links into `/private`, which a whole-disk scan +/// reaches by its real name. `/Applications` is left out on purpose: moving +/// an app to the Trash is how macOS uninstalls it, and the apps macOS ships +/// live on the read-only system volume anyway. +const SYSTEM_TREES: [&str; 20] = [ "/bin", "/boot", "/dev", @@ -150,36 +164,134 @@ const SYSTEM_TREES: [&str; 14] = [ "/usr", "/var/lib", "/efi", + // macOS. + "/System", + "/Library", + "/private", + "/cores", + "/opt/homebrew", + "/Network", ]; -/// The system tree `path` is in, if any. The home directory is never -/// system, wherever it lives. -fn system_tree(path: &Path, home: Option<&Path>) -> Option<&'static str> { - if home.is_some_and(|home| path.starts_with(normalize(home))) { - return None; - } - SYSTEM_TREES - .iter() - .find(|tree| path.starts_with(tree)) - .copied() +/// How the guards compare paths: lexically normalized, and on macOS also in +/// the form Finder shows and without case. +/// +/// macOS reaches the same directory under two names — `/Users/x` and +/// `/System/Volumes/Data/Users/x` — and its disks ignore case by default, so +/// `/library/caches` is `/Library/Caches`. A guard that compared the spelling +/// would be passed by the other one. Only for judging: what is removed is +/// always the path as marked. +fn guard_key(path: &Path) -> PathBuf { + guard_key_for(path, cfg!(target_os = "macos")) } -fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { +fn guard_key_for(path: &Path, macos: bool) -> PathBuf { + let path = normalize(path); + if !macos { + return path; + } + // The Data volume's own root stays as it is: it is under /System. + let path = match path.strip_prefix(crate::space::MACOS_DATA_VOLUME) { + Ok(rest) if !rest.as_os_str().is_empty() => Path::new("/").join(rest), + _ => path, + }; + PathBuf::from(path.to_string_lossy().to_lowercase()) +} + +/// [`SYSTEM_TREES`] with their guard keys, computed once: the review screen +/// plans on every frame, for every mark. +fn system_tree_keys() -> &'static [(&'static str, PathBuf)] { + static KEYS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| { + SYSTEM_TREES + .iter() + .map(|tree| (*tree, guard_key(Path::new(tree)))) + .collect() + }); + &KEYS +} + +/// The system tree the path keyed `key` is in, if any. The home directory is +/// never system, wherever it lives. +fn system_tree(key: &Path, home: Option<&Path>) -> Option<&'static str> { + if home.is_some_and(|home| key.starts_with(home)) { + return None; + } + system_tree_keys() + .iter() + .find(|(_, tree)| key.starts_with(tree)) + .map(|(name, _)| *name) +} + +/// A system tree strictly inside the path keyed `key`: removing `/opt` takes +/// `/opt/homebrew` with it, and `/var` takes `/var/lib`. +fn system_tree_below(key: &Path) -> Option<&'static str> { + system_tree_keys() + .iter() + .find(|(_, tree)| tree != key && tree.starts_with(key)) + .map(|(name, _)| *name) +} + +/// The home directory, as the guards compare it: by key, and by identity. +#[derive(Debug)] +struct Home { + key: PathBuf, + /// Device and inode, so a spelling [`guard_key`] cannot fold still + /// matches. + id: Option<(u64, u64)>, +} + +impl Home { + fn of(path: &Path) -> Self { + Self { + key: guard_key(path), + id: fs::metadata(path).ok().and_then(|meta| file_id(&meta)), + } + } +} + +fn refuse( + path: &Path, + root: &Path, + home: Option<&Home>, + mounts: &[PathBuf], +) -> Option { + let key = guard_key(path); + let home_key = home.map(|home| home.key.as_path()); if path.parent().is_none() { return Some("the filesystem root cannot be removed".into()); } if path == root { return Some("the scanned root cannot be removed".into()); } - if home.is_some_and(|home| path == normalize(home)) { + if home_key.is_some_and(|home| key == home) + || home.and_then(|home| home.id).is_some_and(|id| { + fs::symlink_metadata(path) + .ok() + .and_then(|meta| file_id(&meta)) + == Some(id) + }) + { return Some("the home directory cannot be removed".into()); } + // On Linux `/home` is usually a mount point of its own and refused as + // one; on macOS `/Users` is on the same volume as `/`, and removing it + // would empty the home directory before failing on `/Users` itself. + if home_key.is_some_and(|home| home.starts_with(&key)) { + return Some("it contains the home directory".into()); + } if !path.starts_with(root) { return Some("outside the scanned root".into()); } - if let Some(system) = system_tree(path, home) { + if let Some(system) = system_tree(&key, home_key) { return Some(format!( - "part of the system under {system}: use the package manager" + "part of the system under {system}: remove it with the tool \ + that installed it" + )); + } + if let Some(system) = system_tree_below(&key) { + return Some(format!( + "it contains {system}, which is part of the system" )); } if is_mount_point(path) { @@ -188,9 +300,127 @@ fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { .into(), ); } + if let Some(mount) = mount_below(&key, mounts) { + return Some(format!( + "{} is mounted inside it: removing it would reach into another \ + filesystem", + mount.display() + )); + } None } +/// `(device, inode)`: what makes two spellings one directory entry. +#[allow( + clippy::unnecessary_wraps, + reason = "the Option is the non-Unix answer, so both arms must agree" +)] +#[cfg(unix)] +fn file_id(meta: &fs::Metadata) -> Option<(u64, u64)> { + use std::os::unix::fs::MetadataExt as _; + Some((meta.dev(), meta.ino())) +} + +#[cfg(not(unix))] +const fn file_id(_meta: &fs::Metadata) -> Option<(u64, u64)> { + None +} + +/// How long a read of the mount table is used before it is read again. A +/// disk plugged in is noticed within this, and the removal itself stops at a +/// mount boundary whatever the table said. +const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2); + +/// The last read of the mount table, and whether a read is under way. +struct MountCache { + read: Option, + mounts: Option>>, + refreshing: bool, +} + +static MOUNTS: std::sync::Mutex = + std::sync::Mutex::new(MountCache { + read: None, + mounts: None, + refreshing: false, + }); + +/// Every mount point on this machine, as guard keys, as last read. +/// +/// Never blocks on the read: the review screen plans on every frame, and on +/// macOS the table comes from running `mount`. A stale table starts a read on +/// its own thread and is used meanwhile; before the first read lands it is +/// empty, which is why the app primes it at start with +/// [`prime_mount_points`]. +fn mount_points() -> Arc> { + let mut cache = MOUNTS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let fresh = cache.read.is_some_and(|read| read.elapsed() < MOUNTS_FRESH); + if !fresh && !cache.refreshing { + cache.refreshing = true; + let spawned = thread::Builder::new() + .name("disktree-mounts".into()) + .spawn(|| { + let mounts = Arc::new(read_mount_points()); + let mut cache = MOUNTS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + cache.mounts = Some(mounts); + cache.read = Some(std::time::Instant::now()); + cache.refreshing = false; + }); + if spawned.is_err() { + cache.refreshing = false; + } + } + cache.mounts.clone().unwrap_or_default() +} + +/// Start reading the mount table, so it is there by the time anything is +/// marked. +pub fn prime_mount_points() { + let _ = mount_points(); +} + +/// Read the mount points now: from `/proc/self/mounts`, or on macOS from +/// `mount`, which has no `/proc`. Empty where neither can be read. +fn read_mount_points() -> Vec { + let points: Vec = + if let Ok(table) = fs::read_to_string("/proc/self/mounts") { + crate::space::parse_mounts(&table) + .into_iter() + .map(|mount| mount.point) + .collect() + } else if cfg!(target_os = "macos") { + Command::new("/sbin/mount") + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .filter(|output| output.status.success()) + .map(|output| { + crate::space::parse_macos_mounts(&String::from_utf8_lossy( + &output.stdout, + )) + }) + .unwrap_or_default() + } else { + Vec::new() + }; + points.iter().map(|point| guard_key(point)).collect() +} + +/// A mount point strictly inside the path keyed `key`, if there is one. A +/// scan that stays on one filesystem never shows what is mounted there, so +/// the user cannot have meant to remove it. +fn mount_below<'a>(key: &Path, mounts: &'a [PathBuf]) -> Option<&'a Path> { + mounts + .iter() + .find(|mount| mount.as_path() != key && mount.starts_with(key)) + .map(PathBuf::as_path) +} + /// Whether `path` sits on a different device than its parent, i.e. is a /// mount point. Descending into one would delete data the user never marked. #[cfg(unix)] @@ -250,6 +480,9 @@ pub fn normalize(path: &Path) -> PathBuf { /// Which tool, if any, moves files to the desktop trash. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TrashBackend { + /// The macOS Trash, through `NSFileManager`: the same move as Finder's + /// Move to Trash, into the Trash of the volume the item is on. + MacOs, /// `trash-put` from trash-cli. TrashPut, /// `gio trash`, present anywhere `GLib` is installed. @@ -264,13 +497,14 @@ pub enum TrashBackend { impl TrashBackend { pub const fn is_available(self) -> bool { match self { - Self::TrashPut | Self::Gio | Self::XdgHome => true, + Self::MacOs | Self::TrashPut | Self::Gio | Self::XdgHome => true, Self::Unavailable => false, } } pub const fn label(self) -> &'static str { match self { + Self::MacOs => "the Trash", Self::TrashPut => "trash-put", Self::Gio => "gio trash", Self::XdgHome => "XDG trash", @@ -280,6 +514,7 @@ impl TrashBackend { pub const fn detail(self) -> &'static str { match self { + Self::MacOs => "the same Trash as Finder, on the item's own disk", Self::TrashPut => { "uses trash-cli, the same trash as your file manager" } @@ -295,6 +530,17 @@ impl TrashBackend { } /// Detect the best available trash backend for this machine. +/// +/// On macOS the system Trash is always there, and the Linux tools are not +/// a substitute: Homebrew's `trash-put` writes the XDG layout, which Finder +/// never shows, so their files would look recoverable and not be. +#[cfg(target_os = "macos")] +pub const fn detect_trash_backend() -> TrashBackend { + TrashBackend::MacOs +} + +/// Detect the best available trash backend for this machine. +#[cfg(not(target_os = "macos"))] pub fn detect_trash_backend() -> TrashBackend { if which("trash-put") { TrashBackend::TrashPut @@ -307,6 +553,7 @@ pub fn detect_trash_backend() -> TrashBackend { } } +#[cfg(not(target_os = "macos"))] fn which(program: &str) -> bool { let Some(path) = std::env::var_os("PATH") else { return false; @@ -440,7 +687,27 @@ fn run( }); } -/// `rm -rf` semantics: a symlink is unlinked, never followed. +/// `rm -rf --one-file-system` semantics: a symlink is unlinked, never +/// followed, and nothing on another filesystem is touched. +/// +/// `fs::remove_dir_all` would descend into anything mounted inside `path` and +/// empty it before failing on the mount point itself, so the walk is done here +/// instead: every directory is opened relative to its parent with +/// `O_NOFOLLOW`, and one on a different device or mount stops the removal. +/// (From tobi/disktree#10.) +#[cfg(unix)] +pub fn remove_permanently(path: &Path) -> io::Result<()> { + let meta = fs::symlink_metadata(path)?; + if !meta.is_dir() { + return fs::remove_file(path); + } + let dir = open_dir(rustix::fs::CWD, path)?; + let top = Volume::of(&dir)?; + remove_contents(&dir, &top, path)?; + fs::remove_dir(path) +} + +#[cfg(not(unix))] pub fn remove_permanently(path: &Path) -> io::Result<()> { let meta = fs::symlink_metadata(path)?; if meta.is_dir() { @@ -450,18 +717,166 @@ pub fn remove_permanently(path: &Path) -> io::Result<()> { } } +/// Where a directory lives, as far as crossing into another filesystem goes. +#[cfg(unix)] +struct Volume { + device: rustix::fs::Stat, + /// The mount the directory belongs to, where the kernel reports it (Linux, + /// `statx`). See [`Self::contains`]. + mount: Option, +} + +#[cfg(unix)] +impl Volume { + fn of(dir: &std::os::fd::OwnedFd) -> io::Result { + Ok(Self { + device: rustix::fs::fstat(dir)?, + mount: mount_id(dir), + }) + } + + /// Whether `other` is on the same mount. Where the kernel names mounts, + /// that decides: a btrfs subvolume that is not mounted has its own + /// `st_dev` but is the same mount, and the scan showed it as part of the + /// volume, so it goes with the directory it is in; a bind mount keeps + /// `st_dev` but is a mount of its own, and stops the removal. Without + /// mount IDs (macOS) the device decides. + const fn contains(&self, other: &Self) -> bool { + match (self.mount, other.mount) { + (Some(one), Some(two)) => one == two, + _ => self.device.st_dev == other.device.st_dev, + } + } +} + +#[cfg(target_os = "linux")] +fn mount_id(dir: &std::os::fd::OwnedFd) -> Option { + use rustix::fs::{AtFlags, StatxFlags, statx}; + statx(dir, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID) + .ok() + .filter(|stat| stat.stx_mask & StatxFlags::MNT_ID.bits() != 0) + .map(|stat| stat.stx_mnt_id) +} + +#[cfg(all(unix, not(target_os = "linux")))] +const fn mount_id(_dir: &std::os::fd::OwnedFd) -> Option { + None +} + +#[cfg(unix)] +fn open_dir( + parent: impl std::os::fd::AsFd, + name: P, +) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, openat}; + openat( + parent, + name, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) +} + +/// Empty the directory open at `dir`, staying on the volume of `top`. +#[cfg(unix)] +fn remove_contents( + dir: &std::os::fd::OwnedFd, + top: &Volume, + path: &Path, +) -> io::Result<()> { + use rustix::fs::{AtFlags, Dir, FileType, unlinkat}; + use rustix::io::Errno; + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt as _; + + // Names first, then removal: unlinking while a directory stream is open + // on the same directory may skip entries. + let mut entries = Vec::new(); + for entry in Dir::read_from(dir)? { + let entry = entry?; + let name = entry.file_name(); + if name != c"." && name != c".." { + entries.push((name.to_owned(), entry.file_type())); + } + } + + for (name, kind) in entries { + if !matches!(kind, FileType::Directory | FileType::Unknown) { + unlinkat(dir, &name, AtFlags::empty())?; + continue; + } + let child = match open_dir(dir, &name) { + Ok(child) => child, + // Not a directory after all: a symlink, or a file on a + // filesystem that does not report types. + Err(Errno::NOTDIR | Errno::LOOP) => { + unlinkat(dir, &name, AtFlags::empty())?; + continue; + } + Err(error) => return Err(error.into()), + }; + // Only directories need their path, for the message below. + let child_path = path.join(OsStr::from_bytes(name.to_bytes())); + if !top.contains(&Volume::of(&child)?) { + return Err(io::Error::other(format!( + "stopped at {}: another filesystem is mounted there, and \ + nothing on it was touched", + child_path.display() + ))); + } + remove_contents(&child, top, &child_path)?; + drop(child); + unlinkat(dir, &name, AtFlags::REMOVEDIR)?; + } + Ok(()) +} + /// Move one path to the desktop trash. pub fn move_to_trash(path: &Path, backend: TrashBackend) -> io::Result<()> { match backend { TrashBackend::TrashPut => run_tool(Path::new("trash-put"), &[], path), TrashBackend::Gio => run_tool(Path::new("gio"), &["trash"], path), TrashBackend::XdgHome => trash_via_xdg(path), + TrashBackend::MacOs => trash_via_macos(path), TrashBackend::Unavailable => Err(io::Error::other( "no trash tool is installed; use permanent deletion instead", )), } } +/// Move one path to the macOS Trash. +/// +/// The `trash` crate resolves the parent directory and keeps the final name, +/// so a symlink is trashed itself and its target is left alone. A name that is +/// not UTF-8 is refused rather than handed over: the crate would +/// percent-encode it into a different path. +#[cfg(target_os = "macos")] +fn trash_via_macos(path: &Path) -> io::Result<()> { + use trash::macos::{DeleteMethod, TrashContextExtMacos as _}; + + if path.to_str().is_none() { + return Err(io::Error::other( + "the name is not UTF-8, which the Trash cannot take; \ + use permanent deletion", + )); + } + let mut context = trash::TrashContext::default(); + // Finder's method asks for permission to control Finder and plays a + // sound per call; NSFileManager does neither. + context.set_delete_method(DeleteMethod::NsFileManager); + context.delete(path).map_err(|error| { + io::Error::other(format!( + "could not move to the Trash ({error}); network and read-only \ + disks have none, so use permanent deletion there" + )) + }) +} + +#[cfg(not(target_os = "macos"))] +fn trash_via_macos(_path: &Path) -> io::Result<()> { + Err(io::Error::other("the macOS Trash only exists on macOS")) +} + /// Run one trash tool on one path. /// /// `--` is passed before the path so that a file named `-rf` is read as a path @@ -599,6 +1014,11 @@ mod tests { } } + /// [`system_tree`] for plain paths, keyed the way [`refuse`] keys them. + fn tree_of(path: &Path, home: &Path) -> Option<&'static str> { + system_tree(&guard_key(path), Some(&guard_key(home))) + } + fn tree() -> TempDir { let temp = TempDir::new().expect("tempdir"); fs::create_dir_all(temp.path().join("a/b")).expect("mkdir"); @@ -690,6 +1110,217 @@ mod tests { } } + #[test] + fn a_directory_holding_the_home_directory_is_refused() { + // /Users in a whole-disk scan on macOS: the same volume as /, so no + // mount point, and removing it would empty home first. + let home = Path::new("/Users/tobi"); + let reason = refuse( + Path::new("/Users"), + Path::new("/"), + Some(&Home::of(home)), + &[], + ) + .expect("refused"); + assert!(reason.contains("home directory"), "{reason}"); + assert!( + refuse( + Path::new("/Users/tobi/src"), + Path::new("/"), + Some(&Home::of(home)), + &[] + ) + .is_none(), + "inside home is the user's" + ); + } + + #[test] + fn a_directory_holding_a_system_tree_is_refused() { + let home = Path::new("/Users/tobi"); + for (path, inside) in [("/opt", "/opt/homebrew"), ("/var", "/var/lib")] + { + let reason = refuse( + Path::new(path), + Path::new("/"), + Some(&Home::of(home)), + &[], + ) + .expect("refused"); + assert!(reason.contains(inside), "{path}: {reason}"); + } + assert!( + refuse( + Path::new("/opt/local"), + Path::new("/"), + Some(&Home::of(home)), + &[] + ) + .is_none(), + "a sibling of a system tree is not its parent" + ); + } + + #[test] + fn a_target_with_a_mount_inside_is_refused() { + let temp = tree(); + let root = temp.path(); + let mounts = + vec![guard_key(&root.join("a/b")), guard_key(&root.join("other"))]; + assert_eq!( + mount_below(&guard_key(&root.join("a")), &mounts), + Some(guard_key(&root.join("a/b")).as_path()) + ); + assert_eq!( + mount_below(&guard_key(&root.join("a/b")), &mounts), + None, + "itself" + ); + let reason = + refuse(&root.join("a"), root, None, &mounts).expect("refused"); + assert!(reason.contains("mounted inside"), "{reason}"); + assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None); + } + + #[test] + fn nothing_is_mounted_below_a_temp_dir() { + let temp = tree(); + assert_eq!( + mount_below(&guard_key(temp.path()), &read_mount_points()), + None + ); + } + + #[test] + #[cfg(target_os = "macos")] + fn this_macs_mount_table_is_read_without_proc() { + let mounts = read_mount_points(); + assert!(mounts.contains(&guard_key(Path::new("/"))), "{mounts:?}"); + // Asked of `mount_below` itself: `refuse` would turn /System/Volumes + // away as a system tree before it looked at the mounts. + assert!( + mount_below(&guard_key(Path::new("/System/Volumes")), &mounts) + .is_some(), + "the Data volume is mounted there" + ); + } + + #[test] + fn the_mount_table_is_read_off_the_calling_thread_and_then_kept() { + prime_mount_points(); + // The first read lands on its own thread; wait for it, briefly. + let mut mounts = mount_points(); + for _ in 0..500 { + if !mounts.is_empty() { + break; + } + thread::sleep(std::time::Duration::from_millis(10)); + mounts = mount_points(); + } + assert_eq!(*mounts, read_mount_points(), "the same table, cached"); + } + + #[test] + #[cfg(unix)] + fn a_volume_is_judged_by_its_mount_where_the_kernel_names_one() { + let temp = tree(); + let dir = open_dir(rustix::fs::CWD, temp.path()).expect("open"); + let here = Volume::of(&dir).expect("volume"); + let mut other = Volume::of(&dir).expect("volume"); + assert!(here.contains(&other)); + // A btrfs subvolume: another device, the same mount. + other.device.st_dev = other.device.st_dev.wrapping_add(1); + other.mount = Some(7); + let mount = Volume { + device: here.device, + mount: Some(7), + }; + assert!(mount.contains(&other), "same mount, other device"); + // A bind mount: the same device, another mount. + let bind = Volume { + device: here.device, + mount: Some(8), + }; + assert!(!mount.contains(&bind)); + // No mount IDs, as on macOS: the device decides. + let (mut plain, mut moved) = ( + Volume::of(&dir).expect("volume"), + Volume::of(&dir).expect("volume"), + ); + plain.mount = None; + moved.mount = None; + moved.device.st_dev = moved.device.st_dev.wrapping_add(1); + assert!(!plain.contains(&moved)); + } + + #[test] + fn macos_guard_keys_fold_the_data_volume_and_case() { + let key = |path: &str| guard_key_for(Path::new(path), true); + assert_eq!( + key("/System/Volumes/Data/Users/Tobi/src"), + PathBuf::from("/users/tobi/src") + ); + assert_eq!(key("/Library/./Caches"), PathBuf::from("/library/caches")); + assert_eq!( + key("/System/Volumes/Data"), + PathBuf::from("/system/volumes/data"), + "the Data volume itself stays under /System" + ); + assert_eq!( + guard_key_for(Path::new("/Library/X"), false), + PathBuf::from("/Library/X"), + "Linux paths are compared as spelled" + ); + } + + #[test] + #[cfg(target_os = "macos")] + fn macos_guards_see_through_other_spellings() { + let home = Path::new("/Users/tobi"); + let data = Path::new(crate::space::MACOS_DATA_VOLUME); + assert!( + refuse( + &data.join("Users/tobi/src"), + data, + Some(&Home::of(home)), + &[] + ) + .is_none(), + "home under the Data volume's name is still home" + ); + let reason = refuse( + Path::new("/library/caches"), + Path::new("/"), + Some(&Home::of(home)), + &[], + ) + .expect("refused"); + assert!(reason.contains("/Library"), "{reason}"); + } + + #[test] + fn permanent_removal_takes_nested_trees_and_hidden_files() { + let temp = tree(); + let doomed = temp.path().join("a"); + fs::create_dir_all(doomed.join("b/c/d")).expect("mkdir"); + fs::write(doomed.join("b/c/d/.hidden"), "x").expect("write"); + fs::write(doomed.join("b/c/f"), "x").expect("write"); + remove_permanently(&doomed).expect("remove tree"); + assert!(!doomed.exists()); + assert!(temp.path().join("other").exists()); + } + + #[test] + fn permanent_removal_unlinks_nested_symlinks_without_following_them() { + let temp = tree(); + let outside = TempDir::new().expect("tempdir"); + fs::write(outside.path().join("keep"), "x").expect("write"); + std::os::unix::fs::symlink(outside.path(), temp.path().join("a/link")) + .expect("symlink"); + remove_permanently(&temp.path().join("a")).expect("remove tree"); + assert!(outside.path().join("keep").exists()); + } + #[test] fn permanent_removal_takes_directories_and_leaves_siblings() { let temp = tree(); @@ -873,6 +1504,7 @@ mod tests { } #[test] + #[cfg(not(target_os = "macos"))] fn detection_prefers_a_tool_this_machine_has() { let backend = detect_trash_backend(); if which("trash-put") { @@ -881,34 +1513,92 @@ mod tests { assert!(backend.is_available()); } + #[test] + #[cfg(target_os = "macos")] + fn macos_always_uses_the_system_trash() { + // Whatever Homebrew put on PATH: its trash tools write a trash + // Finder never shows. + assert_eq!(detect_trash_backend(), TrashBackend::MacOs); + assert!(TrashBackend::MacOs.is_available()); + } + + #[test] + #[cfg(target_os = "macos")] + #[ignore = "puts a file in this Mac's real Trash"] + fn the_macos_trash_takes_a_file_and_leaves_a_linked_target() { + let temp = TempDir::new().expect("tempdir"); + let file = temp.path().join("disktree-trash-check.txt"); + fs::write(&file, b"x").expect("write"); + let keep = temp.path().join("keep.txt"); + fs::write(&keep, b"kept").expect("write"); + let link = temp.path().join("disktree-trash-check-link"); + std::os::unix::fs::symlink(&keep, &link).expect("symlink"); + + move_to_trash(&file, TrashBackend::MacOs).expect("trashed"); + move_to_trash(&link, TrashBackend::MacOs).expect("trashed"); + + assert!(!file.exists()); + assert!(fs::symlink_metadata(&link).is_err(), "the link went"); + assert_eq!(fs::read(&keep).expect("read"), b"kept", "not its target"); + } + + #[test] + #[cfg(target_os = "macos")] + fn a_name_that_is_not_utf8_is_refused_before_the_trash_sees_it() { + use std::os::unix::ffi::OsStrExt as _; + let temp = TempDir::new().expect("tempdir"); + let odd = temp + .path() + .join(std::ffi::OsStr::from_bytes(b"not-\xff-utf8")); + let error = trash_via_macos(&odd).expect_err("refused"); + assert!(error.to_string().contains("UTF-8"), "{error}"); + } + #[test] fn system_trees_are_refused_in_a_whole_disk_scan() { let home = Path::new("/home/tobi"); assert_eq!( - system_tree(Path::new("/usr/lib/libfoo.so"), Some(home)), + tree_of(Path::new("/usr/lib/libfoo.so"), home), Some("/usr") ); assert_eq!( - system_tree(Path::new("/var/lib/pacman"), Some(home)), + tree_of(Path::new("/var/lib/pacman"), home), Some("/var/lib") ); + assert_eq!(tree_of(Path::new("/var/cache/pacman/pkg"), home), None); + assert_eq!(tree_of(Path::new("/opt/thing"), home), None); assert_eq!( - system_tree(Path::new("/var/cache/pacman/pkg"), Some(home)), - None - ); - assert_eq!(system_tree(Path::new("/opt/thing"), Some(home)), None); - assert_eq!( - system_tree(Path::new("/usrlocal"), Some(home)), + tree_of(Path::new("/usrlocal"), home), None, "components, not prefixes" ); let odd_home = Path::new("/usr/home/tobi"); - assert_eq!( - system_tree(Path::new("/usr/home/tobi/.cache"), Some(odd_home)), - None + assert_eq!(tree_of(Path::new("/usr/home/tobi/.cache"), odd_home), None); + let reason = refuse( + Path::new("/etc/hosts"), + Path::new("/"), + Some(&Home::of(home)), + &[], ); - let reason = - refuse(Path::new("/etc/hosts"), Path::new("/"), Some(home)); assert!(reason.is_some_and(|reason| reason.contains("/etc"))); } + + #[test] + fn macos_system_trees_are_refused_but_apps_are_not() { + let home = Path::new("/Users/tobi"); + for (path, tree) in [ + ("/System/Library/Fonts", "/System"), + ("/Library/Caches/com.apple.x", "/Library"), + ("/private/etc/hosts", "/private"), + ("/private/var/folders/xy", "/private"), + ("/opt/homebrew/Cellar/git", "/opt/homebrew"), + ] { + assert_eq!(tree_of(Path::new(path), home), Some(tree)); + } + // An app is uninstalled by moving it to the Trash, and a user's own + // Library is theirs. + for path in ["/Applications/Xcode.app", "/Users/tobi/Library/Caches"] { + assert_eq!(tree_of(Path::new(path), home), None, "{path}"); + } + } } diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index be5f2ff..42f150d 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -114,10 +114,11 @@ impl ScanProgress { fn record_error(&self, path: &Path, error: &io::Error) { self.errors.fetch_add(1, Ordering::Relaxed); - let message = format!("{}: {error}", path.display()); + // A scan without Full Disk Access can refuse thousands of paths; + // only the ones that will be kept are worth formatting. let mut messages = lock(&self.messages); if messages.len() < MAX_ERROR_DETAIL { - messages.push(message); + messages.push(format!("{}: {error}", path.display())); } drop(messages); } @@ -185,6 +186,7 @@ impl ScanHandle { progress: Arc::clone(&progress), root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), + never_scanned: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), root: Mutex::new(None), }); @@ -233,6 +235,7 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result { progress: Arc::clone(&progress), root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), + never_scanned: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), root: Mutex::new(None), }); @@ -252,6 +255,9 @@ struct WalkContext { /// Mount points `one_filesystem` keeps out, from the mount table. Unset /// when the table cannot be read, and devices are compared instead. foreign_mounts: OnceLock>, + /// Directories no scan enters, on any volume setting: see + /// [`crate::space::never_scanned`]. + never_scanned: OnceLock>, /// Directories already entered, so followed symlinks cannot loop. visited_dirs: Mutex>, /// Set by the root's `complete`, read after the scope joins. @@ -297,6 +303,23 @@ impl WalkContext { } if file_type.is_dir() { + if self + .never_scanned + .get() + .is_some_and(|never| never.contains(&path)) + { + return Classified::Skipped; + } + // `lstat` at most once per directory: macOS reads the dataless + // flag from it, and the device check below needs it wherever the + // mount table cannot be read, which on macOS is everywhere. + let meta_cell = std::cell::OnceCell::new(); + let meta = || meta_cell.get_or_init(|| entry.metadata()); + if cfg!(target_os = "macos") + && meta().as_ref().is_ok_and(is_dataless) + { + return Classified::Skipped; + } // Memoized: the subtree a narrower scan already measured is // taken whole, before any volume rule, since it was measured // under the same rules. @@ -320,18 +343,18 @@ impl WalkContext { return Classified::Skipped; } } else if self.options.one_filesystem { - let device = entry.metadata().map(|meta| device_of(&meta)); - match (device, self.root_device(&path)) { - (Ok(device), Some(root_device)) - if device != root_device => - { + let device = match meta() { + Ok(meta) => device_of(meta), + Err(error) => { + self.progress.record_error(&path, error); return Classified::Skipped; } - (Err(error), _) => { - self.progress.record_error(&path, &error); - return Classified::Skipped; - } - _ => {} + }; + if self + .root_device(&path) + .is_some_and(|root_device| device != root_device) + { + return Classified::Skipped; } } self.progress.count_dir(); @@ -360,6 +383,7 @@ impl WalkContext { NodeKind::Symlink, size, &meta, + shares_inode(&meta), )) } Err(error) => { @@ -381,6 +405,11 @@ impl WalkContext { }; if meta.is_dir() { + // A link into an evicted cloud folder is left alone for the + // same reason the folder itself is. + if is_dataless(&meta) { + return Classified::Skipped; + } if let Some(key) = file_identity(&meta) && !lock(&self.visited_dirs).insert(key) { @@ -401,7 +430,10 @@ impl WalkContext { ) -> Classified { let size = measure(meta, self.options.apparent_size); self.progress.count_file(size); - Classified::Entry(leaf_node(name, kind, size, meta)) + // A followed link reaches a file a second way, whatever its link + // count says. + let track = self.options.follow_links || shares_inode(meta); + Classified::Entry(leaf_node(name, kind, size, meta, track)) } } @@ -478,10 +510,12 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { format!("{} is not a directory", root.display()), )); } + let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + let never = crate::space::never_scanned(root, &canonical); + let _ = context.never_scanned.set(never.into_iter().collect()); if context.options.one_filesystem { *lock(&context.root_device) = Some(device_of(&root_meta)); - let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); - if let Some(foreign) = crate::space::foreign_mounts_for(&root) { + if let Some(foreign) = crate::space::foreign_mounts_for(&canonical) { let _ = context.foreign_mounts.set(foreign.into_iter().collect()); } } @@ -607,14 +641,20 @@ fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) { } } +/// A leaf. Its `(device, inode)` is kept only when `track` says the walk +/// could meet the same file again: a hardlink de-duplication set of every +/// file on a disk is millions of entries, nearly all for files with one name. fn leaf_node( name: Box, kind: NodeKind, size: u64, meta: &Metadata, + track: bool, ) -> Node { let mut node = Node::entry(name, kind, size); - node.inode = file_identity(meta); + if track { + node.inode = file_identity(meta); + } node.modified = modified_seconds(meta); node } @@ -658,6 +698,37 @@ fn allocated_bytes(_meta: &Metadata) -> Option { None } +/// Whether a directory's contents are only in the cloud: an iCloud Drive or +/// File Provider folder macOS has evicted. Listing one makes macOS fetch its +/// entries from the server, so a disk scan must not; the folder holds no +/// local blocks, so skipping it loses nothing a scan measures. +/// +/// A `stat` or `lstat` carries the flag without touching the contents. +#[cfg(target_os = "macos")] +fn is_dataless(meta: &Metadata) -> bool { + use std::os::macos::fs::MetadataExt as _; + // `SF_DATALESS` from ; the libc crate does not name it. + const SF_DATALESS: u32 = 0x4000_0000; + meta.st_flags() & SF_DATALESS != 0 +} + +#[cfg(not(target_os = "macos"))] +const fn is_dataless(_meta: &Metadata) -> bool { + false +} + +/// Whether the file has more than one name, so the walk can count it twice. +#[cfg(unix)] +fn shares_inode(meta: &Metadata) -> bool { + use std::os::unix::fs::MetadataExt as _; + meta.nlink() > 1 +} + +#[cfg(not(unix))] +const fn shares_inode(_meta: &Metadata) -> bool { + false +} + #[cfg(unix)] fn device_of(meta: &Metadata) -> u64 { use std::os::unix::fs::MetadataExt as _; @@ -948,6 +1019,7 @@ mod tests { progress: Arc::clone(&progress), root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), + never_scanned: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), root: Mutex::new(None), }); diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs index 008eec3..22aab9b 100644 --- a/crates/disktree-core/src/space.rs +++ b/crates/disktree-core/src/space.rs @@ -69,6 +69,7 @@ pub fn space_info(path: &Path) -> io::Result { /// The device a path's filesystem is mounted from, such as /// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in /// `/proc/self/mounts`. `None` where that table cannot be read. +#[cfg(not(target_os = "macos"))] pub fn device_for(path: &Path) -> Option { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); @@ -186,6 +187,7 @@ pub fn volume_root(mounts: &[Mount], path: &Path) -> Option { } /// [`volume_root`] for this machine. +#[cfg(not(target_os = "macos"))] pub fn volume_root_for(path: &Path) -> Option { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); @@ -199,6 +201,98 @@ pub fn foreign_mounts_for(root: &Path) -> Option> { Some(foreign_mounts(&parse_mounts(&table), root)) } +/// The mount points in what macOS's `mount` prints. +/// +/// One per line: `/dev/disk3s5 on /System/Volumes/Data (apfs, local, …)`. +/// The point is +/// between the first ` on ` and the last ` (`, so a name with spaces or +/// brackets in it survives. +pub fn parse_macos_mounts(output: &str) -> Vec { + output + .lines() + .filter_map(|line| { + let (_, rest) = line.split_once(" on ")?; + let (point, _) = rest.rsplit_once(" (")?; + Some(PathBuf::from(point)) + }) + .collect() +} + +/// Where the Data volume is mounted on macOS. +/// +/// Since Catalina `/` is a read-only system volume, and everything the user +/// can write — `/Users`, +/// `/Applications`, `/Library`, `/private`, … — lives on the Data volume, +/// joined into `/` by firmlinks. The two report the same device, and +/// `/Users` and `/System/Volumes/Data/Users` are the same inode. +pub const MACOS_DATA_VOLUME: &str = "/System/Volumes/Data"; + +/// Directories under `root` a scan must never enter, whatever the volume +/// rules say, given where `root` really is (`canonical`). +/// +/// On macOS: the Data volume's second mount, which is every firmlinked +/// directory again under another name, so walking it counts the disk twice; +/// and `/Network`, an automount point that would reach for a server. The +/// paths are returned in `root`'s own spelling, because that is how the walk +/// names what it finds. +pub fn never_scanned(root: &Path, canonical: &Path) -> Vec { + if !cfg!(target_os = "macos") { + return Vec::new(); + } + [MACOS_DATA_VOLUME, "/Network"] + .iter() + .filter_map(|skip| Path::new(skip).strip_prefix(canonical).ok()) + .filter(|below| !below.as_os_str().is_empty()) + .map(|below| root.join(below)) + .collect() +} + +/// The top of the disk `path` lives on: its mount point, from `statfs`. +/// +/// The Data volume answers `/System/Volumes/Data`, but the disk a user +/// thinks of is `/`, which shows the same files under the names Finder uses +/// and adds the system volume beside them. +#[cfg(target_os = "macos")] +pub fn volume_root_for(path: &Path) -> Option { + let stat = rustix::fs::statfs(path).ok()?; + let mount = PathBuf::from(c_chars(&stat.f_mntonname)); + if mount.as_os_str().is_empty() { + return None; + } + Some(if mount == Path::new(MACOS_DATA_VOLUME) { + PathBuf::from("/") + } else { + mount + }) +} + +/// The device a path's filesystem is mounted from, such as +/// `/dev/disk3s5`, from `statfs`. +#[cfg(target_os = "macos")] +pub fn device_for(path: &Path) -> Option { + // `/` is a snapshot of the system volume (`disk3s1s1`); name the disk + // the user's files are on instead, which is what the meter measures. + let path = if path == Path::new("/") { + Path::new(MACOS_DATA_VOLUME) + } else { + path + }; + let stat = rustix::fs::statfs(path).ok()?; + let device = c_chars(&stat.f_mntfromname); + (!device.is_empty()).then_some(device) +} + +/// A NUL-terminated C string field as text. +#[cfg(target_os = "macos")] +fn c_chars(field: &[std::ffi::c_char]) -> String { + let bytes: Vec = field + .iter() + .take_while(|&&byte| byte != 0) + .map(|&byte| byte as u8) + .collect(); + String::from_utf8_lossy(&bytes).into_owned() +} + #[cfg(test)] mod tests { use super::*; @@ -271,6 +365,67 @@ tmpfs /tmp tmpfs rw 0 0 ); } + #[test] + fn macos_mount_points_keep_spaces_and_brackets() { + let output = "\ +/dev/disk3s1s1 on / (apfs, sealed, local, read-only, journaled) +devfs on /dev (devfs, local, nobrowse) +/dev/disk3s5 on /System/Volumes/Data (apfs, local, journaled, nobrowse) +map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse) +/dev/disk5s1 on /Volumes/My Disk (2) (apfs, local, nodev, nosuid) +//tobi@nas/share on /Volumes/share on nas (smbfs, nodev, nosuid) +"; + let points: Vec = [ + "/", + "/dev", + MACOS_DATA_VOLUME, + "/System/Volumes/Data/home", + "/Volumes/My Disk (2)", + "/Volumes/share on nas", + ] + .iter() + .map(PathBuf::from) + .collect(); + assert_eq!(parse_macos_mounts(output), points); + } + + #[test] + fn only_macos_skips_the_data_volume_and_in_the_roots_spelling() { + let skipped = never_scanned(Path::new("/"), Path::new("/")); + let below_system = + never_scanned(Path::new("/System/"), Path::new("/System")); + let inside = + never_scanned(Path::new("/Users/tobi"), Path::new("/Users/tobi")); + let itself = never_scanned( + Path::new(MACOS_DATA_VOLUME), + Path::new(MACOS_DATA_VOLUME), + ); + if cfg!(target_os = "macos") { + assert_eq!( + skipped, + vec![PathBuf::from(MACOS_DATA_VOLUME), "/Network".into()] + ); + assert_eq!( + below_system, + vec![PathBuf::from("/System/Volumes/Data")] + ); + } else { + assert!(skipped.is_empty() && below_system.is_empty()); + } + assert!(inside.is_empty()); + assert!(itself.is_empty(), "asking for it by name scans it"); + } + + #[test] + #[cfg(target_os = "macos")] + fn the_home_disk_on_macos_is_the_root_and_has_a_device() { + let home = std::env::var_os("HOME").map(PathBuf::from); + let home = home.expect("HOME is set"); + assert_eq!(volume_root_for(&home), Some(PathBuf::from("/"))); + let device = device_for(Path::new("/")).expect("a device"); + assert!(device.starts_with("/dev/disk"), "{device}"); + } + #[test] fn a_real_volume_reports_plausible_numbers() { let temp = std::env::temp_dir(); diff --git a/packaging/macos/AppIcon.svg b/packaging/macos/AppIcon.svg new file mode 100644 index 0000000..4732a05 --- /dev/null +++ b/packaging/macos/AppIcon.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in new file mode 100644 index 0000000..7e87cda --- /dev/null +++ b/packaging/macos/Info.plist.in @@ -0,0 +1,48 @@ + + + + + + CFBundleIdentifier + io.github.tobi.disktree + CFBundleName + disktree + CFBundleDisplayName + disktree + CFBundleExecutable + disktree + CFBundleIconFile + AppIcon + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + CFBundleShortVersionString + @VERSION@ + CFBundleVersion + @VERSION@ + LSMinimumSystemVersion + 11.0 + LSApplicationCategoryType + public.app-category.utilities + NSHighResolutionCapable + + NSHumanReadableCopyright + MIT License + + NSDesktopFolderUsageDescription + disktree measures the Desktop folder to show what is using your disk. It reads sizes and names only. + NSDocumentsFolderUsageDescription + disktree measures the Documents folder to show what is using your disk. It reads sizes and names only. + NSDownloadsFolderUsageDescription + disktree measures the Downloads folder to show what is using your disk. It reads sizes and names only. + NSRemovableVolumesUsageDescription + disktree measures removable disks you scan to show what is using them. It reads sizes and names only. + NSNetworkVolumesUsageDescription + disktree measures network disks you scan to show what is using them. It reads sizes and names only. + + diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 6120e59..3571573 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true rust-version.workspace = true license.workspace = true publish = false -description = "Check entry points for disktree: one command per gate" +description = "Check and packaging entry points for disktree: one command per gate" [lints] workspace = true diff --git a/xtask/src/bundle.rs b/xtask/src/bundle.rs new file mode 100644 index 0000000..63e3113 --- /dev/null +++ b/xtask/src/bundle.rs @@ -0,0 +1,339 @@ +//! `cargo xtask bundle`: the macOS app, from a release build. +//! +//! Plain Apple tools and nothing to install: `sips` and `iconutil` draw the +//! icon from its SVG, `codesign` signs, `ditto` zips the way Finder does +//! (keeping the signature's extended attributes), and `notarytool` and +//! `stapler` notarize. Everything lands in `target/bundle/`. +//! +//! Signing is ad hoc unless an identity is given. An ad-hoc app runs on the +//! Mac that built it; a downloaded one needs a Developer ID signature and +//! notarization, or Gatekeeper stops it. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +const APP: &str = "disktree.app"; +const EXECUTABLE: &str = "disktree"; +/// What the binary is built for at least; `LSMinimumSystemVersion` in +/// `packaging/macos/Info.plist.in` says the same, and GPUI needs 10.15.7. +const DEPLOYMENT_TARGET: &str = "11.0"; + +/// The iconset `iconutil` expects: each point size at 1x and 2x. +const ICON_SIZES: [(&str, u32); 10] = [ + ("icon_16x16.png", 16), + ("icon_16x16@2x.png", 32), + ("icon_32x32.png", 32), + ("icon_32x32@2x.png", 64), + ("icon_128x128.png", 128), + ("icon_128x128@2x.png", 256), + ("icon_256x256.png", 256), + ("icon_256x256@2x.png", 512), + ("icon_512x512.png", 512), + ("icon_512x512@2x.png", 1024), +]; + +/// What `bundle` was asked to do. +#[derive(Debug, Default)] +struct Options { + /// A `Developer ID Application: …` identity from the keychain; ad hoc + /// when absent. + identity: Option, + notarize: bool, +} + +fn parse(args: &[String]) -> Result { + let mut options = Options::default(); + let mut args = args.iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--sign" => { + let identity = args + .next() + .ok_or("--sign needs an identity, e.g. \"Developer ID Application: Name (TEAMID)\"")?; + // An empty identity is what CI passes when a secret is + // missing; codesign would fail on it without saying why. + if identity.trim().is_empty() { + return Err("--sign got an empty identity".into()); + } + options.identity = Some(identity.clone()); + } + "--notarize" => options.notarize = true, + other => return Err(format!("unknown bundle option {other}")), + } + } + if options.notarize && options.identity.is_none() { + return Err("--notarize needs --sign: Apple notarizes Developer ID \ + signatures only" + .into()); + } + Ok(options) +} + +pub fn bundle(args: &[String]) -> Result<(), String> { + if !cfg!(target_os = "macos") { + return Err("the app bundle is built on macOS".into()); + } + let options = parse(args)?; + let root = workspace_root(); + let version = env!("CARGO_PKG_VERSION"); + let out = root.join("target/bundle"); + let app = out.join(APP); + + // The target directory is named rather than inherited: a + // `CARGO_TARGET_DIR` or `build.target-dir` elsewhere would put the fresh + // binary there and leave a stale one here to be bundled. + let target = root.join("target"); + let cargo = option_env!("CARGO").unwrap_or("cargo"); + tool( + Command::new(cargo) + .current_dir(&root) + .args(["build", "--release", "--locked", "-p", "disktree-app"]) + .arg("--target-dir") + .arg(&target) + .env("MACOSX_DEPLOYMENT_TARGET", DEPLOYMENT_TARGET), + )?; + + // Only ever the bundle this task made, never anything else in target/. + if app.exists() { + fs::remove_dir_all(&app) + .map_err(|err| format!("cannot clear {}: {err}", app.display()))?; + } + let contents = app.join("Contents"); + let macos = contents.join("MacOS"); + let resources = contents.join("Resources"); + for dir in [&macos, &resources] { + fs::create_dir_all(dir) + .map_err(|err| format!("cannot create {}: {err}", dir.display()))?; + } + + let binary = macos.join(EXECUTABLE); + copy(&target.join("release").join(EXECUTABLE), &binary)?; + // Local symbols only: the backtrace of a panic still names functions. + tool(Command::new("strip").arg("-x").arg(&binary))?; + + let plist = fs::read_to_string(root.join("packaging/macos/Info.plist.in")) + .map_err(|err| format!("cannot read the Info.plist template: {err}"))?; + write( + &contents.join("Info.plist"), + &plist.replace("@VERSION@", version), + )?; + tool( + Command::new("plutil") + .arg("-lint") + .arg(contents.join("Info.plist")), + )?; + + icon( + &root.join("packaging/macos/AppIcon.svg"), + &out, + &resources.join("AppIcon.icns"), + )?; + + sign(&app, options.identity.as_deref())?; + + let zip = out.join(format!( + "disktree-{version}-{}-macos.zip", + std::env::consts::ARCH + )); + archive(&app, &zip)?; + + if options.notarize { + notarize(&zip)?; + // The ticket is stapled to the app, so zip it again: a zip itself + // cannot carry one. + tool(Command::new("xcrun").args(["stapler", "staple"]).arg(&app))?; + archive(&app, &zip)?; + tool( + Command::new("spctl") + .args(["--assess", "--type", "execute", "-vv"]) + .arg(&app), + )?; + } + + println!("\n{}\n{}", app.display(), zip.display()); + Ok(()) +} + +/// `AppIcon.icns` from the SVG, through an iconset of every size. +fn icon(svg: &Path, scratch: &Path, icns: &Path) -> Result<(), String> { + let iconset = scratch.join("AppIcon.iconset"); + if iconset.exists() { + fs::remove_dir_all(&iconset).map_err(|err| { + format!("cannot clear {}: {err}", iconset.display()) + })?; + } + fs::create_dir_all(&iconset) + .map_err(|err| format!("cannot create {}: {err}", iconset.display()))?; + for (name, pixels) in ICON_SIZES { + let pixels = pixels.to_string(); + tool( + Command::new("sips") + .args(["-s", "format", "png", "-z", &pixels, &pixels]) + .arg(svg) + .arg("--out") + .arg(iconset.join(name)) + // sips names every file it writes; the errors still show. + .stdout(Stdio::null()), + )?; + } + tool( + Command::new("iconutil") + .args(["-c", "icns"]) + .arg(&iconset) + .arg("-o") + .arg(icns), + ) +} + +/// Sign the bundle, then check the signature holds. +/// +/// A real identity gets the hardened runtime and a secure timestamp, both of +/// which notarization requires. No entitlements: the app needs none of what +/// the hardened runtime withholds, and the Trash is reached through +/// `NSFileManager`, which asks for no permission. +fn sign(app: &Path, identity: Option<&str>) -> Result<(), String> { + let mut command = Command::new("codesign"); + command.arg("--force"); + match identity { + Some(identity) => { + command + .args(["--timestamp", "--options", "runtime", "--sign"]) + .arg(identity); + } + None => { + command.args(["--sign", "-"]); + } + } + tool(command.arg(app))?; + tool( + Command::new("codesign") + .args(["--verify", "--strict", "--verbose=2"]) + .arg(app), + ) +} + +fn archive(app: &Path, zip: &Path) -> Result<(), String> { + if zip.exists() { + fs::remove_file(zip).map_err(|err| { + format!("cannot replace {}: {err}", zip.display()) + })?; + } + tool( + Command::new("ditto") + .args(["-c", "-k", "--sequesterRsrc", "--keepParent"]) + .arg(app) + .arg(zip), + ) +} + +/// Submit `zip` and wait for Apple's verdict. +/// +/// Credentials come from the environment, never the command line, so they +/// stay out of shell history and CI logs: `NOTARY_PROFILE`, a keychain +/// profile saved with `xcrun notarytool store-credentials`, or an App Store +/// Connect API key as `NOTARY_KEY` (the `.p8` file), `NOTARY_KEY_ID` and +/// `NOTARY_ISSUER`. +fn notarize(zip: &Path) -> Result<(), String> { + let mut command = Command::new("xcrun"); + command + .args(["notarytool", "submit"]) + .arg(zip) + .arg("--wait"); + if let Ok(profile) = std::env::var("NOTARY_PROFILE") { + command.arg("--keychain-profile").arg(profile); + } else { + let var = |name: &str| { + std::env::var(name).map_err(|_| { + format!( + "--notarize needs NOTARY_PROFILE, or NOTARY_KEY, \ + NOTARY_KEY_ID and NOTARY_ISSUER; {name} is not set" + ) + }) + }; + command + .arg("--key") + .arg(var("NOTARY_KEY")?) + .arg("--key-id") + .arg(var("NOTARY_KEY_ID")?) + .arg("--issuer") + .arg(var("NOTARY_ISSUER")?); + } + tool(&mut command) +} + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .map_or_else(|| PathBuf::from("."), Path::to_path_buf) +} + +fn copy(from: &Path, to: &Path) -> Result<(), String> { + fs::copy(from, to).map(drop).map_err(|err| { + format!("cannot copy {} to {}: {err}", from.display(), to.display()) + }) +} + +fn write(path: &Path, contents: &str) -> Result<(), String> { + fs::write(path, contents) + .map_err(|err| format!("cannot write {}: {err}", path.display())) +} + +/// Run one tool, inheriting the terminal so its own report is seen. +fn tool(command: &mut Command) -> Result<(), String> { + let display = format!("{command:?}"); + let status = command + .stdin(Stdio::null()) + .status() + .map_err(|err| format!("could not start {display}: {err}"))?; + if status.success() { + Ok(()) + } else { + Err(format!("{display} failed")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(list: &[&str]) -> Vec { + list.iter().map(ToString::to_string).collect() + } + + #[test] + fn signing_is_ad_hoc_unless_an_identity_is_given() { + let options = parse(&[]).expect("no options"); + assert!(options.identity.is_none() && !options.notarize); + let options = parse(&args(&["--sign", "Developer ID Application: X"])) + .expect("an identity"); + assert_eq!( + options.identity.as_deref(), + Some("Developer ID Application: X") + ); + } + + #[test] + fn notarizing_needs_a_real_signature() { + let error = parse(&args(&["--notarize"])).expect_err("no identity"); + assert!(error.contains("--sign"), "{error}"); + assert!( + parse(&args(&["--sign"])).is_err(), + "an identity is required" + ); + assert!( + parse(&args(&["--sign", ""])).is_err(), + "an empty identity is not one" + ); + } + + #[test] + fn the_plist_template_names_the_executable_and_takes_the_version() { + let plist = include_str!("../../packaging/macos/Info.plist.in"); + assert!(plist.contains(&format!("{EXECUTABLE}"))); + assert!(plist.contains("@VERSION@")); + assert!( + plist.contains(&format!("{DEPLOYMENT_TARGET}")) + ); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 6f3c3c3..ce225e5 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,4 +1,4 @@ -//! Check entry points for disktree. +//! Check and packaging entry points for disktree. //! //! Each gate is reachable on its own (`cargo xtask fmt`) and through the //! aggregate CI runs (`cargo xtask lint`), mirroring how omatrack exposes every @@ -6,6 +6,8 @@ //! anything: it reports the diff and fails, so a red local run is the same //! signal CI gives. +mod bundle; + use std::process::{Command, ExitCode, Stdio}; const USAGE: &str = "\ @@ -18,6 +20,10 @@ tasks: clippy clippy --workspace --all-targets -- -D warnings test cargo test --workspace ci lint, then test + bundle macOS: target/bundle/disktree.app and its zip + --sign IDENTITY sign with a Developer ID (default: ad hoc) + --notarize notarize and staple; needs NOTARY_PROFILE, or + NOTARY_KEY, NOTARY_KEY_ID and NOTARY_ISSUER "; fn main() -> ExitCode { @@ -31,6 +37,7 @@ fn main() -> ExitCode { "clippy" => clippy(), "test" => test(), "ci" => fmt(false).and_then(|()| clippy()).and_then(|()| test()), + "bundle" => bundle::bundle(&args[1..]), "help" | "-h" | "--help" => { println!("{USAGE}"); return ExitCode::SUCCESS; From f3741c1a5174dacff8ef36cbb9629007061a3f54 Mon Sep 17 00:00:00 2001 From: Oleg Shevchuk Date: Fri, 25 Sep 2026 15:08:55 +0500 Subject: [PATCH 06/17] core: list, measure and remove on Windows disktree-core builds and measures on Windows. `windows.rs` holds what the standard library does not give: a directory listing through GetFileInformationByHandleEx with FileIdExtdDirectoryInfo, which carries each entry's allocation and file id for a whole buffer of entries. Opening every file for those two numbers made a walk of a home directory of 1.3 million files seven times slower (65 s against 9 s); the listing costs what FindNextFileW costs. Where a file system does not implement it (a Samba share answers ERROR_INVALID_LEVEL), the walk falls back to std's listing, with lengths. - Disk usage is the NTFS allocation: whole clusters, less for a compressed or sparse file, nothing for data kept in the file record. - Hardlinks count once on NTFS, keyed by volume serial and file id. FAT ids are documented as not unique and ReFS ids need all 128 bits, so neither is used; there a hardlink counts once per name. - Junctions and mounted folders are links, as std already treats them, so the walk stays on one volume unless links are followed. The whole disk is the drive the profile is on. - Removal refuses Windows, Program Files, ProgramData and what Windows keeps at the top of its drive, comparing names without case. A mounted folder is a mount point. A link to a directory is removed with RemoveDirectoryW, which leaves its target alone. - Move to trash is the Recycle Bin, through the trash crate, which asks the shell to warn before destroying anything it cannot recycle. All unsafe code is in windows.rs, each block with the reason it is sound. On Unix the walk reads the same metadata through the same calls. --- Cargo.lock | 26 + crates/disktree-core/Cargo.toml | 11 +- crates/disktree-core/src/lib.rs | 2 + crates/disktree-core/src/removal.rs | 241 ++++++++- crates/disktree-core/src/scan.rs | 347 +++++++++---- crates/disktree-core/src/space.rs | 38 ++ crates/disktree-core/src/windows.rs | 727 ++++++++++++++++++++++++++++ 7 files changed, 1291 insertions(+), 101 deletions(-) create mode 100644 crates/disktree-core/src/windows.rs diff --git a/Cargo.lock b/Cargo.lock index 4047a24..832669d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1439,6 +1439,9 @@ dependencies = [ "rustc-hash 2.1.3", "rustix", "tempfile", + "trash", + "winapi-util", + "windows-sys 0.61.2", ] [[package]] @@ -7071,6 +7074,23 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "trash" +version = "5.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317" +dependencies = [ + "libc", + "log", + "objc2 0.6.4", + "objc2-foundation 0.3.2", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows 0.62.2", +] + [[package]] name = "triomphe" version = "0.1.16" @@ -7228,6 +7248,12 @@ dependencies = [ "serde", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "usvg" version = "0.45.1" diff --git a/crates/disktree-core/Cargo.toml b/crates/disktree-core/Cargo.toml index 21ac328..9647cb8 100644 --- a/crates/disktree-core/Cargo.toml +++ b/crates/disktree-core/Cargo.toml @@ -12,8 +12,17 @@ workspace = true [dependencies] chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } rayon = { workspace = true } -rustix = { version = "1.1", features = ["fs"] } rustc-hash = { workspace = true } +# rustix has no filesystem calls on Windows; `windows.rs` covers them there. +[target.'cfg(not(windows))'.dependencies] +rustix = { version = "1.1", features = ["fs"] } + +[target.'cfg(windows)'.dependencies] +# The Recycle Bin, through the shell's own file operation. +trash = { version = "5.2.9", default-features = false, features = ["coinit_apartmentthreaded"] } +winapi-util = "0.1.11" +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] } + [dev-dependencies] tempfile = "3" diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rs index d7cdb24..aa2dfce 100644 --- a/crates/disktree-core/src/lib.rs +++ b/crates/disktree-core/src/lib.rs @@ -14,3 +14,5 @@ pub mod size; pub mod space; pub mod tree; pub mod treemap; +#[cfg(windows)] +mod windows; diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index c15ad04..08b4b58 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -10,8 +10,9 @@ //! standard library rather than by shelling out, so no path ever reaches a //! shell and no filename can be misread as an option. //! * [`RemovalMode::Trash`] — move to the desktop trash, using `trash-put`, -//! then `gio trash`, then a built-in XDG implementation. The backend is -//! detected once and named in the UI so the user knows what actually happens. +//! then `gio trash`, then a built-in XDG implementation; on Windows, the +//! Recycle Bin. The backend is detected once and named in the UI so the +//! user knows what actually happens. use std::fs; use std::io; @@ -22,6 +23,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{self, Receiver}; use std::thread; +#[cfg(windows)] +use crate::windows::{same, within}; + /// One path the user asked to remove. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Target { @@ -92,7 +96,7 @@ impl Plan { /// looking at is the only thing they consented to act on. pub fn plan(targets: &[Target], root: &Path) -> Plan { let root = normalize(root); - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let mut plan = Plan::default(); let mut accepted: Vec = Vec::new(); @@ -118,7 +122,7 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { for target in accepted { if outer .iter() - .any(|candidate| target.path.starts_with(&candidate.path)) + .any(|candidate| within(&target.path, &candidate.path)) { plan.covered.push(target); } else { @@ -135,6 +139,7 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { /// and removing them by hand breaks the system; pacman, paccache and /// `journalctl --vacuum` are the right tools. Refused even where /// permissions would allow it, and even inside them. +#[cfg(not(windows))] const SYSTEM_TREES: [&str; 14] = [ "/bin", "/boot", @@ -152,8 +157,13 @@ const SYSTEM_TREES: [&str; 14] = [ "/efi", ]; +/// What to use instead, said when a system tree is refused. +#[cfg(not(windows))] +const SYSTEM_TOOLS: &str = "use the package manager"; + /// The system tree `path` is in, if any. The home directory is never /// system, wherever it lives. +#[cfg(not(windows))] fn system_tree(path: &Path, home: Option<&Path>) -> Option<&'static str> { if home.is_some_and(|home| path.starts_with(normalize(home))) { return None; @@ -164,22 +174,83 @@ fn system_tree(path: &Path, home: Option<&Path>) -> Option<&'static str> { .copied() } +/// [`SYSTEM_TREES`] on Windows: Windows itself, installed programs and +/// their machine-wide data, and what Windows keeps at the top of its drive +/// for restore points, recovery and booting. Taken from the environment, so +/// a system elsewhere is still recognized, and the usual places on the +/// system drive besides. +#[cfg(windows)] +fn system_trees() -> Vec { + let drive = system_drive(); + let mut trees: Vec = [ + "SystemRoot", + "ProgramFiles", + "ProgramFiles(x86)", + "ProgramW6432", + "ProgramData", + ] + .into_iter() + .filter_map(std::env::var_os) + .map(PathBuf::from) + // An empty or relative value would match too much or nothing at all. + .filter(|tree| tree.is_absolute()) + .collect(); + trees.extend( + [ + "Windows", + "Program Files", + "Program Files (x86)", + "ProgramData", + "System Volume Information", + "Recovery", + "Boot", + "bootmgr", + ] + .map(|name| drive.join(name)), + ); + trees +} + +/// The root of the drive Windows runs from, such as `C:\`. +#[cfg(windows)] +fn system_drive() -> PathBuf { + let mut drive = + std::env::var_os("SystemDrive").unwrap_or_else(|| "C:".into()); + // `C:` alone is the current directory on C:, not its root. + drive.push(r"\"); + PathBuf::from(drive) +} + +#[cfg(windows)] +const SYSTEM_TOOLS: &str = "use Settings, or the program's own uninstaller"; + +#[cfg(windows)] +fn system_tree(path: &Path, home: Option<&Path>) -> Option { + if home.is_some_and(|home| within(path, &normalize(home))) { + return None; + } + system_trees() + .into_iter() + .find(|tree| within(path, tree)) + .map(|tree| tree.display().to_string()) +} + fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { if path.parent().is_none() { return Some("the filesystem root cannot be removed".into()); } - if path == root { + if same(path, root) { return Some("the scanned root cannot be removed".into()); } - if home.is_some_and(|home| path == normalize(home)) { + if home.is_some_and(|home| same(path, &normalize(home))) { return Some("the home directory cannot be removed".into()); } - if !path.starts_with(root) { + if !within(path, root) { return Some("outside the scanned root".into()); } if let Some(system) = system_tree(path, home) { return Some(format!( - "part of the system under {system}: use the package manager" + "part of the system under {system}: {SYSTEM_TOOLS}" )); } if is_mount_point(path) { @@ -191,6 +262,17 @@ fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { None } +/// `path` is `base` or inside it, by whole components. +#[cfg(not(windows))] +fn within(path: &Path, base: &Path) -> bool { + path.starts_with(base) +} + +#[cfg(not(windows))] +fn same(left: &Path, right: &Path) -> bool { + left == right +} + /// Whether `path` sits on a different device than its parent, i.e. is a /// mount point. Descending into one would delete data the user never marked. #[cfg(unix)] @@ -212,7 +294,13 @@ pub fn is_mount_point(path: &Path) -> bool { } } -#[cfg(not(unix))] +/// Whether `path` is a folder another volume is mounted on. +#[cfg(windows)] +pub fn is_mount_point(path: &Path) -> bool { + crate::windows::is_mount_point(path) +} + +#[cfg(not(any(unix, windows)))] pub fn is_mount_point(_path: &Path) -> bool { false } @@ -256,6 +344,8 @@ pub enum TrashBackend { Gio, /// The XDG trash directory, implemented here. XdgHome, + /// The Windows Recycle Bin, through the shell's own file operation. + RecycleBin, /// No way to move files to a trash on this machine. #[default] Unavailable, @@ -264,7 +354,9 @@ pub enum TrashBackend { impl TrashBackend { pub const fn is_available(self) -> bool { match self { - Self::TrashPut | Self::Gio | Self::XdgHome => true, + Self::TrashPut | Self::Gio | Self::XdgHome | Self::RecycleBin => { + true + } Self::Unavailable => false, } } @@ -274,6 +366,7 @@ impl TrashBackend { Self::TrashPut => "trash-put", Self::Gio => "gio trash", Self::XdgHome => "XDG trash", + Self::RecycleBin => "the Recycle Bin", Self::Unavailable => "no trash tool found", } } @@ -287,6 +380,7 @@ impl TrashBackend { Self::XdgHome => { "moves into ~/.local/share/Trash on the same volume" } + Self::RecycleBin => "the same Recycle Bin as File Explorer", Self::Unavailable => { "install trash-cli or keep deleting permanently" } @@ -294,7 +388,15 @@ impl TrashBackend { } } +/// Detect the best available trash backend for this machine. Windows +/// always has its Recycle Bin. +#[cfg(windows)] +pub const fn detect_trash_backend() -> TrashBackend { + TrashBackend::RecycleBin +} + /// Detect the best available trash backend for this machine. +#[cfg(not(windows))] pub fn detect_trash_backend() -> TrashBackend { if which("trash-put") { TrashBackend::TrashPut @@ -307,6 +409,7 @@ pub fn detect_trash_backend() -> TrashBackend { } } +#[cfg(not(windows))] fn which(program: &str) -> bool { let Some(path) = std::env::var_os("PATH") else { return false; @@ -445,23 +548,53 @@ pub fn remove_permanently(path: &Path) -> io::Result<()> { let meta = fs::symlink_metadata(path)?; if meta.is_dir() { fs::remove_dir_all(path) + } else if is_dir_link(&meta) { + // Windows removes a link to a directory, a junction or a directory + // symlink, as a directory: `RemoveDirectoryW` takes the link and + // leaves its target alone. + fs::remove_dir(path) } else { fs::remove_file(path) } } +#[cfg(windows)] +fn is_dir_link(meta: &fs::Metadata) -> bool { + use std::os::windows::fs::FileTypeExt as _; + meta.file_type().is_symlink_dir() +} + +#[cfg(not(windows))] +const fn is_dir_link(_meta: &fs::Metadata) -> bool { + false +} + /// Move one path to the desktop trash. pub fn move_to_trash(path: &Path, backend: TrashBackend) -> io::Result<()> { match backend { TrashBackend::TrashPut => run_tool(Path::new("trash-put"), &[], path), TrashBackend::Gio => run_tool(Path::new("gio"), &["trash"], path), TrashBackend::XdgHome => trash_via_xdg(path), + TrashBackend::RecycleBin => recycle(path), TrashBackend::Unavailable => Err(io::Error::other( "no trash tool is installed; use permanent deletion instead", )), } } +/// Hand `path` to the Recycle Bin. `trash` asks the shell to warn before it +/// destroys anything rather than recycling it (`FOF_WANTNUKEWARNING`), so +/// the reversible path cannot turn into a permanent one silently. +#[cfg(windows)] +fn recycle(path: &Path) -> io::Result<()> { + trash::delete(path).map_err(io::Error::other) +} + +#[cfg(not(windows))] +fn recycle(_path: &Path) -> io::Result<()> { + Err(io::Error::other("the Recycle Bin is only on Windows")) +} + /// Run one trash tool on one path. /// /// `--` is passed before the path so that a file named `-rf` is read as a path @@ -547,6 +680,7 @@ pub fn trash_into(_path: &Path, _trash: &Path) -> io::Result<()> { } /// `name`, or `name.1`, `name.2`, … until the name is free in `dir`. +#[cfg(unix)] fn unique_name(dir: &Path, name: &str) -> (PathBuf, String) { let first = dir.join(name); if !first.exists() { @@ -579,6 +713,7 @@ pub fn percent_encode(input: &str) -> String { out } +#[cfg(unix)] fn deletion_date() -> String { // The specification wants ISO 8601 in local time; chrono is already in the // dependency graph, so use it rather than approximating the offset. @@ -631,7 +766,7 @@ mod tests { fn the_root_and_home_are_refused() { let temp = tree(); let root = temp.path(); - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let mut targets = vec![target(Path::new("/"), 0), target(root, 0)]; if let Some(home) = &home { targets.push(target(home, 0)); @@ -699,19 +834,54 @@ mod tests { assert!(temp.path().join("a/c.bin").exists()); } + /// A link to a directory: a symbolic link on Unix, a junction on + /// Windows, which needs no privilege to make. + fn link_dir(target: &Path, link: &Path) { + #[cfg(unix)] + std::os::unix::fs::symlink(target, link).expect("symlink"); + #[cfg(windows)] + assert!(crate::windows::make_junction(link, target), "junction"); + } + #[test] fn permanent_removal_unlinks_a_symlink_instead_of_following_it() { let temp = tree(); let keep = TempDir::new().expect("tempdir"); fs::write(keep.path().join("precious.bin"), b"data").expect("write"); let link = temp.path().join("link"); - std::os::unix::fs::symlink(keep.path(), &link).expect("symlink"); + link_dir(keep.path(), &link); remove_permanently(&link).expect("remove link"); - assert!(!link.exists()); + assert!(fs::symlink_metadata(&link).is_err(), "the link is gone"); assert!(keep.path().join("precious.bin").exists()); } + /// Git keeps its objects read-only, which on Windows stops a plain + /// delete; clearing an old checkout must still work. + #[test] + fn read_only_files_are_removed_too() { + let temp = tree(); + let objects = temp.path().join("a/b/objects"); + fs::create_dir_all(&objects).expect("mkdir"); + let object = objects.join("pack.idx"); + fs::write(&object, b"x").expect("write"); + let mut permissions = + fs::metadata(&object).expect("stat").permissions(); + permissions.set_readonly(true); + fs::set_permissions(&object, permissions).expect("read-only"); + let lone = temp.path().join("a/lone.idx"); + fs::write(&lone, b"x").expect("write"); + let mut permissions = fs::metadata(&lone).expect("stat").permissions(); + permissions.set_readonly(true); + fs::set_permissions(&lone, permissions).expect("read-only"); + + remove_permanently(&lone).expect("a read-only file"); + remove_permanently(&temp.path().join("a/b")).expect("a directory"); + assert!(!lone.exists()); + assert!(!temp.path().join("a/b").exists()); + assert!(temp.path().join("a/c.bin").exists()); + } + #[test] fn a_missing_target_reports_not_found() { let temp = tree(); @@ -728,6 +898,7 @@ mod tests { assert_eq!(percent_encode("/a\nb"), "/a%0Ab"); } + #[cfg(unix)] #[test] fn trash_names_avoid_collisions() { let temp = TempDir::new().expect("tempdir"); @@ -740,6 +911,7 @@ mod tests { assert_ne!(first, second); } + #[cfg(unix)] #[test] fn the_xdg_trash_moves_a_file_and_records_where_it_came_from() { // A private trash directory keeps the test out of the real trash can. @@ -762,6 +934,7 @@ mod tests { assert!(info.contains("DeletionDate=")); } + #[cfg(unix)] #[test] fn a_trash_info_path_is_restorable() { let trash = TempDir::new().expect("tempdir"); @@ -830,6 +1003,7 @@ mod tests { assert!(root.join("a/one.bin").exists()); } + #[cfg(unix)] #[test] fn a_trash_tool_is_called_with_the_path_after_a_separator() { use std::os::unix::fs::PermissionsExt as _; @@ -858,6 +1032,7 @@ mod tests { assert!(doomed.exists(), "the real tool would have moved it"); } + #[cfg(unix)] #[test] fn a_failing_trash_tool_reports_its_stderr() { use std::os::unix::fs::PermissionsExt as _; @@ -872,6 +1047,7 @@ mod tests { assert!(error.to_string().contains("no trash here"), "{error}"); } + #[cfg(not(windows))] #[test] fn detection_prefers_a_tool_this_machine_has() { let backend = detect_trash_backend(); @@ -881,6 +1057,45 @@ mod tests { assert!(backend.is_available()); } + #[cfg(windows)] + #[test] + fn windows_trashes_into_the_recycle_bin() { + let backend = detect_trash_backend(); + assert_eq!(backend, TrashBackend::RecycleBin); + assert!(backend.is_available()); + } + + #[cfg(windows)] + #[test] + fn windows_system_trees_are_refused_in_a_whole_disk_scan() { + let drive = system_drive(); + let home = drive.join(r"Users\tobi"); + let system = |relative: &str| { + system_tree(&drive.join(relative), Some(&home)) + .map(|tree| tree.to_lowercase()) + }; + let windows = drive.join("Windows").display().to_string(); + assert!( + system(r"WINDOWS\System32\drivers\etc\hosts").is_some(), + "without regard to case" + ); + assert!(system(r"Program Files\App\app.exe").is_some()); + assert!(system(r"Program Files (x86)\App").is_some()); + assert!(system(r"ProgramData\Vendor\state.db").is_some()); + assert!(system("System Volume Information").is_some()); + assert_eq!(system("Windows.old"), None, "components, not prefixes"); + assert_eq!(system(r"Users\tobi\AppData\Local\Temp"), None); + assert_eq!(system("Games"), None); + let reason = refuse(&drive.join(r"Windows\Temp"), &drive, Some(&home)); + assert!( + reason.is_some_and(|reason| reason + .to_lowercase() + .contains(&windows.to_lowercase())), + "refused as part of {windows}" + ); + } + + #[cfg(not(windows))] #[test] fn system_trees_are_refused_in_a_whole_disk_scan() { let home = Path::new("/home/tobi"); diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index be5f2ff..fb9fb50 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -15,7 +15,9 @@ //! poll without locking, and cooperative cancellation so a re-scan can abandon //! a walk of a large home directory instead of queueing behind it. -use std::fs::{self, DirEntry, Metadata}; +#[cfg(not(windows))] +use std::fs::DirEntry; +use std::fs::{self, Metadata}; use std::io; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; @@ -274,72 +276,28 @@ impl WalkContext { } /// Decide what to do with an entry, and account for the work it implies. - fn classify(&self, entry: &DirEntry) -> Classified { - let path = entry.path(); - let file_type = match entry.file_type() { - Ok(file_type) => file_type, + fn classify(&self, entry: &impl Listed) -> Classified { + let path = entry.entry_path(); + let listing = match entry.listing() { + Ok(listing) => listing, Err(error) => { self.progress.record_error(&path, &error); return Classified::Skipped; } }; - // Non-UTF-8 names are lossy for display. The scan still measures them - // correctly; only the reported name is approximate. - let name: Box = - entry.file_name().to_string_lossy().into_owned().into(); + let name = entry.display_name(); if !self.options.include_hidden && name.starts_with('.') { return Classified::Skipped; } - if file_type.is_symlink() { - return self.classify_symlink(&path, name); - } - - if file_type.is_dir() { - // Memoized: the subtree a narrower scan already measured is - // taken whole, before any volume rule, since it was measured - // under the same rules. - if let Some(known) = &self.known - && known.path == path - { - let tree = (*known.tree).clone(); - self.progress.files.fetch_add(tree.files, Ordering::Relaxed); - self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed); - self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed); - let mut tree = tree; - tree.name = name; - return Classified::Entry(tree); - } - if self.options.one_filesystem - && let Some(foreign) = self.foreign_mounts.get() - { - // Checked by path before anything reads the directory, so an - // automount point is never triggered. - if foreign.contains(&path) { - return Classified::Skipped; - } - } else if self.options.one_filesystem { - let device = entry.metadata().map(|meta| device_of(&meta)); - match (device, self.root_device(&path)) { - (Ok(device), Some(root_device)) - if device != root_device => - { - return Classified::Skipped; - } - (Err(error), _) => { - self.progress.record_error(&path, &error); - return Classified::Skipped; - } - _ => {} - } - } - self.progress.count_dir(); - return Classified::Subdirectory(path); - } - - match entry.metadata() { - Ok(meta) => self.leaf(name, kind_of(&meta, file_type), &meta), + let kind = match listing { + Listing::Symlink => return self.classify_symlink(&path, name), + Listing::Directory => return self.classify_dir(entry, path, name), + Listing::Leaf(kind) => kind, + }; + match entry.facts(self.options.apparent_size) { + Ok(facts) => self.leaf(name, kind, &facts), Err(error) => { self.progress.record_error(&path, &error); Classified::Skipped @@ -347,19 +305,62 @@ impl WalkContext { } } + fn classify_dir( + &self, + entry: &impl Listed, + path: PathBuf, + name: Box, + ) -> Classified { + // Memoized: the subtree a narrower scan already measured is taken + // whole, before any volume rule, since it was measured under the same + // rules. + if let Some(known) = &self.known + && known.path == path + { + let tree = (*known.tree).clone(); + self.progress.files.fetch_add(tree.files, Ordering::Relaxed); + self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed); + self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed); + let mut tree = tree; + tree.name = name; + return Classified::Entry(tree); + } + if self.options.one_filesystem + && let Some(foreign) = self.foreign_mounts.get() + { + // Checked by path before anything reads the directory, so an + // automount point is never triggered. + if foreign.contains(&path) { + return Classified::Skipped; + } + } else if self.options.one_filesystem { + match (entry.device(), self.root_device(&path)) { + (Ok(device), Some(root_device)) if device != root_device => { + return Classified::Skipped; + } + (Err(error), _) => { + self.progress.record_error(&path, &error); + return Classified::Skipped; + } + _ => {} + } + } + self.progress.count_dir(); + Classified::Subdirectory(path) + } + fn classify_symlink(&self, path: &Path, name: Box) -> Classified { if !self.options.follow_links { // Not followed: the link occupies only its target string, which // `du` reports as a handful of bytes or nothing at all. return match fs::symlink_metadata(path) { Ok(meta) => { - let size = measure(&meta, self.options.apparent_size); - self.progress.count_file(size); + let facts = Facts::of(&meta, self.options.apparent_size); + self.progress.count_file(facts.size); Classified::Entry(leaf_node( name, NodeKind::Symlink, - size, - &meta, + &facts, )) } Err(error) => { @@ -381,7 +382,7 @@ impl WalkContext { }; if meta.is_dir() { - if let Some(key) = file_identity(&meta) + if let Some(key) = identity_of(path, &meta) && !lock(&self.visited_dirs).insert(key) { return Classified::Skipped; @@ -390,21 +391,147 @@ impl WalkContext { return Classified::Subdirectory(path.to_path_buf()); } - self.leaf(name, kind_of(&meta, meta.file_type()), &meta) + let mut facts = Facts::of(&meta, self.options.apparent_size); + // What the link leads to, so a file that is also reached directly is + // charged once. + facts.identity = identity_of(path, &meta); + self.leaf(name, kind_of(&meta, meta.file_type()), &facts) } fn leaf( &self, name: Box, kind: NodeKind, - meta: &Metadata, + facts: &Facts, ) -> Classified { - let size = measure(meta, self.options.apparent_size); - self.progress.count_file(size); - Classified::Entry(leaf_node(name, kind, size, meta)) + self.progress.count_file(facts.size); + Classified::Entry(leaf_node(name, kind, facts)) } } +/// What the walk reads about one directory entry. +/// +/// `std::fs::DirEntry` everywhere but Windows. There the standard listing +/// has neither the allocated size nor a file id, so measuring like `du` +/// would cost an open per file; [`crate::windows`] lists a directory with +/// both instead. +trait Listed { + fn entry_path(&self) -> PathBuf; + /// Non-UTF-8 names are lossy for display. The scan still measures them + /// correctly; only the reported name is approximate. + fn display_name(&self) -> Box; + fn listing(&self) -> io::Result; + /// Size, identity and age of a leaf. + fn facts(&self, apparent_size: bool) -> io::Result; + /// The device a directory is on, for staying on one volume when the + /// mount table cannot be read. + fn device(&self) -> io::Result; +} + +/// What an entry is, as far as the walk is concerned. +enum Listing { + Directory, + Symlink, + Leaf(NodeKind), +} + +/// What a leaf contributes. +struct Facts { + size: u64, + identity: Option<(u64, u64)>, + modified: i64, +} + +impl Facts { + fn of(meta: &Metadata, apparent_size: bool) -> Self { + Self { + size: measure(meta, apparent_size), + identity: file_identity(meta), + modified: modified_seconds(meta), + } + } +} + +#[cfg(not(windows))] +impl Listed for DirEntry { + fn entry_path(&self) -> PathBuf { + self.path() + } + + fn display_name(&self) -> Box { + self.file_name().to_string_lossy().into_owned().into() + } + + fn listing(&self) -> io::Result { + let file_type = self.file_type()?; + Ok(if file_type.is_symlink() { + Listing::Symlink + } else if file_type.is_dir() { + Listing::Directory + } else if file_type.is_file() { + Listing::Leaf(NodeKind::File) + } else { + Listing::Leaf(NodeKind::Other) + }) + } + + fn facts(&self, apparent_size: bool) -> io::Result { + self.metadata().map(|meta| Facts::of(&meta, apparent_size)) + } + + fn device(&self) -> io::Result { + self.metadata().map(|meta| device_of(&meta)) + } +} + +#[cfg(windows)] +impl Listed for crate::windows::Entry { + fn entry_path(&self) -> PathBuf { + self.path() + } + + fn display_name(&self) -> Box { + self.file_name().to_string_lossy().into_owned().into() + } + + fn listing(&self) -> io::Result { + Ok(match self.kind() { + crate::windows::Kind::Link => Listing::Symlink, + crate::windows::Kind::Directory => Listing::Directory, + crate::windows::Kind::File => Listing::Leaf(NodeKind::File), + }) + } + + fn facts(&self, apparent_size: bool) -> io::Result { + Ok(Facts { + size: if apparent_size { + self.apparent() + } else { + self.allocated() + }, + identity: self.identity(), + modified: self.modified(), + }) + } + + /// Never consulted: see [`crate::space::foreign_mounts_for`]. The same + /// answer as [`device_of`], so the two could only ever agree. + fn device(&self) -> io::Result { + Ok(0) + } +} + +/// List a directory the way [`Listed`] describes. +#[cfg(not(windows))] +fn list(path: &Path) -> io::Result { + fs::read_dir(path) +} + +#[cfg(windows)] +fn list(path: &Path) -> io::Result { + crate::windows::read_dir(path) +} + /// What a directory entry turned out to be. enum Classified { /// Descend into this directory on a new task. @@ -486,7 +613,7 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { } } if context.options.follow_links - && let Some(key) = file_identity(&root_meta) + && let Some(key) = identity_of(root, &root_meta) { lock(&context.visited_dirs).insert(key); } @@ -508,7 +635,7 @@ fn walk(scope: &Scope<'_>, dir: &Arc, context: &Arc) { let mut subdirs: Vec> = Vec::new(); let mut leaves: Vec = Vec::new(); - match fs::read_dir(&dir.path) { + match list(&dir.path) { Ok(entries) => { for entry in entries { if context.cancelled() { @@ -607,15 +734,10 @@ fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) { } } -fn leaf_node( - name: Box, - kind: NodeKind, - size: u64, - meta: &Metadata, -) -> Node { - let mut node = Node::entry(name, kind, size); - node.inode = file_identity(meta); - node.modified = modified_seconds(meta); +fn leaf_node(name: Box, kind: NodeKind, facts: &Facts) -> Node { + let mut node = Node::entry(name, kind, facts.size); + node.inode = facts.identity; + node.modified = facts.modified; node } @@ -654,7 +776,7 @@ fn allocated_bytes(meta: &Metadata) -> Option { } #[cfg(not(unix))] -fn allocated_bytes(_meta: &Metadata) -> Option { +const fn allocated_bytes(_meta: &Metadata) -> Option { None } @@ -665,13 +787,15 @@ fn device_of(meta: &Metadata) -> u64 { } #[cfg(not(unix))] -fn device_of(_meta: &Metadata) -> u64 { +const fn device_of(_meta: &Metadata) -> u64 { 0 } /// `(device, inode)`, or `None` where the platform does not expose them. /// Hardlink de-duplication and symlink loop detection both depend on this, so -/// they are simply unavailable rather than silently wrong elsewhere. +/// they are simply unavailable rather than silently wrong elsewhere. Windows +/// has no file id in `Metadata` on stable Rust; its listing carries one +/// instead (see [`crate::windows`]). #[allow( clippy::unnecessary_wraps, reason = "the Option is the non-Unix answer, so both arms must agree" @@ -683,10 +807,23 @@ fn file_identity(meta: &Metadata) -> Option<(u64, u64)> { } #[cfg(not(unix))] -fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> { +const fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> { None } +/// The identity of what `path` leads to, `meta` being its followed +/// metadata: how a walk that follows links recognizes a directory it has +/// entered before, and a file it has already charged. +#[cfg(not(windows))] +fn identity_of(_path: &Path, meta: &Metadata) -> Option<(u64, u64)> { + file_identity(meta) +} + +#[cfg(windows)] +fn identity_of(path: &Path, _meta: &Metadata) -> Option<(u64, u64)> { + crate::windows::identity(path) +} + fn kind_of(meta: &Metadata, file_type: fs::FileType) -> NodeKind { if meta.is_dir() || file_type.is_dir() { NodeKind::Directory @@ -838,6 +975,20 @@ mod tests { assert_eq!(without.bytes, 100); } + /// A link to a directory: a symbolic link on Unix, a junction on + /// Windows, which needs no privilege to make. `false` if it could not be + /// made. + fn link_dir(target: &Path, link: &Path) -> bool { + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(windows)] + { + crate::windows::make_junction(link, target) + } + } + #[test] fn symlinks_are_not_followed_by_default() { let temp = TempDir::new().expect("tempdir"); @@ -845,8 +996,7 @@ mod tests { write(outside.path(), "elsewhere.bin", 5000); let root = temp.path(); write(root, "real.bin", 100); - std::os::unix::fs::symlink(outside.path(), root.join("link")) - .expect("symlink"); + assert!(link_dir(outside.path(), &root.join("link")), "a link"); let tree = scan_dir(root, &options()); // Only the real file's bytes; the link itself holds just its target @@ -862,8 +1012,7 @@ mod tests { let temp = TempDir::new().expect("tempdir"); let root = temp.path(); write(root, "sub/leaf.bin", 42); - std::os::unix::fs::symlink(root, root.join("sub/loop")) - .expect("symlink"); + assert!(link_dir(root, &root.join("sub/loop")), "a link"); let tree = scan_dir( root, @@ -875,6 +1024,29 @@ mod tests { assert_eq!(tree.bytes, 42); } + /// Disk usage is what the volume allocated, not the length: whole + /// blocks, so it covers the data and ends on a block boundary. + #[test] + fn disk_usage_is_whole_allocation_units() { + let temp = TempDir::new().expect("tempdir"); + // Noise, so a compressing filesystem cannot store it in less. + let mut state = 0x2545_f491_4f6c_dd1d_u64; + let noise: Vec = (0..100_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state.to_le_bytes()[0] + }) + .collect(); + fs::write(temp.path().join("data.bin"), noise).expect("write"); + let tree = scan_dir(temp.path(), &ScanOptions::default()); + assert!(tree.bytes >= 100_000, "{}", tree.bytes); + assert_eq!(tree.bytes % 512, 0, "{}", tree.bytes); + let apparent = scan_dir(temp.path(), &options()); + assert_eq!(apparent.bytes, 100_000); + } + #[test] fn max_depth_stops_descending_but_keeps_direct_files() { let temp = TempDir::new().expect("tempdir"); @@ -927,6 +1099,7 @@ mod tests { assert_eq!(by_files.children[0].files, 5); } + #[cfg(unix)] #[test] fn an_unreadable_directory_is_recorded_not_fatal() { use std::os::unix::fs::PermissionsExt as _; @@ -1040,7 +1213,7 @@ mod tests { #[test] #[ignore = "walks the whole disk"] fn whole_disk_smoke() { - let home = std::env::var_os("HOME").map(PathBuf::from).expect("HOME"); + let home = std::env::home_dir().expect("a home directory"); let root = crate::space::volume_root_for(&home).expect("a volume root"); let started = std::time::Instant::now(); let tree = scan(&root, ScanOptions::default()).expect("scan"); diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs index 008eec3..74a4ae9 100644 --- a/crates/disktree-core/src/space.rs +++ b/crates/disktree-core/src/space.rs @@ -49,6 +49,13 @@ impl SpaceInfo { } /// Read the space on the volume containing `path`. +#[cfg(windows)] +pub fn space_info(path: &Path) -> io::Result { + crate::windows::space_info(path) +} + +/// Read the space on the volume containing `path`. +#[cfg(not(windows))] pub fn space_info(path: &Path) -> io::Result { let stat = rustix::fs::statvfs(path)?; // `f_frsize` is the fragment size the block counts are expressed in; @@ -66,9 +73,17 @@ pub fn space_info(path: &Path) -> io::Result { }) } +/// The volume a path is on, as Windows names it: `C:\`, a share, or the +/// folder a volume is mounted on. +#[cfg(windows)] +pub fn device_for(path: &Path) -> Option { + crate::windows::volume_root(path).map(|root| root.display().to_string()) +} + /// The device a path's filesystem is mounted from, such as /// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in /// `/proc/self/mounts`. `None` where that table cannot be read. +#[cfg(not(windows))] pub fn device_for(path: &Path) -> Option { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); @@ -186,19 +201,42 @@ pub fn volume_root(mounts: &[Mount], path: &Path) -> Option { } /// [`volume_root`] for this machine. +#[cfg(not(windows))] pub fn volume_root_for(path: &Path) -> Option { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); volume_root(&parse_mounts(&table), &path) } +/// The top of the volume `path` lives on: its drive, such as `C:\`. +#[cfg(windows)] +pub fn volume_root_for(path: &Path) -> Option { + crate::windows::volume_root(path) +} + /// [`foreign_mounts`] for this machine; `None` when the mount table cannot /// be read, so the caller can fall back to comparing devices. +#[cfg(not(windows))] pub fn foreign_mounts_for(root: &Path) -> Option> { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; Some(foreign_mounts(&parse_mounts(&table), root)) } +/// Nothing to leave out by path on Windows. +/// +/// There, the only way into another volume below `root` is a folder that +/// volume is mounted on, which is a reparse point the walk treats as a link +/// and does not enter unless links are followed; other drives are separate +/// trees altogether. +#[cfg(windows)] +#[allow( + clippy::unnecessary_wraps, + reason = "the Option is the Unix answer when the mount table is missing" +)] +pub const fn foreign_mounts_for(_root: &Path) -> Option> { + Some(Vec::new()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-core/src/windows.rs new file mode 100644 index 0000000..e834239 --- /dev/null +++ b/crates/disktree-core/src/windows.rs @@ -0,0 +1,727 @@ +//! What a walk on Windows needs beyond the standard library. +//! +//! `std::fs::read_dir` lists a directory with `FindNextFileW`, whose records +//! carry neither the space a file occupies nor a file id. Asking for them +//! file by file costs an open per file: on a home directory of 1.3 million +//! files that made the walk seven times slower. `GetFileInformationByHandleEx` +//! with `FileIdExtdDirectoryInfo` returns both for a whole buffer of entries, +//! for what the listing costs anyway. +//! +//! The rest is small: the volume a path is on, its free space, and comparing +//! paths the way Windows does. + +#![allow( + unsafe_code, + reason = "Win32 calls std does not wrap; each block says why it is sound" +)] + +use std::ffi::{OsStr, OsString}; +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::mem::offset_of; +use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _}; +use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _}; +use std::os::windows::io::AsRawHandle as _; +use std::path::{Component, Path, PathBuf, Prefix}; +use std::sync::Arc; + +use windows_sys::Win32::Foundation::{ + ERROR_INVALID_FUNCTION, ERROR_INVALID_LEVEL, ERROR_INVALID_PARAMETER, + ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED, +}; +use windows_sys::Win32::Storage::FileSystem::{ + FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, + FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, + FILE_READ_ATTRIBUTES, FileIdExtdDirectoryInfo, GetDiskFreeSpaceExW, + GetFileInformationByHandleEx, GetVolumePathNameW, SYNCHRONIZE, +}; + +use crate::space::SpaceInfo; + +/// Bytes the file system fills per call: some hundreds of entries. +const BUFFER_BYTES: usize = 64 * 1024; + +/// Where a record's name starts; everything before it has a fixed size. +const NAME_AT: usize = offset_of!(FILE_ID_EXTD_DIR_INFO, FileName); + +/// Reparse tags with this bit stand for another path: symbolic links, +/// junctions and mounted folders. These are exactly what the standard +/// library calls symlinks, so this listing agrees with `std::fs::FileType`. +const NAME_SURROGATE: u32 = 0x2000_0000; + +/// A `FILETIME` counts 100 ns ticks from 1601; this many precede 1970. +const EPOCH_TICKS: i64 = 116_444_736_000_000_000; +const TICKS_PER_SECOND: i64 = 10_000_000; + +/// What an entry is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Directory, + /// A symbolic link, a junction or a mounted folder. + Link, + File, +} + +/// One directory entry, with what a measurement needs. +#[derive(Debug)] +pub struct Entry { + dir: Arc, + name: OsString, + kind: Kind, + apparent: u64, + allocated: u64, + modified: i64, + identity: Option<(u64, u64)>, +} + +impl Entry { + pub fn path(&self) -> PathBuf { + self.dir.join(&self.name) + } + + pub fn file_name(&self) -> &OsStr { + &self.name + } + + pub const fn kind(&self) -> Kind { + self.kind + } + + /// The length, in bytes. + pub const fn apparent(&self) -> u64 { + self.apparent + } + + /// Bytes the volume has allocated to the file, in whole clusters: less + /// than the length for a compressed or sparse file, and zero for one + /// whose data is kept in its file record. Where the listing could not say + /// (see [`read_dir`]), the length. + pub const fn allocated(&self) -> u64 { + self.allocated + } + + /// Last write, in Unix seconds; `0` when earlier or unknown. + pub const fn modified(&self) -> i64 { + self.modified + } + + /// `(volume serial, file id)`: the same for two names of one file. + pub const fn identity(&self) -> Option<(u64, u64)> { + self.identity + } + + fn from_std(dir: &Arc, entry: &fs::DirEntry) -> io::Result { + let meta = entry.metadata()?; + let file_type = meta.file_type(); + let kind = if file_type.is_symlink() { + Kind::Link + } else if file_type.is_dir() { + Kind::Directory + } else { + Kind::File + }; + Ok(Self { + dir: Arc::clone(dir), + name: entry.file_name(), + kind, + apparent: meta.len(), + allocated: meta.len(), + modified: unix_seconds( + i64::try_from(meta.last_write_time()).unwrap_or(0), + ), + identity: None, + }) + } +} + +/// A directory being listed; like `std::fs::ReadDir`, it leaves out `.` +/// and `..`. +#[derive(Debug)] +pub struct ReadDir { + dir: Arc, + source: Source, +} + +#[derive(Debug)] +enum Source { + Records(Records), + /// A file system or network share that does not implement the listing + /// with ids: the standard one, which has lengths but not allocations. + /// Boxed, being ten times the size of the common case. + Std(Box), +} + +#[derive(Debug)] +struct Records { + handle: File, + /// Serial number of the directory's volume, which with a file id names + /// a file. `None` when it cannot be read; nothing is de-duplicated then. + volume: Option, + /// `u64`s for the eight-byte alignment the records are laid out in. + buffer: Box<[u64]>, + /// Where the next record starts, or `None` once the buffer is used up. + next: Option, + done: bool, +} + +/// List `dir`, with each entry's allocation and file id. +pub fn read_dir(dir: &Path) -> io::Result { + let handle = OpenOptions::new() + .access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE) + // Needed to open a directory at all. Without + // `FILE_FLAG_OPEN_REPARSE_POINT` a link is followed, which is what + // a walk that chose to enter one wants. + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(dir)?; + let volume = winapi_util::file::information(&handle) + .ok() + .map(|info| info.volume_serial_number()); + let mut records = Records { + handle, + volume, + buffer: vec![0; BUFFER_BYTES / 8].into_boxed_slice(), + next: None, + done: false, + }; + let dir: Arc = Arc::from(dir); + // The first fill shows whether the file system implements this listing, + // before any entry has been handed out. + let source = match records.fill() { + Ok(()) => Source::Records(records), + Err(error) if unsupported(&error) => { + Source::Std(Box::new(fs::read_dir(&dir)?)) + } + Err(error) => return Err(error), + }; + Ok(ReadDir { dir, source }) +} + +impl Iterator for ReadDir { + type Item = io::Result; + + fn next(&mut self) -> Option { + let records = match &mut self.source { + Source::Std(listing) => { + return listing.next().map(|entry| { + entry.and_then(|entry| Entry::from_std(&self.dir, &entry)) + }); + } + Source::Records(records) => records, + }; + loop { + if records.done { + return None; + } + let Some(offset) = records.next else { + if let Err(error) = records.fill() { + records.done = true; + return Some(Err(error)); + } + continue; + }; + match records.record(&self.dir, offset) { + Ok((entry, next)) => { + records.next = next; + if let Some(entry) = entry { + return Some(Ok(entry)); + } + } + Err(error) => { + records.done = true; + return Some(Err(error)); + } + } + } + } +} + +impl Records { + /// Ask the file system for the next buffer of records. + fn fill(&mut self) -> io::Result<()> { + // SAFETY: the handle is an open directory handle owned by `self`; + // the pointer and length describe `self.buffer`, which is writable + // for that many bytes and not otherwise borrowed during the call; + // and the class is the one the records are read as. + let filled = unsafe { + GetFileInformationByHandleEx( + self.handle.as_raw_handle(), + FileIdExtdDirectoryInfo, + self.buffer.as_mut_ptr().cast(), + BUFFER_BYTES as u32, + ) + }; + if filled != 0 { + self.next = Some(0); + return Ok(()); + } + let error = io::Error::last_os_error(); + if code(&error) == Some(ERROR_NO_MORE_FILES) { + self.done = true; + return Ok(()); + } + Err(error) + } + + /// The buffer as the bytes the file system wrote. + fn bytes(&self) -> &[u8] { + // SAFETY: `[u64]` can be read as `u8`s of eight times its length: + // one allocation, no alignment requirement for `u8`, and every byte + // initialized, since the buffer starts zeroed. + unsafe { + std::slice::from_raw_parts( + self.buffer.as_ptr().cast::(), + size_of_val(&*self.buffer), + ) + } + } + + /// The entry at `offset`, or `None` for `.` and `..`, and where the next + /// record starts. Every length the file system wrote is checked against + /// the buffer before it is used. + fn record( + &self, + dir: &Arc, + offset: usize, + ) -> io::Result<(Option, Option)> { + let malformed = + || io::Error::other("the file system returned a malformed record"); + let bytes = self.bytes(); + let header = + bytes.get(offset..offset + NAME_AT).ok_or_else(malformed)?; + let field = |at: usize| { + u32::from_ne_bytes(header[at..at + 4].try_into().expect("four")) + }; + let signed = |at: usize| { + i64::from_ne_bytes(header[at..at + 8].try_into().expect("eight")) + }; + let name_len = + field(offset_of!(FILE_ID_EXTD_DIR_INFO, FileNameLength)) as usize; + let name_bytes = bytes + .get(offset + NAME_AT..offset + NAME_AT + name_len) + .filter(|name| name.len() % 2 == 0) + .ok_or_else(malformed)?; + let next = + match field(offset_of!(FILE_ID_EXTD_DIR_INFO, NextEntryOffset)) { + 0 => None, + step if step as usize >= NAME_AT + name_len => { + Some(offset + step as usize) + } + _ => return Err(malformed()), + }; + + let name: Vec = name_bytes + .chunks_exact(2) + .map(|pair| u16::from_ne_bytes([pair[0], pair[1]])) + .collect(); + if name == [u16::from(b'.')] || name == [u16::from(b'.'); 2] { + return Ok((None, next)); + } + + let attributes = + field(offset_of!(FILE_ID_EXTD_DIR_INFO, FileAttributes)); + let tag = field(offset_of!(FILE_ID_EXTD_DIR_INFO, ReparsePointTag)); + let kind = if attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 + && tag & NAME_SURROGATE != 0 + { + Kind::Link + } else if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 { + Kind::Directory + } else { + Kind::File + }; + let id_at = offset_of!(FILE_ID_EXTD_DIR_INFO, FileId); + let id = u128::from_le_bytes( + header[id_at..id_at + 16].try_into().expect("sixteen"), + ); + let entry = Entry { + dir: Arc::clone(dir), + name: OsString::from_wide(&name), + kind, + apparent: bytes_from(signed(offset_of!( + FILE_ID_EXTD_DIR_INFO, + EndOfFile + ))), + allocated: bytes_from(signed(offset_of!( + FILE_ID_EXTD_DIR_INFO, + AllocationSize + ))), + modified: unix_seconds(signed(offset_of!( + FILE_ID_EXTD_DIR_INFO, + LastWriteTime + ))), + identity: self.volume.zip(file_id(id)), + }; + Ok((Some(entry), next)) + } +} + +/// The part of a 128-bit file id that names a file by itself. +/// +/// NTFS keeps the high half zero ([MS-FSCC] 2.1.10), so the low half is the +/// id. Zero is what a file system without ids reports; FAT and exFAT do, +/// and their 64-bit ids are documented as not unique, so trusting them could +/// merge two files into one. +/// +/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/98860416-1caf-4c80-a9ab-8d61e1ccf5a5 +fn file_id(id: u128) -> Option { + // TODO(refs-hardlinks): ReFS ids use both halves, which a (u64, u64) + // key cannot hold together with the volume, so hardlinks on ReFS (Dev + // Drives) are counted once per name. That overcounts; it never drops a + // file's size. + u64::try_from(id).ok().filter(|&low| low != 0) +} + +/// `(volume serial, file index)` of what `path` names, following links: how +/// a walk that follows links notices it has been somewhere before. `None` +/// where there is no usable index; zero and all ones mean exactly that +/// ([MS-FSCC] 2.1.9). +/// +/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/2d3333fe-fc98-4a6f-98a2-4bb805aff407 +pub fn identity(path: &Path) -> Option<(u64, u64)> { + let file = OpenOptions::new() + .access_mode(FILE_READ_ATTRIBUTES) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(path) + .ok()?; + let info = winapi_util::file::information(&file).ok()?; + let index = info.file_index(); + (index != 0 && index != u64::MAX) + .then(|| (info.volume_serial_number(), index)) +} + +/// Capacity and free space of the volume holding `path`. +pub fn space_info(path: &Path) -> io::Result { + // A network share is only accepted with a trailing separator. + let directory = wide(path, true)?; + let (mut available, mut total, mut free) = (0_u64, 0_u64, 0_u64); + // SAFETY: `directory` is NUL-terminated and outlives the call, and each + // out pointer is to a live, writable `u64`. + let ok = unsafe { + GetDiskFreeSpaceExW( + directory.as_ptr(), + &raw mut available, + &raw mut total, + &raw mut free, + ) + }; + if ok == 0 { + return Err(io::Error::last_os_error()); + } + Ok(SpaceInfo { + total, + free, + available, + }) +} + +/// Where the volume holding `path` is mounted: a drive such as `C:\`, a +/// share, or a folder another volume is mounted on. +pub fn volume_root(path: &Path) -> Option { + let name = wide(path, false).ok()?; + // The answer is a prefix of the path made absolute; the path's length + // plus room for the longest drive and directory it could gain is ample. + let mut root = vec![0_u16; name.len() + 260]; + // SAFETY: `name` is NUL-terminated and outlives the call, and `root` is + // writable for the length passed. + let ok = unsafe { + GetVolumePathNameW( + name.as_ptr(), + root.as_mut_ptr(), + u32::try_from(root.len()).ok()?, + ) + }; + if ok == 0 { + return None; + } + let end = root.iter().position(|&unit| unit == 0)?; + Some(PathBuf::from(OsString::from_wide(&root[..end]))) +} + +/// Whether `path` is a folder another volume is mounted on. Removing one +/// would reach onto that volume, which nobody marked. +pub fn is_mount_point(path: &Path) -> bool { + path.parent().is_some() + && volume_root(path).is_some_and(|root| same(&root, path)) +} + +/// Whether `path` is `base` or inside it, compared the way Windows compares +/// names: without regard to case, so `C:\WINDOWS\System32` is inside +/// `C:\Windows`, and with `\\?\C:\` the same place as `C:\`. +pub fn within(path: &Path, base: &Path) -> bool { + folded(path).starts_with(&folded(base)) +} + +/// Whether `left` and `right` name the same place, as [`within`] compares. +pub fn same(left: &Path, right: &Path) -> bool { + folded(left) == folded(right) +} + +/// Each component in the form Windows would treat as equal. +fn folded(path: &Path) -> Vec { + path.components() + .map(|component| match component { + Component::Prefix(prefix) => match prefix.kind() { + Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => { + format!("{}:", char::from(letter.to_ascii_lowercase())) + } + Prefix::UNC(server, share) + | Prefix::VerbatimUNC(server, share) => format!( + r"\\{}\{}", + server.to_string_lossy(), + share.to_string_lossy() + ) + .to_lowercase(), + Prefix::Verbatim(_) | Prefix::DeviceNS(_) => { + prefix.as_os_str().to_string_lossy().to_lowercase() + } + }, + other => other.as_os_str().to_string_lossy().to_lowercase(), + }) + .collect() +} + +/// `path` as a NUL-terminated wide string, with a trailing separator when +/// `directory` is set. +fn wide(path: &Path, directory: bool) -> io::Result> { + let mut wide: Vec = path.as_os_str().encode_wide().collect(); + if wide.contains(&0) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "a path cannot contain NUL", + )); + } + let separator = + |unit: &u16| *unit == u16::from(b'\\') || *unit == u16::from(b'/'); + if directory && !wide.last().is_some_and(separator) { + wide.push(u16::from(b'\\')); + } + wide.push(0); + Ok(wide) +} + +/// Errors a file system or redirector gives for a listing it does not +/// implement. +fn unsupported(error: &io::Error) -> bool { + matches!( + code(error), + Some( + ERROR_INVALID_FUNCTION + | ERROR_NOT_SUPPORTED + | ERROR_INVALID_PARAMETER + | ERROR_INVALID_LEVEL + ) + ) +} + +fn code(error: &io::Error) -> Option { + error + .raw_os_error() + .and_then(|code| u32::try_from(code).ok()) +} + +/// A byte count the file system reports as signed; it never is negative. +fn bytes_from(value: i64) -> u64 { + u64::try_from(value).unwrap_or(0) +} + +/// A `FILETIME` as Unix seconds, `0` before 1970. +const fn unix_seconds(ticks: i64) -> i64 { + if ticks <= EPOCH_TICKS { + 0 + } else { + (ticks - EPOCH_TICKS) / TICKS_PER_SECOND + } +} + +/// Make a directory junction for a test: unlike a symbolic link, one needs +/// no privilege to create. `false` when there is no `cmd` to make it with. +#[cfg(test)] +pub fn make_junction(link: &Path, target: &Path) -> bool { + // Rebuilt from components, because `mklink` takes no `/` in a path, and + // a test's `root.join("sub/loop")` has one. + let native = |path: &Path| path.components().collect::(); + std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(native(link)) + .arg(native(target)) + .output() + .is_ok_and(|output| output.status.success()) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::TempDir; + + fn listed(dir: &Path) -> Vec { + let mut entries: Vec = read_dir(dir) + .expect("list") + .collect::>() + .expect("entries"); + entries.sort_by(|left, right| left.name.cmp(&right.name)); + entries + } + + #[test] + fn a_listing_has_names_kinds_lengths_and_no_dot_entries() { + let temp = TempDir::new().expect("tempdir"); + fs::create_dir(temp.path().join("sub")).expect("mkdir"); + fs::write(temp.path().join("data.bin"), vec![7_u8; 100_000]) + .expect("write"); + + let entries = listed(temp.path()); + let names: Vec<&OsStr> = entries.iter().map(Entry::file_name).collect(); + assert_eq!(names, ["data.bin", "sub"]); + assert_eq!(entries[0].kind(), Kind::File); + assert_eq!(entries[0].apparent(), 100_000); + assert_eq!(entries[0].path(), temp.path().join("data.bin")); + assert_eq!(entries[1].kind(), Kind::Directory); + assert!(entries[0].modified() > 0, "written just now"); + } + + #[test] + fn the_allocation_is_whole_clusters_of_the_data() { + let temp = TempDir::new().expect("tempdir"); + // Noise, so a compressed folder cannot store it in less. + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let noise: Vec = (0..100_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state.to_le_bytes()[0] + }) + .collect(); + fs::write(temp.path().join("data.bin"), noise).expect("write"); + let entry = &listed(temp.path())[0]; + // Clusters are powers of two between 512 bytes and 2 MiB, so the + // allocation covers the data and is a whole number of sectors. + assert!(entry.allocated() >= 100_000, "{}", entry.allocated()); + assert!(entry.allocated() < 100_000 + 2 * 1024 * 1024); + assert_eq!(entry.allocated() % 512, 0); + } + + #[test] + fn two_names_of_one_file_share_an_identity() { + let temp = TempDir::new().expect("tempdir"); + let original = temp.path().join("original.bin"); + fs::write(&original, b"payload").expect("write"); + fs::hard_link(&original, temp.path().join("link.bin")) + .expect("hard link"); + fs::write(temp.path().join("other.bin"), b"payload").expect("write"); + + let entries = listed(temp.path()); + let id = |name: &str| { + entries + .iter() + .find(|entry| entry.file_name() == name) + .and_then(Entry::identity) + }; + assert!(id("original.bin").is_some(), "NTFS gives ids"); + assert_eq!(id("link.bin"), id("original.bin")); + assert_ne!(id("other.bin"), id("original.bin")); + assert_eq!(identity(&original), id("original.bin"), "one id scheme"); + } + + #[test] + fn a_junction_is_a_link_and_listing_it_lists_its_target() { + let temp = TempDir::new().expect("tempdir"); + let target = temp.path().join("target"); + fs::create_dir(&target).expect("mkdir"); + fs::write(target.join("inside.bin"), b"x").expect("write"); + let junction = temp.path().join("junction"); + if !make_junction(&junction, &target) { + return; // no cmd.exe to make one with + } + + let entries = listed(temp.path()); + let kind = |name: &str| { + entries + .iter() + .find(|entry| entry.file_name() == name) + .map(Entry::kind) + }; + assert_eq!(kind("junction"), Some(Kind::Link)); + assert_eq!(kind("target"), Some(Kind::Directory)); + let through: Vec = listed(&junction) + .into_iter() + .map(|entry| entry.name) + .collect(); + assert_eq!(through, ["inside.bin"], "a walk that enters one follows"); + } + + #[test] + fn a_large_directory_spans_several_buffers() { + let temp = TempDir::new().expect("tempdir"); + // Long names so the records overflow one 64 KiB buffer many times. + for index in 0..2000 { + let name = format!("{index:04}-{}", "n".repeat(120)); + fs::write(temp.path().join(name), b"").expect("write"); + } + let entries = listed(temp.path()); + assert_eq!(entries.len(), 2000); + assert!( + entries[1999] + .file_name() + .to_string_lossy() + .starts_with("1999") + ); + } + + #[test] + fn free_space_is_plausible_and_a_missing_path_is_not_found() { + let temp = TempDir::new().expect("tempdir"); + let space = space_info(temp.path()).expect("space"); + assert!(space.total > 0 && space.free <= space.total, "{space:?}"); + assert!(space.available <= space.free, "{space:?}"); + let error = space_info(&temp.path().join("absent")) + .expect_err("no such directory"); + assert_eq!(error.kind(), io::ErrorKind::NotFound); + } + + #[test] + fn a_path_is_on_its_drive_and_a_folder_is_no_mount_point() { + let temp = TempDir::new().expect("tempdir"); + let drive = temp.path().ancestors().last().expect("a drive"); + let root = volume_root(temp.path()).expect("a volume"); + assert!( + same(&root, drive), + "{} on {}", + root.display(), + drive.display() + ); + assert!(!is_mount_point(temp.path())); + assert!(!is_mount_point(drive), "a drive is a root, not a folder"); + } + + #[test] + fn paths_compare_without_case_or_verbatim_prefixes() { + let windows = Path::new(r"C:\Windows"); + assert!(within(Path::new(r"c:\WINDOWS\System32"), windows)); + assert!(within(Path::new(r"\\?\C:\Windows\Temp"), windows)); + assert!(!within(Path::new(r"C:\Windows.old"), windows), "components"); + assert!(!within(Path::new(r"D:\Windows"), windows)); + assert!(same( + Path::new(r"\\server\Share\Dir"), + Path::new(r"\\?\UNC\SERVER\share\dir") + )); + assert!(within( + Path::new(r"C:\Users\Олег\x"), + Path::new(r"c:\users\ОЛЕГ") + )); + } + + #[test] + fn times_convert_to_unix_seconds() { + assert_eq!(unix_seconds(0), 0, "before 1970"); + assert_eq!(unix_seconds(EPOCH_TICKS), 0); + assert_eq!(unix_seconds(EPOCH_TICKS + 90 * TICKS_PER_SECOND), 90); + } + + #[test] + fn only_whole_ids_name_a_file() { + assert_eq!(file_id(0), None, "no id at all"); + assert_eq!(file_id(0x0005_0000_0000_1234), Some(0x0005_0000_0000_1234)); + assert_eq!(file_id((1 << 64) | 7), None, "a ReFS id needs both halves"); + } +} From cac3d76c3fdcb4e3430042926f06cb4272188337 Mon Sep 17 00:00:00 2001 From: Oleg Shevchuk Date: Fri, 25 Sep 2026 15:09:09 +0500 Subject: [PATCH 07/17] core: refuse a directory that holds the home directory Removing a directory takes what is inside it. In a whole-disk scan on Windows, C:\Users is an ordinary directory that passes every other guard, and so is /home on a Linux install without a separate volume: marking either would remove the home directory the guards are there to protect. --- AGENTS.md | 3 ++- README.md | 4 +++- crates/disktree-core/src/removal.rs | 29 +++++++++++++++++++++++++++-- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 30a5414..3dd73b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,7 +63,8 @@ done, and it must not fix anything: a red local run is the same signal CI gives. has finished.** That is the `+1` sentinel in `PendingDir::pending`. Building early silently drops whole subtrees — it has happened once. 4. **Only paths under the scanned root may be removed**, and mount points, the - root, the home directory and symlink targets are refused. + root, the home directory, any directory holding it, and symlink targets are + refused. 5. **Marks are keyed by absolute path**, not tree position, so they survive a re-scan; `Marks::refresh` re-reads their sizes and drops what is gone. 6. **The treemap is painted, not composed of elements.** Thousands of diff --git a/README.md b/README.md index e1c1580..5c2b37c 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,9 @@ The removal rules live in `crates/disktree-core/src/removal.rs`, and each one is tested: - only paths under the scanned root can be removed; -- the filesystem root, the scanned root and your home directory are refused; +- the filesystem root, the scanned root and your home directory are refused, + and so is any directory holding your home directory, which would take it + along; - a mount point is refused, since removing it would reach into another filesystem; - system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, …) are diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index 08b4b58..f2c2bb2 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -242,8 +242,15 @@ fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { if same(path, root) { return Some("the scanned root cannot be removed".into()); } - if home.is_some_and(|home| same(path, &normalize(home))) { - return Some("the home directory cannot be removed".into()); + if let Some(home) = home.map(normalize) { + if same(path, &home) { + return Some("the home directory cannot be removed".into()); + } + // A directory goes with everything in it, so `/home` or `C:\Users` + // would take the home directory along. + if within(&home, path) { + return Some("it contains the home directory".into()); + } } if !within(path, root) { return Some("outside the scanned root".into()); @@ -783,6 +790,24 @@ mod tests { ); } + /// Removing a directory takes what is inside it, so the directories + /// above home are refused too: in a whole-disk scan, `C:\Users` is an + /// ordinary directory, and so is `/home` without a separate volume. + #[test] + fn a_directory_holding_the_home_directory_is_refused() { + let home = Path::new("/home/tobi"); + let reason = refuse(Path::new("/home"), Path::new("/"), Some(home)); + assert!( + reason.is_some_and(|reason| reason.contains("home directory")), + "the home directory is inside it" + ); + assert_eq!( + refuse(Path::new("/home/other"), Path::new("/"), Some(home)), + None, + "a sibling of home is not" + ); + } + #[test] fn paths_outside_the_root_are_refused() { let temp = tree(); From 5aa98e38180b7dae06bce2d2da9326758a943cf6 Mon Sep 17 00:00:00 2001 From: Oleg Shevchuk Date: Fri, 25 Sep 2026 15:09:18 +0500 Subject: [PATCH 08/17] app: run on Windows - The home directory comes from std::env::home_dir, which reads USERPROFILE on Windows and HOME elsewhere. - The root is canonicalized through dunce, so Windows paths read C:\Users\... rather than \?\C:\..., the form nothing else is written in and which would never match the home directory. - A windowed program on Windows: no console window from Explorer or the Start menu. It attaches to the console of a terminal it was started from, as Alacritty does, so --help and errors still show there. - Paths after ~ and the trail between crumbs use the platform's separator: ~\AppData\Local, C:\ Users \ tobi. --- Cargo.lock | 2 + crates/disktree-app/Cargo.toml | 4 ++ crates/disktree-app/src/main.rs | 63 +++++++++++++++++++++++++++----- crates/disktree-app/src/marks.rs | 12 ++++-- crates/disktree-app/src/state.rs | 2 +- crates/disktree-app/src/tests.rs | 6 ++- crates/disktree-app/src/views.rs | 4 +- 7 files changed, 76 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 832669d..ee104b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1424,10 +1424,12 @@ version = "0.9.1" dependencies = [ "anyhow", "disktree-core", + "dunce", "gpui-kit", "gpui-omarchy", "rustc-hash 2.1.3", "tempfile", + "windows-sys 0.61.2", ] [[package]] diff --git a/crates/disktree-app/Cargo.toml b/crates/disktree-app/Cargo.toml index 63644e0..02d93aa 100644 --- a/crates/disktree-app/Cargo.toml +++ b/crates/disktree-app/Cargo.toml @@ -18,8 +18,12 @@ gpui-kit = { version = "=0.6.1", default-features = false, features = ["assets"] gpui-omarchy = "0.1.2" disktree-core = { workspace = true } anyhow = { workspace = true } +dunce = "1.0.5" rustc-hash = { workspace = true } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_System_Console"] } + [dev-dependencies] # The window harness: it lets the tests draw a real frame and press real keys. gpui-kit = { version = "=0.6.1", default-features = false, features = [ diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 22b8265..6d17cfd 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -5,6 +5,12 @@ //! live free-space meter. Marking is non-destructive until the review screen //! is confirmed. +// A window, not a console program: on Windows, opening it from Explorer or +// the Start menu should not bring a console window along. `main` attaches to +// the console of a terminal it was started from, so `--help` and errors still +// reach one. Ignored elsewhere. +#![windows_subsystem = "windows"] + mod git; mod marks; mod palette; @@ -56,6 +62,15 @@ options: "; fn main() -> Result<()> { + #[cfg(windows)] + console::attach(); + let outcome = run(); + #[cfg(windows)] + console::detach(); + outcome +} + +fn run() -> Result<()> { let args = parse_args()?; let root = args.root.clone(); let depth = args.depth; @@ -82,9 +97,7 @@ fn main() -> Result<()> { "disktree · {}", marks::display_path( &title_root, - std::env::var_os("HOME") - .map(PathBuf::from) - .as_deref(), + std::env::home_dir().as_deref(), ) ) .into(), @@ -173,21 +186,21 @@ fn parse_args() -> Result { !(disk && root.is_some()), "--disk and a PATH cannot be combined" ); - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let root = match root { _ if disk => home .as_deref() .and_then(disktree_core::space::volume_root_for) .unwrap_or_else(|| PathBuf::from("/")), Some(root) => root, - None => std::env::var_os("HOME") - .map(PathBuf::from) - .context("no path given and HOME is not set")?, + None => home.context("no path given and no home directory")?, }; // Store the depth as the initial view setting rather than a scan option: it // is a display choice the run-time `[` and `]` keys also change. - // Canonical, so a later widening recognises this tree in the wider walk. - let root = root.canonicalize().unwrap_or(root); + // Canonical, so a later widening recognises this tree in the wider walk; + // through dunce, so Windows gets `C:\Users\…` rather than the `\\?\C:\…` + // form nothing else is written in. + let root = dunce::canonicalize(&root).unwrap_or(root); let metadata = std::fs::metadata(&root) .with_context(|| format!("cannot read {}", root.display()))?; anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display()); @@ -198,3 +211,35 @@ fn parse_args() -> Result { depth: depth.clamp(1, 6), }) } + +/// The console of the terminal disktree was started from, if any: a +/// windowed program on Windows gets none of its own. +#[cfg(windows)] +mod console { + #![allow( + unsafe_code, + reason = "two Win32 calls that take no pointers to get wrong" + )] + + use windows_sys::Win32::System::Console::{ + ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole, + }; + + /// Borrow the parent's console so printed text reaches it. Does + /// nothing when started from Explorer, which has none. + pub fn attach() { + // SAFETY: takes a process id by value, and failure only means + // there was no console to attach to. + unsafe { + AttachConsole(ATTACH_PARENT_PROCESS); + } + } + + /// Let go of it again, so the shell redraws its prompt. + pub fn detach() { + // SAFETY: no arguments; a process without a console is left as is. + unsafe { + FreeConsole(); + } + } +} diff --git a/crates/disktree-app/src/marks.rs b/crates/disktree-app/src/marks.rs index 51483ce..89141ae 100644 --- a/crates/disktree-app/src/marks.rs +++ b/crates/disktree-app/src/marks.rs @@ -107,13 +107,16 @@ pub fn is_hidden(path: &Path) -> bool { } /// Shorten a path for display: `~` for the home directory, and the path with -/// the home prefix replaced when it is below it. +/// the home prefix replaced when it is below it. The separator after `~` is +/// the platform's, so Windows shows `~\AppData\Local`, not `~/AppData\Local`. pub fn display_path(path: &Path, home: Option<&Path>) -> String { match home .and_then(|home| path.strip_prefix(home).ok().map(|rest| (home, rest))) { Some((_, rest)) if rest.as_os_str().is_empty() => "~".to_string(), - Some((_, rest)) => format!("~/{}", rest.display()), + Some((_, rest)) => { + format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()) + } None => path.display().to_string(), } } @@ -220,9 +223,10 @@ mod tests { #[test] fn display_path_shortens_the_home_prefix() { let home = Path::new("/home/tobi"); + let separator = std::path::MAIN_SEPARATOR; assert_eq!( - display_path(Path::new("/home/tobi/.cache/npm"), Some(home)), - "~/.cache/npm" + display_path(&home.join(".cache").join("npm"), Some(home)), + format!("~{separator}.cache{separator}npm") ); assert_eq!(display_path(home, Some(home)), "~"); assert_eq!(display_path(Path::new("/var/log"), Some(home)), "/var/log"); diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 6a2212a..4d8212c 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -414,7 +414,7 @@ impl Disktree { depth: u32, cx: &mut Context<'_, Self>, ) -> Self { - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let space = space_info(&root_path).ok(); let trash_backend = detect_trash_backend(); let mut tree = Self { diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 946b06a..846f359 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -943,9 +943,11 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest( }); let before = read(&view, cx, |app| app.tree().map(|tree| tree.files)); - // The trail runs from "/", and the scanned root sits under its parents. + // The trail runs from the top of the filesystem — "/", or a drive such + // as "C:\" — and the scanned root sits under its parents. let trail = read(&view, cx, Disktree::breadcrumbs); - assert_eq!(trail[0].0, "/"); + let top = temp.path().ancestors().last().expect("a top"); + assert_eq!(trail[0].0, top.display().to_string()); assert!( trail.contains(&( temp.path() diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index ca7b193..4062ce5 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -363,11 +363,13 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { /// Steps a trail shows before it folds its middle into an ellipsis. const TRAIL_STEPS: usize = 7; +/// The platform's path separator, so the trail reads like the paths shown +/// elsewhere: `/` here, `\` on Windows. fn separator_glyph(theme: &Theme) -> Div { div() .text_color(theme.secondary.opacity(0.5)) .text_size(text::BODY) - .child("/") + .child(std::path::MAIN_SEPARATOR_STR) } /// A crumb in the tree. Its label goes there (the current one opens the From 82d73fbcf875c017b67823520ae9a2db14a3ba61 Mon Sep 17 00:00:00 2001 From: Oleg Shevchuk Date: Fri, 25 Sep 2026 15:09:27 +0500 Subject: [PATCH 09/17] CI and releases on Windows; README - CI runs the lint gate and the tests on windows-2025 beside Ubuntu, on the same pinned toolchain. - A tag also publishes disktree--x86_64-windows.zip, built after the Linux job, which checks the tag and creates the release. The C runtime is linked in, so it runs without the Visual C++ redistributable. - README says how to install on Windows and what differs there; AGENTS points at windows.rs and says how to run the gate without make. --- .github/workflows/ci.yml | 24 ++++++++++++++++ .github/workflows/release.yml | 53 +++++++++++++++++++++++++++++++++++ AGENTS.md | 6 +++- README.md | 37 ++++++++++++++++++++++++ 4 files changed, 119 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d14d6e..058c6c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,3 +43,27 @@ jobs: - name: Test run: cargo xtask test + + windows: + name: Lint and test (Windows) + runs-on: windows-2025 + steps: + # Check out with the repository's own line endings, as on Linux. + - run: git config --global core.autocrlf false + + - uses: actions/checkout@v5 + + # Pinned with the Linux job, for the same reason. GPUI needs nothing + # beyond the Windows SDK the runner already has. + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + components: clippy, rustfmt + + - uses: Swatinem/rust-cache@v2 + + - name: Lint + run: cargo xtask lint + + - name: Test + run: cargo xtask test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed382d8..1802562 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,6 +23,9 @@ jobs: # The oldest supported runner: its glibc is what the binary needs at # least, so building here runs on the most systems. runs-on: ubuntu-22.04 + outputs: + tag: ${{ steps.version.outputs.tag }} + version: ${{ steps.version.outputs.version }} steps: - uses: actions/checkout@v5 with: @@ -86,3 +89,53 @@ jobs: gh release create "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" \ --title "disktree ${TAG#v}" --generate-notes fi + + windows: + name: Build and publish (Windows) + # After the Linux job, which checks the tag and creates the release. + needs: release + runs-on: windows-2025 + env: + # The C runtime linked in, so disktree.exe also runs where the Visual + # C++ runtime was never installed. For the tests too, so both steps + # share one build. + RUSTFLAGS: -C target-feature=+crt-static + steps: + - run: git config --global core.autocrlf false + + - uses: actions/checkout@v5 + with: + ref: ${{ inputs.tag || github.ref }} + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + + - uses: Swatinem/rust-cache@v2 + + - name: Test + run: cargo xtask test + + - name: Build + run: cargo build --release --locked -p disktree-app + + - name: Package + id: package + shell: pwsh + run: | + $name = "disktree-${{ needs.release.outputs.version }}-x86_64-windows" + New-Item -ItemType Directory -Force "dist/$name" | Out-Null + Copy-Item target/release/disktree.exe, README.md, LICENSE "dist/$name/" + Compress-Archive -Path "dist/$name" -DestinationPath "dist/$name.zip" + $hash = (Get-FileHash "dist/$name.zip" -Algorithm SHA256).Hash.ToLower() + # The format `sha256sum -c` reads, with a Unix line ending. + [IO.File]::WriteAllText("dist/$name.zip.sha256", "$hash $name.zip`n") + "archive=dist/$name.zip" >> $env:GITHUB_OUTPUT + + - name: Publish + shell: bash + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.release.outputs.tag }} + ARCHIVE: ${{ steps.package.outputs.archive }} + run: gh release upload "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" --clobber diff --git a/AGENTS.md b/AGENTS.md index 3dd73b0..d1ad868 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,8 @@ entry's `Categories` to a single main category plus additional ones, or `cargo xtask lint` is the gate. It must be green before anything is called done, and it must not fix anything: a red local run is the same signal CI gives. +On Windows, where there is no make, run `cargo xtask lint`, `cargo xtask test` +and `cargo build --release` directly; CI runs the gate on both systems. ## House rules @@ -54,7 +56,8 @@ done, and it must not fix anything: a red local run is the same signal CI gives. ## Invariants 1. **Sizes come from `st_blocks * 512` unless apparent size was asked for.** - That is the number that comes back when a file is deleted. + That is the number that comes back when a file is deleted. On Windows it + is the allocation the directory listing reports; see `windows.rs`. 2. **`own_bytes`/`own_files` are derived, never tracked.** `tree::aggregate` computes the totals from the children. Hardlink de-duplication rewrites a leaf's weight and re-aggregates; anything that patches `bytes` directly will @@ -89,6 +92,7 @@ done, and it must not fix anything: a red local run is the same signal CI gives. | tile geometry, nesting, the merged tail | `crates/disktree-core/src/treemap.rs` | | anything that deletes, or refuses to | `crates/disktree-core/src/removal.rs` | | free space and projections | `crates/disktree-core/src/space.rs` | +| what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — the only `unsafe` | | a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` | | spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout | | the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` | diff --git a/README.md b/README.md index 5c2b37c..afc9aca 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,18 @@ removes exactly what was installed. You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI can drive (Vulkan). +On Windows 10 or 11, download `disktree-*-x86_64-windows.zip` from the same +release, unpack it anywhere and run `disktree.exe`. Or build it with the MSVC +toolchain (Visual Studio Build Tools, C++ workload): + +```powershell +git clone https://github.com/tobi/disktree +cd disktree +cargo build --release # target\release\disktree.exe +``` + +See [On Windows](#on-windows) for what differs there. + ## Use ```sh @@ -184,6 +196,31 @@ twice. `-X` crosses into everything. Without root, some system directories cannot be read; they are counted as unreadable in the top bar rather than guessed at. +## On Windows + +The same program, with Windows' answers to the questions above: + +- **Disk usage** is the allocation NTFS reports for each file: whole + clusters, less for a compressed or sparse file, nothing for one small + enough to live in its file record. It arrives with the directory listing + itself (`FileIdExtdDirectoryInfo`), so it costs no more than the walk. + Hardlinks count once on NTFS. +- **The whole disk** is the drive your profile is on, usually `C:\`. A + folder another volume is mounted on is a link, like a junction, and is + not entered, so a scan stays on one volume; `-l` follows links, and with + them mounted folders. +- **Move to trash** is the Recycle Bin, through the shell, which asks + before destroying anything it cannot recycle. +- **Refused besides the rules below:** Windows, Program Files and + ProgramData, what Windows keeps at the top of its drive (System Volume + Information, Recovery, Boot), and any folder holding your profile, such as + `C:\Users`. Names compare without regard to case, as Windows compares + them. +- **Hidden** still means a name starting with a dot; the hidden attribute is + not consulted, so `-H` does not drop `AppData`. +- **The theme** is gpui-omarchy's default, since there is no Omarchy theme + to follow. + ## What it refuses to do The removal rules live in `crates/disktree-core/src/removal.rs`, and each one is From 21157ca87853e153a0c1d873dff556f214b8d909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 14:01:06 +0000 Subject: [PATCH 10/17] README: restore the history and window-class notes --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3990695..60d3a5e 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,9 @@ Scroll to magnify toward the pointer. The wheel magnifies until the directory under the pointer fills the view, and the next notch goes into it — one continuous motion, with the directory's contents growing into place. Scroll the other way to come back out. Enter goes into the selected directory at any -depth, and Backspace or Escape goes up one level. `+` and `-` magnify without +depth, and Backspace or Escape goes up one level. `<` and `>`, beside the +Size / Files / Age switch, go back and forward through the directories visited, +as do `alt ←` `alt →` and the mouse's side buttons. `+` and `-` magnify without going in; `0` resets. ### Removing @@ -169,6 +171,7 @@ and shows how much free space was actually gained. | `ctrl`-click (`⌘`-click on macOS) | mark without moving the selection | | `enter` | open that directory, at any depth | | `⌫` / `esc` | go up one directory | +| `alt ←` `alt →` | back and forward through where you have been | | `←` `↑` `↓` `→` | move between tiles at this level | | `tab` | next largest sibling | | scroll | zoom toward a directory, then go into it | @@ -263,7 +266,8 @@ tested: ## On Hyprland Hyprland tiles new windows, so disktree opens into whatever tile it is given. -It is designed for a roomy window; float it, or give it a rule: +It is designed for a roomy window; float it, or give it a rule. The window +class is `disktree`. ``` windowrule = float, class:^(disktree)$ From 1220150762e256ff931ba002ccb6baaac2c0efa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 14:14:22 +0000 Subject: [PATCH 11/17] removal: close the path race, and judge mounts again before removing Permanent deletion opened its target by full path, following any symlink on the way down. A directory swapped for a link after the scan (a shared /tmp, say) redirected the removal: `/tmp/d/x` marked, `d` made a link to `~`, and `~/x` went. The way down is now opened one component at a time with O_NOFOLLOW (O_PATH on Linux), and the target removed with unlinkat relative to its parent. The scanned root is canonical, so a marked path never legitimately has a link on it. The plan is judged against a mount table read on a background thread, empty until the first read lands and up to two seconds old after. The removal worker now reads it fresh and checks each target for a mount point on it or inside it before touching anything. Permanent deletion stopped at a mount boundary already; the trash did not. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/disktree-core/src/removal.rs | 138 ++++++++++++++++++++++++++-- 1 file changed, 130 insertions(+), 8 deletions(-) diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index ded9e4c..0e67a4a 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -771,14 +771,22 @@ fn run( let mut removed = 0_u64; let mut bytes = 0_u64; let mut failed = 0_usize; + // The plan was judged against a mount table up to `MOUNTS_FRESH` old, + // or, right after start, not read yet. Judged again against a fresh + // read, here on the worker, before anything is touched. + let mounts = read_mount_points(); for target in &plan.targets { if cancel.load(Ordering::Relaxed) { break; } - let outcome = match mode { - RemovalMode::Permanent => remove_permanently(&target.path), - RemovalMode::Trash => move_to_trash(&target.path, backend), + let outcome = if let Some(reason) = mounted(&target.path, &mounts) { + Err(io::Error::other(reason)) + } else { + match mode { + RemovalMode::Permanent => remove_permanently(&target.path), + RemovalMode::Trash => move_to_trash(&target.path, backend), + } }; if outcome.is_ok() { removed += 1; @@ -800,6 +808,21 @@ fn run( }); } +/// Why `path` would reach into another filesystem, if it would: the +/// mount-point rules of [`refuse`], asked again at removal time. +fn mounted(path: &Path, mounts: &[PathBuf]) -> Option { + if is_mount_point(path) { + return Some("it became a mount point since it was marked".into()); + } + mount_below(&guard_key(path), mounts).map(|mount| { + format!( + "{} is mounted inside it: removing it would reach into another \ + filesystem", + mount.display() + ) + }) +} + /// `rm -rf --one-file-system` semantics: a symlink is unlinked, never /// followed, and nothing on another filesystem is touched. /// @@ -809,16 +832,87 @@ fn run( /// `O_NOFOLLOW`, and one on a different device or mount stops the removal. /// (From tobi/disktree#10.) /// +/// The same goes for the way down to `path`: see [`open_parent`]. #[cfg(unix)] pub fn remove_permanently(path: &Path) -> io::Result<()> { - let meta = fs::symlink_metadata(path)?; - if !meta.is_dir() { - return fs::remove_file(path); + use rustix::fs::{AtFlags, FileType, statat, unlinkat}; + + let (parent, name) = open_parent(path)?; + let stat = statat(&parent, name, AtFlags::SYMLINK_NOFOLLOW)?; + if FileType::from_raw_mode(stat.st_mode) != FileType::Directory { + unlinkat(&parent, name, AtFlags::empty())?; + return Ok(()); } - let dir = open_dir(rustix::fs::CWD, path)?; + let dir = open_dir(&parent, name)?; let top = Volume::of(&dir)?; remove_contents(&dir, &top, path)?; - fs::remove_dir(path) + drop(dir); + unlinkat(&parent, name, AtFlags::REMOVEDIR)?; + Ok(()) +} + +/// The directory holding `path`, and `path`'s own name in it. +/// +/// Opened one component at a time from `/`, none of them followed if it is +/// a symlink. The scanned root is canonical, so no marked path has a symlink +/// on its way down; one that does now was put there after the scan, and +/// following it would remove whatever it points to — a directory swapped +/// for a link to `~` would take `~/x` in place of the `/tmp/d/x` that was +/// marked. `rm -rf` has the same race; this closes it. +#[cfg(unix)] +fn open_parent( + path: &Path, +) -> io::Result<(std::os::fd::OwnedFd, &std::ffi::OsStr)> { + use rustix::io::Errno; + + let not_marked = || { + io::Error::other(format!( + "{} is not an absolute, normalized path", + path.display() + )) + }; + let name = path.file_name().ok_or_else(not_marked)?; + let parent = path.parent().ok_or_else(not_marked)?; + let mut dir = open_step(rustix::fs::CWD, "/")?; + for component in parent.components() { + match component { + Component::RootDir => {} + Component::Normal(part) => { + dir = open_step(&dir, part).map_err(|error| match error { + Errno::LOOP | Errno::NOTDIR => io::Error::other(format!( + "{} changed since the scan: {} is no longer a \ + directory, so nothing was removed", + path.display(), + part.display() + )), + error => error.into(), + })?; + } + _ => return Err(not_marked()), + } + } + Ok((dir, name)) +} + +/// Open a directory on the way down to a target, not following a symlink. +/// Only a handle to walk through: on Linux `O_PATH`, which needs no read +/// permission, just as a path lookup does not. +#[cfg(unix)] +fn open_step( + parent: impl std::os::fd::AsFd, + name: P, +) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, openat}; + #[cfg(any(target_os = "linux", target_os = "android"))] + let access = OFlags::PATH; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let access = OFlags::RDONLY; + openat( + parent, + name, + access | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) } #[cfg(not(unix))] @@ -1517,6 +1611,34 @@ mod tests { assert!(keep.path().join("precious.bin").exists()); } + /// Marked as `a/b/x`, then `a/b` swapped for a link to somewhere else + /// holding an `x`: that other `x` must survive. + #[test] + #[cfg(unix)] + fn permanent_removal_does_not_follow_a_link_put_on_the_way_down() { + let temp = tree(); + let keep = TempDir::new().expect("tempdir"); + fs::create_dir(keep.path().join("x")).expect("mkdir"); + fs::write(keep.path().join("x/precious.bin"), b"data").expect("write"); + let marked = temp.path().join("a/b/x"); + fs::remove_dir_all(temp.path().join("a/b")).expect("clear"); + link_dir(keep.path(), &temp.path().join("a/b")); + + let error = remove_permanently(&marked).expect_err("refused"); + assert!(error.to_string().contains("changed since"), "{error}"); + assert!(keep.path().join("x/precious.bin").exists()); + } + + #[test] + fn a_mount_below_a_target_is_caught_again_at_removal_time() { + let temp = tree(); + let root = temp.path(); + let mounts = vec![guard_key(&root.join("a/b"))]; + let reason = mounted(&root.join("a"), &mounts).expect("caught"); + assert!(reason.contains("mounted inside"), "{reason}"); + assert_eq!(mounted(&root.join("other"), &mounts), None); + } + /// Git keeps its objects read-only, which on Windows stops a plain /// delete; clearing an old checkout must still work. #[test] From 41331f363fa28cbd5b42b5e0717e085aef6e3344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 14:16:36 +0000 Subject: [PATCH 12/17] =?UTF-8?q?macOS:=20=E2=8C=98[=20and=20=E2=8C=98]=20?= =?UTF-8?q?for=20back=20and=20forward,=20and=20a=20Go=20menu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What Finder and Safari use; alt-arrows from #12 still work. Only on the explore screen, where the history buttons are. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 4 ++-- crates/disktree-app/src/app_menu.rs | 15 +++++++++++++-- crates/disktree-app/src/views.rs | 13 +++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index bf3c21f..cb9d37e 100644 --- a/README.md +++ b/README.md @@ -158,8 +158,8 @@ continuous motion, with the directory's contents growing into place. Scroll the other way to come back out. Enter goes into the selected directory at any depth, and Backspace or Escape goes up one level. `<` and `>`, beside the Size / Files / Age switch, go back and forward through the directories visited, -as do `alt ←` `alt →` and the mouse's side buttons. `+` and `-` magnify without -going in; `0` resets. +as do `alt ←` `alt →` (also `⌘[` `⌘]` on macOS) and the mouse's side +buttons. `+` and `-` magnify without going in; `0` resets. ### Removing diff --git a/crates/disktree-app/src/app_menu.rs b/crates/disktree-app/src/app_menu.rs index 382844d..00804ca 100644 --- a/crates/disktree-app/src/app_menu.rs +++ b/crates/disktree-app/src/app_menu.rs @@ -35,6 +35,10 @@ mod menu_actions { OpenFolder, /// Reveal the tile a key acts on in Finder. ShowInFinder, + /// Back through the directories visited. + GoBack, + /// Forward again, after going back. + GoForward, ] ); } @@ -62,8 +66,8 @@ pub fn install(cx: &mut App) { let _ = window.update(cx, |_, window, _| window.remove_window()); } }); - // `Rescan`, `OpenFolder` and `ShowInFinder` are handled by the window, - // which owns the scan and the selection; see `views::root`. + // `Rescan`, `OpenFolder`, `ShowInFinder` and the history are handled by + // the window, which owns the scan and the selection; see `views::root`. cx.bind_keys([ KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("cmd-h", Hide, None), @@ -74,6 +78,9 @@ pub fn install(cx: &mut App) { // ⌘R is taken by Rescan, as in a browser; Xcode uses ⌘⇧R-like // chords for its reveals, and `o` does the same without a modifier. KeyBinding::new("cmd-shift-r", ShowInFinder, None), + // Finder's and Safari's back and forward; alt-arrows work too. + KeyBinding::new("cmd-[", GoBack, None), + KeyBinding::new("cmd-]", GoForward, None), ]); cx.set_menus([ Menu::new("disktree").items([ @@ -93,5 +100,9 @@ pub fn install(cx: &mut App) { MenuItem::separator(), MenuItem::action("Close Window", CloseWindow), ]), + Menu::new("Go").items([ + MenuItem::action("Back", GoBack), + MenuItem::action("Forward", GoForward), + ]), ]); } diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index b8e53cc..fc5541e 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -75,6 +75,19 @@ pub fn root( this.reveal_target(cx); }, )) + // Only where the history buttons are: the review screen has none. + .on_action(cx.listener(|this, _: &crate::app_menu::GoBack, _, cx| { + if this.screen == Screen::Explore { + this.go_back(cx); + } + })) + .on_action(cx.listener( + |this, _: &crate::app_menu::GoForward, _, cx| { + if this.screen == Screen::Explore { + this.go_forward(cx); + } + }, + )) .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { if this.zoom_interface(event, window) { cx.notify(); From f2a00569606bab658bf1c5fca5a2314b670fca35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 14:24:31 +0000 Subject: [PATCH 13/17] git: a checkout's config can no longer run programs through the status probe `git stash list` is `git log`: a repository that sets log.showSignature and gpg.program ran that program when the Explore screen probed it. Count stashes from the reflog, and turn off every program-valued key and network path the probe could reach. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/disktree-app/src/git.rs | 90 ++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 3 deletions(-) diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index 84540af..ec88f55 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -71,8 +71,15 @@ pub fn state(path: &Path) -> Option { )?; Some(status.split('\0').filter(|line| !line.is_empty()).count()) }; - let stashes = - run(path, &["stash", "list"]).map_or(0, |list| list.lines().count()); + // Counted from the reflog, not listed: `stash list` is `git log`, which + // verifies signatures with the checkout's `gpg.program` when its config + // sets `log.showSignature`. + let stashes = run( + path, + &["rev-list", "--walk-reflogs", "--count", "refs/stash"], + ) + .and_then(|count| count.trim().parse().ok()) + .unwrap_or(0); let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"]) .and_then(|count| count.trim().parse().ok()); Some(GitState { @@ -157,7 +164,9 @@ fn git(path: &Path, args: &[&str]) -> Option { // fsmonitor on every `status`, hooks, a pager. Selecting a directory // in a disk viewer must not execute anything it contains, and a // command-line `-c` outranks the repository's config. (From - // tobi/disktree#10.) + // tobi/disktree#10.) Also a signature verifier, and whatever a + // partial clone would run to fetch a missing object: nothing here + // may reach the network either. .args([ "-c", "core.fsmonitor=false", @@ -165,11 +174,24 @@ fn git(path: &Path, args: &[&str]) -> Option { "core.hooksPath=/dev/null", "-c", "core.pager=cat", + "-c", + "log.showSignature=false", + "-c", + "gpg.program=false", + "-c", + "gpg.ssh.program=false", + "-c", + "gpg.x509.program=false", + "-c", + "core.sshCommand=false", + "-c", + "protocol.allow=never", ]) .args(args) // Never prompt, never page, never take a lock for the index refresh. .env("GIT_TERMINAL_PROMPT", "0") .env("GIT_OPTIONAL_LOCKS", "0") + .env("GIT_NO_LAZY_FETCH", "1") .stdin(Stdio::null()) .stderr(Stdio::null()) .output() @@ -263,6 +285,68 @@ mod tests { assert!(!marker.exists(), "the checkout's fsmonitor ran"); } + /// A signed stash and `log.showSignature`: listing stashes the way + /// `git stash list` does would run the checkout's `gpg.program`. + #[cfg(unix)] + #[test] + fn a_checkout_cannot_make_git_verify_a_signature_with_its_program() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let gpg = dir.path().join("gpg.sh"); + std::fs::write( + &gpg, + format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display()), + ) + .expect("write gpg"); + std::fs::set_permissions(&gpg, std::fs::Permissions::from_mode(0o755)) + .expect("chmod"); + let git = |args: &[&str], input: Option<&str>| { + use std::io::Write as _; + let mut child = Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .ok()?; + let mut stdin = child.stdin.take()?; + stdin.write_all(input.unwrap_or("").as_bytes()).ok()?; + drop(stdin); + let output = child.wait_with_output().ok()?; + output.status.success().then(|| { + String::from_utf8_lossy(&output.stdout).trim().to_owned() + }) + }; + if !git_installed() || git(&["init", "-q"], None).is_none() { + return; // no git on this machine + } + let tree = git(&["mktree"], None).expect("empty tree"); + let commit = format!( + "tree {tree}\nauthor t 0 +0000\ncommitter t 0 +0000\n\ + gpgsig -----BEGIN PGP SIGNATURE-----\n \n \ + -----END PGP SIGNATURE-----\n\nstash\n" + ); + let id = git( + &["hash-object", "-t", "commit", "-w", "--stdin"], + Some(&commit), + ) + .expect("a signed commit"); + assert!( + git(&["update-ref", "--create-reflog", "refs/stash", &id], None) + .is_some() + ); + let gpg = gpg.to_string_lossy(); + assert!(git(&["config", "log.showSignature", "true"], None).is_some()); + assert!(git(&["config", "gpg.program", &gpg], None).is_some()); + + let state = state(dir.path()).expect("a checkout"); + assert!(!marker.exists(), "the checkout's gpg.program ran"); + assert_eq!(state.stashes, 1, "the stash is still counted"); + } + #[cfg(unix)] #[test] fn a_checkouts_own_filter_is_never_run() { From d37870cdeae492865246e83abf59da7b8299027d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 14:27:05 +0000 Subject: [PATCH 14/17] removal: refuse names Win32 misreads, links on the way down, and home by its real path - Windows strips trailing dots and spaces and maps NUL/COM1 to devices, so a scanned `C:\Users.` would have removed `C:\Users`. Refused. - The trash (everywhere) and removal on Windows follow a link on the way to a target out of the scanned root. The real parent is compared with the real root, in the plan and again on the worker. - The home directory is also matched by its canonical path, so a link such as /home -> /data/home no longer hides it from 'contains home'. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/disktree-core/src/removal.rs | 200 +++++++++++++++++++++++++++- 1 file changed, 197 insertions(+), 3 deletions(-) diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index 0e67a4a..cfdb3ad 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -76,6 +76,8 @@ pub struct Plan { pub covered: Vec, /// Marked paths that must not be touched. pub blocked: Vec, + /// The scanned root the targets were judged against. + pub root: PathBuf, } impl Plan { @@ -94,7 +96,10 @@ impl Plan { /// looking at is the only thing they consented to act on. pub fn plan(targets: &[Target], root: &Path) -> Plan { let root = normalize(root); - let mut plan = Plan::default(); + let mut plan = Plan { + root: root.clone(), + ..Plan::default() + }; let mut accepted: Vec = Vec::new(); if targets.is_empty() { @@ -103,10 +108,15 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { let mounts = mount_points(); // Once per plan, not per target: the review screen plans every frame. let home = std::env::home_dir().map(|home| Home::of(&home)); + let real_root = fs::canonicalize(&root).ok(); for target in targets { let path = normalize(&target.path); - if let Some(reason) = refuse(&path, &root, home.as_ref(), &mounts) { + let reason = + refuse(&path, &root, home.as_ref(), &mounts).or_else(|| { + linked(&path, &root, real_root.as_deref(), home.as_ref()) + }); + if let Some(reason) = reason { plan.blocked.push(Blocked { path: target.path.clone(), reason, @@ -320,6 +330,10 @@ fn system_tree_below(key: &Path) -> Option<&'static str> { #[derive(Debug)] struct Home { key: PathBuf, + /// The key of the path with every link resolved: `/home` may be a link + /// to `/data/home`, and a scan of `/data` then shows home under a + /// spelling [`Self::key`] does not match. + real: Option, /// Device and inode (volume and file id on Windows), so a spelling /// [`guard_key`] cannot fold still matches. id: Option<(u64, u64)>, @@ -329,6 +343,7 @@ impl Home { fn of(path: &Path) -> Self { Self { key: guard_key(path), + real: fs::canonicalize(path).ok().map(|real| guard_key(&real)), id: identity(path, true), } } @@ -349,6 +364,19 @@ fn refuse( if key == root_key { return Some("the scanned root cannot be removed".into()); } + if cfg!(windows) + && let Some(name) = path.components().find_map(|part| match part { + Component::Normal(name) => { + misread_by_win32(&name.to_string_lossy()).then_some(name) + } + _ => None, + }) + { + return Some(format!( + "Windows would read {} as a different name, and remove that", + name.display() + )); + } if home_key.is_some_and(|home| key == home) || home .and_then(|home| home.id) @@ -391,6 +419,67 @@ fn refuse( None } +/// A name Win32 reads as some other one. It strips trailing dots and +/// spaces, so `C:\Users.` opens `C:\Users`; it reads `NUL` or `COM1` in +/// any directory as a device; and after a colon comes a stream of another +/// file. NTFS keeps such names when they arrive through `\\?\` or WSL, +/// and the scan lists them as stored, but the trash and the removal open +/// them through Win32. +fn misread_by_win32(name: &str) -> bool { + const DEVICES: [&str; 4] = ["con", "prn", "aux", "nul"]; + if name.ends_with(['.', ' ']) || name.contains(':') { + return true; + } + // `nul.txt` was a device too, before Windows 11: refused either way. + let stem = name + .split('.') + .next() + .unwrap_or(name) + .trim_end() + .to_lowercase(); + let numbered = ["com", "lpt"].iter().any(|device| { + stem.strip_prefix(device).is_some_and(|number| { + matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8") + || matches!(number, "9" | "\u{b9}" | "\u{b2}" | "\u{b3}") + }) + }); + numbered || DEVICES.contains(&stem.as_str()) +} + +/// Why `path`, inside `root` as spelled, is somewhere else in fact, if it +/// is. The guards compare spellings, and a link or junction on the way +/// down makes a spelling inside the root name something outside it: the +/// trash, and removal on Windows, follow it. Links above the root are the +/// user's own choice of root, so the real path is compared with the real +/// root. The home directory is looked for again by real path, too. +/// +/// Anything that cannot be resolved passes: the removal of a path that is +/// gone fails on its own. +fn linked( + path: &Path, + root: &Path, + real_root: Option<&Path>, + home: Option<&Home>, +) -> Option { + let (parent, name) = (path.parent()?, path.file_name()?); + let real = guard_key(&fs::canonicalize(parent).ok()?.join(name)); + if let (Some(real_root), Ok(rest)) = (real_root, path.strip_prefix(root)) + && real != guard_key(&real_root.join(rest)) + { + return Some(format!( + "reached through a link: it is really {}", + real.display() + )); + } + if home + .and_then(|home| home.real.as_ref()) + .is_some_and(|home| home.starts_with(&real)) + { + return Some("it contains the home directory".into()); + } + None +} + /// `(device, inode)`: what makes two spellings one directory entry. /// `follow` decides whether a symlink at `path` answers for itself or for /// what it points to. @@ -775,12 +864,25 @@ fn run( // or, right after start, not read yet. Judged again against a fresh // read, here on the worker, before anything is touched. let mounts = read_mount_points(); + // Links too: one put on the way down since the plan was made would lead + // the trash out of the root. Permanent removal on Unix refuses that by + // itself; see [`open_parent`]. + let home = std::env::home_dir().map(|home| Home::of(&home)); + let real_root = fs::canonicalize(&plan.root).ok(); for target in &plan.targets { if cancel.load(Ordering::Relaxed) { break; } - let outcome = if let Some(reason) = mounted(&target.path, &mounts) { + let reason = mounted(&target.path, &mounts).or_else(|| { + linked( + &target.path, + &plan.root, + real_root.as_deref(), + home.as_ref(), + ) + }); + let outcome = if let Some(reason) = reason { Err(io::Error::other(reason)) } else { match mode { @@ -1629,6 +1731,98 @@ mod tests { assert!(keep.path().join("x/precious.bin").exists()); } + #[test] + fn a_target_reached_through_a_link_is_refused() { + let temp = tree(); + let keep = TempDir::new().expect("tempdir"); + fs::write(keep.path().join("precious.bin"), b"data").expect("write"); + link_dir(keep.path(), &temp.path().join("link")); + + let plan = plan( + &[target(&temp.path().join("link/precious.bin"), 4)], + temp.path(), + ); + assert!(plan.is_empty()); + assert!( + plan.blocked[0].reason.contains("through a link"), + "{}", + plan.blocked[0].reason + ); + } + + /// The trash follows links on the way down, so the worker asks again, + /// whatever the mode. + #[test] + fn a_link_put_on_the_way_down_after_planning_stops_the_worker() { + let temp = tree(); + let keep = TempDir::new().expect("tempdir"); + fs::create_dir(keep.path().join("x")).expect("mkdir"); + fs::write(keep.path().join("x/precious.bin"), b"data").expect("write"); + fs::create_dir(temp.path().join("a/b/x")).expect("mkdir"); + let plan = plan(&[target(&temp.path().join("a/b/x"), 0)], temp.path()); + assert_eq!(plan.targets.len(), 1); + fs::remove_dir_all(temp.path().join("a/b")).expect("clear"); + link_dir(keep.path(), &temp.path().join("a/b")); + + let handle = spawn(plan, RemovalMode::Permanent); + let mut outcome = None; + for _ in 0..2000 { + while let Some(event) = handle.poll() { + if let RemovalEvent::Item { outcome: item, .. } = event { + outcome = Some(item); + } + } + if outcome.is_some() { + break; + } + thread::sleep(std::time::Duration::from_millis(1)); + } + let error = outcome.expect("an item").expect_err("refused"); + assert!(error.contains("through a link"), "{error}"); + assert!(keep.path().join("x/precious.bin").exists()); + } + + #[test] + fn home_is_found_by_its_real_path_too() { + let temp = tree(); + let real = temp.path().join("data"); + fs::create_dir_all(real.join("home/user")).expect("mkdir"); + let spelled = TempDir::new().expect("tempdir"); + link_dir(&real.join("home"), &spelled.path().join("home")); + let home = Home::of(&spelled.path().join("home/user")); + let root = fs::canonicalize(temp.path()).expect("real root"); + + let reason = + linked(&root.join("data"), &root, Some(&root), Some(&home)) + .expect("refused"); + assert!(reason.contains("home directory"), "{reason}"); + assert_eq!( + linked(&root.join("other"), &root, Some(&root), Some(&home)), + None + ); + } + + #[test] + fn names_win32_would_misread_are_recognized() { + for name in [ + "Users.", + "Users ", + "a. .", + "NUL", + "nul.txt", + "Com1", + "LPT9.log", + "con ", + "file:stream", + "COM\u{b9}", + ] { + assert!(misread_by_win32(name), "{name:?}"); + } + for name in ["Users", ".git", "..hidden", "console", "COM0", "LPT10"] { + assert!(!misread_by_win32(name), "{name:?}"); + } + } + #[test] fn a_mount_below_a_target_is_caught_again_at_removal_time() { let temp = tree(); From 2ee640a4488fc19bcffa88bd5fe2e8df8a36fefb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 14:27:16 +0000 Subject: [PATCH 15/17] ci: read-only token for CI, and the release tag through the environment Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/ci.yml | 4 ++++ .github/workflows/release.yml | 12 ++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 717fdf4..e97abec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,10 @@ on: branches: [main] pull_request: +# Pull requests run here, so the token can read and nothing more. +permissions: + contents: read + concurrency: group: ci-${{ github.ref }} cancel-in-progress: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9d20799..b3cc857 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,8 +33,12 @@ jobs: - name: Version id: version + # Through the environment, not spliced into the script: a tag typed + # into the dispatch form is text, never shell. + env: + TAG: ${{ inputs.tag || github.ref_name }} run: | - tag="${{ inputs.tag || github.ref_name }}" + tag="$TAG" version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) if [ "$tag" != "v$version" ]; then echo "tag $tag does not match Cargo.toml version $version" >&2 @@ -118,8 +122,12 @@ jobs: - name: Version id: version + # Through the environment, not spliced into the script: a tag typed + # into the dispatch form is text, never shell. + env: + TAG: ${{ inputs.tag || github.ref_name }} run: | - tag="${{ inputs.tag || github.ref_name }}" + tag="$TAG" version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) if [ "$tag" != "v$version" ]; then echo "tag $tag does not match Cargo.toml version $version" >&2 From b9ba523a9269748d3b6d7343befc2449513de50e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 15:21:12 +0000 Subject: [PATCH 16/17] removal: follow links above the scanned root, only refuse them below Walking from / with O_NOFOLLOW refused every path under /var and /tmp on macOS, which are links. Open the root as named and refuse links only between it and the target, as the plan does. Also two tests that assumed Unix now run or skip on Windows. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/disktree-core/src/access.rs | 4 +- crates/disktree-core/src/removal.rs | 102 ++++++++++++++++++++-------- 2 files changed, 77 insertions(+), 29 deletions(-) diff --git a/crates/disktree-core/src/access.rs b/crates/disktree-core/src/access.rs index d56e2d9..d19abc1 100644 --- a/crates/disktree-core/src/access.rs +++ b/crates/disktree-core/src/access.rs @@ -42,8 +42,8 @@ mod tests { let temp = tempfile::TempDir::new().expect("tempdir"); assert_eq!(full_disk_access(temp.path()), None); if !cfg!(target_os = "macos") { - let home = std::env::var_os("HOME").expect("HOME is set"); - assert_eq!(full_disk_access(Path::new(&home)), None); + let home = std::env::home_dir().expect("a home directory"); + assert_eq!(full_disk_access(&home), None); } } } diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index cfdb3ad..e6e4d8f 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -886,7 +886,9 @@ fn run( Err(io::Error::other(reason)) } else { match mode { - RemovalMode::Permanent => remove_permanently(&target.path), + RemovalMode::Permanent => { + remove_permanently(&target.path, &plan.root) + } RemovalMode::Trash => move_to_trash(&target.path, backend), } }; @@ -934,12 +936,13 @@ fn mounted(path: &Path, mounts: &[PathBuf]) -> Option { /// `O_NOFOLLOW`, and one on a different device or mount stops the removal. /// (From tobi/disktree#10.) /// -/// The same goes for the way down to `path`: see [`open_parent`]. +/// The same goes for the way down to `path` from `root`, the scanned root: +/// see [`open_parent`]. #[cfg(unix)] -pub fn remove_permanently(path: &Path) -> io::Result<()> { +pub fn remove_permanently(path: &Path, root: &Path) -> io::Result<()> { use rustix::fs::{AtFlags, FileType, statat, unlinkat}; - let (parent, name) = open_parent(path)?; + let (parent, name) = open_parent(path, root)?; let stat = statat(&parent, name, AtFlags::SYMLINK_NOFOLLOW)?; if FileType::from_raw_mode(stat.st_mode) != FileType::Directory { unlinkat(&parent, name, AtFlags::empty())?; @@ -955,16 +958,19 @@ pub fn remove_permanently(path: &Path) -> io::Result<()> { /// The directory holding `path`, and `path`'s own name in it. /// -/// Opened one component at a time from `/`, none of them followed if it is -/// a symlink. The scanned root is canonical, so no marked path has a symlink -/// on its way down; one that does now was put there after the scan, and -/// following it would remove whatever it points to — a directory swapped -/// for a link to `~` would take `~/x` in place of the `/tmp/d/x` that was -/// marked. `rm -rf` has the same race; this closes it. +/// Opened one component at a time from `root`, none of them followed if it +/// is a symlink. The scan does not follow links, so no marked path has one +/// between the root and itself; one that does now was put there after the +/// scan, and following it would remove whatever it points to — a directory +/// swapped for a link to `~` would take `~/x` in place of the `/tmp/d/x` +/// that was marked. `rm -rf` has the same race; this closes it. Links above +/// the root are followed: they are how the user named it, and on macOS +/// `/tmp` and `/var` are links themselves. #[cfg(unix)] -fn open_parent( - path: &Path, -) -> io::Result<(std::os::fd::OwnedFd, &std::ffi::OsStr)> { +fn open_parent<'a>( + path: &'a Path, + root: &Path, +) -> io::Result<(std::os::fd::OwnedFd, &'a std::ffi::OsStr)> { use rustix::io::Errno; let not_marked = || { @@ -974,11 +980,19 @@ fn open_parent( )) }; let name = path.file_name().ok_or_else(not_marked)?; - let parent = path.parent().ok_or_else(not_marked)?; - let mut dir = open_step(rustix::fs::CWD, "/")?; - for component in parent.components() { + let below = path + .parent() + .and_then(|parent| parent.strip_prefix(root).ok()) + .ok_or_else(|| { + io::Error::other(format!( + "{} is not inside the scanned root {}", + path.display(), + root.display() + )) + })?; + let mut dir = open_root(root)?; + for component in below.components() { match component { - Component::RootDir => {} Component::Normal(part) => { dir = open_step(&dir, part).map_err(|error| match error { Errno::LOOP | Errno::NOTDIR => io::Error::other(format!( @@ -996,6 +1010,21 @@ fn open_parent( Ok((dir, name)) } +/// Open the scanned root, following links: see [`open_parent`]. +#[cfg(unix)] +fn open_root(root: &Path) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, open}; + #[cfg(any(target_os = "linux", target_os = "android"))] + let access = OFlags::PATH; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let access = OFlags::RDONLY; + open( + root, + access | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) +} + /// Open a directory on the way down to a target, not following a symlink. /// Only a handle to walk through: on Linux `O_PATH`, which needs no read /// permission, just as a path lookup does not. @@ -1018,7 +1047,7 @@ fn open_step( } #[cfg(not(unix))] -pub fn remove_permanently(path: &Path) -> io::Result<()> { +pub fn remove_permanently(path: &Path, _root: &Path) -> io::Result<()> { let meta = fs::symlink_metadata(path)?; if meta.is_dir() { fs::remove_dir_all(path) @@ -1497,6 +1526,7 @@ mod tests { ); } + #[cfg(not(windows))] #[test] fn a_directory_holding_a_system_tree_is_refused() { let home = Path::new("/Users/tobi"); @@ -1667,7 +1697,7 @@ mod tests { fs::create_dir_all(doomed.join("b/c/d")).expect("mkdir"); fs::write(doomed.join("b/c/d/.hidden"), "x").expect("write"); fs::write(doomed.join("b/c/f"), "x").expect("write"); - remove_permanently(&doomed).expect("remove tree"); + remove_permanently(&doomed, temp.path()).expect("remove tree"); assert!(!doomed.exists()); assert!(temp.path().join("other").exists()); } @@ -1678,7 +1708,8 @@ mod tests { let outside = TempDir::new().expect("tempdir"); fs::write(outside.path().join("keep"), "x").expect("write"); link_dir(outside.path(), &temp.path().join("a/link")); - remove_permanently(&temp.path().join("a")).expect("remove tree"); + remove_permanently(&temp.path().join("a"), temp.path()) + .expect("remove tree"); assert!(outside.path().join("keep").exists()); } @@ -1686,7 +1717,7 @@ mod tests { fn permanent_removal_takes_directories_and_leaves_siblings() { let temp = tree(); let doomed = temp.path().join("a/b"); - remove_permanently(&doomed).expect("remove dir"); + remove_permanently(&doomed, temp.path()).expect("remove dir"); assert!(!doomed.exists()); assert!(temp.path().join("a/c.bin").exists()); } @@ -1708,7 +1739,7 @@ mod tests { let link = temp.path().join("link"); link_dir(keep.path(), &link); - remove_permanently(&link).expect("remove link"); + remove_permanently(&link, temp.path()).expect("remove link"); assert!(fs::symlink_metadata(&link).is_err(), "the link is gone"); assert!(keep.path().join("precious.bin").exists()); } @@ -1726,7 +1757,8 @@ mod tests { fs::remove_dir_all(temp.path().join("a/b")).expect("clear"); link_dir(keep.path(), &temp.path().join("a/b")); - let error = remove_permanently(&marked).expect_err("refused"); + let error = + remove_permanently(&marked, temp.path()).expect_err("refused"); assert!(error.to_string().contains("changed since"), "{error}"); assert!(keep.path().join("x/precious.bin").exists()); } @@ -1823,6 +1855,20 @@ mod tests { } } + /// On macOS the temporary directory is under `/var`, itself a link to + /// `/private/var`: a link above the scanned root is how it was named. + #[test] + fn permanent_removal_follows_links_above_the_root() { + let temp = tree(); + let spelled = TempDir::new().expect("tempdir"); + let root = spelled.path().join("root"); + link_dir(temp.path(), &root); + + remove_permanently(&root.join("a/b"), &root).expect("removed"); + assert!(!temp.path().join("a/b").exists()); + assert!(temp.path().join("a/one.bin").exists()); + } + #[test] fn a_mount_below_a_target_is_caught_again_at_removal_time() { let temp = tree(); @@ -1852,8 +1898,9 @@ mod tests { permissions.set_readonly(true); fs::set_permissions(&lone, permissions).expect("read-only"); - remove_permanently(&lone).expect("a read-only file"); - remove_permanently(&temp.path().join("a/b")).expect("a directory"); + remove_permanently(&lone, temp.path()).expect("a read-only file"); + remove_permanently(&temp.path().join("a/b"), temp.path()) + .expect("a directory"); assert!(!lone.exists()); assert!(!temp.path().join("a/b").exists()); assert!(temp.path().join("a/c.bin").exists()); @@ -1862,8 +1909,9 @@ mod tests { #[test] fn a_missing_target_reports_not_found() { let temp = tree(); - let error = remove_permanently(&temp.path().join("absent")) - .expect_err("missing"); + let error = + remove_permanently(&temp.path().join("absent"), temp.path()) + .expect_err("missing"); assert_eq!(error.kind(), io::ErrorKind::NotFound); } From 46711fc8161ef067055366ddf157111e71b06c86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobi=20L=C3=BCtke?= Date: Fri, 25 Sep 2026 15:39:33 +0000 Subject: [PATCH 17/17] removal: a target under the Data volume's root is inside it Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/disktree-core/src/removal.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index e6e4d8f..3874564 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -390,7 +390,9 @@ fn refuse( if home_key.is_some_and(|home| home.starts_with(&key)) { return Some("it contains the home directory".into()); } - if !key.starts_with(&root_key) { + // By spelling too: the Data volume's root keeps its name as a key, while + // everything under it is keyed as under `/`. + if !key.starts_with(&root_key) && !path.starts_with(root) { return Some("outside the scanned root".into()); } if let Some(system) = system_tree(&key, home_key) {