Skip to content

A treemap for finding and removing what fills your disk, for Omarchy. Rust + GPUI.

Rust

Merge pr/14 (Windows) onto the macOS port

Tobi Lütkef39f96e62fe4
diff --cc .github/workflows/ci.yml
index f35f42a,058c6c0..717fdf4
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@@ -44,29 -44,26 +44,53 @@@ jobs
- name: Test
run: cargo xtask test
+ check-macos:
+ name: Lint and test (macOS)
+ # Apple silicon. No system libraries to install, and no Metal toolchain
+ # either: gpui-kit builds GPUI with runtime shader compilation, so the
+ # shaders compile when the app starts, not here.
+ runs-on: macos-15
+ steps:
+ - uses: actions/checkout@v5
+
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ toolchain: "1.97"
+ components: clippy, rustfmt
+
+ - uses: Swatinem/rust-cache@v2
+
+ - name: Lint
+ run: cargo xtask lint
+
+ - name: Test
+ run: cargo xtask test
+
+ # The app bundle, signed ad hoc: catches a broken Info.plist, icon or
+ # signature before a release does.
+ - name: Bundle
+ run: cargo xtask bundle
++
+ 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 --cc .github/workflows/release.yml
index 6de163f,1802562..9d20799
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@@ -87,91 -90,52 +90,141 @@@ jobs
--title "disktree ${TAG#v}" --generate-notes
fi
+ release-macos:
+ name: Build and publish (macOS)
+ # After the Linux job, which creates the release: two jobs racing to
+ # create it would leave one failing.
+ needs: release
+ runs-on: macos-15
+ env:
+ # Signing and notarizing happen only when the repository has these
+ # secrets; without them the app is signed ad hoc, and a downloaded
+ # copy needs "Open Anyway" in System Settings once.
+ # MACOS_CERTIFICATE base64 of the Developer ID .p12
+ # MACOS_CERTIFICATE_PASSWORD its password
+ # MACOS_SIGN_IDENTITY "Developer ID Application: Name (TEAMID)"
+ # NOTARY_KEY_P8 base64 of an App Store Connect API key
+ # NOTARY_KEY_ID, NOTARY_ISSUER that key's ID and issuer
+ MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }}
+ MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
+ MACOS_SIGN_IDENTITY: ${{ secrets.MACOS_SIGN_IDENTITY }}
+ NOTARY_KEY_P8: ${{ secrets.NOTARY_KEY_P8 }}
+ NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }}
+ NOTARY_ISSUER: ${{ secrets.NOTARY_ISSUER }}
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ ref: ${{ inputs.tag || github.ref }}
+
+ - name: Version
+ id: version
+ run: |
+ tag="${{ inputs.tag || github.ref_name }}"
+ version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
+ if [ "$tag" != "v$version" ]; then
+ echo "tag $tag does not match Cargo.toml version $version" >&2
+ exit 1
+ fi
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ toolchain: "1.97"
+
+ - uses: Swatinem/rust-cache@v2
+
+ - name: Test
+ run: cargo xtask test
+
+ # A keychain of its own for the certificate, deleted with the runner.
+ - name: Signing certificate
+ if: env.MACOS_CERTIFICATE != ''
+ run: |
+ keychain="$RUNNER_TEMP/signing.keychain-db"
+ password=$(uuidgen)
+ echo "$MACOS_CERTIFICATE" | base64 --decode > "$RUNNER_TEMP/cert.p12"
+ security create-keychain -p "$password" "$keychain"
+ security set-keychain-settings -lut 3600 "$keychain"
+ security unlock-keychain -p "$password" "$keychain"
+ security import "$RUNNER_TEMP/cert.p12" -k "$keychain" \
+ -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
+ security set-key-partition-list -S apple-tool:,apple: \
+ -s -k "$password" "$keychain"
+ security list-keychains -d user -s "$keychain" \
+ $(security list-keychains -d user | tr -d '"')
+ rm "$RUNNER_TEMP/cert.p12"
+
+ - name: Bundle
+ run: |
+ args=()
+ if [ -n "$MACOS_CERTIFICATE" ]; then
+ args+=(--sign "$MACOS_SIGN_IDENTITY")
+ if [ -n "$NOTARY_KEY_P8" ]; then
+ echo "$NOTARY_KEY_P8" | base64 --decode \
+ > "$RUNNER_TEMP/AuthKey.p8"
+ export NOTARY_KEY="$RUNNER_TEMP/AuthKey.p8"
+ args+=(--notarize)
+ fi
+ fi
+ cargo xtask bundle "${args[@]}"
+
+ - name: Publish
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ steps.version.outputs.tag }}
+ run: |
+ zip="target/bundle/disktree-${{ steps.version.outputs.version }}-aarch64-macos.zip"
+ (cd "$(dirname "$zip")" && shasum -a 256 "$(basename "$zip")" \
+ > "$(basename "$zip").sha256")
+ gh release upload "$TAG" "$zip" "$zip.sha256" --clobber
++
+ 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 --cc AGENTS.md
index 873bc1d,d1ad868..ff8491b
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -31,13 -30,10 +31,15 @@@ prefix and the crate version) and `asse
entry's `Categories` to a single main category plus additional ones, or
`desktop-file-validate` complains.
+On macOS `make install` installs `target/bundle/disktree.app` into
+`~/Applications` instead, built by `cargo xtask bundle` from
+`packaging/macos/` (the `Info.plist` template and the icon's SVG). The bundle
+identifier there keys every macOS permission grant; do not change it lightly.
+
`cargo xtask lint` is the gate. It must be green before anything is called
done, and it must not fix anything: a red local run is the same signal CI gives.
+ 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
diff --cc README.md
index 60d3a5e,afc9aca..bf3c21f
--- a/README.md
+++ b/README.md
@@@ -43,49 -43,18 +43,63 @@@ removes exactly what was installed
You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI
can drive (Vulkan).
+### macOS
+
+Download `disktree-*-aarch64-macos.zip` from the
+[latest release](https://github.com/tobi/disktree/releases/latest), unzip it,
+and drag `disktree.app` into Applications. Apple silicon and macOS 11 or
+newer. A release that was not signed and notarized is stopped by Gatekeeper
+the first time: open it once, then choose **Open Anyway** in System Settings
+› Privacy & Security.
+
+Or build it, with Rust 1.97 or newer and Xcode or its Command Line Tools:
+
+```sh
+make install # ~/Applications/disktree.app, and ~/.local/bin/disktree
+make uninstall
+```
+
+To see everything, give disktree **Full Disk Access** in System Settings ›
+Privacy & Security (the panel offers a button when it is missing), then
+reopen it. Without it macOS hides Mail, Messages, Safari, other apps' data
+and the Trash, and disktree counts them as unreadable. Started from a
+terminal, it is the terminal that needs the access. macOS also asks once
+each for Desktop, Documents and Downloads.
+
+What is different from Linux:
+
+- **Free space** is what `df` reports. Finder's figure is larger: it counts
+ purgeable space (caches and local snapshots macOS will clear on its own).
+- **Cloned files** (copies APFS shares blocks between, as Finder's Duplicate
+ makes) are each counted in full, so a total can exceed what deleting them
+ frees.
+- **Time Machine's local snapshots** are not files and do not appear; they
+ are part of the gap between the scan and the disk's used space.
+- **Cloud-only folders** (iCloud Drive, Dropbox and the like, evicted to the
+ server) are not opened, so a scan never downloads them.
+
+To sign and notarize a build for others, with a Developer ID certificate in
+the keychain and credentials saved by `xcrun notarytool store-credentials`:
+
+```sh
+NOTARY_PROFILE=<profile> cargo xtask bundle \
+ --sign "Developer ID Application: Name (TEAMID)" --notarize
+```
+
++### 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):
+
+ ```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
diff --cc crates/disktree-app/src/main.rs
index acdf207,6d17cfd..7ce0180
--- a/crates/disktree-app/src/main.rs
+++ b/crates/disktree-app/src/main.rs
@@@ -5,8 -5,12 +5,14 @@@
//! 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 app_menu;
+mod appearance;
mod git;
mod marks;
mod palette;
@@@ -67,12 -80,6 +82,12 @@@ fn run() -> Result<()>
.with_assets(gpui_kit::assets::Assets)
.run(move |cx| {
gpui_omarchy::init(cx);
+ app_menu::install(cx);
- let home = std::env::var_os("HOME").map(PathBuf::from);
++ let home = std::env::home_dir();
+ let native_look = appearance::follows_system(home.as_deref());
+ if native_look {
+ appearance::apply(cx.window_appearance(), cx);
+ }
let options = args.options.clone();
let root_for_app = root.clone();
let window = cx
diff --cc crates/disktree-app/src/views.rs
index 66aedd1,4062ce5..b8e53cc
--- a/crates/disktree-app/src/views.rs
+++ b/crates/disktree-app/src/views.rs
@@@ -2934,15 -2740,11 +2936,15 @@@ fn help_overlay(app: &Disktree, cx: &gp
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); 25] = [
- let rows: [(&str, &str); 24] = [
++ let rows: [(&str, &str); 26] = [
("space / x", "Mark or unmark the tile you point at"),
- ("ctrl-click", "Mark without moving the selection"),
+ (MODIFIER_CLICK, "Mark without moving the selection"),
("enter", "Open that directory, at any depth"),
("\u{232b} / esc", "Go up one directory"),
+ (
+ "alt \u{2190} / \u{2192}",
+ "Back or forward through where you have been",
+ ),
(
"\u{2190} \u{2191} \u{2193} \u{2192}",
"Move between tiles at this level",
diff --cc crates/disktree-core/Cargo.toml
index 8b3ef03,9647cb8..a1eb131
--- a/crates/disktree-core/Cargo.toml
+++ b/crates/disktree-core/Cargo.toml
@@@ -12,14 -12,17 +12,23 @@@ workspace = tru
[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 }
- [dev-dependencies]
- tempfile = "3"
+ # 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"] }
+# The system trash, through NSFileManager: what Finder's Move to Trash does,
+# without asking to control Finder. Only this backend is used; the crate's
+# Linux and Windows code is not built.
+[target.'cfg(target_os = "macos")'.dependencies]
+trash = { version = "5.2.9", default-features = false }
++
+ [dev-dependencies]
+ tempfile = "3"
diff --cc crates/disktree-core/src/removal.rs
index f328a2e,f2c2bb2..ded9e4c
--- a/crates/disktree-core/src/removal.rs
+++ b/crates/disktree-core/src/removal.rs
@@@ -6,14 -6,13 +6,14 @@@
//!
//! Two mechanisms are offered:
//!
-//! * [`RemovalMode::Permanent`] — `rm -rf` semantics, implemented with the
-//! standard library rather than by shelling out, so no path ever reaches a
+//! * [`RemovalMode::Permanent`] — `rm -rf --one-file-system` semantics,
+//! implemented here rather than by shelling out, so no path ever reaches a
//! shell and no filename can be misread as an option.
-//! * [`RemovalMode::Trash`] — move to the desktop trash, using `trash-put`,
-//! then `gio trash`, then a built-in XDG implementation; on Windows, the
-//! Recycle Bin. The backend is detected once and named in the UI so the
-//! user knows what actually happens.
+//! * [`RemovalMode::Trash`] — move to the desktop trash. On macOS that is
- //! always the system Trash, through `NSFileManager`. Elsewhere it is
- //! `trash-put`, then `gio trash`, then a built-in XDG implementation. The
- //! backend is detected once and named in the UI so the user knows what
- //! actually happens.
++//! always the system Trash, through `NSFileManager`, and on Windows the
++//! Recycle Bin. Elsewhere it is `trash-put`, then `gio trash`, then a
++//! built-in XDG implementation. The backend is detected once and named in
++//! the UI so the user knows what actually happens.
use std::fs;
use std::io;
@@@ -97,16 -99,10 +97,16 @@@ pub fn plan(targets: &[Target], root: &
let mut plan = Plan::default();
let mut accepted: Vec<Target> = Vec::new();
+ if targets.is_empty() {
+ return plan;
+ }
+ let mounts = mount_points();
+ // Once per plan, not per target: the review screen plans every frame.
- let home = std::env::var_os("HOME").map(|home| Home::of(Path::new(&home)));
++ let home = std::env::home_dir().map(|home| Home::of(&home));
+
for target in targets {
let path = normalize(&target.path);
- if let Some(reason) = refuse(&path, &root, home.as_deref()) {
+ if let Some(reason) = refuse(&path, &root, home.as_ref(), &mounts) {
plan.blocked.push(Blocked {
path: target.path.clone(),
reason,
@@@ -137,19 -133,14 +137,20 @@@
plan
}
-/// Why this path must not be removed, if it must not.
/// Trees the operating system owns. A whole-disk scan shows them, because
/// they are part of what fills the disk, but files there belong to packages
-/// and removing them by hand breaks the system; pacman, paccache and
-/// `journalctl --vacuum` are the right tools. Refused even where
-/// permissions would allow it, and even inside them.
+/// and removing them by hand breaks the system; pacman, paccache,
+/// `journalctl --vacuum` or `brew cleanup` are the right tools. Refused even
+/// where permissions would allow it, and even inside them.
+///
+/// One list for every platform: a macOS tree never exists on Linux, and the
+/// other way round, so the extra entries cost nothing. On macOS `/etc`,
+/// `/var` and `/tmp` are links into `/private`, which a whole-disk scan
+/// reaches by its real name. `/Applications` is left out on purpose: moving
+/// an app to the Trash is how macOS uninstalls it, and the apps macOS ships
+/// live on the read-only system volume anyway.
+ #[cfg(not(windows))]
-const SYSTEM_TREES: [&str; 14] = [
+const SYSTEM_TREES: [&str; 20] = [
"/bin",
"/boot",
"/dev",
@@@ -164,136 -155,111 +165,216 @@@
"/usr",
"/var/lib",
"/efi",
+ // macOS.
+ "/System",
+ "/Library",
+ "/private",
+ "/cores",
+ "/opt/homebrew",
+ "/Network",
];
- /// How the guards compare paths: lexically normalized, and on macOS also in
- /// the form Finder shows and without case.
-/// What to use instead, said when a system tree is refused.
++/// How the guards compare paths: lexically normalized, and where the
++/// platform has more than one spelling for a place, in one of them.
+///
+/// macOS reaches the same directory under two names — `/Users/x` and
+/// `/System/Volumes/Data/Users/x` — and its disks ignore case by default, so
- /// `/library/caches` is `/Library/Caches`. A guard that compared the spelling
- /// would be passed by the other one. Only for judging: what is removed is
- /// always the path as marked.
++/// `/library/caches` is `/Library/Caches`. Windows ignores case too, and
++/// `\\?\C:\` is `C:\`. A guard that compared the spelling would be passed by
++/// the other one. Only for judging: what is removed is always the path as
++/// marked.
+fn guard_key(path: &Path) -> PathBuf {
++ if cfg!(windows) {
++ return windows_key(&normalize(path));
++ }
+ guard_key_for(path, cfg!(target_os = "macos"))
+}
+
+fn guard_key_for(path: &Path, macos: bool) -> PathBuf {
+ let path = normalize(path);
+ if !macos {
+ return path;
+ }
+ // The Data volume's own root stays as it is: it is under /System.
+ let path = match path.strip_prefix(crate::space::MACOS_DATA_VOLUME) {
+ Ok(rest) if !rest.as_os_str().is_empty() => Path::new("/").join(rest),
+ _ => path,
+ };
+ PathBuf::from(path.to_string_lossy().to_lowercase())
+}
+
- /// [`SYSTEM_TREES`] with their guard keys, computed once: the review screen
++#[cfg(windows)]
++fn windows_key(path: &Path) -> PathBuf {
++ crate::windows::guard_key(path)
++}
++
+ #[cfg(not(windows))]
-const SYSTEM_TOOLS: &str = "use the package manager";
++fn windows_key(path: &Path) -> PathBuf {
++ path.to_path_buf()
++}
++
++/// `path` is `base` or inside it, by whole components, as the guards
++/// compare them.
++fn within(path: &Path, base: &Path) -> bool {
++ guard_key(path).starts_with(guard_key(base))
++}
++
++/// The system trees with their guard keys, computed once: the review screen
+/// plans on every frame, for every mark.
- fn system_tree_keys() -> &'static [(&'static str, PathBuf)] {
- static KEYS: std::sync::LazyLock<Vec<(&'static str, PathBuf)>> =
++fn system_tree_keys() -> &'static [(String, PathBuf)] {
++ static KEYS: std::sync::LazyLock<Vec<(String, PathBuf)>> =
+ std::sync::LazyLock::new(|| {
- SYSTEM_TREES
- .iter()
- .map(|tree| (*tree, guard_key(Path::new(tree))))
++ system_trees()
++ .into_iter()
++ .map(|tree| {
++ let key = guard_key(&tree);
++ (tree.display().to_string(), key)
++ })
+ .collect()
+ });
+ &KEYS
+}
-/// 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;
- }
- SYSTEM_TREES
- .iter()
- .find(|tree| path.starts_with(tree))
- .copied()
++fn system_trees() -> Vec<PathBuf> {
++ SYSTEM_TREES.iter().map(PathBuf::from).collect()
+ }
+
+ /// [`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<PathBuf> {
+ let drive = system_drive();
+ let mut trees: Vec<PathBuf> = [
+ "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",
++ "$Recycle.Bin",
+ "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)
+ }
+
++/// What to use instead, said when a system tree is refused.
++#[cfg(not(windows))]
++const SYSTEM_TOOLS: &str = "remove it with the tool that installed it";
++
+ #[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<String> {
- if home.is_some_and(|home| within(path, &normalize(home))) {
+/// The system tree the path keyed `key` is in, if any. The home directory is
+/// never system, wherever it lives.
+fn system_tree(key: &Path, home: Option<&Path>) -> Option<&'static str> {
+ if home.is_some_and(|home| key.starts_with(home)) {
return None;
}
- system_trees()
- .into_iter()
- .find(|tree| within(path, tree))
- .map(|tree| tree.display().to_string())
+ system_tree_keys()
+ .iter()
+ .find(|(_, tree)| key.starts_with(tree))
- .map(|(name, _)| *name)
++ .map(|(name, _)| name.as_str())
+}
+
+/// A system tree strictly inside the path keyed `key`: removing `/opt` takes
+/// `/opt/homebrew` with it, and `/var` takes `/var/lib`.
+fn system_tree_below(key: &Path) -> Option<&'static str> {
+ system_tree_keys()
+ .iter()
+ .find(|(_, tree)| tree != key && tree.starts_with(key))
- .map(|(name, _)| *name)
++ .map(|(name, _)| name.as_str())
+}
+
+/// The home directory, as the guards compare it: by key, and by identity.
+#[derive(Debug)]
+struct Home {
+ key: PathBuf,
- /// Device and inode, so a spelling [`guard_key`] cannot fold still
- /// matches.
++ /// Device and inode (volume and file id on Windows), so a spelling
++ /// [`guard_key`] cannot fold still matches.
+ id: Option<(u64, u64)>,
+}
+
+impl Home {
+ fn of(path: &Path) -> Self {
+ Self {
+ key: guard_key(path),
- id: fs::metadata(path).ok().and_then(|meta| file_id(&meta)),
++ id: identity(path, true),
+ }
+ }
}
-fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option<String> {
+fn refuse(
+ path: &Path,
+ root: &Path,
+ home: Option<&Home>,
+ mounts: &[PathBuf],
+) -> Option<String> {
+ let key = guard_key(path);
++ let root_key = guard_key(root);
+ let home_key = home.map(|home| home.key.as_path());
if path.parent().is_none() {
return Some("the filesystem root cannot be removed".into());
}
- if path == root {
- if same(path, root) {
++ if key == root_key {
return Some("the scanned root 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 home_key.is_some_and(|home| key == home)
- || home.and_then(|home| home.id).is_some_and(|id| {
- fs::symlink_metadata(path)
- .ok()
- .and_then(|meta| file_id(&meta))
- == Some(id)
- })
++ || home
++ .and_then(|home| home.id)
++ .is_some_and(|id| identity(path, false) == Some(id))
+ {
+ return Some("the home directory cannot be removed".into());
+ }
+ // On Linux `/home` is usually a mount point of its own and refused as
+ // one; on macOS `/Users` is on the same volume as `/`, and removing it
+ // would empty the home directory before failing on `/Users` itself.
+ if home_key.is_some_and(|home| home.starts_with(&key)) {
+ return Some("it contains the home directory".into());
}
- if !path.starts_with(root) {
- if !within(path, root) {
++ if !key.starts_with(&root_key) {
return Some("outside the scanned root".into());
}
- if let Some(system) = system_tree(path, home) {
+ if let Some(system) = system_tree(&key, home_key) {
return Some(format!(
- "part of the system under {system}: remove it with the tool \
- that installed it"
+ "part of the system under {system}: {SYSTEM_TOOLS}"
));
}
+ if let Some(system) = system_tree_below(&key) {
+ return Some(format!(
+ "it contains {system}, which is part of the system"
+ ));
+ }
if is_mount_point(path) {
return Some(
"a mount point: removing it would cross onto another filesystem"
@@@ -310,115 -269,15 +391,126 @@@
None
}
-/// `path` is `base` or inside it, by whole components.
-#[cfg(not(windows))]
-fn within(path: &Path, base: &Path) -> bool {
- path.starts_with(base)
+/// `(device, inode)`: what makes two spellings one directory entry.
- #[allow(
- clippy::unnecessary_wraps,
- reason = "the Option is the non-Unix answer, so both arms must agree"
- )]
++/// `follow` decides whether a symlink at `path` answers for itself or for
++/// what it points to.
+#[cfg(unix)]
- fn file_id(meta: &fs::Metadata) -> Option<(u64, u64)> {
++fn identity(path: &Path, follow: bool) -> Option<(u64, u64)> {
+ use std::os::unix::fs::MetadataExt as _;
- Some((meta.dev(), meta.ino()))
++ let meta = if follow {
++ fs::metadata(path)
++ } else {
++ fs::symlink_metadata(path)
++ };
++ meta.ok().map(|meta| (meta.dev(), meta.ino()))
}
- #[cfg(not(unix))]
- const fn file_id(_meta: &fs::Metadata) -> Option<(u64, u64)> {
-#[cfg(not(windows))]
-fn same(left: &Path, right: &Path) -> bool {
- left == right
++/// `(volume serial, file id)`. Always what a link leads to: a junction to
++/// the home directory is refused as the home directory, which is only ever
++/// too careful.
++#[cfg(windows)]
++fn identity(path: &Path, _follow: bool) -> Option<(u64, u64)> {
++ crate::windows::identity(path)
++}
++
++#[cfg(not(any(unix, windows)))]
++const fn identity(_path: &Path, _follow: bool) -> Option<(u64, u64)> {
+ None
+}
+
+/// How long a read of the mount table is used before it is read again. A
+/// disk plugged in is noticed within this, and the removal itself stops at a
+/// mount boundary whatever the table said.
+const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2);
+
+/// The last read of the mount table, and whether a read is under way.
+struct MountCache {
+ read: Option<std::time::Instant>,
+ mounts: Option<Arc<Vec<PathBuf>>>,
+ refreshing: bool,
+}
+
+static MOUNTS: std::sync::Mutex<MountCache> =
+ std::sync::Mutex::new(MountCache {
+ read: None,
+ mounts: None,
+ refreshing: false,
+ });
+
+/// Every mount point on this machine, as guard keys, as last read.
+///
+/// Never blocks on the read: the review screen plans on every frame, and on
+/// macOS the table comes from running `mount`. A stale table starts a read on
+/// its own thread and is used meanwhile; before the first read lands it is
+/// empty, which is why the app primes it at start with
+/// [`prime_mount_points`].
+fn mount_points() -> Arc<Vec<PathBuf>> {
+ let mut cache = MOUNTS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let fresh = cache.read.is_some_and(|read| read.elapsed() < MOUNTS_FRESH);
+ if !fresh && !cache.refreshing {
+ cache.refreshing = true;
+ let spawned = thread::Builder::new()
+ .name("disktree-mounts".into())
+ .spawn(|| {
+ let mounts = Arc::new(read_mount_points());
+ let mut cache = MOUNTS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ cache.mounts = Some(mounts);
+ cache.read = Some(std::time::Instant::now());
+ cache.refreshing = false;
+ });
+ if spawned.is_err() {
+ cache.refreshing = false;
+ }
+ }
+ cache.mounts.clone().unwrap_or_default()
+}
+
+/// Start reading the mount table, so it is there by the time anything is
+/// marked.
+pub fn prime_mount_points() {
+ let _ = mount_points();
+}
+
+/// Read the mount points now: from `/proc/self/mounts`, or on macOS from
+/// `mount`, which has no `/proc`. Empty where neither can be read.
+fn read_mount_points() -> Vec<PathBuf> {
+ let points: Vec<PathBuf> =
+ if let Ok(table) = fs::read_to_string("/proc/self/mounts") {
+ crate::space::parse_mounts(&table)
+ .into_iter()
+ .map(|mount| mount.point)
+ .collect()
+ } else if cfg!(target_os = "macos") {
+ Command::new("/sbin/mount")
+ .stdin(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .output()
+ .ok()
+ .filter(|output| output.status.success())
+ .map(|output| {
+ crate::space::parse_macos_mounts(&String::from_utf8_lossy(
+ &output.stdout,
+ ))
+ })
+ .unwrap_or_default()
+ } else {
+ Vec::new()
+ };
+ points.iter().map(|point| guard_key(point)).collect()
+}
+
+/// A mount point strictly inside the path keyed `key`, if there is one. A
+/// scan that stays on one filesystem never shows what is mounted there, so
+/// the user cannot have meant to remove it.
+fn mount_below<'a>(key: &Path, mounts: &'a [PathBuf]) -> Option<&'a Path> {
+ mounts
+ .iter()
+ .find(|mount| mount.as_path() != key && mount.starts_with(key))
+ .map(PathBuf::as_path)
}
/// Whether `path` sits on a different device than its parent, i.e. is a
@@@ -497,7 -361,9 +597,11 @@@ pub enum TrashBackend
impl TrashBackend {
pub const fn is_available(self) -> bool {
match self {
- Self::MacOs | Self::TrashPut | Self::Gio | Self::XdgHome => true,
- Self::TrashPut | Self::Gio | Self::XdgHome | Self::RecycleBin => {
- true
- }
++ Self::MacOs
++ | Self::TrashPut
++ | Self::Gio
++ | Self::XdgHome
++ | Self::RecycleBin => true,
Self::Unavailable => false,
}
}
@@@ -529,18 -395,15 +635,25 @@@
}
}
+ /// 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))]
+///
+/// On macOS the system Trash is always there, and the Linux tools are not
+/// a substitute: Homebrew's `trash-put` writes the XDG layout, which Finder
+/// never shows, so their files would look recoverable and not be.
+#[cfg(target_os = "macos")]
+pub const fn detect_trash_backend() -> TrashBackend {
+ TrashBackend::MacOs
+}
+
+/// Detect the best available trash backend for this machine.
- #[cfg(not(target_os = "macos"))]
++#[cfg(not(any(target_os = "macos", windows)))]
pub fn detect_trash_backend() -> TrashBackend {
if which("trash-put") {
TrashBackend::TrashPut
@@@ -553,7 -416,7 +666,7 @@@
}
}
- #[cfg(not(target_os = "macos"))]
-#[cfg(not(windows))]
++#[cfg(not(any(target_os = "macos", windows)))]
fn which(program: &str) -> bool {
let Some(path) = std::env::var_os("PATH") else {
return false;
@@@ -687,27 -550,7 +800,28 @@@ fn run
});
}
-/// `rm -rf` semantics: a symlink is unlinked, never followed.
+/// `rm -rf --one-file-system` semantics: a symlink is unlinked, never
+/// followed, and nothing on another filesystem is touched.
+///
+/// `fs::remove_dir_all` would descend into anything mounted inside `path` and
+/// empty it before failing on the mount point itself, so the walk is done here
+/// instead: every directory is opened relative to its parent with
+/// `O_NOFOLLOW`, and one on a different device or mount stops the removal.
+/// (From tobi/disktree#10.)
++///
+#[cfg(unix)]
+pub fn remove_permanently(path: &Path) -> io::Result<()> {
+ let meta = fs::symlink_metadata(path)?;
+ if !meta.is_dir() {
+ return fs::remove_file(path);
+ }
+ let dir = open_dir(rustix::fs::CWD, path)?;
+ let top = Volume::of(&dir)?;
+ remove_contents(&dir, &top, path)?;
+ fs::remove_dir(path)
+}
+
+#[cfg(not(unix))]
pub fn remove_permanently(path: &Path) -> io::Result<()> {
let meta = fs::symlink_metadata(path)?;
if meta.is_dir() {
@@@ -717,166 -565,43 +836,191 @@@
}
}
+/// Where a directory lives, as far as crossing into another filesystem goes.
+#[cfg(unix)]
+struct Volume {
+ device: rustix::fs::Stat,
+ /// The mount the directory belongs to, where the kernel reports it (Linux,
+ /// `statx`). See [`Self::contains`].
+ mount: Option<u64>,
+}
+
+#[cfg(unix)]
+impl Volume {
+ fn of(dir: &std::os::fd::OwnedFd) -> io::Result<Self> {
+ Ok(Self {
+ device: rustix::fs::fstat(dir)?,
+ mount: mount_id(dir),
+ })
+ }
+
+ /// Whether `other` is on the same mount. Where the kernel names mounts,
+ /// that decides: a btrfs subvolume that is not mounted has its own
+ /// `st_dev` but is the same mount, and the scan showed it as part of the
+ /// volume, so it goes with the directory it is in; a bind mount keeps
+ /// `st_dev` but is a mount of its own, and stops the removal. Without
+ /// mount IDs (macOS) the device decides.
+ const fn contains(&self, other: &Self) -> bool {
+ match (self.mount, other.mount) {
+ (Some(one), Some(two)) => one == two,
+ _ => self.device.st_dev == other.device.st_dev,
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn mount_id(dir: &std::os::fd::OwnedFd) -> Option<u64> {
+ use rustix::fs::{AtFlags, StatxFlags, statx};
+ statx(dir, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID)
+ .ok()
+ .filter(|stat| stat.stx_mask & StatxFlags::MNT_ID.bits() != 0)
+ .map(|stat| stat.stx_mnt_id)
+}
+
+#[cfg(all(unix, not(target_os = "linux")))]
+const fn mount_id(_dir: &std::os::fd::OwnedFd) -> Option<u64> {
+ None
+}
+
+#[cfg(unix)]
+fn open_dir<P: rustix::path::Arg>(
+ parent: impl std::os::fd::AsFd,
+ name: P,
+) -> rustix::io::Result<std::os::fd::OwnedFd> {
+ use rustix::fs::{Mode, OFlags, openat};
+ openat(
+ parent,
+ name,
+ OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
+ Mode::empty(),
+ )
+}
+
+/// Empty the directory open at `dir`, staying on the volume of `top`.
+#[cfg(unix)]
+fn remove_contents(
+ dir: &std::os::fd::OwnedFd,
+ top: &Volume,
+ path: &Path,
+) -> io::Result<()> {
+ use rustix::fs::{AtFlags, Dir, FileType, unlinkat};
+ use rustix::io::Errno;
+ use std::ffi::OsStr;
+ use std::os::unix::ffi::OsStrExt as _;
+
+ // Names first, then removal: unlinking while a directory stream is open
+ // on the same directory may skip entries.
+ let mut entries = Vec::new();
+ for entry in Dir::read_from(dir)? {
+ let entry = entry?;
+ let name = entry.file_name();
+ if name != c"." && name != c".." {
+ entries.push((name.to_owned(), entry.file_type()));
+ }
+ }
+
+ for (name, kind) in entries {
+ if !matches!(kind, FileType::Directory | FileType::Unknown) {
+ unlinkat(dir, &name, AtFlags::empty())?;
+ continue;
+ }
+ let child = match open_dir(dir, &name) {
+ Ok(child) => child,
+ // Not a directory after all: a symlink, or a file on a
+ // filesystem that does not report types.
+ Err(Errno::NOTDIR | Errno::LOOP) => {
+ unlinkat(dir, &name, AtFlags::empty())?;
+ continue;
+ }
+ Err(error) => return Err(error.into()),
+ };
+ // Only directories need their path, for the message below.
+ let child_path = path.join(OsStr::from_bytes(name.to_bytes()));
+ if !top.contains(&Volume::of(&child)?) {
+ return Err(io::Error::other(format!(
+ "stopped at {}: another filesystem is mounted there, and \
+ nothing on it was touched",
+ child_path.display()
+ )));
+ }
+ remove_contents(&child, top, &child_path)?;
+ drop(child);
+ unlinkat(dir, &name, AtFlags::REMOVEDIR)?;
+ }
+ Ok(())
+}
+
+ #[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))]
++#[cfg(not(any(unix, 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::MacOs => trash_via_macos(path),
+ TrashBackend::RecycleBin => recycle(path),
TrashBackend::Unavailable => Err(io::Error::other(
"no trash tool is installed; use permanent deletion instead",
)),
}
}
+/// Move one path to the macOS Trash.
+///
+/// The `trash` crate resolves the parent directory and keeps the final name,
+/// so a symlink is trashed itself and its target is left alone. A name that is
+/// not UTF-8 is refused rather than handed over: the crate would
+/// percent-encode it into a different path.
+#[cfg(target_os = "macos")]
+fn trash_via_macos(path: &Path) -> io::Result<()> {
+ use trash::macos::{DeleteMethod, TrashContextExtMacos as _};
+
+ if path.to_str().is_none() {
+ return Err(io::Error::other(
+ "the name is not UTF-8, which the Trash cannot take; \
+ use permanent deletion",
+ ));
+ }
+ let mut context = trash::TrashContext::default();
+ // Finder's method asks for permission to control Finder and plays a
+ // sound per call; NSFileManager does neither.
+ context.set_delete_method(DeleteMethod::NsFileManager);
+ context.delete(path).map_err(|error| {
+ io::Error::other(format!(
+ "could not move to the Trash ({error}); network and read-only \
+ disks have none, so use permanent deletion there"
+ ))
+ })
+}
+
+#[cfg(not(target_os = "macos"))]
+fn trash_via_macos(_path: &Path) -> io::Result<()> {
+ Err(io::Error::other("the macOS Trash only exists on macOS"))
+}
+
+ /// 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
@@@ -1014,11 -741,6 +1160,12 @@@ mod tests
}
}
+ /// [`system_tree`] for plain paths, keyed the way [`refuse`] keys them.
++ #[cfg(not(windows))]
+ fn tree_of(path: &Path, home: &Path) -> Option<&'static str> {
+ system_tree(&guard_key(path), Some(&guard_key(home)))
+ }
+
fn tree() -> TempDir {
let temp = TempDir::new().expect("tempdir");
fs::create_dir_all(temp.path().join("a/b")).expect("mkdir");
@@@ -1068,6 -790,24 +1215,25 @@@
);
}
+ /// 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));
++ fn the_directories_above_home_are_refused() {
++ let home = Home::of(Path::new("/home/disktree-test-user"));
++ 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)),
++ 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();
@@@ -1110,217 -850,6 +1276,216 @@@
}
}
+ #[test]
+ fn a_directory_holding_the_home_directory_is_refused() {
+ // /Users in a whole-disk scan on macOS: the same volume as /, so no
+ // mount point, and removing it would empty home first.
+ let home = Path::new("/Users/tobi");
+ let reason = refuse(
+ Path::new("/Users"),
+ Path::new("/"),
+ Some(&Home::of(home)),
+ &[],
+ )
+ .expect("refused");
+ assert!(reason.contains("home directory"), "{reason}");
+ assert!(
+ refuse(
+ Path::new("/Users/tobi/src"),
+ Path::new("/"),
+ Some(&Home::of(home)),
+ &[]
+ )
+ .is_none(),
+ "inside home is the user's"
+ );
+ }
+
+ #[test]
+ fn a_directory_holding_a_system_tree_is_refused() {
+ let home = Path::new("/Users/tobi");
+ for (path, inside) in [("/opt", "/opt/homebrew"), ("/var", "/var/lib")]
+ {
+ let reason = refuse(
+ Path::new(path),
+ Path::new("/"),
+ Some(&Home::of(home)),
+ &[],
+ )
+ .expect("refused");
+ assert!(reason.contains(inside), "{path}: {reason}");
+ }
+ assert!(
+ refuse(
+ Path::new("/opt/local"),
+ Path::new("/"),
+ Some(&Home::of(home)),
+ &[]
+ )
+ .is_none(),
+ "a sibling of a system tree is not its parent"
+ );
+ }
+
+ #[test]
+ fn a_target_with_a_mount_inside_is_refused() {
+ let temp = tree();
+ let root = temp.path();
+ let mounts =
+ vec![guard_key(&root.join("a/b")), guard_key(&root.join("other"))];
+ assert_eq!(
+ mount_below(&guard_key(&root.join("a")), &mounts),
+ Some(guard_key(&root.join("a/b")).as_path())
+ );
+ assert_eq!(
+ mount_below(&guard_key(&root.join("a/b")), &mounts),
+ None,
+ "itself"
+ );
+ let reason =
+ refuse(&root.join("a"), root, None, &mounts).expect("refused");
+ assert!(reason.contains("mounted inside"), "{reason}");
+ assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None);
+ }
+
+ #[test]
+ fn nothing_is_mounted_below_a_temp_dir() {
+ let temp = tree();
+ assert_eq!(
+ mount_below(&guard_key(temp.path()), &read_mount_points()),
+ None
+ );
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn this_macs_mount_table_is_read_without_proc() {
+ let mounts = read_mount_points();
+ assert!(mounts.contains(&guard_key(Path::new("/"))), "{mounts:?}");
+ // Asked of `mount_below` itself: `refuse` would turn /System/Volumes
+ // away as a system tree before it looked at the mounts.
+ assert!(
+ mount_below(&guard_key(Path::new("/System/Volumes")), &mounts)
+ .is_some(),
+ "the Data volume is mounted there"
+ );
+ }
+
+ #[test]
+ fn the_mount_table_is_read_off_the_calling_thread_and_then_kept() {
+ prime_mount_points();
+ // The first read lands on its own thread; wait for it, briefly.
+ let mut mounts = mount_points();
+ for _ in 0..500 {
+ if !mounts.is_empty() {
+ break;
+ }
+ thread::sleep(std::time::Duration::from_millis(10));
+ mounts = mount_points();
+ }
+ assert_eq!(*mounts, read_mount_points(), "the same table, cached");
+ }
+
+ #[test]
+ #[cfg(unix)]
+ fn a_volume_is_judged_by_its_mount_where_the_kernel_names_one() {
+ let temp = tree();
+ let dir = open_dir(rustix::fs::CWD, temp.path()).expect("open");
+ let here = Volume::of(&dir).expect("volume");
+ let mut other = Volume::of(&dir).expect("volume");
+ assert!(here.contains(&other));
+ // A btrfs subvolume: another device, the same mount.
+ other.device.st_dev = other.device.st_dev.wrapping_add(1);
+ other.mount = Some(7);
+ let mount = Volume {
+ device: here.device,
+ mount: Some(7),
+ };
+ assert!(mount.contains(&other), "same mount, other device");
+ // A bind mount: the same device, another mount.
+ let bind = Volume {
+ device: here.device,
+ mount: Some(8),
+ };
+ assert!(!mount.contains(&bind));
+ // No mount IDs, as on macOS: the device decides.
+ let (mut plain, mut moved) = (
+ Volume::of(&dir).expect("volume"),
+ Volume::of(&dir).expect("volume"),
+ );
+ plain.mount = None;
+ moved.mount = None;
+ moved.device.st_dev = moved.device.st_dev.wrapping_add(1);
+ assert!(!plain.contains(&moved));
+ }
+
+ #[test]
+ fn macos_guard_keys_fold_the_data_volume_and_case() {
+ let key = |path: &str| guard_key_for(Path::new(path), true);
+ assert_eq!(
+ key("/System/Volumes/Data/Users/Tobi/src"),
+ PathBuf::from("/users/tobi/src")
+ );
+ assert_eq!(key("/Library/./Caches"), PathBuf::from("/library/caches"));
+ assert_eq!(
+ key("/System/Volumes/Data"),
+ PathBuf::from("/system/volumes/data"),
+ "the Data volume itself stays under /System"
+ );
+ assert_eq!(
+ guard_key_for(Path::new("/Library/X"), false),
+ PathBuf::from("/Library/X"),
+ "Linux paths are compared as spelled"
+ );
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn macos_guards_see_through_other_spellings() {
+ let home = Path::new("/Users/tobi");
+ let data = Path::new(crate::space::MACOS_DATA_VOLUME);
+ assert!(
+ refuse(
+ &data.join("Users/tobi/src"),
+ data,
+ Some(&Home::of(home)),
+ &[]
+ )
+ .is_none(),
+ "home under the Data volume's name is still home"
+ );
+ let reason = refuse(
+ Path::new("/library/caches"),
+ Path::new("/"),
+ Some(&Home::of(home)),
+ &[],
+ )
+ .expect("refused");
+ assert!(reason.contains("/Library"), "{reason}");
+ }
+
+ #[test]
+ fn permanent_removal_takes_nested_trees_and_hidden_files() {
+ let temp = tree();
+ let doomed = temp.path().join("a");
+ fs::create_dir_all(doomed.join("b/c/d")).expect("mkdir");
+ fs::write(doomed.join("b/c/d/.hidden"), "x").expect("write");
+ fs::write(doomed.join("b/c/f"), "x").expect("write");
+ remove_permanently(&doomed).expect("remove tree");
+ assert!(!doomed.exists());
+ assert!(temp.path().join("other").exists());
+ }
+
+ #[test]
+ fn permanent_removal_unlinks_nested_symlinks_without_following_them() {
+ let temp = tree();
+ let outside = TempDir::new().expect("tempdir");
+ fs::write(outside.path().join("keep"), "x").expect("write");
- std::os::unix::fs::symlink(outside.path(), temp.path().join("a/link"))
- .expect("symlink");
++ link_dir(outside.path(), &temp.path().join("a/link"));
+ remove_permanently(&temp.path().join("a")).expect("remove tree");
+ assert!(outside.path().join("keep").exists());
+ }
+
#[test]
fn permanent_removal_takes_directories_and_leaves_siblings() {
let temp = tree();
@@@ -1503,8 -1072,8 +1708,9 @@@
assert!(error.to_string().contains("no trash here"), "{error}");
}
+ #[cfg(not(windows))]
#[test]
- #[cfg(not(target_os = "macos"))]
++ #[cfg(not(any(target_os = "macos", windows)))]
fn detection_prefers_a_tool_this_machine_has() {
let backend = detect_trash_backend();
if which("trash-put") {
@@@ -1513,48 -1082,46 +1719,95 @@@
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())
++ system_tree(
++ &guard_key(&drive.join(relative)),
++ Some(&guard_key(&home)),
++ )
++ .map(str::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));
++ let reason = refuse(
++ &drive.join(r"Windows\Temp"),
++ &drive,
++ Some(&Home::of(&home)),
++ &[],
++ );
+ assert!(
+ reason.is_some_and(|reason| reason
+ .to_lowercase()
+ .contains(&windows.to_lowercase())),
+ "refused as part of {windows}"
+ );
+ }
+
- #[cfg(not(windows))]
#[test]
+ #[cfg(target_os = "macos")]
+ fn macos_always_uses_the_system_trash() {
+ // Whatever Homebrew put on PATH: its trash tools write a trash
+ // Finder never shows.
+ assert_eq!(detect_trash_backend(), TrashBackend::MacOs);
+ assert!(TrashBackend::MacOs.is_available());
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ #[ignore = "puts a file in this Mac's real Trash"]
+ fn the_macos_trash_takes_a_file_and_leaves_a_linked_target() {
+ let temp = TempDir::new().expect("tempdir");
+ let file = temp.path().join("disktree-trash-check.txt");
+ fs::write(&file, b"x").expect("write");
+ let keep = temp.path().join("keep.txt");
+ fs::write(&keep, b"kept").expect("write");
+ let link = temp.path().join("disktree-trash-check-link");
+ std::os::unix::fs::symlink(&keep, &link).expect("symlink");
+
+ move_to_trash(&file, TrashBackend::MacOs).expect("trashed");
+ move_to_trash(&link, TrashBackend::MacOs).expect("trashed");
+
+ assert!(!file.exists());
+ assert!(fs::symlink_metadata(&link).is_err(), "the link went");
+ assert_eq!(fs::read(&keep).expect("read"), b"kept", "not its target");
+ }
+
+ #[test]
+ #[cfg(target_os = "macos")]
+ fn a_name_that_is_not_utf8_is_refused_before_the_trash_sees_it() {
+ use std::os::unix::ffi::OsStrExt as _;
+ let temp = TempDir::new().expect("tempdir");
+ let odd = temp
+ .path()
+ .join(std::ffi::OsStr::from_bytes(b"not-\xff-utf8"));
+ let error = trash_via_macos(&odd).expect_err("refused");
+ assert!(error.to_string().contains("UTF-8"), "{error}");
+ }
+
+ #[test]
++ #[cfg(not(windows))]
fn system_trees_are_refused_in_a_whole_disk_scan() {
let home = Path::new("/home/tobi");
assert_eq!(
@@@ -1573,32 -1143,12 +1826,33 @@@
"components, not prefixes"
);
let odd_home = Path::new("/usr/home/tobi");
- assert_eq!(
- system_tree(Path::new("/usr/home/tobi/.cache"), Some(odd_home)),
- None
+ assert_eq!(tree_of(Path::new("/usr/home/tobi/.cache"), odd_home), None);
+ let reason = refuse(
+ Path::new("/etc/hosts"),
+ Path::new("/"),
+ Some(&Home::of(home)),
+ &[],
);
- let reason =
- refuse(Path::new("/etc/hosts"), Path::new("/"), Some(home));
assert!(reason.is_some_and(|reason| reason.contains("/etc")));
}
+
+ #[test]
++ #[cfg(not(windows))]
+ fn macos_system_trees_are_refused_but_apps_are_not() {
+ let home = Path::new("/Users/tobi");
+ for (path, tree) in [
+ ("/System/Library/Fonts", "/System"),
+ ("/Library/Caches/com.apple.x", "/Library"),
+ ("/private/etc/hosts", "/private"),
+ ("/private/var/folders/xy", "/private"),
+ ("/opt/homebrew/Cellar/git", "/opt/homebrew"),
+ ] {
+ assert_eq!(tree_of(Path::new(path), home), Some(tree));
+ }
+ // An app is uninstalled by moving it to the Trash, and a user's own
+ // Library is theirs.
+ for path in ["/Applications/Xcode.app", "/Users/tobi/Library/Caches"] {
+ assert_eq!(tree_of(Path::new(path), home), None, "{path}");
+ }
+ }
}
diff --cc crates/disktree-core/src/scan.rs
index 42f150d,fb9fb50..2dd0ed7
--- a/crates/disktree-core/src/scan.rs
+++ b/crates/disktree-core/src/scan.rs
@@@ -298,76 -291,62 +297,83 @@@ impl WalkContext
return Classified::Skipped;
}
- if file_type.is_symlink() {
- return self.classify_symlink(&path, name);
+ 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
+ }
}
+ }
- if file_type.is_dir() {
- if self
- .never_scanned
- .get()
- .is_some_and(|never| never.contains(&path))
- {
- return Classified::Skipped;
- }
- // `lstat` at most once per directory: macOS reads the dataless
- // flag from it, and the device check below needs it wherever the
- // mount table cannot be read, which on macOS is everywhere.
- let meta_cell = std::cell::OnceCell::new();
- let meta = || meta_cell.get_or_init(|| entry.metadata());
- if cfg!(target_os = "macos")
- && meta().as_ref().is_ok_and(is_dataless)
- {
+ fn classify_dir(
+ &self,
+ entry: &impl Listed,
+ path: PathBuf,
+ name: Box<str>,
+ ) -> Classified {
++ if self
++ .never_scanned
++ .get()
++ .is_some_and(|never| never.contains(&path))
++ {
++ return Classified::Skipped;
++ }
++ // Read at most once per directory: macOS needs it for the dataless
++ // flag, and the device check below wherever the mount table cannot
++ // be read, which on macOS is everywhere.
++ let directory_cell = std::cell::OnceCell::new();
++ let directory = || directory_cell.get_or_init(|| entry.directory());
++ if EVICTED_IS_KNOWN
++ && directory()
++ .as_ref()
++ .is_ok_and(|directory| directory.evicted)
++ {
++ return Classified::Skipped;
++ }
+ // Memoized: the subtree a narrower scan already measured is taken
+ // whole, before any volume rule, since it was measured under the same
+ // rules.
+ 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;
}
- // 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) {
+ } else if self.options.one_filesystem {
- match (entry.device(), self.root_device(&path)) {
- (Ok(device), Some(root_device)) if device != root_device => {
++ match (directory(), self.root_device(&path)) {
++ (Ok(directory), Some(root_device))
++ if directory.device != root_device =>
++ {
return Classified::Skipped;
}
- } else if self.options.one_filesystem {
- let device = match meta() {
- Ok(meta) => device_of(meta),
- Err(error) => {
- self.progress.record_error(&path, error);
- return Classified::Skipped;
- }
- };
- if self
- .root_device(&path)
- .is_some_and(|root_device| device != root_device)
- {
+ (Err(error), _) => {
- self.progress.record_error(&path, &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),
- Err(error) => {
- self.progress.record_error(&path, &error);
- Classified::Skipped
+ _ => {}
}
}
+ self.progress.count_dir();
+ Classified::Subdirectory(path)
}
fn classify_symlink(&self, path: &Path, name: Box<str>) -> Classified {
@@@ -381,9 -360,7 +387,8 @@@
Classified::Entry(leaf_node(
name,
NodeKind::Symlink,
- size,
- &meta,
- shares_inode(&meta),
+ &facts,
++ facts.shared,
))
}
Err(error) => {
@@@ -405,12 -382,7 +410,12 @@@
};
if meta.is_dir() {
+ // A link into an evicted cloud folder is left alone for the
+ // same reason the folder itself is.
+ if is_dataless(&meta) {
+ return Classified::Skipped;
+ }
- if let Some(key) = file_identity(&meta)
+ if let Some(key) = identity_of(path, &meta)
&& !lock(&self.visited_dirs).insert(key)
{
return Classified::Skipped;
@@@ -426,17 -402,136 +435,168 @@@
&self,
name: Box<str>,
kind: NodeKind,
- meta: &Metadata,
+ facts: &Facts,
) -> Classified {
- let size = measure(meta, self.options.apparent_size);
- self.progress.count_file(size);
+ self.progress.count_file(facts.size);
- Classified::Entry(leaf_node(name, kind, facts))
+ // A followed link reaches a file a second way, whatever its link
+ // count says.
- let track = self.options.follow_links || shares_inode(meta);
- Classified::Entry(leaf_node(name, kind, size, meta, track))
++ let track = self.options.follow_links || facts.shared;
++ Classified::Entry(leaf_node(name, kind, facts, track))
+ }
+ }
+
+ /// 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<str>;
+ fn listing(&self) -> io::Result<Listing>;
+ /// Size, identity and age of a leaf.
+ fn facts(&self, apparent_size: bool) -> io::Result<Facts>;
- /// The device a directory is on, for staying on one volume when the
- /// mount table cannot be read.
- fn device(&self) -> io::Result<u64>;
++ /// What a directory is, read before the walk enters it.
++ fn directory(&self) -> io::Result<Directory>;
++}
++
++/// Whether [`Directory::evicted`] can ever be true here, so a platform that
++/// cannot say never pays for asking.
++const EVICTED_IS_KNOWN: bool = cfg!(any(target_os = "macos", windows));
++
++/// What the walk needs to know about a directory before entering it.
++struct Directory {
++ /// The device it is on, for staying on one volume when the mount table
++ /// cannot be read.
++ device: u64,
++ /// Its contents live only in the cloud (iCloud Drive or a File Provider
++ /// on macOS, `OneDrive` or another cloud files provider on Windows).
++ /// Listing it would make the provider fetch them, so a disk scan must
++ /// not; it holds no local blocks, so skipping it loses nothing.
++ evicted: bool,
+ }
+
+ /// 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,
++ /// The file may have another name the walk could meet: its identity is
++ /// worth keeping for hardlink de-duplication.
++ shared: bool,
+ }
+
+ impl Facts {
+ fn of(meta: &Metadata, apparent_size: bool) -> Self {
+ Self {
+ size: measure(meta, apparent_size),
+ identity: file_identity(meta),
+ modified: modified_seconds(meta),
++ shared: shares_inode(meta),
+ }
+ }
+ }
+
+ #[cfg(not(windows))]
+ impl Listed for DirEntry {
+ fn entry_path(&self) -> PathBuf {
+ self.path()
+ }
+
+ fn display_name(&self) -> Box<str> {
+ self.file_name().to_string_lossy().into_owned().into()
+ }
+
+ fn listing(&self) -> io::Result<Listing> {
+ 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<Facts> {
+ self.metadata().map(|meta| Facts::of(&meta, apparent_size))
+ }
+
- fn device(&self) -> io::Result<u64> {
- self.metadata().map(|meta| device_of(&meta))
++ fn directory(&self) -> io::Result<Directory> {
++ self.metadata().map(|meta| Directory {
++ device: device_of(&meta),
++ evicted: is_dataless(&meta),
++ })
}
}
+ #[cfg(windows)]
+ impl Listed for crate::windows::Entry {
+ fn entry_path(&self) -> PathBuf {
+ self.path()
+ }
+
+ fn display_name(&self) -> Box<str> {
+ self.file_name().to_string_lossy().into_owned().into()
+ }
+
+ fn listing(&self) -> io::Result<Listing> {
+ 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<Facts> {
+ Ok(Facts {
+ size: if apparent_size {
+ self.apparent()
+ } else {
+ self.allocated()
+ },
+ identity: self.identity(),
+ modified: self.modified(),
++ // The listing has no link count; a file id is free here, so
++ // every file keeps one.
++ shared: true,
+ })
+ }
+
- /// 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<u64> {
- Ok(0)
++ /// The device is never consulted: see
++ /// [`crate::space::foreign_mounts_for`]. The same answer as
++ /// [`device_of`], so the two could only ever agree.
++ fn directory(&self) -> io::Result<Directory> {
++ Ok(Directory {
++ device: 0,
++ evicted: self.evicted(),
++ })
+ }
+ }
+
+ /// List a directory the way [`Listed`] describes.
+ #[cfg(not(windows))]
+ fn list(path: &Path) -> io::Result<fs::ReadDir> {
+ fs::read_dir(path)
+ }
+
+ #[cfg(windows)]
+ fn list(path: &Path) -> io::Result<crate::windows::ReadDir> {
+ crate::windows::read_dir(path)
+ }
+
/// What a directory entry turned out to be.
enum Classified {
/// Descend into this directory on a new task.
@@@ -641,21 -734,10 +801,20 @@@ fn mark_duplicate_hardlinks(node: &mut
}
}
- /// A leaf. Its `(device, inode)` is kept only when `track` says the walk
- /// could meet the same file again: a hardlink de-duplication set of every
- /// file on a disk is millions of entries, nearly all for files with one name.
-fn leaf_node(name: Box<str>, kind: NodeKind, facts: &Facts) -> Node {
++/// A leaf. Its identity is kept only when `track` says the walk could meet
++/// the same file again: a hardlink de-duplication set of every file on a
++/// disk is millions of entries, nearly all for files with one name.
+fn leaf_node(
+ name: Box<str>,
+ kind: NodeKind,
- size: u64,
- meta: &Metadata,
++ facts: &Facts,
+ track: bool,
+) -> Node {
- let mut node = Node::entry(name, kind, size);
+ let mut node = Node::entry(name, kind, facts.size);
- node.inode = facts.identity;
+ if track {
- node.inode = file_identity(meta);
++ node.inode = facts.identity;
+ }
- node.modified = modified_seconds(meta);
+ node.modified = facts.modified;
node
}
diff --cc crates/disktree-core/src/space.rs
index 22aab9b,74a4ae9..f7b5bb4
--- a/crates/disktree-core/src/space.rs
+++ b/crates/disktree-core/src/space.rs
@@@ -69,7 -83,7 +83,7 @@@ pub fn device_for(path: &Path) -> Optio
/// The device a path's filesystem is mounted from, such as
/// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in
/// `/proc/self/mounts`. `None` where that table cannot be read.
- #[cfg(not(target_os = "macos"))]
-#[cfg(not(windows))]
++#[cfg(not(any(target_os = "macos", windows)))]
pub fn device_for(path: &Path) -> Option<String> {
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
@@@ -187,7 -201,7 +201,7 @@@ pub fn volume_root(mounts: &[Mount], pa
}
/// [`volume_root`] for this machine.
- #[cfg(not(target_os = "macos"))]
-#[cfg(not(windows))]
++#[cfg(not(any(target_os = "macos", windows)))]
pub fn volume_root_for(path: &Path) -> Option<PathBuf> {
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
@@@ -201,98 -222,21 +222,113 @@@ pub fn foreign_mounts_for(root: &Path)
Some(foreign_mounts(&parse_mounts(&table), root))
}
+/// The mount points in what macOS's `mount` prints.
+///
+/// One per line: `/dev/disk3s5 on /System/Volumes/Data (apfs, local, …)`.
+/// The point is
+/// between the first ` on ` and the last ` (`, so a name with spaces or
+/// brackets in it survives.
+pub fn parse_macos_mounts(output: &str) -> Vec<PathBuf> {
+ output
+ .lines()
+ .filter_map(|line| {
+ let (_, rest) = line.split_once(" on ")?;
+ let (point, _) = rest.rsplit_once(" (")?;
+ Some(PathBuf::from(point))
+ })
+ .collect()
+}
+
+/// Where the Data volume is mounted on macOS.
+///
+/// Since Catalina `/` is a read-only system volume, and everything the user
+/// can write — `/Users`,
+/// `/Applications`, `/Library`, `/private`, … — lives on the Data volume,
+/// joined into `/` by firmlinks. The two report the same device, and
+/// `/Users` and `/System/Volumes/Data/Users` are the same inode.
+pub const MACOS_DATA_VOLUME: &str = "/System/Volumes/Data";
+
+/// Directories under `root` a scan must never enter, whatever the volume
+/// rules say, given where `root` really is (`canonical`).
+///
+/// On macOS: the Data volume's second mount, which is every firmlinked
+/// directory again under another name, so walking it counts the disk twice;
+/// and `/Network`, an automount point that would reach for a server. The
+/// paths are returned in `root`'s own spelling, because that is how the walk
+/// names what it finds.
+pub fn never_scanned(root: &Path, canonical: &Path) -> Vec<PathBuf> {
+ if !cfg!(target_os = "macos") {
+ return Vec::new();
+ }
+ [MACOS_DATA_VOLUME, "/Network"]
+ .iter()
+ .filter_map(|skip| Path::new(skip).strip_prefix(canonical).ok())
+ .filter(|below| !below.as_os_str().is_empty())
+ .map(|below| root.join(below))
+ .collect()
+}
+
+/// The top of the disk `path` lives on: its mount point, from `statfs`.
+///
+/// The Data volume answers `/System/Volumes/Data`, but the disk a user
+/// thinks of is `/`, which shows the same files under the names Finder uses
+/// and adds the system volume beside them.
+#[cfg(target_os = "macos")]
+pub fn volume_root_for(path: &Path) -> Option<PathBuf> {
+ let stat = rustix::fs::statfs(path).ok()?;
+ let mount = PathBuf::from(c_chars(&stat.f_mntonname));
+ if mount.as_os_str().is_empty() {
+ return None;
+ }
+ Some(if mount == Path::new(MACOS_DATA_VOLUME) {
+ PathBuf::from("/")
+ } else {
+ mount
+ })
+}
+
+/// The device a path's filesystem is mounted from, such as
+/// `/dev/disk3s5`, from `statfs`.
+#[cfg(target_os = "macos")]
+pub fn device_for(path: &Path) -> Option<String> {
+ // `/` is a snapshot of the system volume (`disk3s1s1`); name the disk
+ // the user's files are on instead, which is what the meter measures.
+ let path = if path == Path::new("/") {
+ Path::new(MACOS_DATA_VOLUME)
+ } else {
+ path
+ };
+ let stat = rustix::fs::statfs(path).ok()?;
+ let device = c_chars(&stat.f_mntfromname);
+ (!device.is_empty()).then_some(device)
+}
+
+/// A NUL-terminated C string field as text.
+#[cfg(target_os = "macos")]
+fn c_chars(field: &[std::ffi::c_char]) -> String {
+ let bytes: Vec<u8> = field
+ .iter()
+ .take_while(|&&byte| byte != 0)
+ .map(|&byte| byte as u8)
+ .collect();
+ String::from_utf8_lossy(&bytes).into_owned()
+}
+
+ /// 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<Vec<PathBuf>> {
+ Some(Vec::new())
+ }
+
#[cfg(test)]
mod tests {
use super::*;
diff --cc crates/disktree-core/src/windows.rs
index 0000000,e834239..6e2ef8c
mode 000000,100644..100644
--- a/crates/disktree-core/src/windows.rs
+++ b/crates/disktree-core/src/windows.rs
@@@ -1,0 -1,727 +1,752 @@@
+ //! 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_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,
+ };
+
+ 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.
++/// A cloud files placeholder (`OneDrive` and the like) with nothing local:
++/// opening or listing it makes the provider fetch it. `RECALL_ON_OPEN` marks
++/// a directory whose entries are not local, `RECALL_ON_DATA_ACCESS` one whose
++/// files are all online-only.
++const EVICTED: u32 =
++ FILE_ATTRIBUTE_RECALL_ON_OPEN | FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS;
++
+ 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<Path>,
+ name: OsString,
+ kind: Kind,
+ apparent: u64,
+ allocated: u64,
+ modified: i64,
+ identity: Option<(u64, u64)>,
++ attributes: u32,
+ }
+
+ 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
+ }
+
++ /// Whether this is a directory the cloud files provider holds and the
++ /// disk does not: see [`EVICTED`].
++ pub const fn evicted(&self) -> bool {
++ matches!(self.kind, Kind::Directory) && self.attributes & EVICTED != 0
++ }
++
+ /// `(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<Path>, entry: &fs::DirEntry) -> io::Result<Self> {
+ 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,
++ attributes: meta.file_attributes(),
+ })
+ }
+ }
+
+ /// A directory being listed; like `std::fs::ReadDir`, it leaves out `.`
+ /// and `..`.
+ #[derive(Debug)]
+ pub struct ReadDir {
+ dir: Arc<Path>,
+ 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<fs::ReadDir>),
+ }
+
+ #[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>,
+ /// `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<usize>,
+ done: bool,
+ }
+
+ /// List `dir`, with each entry's allocation and file id.
+ pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
+ 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<Path> = 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<Entry>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ 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::<u8>(),
+ 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<Path>,
+ offset: usize,
+ ) -> io::Result<(Option<Entry>, Option<usize>)> {
+ 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<u16> = 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)),
++ attributes,
+ };
+ 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<u64> {
+ // 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<SpaceInfo> {
+ // 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<PathBuf> {
+ 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.
++/// Whether `left` and `right` name the same place, compared the way Windows
++/// compares names: see [`folded`].
+ pub fn same(left: &Path, right: &Path) -> bool {
+ folded(left) == folded(right)
+ }
+
-/// Each component in the form Windows would treat as equal.
++/// `path` in the one spelling the removal guards compare: [`folded`], put
++/// back together, so `Path::starts_with` on two keys is containment as
++/// Windows sees it.
++pub fn guard_key(path: &Path) -> PathBuf {
++ folded(path).into_iter().collect()
++}
++
++/// Each component in the form Windows would treat as equal: without regard
++/// to case, so `C:\WINDOWS\System32` is inside `C:\Windows`, and with
++/// `\\?\C:\` the same place as `C:\`.
+ fn folded(path: &Path) -> Vec<String> {
+ 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<Vec<u16>> {
+ let mut wide: Vec<u16> = 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<u32> {
+ 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::<PathBuf>();
+ 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<Entry> {
+ let mut entries: Vec<Entry> = read_dir(dir)
+ .expect("list")
+ .collect::<io::Result<_>>()
+ .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<u8> = (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<OsString> = 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");
+ }
+
++ /// Containment as the removal guards judge it.
++ fn within(path: &Path, base: &Path) -> bool {
++ guard_key(path).starts_with(guard_key(base))
++ }
++
+ #[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");
+ }
+ }