diff --git a/README.md b/README.md index cb9d37e..c42c800 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ make install 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). +can drive (Vulkan). Distributions often package an older Rust; +[rustup](https://rustup.rs) installs a current one. ### macOS @@ -52,7 +53,8 @@ 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: +Or build it, with Rust 1.97 or newer and Xcode or its Command Line Tools. +macOS does not come with Rust; install it with [rustup](https://rustup.rs). ```sh make install # ~/Applications/disktree.app, and ~/.local/bin/disktree @@ -89,8 +91,9 @@ NOTARY_PROFILE= cargo xtask bundle \ ### Windows 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): +release, unpack it anywhere and run `disktree.exe`. Or build it with Rust 1.97 +or newer, from [rustup](https://rustup.rs), and the MSVC toolchain (Visual +Studio Build Tools, C++ workload): ```powershell git clone https://github.com/tobi/disktree @@ -199,15 +202,17 @@ and shows how much free space was actually gained. | `d` | disk usage or apparent size | | `i` | include or skip hidden entries | | `r` | scan again | +| `ctrl o` (`⌘O` on macOS) | choose another directory to scan | | `g` | the whole disk | | `p` | show or hide the selection line | -| `o` | show it in Finder or the file manager | +| `o` | show it in Finder, File Explorer 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 macOS the menu bar also has ⌘⇧R to show the selection in Finder, ⌘R to +rescan, ⌘[ and ⌘] for back and forward, and ⌘Q, ⌘H and ⌘W (closing the +window quits); other ⌘ chords are left to the system. On Linux and Windows +the same work with ctrl, with F5 to rescan too. On the review screen: `m` trash, `p` permanent, `!` unmark all, `enter` commits, `esc` goes back. @@ -270,13 +275,14 @@ The same program, with Windows' answers to the questions above: 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 + Information, Recovery, Boot, and the page and hibernation files, which + Settings turns off), 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. +- **Hidden** means a name starting with a dot, or the hidden attribute, so + `-H` drops `AppData` as Explorer hides it. +- **The theme** follows Windows' light or dark setting, since there is no + Omarchy theme to follow. It does on macOS too, and on GNOME and KDE. ## What it refuses to do @@ -293,7 +299,8 @@ tested: - 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 +- system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, + `/gnu/store`, Homebrew's prefix on macOS and Linux, …) 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; diff --git a/crates/disktree-app/src/app_menu.rs b/crates/disktree-app/src/app_menu.rs index 00804ca..faee476 100644 --- a/crates/disktree-app/src/app_menu.rs +++ b/crates/disktree-app/src/app_menu.rs @@ -1,9 +1,9 @@ //! 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. +//! menu bar and no ⌘Q, so this is where disktree becomes a Mac app. GPUI +//! draws no menu bar on Linux or Windows, so there the same actions get the +//! shortcuts their users expect, with ctrl, and nothing else. use gpui_kit::{App, KeyBinding, Menu, MenuItem, SystemMenuType}; @@ -54,13 +54,7 @@ pub fn install(cx: &mut App) { }) .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()); @@ -68,6 +62,20 @@ pub fn install(cx: &mut App) { }); // `Rescan`, `OpenFolder`, `ShowInFinder` and the history are handled by // the window, which owns the scan and the selection; see `views::root`. + if !cfg!(target_os = "macos") { + cx.bind_keys([ + KeyBinding::new("ctrl-q", Quit, None), + KeyBinding::new("ctrl-w", CloseWindow, None), + KeyBinding::new("ctrl-o", OpenFolder, None), + KeyBinding::new("ctrl-r", Rescan, None), + KeyBinding::new("f5", Rescan, None), + KeyBinding::new("ctrl-shift-r", ShowInFinder, None), + ]); + return; + } + 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.bind_keys([ KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("cmd-h", Hide, None), diff --git a/crates/disktree-app/src/appearance.rs b/crates/disktree-app/src/appearance.rs index caa1eb6..274bce6 100644 --- a/crates/disktree-app/src/appearance.rs +++ b/crates/disktree-app/src/appearance.rs @@ -1,9 +1,9 @@ //! 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. +//! On Omarchy, gpui-omarchy follows the desktop's theme files. Elsewhere there +//! are 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; @@ -11,9 +11,11 @@ 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. +/// colours: unless an Omarchy theme is installed, on macOS and Windows, and +/// on a Linux desktop that states a preference. pub fn follows_system(home: Option<&Path>) -> bool { - cfg!(target_os = "macos") + let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); + states_a_preference(&desktop) && !home.is_some_and(|home| { [".local/state/omarchy/current", ".config/omarchy/current"] .iter() @@ -21,6 +23,18 @@ pub fn follows_system(home: Option<&Path>) -> bool { }) } +/// Whether the system has a light or dark setting to follow. macOS and +/// Windows always do. On Linux GPUI asks the desktop portal, which reads "no +/// preference" as light: a window manager that never sets one would turn +/// the app light, so only GNOME and KDE, whose settings do, are followed. +fn states_a_preference(desktop: &str) -> bool { + cfg!(any(target_os = "macos", windows)) + || desktop.split(':').any(|name| { + ["gnome", "kde", "ubuntu", "unity", "pantheon", "cinnamon"] + .contains(&name.to_ascii_lowercase().as_str()) + }) +} + /// 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) { @@ -41,3 +55,17 @@ pub fn follow(window: &Window) { .observe_window_appearance(|window, cx| apply(window.appearance(), cx)) .detach(); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_linux_desktop_is_followed_only_if_it_states_a_preference() { + let native = cfg!(any(target_os = "macos", windows)); + assert!(states_a_preference("ubuntu:GNOME")); + assert!(states_a_preference("KDE")); + assert_eq!(states_a_preference("Hyprland"), native); + assert_eq!(states_a_preference(""), native); + } +} diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index ec88f55..b4a69e3 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -157,7 +157,15 @@ fn run(path: &Path, args: &[&str]) -> Option { } fn git(path: &Path, args: &[&str]) -> Option { - Command::new("git") + let mut command = Command::new("git"); + // disktree is a GUI program on Windows, with no console to lend: without + // this, every probe flashes a console window of its own. + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags( + &mut command, + 0x0800_0000, // CREATE_NO_WINDOW + ); + command .arg("-C") .arg(path) // A checkout's own config can name programs for git to run: an diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index fc5541e..fcfd83c 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -2944,12 +2944,17 @@ const MODIFIER_ZOOM: &str = if cfg!(target_os = "macos") { } else { "ctrl = / - / 0" }; +const MODIFIER_OPEN: &str = if cfg!(target_os = "macos") { + "\u{2318}O" +} else { + "ctrl-o" +}; 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); 26] = [ + let rows: [(&str, &str); 27] = [ ("space / x", "Mark or unmark the tile you point at"), (MODIFIER_CLICK, "Mark without moving the selection"), ("enter", "Open that directory, at any depth"), @@ -2975,6 +2980,7 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("c", "Review the marked list"), ("t", "Size, files or age: what areas and colours say"), ("r", "Scan again from the same root"), + (MODIFIER_OPEN, "Choose another directory to scan"), ("g", "The whole disk; click any directory above to widen"), ("d", "Disk usage or apparent size"), ("i", "Include or skip hidden entries"), @@ -2983,6 +2989,8 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { "o", if cfg!(target_os = "macos") { "Show it in Finder" + } else if cfg!(windows) { + "Show it in File Explorer" } else { "Show it in the file manager" }, diff --git a/crates/disktree-core/src/classify.rs b/crates/disktree-core/src/classify.rs index 098e5de..6aad615 100644 --- a/crates/disktree-core/src/classify.rs +++ b/crates/disktree-core/src/classify.rs @@ -108,6 +108,11 @@ impl Reclaim { /// The kind a directory name announces on its own, if any. pub fn category_of_name(name: &str) -> Option { let lower = name.to_ascii_lowercase(); + // Windows: a work or school account's folder carries the organisation, + // `OneDrive - Contoso`, and Dropbox's does the same, `Dropbox (Contoso)`. + if lower.starts_with("onedrive - ") || lower.starts_with("dropbox (") { + return Some(Category::Synced); + } let category = match lower.as_str() { "src" | "code" | "projects" | "repos" | "dev" | "work" | "workspace" | "workspaces" | "github.com" | "gitlab.com" @@ -122,7 +127,7 @@ 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" + | ".sdkman" | ".volta" | ".yarn" | ".java" | ".nuget" // macOS: Xcode's and the simulators' state in ~/Library/Developer. // Not `Developer` itself: ~/Developer is where Apple puts projects. | "xcode" | "coresimulator" => Category::Toolchain, @@ -130,7 +135,9 @@ pub fn category_of_name(name: &str) -> Option { | "pclouddrive" | "mega" | ".stversions" // macOS: iCloud Drive, and the File Provider clients (Dropbox, // Google Drive, OneDrive) since macOS 12. - | "mobile documents" | "cloudstorage" => Category::Synced, + | "mobile documents" | "cloudstorage" + // Windows: iCloud for Windows. + | "iclouddrive" => Category::Synced, ".git" => Category::Git, "pictures" | "photos" | "music" | "videos" | "movies" | "steam" | "models" | ".ollama" | ".lmstudio" | "games" | "wineprefix" => { @@ -141,7 +148,10 @@ pub fn category_of_name(name: &str) -> Option { ".cache" | "cache" | "caches" | ".ccache" | ".sccache" | "_cacache" | "__pycache__" | "node_modules" | "trash" | ".trash" | "tmp" | ".tmp" | "deriveddata" | "ios devicesupport" - | "watchos devicesupport" => Category::Cache, + | "watchos devicesupport" + // Windows: see `reclaim_of`. + | "temp" | "$recycle.bin" | "npm-cache" | "v3-cache" | "inetcache" + | "d3dscache" | "dxcache" | "glcache" | "crashdumps" => Category::Cache, _ => return None, }; Some(category) @@ -156,18 +166,21 @@ pub fn reclaim_of( ) -> Option { let lower = name.to_ascii_lowercase(); let reclaim = match lower.as_str() { - ".cache" | "cache" | "caches" | ".ccache" | ".sccache" | "_cacache" => { - Reclaim::Regenerable - } + ".cache" | "cache" | "caches" | ".ccache" | ".sccache" | "_cacache" + // Windows' own caches in AppData\Local: npm's, NuGet's downloads, + // the browser engine's, and compiled shaders, Direct3D's and the + // graphics driver's, all rebuilt as they are needed. + | "npm-cache" | "v3-cache" | "inetcache" | "d3dscache" | "dxcache" + | "glcache" + // 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, ".stversions" => Reclaim::SyncHistory, ".pnpm-store" | "pnpm" => Reclaim::PackageStore, "__pycache__" | ".pytest_cache" | ".mypy_cache" | ".ruff_cache" | ".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. @@ -176,8 +189,10 @@ pub fn reclaim_of( // Layers and snapshots are only disposable inside sandbox state. "layers" if parent == Category::AgentScratch => Reclaim::SandboxLayers, "snapshots" if parent == Category::AgentScratch => Reclaim::Snapshots, - "trash" | ".trash" => Reclaim::Trash, - "tmp" | ".tmp" => Reclaim::Temporary, + "trash" | ".trash" | "$recycle.bin" => Reclaim::Trash, + // `Temp` is where Windows puts temporary files, in AppData\Local; + // `CrashDumps` beside it holds dumps of programs that crashed. + "tmp" | ".tmp" | "temp" | "crashdumps" => Reclaim::Temporary, _ => return None, }; Some(reclaim) @@ -469,6 +484,37 @@ mod tests { assert_eq!(category_of_name("Xcode"), Some(Category::Toolchain)); } + #[test] + fn windows_caches_and_sync_folders_are_recognized() { + let none = |_: &str| false; + for (name, reclaim) in [ + ("Temp", Reclaim::Temporary), + ("CrashDumps", Reclaim::Temporary), + ("npm-cache", Reclaim::Regenerable), + ("v3-cache", Reclaim::Regenerable), + ("INetCache", Reclaim::Regenerable), + ("D3DSCache", Reclaim::Regenerable), + ("DXCache", Reclaim::Regenerable), + ("$Recycle.Bin", Reclaim::Trash), + ] { + assert_eq!( + reclaim_of(name, Category::Other, none), + Some(reclaim), + "{name}" + ); + assert_eq!(category_of_name(name), Some(Category::Cache), "{name}"); + } + for name in ["OneDrive - Contoso", "Dropbox (Contoso)", "iCloudDrive"] { + assert_eq!( + category_of_name(name), + Some(Category::Synced), + "{name}" + ); + } + assert_eq!(category_of_name(".nuget"), Some(Category::Toolchain)); + assert_eq!(category_of_name("OneDriveSetup"), None); + } + #[test] fn the_legend_lists_every_named_category_once() { let mut seen = std::collections::HashSet::new(); diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index 3874564..c41843d 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -160,14 +160,17 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { /// an app to the Trash is how macOS uninstalls it, and the apps macOS ships /// live on the read-only system volume anyway. #[cfg(not(windows))] -const SYSTEM_TREES: [&str; 20] = [ +const SYSTEM_TREES: [&str; 24] = [ "/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", + "/lib32", + "/libx32", "/nix/store", + "/gnu/store", "/proc", "/run", "/sbin", @@ -175,6 +178,8 @@ const SYSTEM_TREES: [&str; 20] = [ "/usr", "/var/lib", "/efi", + // Homebrew on Linux, where it lives outside every user's home. + "/home/linuxbrew/.linuxbrew", // macOS. "/System", "/Library", @@ -282,6 +287,11 @@ fn system_trees() -> Vec { "Recovery", "Boot", "bootmgr", + // Windows' memory: turned off in Settings (`powercfg /h off` for + // hibernation), never deleted by hand. + "pagefile.sys", + "hiberfil.sys", + "swapfile.sys", ] .map(|name| drive.join(name)), ); @@ -566,34 +576,46 @@ 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. +/// Read the mount points now: from `/proc/self/mounts`, on macOS from +/// `mount`, which has no `/proc`, and on Windows from the volume list. +/// Empty where none 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() - }; + let points: Vec = if cfg!(windows) { + windows_mount_points() + } else 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() } +#[cfg(windows)] +fn windows_mount_points() -> Vec { + crate::windows::mount_points() +} + +#[cfg(not(windows))] +const fn windows_mount_points() -> Vec { + Vec::new() +} + /// 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. @@ -2114,6 +2136,8 @@ mod tests { 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!(system("pagefile.sys").is_some()); + assert!(system("HIBERFIL.SYS").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); @@ -2186,6 +2210,14 @@ mod tests { ); assert_eq!(tree_of(Path::new("/var/cache/pacman/pkg"), home), None); assert_eq!(tree_of(Path::new("/opt/thing"), home), None); + assert_eq!( + tree_of(Path::new("/home/linuxbrew/.linuxbrew/Cellar"), home), + Some("/home/linuxbrew/.linuxbrew") + ); + assert_eq!( + tree_of(Path::new("/gnu/store/abc-hello"), home), + Some("/gnu/store") + ); assert_eq!( tree_of(Path::new("/usrlocal"), home), None, diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index 2dd0ed7..f9abac6 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -293,7 +293,9 @@ impl WalkContext { }; let name = entry.display_name(); - if !self.options.include_hidden && name.starts_with('.') { + if !self.options.include_hidden + && (name.starts_with('.') || entry.hidden()) + { return Classified::Skipped; } @@ -461,6 +463,12 @@ trait Listed { fn facts(&self, apparent_size: bool) -> io::Result; /// What a directory is, read before the walk enters it. fn directory(&self) -> io::Result; + /// Hidden by an attribute rather than by a leading dot: on Windows, + /// where the listing carries it, so `AppData` is hidden as Explorer + /// hides it. macOS's `UF_HIDDEN` would cost a stat per entry. + fn hidden(&self) -> bool { + false + } } /// Whether [`Directory::evicted`] can ever be true here, so a platform that @@ -584,6 +592,10 @@ impl Listed for crate::windows::Entry { evicted: self.evicted(), }) } + + fn hidden(&self) -> bool { + self.hidden() + } } /// List a directory the way [`Listed`] describes. @@ -1083,6 +1095,31 @@ mod tests { assert_eq!(without.bytes, 100); } + /// Explorer's hidden attribute counts as hidden, as `AppData` has it. + #[cfg(windows)] + #[test] + fn the_hidden_attribute_hides_an_entry_on_windows() { + let temp = TempDir::new().expect("tempdir"); + let root = temp.path(); + write(root, "AppData/blob.bin", 900); + write(root, "visible.bin", 100); + let marked = std::process::Command::new("attrib") + .arg("+h") + .arg(root.join("AppData")) + .status() + .is_ok_and(|status| status.success()); + assert!(marked, "attrib +h"); + + let without = scan_dir( + root, + &ScanOptions { + include_hidden: false, + ..options() + }, + ); + 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. diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-core/src/windows.rs index 6e2ef8c..9e9468d 100644 --- a/crates/disktree-core/src/windows.rs +++ b/crates/disktree-core/src/windows.rs @@ -27,14 +27,16 @@ 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, + ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED, INVALID_HANDLE_VALUE, }; use windows_sys::Win32::Storage::FileSystem::{ - FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, - FILE_ATTRIBUTE_RECALL_ON_OPEN, FILE_ATTRIBUTE_REPARSE_POINT, - FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, - FILE_READ_ATTRIBUTES, FileIdExtdDirectoryInfo, GetDiskFreeSpaceExW, - GetFileInformationByHandleEx, GetVolumePathNameW, SYNCHRONIZE, + FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_HIDDEN, + FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, FILE_ATTRIBUTE_RECALL_ON_OPEN, + FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS, + FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, + FileIdExtdDirectoryInfo, FindFirstVolumeW, FindNextVolumeW, + FindVolumeClose, GetDiskFreeSpaceExW, GetFileInformationByHandleEx, + GetVolumePathNameW, GetVolumePathNamesForVolumeNameW, SYNCHRONIZE, }; use crate::space::SpaceInfo; @@ -114,6 +116,12 @@ impl Entry { self.modified } + /// Whether Explorer hides this: `FILE_ATTRIBUTE_HIDDEN`, as on + /// `AppData` and `$Recycle.Bin`. + pub const fn hidden(&self) -> bool { + self.attributes & FILE_ATTRIBUTE_HIDDEN != 0 + } + /// Whether this is a directory the cloud files provider holds and the /// disk does not: see [`EVICTED`]. pub const fn evicted(&self) -> bool { @@ -454,6 +462,68 @@ pub fn volume_root(path: &Path) -> Option { Some(PathBuf::from(OsString::from_wide(&root[..end]))) } +/// Every place a volume is mounted: drive roots such as `D:\`, and folders +/// a volume is mounted on, such as `C:\Data\Disk2\`. The mount table +/// Windows has in place of `/proc/self/mounts`. +pub fn mount_points() -> Vec { + let mut points = Vec::new(); + // A volume GUID path, `\\?\Volume{…}\`, is 49 units with its NUL. + let mut volume = [0_u16; 64]; + let length = u32::try_from(volume.len()).unwrap_or(u32::MAX); + // SAFETY: `volume` is writable for the length passed. + let find = unsafe { FindFirstVolumeW(volume.as_mut_ptr(), length) }; + if find.is_null() || find == INVALID_HANDLE_VALUE { + return points; + } + loop { + points.extend(volume_paths(&volume)); + // SAFETY: `find` is a live search handle, and `volume` is writable + // for the length passed. + if unsafe { FindNextVolumeW(find, volume.as_mut_ptr(), length) } == 0 { + break; + } + } + // SAFETY: `find` is a live search handle, closed once. + unsafe { FindVolumeClose(find) }; + points +} + +/// The paths the volume named by the NUL-terminated `volume` is mounted at. +fn volume_paths(volume: &[u16]) -> Vec { + let mut names = vec![0_u16; 1024]; + loop { + let mut needed = 0_u32; + let Ok(length) = u32::try_from(names.len()) else { + return Vec::new(); + }; + // SAFETY: `volume` is NUL-terminated, `names` is writable for the + // length passed, and `needed` is a live `u32`. + let ok = unsafe { + GetVolumePathNamesForVolumeNameW( + volume.as_ptr(), + names.as_mut_ptr(), + length, + &raw mut needed, + ) + }; + if ok != 0 { + break; + } + // Too small: grow to what it asked for, once more at most. + let needed = usize::try_from(needed).unwrap_or(0); + if needed <= names.len() { + return Vec::new(); + } + names.resize(needed, 0); + } + // NUL-separated names, ended by an empty one. + names + .split(|&unit| unit == 0) + .take_while(|name| !name.is_empty()) + .map(|name| PathBuf::from(OsString::from_wide(name))) + .collect() +} + /// 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 { @@ -573,6 +643,19 @@ mod tests { use super::*; use tempfile::TempDir; + #[test] + fn the_volume_list_has_the_system_drive() { + let drive = + std::env::var_os("SystemDrive").unwrap_or_else(|| "C:".into()); + let root = PathBuf::from(drive).join(Component::RootDir.as_os_str()); + let points = mount_points(); + assert!( + points.iter().any(|point| same(point, &root)), + "{} not in {points:?}", + root.display() + ); + } + fn listed(dir: &Path) -> Vec { let mut entries: Vec = read_dir(dir) .expect("list")