From f3741c1a5174dacff8ef36cbb9629007061a3f54 Mon Sep 17 00:00:00 2001 From: Oleg Shevchuk Date: Fri, 25 Sep 2026 15:08:55 +0500 Subject: [PATCH 1/4] 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 2/4] 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 3/4] 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 4/4] 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