mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
Merge pr/14 (Windows) onto the macOS port
One set of removal guards for all three platforms: guard_key folds macOS firmlinks and case, and now Windows case and verbatim prefixes, so within/same from #14 become key comparisons. System trees are one keyed list per platform. Fixed while merging: - plan() found home through $HOME, which Windows does not set, so every home guard was off there; std::env::home_dir() instead. - Scan: #14's Listed/Facts shape with #13's never-scanned paths, dataless iCloud folders and track-only-shared-inodes; OneDrive cloud-only folders are skipped the same way on Windows. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -70,3 +70,27 @@ jobs:
|
||||
# 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
|
||||
|
||||
@@ -23,6 +23,9 @@ jobs:
|
||||
# The oldest supported runner: its glibc is what the binary needs at
|
||||
# least, so building here runs on the most systems.
|
||||
runs-on: ubuntu-22.04
|
||||
outputs:
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
@@ -175,3 +178,53 @@ jobs:
|
||||
(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
|
||||
|
||||
@@ -38,6 +38,8 @@ 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
|
||||
|
||||
@@ -60,7 +62,8 @@ done, and it must not fix anything: a red local run is the same signal CI gives.
|
||||
## Invariants
|
||||
|
||||
1. **Sizes come from `st_blocks * 512` unless apparent size was asked for.**
|
||||
That is the number that comes back when a file is deleted.
|
||||
That is the number that comes back when a file is deleted. On Windows it
|
||||
is the allocation the directory listing reports; see `windows.rs`.
|
||||
2. **`own_bytes`/`own_files` are derived, never tracked.** `tree::aggregate`
|
||||
computes the totals from the children. Hardlink de-duplication rewrites a
|
||||
leaf's weight and re-aggregates; anything that patches `bytes` directly will
|
||||
@@ -69,7 +72,8 @@ done, and it must not fix anything: a red local run is the same signal CI gives.
|
||||
has finished.** That is the `+1` sentinel in `PendingDir::pending`. Building
|
||||
early silently drops whole subtrees — it has happened once.
|
||||
4. **Only paths under the scanned root may be removed**, and mount points, the
|
||||
root, the home directory and symlink targets are refused.
|
||||
root, the home directory, any directory holding it, and symlink targets are
|
||||
refused.
|
||||
5. **Marks are keyed by absolute path**, not tree position, so they survive a
|
||||
re-scan; `Marks::refresh` re-reads their sizes and drops what is gone.
|
||||
6. **The treemap is painted, not composed of elements.** Thousands of
|
||||
@@ -94,6 +98,7 @@ done, and it must not fix anything: a red local run is the same signal CI gives.
|
||||
| tile geometry, nesting, the merged tail | `crates/disktree-core/src/treemap.rs` |
|
||||
| anything that deletes, or refuses to | `crates/disktree-core/src/removal.rs` |
|
||||
| free space and projections | `crates/disktree-core/src/space.rs` |
|
||||
| what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — the only `unsafe` |
|
||||
| a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` |
|
||||
| spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout |
|
||||
| the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` |
|
||||
|
||||
Generated
+4
@@ -1424,10 +1424,12 @@ version = "0.9.1"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"disktree-core",
|
||||
"dunce",
|
||||
"gpui-kit",
|
||||
"gpui-omarchy",
|
||||
"rustc-hash 2.1.3",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1440,6 +1442,8 @@ dependencies = [
|
||||
"rustix",
|
||||
"tempfile",
|
||||
"trash",
|
||||
"winapi-util",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -86,6 +86,20 @@ 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
|
||||
@@ -239,6 +253,31 @@ twice. `-X` crosses into everything.
|
||||
Without root, some system directories cannot be read; they are counted as
|
||||
unreadable in the top bar rather than guessed at.
|
||||
|
||||
## On Windows
|
||||
|
||||
The same program, with Windows' answers to the questions above:
|
||||
|
||||
- **Disk usage** is the allocation NTFS reports for each file: whole
|
||||
clusters, less for a compressed or sparse file, nothing for one small
|
||||
enough to live in its file record. It arrives with the directory listing
|
||||
itself (`FileIdExtdDirectoryInfo`), so it costs no more than the walk.
|
||||
Hardlinks count once on NTFS.
|
||||
- **The whole disk** is the drive your profile is on, usually `C:\`. A
|
||||
folder another volume is mounted on is a link, like a junction, and is
|
||||
not entered, so a scan stays on one volume; `-l` follows links, and with
|
||||
them mounted folders.
|
||||
- **Move to trash** is the Recycle Bin, through the shell, which asks
|
||||
before destroying anything it cannot recycle.
|
||||
- **Refused besides the rules below:** Windows, Program Files and
|
||||
ProgramData, what Windows keeps at the top of its drive (System Volume
|
||||
Information, Recovery, Boot), and any folder holding your profile, such as
|
||||
`C:\Users`. Names compare without regard to case, as Windows compares
|
||||
them.
|
||||
- **Hidden** still means a name starting with a dot; the hidden attribute is
|
||||
not consulted, so `-H` does not drop `AppData`.
|
||||
- **The theme** is gpui-omarchy's default, since there is no Omarchy theme
|
||||
to follow.
|
||||
|
||||
## What it refuses to do
|
||||
|
||||
The removal rules live in `crates/disktree-core/src/removal.rs`, and each one is
|
||||
|
||||
@@ -18,8 +18,12 @@ gpui-kit = { version = "=0.6.1", default-features = false, features = ["assets"]
|
||||
gpui-omarchy = "0.1.2"
|
||||
disktree-core = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
dunce = "1.0.5"
|
||||
rustc-hash = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_System_Console"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# The window harness: it lets the tests draw a real frame and press real keys.
|
||||
gpui-kit = { version = "=0.6.1", default-features = false, features = [
|
||||
|
||||
@@ -5,6 +5,12 @@
|
||||
//! live free-space meter. Marking is non-destructive until the review screen
|
||||
//! is confirmed.
|
||||
|
||||
// A window, not a console program: on Windows, opening it from Explorer or
|
||||
// the Start menu should not bring a console window along. `main` attaches to
|
||||
// the console of a terminal it was started from, so `--help` and errors still
|
||||
// reach one. Ignored elsewhere.
|
||||
#![windows_subsystem = "windows"]
|
||||
|
||||
mod app_menu;
|
||||
mod appearance;
|
||||
mod git;
|
||||
@@ -58,6 +64,15 @@ options:
|
||||
";
|
||||
|
||||
fn main() -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
console::attach();
|
||||
let outcome = run();
|
||||
#[cfg(windows)]
|
||||
console::detach();
|
||||
outcome
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
let args = parse_args()?;
|
||||
let root = args.root.clone();
|
||||
let depth = args.depth;
|
||||
@@ -68,7 +83,7 @@ fn main() -> Result<()> {
|
||||
.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);
|
||||
@@ -191,21 +206,21 @@ fn parse_args() -> Result<Args> {
|
||||
!(disk && root.is_some()),
|
||||
"--disk and a PATH cannot be combined"
|
||||
);
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let home = std::env::home_dir();
|
||||
let root = match root {
|
||||
_ if disk => home
|
||||
.as_deref()
|
||||
.and_then(disktree_core::space::volume_root_for)
|
||||
.unwrap_or_else(|| PathBuf::from("/")),
|
||||
Some(root) => root,
|
||||
None => std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.context("no path given and HOME is not set")?,
|
||||
None => home.context("no path given and no home directory")?,
|
||||
};
|
||||
// Store the depth as the initial view setting rather than a scan option: it
|
||||
// is a display choice the run-time `[` and `]` keys also change.
|
||||
// Canonical, so a later widening recognises this tree in the wider walk.
|
||||
let root = root.canonicalize().unwrap_or(root);
|
||||
// Canonical, so a later widening recognises this tree in the wider walk;
|
||||
// through dunce, so Windows gets `C:\Users\…` rather than the `\\?\C:\…`
|
||||
// form nothing else is written in.
|
||||
let root = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let metadata = std::fs::metadata(&root)
|
||||
.with_context(|| format!("cannot read {}", root.display()))?;
|
||||
anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display());
|
||||
@@ -216,3 +231,35 @@ fn parse_args() -> Result<Args> {
|
||||
depth: depth.clamp(1, 6),
|
||||
})
|
||||
}
|
||||
|
||||
/// The console of the terminal disktree was started from, if any: a
|
||||
/// windowed program on Windows gets none of its own.
|
||||
#[cfg(windows)]
|
||||
mod console {
|
||||
#![allow(
|
||||
unsafe_code,
|
||||
reason = "two Win32 calls that take no pointers to get wrong"
|
||||
)]
|
||||
|
||||
use windows_sys::Win32::System::Console::{
|
||||
ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole,
|
||||
};
|
||||
|
||||
/// Borrow the parent's console so printed text reaches it. Does
|
||||
/// nothing when started from Explorer, which has none.
|
||||
pub fn attach() {
|
||||
// SAFETY: takes a process id by value, and failure only means
|
||||
// there was no console to attach to.
|
||||
unsafe {
|
||||
AttachConsole(ATTACH_PARENT_PROCESS);
|
||||
}
|
||||
}
|
||||
|
||||
/// Let go of it again, so the shell redraws its prompt.
|
||||
pub fn detach() {
|
||||
// SAFETY: no arguments; a process without a console is left as is.
|
||||
unsafe {
|
||||
FreeConsole();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,13 +107,16 @@ pub fn is_hidden(path: &Path) -> bool {
|
||||
}
|
||||
|
||||
/// Shorten a path for display: `~` for the home directory, and the path with
|
||||
/// the home prefix replaced when it is below it.
|
||||
/// the home prefix replaced when it is below it. The separator after `~` is
|
||||
/// the platform's, so Windows shows `~\AppData\Local`, not `~/AppData\Local`.
|
||||
pub fn display_path(path: &Path, home: Option<&Path>) -> String {
|
||||
match home
|
||||
.and_then(|home| path.strip_prefix(home).ok().map(|rest| (home, rest)))
|
||||
{
|
||||
Some((_, rest)) if rest.as_os_str().is_empty() => "~".to_string(),
|
||||
Some((_, rest)) => format!("~/{}", rest.display()),
|
||||
Some((_, rest)) => {
|
||||
format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display())
|
||||
}
|
||||
None => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
@@ -220,9 +223,10 @@ mod tests {
|
||||
#[test]
|
||||
fn display_path_shortens_the_home_prefix() {
|
||||
let home = Path::new("/home/tobi");
|
||||
let separator = std::path::MAIN_SEPARATOR;
|
||||
assert_eq!(
|
||||
display_path(Path::new("/home/tobi/.cache/npm"), Some(home)),
|
||||
"~/.cache/npm"
|
||||
display_path(&home.join(".cache").join("npm"), Some(home)),
|
||||
format!("~{separator}.cache{separator}npm")
|
||||
);
|
||||
assert_eq!(display_path(home, Some(home)), "~");
|
||||
assert_eq!(display_path(Path::new("/var/log"), Some(home)), "/var/log");
|
||||
|
||||
@@ -437,7 +437,7 @@ impl Disktree {
|
||||
depth: u32,
|
||||
cx: &mut Context<'_, Self>,
|
||||
) -> Self {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let home = std::env::home_dir();
|
||||
let space = space_info(&root_path).ok();
|
||||
let trash_backend = detect_trash_backend();
|
||||
let mut tree = Self {
|
||||
|
||||
@@ -975,9 +975,11 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest(
|
||||
});
|
||||
let before = read(&view, cx, |app| app.tree().map(|tree| tree.files));
|
||||
|
||||
// The trail runs from "/", and the scanned root sits under its parents.
|
||||
// The trail runs from the top of the filesystem — "/", or a drive such
|
||||
// as "C:\" — and the scanned root sits under its parents.
|
||||
let trail = read(&view, cx, Disktree::breadcrumbs);
|
||||
assert_eq!(trail[0].0, "/");
|
||||
let top = temp.path().ancestors().last().expect("a top");
|
||||
assert_eq!(trail[0].0, top.display().to_string());
|
||||
assert!(
|
||||
trail.contains(&(
|
||||
temp.path()
|
||||
|
||||
@@ -372,11 +372,13 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div {
|
||||
/// Steps a trail shows before it folds its middle into an ellipsis.
|
||||
const TRAIL_STEPS: usize = 7;
|
||||
|
||||
/// The platform's path separator, so the trail reads like the paths shown
|
||||
/// elsewhere: `/` here, `\` on Windows.
|
||||
fn separator_glyph(theme: &Theme) -> Div {
|
||||
div()
|
||||
.text_color(theme.secondary.opacity(0.5))
|
||||
.text_size(text::BODY)
|
||||
.child("/")
|
||||
.child(std::path::MAIN_SEPARATOR_STR)
|
||||
}
|
||||
|
||||
/// A crumb in the tree. Its label goes there (the current one opens the
|
||||
@@ -2934,7 +2936,7 @@ 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); 25] = [
|
||||
let rows: [(&str, &str); 26] = [
|
||||
("space / x", "Mark or unmark the tile you point at"),
|
||||
(MODIFIER_CLICK, "Mark without moving the selection"),
|
||||
("enter", "Open that directory, at any depth"),
|
||||
|
||||
@@ -12,14 +12,23 @@ workspace = true
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] }
|
||||
rayon = { workspace = true }
|
||||
rustix = { version = "1.1", features = ["fs"] }
|
||||
rustc-hash = { workspace = true }
|
||||
|
||||
[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"
|
||||
|
||||
@@ -15,3 +15,5 @@ pub mod size;
|
||||
pub mod space;
|
||||
pub mod tree;
|
||||
pub mod treemap;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
//! 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. 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;
|
||||
@@ -102,7 +102,7 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
|
||||
}
|
||||
let mounts = mount_points();
|
||||
// Once per plan, not per target: the review screen plans every frame.
|
||||
let home = std::env::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);
|
||||
@@ -126,7 +126,7 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
|
||||
for target in accepted {
|
||||
if outer
|
||||
.iter()
|
||||
.any(|candidate| target.path.starts_with(&candidate.path))
|
||||
.any(|candidate| within(&target.path, &candidate.path))
|
||||
{
|
||||
plan.covered.push(target);
|
||||
} else {
|
||||
@@ -149,6 +149,7 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
|
||||
/// 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; 20] = [
|
||||
"/bin",
|
||||
"/boot",
|
||||
@@ -173,15 +174,19 @@ const SYSTEM_TREES: [&str; 20] = [
|
||||
"/Network",
|
||||
];
|
||||
|
||||
/// How the guards compare paths: lexically normalized, and on macOS also in
|
||||
/// the form Finder shows and without case.
|
||||
/// 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"))
|
||||
}
|
||||
|
||||
@@ -198,19 +203,98 @@ fn guard_key_for(path: &Path, macos: bool) -> PathBuf {
|
||||
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))]
|
||||
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
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
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";
|
||||
|
||||
/// 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> {
|
||||
@@ -220,7 +304,7 @@ fn system_tree(key: &Path, home: Option<&Path>) -> Option<&'static str> {
|
||||
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
|
||||
@@ -229,15 +313,15 @@ 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)>,
|
||||
}
|
||||
|
||||
@@ -245,7 +329,7 @@ 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,20 +341,18 @@ fn refuse(
|
||||
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 key == root_key {
|
||||
return Some("the scanned root cannot be removed".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());
|
||||
}
|
||||
@@ -280,13 +362,12 @@ fn refuse(
|
||||
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 !key.starts_with(&root_key) {
|
||||
return Some("outside the scanned root".into());
|
||||
}
|
||||
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) {
|
||||
@@ -311,18 +392,29 @@ fn refuse(
|
||||
}
|
||||
|
||||
/// `(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)> {
|
||||
/// `(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
|
||||
}
|
||||
|
||||
@@ -442,7 +534,13 @@ pub fn is_mount_point(path: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
/// Whether `path` is a folder another volume is mounted on.
|
||||
#[cfg(windows)]
|
||||
pub fn is_mount_point(path: &Path) -> bool {
|
||||
crate::windows::is_mount_point(path)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
pub fn is_mount_point(_path: &Path) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -489,6 +587,8 @@ pub enum TrashBackend {
|
||||
Gio,
|
||||
/// The XDG trash directory, implemented here.
|
||||
XdgHome,
|
||||
/// The Windows Recycle Bin, through the shell's own file operation.
|
||||
RecycleBin,
|
||||
/// No way to move files to a trash on this machine.
|
||||
#[default]
|
||||
Unavailable,
|
||||
@@ -497,7 +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::MacOs
|
||||
| Self::TrashPut
|
||||
| Self::Gio
|
||||
| Self::XdgHome
|
||||
| Self::RecycleBin => true,
|
||||
Self::Unavailable => false,
|
||||
}
|
||||
}
|
||||
@@ -508,6 +612,7 @@ impl TrashBackend {
|
||||
Self::TrashPut => "trash-put",
|
||||
Self::Gio => "gio trash",
|
||||
Self::XdgHome => "XDG trash",
|
||||
Self::RecycleBin => "the Recycle Bin",
|
||||
Self::Unavailable => "no trash tool found",
|
||||
}
|
||||
}
|
||||
@@ -522,6 +627,7 @@ impl TrashBackend {
|
||||
Self::XdgHome => {
|
||||
"moves into ~/.local/share/Trash on the same volume"
|
||||
}
|
||||
Self::RecycleBin => "the same Recycle Bin as File Explorer",
|
||||
Self::Unavailable => {
|
||||
"install trash-cli or keep deleting permanently"
|
||||
}
|
||||
@@ -529,6 +635,13 @@ impl TrashBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect the best available trash backend for this machine. Windows
|
||||
/// always has its Recycle Bin.
|
||||
#[cfg(windows)]
|
||||
pub const fn detect_trash_backend() -> TrashBackend {
|
||||
TrashBackend::RecycleBin
|
||||
}
|
||||
|
||||
/// Detect the best available trash backend for this machine.
|
||||
///
|
||||
/// On macOS the system Trash is always there, and the Linux tools are not
|
||||
@@ -540,7 +653,7 @@ pub const fn detect_trash_backend() -> TrashBackend {
|
||||
}
|
||||
|
||||
/// 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 +666,7 @@ pub fn detect_trash_backend() -> TrashBackend {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
fn which(program: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
@@ -695,6 +808,7 @@ fn run(
|
||||
/// 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)?;
|
||||
@@ -712,6 +826,11 @@ pub fn remove_permanently(path: &Path) -> io::Result<()> {
|
||||
let meta = fs::symlink_metadata(path)?;
|
||||
if meta.is_dir() {
|
||||
fs::remove_dir_all(path)
|
||||
} else if is_dir_link(&meta) {
|
||||
// Windows removes a link to a directory, a junction or a directory
|
||||
// symlink, as a directory: `RemoveDirectoryW` takes the link and
|
||||
// leaves its target alone.
|
||||
fs::remove_dir(path)
|
||||
} else {
|
||||
fs::remove_file(path)
|
||||
}
|
||||
@@ -831,6 +950,17 @@ fn remove_contents(
|
||||
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(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 {
|
||||
@@ -838,6 +968,7 @@ pub fn move_to_trash(path: &Path, backend: TrashBackend) -> io::Result<()> {
|
||||
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",
|
||||
)),
|
||||
@@ -877,6 +1008,19 @@ 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
|
||||
@@ -962,6 +1106,7 @@ pub fn trash_into(_path: &Path, _trash: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// `name`, or `name.1`, `name.2`, … until the name is free in `dir`.
|
||||
#[cfg(unix)]
|
||||
fn unique_name(dir: &Path, name: &str) -> (PathBuf, String) {
|
||||
let first = dir.join(name);
|
||||
if !first.exists() {
|
||||
@@ -994,6 +1139,7 @@ pub fn percent_encode(input: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn deletion_date() -> String {
|
||||
// The specification wants ISO 8601 in local time; chrono is already in the
|
||||
// dependency graph, so use it rather than approximating the offset.
|
||||
@@ -1015,6 +1161,7 @@ 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)))
|
||||
}
|
||||
@@ -1051,7 +1198,7 @@ mod tests {
|
||||
fn the_root_and_home_are_refused() {
|
||||
let temp = tree();
|
||||
let root = temp.path();
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let home = std::env::home_dir();
|
||||
let mut targets = vec![target(Path::new("/"), 0), target(root, 0)];
|
||||
if let Some(home) = &home {
|
||||
targets.push(target(home, 0));
|
||||
@@ -1068,6 +1215,25 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Removing a directory takes what is inside it, so the directories
|
||||
/// above home are refused too: in a whole-disk scan, `C:\Users` is an
|
||||
/// ordinary directory, and so is `/home` without a separate volume.
|
||||
#[test]
|
||||
fn 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), &[]),
|
||||
None,
|
||||
"a sibling of home is not"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_outside_the_root_are_refused() {
|
||||
let temp = tree();
|
||||
@@ -1315,8 +1481,7 @@ mod tests {
|
||||
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());
|
||||
}
|
||||
@@ -1330,19 +1495,54 @@ mod tests {
|
||||
assert!(temp.path().join("a/c.bin").exists());
|
||||
}
|
||||
|
||||
/// A link to a directory: a symbolic link on Unix, a junction on
|
||||
/// Windows, which needs no privilege to make.
|
||||
fn link_dir(target: &Path, link: &Path) {
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(target, link).expect("symlink");
|
||||
#[cfg(windows)]
|
||||
assert!(crate::windows::make_junction(link, target), "junction");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permanent_removal_unlinks_a_symlink_instead_of_following_it() {
|
||||
let temp = tree();
|
||||
let keep = TempDir::new().expect("tempdir");
|
||||
fs::write(keep.path().join("precious.bin"), b"data").expect("write");
|
||||
let link = temp.path().join("link");
|
||||
std::os::unix::fs::symlink(keep.path(), &link).expect("symlink");
|
||||
link_dir(keep.path(), &link);
|
||||
|
||||
remove_permanently(&link).expect("remove link");
|
||||
assert!(!link.exists());
|
||||
assert!(fs::symlink_metadata(&link).is_err(), "the link is gone");
|
||||
assert!(keep.path().join("precious.bin").exists());
|
||||
}
|
||||
|
||||
/// Git keeps its objects read-only, which on Windows stops a plain
|
||||
/// delete; clearing an old checkout must still work.
|
||||
#[test]
|
||||
fn read_only_files_are_removed_too() {
|
||||
let temp = tree();
|
||||
let objects = temp.path().join("a/b/objects");
|
||||
fs::create_dir_all(&objects).expect("mkdir");
|
||||
let object = objects.join("pack.idx");
|
||||
fs::write(&object, b"x").expect("write");
|
||||
let mut permissions =
|
||||
fs::metadata(&object).expect("stat").permissions();
|
||||
permissions.set_readonly(true);
|
||||
fs::set_permissions(&object, permissions).expect("read-only");
|
||||
let lone = temp.path().join("a/lone.idx");
|
||||
fs::write(&lone, b"x").expect("write");
|
||||
let mut permissions = fs::metadata(&lone).expect("stat").permissions();
|
||||
permissions.set_readonly(true);
|
||||
fs::set_permissions(&lone, permissions).expect("read-only");
|
||||
|
||||
remove_permanently(&lone).expect("a read-only file");
|
||||
remove_permanently(&temp.path().join("a/b")).expect("a directory");
|
||||
assert!(!lone.exists());
|
||||
assert!(!temp.path().join("a/b").exists());
|
||||
assert!(temp.path().join("a/c.bin").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_target_reports_not_found() {
|
||||
let temp = tree();
|
||||
@@ -1359,6 +1559,7 @@ mod tests {
|
||||
assert_eq!(percent_encode("/a\nb"), "/a%0Ab");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn trash_names_avoid_collisions() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
@@ -1371,6 +1572,7 @@ mod tests {
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_xdg_trash_moves_a_file_and_records_where_it_came_from() {
|
||||
// A private trash directory keeps the test out of the real trash can.
|
||||
@@ -1393,6 +1595,7 @@ mod tests {
|
||||
assert!(info.contains("DeletionDate="));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_trash_info_path_is_restorable() {
|
||||
let trash = TempDir::new().expect("tempdir");
|
||||
@@ -1461,6 +1664,7 @@ mod tests {
|
||||
assert!(root.join("a/one.bin").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_trash_tool_is_called_with_the_path_after_a_separator() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
@@ -1489,6 +1693,7 @@ mod tests {
|
||||
assert!(doomed.exists(), "the real tool would have moved it");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_failing_trash_tool_reports_its_stderr() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
@@ -1503,8 +1708,9 @@ mod tests {
|
||||
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,6 +1719,52 @@ mod tests {
|
||||
assert!(backend.is_available());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_trashes_into_the_recycle_bin() {
|
||||
let backend = detect_trash_backend();
|
||||
assert_eq!(backend, TrashBackend::RecycleBin);
|
||||
assert!(backend.is_available());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_system_trees_are_refused_in_a_whole_disk_scan() {
|
||||
let drive = system_drive();
|
||||
let home = drive.join(r"Users\tobi");
|
||||
let system = |relative: &str| {
|
||||
system_tree(
|
||||
&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::of(&home)),
|
||||
&[],
|
||||
);
|
||||
assert!(
|
||||
reason.is_some_and(|reason| reason
|
||||
.to_lowercase()
|
||||
.contains(&windows.to_lowercase())),
|
||||
"refused as part of {windows}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_always_uses_the_system_trash() {
|
||||
@@ -1555,6 +1807,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(windows))]
|
||||
fn system_trees_are_refused_in_a_whole_disk_scan() {
|
||||
let home = Path::new("/home/tobi");
|
||||
assert_eq!(
|
||||
@@ -1584,6 +1837,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(windows))]
|
||||
fn macos_system_trees_are_refused_but_apps_are_not() {
|
||||
let home = Path::new("/Users/tobi");
|
||||
for (path, tree) in [
|
||||
|
||||
+315
-105
@@ -15,7 +15,9 @@
|
||||
//! poll without locking, and cooperative cancellation so a re-scan can abandon
|
||||
//! a walk of a large home directory instead of queueing behind it.
|
||||
|
||||
use std::fs::{self, DirEntry, Metadata};
|
||||
#[cfg(not(windows))]
|
||||
use std::fs::DirEntry;
|
||||
use std::fs::{self, Metadata};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
@@ -280,89 +282,28 @@ impl WalkContext {
|
||||
}
|
||||
|
||||
/// Decide what to do with an entry, and account for the work it implies.
|
||||
fn classify(&self, entry: &DirEntry) -> Classified {
|
||||
let path = entry.path();
|
||||
let file_type = match entry.file_type() {
|
||||
Ok(file_type) => file_type,
|
||||
fn classify(&self, entry: &impl Listed) -> Classified {
|
||||
let path = entry.entry_path();
|
||||
let listing = match entry.listing() {
|
||||
Ok(listing) => listing,
|
||||
Err(error) => {
|
||||
self.progress.record_error(&path, &error);
|
||||
return Classified::Skipped;
|
||||
}
|
||||
};
|
||||
// Non-UTF-8 names are lossy for display. The scan still measures them
|
||||
// correctly; only the reported name is approximate.
|
||||
let name: Box<str> =
|
||||
entry.file_name().to_string_lossy().into_owned().into();
|
||||
let name = entry.display_name();
|
||||
|
||||
if !self.options.include_hidden && name.starts_with('.') {
|
||||
return Classified::Skipped;
|
||||
}
|
||||
|
||||
if file_type.is_symlink() {
|
||||
return self.classify_symlink(&path, name);
|
||||
}
|
||||
|
||||
if file_type.is_dir() {
|
||||
if self
|
||||
.never_scanned
|
||||
.get()
|
||||
.is_some_and(|never| never.contains(&path))
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
// `lstat` at most once per directory: macOS reads the dataless
|
||||
// flag from it, and the device check below needs it wherever the
|
||||
// mount table cannot be read, which on macOS is everywhere.
|
||||
let meta_cell = std::cell::OnceCell::new();
|
||||
let meta = || meta_cell.get_or_init(|| entry.metadata());
|
||||
if cfg!(target_os = "macos")
|
||||
&& meta().as_ref().is_ok_and(is_dataless)
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
// Memoized: the subtree a narrower scan already measured is
|
||||
// taken whole, before any volume rule, since it was measured
|
||||
// under the same rules.
|
||||
if let Some(known) = &self.known
|
||||
&& known.path == path
|
||||
{
|
||||
let tree = (*known.tree).clone();
|
||||
self.progress.files.fetch_add(tree.files, Ordering::Relaxed);
|
||||
self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed);
|
||||
self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed);
|
||||
let mut tree = tree;
|
||||
tree.name = name;
|
||||
return Classified::Entry(tree);
|
||||
}
|
||||
if self.options.one_filesystem
|
||||
&& let Some(foreign) = self.foreign_mounts.get()
|
||||
{
|
||||
// Checked by path before anything reads the directory, so an
|
||||
// automount point is never triggered.
|
||||
if foreign.contains(&path) {
|
||||
return Classified::Skipped;
|
||||
}
|
||||
} else if self.options.one_filesystem {
|
||||
let device = 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)
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
}
|
||||
self.progress.count_dir();
|
||||
return Classified::Subdirectory(path);
|
||||
}
|
||||
|
||||
match entry.metadata() {
|
||||
Ok(meta) => self.leaf(name, kind_of(&meta, file_type), &meta),
|
||||
let kind = match listing {
|
||||
Listing::Symlink => return self.classify_symlink(&path, name),
|
||||
Listing::Directory => return self.classify_dir(entry, path, name),
|
||||
Listing::Leaf(kind) => kind,
|
||||
};
|
||||
match entry.facts(self.options.apparent_size) {
|
||||
Ok(facts) => self.leaf(name, kind, &facts),
|
||||
Err(error) => {
|
||||
self.progress.record_error(&path, &error);
|
||||
Classified::Skipped
|
||||
@@ -370,20 +311,84 @@ impl WalkContext {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
} else if self.options.one_filesystem {
|
||||
match (directory(), self.root_device(&path)) {
|
||||
(Ok(directory), Some(root_device))
|
||||
if directory.device != root_device =>
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
(Err(error), _) => {
|
||||
self.progress.record_error(&path, error);
|
||||
return Classified::Skipped;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.progress.count_dir();
|
||||
Classified::Subdirectory(path)
|
||||
}
|
||||
|
||||
fn classify_symlink(&self, path: &Path, name: Box<str>) -> Classified {
|
||||
if !self.options.follow_links {
|
||||
// Not followed: the link occupies only its target string, which
|
||||
// `du` reports as a handful of bytes or nothing at all.
|
||||
return match fs::symlink_metadata(path) {
|
||||
Ok(meta) => {
|
||||
let size = measure(&meta, self.options.apparent_size);
|
||||
self.progress.count_file(size);
|
||||
let facts = Facts::of(&meta, self.options.apparent_size);
|
||||
self.progress.count_file(facts.size);
|
||||
Classified::Entry(leaf_node(
|
||||
name,
|
||||
NodeKind::Symlink,
|
||||
size,
|
||||
&meta,
|
||||
shares_inode(&meta),
|
||||
&facts,
|
||||
facts.shared,
|
||||
))
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -410,7 +415,7 @@ impl WalkContext {
|
||||
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;
|
||||
@@ -419,24 +424,179 @@ impl WalkContext {
|
||||
return Classified::Subdirectory(path.to_path_buf());
|
||||
}
|
||||
|
||||
self.leaf(name, kind_of(&meta, meta.file_type()), &meta)
|
||||
let mut facts = Facts::of(&meta, self.options.apparent_size);
|
||||
// What the link leads to, so a file that is also reached directly is
|
||||
// charged once.
|
||||
facts.identity = identity_of(path, &meta);
|
||||
self.leaf(name, kind_of(&meta, meta.file_type()), &facts)
|
||||
}
|
||||
|
||||
fn leaf(
|
||||
&self,
|
||||
name: Box<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);
|
||||
// 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>;
|
||||
/// 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 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,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -520,7 +680,7 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
|
||||
}
|
||||
}
|
||||
if context.options.follow_links
|
||||
&& let Some(key) = file_identity(&root_meta)
|
||||
&& let Some(key) = identity_of(root, &root_meta)
|
||||
{
|
||||
lock(&context.visited_dirs).insert(key);
|
||||
}
|
||||
@@ -542,7 +702,7 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
|
||||
let mut subdirs: Vec<Arc<PendingDir>> = Vec::new();
|
||||
let mut leaves: Vec<Node> = Vec::new();
|
||||
|
||||
match fs::read_dir(&dir.path) {
|
||||
match list(&dir.path) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
if context.cancelled() {
|
||||
@@ -641,21 +801,20 @@ fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A leaf. Its `(device, inode)` is kept only when `track` says the walk
|
||||
/// could meet the same file again: a hardlink de-duplication set of every
|
||||
/// file on a disk is millions of entries, nearly all for files with one name.
|
||||
/// 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);
|
||||
if track {
|
||||
node.inode = file_identity(meta);
|
||||
node.inode = facts.identity;
|
||||
}
|
||||
node.modified = modified_seconds(meta);
|
||||
node.modified = facts.modified;
|
||||
node
|
||||
}
|
||||
|
||||
@@ -694,7 +853,7 @@ fn allocated_bytes(meta: &Metadata) -> Option<u64> {
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn allocated_bytes(_meta: &Metadata) -> Option<u64> {
|
||||
const fn allocated_bytes(_meta: &Metadata) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -736,13 +895,15 @@ fn device_of(meta: &Metadata) -> u64 {
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn device_of(_meta: &Metadata) -> u64 {
|
||||
const fn device_of(_meta: &Metadata) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// `(device, inode)`, or `None` where the platform does not expose them.
|
||||
/// Hardlink de-duplication and symlink loop detection both depend on this, so
|
||||
/// they are simply unavailable rather than silently wrong elsewhere.
|
||||
/// they are simply unavailable rather than silently wrong elsewhere. Windows
|
||||
/// has no file id in `Metadata` on stable Rust; its listing carries one
|
||||
/// instead (see [`crate::windows`]).
|
||||
#[allow(
|
||||
clippy::unnecessary_wraps,
|
||||
reason = "the Option is the non-Unix answer, so both arms must agree"
|
||||
@@ -754,10 +915,23 @@ fn file_identity(meta: &Metadata) -> Option<(u64, u64)> {
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> {
|
||||
const fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The identity of what `path` leads to, `meta` being its followed
|
||||
/// metadata: how a walk that follows links recognizes a directory it has
|
||||
/// entered before, and a file it has already charged.
|
||||
#[cfg(not(windows))]
|
||||
fn identity_of(_path: &Path, meta: &Metadata) -> Option<(u64, u64)> {
|
||||
file_identity(meta)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn identity_of(path: &Path, _meta: &Metadata) -> Option<(u64, u64)> {
|
||||
crate::windows::identity(path)
|
||||
}
|
||||
|
||||
fn kind_of(meta: &Metadata, file_type: fs::FileType) -> NodeKind {
|
||||
if meta.is_dir() || file_type.is_dir() {
|
||||
NodeKind::Directory
|
||||
@@ -909,6 +1083,20 @@ mod tests {
|
||||
assert_eq!(without.bytes, 100);
|
||||
}
|
||||
|
||||
/// A link to a directory: a symbolic link on Unix, a junction on
|
||||
/// Windows, which needs no privilege to make. `false` if it could not be
|
||||
/// made.
|
||||
fn link_dir(target: &Path, link: &Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, link).is_ok()
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
crate::windows::make_junction(link, target)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symlinks_are_not_followed_by_default() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
@@ -916,8 +1104,7 @@ mod tests {
|
||||
write(outside.path(), "elsewhere.bin", 5000);
|
||||
let root = temp.path();
|
||||
write(root, "real.bin", 100);
|
||||
std::os::unix::fs::symlink(outside.path(), root.join("link"))
|
||||
.expect("symlink");
|
||||
assert!(link_dir(outside.path(), &root.join("link")), "a link");
|
||||
|
||||
let tree = scan_dir(root, &options());
|
||||
// Only the real file's bytes; the link itself holds just its target
|
||||
@@ -933,8 +1120,7 @@ mod tests {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
let root = temp.path();
|
||||
write(root, "sub/leaf.bin", 42);
|
||||
std::os::unix::fs::symlink(root, root.join("sub/loop"))
|
||||
.expect("symlink");
|
||||
assert!(link_dir(root, &root.join("sub/loop")), "a link");
|
||||
|
||||
let tree = scan_dir(
|
||||
root,
|
||||
@@ -946,6 +1132,29 @@ mod tests {
|
||||
assert_eq!(tree.bytes, 42);
|
||||
}
|
||||
|
||||
/// Disk usage is what the volume allocated, not the length: whole
|
||||
/// blocks, so it covers the data and ends on a block boundary.
|
||||
#[test]
|
||||
fn disk_usage_is_whole_allocation_units() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
// Noise, so a compressing filesystem cannot store it in less.
|
||||
let mut state = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let noise: Vec<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 tree = scan_dir(temp.path(), &ScanOptions::default());
|
||||
assert!(tree.bytes >= 100_000, "{}", tree.bytes);
|
||||
assert_eq!(tree.bytes % 512, 0, "{}", tree.bytes);
|
||||
let apparent = scan_dir(temp.path(), &options());
|
||||
assert_eq!(apparent.bytes, 100_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_depth_stops_descending_but_keeps_direct_files() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
@@ -998,6 +1207,7 @@ mod tests {
|
||||
assert_eq!(by_files.children[0].files, 5);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_unreadable_directory_is_recorded_not_fatal() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
@@ -1112,7 +1322,7 @@ mod tests {
|
||||
#[test]
|
||||
#[ignore = "walks the whole disk"]
|
||||
fn whole_disk_smoke() {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from).expect("HOME");
|
||||
let home = std::env::home_dir().expect("a home directory");
|
||||
let root = crate::space::volume_root_for(&home).expect("a volume root");
|
||||
let started = std::time::Instant::now();
|
||||
let tree = scan(&root, ScanOptions::default()).expect("scan");
|
||||
|
||||
@@ -49,6 +49,13 @@ impl SpaceInfo {
|
||||
}
|
||||
|
||||
/// Read the space on the volume containing `path`.
|
||||
#[cfg(windows)]
|
||||
pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
|
||||
crate::windows::space_info(path)
|
||||
}
|
||||
|
||||
/// Read the space on the volume containing `path`.
|
||||
#[cfg(not(windows))]
|
||||
pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
|
||||
let stat = rustix::fs::statvfs(path)?;
|
||||
// `f_frsize` is the fragment size the block counts are expressed in;
|
||||
@@ -66,10 +73,17 @@ pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The volume a path is on, as Windows names it: `C:\`, a share, or the
|
||||
/// folder a volume is mounted on.
|
||||
#[cfg(windows)]
|
||||
pub fn device_for(path: &Path) -> Option<String> {
|
||||
crate::windows::volume_root(path).map(|root| root.display().to_string())
|
||||
}
|
||||
|
||||
/// The device a path's filesystem is mounted from, such as
|
||||
/// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in
|
||||
/// `/proc/self/mounts`. `None` where that table cannot be read.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[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,15 +201,22 @@ pub fn volume_root(mounts: &[Mount], path: &Path) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// [`volume_root`] for this machine.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[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());
|
||||
volume_root(&parse_mounts(&table), &path)
|
||||
}
|
||||
|
||||
/// The top of the volume `path` lives on: its drive, such as `C:\`.
|
||||
#[cfg(windows)]
|
||||
pub fn volume_root_for(path: &Path) -> Option<PathBuf> {
|
||||
crate::windows::volume_root(path)
|
||||
}
|
||||
|
||||
/// [`foreign_mounts`] for this machine; `None` when the mount table cannot
|
||||
/// be read, so the caller can fall back to comparing devices.
|
||||
#[cfg(not(windows))]
|
||||
pub fn foreign_mounts_for(root: &Path) -> Option<Vec<PathBuf>> {
|
||||
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
|
||||
Some(foreign_mounts(&parse_mounts(&table), root))
|
||||
@@ -293,6 +314,21 @@ fn c_chars(field: &[std::ffi::c_char]) -> String {
|
||||
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::*;
|
||||
|
||||
@@ -0,0 +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_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 `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)
|
||||
}
|
||||
|
||||
/// `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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user