mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
Merge origin/main and preserve scan admission integration
This commit is contained in:
@@ -99,6 +99,24 @@ jobs:
|
||||
- name: Test
|
||||
run: cargo xtask test
|
||||
|
||||
- name: Check embedded executable icon
|
||||
shell: pwsh
|
||||
run: |
|
||||
cargo build --release --locked -p disktree-app
|
||||
Add-Type @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class ExecutableIcons {
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern uint ExtractIconEx(
|
||||
string file, int index, IntPtr[] large, IntPtr[] small, uint count);
|
||||
}
|
||||
'@
|
||||
$exe = (Resolve-Path target/release/disktree.exe).Path
|
||||
if ([ExecutableIcons]::ExtractIconEx($exe, -1, $null, $null, 0) -lt 1) {
|
||||
throw "disktree.exe has no embedded icon"
|
||||
}
|
||||
|
||||
# The other half of each release: the same tests on the architectures
|
||||
# the release builds for but the jobs above do not run on.
|
||||
other-architectures:
|
||||
|
||||
@@ -63,17 +63,25 @@ and `cargo build --release` directly; CI runs the gate on both systems.
|
||||
|
||||
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. On Windows it
|
||||
is the allocation the directory listing reports; see `windows.rs`.
|
||||
is the allocation the directory listing reports; see `windows.rs`. An
|
||||
elevated scan of a whole NTFS drive reads it from the master file table
|
||||
instead, keeping the walk's rules for hidden entries, links, cloud
|
||||
folders and depth; see `mft.rs`. That path counts every stream's
|
||||
allocation, alternate data streams included since they go when the file
|
||||
goes, so for a file with alternate streams it can exceed the walk's
|
||||
number.
|
||||
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
|
||||
be overwritten.
|
||||
computes the totals from the children. Hardlink de-duplication zeroes a
|
||||
duplicate leaf's weight while that pass runs; anything that patches
|
||||
`bytes` directly will be overwritten.
|
||||
3. **A directory is only built when its own scan *and* every subdirectory task
|
||||
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, any directory holding it, and symlink targets are
|
||||
refused.
|
||||
refused. On Windows so is every directory directly in the profiles folder
|
||||
Windows reports (`FOLDERID_UserProfiles`, usually `C:\Users`); what is
|
||||
inside a profile stays removable.
|
||||
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
|
||||
@@ -99,6 +107,7 @@ and `cargo build --release` directly; CI runs the gate on both systems.
|
||||
| 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` |
|
||||
| reading a whole NTFS drive from its file table | `crates/disktree-core/src/mft.rs` |
|
||||
| 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` |
|
||||
|
||||
@@ -40,9 +40,21 @@ make install
|
||||
`sudo make install PREFIX=/usr/local` installs system-wide; `make uninstall`
|
||||
removes exactly what was installed.
|
||||
|
||||
On Arch, including Omarchy, disktree is in the AUR:
|
||||
[`disktree`](https://aur.archlinux.org/packages/disktree) builds each release
|
||||
from source, and
|
||||
[`disktree-bin`](https://aur.archlinux.org/packages/disktree-bin) installs
|
||||
the release binary:
|
||||
|
||||
```sh
|
||||
yay -S disktree-bin
|
||||
```
|
||||
|
||||
You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI
|
||||
can drive (Vulkan). Distributions often package an older Rust;
|
||||
[rustup](https://rustup.rs) installs a current one.
|
||||
[rustup](https://rustup.rs) installs a current one. The repo pins 1.97 in
|
||||
`rust-toolchain.toml`, so with rustup the right toolchain is fetched on the
|
||||
first build even if `rustup default` points at something older.
|
||||
|
||||
### macOS
|
||||
|
||||
@@ -211,6 +223,8 @@ and shows how much free space was actually gained.
|
||||
| `d` | disk usage or apparent size |
|
||||
| `i` | include or skip hidden entries |
|
||||
| `r` | scan again |
|
||||
| `esc` while scanning | stop the scan |
|
||||
| `v` | scan another mounted volume |
|
||||
| `ctrl o` (`⌘O` on macOS) | choose another directory to scan |
|
||||
| `g` | the whole disk |
|
||||
| `p` | show or hide the selection line |
|
||||
@@ -245,6 +259,14 @@ scope per root, a completion counter per directory so no directory is built
|
||||
before its last subdirectory lands, and one bottom-up pass that aggregates sizes
|
||||
and removes duplicate hardlinks.
|
||||
|
||||
## Switching volumes
|
||||
|
||||
Press `v` (or click **Volumes** beside the disk name in the side panel) to
|
||||
bring up the volume picker. It lists every candidate volume mounted on the
|
||||
system together with its free space, ordered fullest first, filtering out
|
||||
pseudo-filesystems and duplicate btrfs/APFS mount points. Selecting any
|
||||
entry resets the scan root directly to that volume.
|
||||
|
||||
## The whole disk
|
||||
|
||||
Click `/` (or any directory above the scanned root) in the trail, press
|
||||
@@ -285,14 +307,31 @@ The same program, with Windows' answers to the questions above:
|
||||
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.
|
||||
- **Run as administrator** and the whole disk is read from NTFS's master
|
||||
file table instead of walked, as WizTree does: one pass over the table in
|
||||
large reads. On a 4-million-file `C:\` that took about 3.4 s against 11.2
|
||||
s for WizTree and about 20 s for the walk. It also sees what the walk is
|
||||
refused, such as System Volume Information. It is used only for a whole
|
||||
NTFS drive, since a folder would still cost the whole table, and not with
|
||||
`-l`, whose links the table does not follow. disktree flushes the volume
|
||||
after its own removals so the rescan shows them; changes other programs
|
||||
made seconds before may not show yet.
|
||||
Started without admin rights, disktree walks as before. On a whole NTFS
|
||||
drive without `-l`, or once Windows refuses the walk a folder, the side
|
||||
panel offers **Restart as Administrator**, which reopens the same folder
|
||||
and options through the UAC prompt; during a widening scan, the wider
|
||||
folder being scanned.
|
||||
- **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 the page and hibernation files, which
|
||||
Settings turns off), and any folder holding your profile, such as
|
||||
`C:\Users`. Names compare without regard to case, as Windows compares
|
||||
them.
|
||||
Settings turns off), any folder holding your profile, such as
|
||||
`C:\Users`, and every profile in the folder Windows keeps them in
|
||||
(`C:\Users\*`, `Public` and `Default` included), since an elevated
|
||||
disktree may run as another account and can reach them all. What is
|
||||
inside a profile can still be removed, as under your own. Names compare
|
||||
without regard to case, as Windows compares them.
|
||||
- **Hidden** means a name starting with a dot, or the hidden attribute, so
|
||||
`-H` drops `AppData` as Explorer hides it.
|
||||
- **The theme** follows Windows' light or dark setting, since there is no
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,65 @@
|
||||
#[cfg(windows)]
|
||||
fn main() {
|
||||
use std::{env, fs, path::PathBuf, process::Command};
|
||||
|
||||
let icon = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap())
|
||||
.join("../../assets/disktree.ico")
|
||||
.canonicalize()
|
||||
.expect("Windows icon asset is missing");
|
||||
let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||
let rc = out.join("disktree.rc");
|
||||
let res = out.join("disktree.res");
|
||||
|
||||
// rc.exe treats backslashes inside quoted paths as separators, not escapes.
|
||||
let icon_path = icon.to_string_lossy().replace('\\', "/");
|
||||
fs::write(&rc, format!("1 ICON \"{icon_path}\"\n"))
|
||||
.expect("could not write Windows icon resource script");
|
||||
|
||||
// Cargo can run outside a Visual Studio prompt, where the SDK bin is not
|
||||
// on PATH even though the MSVC linker and Windows SDK are installed.
|
||||
let rc_exe = env::var_os("DISKTREE_RC").map_or_else(
|
||||
|| {
|
||||
let sdk_bin = env::var_os("WindowsSdkDir")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| {
|
||||
env::var_os("ProgramFiles(x86)")
|
||||
.map(|root| PathBuf::from(root).join("Windows Kits/10"))
|
||||
})
|
||||
.expect("Windows SDK is required to embed the icon")
|
||||
.join("bin");
|
||||
let host = match env::consts::ARCH {
|
||||
"x86_64" => "x64",
|
||||
"aarch64" => "arm64",
|
||||
"x86" => "x86",
|
||||
other => panic!("unsupported Windows build host: {other}"),
|
||||
};
|
||||
let mut versions: Vec<_> = fs::read_dir(&sdk_bin)
|
||||
.expect("Windows SDK bin directory is missing")
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path().join(host).join("rc.exe"))
|
||||
.filter(|path| path.is_file())
|
||||
.collect();
|
||||
versions.sort();
|
||||
versions
|
||||
.pop()
|
||||
.expect("rc.exe is missing from the Windows SDK")
|
||||
},
|
||||
PathBuf::from,
|
||||
);
|
||||
let status = Command::new(rc_exe)
|
||||
.arg("/nologo")
|
||||
.arg(format!("/fo{}", res.display()))
|
||||
.arg(&rc)
|
||||
.status()
|
||||
.expect("could not start rc.exe to embed the Windows icon");
|
||||
assert!(
|
||||
status.success(),
|
||||
"rc.exe failed to compile the Windows icon"
|
||||
);
|
||||
|
||||
println!("cargo:rerun-if-changed={}", icon.display());
|
||||
println!("cargo:rustc-link-arg-bin=disktree={}", res.display());
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn main() {}
|
||||
@@ -25,6 +25,12 @@ mod views;
|
||||
mod widgets;
|
||||
|
||||
use std::path::PathBuf;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::{
|
||||
io::IsTerminal as _,
|
||||
os::unix::process::CommandExt as _,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use disktree_core::scan::ScanOptions;
|
||||
@@ -79,7 +85,31 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
let args = parse_args()?;
|
||||
let args = parse_args(std::env::args_os().skip(1))?;
|
||||
|
||||
// When the app executable is reached through the command-line symlink,
|
||||
// cmux sends SIGTERM to its foreground process group as AppKit takes
|
||||
// focus. Spawn once into a separate group before AppKit starts. Restrict
|
||||
// this to interactive cmux sessions so scripts retain normal foreground
|
||||
// lifetime; the marker prevents the child from spawning recursively.
|
||||
#[cfg(target_os = "macos")]
|
||||
if std::io::stdin().is_terminal()
|
||||
&& std::env::var_os("CMUX_SURFACE_ID").is_some()
|
||||
&& std::env::var_os("DISKTREE_CMUX_DETACHED").is_none()
|
||||
{
|
||||
Command::new(std::env::current_exe().context("find disktree")?)
|
||||
.args(std::env::args_os().skip(1))
|
||||
.env("DISKTREE_CMUX_DETACHED", "1")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
// Zero makes the child the leader of a new process group.
|
||||
.process_group(0)
|
||||
.spawn()
|
||||
.context("start disktree")?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let root = args.root.clone();
|
||||
let depth = args.depth;
|
||||
let title_root = root.clone();
|
||||
@@ -156,11 +186,10 @@ fn run() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Args> {
|
||||
parse_args_from(std::env::args().skip(1))
|
||||
}
|
||||
|
||||
fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
/// Read the command line, program name already skipped.
|
||||
fn parse_args(
|
||||
mut args: impl Iterator<Item = std::ffi::OsString>,
|
||||
) -> Result<Args> {
|
||||
let mut root: Option<PathBuf> = None;
|
||||
let mut options = ScanOptions::default();
|
||||
if cfg!(target_os = "macos") {
|
||||
@@ -169,10 +198,17 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
}
|
||||
let mut depth = 3_u32;
|
||||
let mut disk = false;
|
||||
let mut args = arguments;
|
||||
// `std::env::args` panics on a name that is not Unicode, and a path is
|
||||
// any name: a restart as administrator hands the root back exactly as
|
||||
// it was, so the caller passes `args_os`.
|
||||
let text = |value: Option<std::ffi::OsString>, need: &str| {
|
||||
value
|
||||
.and_then(|value| value.into_string().ok())
|
||||
.with_context(|| need.to_owned())
|
||||
};
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
match arg.to_str().unwrap_or_default() {
|
||||
"-h" | "--help" => {
|
||||
println!("{USAGE}");
|
||||
std::process::exit(0);
|
||||
@@ -186,7 +222,7 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
"-X" | "--cross-filesystems" => options.one_filesystem = false,
|
||||
"-D" | "--disk" => disk = true,
|
||||
"-d" | "--depth" => {
|
||||
let value = args.next().context("--depth needs a number")?;
|
||||
let value = text(args.next(), "--depth needs a number")?;
|
||||
depth = value.parse().context("--depth needs a number")?;
|
||||
anyhow::ensure!(
|
||||
(1..=6).contains(&depth),
|
||||
@@ -194,8 +230,7 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
);
|
||||
}
|
||||
"--scan-threads" => {
|
||||
let value =
|
||||
args.next().context("--scan-threads needs a number")?;
|
||||
let value = text(args.next(), "--scan-threads needs a number")?;
|
||||
options.threads.max_threads = value
|
||||
.parse()
|
||||
.context("--scan-threads needs a positive integer")?;
|
||||
@@ -206,9 +241,10 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
}
|
||||
"--fixed-threads" => options.threads.adaptive = false,
|
||||
"--thread-throughput-percent" => {
|
||||
let value = args
|
||||
.next()
|
||||
.context("--thread-throughput-percent needs a number")?;
|
||||
let value = text(
|
||||
args.next(),
|
||||
"--thread-throughput-percent needs a number",
|
||||
)?;
|
||||
let percent: u8 = value
|
||||
.parse()
|
||||
.context("throughput percent must be 1 to 100")?;
|
||||
@@ -220,9 +256,10 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
f64::from(percent) / 100.0;
|
||||
}
|
||||
"--thread-system-cpu-percent" => {
|
||||
let value = args
|
||||
.next()
|
||||
.context("--thread-system-cpu-percent needs a number")?;
|
||||
let value = text(
|
||||
args.next(),
|
||||
"--thread-system-cpu-percent needs a number",
|
||||
)?;
|
||||
let percent: u8 =
|
||||
value.parse().context("CPU percent must be 0 to 100")?;
|
||||
anyhow::ensure!(percent <= 100, "CPU percent must be 0 to 100");
|
||||
@@ -230,7 +267,7 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
(percent > 0).then(|| f64::from(percent) / 100.0);
|
||||
}
|
||||
"--metric" => {
|
||||
let value = args.next().context("--metric needs a value")?;
|
||||
let value = text(args.next(), "--metric needs a value")?;
|
||||
options.metric = match value.as_str() {
|
||||
"files" => disktree_core::tree::Metric::Files,
|
||||
"bytes" | "size" => disktree_core::tree::Metric::Bytes,
|
||||
@@ -245,9 +282,9 @@ fn parse_args_from(arguments: impl Iterator<Item = String>) -> Result<Args> {
|
||||
other if other.starts_with('-') => {
|
||||
anyhow::bail!("unknown option {other}\n\n{USAGE}");
|
||||
}
|
||||
path => {
|
||||
_ => {
|
||||
anyhow::ensure!(root.is_none(), "only one path can be scanned");
|
||||
root = Some(PathBuf::from(path));
|
||||
root = Some(PathBuf::from(arg));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,17 +355,17 @@ mod console {
|
||||
mod argument_tests {
|
||||
use super::*;
|
||||
|
||||
fn arguments(extra: &[&str]) -> impl Iterator<Item = String> {
|
||||
fn arguments(extra: &[&str]) -> impl Iterator<Item = std::ffi::OsString> {
|
||||
extra
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(std::iter::once("."))
|
||||
.map(str::to_owned)
|
||||
.map(std::ffi::OsString::from)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_budget_and_fixed_override_are_explicit() {
|
||||
let args = parse_args_from(arguments(&[])).expect("defaults");
|
||||
let args = parse_args(arguments(&[])).expect("defaults");
|
||||
assert_eq!(
|
||||
args.options.threads.max_threads,
|
||||
if cfg!(target_os = "macos") {
|
||||
@@ -338,7 +375,7 @@ mod argument_tests {
|
||||
}
|
||||
);
|
||||
assert_eq!(args.options.threads.adaptive, cfg!(target_os = "macos"));
|
||||
let args = parse_args_from(arguments(&[
|
||||
let args = parse_args(arguments(&[
|
||||
"--scan-threads",
|
||||
"4",
|
||||
"--fixed-threads",
|
||||
@@ -357,6 +394,30 @@ mod argument_tests {
|
||||
assert_eq!(args.options.threads.system_cpu_limit, None);
|
||||
}
|
||||
|
||||
// APFS rejects these filename bytes; Linux filesystems permit them.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn worker_options_preserve_a_non_unicode_root() {
|
||||
use std::os::unix::ffi::OsStringExt as _;
|
||||
|
||||
let temp = tempfile::TempDir::new().expect("tempdir");
|
||||
let root = temp
|
||||
.path()
|
||||
.join(std::ffi::OsString::from_vec(vec![b'r', 0xff]));
|
||||
std::fs::create_dir(&root).expect("directory");
|
||||
let args = parse_args(
|
||||
[
|
||||
std::ffi::OsString::from("--scan-threads"),
|
||||
std::ffi::OsString::from("4"),
|
||||
root.clone().into_os_string(),
|
||||
]
|
||||
.into_iter(),
|
||||
)
|
||||
.expect("native path");
|
||||
assert_eq!(args.root, dunce::canonicalize(root).expect("root"));
|
||||
assert_eq!(args.options.threads.max_threads, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_worker_budgets_are_rejected() {
|
||||
for extra in [
|
||||
@@ -366,7 +427,7 @@ mod argument_tests {
|
||||
vec!["--thread-throughput-percent", "101"],
|
||||
vec!["--thread-system-cpu-percent", "101"],
|
||||
] {
|
||||
assert!(parse_args_from(arguments(&extra)).is_err());
|
||||
assert!(parse_args(arguments(&extra)).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use disktree_core::access::file_table_readable;
|
||||
use disktree_core::filter::{Keep, Matches, filter};
|
||||
use disktree_core::insights::{Candidate, worth_a_look};
|
||||
use disktree_core::removal::{
|
||||
@@ -416,9 +417,26 @@ pub struct Disktree {
|
||||
/// Whether macOS lets this process read everything: asked once, since a
|
||||
/// grant only takes effect after a relaunch. `None` off macOS.
|
||||
pub full_disk_access: Option<bool>,
|
||||
/// Whether disktree runs as an administrator, which lets a whole drive
|
||||
/// be read from its file table instead of walked. `None` off Windows.
|
||||
pub administrator: Option<bool>,
|
||||
/// Whether the root is a whole NTFS drive, which an administrator reads
|
||||
/// from its file table. Follows the root; `false` off Windows.
|
||||
pub file_table: bool,
|
||||
/// A restart as administrator was asked for and not yet declined, so a
|
||||
/// second click does not raise a second prompt.
|
||||
pub restarting: bool,
|
||||
/// The top of the disk the scanned root lives on: what "Whole disk"
|
||||
/// scans. Follows the root when a folder is opened.
|
||||
pub disk_root: Option<PathBuf>,
|
||||
/// The volume picker: open, what it listed, and which row the keys are
|
||||
/// on. `None` when closed; empty when no volume besides the current one
|
||||
/// could be read.
|
||||
pub volumes_open: bool,
|
||||
pub volumes_loading: bool,
|
||||
volume_epoch: u64,
|
||||
pub volumes: Vec<disktree_core::space::Volume>,
|
||||
pub volume_highlight: usize,
|
||||
/// The side panel's width, in rem; dragged from its left edge.
|
||||
pub panel_rems: f32,
|
||||
pub scan_started: Option<Instant>,
|
||||
@@ -505,7 +523,15 @@ impl Disktree {
|
||||
git_pending: FxHashSet::default(),
|
||||
device: None,
|
||||
full_disk_access: None,
|
||||
administrator: disktree_core::access::administrator(),
|
||||
file_table: false,
|
||||
restarting: false,
|
||||
disk_root: None,
|
||||
volumes_open: false,
|
||||
volumes_loading: false,
|
||||
volume_epoch: 0,
|
||||
volumes: Vec::new(),
|
||||
volume_highlight: 0,
|
||||
panel_rems: PANEL_REMS,
|
||||
scan_started: None,
|
||||
scan_root: PathBuf::new(),
|
||||
@@ -520,6 +546,7 @@ impl Disktree {
|
||||
// The disk of what is on screen, as `set_root` keeps it: `disktree
|
||||
// /Volumes/Ext` then `g` measures that drive, like opening it with ⌘O.
|
||||
tree.disk_root = volume_root_for(&tree.root_path);
|
||||
tree.file_table = file_table_readable(&tree.root_path);
|
||||
disktree_core::removal::prime_mount_points();
|
||||
tree.start_scan(cx);
|
||||
Self::start_space_ticker(cx);
|
||||
@@ -540,6 +567,11 @@ impl Disktree {
|
||||
cx: &mut Context<'_, Self>,
|
||||
) -> Self {
|
||||
let mut app = Self::new(root_path, options, depth, cx);
|
||||
// `new` started a walk; this tree stands in for its result.
|
||||
if let Some(scan) = app.scan.take() {
|
||||
scan.cancel();
|
||||
}
|
||||
app.scan_epoch += 1;
|
||||
app.marks.refresh(&app.root_path, &tree, app.options.metric);
|
||||
app.tree = Some(Arc::new(tree));
|
||||
app.cache = None;
|
||||
@@ -557,6 +589,7 @@ impl Disktree {
|
||||
// can change: an external drive has its own.
|
||||
self.disk_root =
|
||||
volume_root_for(&root).or_else(|| self.disk_root.take());
|
||||
self.file_table = file_table_readable(&root);
|
||||
self.root_path = root;
|
||||
self.screen = Screen::Explore;
|
||||
self.start_scan(cx);
|
||||
@@ -599,6 +632,98 @@ impl Disktree {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// `V`: list every volume and let the scan move to one. The in-flight walk
|
||||
/// is left alone until a volume is picked; picking calls [`set_root`],
|
||||
/// which cancels it.
|
||||
pub fn open_volumes(&mut self, cx: &mut Context<'_, Self>) {
|
||||
self.volume_epoch += 1;
|
||||
let epoch = self.volume_epoch;
|
||||
let root_path = self.root_path.clone();
|
||||
self.volumes.clear();
|
||||
self.volume_highlight = 0;
|
||||
self.volumes_loading = true;
|
||||
self.volumes_open = true;
|
||||
self.focus_request = Some(FocusTarget::Dialog);
|
||||
// Removable media and network volumes can take seconds to answer.
|
||||
// Keep Escape and the window responsive while probing them.
|
||||
let task = cx.background_executor().spawn(async move {
|
||||
let mut volumes = disktree_core::space::volumes();
|
||||
if let Some(root) = volume_root_for(&root_path)
|
||||
&& !volumes.iter().any(|volume| volume.point == root)
|
||||
{
|
||||
volumes.push(disktree_core::space::Volume {
|
||||
point: root.clone(),
|
||||
device: device_for(&root),
|
||||
space: space_info(&root).ok(),
|
||||
});
|
||||
}
|
||||
volumes.retain(|volume| volume.point != root_path);
|
||||
volumes
|
||||
});
|
||||
cx.spawn(async move |this, cx| {
|
||||
let volumes = task.await;
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
if this.volumes_open && this.volume_epoch == epoch {
|
||||
this.volumes = volumes;
|
||||
this.volumes_loading = false;
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Close the picker and return the keyboard to the treemap.
|
||||
pub fn close_volumes(&mut self, cx: &mut Context<'_, Self>) {
|
||||
self.volumes_open = false;
|
||||
self.focus_request = Some(FocusTarget::Root);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Scan the highlighted volume from scratch; closes the picker when there
|
||||
/// is nothing to pick.
|
||||
pub fn choose_volume(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.volumes_loading {
|
||||
return;
|
||||
}
|
||||
self.focus_request = Some(FocusTarget::Root);
|
||||
let Some(point) = self
|
||||
.volumes
|
||||
.get(self.volume_highlight)
|
||||
.map(|volume| volume.point.clone())
|
||||
else {
|
||||
self.volumes_open = false;
|
||||
cx.notify();
|
||||
return;
|
||||
};
|
||||
self.volumes_open = false;
|
||||
self.volumes.clear();
|
||||
self.set_root(point, cx);
|
||||
}
|
||||
|
||||
/// Move the highlight in the open picker, wrapping at the ends.
|
||||
pub fn move_volume_highlight(
|
||||
&mut self,
|
||||
step: i32,
|
||||
cx: &mut Context<'_, Self>,
|
||||
) {
|
||||
if self.volumes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let len = self.volumes.len();
|
||||
let at = self.volume_highlight;
|
||||
// Picker steps are ±1, but wrap either way without casting the length
|
||||
// down to a narrower type.
|
||||
let next = match step.signum() {
|
||||
1 => (at + 1) % len,
|
||||
-1 => at.checked_sub(1).unwrap_or(len - 1),
|
||||
_ => at,
|
||||
};
|
||||
self.volume_highlight = next;
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// `g`: the whole disk. Widens when the disk is above the scanned root,
|
||||
/// and goes to its top when it already is the root.
|
||||
pub fn go_to_disk(&mut self, cx: &mut Context<'_, Self>) {
|
||||
@@ -658,6 +783,22 @@ impl Disktree {
|
||||
|
||||
// ── scanning ────────────────────────────────────────────────────────
|
||||
|
||||
/// Stop the walk in progress. A partial tree is never shown as if it
|
||||
/// were the whole one: a first scan leaves the panel saying it stopped,
|
||||
/// and a widening scan leaves the tree it started from on screen.
|
||||
pub fn cancel_scan(&mut self, cx: &mut Context<'_, Self>) {
|
||||
let Some(scan) = self.scan.take() else {
|
||||
return;
|
||||
};
|
||||
scan.cancel();
|
||||
// The poller stops at its next tick instead of taking the result.
|
||||
self.scan_epoch += 1;
|
||||
self.progress = scan.progress.snapshot();
|
||||
self.scan_elapsed = self.scan_started.map(|started| started.elapsed());
|
||||
self.scan_root.clone_from(&self.root_path);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Start a fresh scan, abandoning any walk still in progress.
|
||||
pub fn start_scan(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if let Some(scan) = &self.scan {
|
||||
@@ -671,7 +812,7 @@ impl Disktree {
|
||||
if !self.crumbs.is_empty() {
|
||||
self.remember();
|
||||
}
|
||||
self.tree = None;
|
||||
discard(self.tree.take());
|
||||
self.crumbs.clear();
|
||||
self.selected = None;
|
||||
self.hovered = None;
|
||||
@@ -738,10 +879,11 @@ impl Disktree {
|
||||
self.root_path.clone_from(&self.scan_root);
|
||||
self.space = space_info(&self.root_path).ok();
|
||||
self.device = device_for(&self.root_path);
|
||||
self.file_table = file_table_readable(&self.root_path);
|
||||
}
|
||||
let metric = self.options.metric;
|
||||
self.marks.refresh(&self.root_path, &node, metric);
|
||||
self.tree = Some(Arc::new(node));
|
||||
discard(self.tree.replace(Arc::new(node)));
|
||||
self.cache = None;
|
||||
self.refresh_insights();
|
||||
self.scan_elapsed =
|
||||
@@ -1797,11 +1939,15 @@ impl Disktree {
|
||||
}
|
||||
|
||||
pub fn toggle_metric(&mut self, cx: &mut Context<'_, Self>) {
|
||||
// Children are ordered by the metric, so every crumb moves. Keep the
|
||||
// paths and find them again in the reordered tree.
|
||||
let directory = self.current_path();
|
||||
let selected = self.selected.as_deref().and_then(|c| self.path_at(c));
|
||||
self.options.metric = self.options.metric.toggled();
|
||||
if let Some(tree) = &self.tree {
|
||||
let mut tree = (**tree).clone();
|
||||
disktree_core::tree::aggregate(&mut tree, self.options.metric);
|
||||
self.tree = Some(Arc::new(tree));
|
||||
discard(self.tree.replace(Arc::new(tree)));
|
||||
let metric = self.options.metric;
|
||||
self.marks.refresh(
|
||||
&self.root_path,
|
||||
@@ -1809,7 +1955,11 @@ impl Disktree {
|
||||
metric,
|
||||
);
|
||||
}
|
||||
// Children are ordered by the metric, so every crumb moved.
|
||||
self.crumbs = self.crumbs_for_path(&directory).unwrap_or_default();
|
||||
self.selected = selected.and_then(|path| self.crumbs_for_path(&path));
|
||||
self.forget_hover();
|
||||
self.crumb_menu = None;
|
||||
self.transition = None;
|
||||
self.refresh_insights();
|
||||
self.clear_filter();
|
||||
self.cache = None;
|
||||
@@ -1922,6 +2072,16 @@ impl Disktree {
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
// This window quits once the prompt is answered yes, and quitting
|
||||
// would stop a permanent delete halfway.
|
||||
if self.restarting {
|
||||
self.notice = Some((
|
||||
"not while restarting as administrator".into(),
|
||||
Status::Warning,
|
||||
));
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
self.space_baseline = self.space.or(self.space_baseline);
|
||||
self.run_epoch += 1;
|
||||
let epoch = self.run_epoch;
|
||||
@@ -2118,7 +2278,9 @@ impl Disktree {
|
||||
/// behind the confirmation, and not under the review list or a removal
|
||||
/// that is still running.
|
||||
pub fn can_start_over(&self) -> bool {
|
||||
self.screen == Screen::Explore && !self.confirm_open
|
||||
self.screen == Screen::Explore
|
||||
&& !self.confirm_open
|
||||
&& !self.volumes_open
|
||||
}
|
||||
|
||||
/// Ask for a directory and scan it: an app opened from the Dock has no
|
||||
@@ -2259,6 +2421,23 @@ impl Disktree {
|
||||
return;
|
||||
}
|
||||
|
||||
// The volume picker owns its keys while open: arrows move, Enter
|
||||
// picks, Escape closes, and nothing behind it acts.
|
||||
if self.volumes_open {
|
||||
match key {
|
||||
"escape" => self.close_volumes(cx),
|
||||
"enter" => self.choose_volume(cx),
|
||||
"up" | "k" if !control => {
|
||||
self.move_volume_highlight(-1, cx);
|
||||
}
|
||||
"down" | "j" if !control => {
|
||||
self.move_volume_highlight(1, cx);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// ⌘ chords belong to the menu bar (⌘Q, ⌘W, ⌘R) or to the system.
|
||||
// Read as plain letters they would act twice or by surprise: ⌘D
|
||||
// would re-scan with apparent sizes, ⌘H would hide *and* toggle.
|
||||
@@ -2381,6 +2560,7 @@ impl Disktree {
|
||||
"backspace" | "u" if !control => self.ascend(cx),
|
||||
// A filter is the first thing Escape takes away.
|
||||
"escape" if self.matches.is_some() => self.clear_filter(),
|
||||
"escape" if self.scan.is_some() => self.cancel_scan(cx),
|
||||
"escape" => {
|
||||
if self.selected.is_some() {
|
||||
self.selected = None;
|
||||
@@ -2430,6 +2610,7 @@ impl Disktree {
|
||||
}
|
||||
"r" if !control => self.start_scan(cx),
|
||||
"g" if !control => self.go_to_disk(cx),
|
||||
"v" if !control && !shift => self.open_volumes(cx),
|
||||
"i" if !control => {
|
||||
self.options.include_hidden = !self.options.include_hidden;
|
||||
self.start_scan(cx);
|
||||
@@ -2575,10 +2756,17 @@ impl Disktree {
|
||||
self.toggle_mark(&crumbs, cx);
|
||||
}
|
||||
}
|
||||
MouseButton::Navigate(NavigationDirection::Back) => {
|
||||
// Buttons 8 and 9. gpui-pre maps them on X11, Wayland and
|
||||
// Windows; a mouse with no side buttons never sends them, and
|
||||
// then the header `<` / `>` and alt-arrows are the whole story.
|
||||
MouseButton::Navigate(NavigationDirection::Back)
|
||||
if self.screen == Screen::Explore =>
|
||||
{
|
||||
self.go_back(cx);
|
||||
}
|
||||
MouseButton::Navigate(NavigationDirection::Forward) => {
|
||||
MouseButton::Navigate(NavigationDirection::Forward)
|
||||
if self.screen == Screen::Explore =>
|
||||
{
|
||||
self.go_forward(cx);
|
||||
}
|
||||
_ => {}
|
||||
@@ -2726,6 +2914,80 @@ fn crumb_label(path: &Path) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
impl Disktree {
|
||||
/// Start again as an administrator on the root this window is headed
|
||||
/// for, with the same options, and close this window once the prompt is
|
||||
/// accepted.
|
||||
/// Declined, nothing changes. Not while a removal runs: quitting would
|
||||
/// stop a permanent delete halfway.
|
||||
pub fn restart_as_administrator(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.restarting || self.run.is_some() {
|
||||
return;
|
||||
}
|
||||
self.restarting = true;
|
||||
cx.notify();
|
||||
// While a widening scan runs, the wider root is where this window
|
||||
// ends up, and the drive the offer is about: reopening the folder
|
||||
// still on screen would walk it again. `scan_root` equals
|
||||
// `root_path` for any other scan, and is stale once none runs.
|
||||
let root = if self.scan.is_some() {
|
||||
&self.scan_root
|
||||
} else {
|
||||
&self.root_path
|
||||
};
|
||||
let args =
|
||||
restart_args(&self.options, self.layout_options.max_depth, root);
|
||||
// Off the UI thread: the prompt runs its own message loop, which
|
||||
// would re-enter this window while it is still being handled.
|
||||
let restart = cx.background_executor().spawn(async move {
|
||||
disktree_core::access::restart_as_administrator(&args)
|
||||
});
|
||||
cx.spawn(async move |this, cx| {
|
||||
let outcome = restart.await;
|
||||
let _ = this.update(cx, |this, cx| match outcome {
|
||||
Ok(()) => cx.quit(),
|
||||
Err(error) => {
|
||||
this.restarting = false;
|
||||
this.notice = Some((
|
||||
format!("still not an administrator: {error}"),
|
||||
Status::Warning,
|
||||
));
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
/// The command line that reopens `root` with `options` and `depth`, in the
|
||||
/// flags `parse_args` reads.
|
||||
pub fn restart_args(
|
||||
options: &ScanOptions,
|
||||
depth: u32,
|
||||
root: &Path,
|
||||
) -> Vec<std::ffi::OsString> {
|
||||
let mut args: Vec<std::ffi::OsString> = Vec::new();
|
||||
for (on, flag) in [
|
||||
(options.apparent_size, "--apparent-size"),
|
||||
(options.follow_links, "--follow-links"),
|
||||
(!options.include_hidden, "--no-hidden"),
|
||||
(!options.one_filesystem, "--cross-filesystems"),
|
||||
(options.metric == Metric::Files, "--metric"),
|
||||
] {
|
||||
if on {
|
||||
args.push(flag.into());
|
||||
}
|
||||
}
|
||||
if options.metric == Metric::Files {
|
||||
args.push("files".into());
|
||||
}
|
||||
args.push("--depth".into());
|
||||
args.push(depth.to_string().into());
|
||||
args.push(root.as_os_str().to_owned());
|
||||
args
|
||||
}
|
||||
|
||||
/// Now, in Unix seconds.
|
||||
pub fn now_seconds() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
@@ -2735,6 +2997,16 @@ pub fn now_seconds() -> i64 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Let go of a tree off the UI thread: freeing a disk's millions of nodes
|
||||
/// takes a good part of a second, and nothing waits on it.
|
||||
fn discard(tree: Option<Arc<Node>>) {
|
||||
if let Some(tree) = tree {
|
||||
// When no thread can be made, the closure is dropped here instead,
|
||||
// and the tree is freed in place rather than taking the window down.
|
||||
let _ = std::thread::Builder::new().spawn(move || drop(tree));
|
||||
}
|
||||
}
|
||||
|
||||
/// Smallest tile, in rem, that gets a label: below this a name cannot be read.
|
||||
const LABEL_MIN_W_REMS: f32 = 3.375;
|
||||
const LABEL_MIN_H_REMS: f32 = 0.9375;
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
//! that panics while painting, a binding that never fires, a removal that
|
||||
//! reports success without removing anything.
|
||||
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use disktree_core::removal::RemovalMode;
|
||||
use disktree_core::scan::{ScanOptions, scan};
|
||||
use disktree_core::space::{SpaceInfo, Volume};
|
||||
use disktree_core::treemap::Tile;
|
||||
use gpui_kit::{
|
||||
Bounds, Context, Entity, Pixels, Point, TestAppContext, VisualTestContext,
|
||||
@@ -466,6 +467,112 @@ fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) {
|
||||
assert!(!read(&view, cx, |app| app.show_help));
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_volume_picker_opens_moves_and_closes(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
draw(cx);
|
||||
|
||||
// The picker lists volumes and draws them without panicking; Escape
|
||||
// leaves the scan where it was.
|
||||
press(cx, "v");
|
||||
assert!(read(&view, cx, |app| app.volumes_open));
|
||||
draw(cx);
|
||||
assert!(cx.debug_bounds("disktree-root").is_some());
|
||||
let before = read(&view, cx, |app| app.root_path.clone());
|
||||
press(cx, "down");
|
||||
press(cx, "up");
|
||||
press(cx, "escape");
|
||||
assert!(!read(&view, cx, |app| app.volumes_open));
|
||||
assert_eq!(read(&view, cx, |app| app.root_path.clone()), before);
|
||||
}
|
||||
|
||||
/// Enter must reach the picker even when its dialog owns keyboard focus.
|
||||
#[gpui_kit::test]
|
||||
fn enter_in_the_focused_volume_picker_scans_the_selected_root(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let target = temp.path().join("junk");
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, _| {
|
||||
app.volumes = vec![disktree_core::space::Volume {
|
||||
point: target.clone(),
|
||||
device: None,
|
||||
space: None,
|
||||
}];
|
||||
app.volume_highlight = 0;
|
||||
app.volumes_open = true;
|
||||
});
|
||||
let focus = read(&view, cx, |app| app.confirm_focus.clone());
|
||||
cx.update(|window, cx| window.focus(&focus, cx));
|
||||
draw(cx);
|
||||
assert!(!read(&view, cx, Disktree::can_start_over));
|
||||
press(cx, "enter");
|
||||
assert!(!read(&view, cx, |app| app.volumes_open));
|
||||
assert_eq!(read(&view, cx, |app| app.root_path.clone()), target);
|
||||
finish_scan(&view, cx);
|
||||
assert!(read(&view, cx, |app| app.tree().is_some()));
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_volume_picker_is_centred_and_still_dismisses_from_outside(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
// Fixed rows, so this is about where the popup lands and not about which
|
||||
// disks the machine running the test happens to have.
|
||||
update(&view, cx, |app, cx| {
|
||||
app.volumes = vec![
|
||||
Volume {
|
||||
point: PathBuf::from("/one"),
|
||||
device: Some("/dev/one".into()),
|
||||
space: Some(SpaceInfo {
|
||||
total: 1_000,
|
||||
free: 500,
|
||||
available: 400,
|
||||
}),
|
||||
},
|
||||
Volume {
|
||||
point: PathBuf::from("/two"),
|
||||
device: None,
|
||||
space: None,
|
||||
},
|
||||
];
|
||||
app.volumes_open = true;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
|
||||
let viewport = cx.update(|window, _| window.viewport_size());
|
||||
let rows = cx.debug_bounds("volume-rows").expect("the rows are drawn");
|
||||
let centre = rows.center();
|
||||
assert!(
|
||||
(centre.x - viewport.width / 2.0).abs() < px(4.),
|
||||
"the popup is not centred across: {centre:?} in {viewport:?}"
|
||||
);
|
||||
assert!(
|
||||
(centre.y - viewport.height / 2.0).abs() < px(150.),
|
||||
"the popup is not centred down: {centre:?} in {viewport:?}"
|
||||
);
|
||||
|
||||
// The wrapper that centres the popup must not swallow the backdrop's
|
||||
// clicks: a click in the corner, outside the popup, still closes it.
|
||||
cx.simulate_click(
|
||||
gpui_kit::point(px(4.), px(4.)),
|
||||
gpui_kit::Modifiers::none(),
|
||||
);
|
||||
draw(cx);
|
||||
assert!(
|
||||
!read(&view, cx, |app| app.volumes_open),
|
||||
"clicking outside the picker closes it"
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn showing_a_tile_that_is_gone_says_so_instead(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
@@ -1012,6 +1119,8 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest(
|
||||
let (view, cx) = view_over(&inner, cx);
|
||||
update(&view, cx, |app, _| {
|
||||
app.disk_root = Some(temp.path().to_path_buf());
|
||||
// Stale on purpose: the wider root, a folder, must reset it.
|
||||
app.file_table = true;
|
||||
});
|
||||
let before = read(&view, cx, |app| app.tree().map(|tree| tree.files));
|
||||
|
||||
@@ -1039,6 +1148,10 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest(
|
||||
assert!(read(&view, cx, |app| app.tree().is_some()));
|
||||
finish_scan(&view, cx);
|
||||
assert_eq!(read(&view, cx, |app| app.root_path.clone()), temp.path());
|
||||
assert!(
|
||||
!read(&view, cx, |app| app.file_table),
|
||||
"the offer follows the root it widened to"
|
||||
);
|
||||
let (reused, rest, selected) = read(&view, cx, |app| {
|
||||
let tree = app.tree().expect("the wider tree");
|
||||
let junk = tree.child_named("junk").map(|node| node.files);
|
||||
@@ -1322,3 +1435,208 @@ fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) {
|
||||
Vec::<usize>::new()
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression: children are ordered by the metric, so switching between
|
||||
/// Size and Files reorders them. The directory on screen and the selection
|
||||
/// are found again by path, rather than following their old positions into
|
||||
/// a sibling.
|
||||
#[gpui_kit::test]
|
||||
fn switching_the_metric_keeps_the_directory_and_the_selection(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = tempfile::TempDir::new().expect("tempdir");
|
||||
let root = temp.path();
|
||||
// Largest by size, but fewest files: the two swap places.
|
||||
std::fs::create_dir_all(root.join("big")).expect("mkdir");
|
||||
std::fs::write(root.join("big/one.bin"), vec![b'x'; 500_000])
|
||||
.expect("write");
|
||||
std::fs::write(root.join("big/two.bin"), vec![b'x'; 1_000]).expect("write");
|
||||
for index in 0..5 {
|
||||
let file = root.join(format!("many/{index}.txt"));
|
||||
std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
|
||||
std::fs::write(&file, b"x").expect("write");
|
||||
}
|
||||
let (view, cx) = view_over(root, cx);
|
||||
draw(cx);
|
||||
|
||||
update(&view, cx, |app, cx| {
|
||||
let big = child_crumbs(app, &[], "big");
|
||||
assert_eq!(big, vec![0], "largest first by size");
|
||||
app.go_to(big.clone(), cx);
|
||||
let one = child_crumbs(app, &big, "one.bin");
|
||||
app.select(Some(one), cx);
|
||||
});
|
||||
draw(cx);
|
||||
|
||||
update(&view, cx, |app, cx| app.set_mode(1, cx));
|
||||
draw(cx);
|
||||
let (here, selected) = read(&view, cx, |app| {
|
||||
(
|
||||
app.current_path(),
|
||||
app.selected
|
||||
.as_deref()
|
||||
.and_then(|crumbs| app.path_at(crumbs)),
|
||||
)
|
||||
});
|
||||
assert_eq!(here, root.join("big"));
|
||||
assert_eq!(selected, Some(root.join("big/one.bin")));
|
||||
|
||||
update(&view, cx, |app, cx| app.set_mode(0, cx));
|
||||
draw(cx);
|
||||
assert_eq!(read(&view, cx, Disktree::current_path), root.join("big"));
|
||||
}
|
||||
|
||||
/// Escape stops a first scan. What the walk found so far is not shown as a
|
||||
/// tree, a late result is ignored, and `r` starts over.
|
||||
#[gpui_kit::test]
|
||||
fn escape_cancels_the_first_scan_and_r_starts_it_again(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let root = temp.path().to_path_buf();
|
||||
let (view, cx) =
|
||||
cx.add_window_view(move |_, cx| Disktree::new(root, options(), 3, cx));
|
||||
let focus = view.read_with(cx, |app, _| app.focus.clone());
|
||||
cx.update(|window, cx| window.focus(&focus, cx));
|
||||
draw(cx);
|
||||
let epoch = read(&view, cx, |app| app.scan_epoch);
|
||||
|
||||
press(cx, "escape");
|
||||
let (scanning, cancelled) = read(&view, cx, |app| {
|
||||
(app.scan.is_some(), app.progress.cancelled)
|
||||
});
|
||||
assert!(!scanning, "the walk was dropped");
|
||||
assert!(cancelled, "the panel can say it stopped");
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
let polling = update(&view, cx, |app, cx| app.poll_scan_once(epoch, cx));
|
||||
assert!(!polling, "the old poller stops");
|
||||
assert!(read(&view, cx, |app| app.tree().is_none()));
|
||||
draw(cx);
|
||||
|
||||
press(cx, "r");
|
||||
finish_scan(&view, cx);
|
||||
assert!(read(&view, cx, |app| app.tree().is_some()));
|
||||
}
|
||||
|
||||
/// Escape stops a widening scan and keeps the tree it started from.
|
||||
#[gpui_kit::test]
|
||||
fn escape_cancels_widening_and_keeps_the_tree_on_screen(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let inner = temp.path().join("junk");
|
||||
let (view, cx) = view_over(&inner, cx);
|
||||
update(&view, cx, |app, _| {
|
||||
app.disk_root = Some(temp.path().to_path_buf());
|
||||
});
|
||||
let before = read(&view, cx, |app| app.tree().map(|tree| tree.files));
|
||||
|
||||
press(cx, "g");
|
||||
assert!(read(&view, cx, |app| app.scan.is_some()));
|
||||
press(cx, "escape");
|
||||
let (scanning, root, scan_root, files) = read(&view, cx, |app| {
|
||||
(
|
||||
app.scan.is_some(),
|
||||
app.root_path.clone(),
|
||||
app.scan_root.clone(),
|
||||
app.tree().map(|tree| tree.files),
|
||||
)
|
||||
});
|
||||
assert!(!scanning);
|
||||
assert_eq!(root, inner);
|
||||
assert_eq!(scan_root, inner, "the trail stops showing a widening");
|
||||
assert_eq!(files, before, "the tree on screen is unchanged");
|
||||
}
|
||||
|
||||
/// The mouse's back and forward buttons retrace the same history as
|
||||
/// alt-arrows and the header buttons, and only on the explore screen.
|
||||
#[gpui_kit::test]
|
||||
fn mouse_side_buttons_go_back_and_forward(cx: &mut TestAppContext) {
|
||||
use gpui_kit::{Modifiers, MouseButton, NavigationDirection};
|
||||
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
cx.simulate_resize(gpui_kit::size(px(1400.), px(900.)));
|
||||
draw(cx);
|
||||
|
||||
let (junk, deeper) = update(&view, cx, |app, cx| {
|
||||
let junk = child_crumbs(app, &[], "junk");
|
||||
let deeper = child_crumbs(app, &junk, "deeper");
|
||||
app.select(Some(junk.clone()), cx);
|
||||
app.descend(cx);
|
||||
app.select(Some(deeper.clone()), cx);
|
||||
app.descend(cx);
|
||||
(junk, deeper)
|
||||
});
|
||||
draw(cx);
|
||||
assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
|
||||
|
||||
// Over the mosaic, buttons 8 and 9 step the history, as alt-arrows do.
|
||||
let mosaic = cx.debug_bounds("treemap").expect("the mosaic is drawn");
|
||||
let at = mosaic.center();
|
||||
let press_button = |cx: &mut Window, button: MouseButton| {
|
||||
cx.simulate_mouse_move(at, None, Modifiers::none());
|
||||
cx.simulate_mouse_down(at, button, Modifiers::none());
|
||||
cx.simulate_mouse_up(at, button, Modifiers::none());
|
||||
draw(cx);
|
||||
};
|
||||
press_button(cx, MouseButton::Navigate(NavigationDirection::Back));
|
||||
assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk);
|
||||
press_button(cx, MouseButton::Navigate(NavigationDirection::Forward));
|
||||
assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
|
||||
|
||||
// On the review screen the same press changes nothing: the marked list
|
||||
// is not somewhere the history can take you back to.
|
||||
update(&view, cx, |app, cx| app.toggle_mark(&junk, cx));
|
||||
press(cx, "c");
|
||||
assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);
|
||||
press_button(cx, MouseButton::Navigate(NavigationDirection::Back));
|
||||
assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper);
|
||||
assert_eq!(read(&view, cx, |app| app.screen), Screen::Review);
|
||||
}
|
||||
|
||||
/// The restart as administrator reopens the same root and options: every
|
||||
/// flag it writes is one the command line reads back.
|
||||
#[test]
|
||||
fn restart_arguments_parse_back_to_the_same_scan() {
|
||||
use disktree_core::tree::Metric;
|
||||
let temp = tempfile::TempDir::new().expect("tempdir");
|
||||
let root = temp.path().join("a folder");
|
||||
std::fs::create_dir(&root).expect("mkdir");
|
||||
let root = dunce::canonicalize(&root).expect("canonical root");
|
||||
let changed = ScanOptions {
|
||||
apparent_size: true,
|
||||
follow_links: true,
|
||||
include_hidden: false,
|
||||
one_filesystem: false,
|
||||
metric: Metric::Files,
|
||||
..ScanOptions::default()
|
||||
};
|
||||
for (options, depth) in [(changed, 5), (ScanOptions::default(), 1)] {
|
||||
let args = crate::state::restart_args(&options, depth, &root);
|
||||
let parsed = crate::parse_args(args.into_iter()).expect("parses");
|
||||
assert_eq!(parsed.root, root);
|
||||
assert_eq!(parsed.depth, depth);
|
||||
let got = &parsed.options;
|
||||
assert_eq!(
|
||||
(
|
||||
got.apparent_size,
|
||||
got.follow_links,
|
||||
got.include_hidden,
|
||||
got.one_filesystem,
|
||||
got.metric,
|
||||
),
|
||||
(
|
||||
options.apparent_size,
|
||||
options.follow_links,
|
||||
options.include_hidden,
|
||||
options.one_filesystem,
|
||||
options.metric,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,10 +14,10 @@ use std::rc::Rc;
|
||||
use disktree_core::treemap::Rect;
|
||||
use gpui_kit::{
|
||||
App, Bounds, ContentMask, Context, Corners, Edges, Font, FontWeight, Hsla,
|
||||
InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
|
||||
MouseMoveEvent, ParentElement as _, Pixels, Point, ScrollWheelEvent,
|
||||
SharedString, Size, StatefulInteractiveElement as _, Styled, TextAlign,
|
||||
TextRun, Window, canvas, div, pattern_slash, px, quad,
|
||||
InteractiveElement as _, IntoElement, MouseDownEvent, MouseMoveEvent,
|
||||
ParentElement as _, Pixels, Point, ScrollWheelEvent, SharedString, Size,
|
||||
StatefulInteractiveElement as _, Styled, TextAlign, TextRun, Window,
|
||||
canvas, div, pattern_slash, px, quad,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, Theme};
|
||||
|
||||
@@ -86,6 +86,7 @@ pub fn mosaic(
|
||||
|
||||
div()
|
||||
.id("disktree-treemap")
|
||||
.debug_selector(|| "treemap".into())
|
||||
.relative()
|
||||
.flex_1()
|
||||
.min_h_0()
|
||||
@@ -100,18 +101,13 @@ pub fn mosaic(
|
||||
.on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
|
||||
this.on_mouse_move(event, cx);
|
||||
}))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
cx.listener(|this, event: &MouseDownEvent, _, cx| {
|
||||
this.on_mouse_down(event, cx);
|
||||
}),
|
||||
)
|
||||
.on_mouse_down(
|
||||
MouseButton::Middle,
|
||||
cx.listener(|this, event: &MouseDownEvent, _, cx| {
|
||||
this.on_mouse_down(event, cx);
|
||||
}),
|
||||
)
|
||||
// One listener for every button, because the interesting ones are not
|
||||
// the three the platform names: buttons 8 and 9 arrive as
|
||||
// `MouseButton::Navigate`, and a per-button registration would have
|
||||
// to be repeated for each.
|
||||
.on_any_mouse_down(cx.listener(|this, event: &MouseDownEvent, _, cx| {
|
||||
this.on_mouse_down(event, cx);
|
||||
}))
|
||||
.on_scroll_wheel(cx.listener(
|
||||
|this, event: &ScrollWheelEvent, _, cx| {
|
||||
this.on_scroll_wheel(event, cx);
|
||||
|
||||
@@ -13,7 +13,7 @@ use gpui_kit::base::CheckboxState;
|
||||
use gpui_kit::{
|
||||
App, AppContext as _, ClickEvent, Context, Div, DragMoveEvent, ElementId,
|
||||
FontWeight, InteractiveElement as _, IntoElement, KeyDownEvent,
|
||||
ParentElement, Rems, SharedString, Stateful,
|
||||
MouseDownEvent, ParentElement, Rems, SharedString, Stateful,
|
||||
StatefulInteractiveElement as _, Styled, Window, anchored, deferred, div,
|
||||
pattern_slash, px, relative,
|
||||
};
|
||||
@@ -111,12 +111,145 @@ pub fn root(
|
||||
if app.show_help {
|
||||
root = root.child(help_overlay(app, cx));
|
||||
}
|
||||
if app.volumes_open {
|
||||
root = root.child(volumes_dialog(app, cx));
|
||||
}
|
||||
if app.confirm_open {
|
||||
root = root.child(delete_dialog(app, cx));
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
/// Picking another volume scans it from scratch: the picker lists every
|
||||
/// volume with its free space, and the choice is the new root.
|
||||
fn volumes_dialog(
|
||||
app: &Disktree,
|
||||
cx: &mut Context<'_, Disktree>,
|
||||
) -> impl IntoElement {
|
||||
let theme = cx.omarchy().clone();
|
||||
let cancel = cx.entity().downgrade();
|
||||
let mut rows = div()
|
||||
.id("volume-rows")
|
||||
.debug_selector(|| "volume-rows".into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::XS);
|
||||
if app.volumes_loading {
|
||||
rows = rows.child(dialog_description("Looking for volumes…", cx));
|
||||
} else if app.volumes.is_empty() {
|
||||
rows = rows
|
||||
.child(dialog_description("No other volume could be read.", cx));
|
||||
}
|
||||
for (index, volume) in app.volumes.iter().enumerate() {
|
||||
let highlighted = index == app.volume_highlight;
|
||||
let free = volume.space.map_or_else(
|
||||
|| "unknown free".to_string(),
|
||||
|space| format!("{} free", human_bytes(space.available)),
|
||||
);
|
||||
let label = match &volume.device {
|
||||
Some(device) => format!(
|
||||
"{} \u{00b7} {device} \u{00b7} {free}",
|
||||
volume.point.display()
|
||||
),
|
||||
None => format!("{} \u{00b7} {free}", volume.point.display()),
|
||||
};
|
||||
rows = rows.child(
|
||||
div()
|
||||
.id(ElementId::Name(format!("volume-{index}").into()))
|
||||
.px(space::MD)
|
||||
.py(space::SM)
|
||||
.text_size(text::BODY)
|
||||
.text_color(if highlighted {
|
||||
theme.bright
|
||||
} else {
|
||||
theme.foreground
|
||||
})
|
||||
// Only the row the keys are on is tinted: a second highlight
|
||||
// would read as a second selection.
|
||||
.when(highlighted, |row| row.bg(theme.accent.opacity(0.18)))
|
||||
.hover(|row| row.bg(theme.accent.opacity(0.1)))
|
||||
.child(label)
|
||||
.on_click(cx.listener(move |this, _, window, cx| {
|
||||
this.volume_highlight = index;
|
||||
this.choose_volume(cx);
|
||||
window.focus(&this.focus, cx);
|
||||
})),
|
||||
);
|
||||
}
|
||||
let popup = dialog_popup(cx)
|
||||
.child(dialog_title("Scan a volume", cx))
|
||||
.child(dialog_description(
|
||||
"Up and down moves, Enter scans it, Escape stays here.",
|
||||
cx,
|
||||
))
|
||||
.child(rows);
|
||||
let centred = centred_popup(popup, {
|
||||
let close = cancel.clone();
|
||||
move |_, window, cx| {
|
||||
let _ = close.update(cx, |this, cx| {
|
||||
this.close_volumes(cx);
|
||||
this.apply_focus(window, cx);
|
||||
});
|
||||
}
|
||||
});
|
||||
let accept = cx.entity().downgrade();
|
||||
alert_dialog(&app.confirm_focus, cx)
|
||||
.open(true)
|
||||
.on_ok(move |_, window, cx| {
|
||||
let _ = accept.update(cx, |this, cx| {
|
||||
this.choose_volume(cx);
|
||||
this.apply_focus(window, cx);
|
||||
});
|
||||
false
|
||||
})
|
||||
.on_cancel(move |_, window, cx| {
|
||||
let _ = cancel.update(cx, |this, cx| {
|
||||
this.close_volumes(cx);
|
||||
this.apply_focus(window, cx);
|
||||
});
|
||||
false
|
||||
})
|
||||
.popup(centred)
|
||||
}
|
||||
|
||||
/// Put a dialog's popup in the middle of the window, and close it when a
|
||||
/// click lands outside it.
|
||||
///
|
||||
/// The base dialog hosts its popup as an ordinary child of a full-window box,
|
||||
/// so a popup lands in the top-left corner unless something centres it. That
|
||||
/// something ends up in front of the backdrop, which is what used to receive
|
||||
/// the click that dismisses a dialog, so the click is taken here instead. The
|
||||
/// card stops a mouse-down from reaching this wrapper, so a click on the
|
||||
/// dialog itself stays the dialog's own.
|
||||
fn centred_popup(
|
||||
card: impl IntoElement,
|
||||
on_outside: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
|
||||
) -> Stateful<Div> {
|
||||
div()
|
||||
.id("dialog-outside")
|
||||
.absolute()
|
||||
.inset_0()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
// Any button, as the backdrop took them: a right-click outside closes
|
||||
// the dialog too.
|
||||
.on_any_mouse_down(move |event, window, cx| {
|
||||
cx.stop_propagation();
|
||||
on_outside(event, window, cx);
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.id("dialog-card")
|
||||
.on_any_mouse_down(
|
||||
|_: &MouseDownEvent, _: &mut Window, cx: &mut App| {
|
||||
cx.stop_propagation();
|
||||
},
|
||||
)
|
||||
.child(card),
|
||||
)
|
||||
}
|
||||
|
||||
/// The one question disktree asks: a permanent deletion cannot be undone, so
|
||||
/// it is an alert dialog that names what goes and what comes back. The trash is
|
||||
/// reversible and needs no dialog.
|
||||
@@ -171,6 +304,17 @@ fn delete_dialog(
|
||||
.child(dialog_title(title, cx))
|
||||
.child(dialog_description(body, cx))
|
||||
.child(actions);
|
||||
// Built before the chain below, which moves `cancel` into its own
|
||||
// handler for Escape.
|
||||
let centred = centred_popup(popup, {
|
||||
let close = cancel.clone();
|
||||
move |_, window, cx| {
|
||||
let _ = close.update(cx, |this, cx| {
|
||||
this.cancel_delete(cx);
|
||||
this.apply_focus(window, cx);
|
||||
});
|
||||
}
|
||||
});
|
||||
alert_dialog(&app.confirm_focus, cx)
|
||||
.open(true)
|
||||
.on_ok(move |_, window, cx| {
|
||||
@@ -187,7 +331,7 @@ fn delete_dialog(
|
||||
});
|
||||
false
|
||||
})
|
||||
.popup(popup)
|
||||
.popup(centred)
|
||||
}
|
||||
|
||||
// ── explore ─────────────────────────────────────────────────────────────
|
||||
@@ -1003,6 +1147,7 @@ fn side_panel(
|
||||
)
|
||||
.children(notice_line(app, theme, cx))
|
||||
.children(privacy_line(app, theme, cx))
|
||||
.children(administrator_line(app, theme, cx))
|
||||
.child(disk_section(app, theme, cx))
|
||||
}
|
||||
|
||||
@@ -1581,6 +1726,77 @@ fn privacy_line(
|
||||
)
|
||||
}
|
||||
|
||||
/// The faster, fuller scan an administrator gets on Windows, and the way to
|
||||
/// it. Only where it would help: on a whole NTFS drive walked without `-l`,
|
||||
/// which is then read from its file table instead, or once the walk was
|
||||
/// refused something. Hidden once asked, and while a removal runs, which a
|
||||
/// restart would cut short.
|
||||
fn administrator_line(
|
||||
app: &Disktree,
|
||||
theme: &Theme,
|
||||
cx: &Context<'_, Disktree>,
|
||||
) -> Option<Div> {
|
||||
if app.administrator != Some(false) || app.restarting || app.run.is_some() {
|
||||
return None;
|
||||
}
|
||||
let errors = app.progress.errors;
|
||||
let message = if errors > 0 {
|
||||
let noun = if errors == 1 { "item" } else { "items" };
|
||||
// With `-l` the elevated copy walks too: only the reading is gained.
|
||||
let faster = if app.options.follow_links {
|
||||
""
|
||||
} else {
|
||||
", and a whole drive several times faster"
|
||||
};
|
||||
format!(
|
||||
"Windows kept {} {noun} unreadable. Run as administrator to read \
|
||||
them{faster}.",
|
||||
widgets::human_count(errors)
|
||||
)
|
||||
} else if app.file_table && !app.options.follow_links {
|
||||
"Run as administrator to read the whole drive from its file table: \
|
||||
several times faster than this walk."
|
||||
.to_owned()
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
// Marks live only in this process; the new one starts without them.
|
||||
let message = if app.marks.is_empty() {
|
||||
message
|
||||
} else {
|
||||
format!("{message} Restarting drops the marks.")
|
||||
};
|
||||
let color = theme.warning;
|
||||
Some(
|
||||
div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap(space::SM)
|
||||
.px(space::SM)
|
||||
.py(space::SM)
|
||||
.border_1()
|
||||
.border_color(color.opacity(0.5))
|
||||
.text_size(text::CAPTION)
|
||||
.child(div().text_color(color).child(message))
|
||||
.child(
|
||||
button(
|
||||
"administrator",
|
||||
"Restart as Administrator",
|
||||
ButtonVariant::Outline,
|
||||
cx,
|
||||
)
|
||||
.tab_stop(false)
|
||||
.justify_center()
|
||||
.on_click(cx.listener(
|
||||
|this, _, window, cx| {
|
||||
window.focus(&this.focus, cx);
|
||||
this.restart_as_administrator(cx);
|
||||
},
|
||||
)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// Free space on the volume now, and after the marks go.
|
||||
fn disk_section(
|
||||
app: &Disktree,
|
||||
@@ -1588,19 +1804,30 @@ fn disk_section(
|
||||
cx: &Context<'_, Disktree>,
|
||||
) -> Div {
|
||||
let device = app.device.clone().unwrap_or_default();
|
||||
let mut section = div().flex().flex_col().gap(space::SM).child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.gap(space::SM)
|
||||
.child(widgets::eyebrow("Disk", cx))
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary.opacity(0.6))
|
||||
.child(device),
|
||||
),
|
||||
);
|
||||
// The disk header doubles as the way to another volume: it opens the
|
||||
// picker, like `V` does. A plain label would hide that the scan can move.
|
||||
let header = div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.items_center()
|
||||
.gap(space::SM)
|
||||
.child(widgets::eyebrow("Disk", cx))
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
.text_color(theme.secondary.opacity(0.6))
|
||||
.child(device),
|
||||
)
|
||||
.child(div().flex_1())
|
||||
.child(
|
||||
button("volumes", "Volumes", ButtonVariant::Secondary, cx)
|
||||
.tab_stop(false)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.open_volumes(cx);
|
||||
this.apply_focus(window, cx);
|
||||
})),
|
||||
);
|
||||
let mut section = div().flex().flex_col().gap(space::SM).child(header);
|
||||
let Some(space_info) = app.space else {
|
||||
return section.child(
|
||||
div()
|
||||
@@ -1751,7 +1978,7 @@ fn review_button(
|
||||
/// to every other key and the scan's own numbers hold the trailing edge.
|
||||
fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
// Most useful first, so a narrow window clips the least useful.
|
||||
let hints: [(&str, &str); 10] = [
|
||||
let hints: [(&str, &str); 11] = [
|
||||
("space", "mark"),
|
||||
("enter", "open"),
|
||||
("\u{232b}", "up"),
|
||||
@@ -1761,6 +1988,7 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
("[ ]", "depth"),
|
||||
("t", "mode"),
|
||||
("0", "reset"),
|
||||
("v", "volumes"),
|
||||
("r", "rescan"),
|
||||
];
|
||||
let mut lane = div()
|
||||
@@ -1800,6 +2028,11 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
widgets::human_count(app.progress.files),
|
||||
human_bytes(app.progress.bytes)
|
||||
)
|
||||
} else if app.progress.cancelled {
|
||||
format!(
|
||||
"scan cancelled \u{00b7} {} entries \u{00b7} r scans again",
|
||||
widgets::human_count(app.progress.files)
|
||||
)
|
||||
} else {
|
||||
let elapsed = app.scan_elapsed.map_or_else(String::new, |time| {
|
||||
format!(" \u{00b7} {:.1} s", time.as_secs_f32())
|
||||
@@ -1820,8 +2053,13 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
}
|
||||
|
||||
/// What the viewport shows while the first scan is running.
|
||||
fn scanning_panel(app: &Disktree, theme: &Theme, cx: &gpui_kit::App) -> Div {
|
||||
fn scanning_panel(
|
||||
app: &Disktree,
|
||||
theme: &Theme,
|
||||
cx: &Context<'_, Disktree>,
|
||||
) -> Div {
|
||||
let progress = &app.progress;
|
||||
let cancelled = app.scan.is_none() && progress.cancelled;
|
||||
let mut panel = div()
|
||||
.flex()
|
||||
.flex_col()
|
||||
@@ -1831,17 +2069,23 @@ fn scanning_panel(app: &Disktree, theme: &Theme, cx: &gpui_kit::App) -> Div {
|
||||
.justify_center()
|
||||
.gap(space::LG)
|
||||
.bg(theme.inset)
|
||||
.child(
|
||||
gpui_omarchy::icon(gpui_omarchy::IconName::Loader)
|
||||
.size(icon::LG)
|
||||
.text_color(theme.accent),
|
||||
)
|
||||
.when(!cancelled, |panel| {
|
||||
panel.child(
|
||||
gpui_omarchy::icon(gpui_omarchy::IconName::Loader)
|
||||
.size(icon::LG)
|
||||
.text_color(theme.accent),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::TITLE)
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(theme.bright)
|
||||
.child(format!("Reading {}", widgets::display_root(app))),
|
||||
.child(if cancelled {
|
||||
format!("Stopped reading {}", widgets::display_root(app))
|
||||
} else {
|
||||
format!("Reading {}", widgets::display_root(app))
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
@@ -1866,23 +2110,43 @@ fn scanning_panel(app: &Disktree, theme: &Theme, cx: &gpui_kit::App) -> Div {
|
||||
cx,
|
||||
)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.w(size::SCANNING_METER)
|
||||
.child(widgets::meter_row(
|
||||
"",
|
||||
"",
|
||||
progress_estimate(progress.files),
|
||||
theme.accent,
|
||||
cx,
|
||||
)),
|
||||
)
|
||||
.when(!cancelled, |panel| {
|
||||
panel.child(
|
||||
div()
|
||||
.w(size::SCANNING_METER)
|
||||
.child(widgets::meter_row(
|
||||
"",
|
||||
"",
|
||||
progress_estimate(progress.files),
|
||||
theme.accent,
|
||||
cx,
|
||||
)),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::BODY)
|
||||
.text_color(theme.secondary)
|
||||
.child("Marking, zooming and the free-space meter all work as soon as it lands."),
|
||||
);
|
||||
.child(if cancelled {
|
||||
"Nothing is shown from a scan that did not finish."
|
||||
} else {
|
||||
"Marking, zooming and the free-space meter all work as soon as it lands."
|
||||
}),
|
||||
)
|
||||
// A failed scan has nothing left to cancel either.
|
||||
.child(if app.scan.is_none() {
|
||||
button("scan-again", "Scan again", ButtonVariant::Outline, cx)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.start_scan(cx);
|
||||
window.focus(&this.focus, cx);
|
||||
}))
|
||||
} else {
|
||||
button("cancel-scan", "Cancel", ButtonVariant::Outline, cx)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.cancel_scan(cx);
|
||||
window.focus(&this.focus, cx);
|
||||
}))
|
||||
});
|
||||
|
||||
if let Some(error) = &app.scan_error {
|
||||
panel = panel.child(
|
||||
@@ -2826,9 +3090,9 @@ fn card_surface(cx: &gpui_kit::App) -> Div {
|
||||
/// at the pointer, over the button itself.
|
||||
fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div {
|
||||
let (label, keys) = if back {
|
||||
("Back", "alt \u{2190} back")
|
||||
("Back", "alt \u{2190} \u{00b7} side button")
|
||||
} else {
|
||||
("Forward", "alt \u{2192} forward")
|
||||
("Forward", "alt \u{2192} \u{00b7} side button")
|
||||
};
|
||||
let card = app
|
||||
.history_target(back)
|
||||
@@ -2995,14 +3259,14 @@ 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); 27] = [
|
||||
let rows = [
|
||||
("space / x", "Mark or unmark the tile you point at"),
|
||||
(MODIFIER_CLICK, "Mark without moving the selection"),
|
||||
("enter", "Open that directory, at any depth"),
|
||||
("\u{232b} / esc", "Go up one directory"),
|
||||
(
|
||||
"alt \u{2190} / \u{2192}",
|
||||
"Back or forward through where you have been",
|
||||
"Back or forward, as do the mouse's side buttons",
|
||||
),
|
||||
(
|
||||
"\u{2190} \u{2191} \u{2193} \u{2192}",
|
||||
@@ -3021,6 +3285,8 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div {
|
||||
("c", "Review the marked list"),
|
||||
("t", "Size, files or age: what areas and colours say"),
|
||||
("r", "Scan again from the same root"),
|
||||
("esc", "Stop a scan in progress"),
|
||||
("v", "Scan another volume"),
|
||||
(MODIFIER_OPEN, "Choose another directory to scan"),
|
||||
("g", "The whole disk; click any directory above to widen"),
|
||||
("d", "Disk usage or apparent size"),
|
||||
|
||||
@@ -22,7 +22,13 @@ rustix = { version = "1.1", features = ["fs"] }
|
||||
# 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"] }
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Com",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
# 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
|
||||
|
||||
@@ -5,7 +5,14 @@
|
||||
//! with `EPERM`, silently. A disk tool that only counts those as errors
|
||||
//! leaves the user guessing, so the app asks once whether access is granted
|
||||
//! and, if not, says why folders were unreadable and where to fix it.
|
||||
//!
|
||||
//! On Windows the same question is whether disktree runs as an
|
||||
//! administrator: only then can it read a whole drive from its file table,
|
||||
//! several times faster than walking it and including folders a walk is
|
||||
//! refused. Without, it walks.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// System Settings, opened at Privacy & Security › Full Disk Access.
|
||||
@@ -33,6 +40,47 @@ pub fn full_disk_access(home: &Path) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this process runs as an administrator: `None` off Windows,
|
||||
/// where nothing a scan does depends on it.
|
||||
#[cfg(windows)]
|
||||
pub fn administrator() -> Option<bool> {
|
||||
Some(crate::windows::elevated())
|
||||
}
|
||||
|
||||
/// Whether this process runs as an administrator: `None` off Windows,
|
||||
/// where nothing a scan does depends on it.
|
||||
#[cfg(not(windows))]
|
||||
pub const fn administrator() -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether an administrator would read `root` from its file table: a
|
||||
/// whole NTFS drive. Always `false` off Windows.
|
||||
#[cfg(windows)]
|
||||
pub fn file_table_readable(root: &Path) -> bool {
|
||||
crate::windows::file_table_readable(root)
|
||||
}
|
||||
|
||||
/// Whether an administrator would read `root` from its file table: a
|
||||
/// whole NTFS drive. Always `false` off Windows.
|
||||
#[cfg(not(windows))]
|
||||
pub const fn file_table_readable(root: &Path) -> bool {
|
||||
let _ = root;
|
||||
false
|
||||
}
|
||||
|
||||
/// Start this program again as an administrator, with `args`, through the
|
||||
/// UAC prompt. An error if the prompt is declined, or off Windows.
|
||||
pub fn restart_as_administrator(args: &[OsString]) -> io::Result<()> {
|
||||
#[cfg(windows)]
|
||||
return crate::windows::run_elevated(&std::env::current_exe()?, args);
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = args;
|
||||
Err(io::ErrorKind::Unsupported.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
//! space is the same idea, plus a sibling check where a name alone is too
|
||||
//! common to trust: `target` is only a build directory beside a `Cargo.toml`.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::tree::Node;
|
||||
|
||||
/// A kind of data, for colour.
|
||||
@@ -105,15 +109,33 @@ impl Reclaim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of a name lowercased on the stack.
|
||||
const LOWERED: usize = 32;
|
||||
|
||||
/// `name` lowercased, on the stack when it fits in [`LOWERED`] bytes: a
|
||||
/// directory on a whole disk is looked up twice for each of hundreds of
|
||||
/// thousands, and a string allocated each time was most of what
|
||||
/// classifying cost. A longer name is rare enough to allocate.
|
||||
fn lowered<'a>(name: &str, buffer: &'a mut [u8; LOWERED]) -> Cow<'a, str> {
|
||||
let Some(bytes) = buffer.get_mut(..name.len()) else {
|
||||
return Cow::Owned(name.to_ascii_lowercase());
|
||||
};
|
||||
bytes.copy_from_slice(name.as_bytes());
|
||||
bytes.make_ascii_lowercase();
|
||||
// ASCII lowercasing keeps UTF-8.
|
||||
Cow::Borrowed(std::str::from_utf8(bytes).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The kind a directory name announces on its own, if any.
|
||||
pub fn category_of_name(name: &str) -> Option<Category> {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
let mut buffer = [0; LOWERED];
|
||||
let lower = lowered(name, &mut buffer);
|
||||
// Windows: a work or school account's folder carries the organisation,
|
||||
// `OneDrive - Contoso`, and Dropbox's does the same, `Dropbox (Contoso)`.
|
||||
if lower.starts_with("onedrive - ") || lower.starts_with("dropbox (") {
|
||||
return Some(Category::Synced);
|
||||
}
|
||||
let category = match lower.as_str() {
|
||||
let category = match &*lower {
|
||||
"src" | "code" | "projects" | "repos" | "dev" | "work"
|
||||
| "workspace" | "workspaces" | "github.com" | "gitlab.com"
|
||||
| "sites" | "development" => Category::Code,
|
||||
@@ -140,6 +162,7 @@ pub fn category_of_name(name: &str) -> Option<Category> {
|
||||
| "iclouddrive" => Category::Synced,
|
||||
".git" => Category::Git,
|
||||
"pictures" | "photos" | "music" | "videos" | "movies" | "steam"
|
||||
| "steamlibrary" | "steamapps" | "emulation"
|
||||
| "models" | ".ollama" | ".lmstudio" | "games" | "wineprefix" => {
|
||||
Category::Media
|
||||
}
|
||||
@@ -164,8 +187,9 @@ pub fn reclaim_of(
|
||||
parent: Category,
|
||||
has_sibling: impl Fn(&str) -> bool,
|
||||
) -> Option<Reclaim> {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
let reclaim = match lower.as_str() {
|
||||
let mut buffer = [0; LOWERED];
|
||||
let lower = lowered(name, &mut buffer);
|
||||
let reclaim = match &*lower {
|
||||
".cache" | "cache" | "caches" | ".ccache" | ".sccache" | "_cacache"
|
||||
// Windows' own caches in AppData\Local: npm's, NuGet's downloads,
|
||||
// the browser engine's, and compiled shaders, Direct3D's and the
|
||||
@@ -205,14 +229,11 @@ pub fn reclaim_of(
|
||||
pub fn classify(root: &mut Node) {
|
||||
root.category = Category::Other;
|
||||
root.reclaim = None;
|
||||
let children = std::mem::take(&mut root.children);
|
||||
let names: Vec<Box<str>> =
|
||||
children.iter().map(|child| child.name.clone()).collect();
|
||||
root.children = children;
|
||||
for index in 0..root.children.len() {
|
||||
let siblings = &root.children;
|
||||
let has_sibling =
|
||||
|wanted: &str| names.iter().any(|name| &**name == wanted);
|
||||
let child = &mut root.children[index];
|
||||
|wanted: &str| siblings.iter().any(|name| &*name.name == wanted);
|
||||
let child = &siblings[index];
|
||||
// A top-level directory with an unknown name takes the kind of its
|
||||
// largest recognisable child: `~/world` is mostly `.git`.
|
||||
let category = category_of_name(&child.name)
|
||||
@@ -223,7 +244,7 @@ pub fn classify(root: &mut Node) {
|
||||
.is_dir()
|
||||
.then(|| reclaim_of(&child.name, Category::Other, has_sibling))
|
||||
.flatten();
|
||||
classify_below(child, category, reclaim);
|
||||
classify_below(&mut root.children[index], category, reclaim, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,37 +252,67 @@ fn classify_below(
|
||||
node: &mut Node,
|
||||
category: Category,
|
||||
reclaim: Option<Reclaim>,
|
||||
depth: usize,
|
||||
) {
|
||||
node.category = category;
|
||||
node.reclaim = reclaim;
|
||||
if node.children.is_empty() {
|
||||
// Most directories hold only files, which take this one's kind as
|
||||
// they are: no list of kinds to build, no call per file.
|
||||
if !node.children.iter().any(Node::is_dir) {
|
||||
for child in &mut node.children {
|
||||
child.category = category;
|
||||
child.reclaim = reclaim;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let names: Vec<Box<str>> = node
|
||||
.children
|
||||
.iter()
|
||||
.map(|child| child.name.clone())
|
||||
.collect();
|
||||
for child in &mut node.children {
|
||||
let has_sibling =
|
||||
|wanted: &str| names.iter().any(|name| &**name == wanted);
|
||||
let child_category = if child.is_dir() {
|
||||
category_of_name(&child.name)
|
||||
.or_else(|| is_git_store(child).then_some(Category::Git))
|
||||
.unwrap_or(category)
|
||||
} else {
|
||||
category
|
||||
};
|
||||
let child_reclaim = reclaim.or_else(|| {
|
||||
child
|
||||
.is_dir()
|
||||
.then(|| reclaim_of(&child.name, category, has_sibling))
|
||||
.flatten()
|
||||
});
|
||||
classify_below(child, child_category, child_reclaim);
|
||||
// See `tree::PARALLEL_LEVELS`: parallel only near the top. Deeper, the
|
||||
// children are decided and descended one at a time, with no list of
|
||||
// decisions: there are half a million directories to get through.
|
||||
if depth < crate::tree::PARALLEL_LEVELS {
|
||||
let kinds: Vec<(Category, Option<Reclaim>)> = (0..node.children.len())
|
||||
.map(|index| kind_of(&node.children, index, category, reclaim))
|
||||
.collect();
|
||||
node.children.par_iter_mut().zip(kinds).for_each(
|
||||
|(child, (category, reclaim))| {
|
||||
classify_below(child, category, reclaim, depth + 1);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
for index in 0..node.children.len() {
|
||||
let (category, reclaim) =
|
||||
kind_of(&node.children, index, category, reclaim);
|
||||
classify_below(
|
||||
&mut node.children[index],
|
||||
category,
|
||||
reclaim,
|
||||
depth + 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the child at `index` is, given what its parent is: its own name
|
||||
/// wins, otherwise it inherits. A file always inherits.
|
||||
fn kind_of(
|
||||
siblings: &[Node],
|
||||
index: usize,
|
||||
category: Category,
|
||||
reclaim: Option<Reclaim>,
|
||||
) -> (Category, Option<Reclaim>) {
|
||||
let child = &siblings[index];
|
||||
if !child.is_dir() {
|
||||
return (category, reclaim);
|
||||
}
|
||||
let has_sibling =
|
||||
|wanted: &str| siblings.iter().any(|name| &*name.name == wanted);
|
||||
let child_category = category_of_name(&child.name)
|
||||
.or_else(|| is_git_store(child).then_some(Category::Git))
|
||||
.unwrap_or(category);
|
||||
let child_reclaim =
|
||||
reclaim.or_else(|| reclaim_of(&child.name, category, has_sibling));
|
||||
(child_category, child_reclaim)
|
||||
}
|
||||
|
||||
/// The kind of an unknown directory, from what fills it: the first
|
||||
/// recognisable name down the largest children, a few levels deep.
|
||||
fn dominant_child_category(node: &Node) -> Option<Category> {
|
||||
@@ -375,6 +426,41 @@ mod tests {
|
||||
node
|
||||
}
|
||||
|
||||
/// Regression: a Steam library on a second drive was named by the
|
||||
/// `temp` folder Steam keeps in `steamapps`, so a disk of games showed
|
||||
/// as cache.
|
||||
#[test]
|
||||
fn a_steam_library_on_another_drive_is_media_not_its_temp_folder() {
|
||||
let mut root = dir(
|
||||
"data",
|
||||
vec![dir(
|
||||
"SteamLibrary",
|
||||
vec![dir(
|
||||
"steamapps",
|
||||
vec![
|
||||
dir("temp", vec![file("partial", 1)]),
|
||||
dir("common", vec![file("game.pak", 1_000)]),
|
||||
],
|
||||
)],
|
||||
)],
|
||||
);
|
||||
aggregate(&mut root, Metric::Bytes);
|
||||
classify(&mut root);
|
||||
let library = &root.children[0];
|
||||
assert_eq!(library.category, Category::Media);
|
||||
let common = library.children[0].child_named("common").expect("common");
|
||||
assert_eq!(common.category, Category::Media);
|
||||
assert_eq!(common.reclaim, None, "installed games are not hatched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn steam_libraries_and_emulation_are_media_not_disposable_caches() {
|
||||
for name in ["SteamLibrary", "steamapps", "Emulation"] {
|
||||
assert_eq!(category_of_name(name), Some(Category::Media));
|
||||
assert_eq!(reclaim_of(name, Category::Other, |_| false), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_announce_their_kind_and_children_inherit_it() {
|
||||
let home = home();
|
||||
@@ -504,7 +590,13 @@ mod tests {
|
||||
);
|
||||
assert_eq!(category_of_name(name), Some(Category::Cache), "{name}");
|
||||
}
|
||||
for name in ["OneDrive - Contoso", "Dropbox (Contoso)", "iCloudDrive"] {
|
||||
for name in [
|
||||
"OneDrive - Contoso",
|
||||
// Past the stack buffer for lowercasing.
|
||||
"OneDrive - Contoso Pharmaceuticals International",
|
||||
"Dropbox (Contoso)",
|
||||
"iCloudDrive",
|
||||
] {
|
||||
assert_eq!(
|
||||
category_of_name(name),
|
||||
Some(Category::Synced),
|
||||
|
||||
@@ -60,7 +60,9 @@ fn visit(
|
||||
now: i64,
|
||||
found: &mut Vec<Candidate>,
|
||||
) {
|
||||
if !node.is_dir() {
|
||||
// Nothing beneath a small directory can reach `MIN_BYTES` either, so a
|
||||
// scan of millions of files looks at a few thousand directories.
|
||||
if !node.is_dir() || node.bytes < MIN_BYTES {
|
||||
return;
|
||||
}
|
||||
// Topmost only: everything beneath a reclaimable directory goes with it.
|
||||
@@ -72,9 +74,9 @@ fn visit(
|
||||
});
|
||||
return;
|
||||
}
|
||||
let name = node.name.to_ascii_lowercase();
|
||||
let name = &*node.name;
|
||||
let scratch = node.category == Category::AgentScratch;
|
||||
if scratch && name == "worktrees" {
|
||||
if scratch && name.eq_ignore_ascii_case("worktrees") {
|
||||
let trees: Vec<&Node> = node
|
||||
.children
|
||||
.iter()
|
||||
@@ -98,8 +100,9 @@ fn visit(
|
||||
return;
|
||||
}
|
||||
}
|
||||
let experiments =
|
||||
scratch && matches!(name.as_str(), "tries" | "experiments");
|
||||
let experiments = scratch
|
||||
&& (name.eq_ignore_ascii_case("tries")
|
||||
|| name.eq_ignore_ascii_case("experiments"));
|
||||
let mut stale = (0_usize, 0_u64);
|
||||
for (index, child) in node.children.iter().enumerate() {
|
||||
let is_stale = experiments
|
||||
|
||||
@@ -10,6 +10,8 @@ pub mod classify;
|
||||
pub mod export;
|
||||
pub mod filter;
|
||||
pub mod insights;
|
||||
#[cfg(windows)]
|
||||
mod mft;
|
||||
pub mod removal;
|
||||
pub mod scan;
|
||||
pub mod scan_threads;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -113,9 +113,10 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
|
||||
for target in targets {
|
||||
let path = normalize(&target.path);
|
||||
let reason =
|
||||
refuse(&path, &root, home.as_ref(), &mounts).or_else(|| {
|
||||
linked(&path, &root, real_root.as_deref(), home.as_ref())
|
||||
});
|
||||
refuse(&path, &root, home.as_ref(), &mounts.points, &mounts.media)
|
||||
.or_else(|| {
|
||||
linked(&path, &root, real_root.as_deref(), home.as_ref())
|
||||
});
|
||||
if let Some(reason) = reason {
|
||||
plan.blocked.push(Blocked {
|
||||
path: target.path.clone(),
|
||||
@@ -364,6 +365,7 @@ fn refuse(
|
||||
root: &Path,
|
||||
home: Option<&Home>,
|
||||
mounts: &[PathBuf],
|
||||
media: &[PathBuf],
|
||||
) -> Option<String> {
|
||||
let key = guard_key(path);
|
||||
let root_key = guard_key(root);
|
||||
@@ -400,12 +402,25 @@ fn refuse(
|
||||
if home_key.is_some_and(|home| home.starts_with(&key)) {
|
||||
return Some("it contains the home directory".into());
|
||||
}
|
||||
// Elevated through another account's credentials, home is that admin's,
|
||||
// and the user's own profile is just another folder; elevation opens
|
||||
// every other profile too. So on Windows each directory in the profiles
|
||||
// folder (`C:\Users\tobi`, `Public`, `Default`) is refused, taken from
|
||||
// Windows and not from home, whose parent could be anything. What is
|
||||
// inside a profile stays removable, as under one's own home.
|
||||
if profiles_key().is_some_and(|profiles| is_profile(path, &key, profiles)) {
|
||||
return Some("a user profile cannot be removed".into());
|
||||
}
|
||||
// By spelling too: the Data volume's root keeps its name as a key, while
|
||||
// everything under it is keyed as under `/`.
|
||||
if !key.starts_with(&root_key) && !path.starts_with(root) {
|
||||
return Some("outside the scanned root".into());
|
||||
}
|
||||
if let Some(system) = system_tree(&key, home_key) {
|
||||
if let Some(system) = system_tree(&key, home_key)
|
||||
&& !(system == "/run"
|
||||
&& on_media(&key, mounts, media)
|
||||
&& fs::canonicalize(path).is_ok_and(|real| real == path))
|
||||
{
|
||||
return Some(format!(
|
||||
"part of the system under {system}: {SYSTEM_TOOLS}"
|
||||
));
|
||||
@@ -415,7 +430,7 @@ fn refuse(
|
||||
"it contains {system}, which is part of the system"
|
||||
));
|
||||
}
|
||||
if is_mount_point(path) {
|
||||
if mounts.contains(&key) || is_mount_point(path) {
|
||||
return Some(
|
||||
"a mount point: removing it would cross onto another filesystem"
|
||||
.into(),
|
||||
@@ -524,10 +539,81 @@ const fn identity(_path: &Path, _follow: bool) -> Option<(u64, u64)> {
|
||||
/// mount boundary whatever the table said.
|
||||
const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// Paths and safe media exceptions must come from the same snapshot.
|
||||
#[derive(Default)]
|
||||
struct MountTable {
|
||||
points: Vec<PathBuf>,
|
||||
media: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
fn read_mount_table() -> MountTable {
|
||||
if let Ok(table) = fs::read_to_string("/proc/self/mountinfo") {
|
||||
let views = crate::space::parse_mountinfo(&table);
|
||||
return MountTable {
|
||||
points: views.iter().map(|mount| guard_key(&mount.point)).collect(),
|
||||
media: media_roots(&views),
|
||||
};
|
||||
}
|
||||
MountTable {
|
||||
points: read_mount_points(),
|
||||
media: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Only real disks mounted by the desktop under /run/media qualify. A
|
||||
/// directory with that spelling, a bind of a system tree, and virtual
|
||||
/// filesystems retain the /run guard. Missing information fails closed.
|
||||
fn media_roots(mounts: &[crate::space::MountView]) -> Vec<PathBuf> {
|
||||
mounts
|
||||
.iter()
|
||||
.filter(|mount| {
|
||||
mount.point.starts_with("/run/media")
|
||||
&& mount.point != Path::new("/run/media")
|
||||
// An overmounted disk can remain in mountinfo. Ambiguous
|
||||
// stacked views must never grant a deletion exception.
|
||||
&& mounts.iter().filter(|other| other.point == mount.point).count() == 1
|
||||
&& mount.fs_root == Path::new("/")
|
||||
&& mount.source.starts_with("/dev/")
|
||||
&& matches!(
|
||||
mount.fstype.as_str(),
|
||||
"ext2"
|
||||
| "ext3"
|
||||
| "ext4"
|
||||
| "btrfs"
|
||||
| "xfs"
|
||||
| "f2fs"
|
||||
| "vfat"
|
||||
| "exfat"
|
||||
| "ntfs"
|
||||
| "ntfs3"
|
||||
| "fuseblk"
|
||||
| "fuse.ntfs-3g"
|
||||
)
|
||||
&& !mounts.iter().any(|other| {
|
||||
!other.point.starts_with("/run/media")
|
||||
&& (other.point == Path::new("/")
|
||||
|| system_tree(&other.point, None).is_some())
|
||||
&& (other.device == mount.device
|
||||
|| other.source == mount.source)
|
||||
})
|
||||
})
|
||||
.map(|mount| mount.point.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn on_media(key: &Path, mounts: &[PathBuf], media: &[PathBuf]) -> bool {
|
||||
// Nested mounts do not inherit their parent's exception.
|
||||
mounts
|
||||
.iter()
|
||||
.filter(|point| key.starts_with(point))
|
||||
.max_by_key(|point| point.components().count())
|
||||
.is_some_and(|point| key != point && media.contains(point))
|
||||
}
|
||||
|
||||
/// The last read of the mount table, and whether a read is under way.
|
||||
struct MountCache {
|
||||
read: Option<std::time::Instant>,
|
||||
mounts: Option<Arc<Vec<PathBuf>>>,
|
||||
mounts: Option<Arc<MountTable>>,
|
||||
refreshing: bool,
|
||||
}
|
||||
|
||||
@@ -545,7 +631,7 @@ static MOUNTS: std::sync::Mutex<MountCache> =
|
||||
/// its own thread and is used meanwhile; before the first read lands it is
|
||||
/// empty, which is why the app primes it at start with
|
||||
/// [`prime_mount_points`].
|
||||
fn mount_points() -> Arc<Vec<PathBuf>> {
|
||||
fn mount_points() -> Arc<MountTable> {
|
||||
let mut cache = MOUNTS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -555,7 +641,7 @@ fn mount_points() -> Arc<Vec<PathBuf>> {
|
||||
let spawned = thread::Builder::new()
|
||||
.name("disktree-mounts".into())
|
||||
.spawn(|| {
|
||||
let mounts = Arc::new(read_mount_points());
|
||||
let mounts = Arc::new(read_mount_table());
|
||||
let mut cache = MOUNTS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -616,6 +702,29 @@ const fn windows_mount_points() -> Vec<PathBuf> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The key of the folder every user profile is in, `C:\Users` as
|
||||
/// installed; asked of Windows once, since it does not move while running.
|
||||
#[cfg(windows)]
|
||||
fn profiles_key() -> Option<&'static Path> {
|
||||
static PROFILES: std::sync::LazyLock<Option<PathBuf>> =
|
||||
std::sync::LazyLock::new(|| {
|
||||
crate::windows::user_profiles_dir().map(|dir| guard_key(&dir))
|
||||
});
|
||||
PROFILES.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
const fn profiles_key() -> Option<&'static Path> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `path`, keyed `key`, is a profile: a directory directly in
|
||||
/// `profiles`. A file or a link there is no profile and stays removable.
|
||||
fn is_profile(path: &Path, key: &Path, profiles: &Path) -> bool {
|
||||
key.parent() == Some(profiles)
|
||||
&& fs::symlink_metadata(path).is_ok_and(|meta| meta.is_dir())
|
||||
}
|
||||
|
||||
/// A mount point strictly inside the path keyed `key`, if there is one. A
|
||||
/// scan that stays on one filesystem never shows what is mounted there, so
|
||||
/// the user cannot have meant to remove it.
|
||||
@@ -887,7 +996,7 @@ fn run(
|
||||
// The plan was judged against a mount table up to `MOUNTS_FRESH` old,
|
||||
// or, right after start, not read yet. Judged again against a fresh
|
||||
// read, here on the worker, before anything is touched.
|
||||
let mounts = read_mount_points();
|
||||
let mounts = read_mount_table();
|
||||
// Links too: one put on the way down since the plan was made would lead
|
||||
// the trash out of the root. Permanent removal on Unix refuses that by
|
||||
// itself; see [`open_parent`].
|
||||
@@ -898,14 +1007,30 @@ fn run(
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let reason = mounted(&target.path, &mounts).or_else(|| {
|
||||
linked(
|
||||
&target.path,
|
||||
&plan.root,
|
||||
real_root.as_deref(),
|
||||
home.as_ref(),
|
||||
)
|
||||
});
|
||||
// The /run/media exception must still hold when removal starts;
|
||||
// a disk may have been unmounted since the review was displayed.
|
||||
let reason = target
|
||||
.path
|
||||
.starts_with("/run/media")
|
||||
.then(|| {
|
||||
refuse(
|
||||
&target.path,
|
||||
&plan.root,
|
||||
home.as_ref(),
|
||||
&mounts.points,
|
||||
&mounts.media,
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
.or_else(|| mounted(&target.path, &mounts.points))
|
||||
.or_else(|| {
|
||||
linked(
|
||||
&target.path,
|
||||
&plan.root,
|
||||
real_root.as_deref(),
|
||||
home.as_ref(),
|
||||
)
|
||||
});
|
||||
let outcome = if let Some(reason) = reason {
|
||||
Err(io::Error::other(reason))
|
||||
} else {
|
||||
@@ -929,6 +1054,18 @@ fn run(
|
||||
});
|
||||
}
|
||||
|
||||
// NTFS writes the file table's records lazily, and the elevated rescan
|
||||
// of a whole drive reads that table from disk, past the cache:
|
||||
// unflushed, the removed entries would still show. Only then; a folder
|
||||
// is walked. Failing only lets the table lag again.
|
||||
#[cfg(windows)]
|
||||
if removed > 0
|
||||
&& plan.root.parent().is_none()
|
||||
&& crate::access::administrator() == Some(true)
|
||||
{
|
||||
let _ = crate::windows::flush_volume(&plan.root);
|
||||
}
|
||||
|
||||
let _ = sender.send(RemovalEvent::Done {
|
||||
removed,
|
||||
bytes,
|
||||
@@ -1425,6 +1562,134 @@ mod tests {
|
||||
temp
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn desktop_media_exception_requires_an_independent_disk() {
|
||||
let views = crate::space::parse_mountinfo(
|
||||
"1 0 8:1 / / rw - ext4 /dev/root rw\n\
|
||||
2 1 0:20 / /run rw - tmpfs tmpfs rw\n\
|
||||
3 2 8:2 / /run/media/user/Games rw - ext4 /dev/sdb rw\n\
|
||||
4 2 8:1 / /run/media/user/System rw - ext4 /dev/root rw\n\
|
||||
5 2 8:2 /folder /run/media/user/Bind rw - ext4 /dev/sdb rw\n\
|
||||
6 2 0:21 / /run/media/user/Virtual rw - tmpfs tmpfs rw\n\
|
||||
7 3 8:1 /etc /run/media/user/Games/nested rw - ext4 /dev/root rw\n",
|
||||
);
|
||||
let media = media_roots(&views);
|
||||
assert_eq!(media, [PathBuf::from("/run/media/user/Games")]);
|
||||
let points: Vec<_> =
|
||||
views.iter().map(|view| view.point.clone()).collect();
|
||||
assert!(on_media(
|
||||
Path::new("/run/media/user/Games/game"),
|
||||
&points,
|
||||
&media
|
||||
));
|
||||
for path in [
|
||||
"/run/media/user/Games",
|
||||
"/run/media/user/Games/nested/file",
|
||||
"/run/media/user/System/etc",
|
||||
"/run/media/user/Bind/file",
|
||||
"/run/media/user/Virtual/file",
|
||||
"/run/media/user/NotMounted/file",
|
||||
"/run/user/1000/file",
|
||||
] {
|
||||
assert!(!on_media(Path::new(path), &points, &media), "{path}");
|
||||
}
|
||||
let mut stacked = views.clone();
|
||||
let mut covering = views[3].clone();
|
||||
covering.point = PathBuf::from("/run/media/user/Games");
|
||||
stacked.push(covering);
|
||||
assert!(media_roots(&stacked).is_empty(), "overmounted disk");
|
||||
assert!(media_roots(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// Run in a private mount namespace with the fixture described in
|
||||
/// scripts/test-linux-mounts.sh. Never changes the host's mount table.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
#[ignore = "requires the isolated mount fixture"]
|
||||
fn mounted_media_and_repeated_views() {
|
||||
let table =
|
||||
fs::read_to_string("/proc/self/mountinfo").expect("mountinfo");
|
||||
assert!(
|
||||
crate::space::parse_mountinfo(&table)
|
||||
.iter()
|
||||
.any(|mount| mount.point == Path::new("/run")
|
||||
&& mount.source == "disktree-test-run")
|
||||
);
|
||||
let root = Path::new("/run/media/disktree-test");
|
||||
let mounts = read_mount_points();
|
||||
// User namespaces cannot mount a block device. Supply the media
|
||||
// classification separately; the table-policy test above covers it.
|
||||
let media = vec![root.to_path_buf()];
|
||||
let file = root.join("game");
|
||||
fs::write(&file, b"game").expect("fixture");
|
||||
assert_eq!(refuse(&file, root, None, &mounts, &media), None);
|
||||
assert!(refuse(root, Path::new("/"), None, &mounts, &media).is_some());
|
||||
assert!(refuse(&file, root, None, &mounts, &[]).is_some());
|
||||
std::os::unix::fs::symlink("/etc", root.join("link")).expect("link");
|
||||
assert!(
|
||||
refuse(
|
||||
&root.join("link/passwd"),
|
||||
&root.join("link"),
|
||||
None,
|
||||
&mounts,
|
||||
&media
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
fs::write(root.join("nested/keep"), b"keep").expect("nested");
|
||||
assert!(
|
||||
refuse(&root.join("nested/keep"), root, None, &mounts, &media)
|
||||
.is_some()
|
||||
);
|
||||
remove_permanently(&file, root).expect("delete marked game");
|
||||
assert!(!file.exists());
|
||||
assert!(root.join("nested/keep").exists());
|
||||
|
||||
let scan_root = Path::new("/run/disktree-scan");
|
||||
let options = crate::scan::ScanOptions {
|
||||
apparent_size: true,
|
||||
one_filesystem: false,
|
||||
..crate::scan::ScanOptions::default()
|
||||
};
|
||||
let tree = crate::scan::scan(scan_root, options.clone()).expect("scan");
|
||||
for name in ["one", "two", "original"] {
|
||||
assert!(
|
||||
tree.children.iter().any(|child| &*child.name == name),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
assert!(!tree.children.iter().any(|child| &*child.name == "alias"));
|
||||
assert_eq!(tree.files, 3);
|
||||
assert_eq!(tree.bytes, 12);
|
||||
assert!(
|
||||
std::process::Command::new("mount")
|
||||
.args([
|
||||
"-t",
|
||||
"tmpfs",
|
||||
"tmpfs",
|
||||
"/run/disktree-scan/alias/nested"
|
||||
])
|
||||
.status()
|
||||
.expect("nested mount")
|
||||
.success()
|
||||
);
|
||||
fs::write(scan_root.join("alias/nested/unique"), b"unique")
|
||||
.expect("unique");
|
||||
let tree = crate::scan::scan(scan_root, options).expect("rescan");
|
||||
let alias = tree
|
||||
.children
|
||||
.iter()
|
||||
.find(|child| &*child.name == "alias")
|
||||
.expect("alias retained");
|
||||
assert!(
|
||||
alias
|
||||
.children
|
||||
.iter()
|
||||
.any(|child| &*child.name == "nested" && child.files == 1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plan_keeps_only_the_outermost_targets() {
|
||||
let temp = tree();
|
||||
@@ -1471,15 +1736,21 @@ mod tests {
|
||||
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), &[]);
|
||||
refuse(Path::new("/home"), Path::new("/"), Some(&home), &[], &[]);
|
||||
assert!(
|
||||
reason.is_some_and(|reason| reason.contains("home directory")),
|
||||
"the home directory is inside it"
|
||||
);
|
||||
assert_eq!(
|
||||
refuse(Path::new("/home/other"), Path::new("/"), Some(&home), &[]),
|
||||
refuse(
|
||||
Path::new("/home/other"),
|
||||
Path::new("/"),
|
||||
Some(&home),
|
||||
&[],
|
||||
&[]
|
||||
),
|
||||
None,
|
||||
"a sibling of home is not"
|
||||
"a sibling of home is not above it"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1535,6 +1806,7 @@ mod tests {
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.expect("refused");
|
||||
assert!(reason.contains("home directory"), "{reason}");
|
||||
@@ -1543,6 +1815,7 @@ mod tests {
|
||||
Path::new("/Users/tobi/src"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[]
|
||||
)
|
||||
.is_none(),
|
||||
@@ -1561,6 +1834,7 @@ mod tests {
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.expect("refused");
|
||||
assert!(reason.contains(inside), "{path}: {reason}");
|
||||
@@ -1570,6 +1844,7 @@ mod tests {
|
||||
Path::new("/opt/local"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[]
|
||||
)
|
||||
.is_none(),
|
||||
@@ -1593,9 +1868,12 @@ mod tests {
|
||||
"itself"
|
||||
);
|
||||
let reason =
|
||||
refuse(&root.join("a"), root, None, &mounts).expect("refused");
|
||||
refuse(&root.join("a"), root, None, &mounts, &[]).expect("refused");
|
||||
assert!(reason.contains("mounted inside"), "{reason}");
|
||||
assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None);
|
||||
assert_eq!(
|
||||
refuse(&root.join("a/one.bin"), root, None, &mounts, &[]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1627,13 +1905,17 @@ mod tests {
|
||||
// The first read lands on its own thread; wait for it, briefly.
|
||||
let mut mounts = mount_points();
|
||||
for _ in 0..500 {
|
||||
if !mounts.is_empty() {
|
||||
if !mounts.points.is_empty() {
|
||||
break;
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(10));
|
||||
mounts = mount_points();
|
||||
}
|
||||
assert_eq!(*mounts, read_mount_points(), "the same table, cached");
|
||||
assert_eq!(
|
||||
mounts.points,
|
||||
read_mount_table().points,
|
||||
"the same table, cached"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1699,6 +1981,7 @@ mod tests {
|
||||
&data.join("Users/tobi/src"),
|
||||
data,
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[]
|
||||
)
|
||||
.is_none(),
|
||||
@@ -1709,6 +1992,7 @@ mod tests {
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.expect("refused");
|
||||
assert!(reason.contains("/Library"), "{reason}");
|
||||
@@ -2146,6 +2430,7 @@ mod tests {
|
||||
&drive,
|
||||
Some(&Home::of(&home)),
|
||||
&[],
|
||||
&[],
|
||||
);
|
||||
assert!(
|
||||
reason.is_some_and(|reason| reason
|
||||
@@ -2155,6 +2440,31 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_profiles_are_refused() {
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let profiles = temp.path();
|
||||
fs::create_dir_all(profiles.join(r"tobi\Downloads")).expect("mkdir");
|
||||
fs::write(profiles.join("notes.txt"), b"x").expect("write");
|
||||
let profile = |relative: &str| {
|
||||
let path = profiles.join(relative);
|
||||
is_profile(&path, &guard_key(&path), &guard_key(profiles))
|
||||
};
|
||||
assert!(profile("tobi"));
|
||||
assert!(profile("TOBI"), "compared as Windows compares names");
|
||||
assert!(!profile("notes.txt"), "a file there is no profile");
|
||||
assert!(!profile(r"tobi\Downloads"), "inside a profile is not one");
|
||||
assert!(!profile("gone"), "nothing there is no profile");
|
||||
|
||||
// The rule itself, against the profiles folder Windows reports.
|
||||
let public = crate::windows::user_profiles_dir()
|
||||
.expect("profiles folder")
|
||||
.join("Public");
|
||||
let reason = refuse(&public, &system_drive(), None, &[], &[]);
|
||||
assert!(reason.is_some_and(|reason| reason.contains("profile")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_always_uses_the_system_trash() {
|
||||
@@ -2230,6 +2540,7 @@ mod tests {
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
&[],
|
||||
);
|
||||
assert!(reason.is_some_and(|reason| reason.contains("/etc")));
|
||||
}
|
||||
|
||||
+348
-154
@@ -8,8 +8,8 @@
|
||||
//! `+1` sentinel, so a directory is only built once its own scan *and* all of
|
||||
//! its subdirectory tasks have finished,
|
||||
//! * children are handed to the parent as finished `Node`s and sizes are
|
||||
//! aggregated bottom-up in one serial pass, which is also where hardlinks are
|
||||
//! de-duplicated.
|
||||
//! aggregated bottom-up in one pass over the finished tree, which is also
|
||||
//! where hardlinks are de-duplicated.
|
||||
//!
|
||||
//! What is added on top of dust's approach: live progress counters the UI can
|
||||
//! poll without locking, and cooperative cancellation so a re-scan can abandon
|
||||
@@ -22,14 +22,14 @@ use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, TryRecvError};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
use std::thread;
|
||||
|
||||
use rayon::Scope;
|
||||
use rustc_hash::FxHashSet;
|
||||
|
||||
use crate::scan_threads::{Admission, ControllerGuard, ScanThreads};
|
||||
use crate::tree::{Metric, Node, NodeKind, aggregate};
|
||||
use crate::tree::{Metric, Node, NodeKind, Seen, aggregate, aggregate_deduped};
|
||||
|
||||
/// Errors kept verbatim before the list is truncated; the count keeps rising.
|
||||
const MAX_ERROR_DETAIL: usize = 50;
|
||||
@@ -124,13 +124,21 @@ impl ScanProgress {
|
||||
self.files.load(Ordering::Relaxed) + self.dirs.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn count_file(&self, bytes: u64) {
|
||||
self.files.fetch_add(1, Ordering::Relaxed);
|
||||
/// What a directory's listing found (see `Tally`), or what a reader
|
||||
/// that measures in bulk has come across so far.
|
||||
pub(crate) fn add(&self, files: u64, dirs: u64, bytes: u64) {
|
||||
self.files.fetch_add(files, Ordering::Relaxed);
|
||||
self.dirs.fetch_add(dirs, Ordering::Relaxed);
|
||||
self.bytes.fetch_add(bytes, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn count_dir(&self) {
|
||||
self.dirs.fetch_add(1, Ordering::Relaxed);
|
||||
/// The totals of the finished tree, replacing a bulk reader's running
|
||||
/// count: it met the whole volume, and the tree may be less of it.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn settle(&self, files: u64, dirs: u64, bytes: u64) {
|
||||
self.files.store(files, Ordering::Relaxed);
|
||||
self.dirs.store(dirs, Ordering::Relaxed);
|
||||
self.bytes.store(bytes, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn record_error(&self, path: &Path, error: &io::Error) {
|
||||
@@ -217,6 +225,7 @@ impl ScanHandle {
|
||||
never_scanned: OnceLock::new(),
|
||||
visited_dirs: Mutex::new(FxHashSet::default()),
|
||||
root: Mutex::new(None),
|
||||
volume: OnceLock::new(),
|
||||
});
|
||||
let (sender, result) = mpsc::channel();
|
||||
|
||||
@@ -266,6 +275,7 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result<Node> {
|
||||
never_scanned: OnceLock::new(),
|
||||
visited_dirs: Mutex::new(FxHashSet::default()),
|
||||
root: Mutex::new(None),
|
||||
volume: OnceLock::new(),
|
||||
});
|
||||
let node = scan_blocking(root, &context)?;
|
||||
progress.finish();
|
||||
@@ -290,6 +300,10 @@ struct WalkContext {
|
||||
visited_dirs: Mutex<FxHashSet<(u64, u64)>>,
|
||||
/// Set by the root's `complete`, read after the scope joins.
|
||||
root: Mutex<Option<Node>>,
|
||||
/// Serial number of the root's volume, on Windows, for a walk that
|
||||
/// cannot leave it: every listing takes it instead of asking. See
|
||||
/// [`crate::windows::walk_volume`].
|
||||
volume: OnceLock<u64>,
|
||||
}
|
||||
|
||||
impl WalkContext {
|
||||
@@ -307,33 +321,41 @@ impl WalkContext {
|
||||
self.progress.is_cancelled()
|
||||
}
|
||||
|
||||
/// Decide what to do with an entry, and account for the work it implies.
|
||||
fn classify(&self, entry: &impl Listed) -> Classified {
|
||||
let path = entry.entry_path();
|
||||
/// Decide what to do with an entry listed in `dir`.
|
||||
///
|
||||
/// The entry's path is built only where it is used: most entries are
|
||||
/// files, and a disk has millions of them. The name is moved out of
|
||||
/// the entry last, so nothing copies it.
|
||||
fn classify(&self, dir: &Path, entry: &mut impl Listed) -> Classified {
|
||||
let listing = match entry.listing() {
|
||||
Ok(listing) => listing,
|
||||
Err(error) => {
|
||||
self.progress.record_error(&path, &error);
|
||||
self.progress.record_error(&entry.entry_path(dir), &error);
|
||||
return Classified::Skipped;
|
||||
}
|
||||
};
|
||||
let name = entry.display_name();
|
||||
|
||||
if !self.options.include_hidden
|
||||
&& (name.starts_with('.') || entry.hidden())
|
||||
&& (entry.name().starts_with('.') || entry.hidden())
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
|
||||
let kind = match listing {
|
||||
Listing::Symlink => return self.classify_symlink(&path, name),
|
||||
Listing::Directory => return self.classify_dir(entry, path, name),
|
||||
Listing::Symlink => {
|
||||
let path = entry.entry_path(dir);
|
||||
return self.classify_symlink(&path, entry.take_name());
|
||||
}
|
||||
Listing::Directory => {
|
||||
let path = entry.entry_path(dir);
|
||||
return self.classify_dir(entry, path);
|
||||
}
|
||||
Listing::Leaf(kind) => kind,
|
||||
};
|
||||
match entry.facts(self.options.apparent_size) {
|
||||
Ok(facts) => self.leaf(name, kind, &facts),
|
||||
Ok(facts) => self.leaf(entry.take_name(), kind, &facts),
|
||||
Err(error) => {
|
||||
self.progress.record_error(&path, &error);
|
||||
self.progress.record_error(&entry.entry_path(dir), &error);
|
||||
Classified::Skipped
|
||||
}
|
||||
}
|
||||
@@ -341,9 +363,8 @@ impl WalkContext {
|
||||
|
||||
fn classify_dir(
|
||||
&self,
|
||||
entry: &impl Listed,
|
||||
entry: &mut impl Listed,
|
||||
path: PathBuf,
|
||||
name: Box<str>,
|
||||
) -> Classified {
|
||||
if self
|
||||
.never_scanned
|
||||
@@ -370,12 +391,8 @@ impl WalkContext {
|
||||
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;
|
||||
let mut tree = (*known.tree).clone();
|
||||
tree.name = entry.take_name();
|
||||
return Classified::Entry(tree);
|
||||
}
|
||||
if self.options.one_filesystem
|
||||
@@ -400,8 +417,10 @@ impl WalkContext {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.progress.count_dir();
|
||||
Classified::Subdirectory(path)
|
||||
Classified::Subdirectory {
|
||||
path,
|
||||
name: entry.take_name(),
|
||||
}
|
||||
}
|
||||
|
||||
fn classify_symlink(&self, path: &Path, name: Box<str>) -> Classified {
|
||||
@@ -411,7 +430,6 @@ impl WalkContext {
|
||||
return match fs::symlink_metadata(path) {
|
||||
Ok(meta) => {
|
||||
let facts = Facts::of(&meta, self.options.apparent_size);
|
||||
self.progress.count_file(facts.size);
|
||||
Classified::Entry(leaf_node(
|
||||
name,
|
||||
NodeKind::Symlink,
|
||||
@@ -448,8 +466,10 @@ impl WalkContext {
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
self.progress.count_dir();
|
||||
return Classified::Subdirectory(path.to_path_buf());
|
||||
return Classified::Subdirectory {
|
||||
path: path.to_path_buf(),
|
||||
name,
|
||||
};
|
||||
}
|
||||
|
||||
let mut facts = Facts::of(&meta, self.options.apparent_size);
|
||||
@@ -465,7 +485,6 @@ impl WalkContext {
|
||||
kind: NodeKind,
|
||||
facts: &Facts,
|
||||
) -> Classified {
|
||||
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 || facts.shared;
|
||||
@@ -480,10 +499,14 @@ impl WalkContext {
|
||||
/// would cost an open per file; [`crate::windows`] lists a directory with
|
||||
/// both instead.
|
||||
trait Listed {
|
||||
fn entry_path(&self) -> PathBuf;
|
||||
/// The entry's path inside `dir`, the directory it was listed from.
|
||||
fn entry_path(&self, dir: &Path) -> 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 name(&self) -> &str;
|
||||
/// The name, moved out for the tree: after this `name` is empty, and
|
||||
/// `entry_path`, which must open the real file, is off limits.
|
||||
fn take_name(&mut 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>;
|
||||
@@ -541,18 +564,29 @@ impl Facts {
|
||||
}
|
||||
}
|
||||
|
||||
/// A standard directory entry with its name decoded once, up front.
|
||||
#[cfg(not(windows))]
|
||||
impl Listed for DirEntry {
|
||||
fn entry_path(&self) -> PathBuf {
|
||||
self.path()
|
||||
struct Named {
|
||||
entry: DirEntry,
|
||||
name: Box<str>,
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
impl Listed for Named {
|
||||
fn entry_path(&self, _dir: &Path) -> PathBuf {
|
||||
self.entry.path()
|
||||
}
|
||||
|
||||
fn display_name(&self) -> Box<str> {
|
||||
self.file_name().to_string_lossy().into_owned().into()
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn take_name(&mut self) -> Box<str> {
|
||||
std::mem::take(&mut self.name)
|
||||
}
|
||||
|
||||
fn listing(&self) -> io::Result<Listing> {
|
||||
let file_type = self.file_type()?;
|
||||
let file_type = self.entry.file_type()?;
|
||||
Ok(if file_type.is_symlink() {
|
||||
Listing::Symlink
|
||||
} else if file_type.is_dir() {
|
||||
@@ -565,11 +599,13 @@ impl Listed for DirEntry {
|
||||
}
|
||||
|
||||
fn facts(&self, apparent_size: bool) -> io::Result<Facts> {
|
||||
self.metadata().map(|meta| Facts::of(&meta, apparent_size))
|
||||
self.entry
|
||||
.metadata()
|
||||
.map(|meta| Facts::of(&meta, apparent_size))
|
||||
}
|
||||
|
||||
fn directory(&self) -> io::Result<Directory> {
|
||||
self.metadata().map(|meta| Directory {
|
||||
self.entry.metadata().map(|meta| Directory {
|
||||
device: device_of(&meta),
|
||||
evicted: is_dataless(&meta),
|
||||
})
|
||||
@@ -578,12 +614,16 @@ impl Listed for DirEntry {
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Listed for crate::windows::Entry {
|
||||
fn entry_path(&self) -> PathBuf {
|
||||
self.path()
|
||||
fn entry_path(&self, dir: &Path) -> PathBuf {
|
||||
self.path(dir)
|
||||
}
|
||||
|
||||
fn display_name(&self) -> Box<str> {
|
||||
self.file_name().to_string_lossy().into_owned().into()
|
||||
fn name(&self) -> &str {
|
||||
self.name()
|
||||
}
|
||||
|
||||
fn take_name(&mut self) -> Box<str> {
|
||||
self.take_name()
|
||||
}
|
||||
|
||||
fn listing(&self) -> io::Result<Listing> {
|
||||
@@ -626,19 +666,33 @@ impl Listed for crate::windows::Entry {
|
||||
|
||||
/// List a directory the way [`Listed`] describes.
|
||||
#[cfg(not(windows))]
|
||||
fn list(path: &Path) -> io::Result<fs::ReadDir> {
|
||||
fs::read_dir(path)
|
||||
fn list(
|
||||
path: &Path,
|
||||
_volume: Option<u64>,
|
||||
) -> io::Result<impl Iterator<Item = io::Result<Named>>> {
|
||||
Ok(fs::read_dir(path)?.map(|entry| {
|
||||
entry.map(|entry| Named {
|
||||
name: entry.file_name().into_string().map_or_else(
|
||||
|raw| raw.to_string_lossy().into(),
|
||||
String::into_boxed_str,
|
||||
),
|
||||
entry,
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn list(path: &Path) -> io::Result<crate::windows::ReadDir> {
|
||||
crate::windows::read_dir(path)
|
||||
fn list(
|
||||
path: &Path,
|
||||
volume: Option<u64>,
|
||||
) -> io::Result<crate::windows::ReadDir> {
|
||||
crate::windows::read_dir(path, volume)
|
||||
}
|
||||
|
||||
/// What a directory entry turned out to be.
|
||||
enum Classified {
|
||||
/// Descend into this directory on a new task.
|
||||
Subdirectory(PathBuf),
|
||||
Subdirectory { path: PathBuf, name: Box<str> },
|
||||
/// A leaf that contributes size.
|
||||
Entry(Node),
|
||||
/// Filtered out, unreadable, or a symlink we chose not to follow.
|
||||
@@ -653,15 +707,25 @@ struct PendingDir {
|
||||
/// Starts at 1 for the directory itself; one more per subdirectory task.
|
||||
/// When it reaches zero the directory is complete.
|
||||
pending: AtomicUsize,
|
||||
/// Files found directly here, and finished subdirectories handed back up.
|
||||
children: Mutex<Vec<Node>>,
|
||||
/// The node so far, moved out whole once the directory is complete.
|
||||
partial: Mutex<Partial>,
|
||||
read_error: AtomicBool,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// What a directory's node is made of before it is built: the name the
|
||||
/// listing gave it, and the files found directly in it plus the finished
|
||||
/// subdirectories handed back up.
|
||||
#[derive(Debug, Default)]
|
||||
struct Partial {
|
||||
name: Box<str>,
|
||||
children: Vec<Node>,
|
||||
}
|
||||
|
||||
impl PendingDir {
|
||||
const fn new(
|
||||
path: PathBuf,
|
||||
name: Box<str>,
|
||||
parent: Option<Arc<Self>>,
|
||||
depth: usize,
|
||||
) -> Self {
|
||||
@@ -669,21 +733,25 @@ impl PendingDir {
|
||||
path,
|
||||
parent,
|
||||
pending: AtomicUsize::new(1),
|
||||
children: Mutex::new(Vec::new()),
|
||||
partial: Mutex::new(Partial {
|
||||
name,
|
||||
children: Vec::new(),
|
||||
}),
|
||||
read_error: AtomicBool::new(false),
|
||||
depth,
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a completed directory into a node. Only called when `pending` has
|
||||
/// reached zero, so every child is already in `self.children`.
|
||||
/// reached zero, so every child is already in `self.partial`.
|
||||
///
|
||||
/// `bytes` and `own_bytes` are left at zero on purpose: the walk cannot
|
||||
/// know the aggregate, and [`crate::tree::aggregate`] derives both from the
|
||||
/// children once every child is present.
|
||||
fn build(&self) -> Node {
|
||||
let partial = std::mem::take(&mut *lock(&self.partial));
|
||||
Node {
|
||||
name: file_name(&self.path),
|
||||
name: partial.name,
|
||||
kind: NodeKind::Directory,
|
||||
bytes: 0,
|
||||
own_bytes: 0,
|
||||
@@ -695,7 +763,7 @@ impl PendingDir {
|
||||
modified: 0,
|
||||
category: crate::classify::Category::Other,
|
||||
reclaim: None,
|
||||
children: std::mem::take(&mut *lock(&self.children)),
|
||||
children: partial.children,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -708,56 +776,112 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
|
||||
format!("{} is not a directory", root.display()),
|
||||
));
|
||||
}
|
||||
let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
|
||||
let never = crate::space::never_scanned(root, &canonical);
|
||||
let resolved = root.canonicalize().ok();
|
||||
let canonical = resolved.as_deref().unwrap_or(root);
|
||||
let mut never = crate::space::never_scanned(root, canonical);
|
||||
// Hidden-entry and depth filters can leave an alias as the only route
|
||||
// to files. Keep every mount view when either filter is active.
|
||||
if context.options.include_hidden && context.options.max_depth.is_none() {
|
||||
never.extend(crate::space::repeated_mounts_for(
|
||||
root,
|
||||
canonical,
|
||||
context.options.one_filesystem,
|
||||
));
|
||||
}
|
||||
let _ = context.never_scanned.set(never.into_iter().collect());
|
||||
if context.options.one_filesystem {
|
||||
*lock(&context.root_device) = Some(device_of(&root_meta));
|
||||
if let Some(foreign) = crate::space::foreign_mounts_for(&canonical) {
|
||||
if let Some(foreign) = crate::space::foreign_mounts_for(canonical) {
|
||||
let _ = context.foreign_mounts.set(foreign.into_iter().collect());
|
||||
}
|
||||
}
|
||||
// Reading the file table is far faster than any walk, where the
|
||||
// volume allows it. On the walk's pool too: see `WALK_POOL`.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let progress = &context.progress;
|
||||
let read = WALK_POOL.install(|| {
|
||||
crate::mft::scan(root, canonical, &context.options, progress)
|
||||
});
|
||||
if let Some(node) = read {
|
||||
let node = node?;
|
||||
// Cancelled after the reader's last check: the rescan that
|
||||
// asked is waiting, and this tree is not wanted.
|
||||
if progress.is_cancelled() {
|
||||
return Err(crate::mft::cancelled());
|
||||
}
|
||||
let node = finish_tree(node, &context.options);
|
||||
// The reader counted every file on the volume; the tree may
|
||||
// hold fewer.
|
||||
progress.settle(node.files, node.dirs, node.bytes);
|
||||
return Ok(node);
|
||||
}
|
||||
// The reader gave up, or never started: the walk counts from nothing.
|
||||
progress.settle(0, 0, 0);
|
||||
// Asking once instead of per directory; see `walk_volume` for
|
||||
// when a walk that does not follow links cannot leave the volume.
|
||||
// Only on a resolved root: a mapped share's letter kept as typed
|
||||
// looks like a local drive.
|
||||
if !context.options.follow_links
|
||||
&& let Some(resolved) = &resolved
|
||||
&& let Some(serial) = crate::windows::walk_volume(resolved)
|
||||
{
|
||||
let _ = context.volume.set(serial);
|
||||
}
|
||||
}
|
||||
if context.options.follow_links
|
||||
&& let Some(key) = identity_of(root, &root_meta)
|
||||
{
|
||||
lock(&context.visited_dirs).insert(key);
|
||||
}
|
||||
|
||||
let root_dir = Arc::new(PendingDir::new(root.to_path_buf(), None, 0));
|
||||
let mut threads = context.options.threads.normalized();
|
||||
threads.max_threads = threads.max_threads.min(rayon::current_num_threads());
|
||||
context
|
||||
.progress
|
||||
.threads
|
||||
.store(threads.max_threads, Ordering::Relaxed);
|
||||
context
|
||||
.progress
|
||||
.threads_settled
|
||||
.store(true, Ordering::Relaxed);
|
||||
context
|
||||
.progress
|
||||
.thread_tuning_complete
|
||||
.store(!threads.adaptive, Ordering::Relaxed);
|
||||
if !threads.adaptive && threads.max_threads == rayon::current_num_threads()
|
||||
{
|
||||
// Pool-sized fixed scans need no admission lock or ready queue. Keep
|
||||
// existing core callers on Rayon's direct scheduling path.
|
||||
rayon::scope(|scope| {
|
||||
dispatch_fixed(scope, &root_dir, context);
|
||||
});
|
||||
} else {
|
||||
let admission = Arc::new(Admission::new(root_dir, threads.max_threads));
|
||||
// The controller owns no Rayon worker and is joined before finishing
|
||||
// the tree, where entry throughput no longer describes useful work.
|
||||
let _controller = ControllerGuard::spawn(
|
||||
threads,
|
||||
Arc::clone(&admission),
|
||||
Arc::clone(&context.progress),
|
||||
)?;
|
||||
rayon::scope(|scope| {
|
||||
dispatch(scope, admission.start(), context, &admission);
|
||||
});
|
||||
}
|
||||
let root_dir = Arc::new(PendingDir::new(
|
||||
root.to_path_buf(),
|
||||
file_name(root),
|
||||
None,
|
||||
0,
|
||||
));
|
||||
let context: &WalkContext = context;
|
||||
WALK_POOL.install(|| {
|
||||
let mut threads = context.options.threads.normalized();
|
||||
threads.max_threads =
|
||||
threads.max_threads.min(rayon::current_num_threads());
|
||||
context
|
||||
.progress
|
||||
.threads
|
||||
.store(threads.max_threads, Ordering::Relaxed);
|
||||
context
|
||||
.progress
|
||||
.threads_settled
|
||||
.store(true, Ordering::Relaxed);
|
||||
context
|
||||
.progress
|
||||
.thread_tuning_complete
|
||||
.store(!threads.adaptive, Ordering::Relaxed);
|
||||
if !threads.adaptive
|
||||
&& threads.max_threads == rayon::current_num_threads()
|
||||
{
|
||||
// Pool-sized fixed scans need no admission lock or ready queue. Keep
|
||||
// existing core callers on Rayon's direct scheduling path.
|
||||
rayon::scope(|scope| {
|
||||
dispatch_fixed(scope, &root_dir, context);
|
||||
});
|
||||
} else {
|
||||
let admission =
|
||||
Arc::new(Admission::new(root_dir, threads.max_threads));
|
||||
// The controller owns no Rayon worker and is joined before finishing
|
||||
// the tree, where entry throughput no longer describes useful work.
|
||||
let _controller = ControllerGuard::spawn(
|
||||
threads,
|
||||
Arc::clone(&admission),
|
||||
Arc::clone(&context.progress),
|
||||
)?;
|
||||
rayon::scope(|scope| {
|
||||
dispatch(scope, admission.start(), context, &admission);
|
||||
});
|
||||
}
|
||||
Ok::<(), io::Error>(())
|
||||
})?;
|
||||
|
||||
let node = lock(&context.root).take();
|
||||
let node = node.ok_or_else(|| {
|
||||
@@ -766,15 +890,72 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
|
||||
Ok(finish_tree(node, &context.options))
|
||||
}
|
||||
|
||||
fn dispatch_fixed(
|
||||
scope: &Scope<'_>,
|
||||
/// The walk's workers, and the file table reader's. Listing directories
|
||||
/// contends in the file system, and past some number of threads more of
|
||||
/// them only queue: on Windows a home directory of 3.4 million files
|
||||
/// walked in 6.5 s on 16 threads and 8.1 s on all 24. That cap was
|
||||
/// measured on one 24-thread NTFS laptop; another disk or CPU may want
|
||||
/// another. Elsewhere the default count. A pool of its own on every
|
||||
/// platform all the same: work the UI hands the global pool, such as
|
||||
/// re-ranking a tree, must not queue behind a scan's blocking reads.
|
||||
static WALK_POOL: LazyLock<rayon::ThreadPool> = LazyLock::new(|| {
|
||||
let threads = if cfg!(windows) {
|
||||
rayon::current_num_threads().min(16)
|
||||
} else {
|
||||
rayon::current_num_threads()
|
||||
};
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(threads)
|
||||
.thread_name(|index| format!("disktree-walk-{index}"))
|
||||
.build()
|
||||
.expect("a thread pool")
|
||||
});
|
||||
|
||||
/// Entries counted before the shared progress counters are touched. Every
|
||||
/// worker adding to the same counters per entry keeps one cache line
|
||||
/// bouncing between cores; per directory, or per this many entries in a
|
||||
/// wide one so the meter still moves, is invisible to a reader.
|
||||
const TALLY_EVERY: u64 = 1024;
|
||||
|
||||
/// What one directory's listing has found so far, for the progress meter.
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
files: u64,
|
||||
dirs: u64,
|
||||
bytes: u64,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
const fn add(&mut self, node: &Node) {
|
||||
if node.is_dir() {
|
||||
// A subtree taken whole from an earlier scan.
|
||||
self.files += node.files;
|
||||
self.dirs += node.dirs;
|
||||
} else {
|
||||
// A link counts as a file on the meter, as it always has,
|
||||
// though the tree does not count it.
|
||||
self.files += 1;
|
||||
}
|
||||
self.bytes += node.bytes;
|
||||
}
|
||||
|
||||
fn flush(&mut self, progress: &ScanProgress) {
|
||||
progress.add(self.files, self.dirs, self.bytes);
|
||||
*self = Self::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read one directory, spawn a task per subdirectory, then report completion.
|
||||
///
|
||||
/// Flat tasks inside the scope: the worker stack never grows with tree depth.
|
||||
fn dispatch_fixed<'scope>(
|
||||
scope: &Scope<'scope>,
|
||||
dir: &Arc<PendingDir>,
|
||||
context: &Arc<WalkContext>,
|
||||
context: &'scope WalkContext,
|
||||
) {
|
||||
for child in walk(dir, context) {
|
||||
let context = Arc::clone(context);
|
||||
scope.spawn(move |scope| {
|
||||
dispatch_fixed(scope, &child, &context);
|
||||
dispatch_fixed(scope, &child, context);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -782,34 +963,30 @@ fn dispatch_fixed(
|
||||
/// Read one directory, spawn a task per subdirectory, then report completion.
|
||||
///
|
||||
/// Flat tasks inside the scope: the worker stack never grows with tree depth.
|
||||
fn dispatch(
|
||||
scope: &Scope<'_>,
|
||||
fn dispatch<'scope>(
|
||||
scope: &Scope<'scope>,
|
||||
jobs: Vec<Arc<PendingDir>>,
|
||||
context: &Arc<WalkContext>,
|
||||
context: &'scope WalkContext,
|
||||
admission: &Arc<Admission<Arc<PendingDir>>>,
|
||||
) {
|
||||
for dir in jobs {
|
||||
let context = Arc::clone(context);
|
||||
let admission = Arc::clone(admission);
|
||||
scope.spawn(move |scope| {
|
||||
let mut next = Some(dir);
|
||||
while let Some(dir) = next.take() {
|
||||
let children = walk(&dir, &context);
|
||||
let children = walk(&dir, context);
|
||||
let mut jobs = admission.complete(children);
|
||||
// Continue locally into one ready descendant; only surplus
|
||||
// jobs are offered to other workers. A running directory is
|
||||
// never split, and a retirement returns from this loop.
|
||||
next = jobs.pop();
|
||||
dispatch(scope, jobs, &context, &admission);
|
||||
dispatch(scope, jobs, context, &admission);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn walk(
|
||||
dir: &Arc<PendingDir>,
|
||||
context: &Arc<WalkContext>,
|
||||
) -> Vec<Arc<PendingDir>> {
|
||||
fn walk(dir: &Arc<PendingDir>, context: &WalkContext) -> Vec<Arc<PendingDir>> {
|
||||
if context.cancelled() {
|
||||
// Queued jobs still own a pending token even when no I/O is needed.
|
||||
signal_done(dir, context);
|
||||
@@ -817,26 +994,36 @@ fn walk(
|
||||
}
|
||||
let mut subdirs: Vec<Arc<PendingDir>> = Vec::new();
|
||||
let mut leaves: Vec<Node> = Vec::new();
|
||||
let mut tally = Tally::default();
|
||||
|
||||
match list(&dir.path) {
|
||||
match list(&dir.path, context.volume.get().copied()) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
if context.cancelled() {
|
||||
break;
|
||||
}
|
||||
match entry {
|
||||
Ok(entry) => match context.classify(&entry) {
|
||||
Classified::Subdirectory(path) => {
|
||||
let child = Arc::new(PendingDir::new(
|
||||
path,
|
||||
Some(Arc::clone(dir)),
|
||||
dir.depth + 1,
|
||||
));
|
||||
subdirs.push(child);
|
||||
Ok(mut entry) => {
|
||||
match context.classify(&dir.path, &mut entry) {
|
||||
Classified::Subdirectory { path, name } => {
|
||||
tally.dirs += 1;
|
||||
subdirs.push(Arc::new(PendingDir::new(
|
||||
path,
|
||||
name,
|
||||
Some(Arc::clone(dir)),
|
||||
dir.depth + 1,
|
||||
)));
|
||||
}
|
||||
Classified::Entry(node) => {
|
||||
tally.add(&node);
|
||||
leaves.push(node);
|
||||
}
|
||||
Classified::Skipped => {}
|
||||
}
|
||||
Classified::Entry(node) => leaves.push(node),
|
||||
Classified::Skipped => {}
|
||||
},
|
||||
if tally.files + tally.dirs >= TALLY_EVERY {
|
||||
tally.flush(&context.progress);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
context.progress.record_error(&dir.path, &error);
|
||||
}
|
||||
@@ -848,6 +1035,7 @@ fn walk(
|
||||
dir.read_error.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
tally.flush(&context.progress);
|
||||
|
||||
// A depth-limited scan still measures what is directly in the directory,
|
||||
// it just does not descend further.
|
||||
@@ -855,6 +1043,19 @@ fn walk(
|
||||
.options
|
||||
.max_depth
|
||||
.is_none_or(|max_depth| dir.depth < max_depth);
|
||||
// Sized once for the leaves and every subdirectory to come, before any
|
||||
// subdirectory task can push its node: otherwise that first push
|
||||
// doubles a list just sized to the leaves, and the slack stays in the
|
||||
// finished tree. The leaves are copied, not moved: the list they grew
|
||||
// in carries up to twice their size in slack, and moving it in whole
|
||||
// made a home directory walk a second slower (measured, 5 interleaved
|
||||
// pairs).
|
||||
let spawned = if descend { subdirs.len() } else { 0 };
|
||||
{
|
||||
let mut partial = lock(&dir.partial);
|
||||
partial.children.reserve_exact(leaves.len() + spawned);
|
||||
partial.children.extend(leaves);
|
||||
}
|
||||
let mut children = Vec::new();
|
||||
if descend {
|
||||
for subdir in subdirs {
|
||||
@@ -865,7 +1066,6 @@ fn walk(
|
||||
children.push(subdir);
|
||||
}
|
||||
}
|
||||
lock(&dir.children).extend(leaves);
|
||||
|
||||
signal_done(dir, context);
|
||||
children
|
||||
@@ -877,44 +1077,32 @@ fn walk(
|
||||
/// This is the whole reason for the `+1` sentinel: a directory is only built
|
||||
/// once its own scan *and* every subdirectory task has finished, no matter
|
||||
/// which of them lands last.
|
||||
fn signal_done(dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
|
||||
fn signal_done(dir: &Arc<PendingDir>, context: &WalkContext) {
|
||||
if dir.pending.fetch_sub(1, Ordering::AcqRel) != 1 {
|
||||
return;
|
||||
}
|
||||
let node = dir.build();
|
||||
let Some(parent) = dir.parent.clone() else {
|
||||
let Some(parent) = &dir.parent else {
|
||||
*lock(&context.root) = Some(node);
|
||||
return;
|
||||
};
|
||||
lock(&parent.children).push(node);
|
||||
signal_done(&parent, context);
|
||||
lock(&parent.partial).children.push(node);
|
||||
signal_done(parent, context);
|
||||
}
|
||||
|
||||
/// Charge a hardlinked file once, then derive every aggregate from the result.
|
||||
///
|
||||
/// Zeroing `own_bytes` rather than `bytes` is deliberate:
|
||||
/// [`crate::tree::aggregate`] recomputes totals from the direct contents, so a
|
||||
/// patched `bytes` would be overwritten.
|
||||
/// Charge a hardlinked file once, derive every aggregate from the result,
|
||||
/// then classify. On the walk's pool: the UI's own work on the global pool
|
||||
/// must not queue behind a scan finishing.
|
||||
fn finish_tree(mut node: Node, options: &ScanOptions) -> Node {
|
||||
if options.dedup_hardlinks {
|
||||
let mut seen = FxHashSet::default();
|
||||
mark_duplicate_hardlinks(&mut node, &mut seen);
|
||||
}
|
||||
aggregate(&mut node, options.metric);
|
||||
crate::classify::classify(&mut node);
|
||||
node
|
||||
}
|
||||
|
||||
fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) {
|
||||
if !node.is_dir() {
|
||||
if node.inode.is_some_and(|key| !seen.insert(key)) {
|
||||
node.own_bytes = 0;
|
||||
WALK_POOL.install(|| {
|
||||
if options.dedup_hardlinks {
|
||||
aggregate_deduped(&mut node, options.metric, &Seen::new());
|
||||
} else {
|
||||
aggregate(&mut node, options.metric);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for child in &mut node.children {
|
||||
mark_duplicate_hardlinks(child, seen);
|
||||
}
|
||||
crate::classify::classify(&mut node);
|
||||
});
|
||||
node
|
||||
}
|
||||
|
||||
/// A leaf. Its identity is kept only when `track` says the walk could meet
|
||||
@@ -1062,7 +1250,7 @@ fn kind_of(meta: &Metadata, file_type: fs::FileType) -> NodeKind {
|
||||
|
||||
/// The display name of a scanned root: its final component, or the path itself
|
||||
/// for `/`.
|
||||
fn file_name(path: &Path) -> Box<str> {
|
||||
pub(crate) fn file_name(path: &Path) -> Box<str> {
|
||||
path.file_name()
|
||||
.map_or_else(
|
||||
|| path.to_string_lossy().into_owned(),
|
||||
@@ -1073,7 +1261,7 @@ fn file_name(path: &Path) -> Box<str> {
|
||||
|
||||
/// A poisoned lock means another task panicked; the data is still a valid tree
|
||||
/// prefix, and refusing to read it would turn one panic into two.
|
||||
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
mutex.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
@@ -1145,9 +1333,14 @@ mod tests {
|
||||
never_scanned: OnceLock::new(),
|
||||
visited_dirs: Mutex::new(FxHashSet::default()),
|
||||
root: Mutex::new(None),
|
||||
volume: OnceLock::new(),
|
||||
});
|
||||
let root =
|
||||
Arc::new(PendingDir::new(temp.path().to_path_buf(), None, 0));
|
||||
let root = Arc::new(PendingDir::new(
|
||||
temp.path().to_path_buf(),
|
||||
file_name(temp.path()),
|
||||
None,
|
||||
0,
|
||||
));
|
||||
let queued = walk(&root, &context);
|
||||
assert_eq!(queued.len(), 128);
|
||||
assert!(lock(&context.root).is_none());
|
||||
@@ -1420,6 +1613,7 @@ mod tests {
|
||||
never_scanned: OnceLock::new(),
|
||||
visited_dirs: Mutex::new(FxHashSet::default()),
|
||||
root: Mutex::new(None),
|
||||
volume: OnceLock::new(),
|
||||
});
|
||||
let tree = scan_blocking(root, &context).expect("scan still succeeds");
|
||||
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o700));
|
||||
|
||||
@@ -222,6 +222,200 @@ pub fn foreign_mounts_for(root: &Path) -> Option<Vec<PathBuf>> {
|
||||
Some(foreign_mounts(&parse_mounts(&table), root))
|
||||
}
|
||||
|
||||
/// One line of `/proc/self/mountinfo`.
|
||||
///
|
||||
/// What [`Mount`] says, plus which directory of the filesystem the mount
|
||||
/// shows. `/proc/self/mounts` leaves that out, and it is what tells a bind
|
||||
/// mount from the filesystem itself.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MountView {
|
||||
/// Kernel filesystem identity; source names such as `tmpfs` repeat.
|
||||
pub device: String,
|
||||
pub source: String,
|
||||
pub fstype: String,
|
||||
pub point: PathBuf,
|
||||
/// The directory inside the filesystem that appears at `point`: `/` for
|
||||
/// a whole filesystem, `/@home` for a Btrfs subvolume, the bound
|
||||
/// directory for a bind mount.
|
||||
pub fs_root: PathBuf,
|
||||
}
|
||||
|
||||
/// Parse `/proc/self/mountinfo`. Lines it cannot read are skipped.
|
||||
pub fn parse_mountinfo(table: &str) -> Vec<MountView> {
|
||||
table
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
// Optional fields run up to a lone `-`; after it come the type
|
||||
// and the source.
|
||||
let (left, right) = line.split_once(" - ")?;
|
||||
let mut left = left.split_whitespace().skip(2);
|
||||
let device = left.next()?.to_string();
|
||||
let fs_root = PathBuf::from(unescape_octal(left.next()?));
|
||||
let point = PathBuf::from(unescape_octal(left.next()?));
|
||||
let mut right = right.split_whitespace();
|
||||
let fstype = right.next()?.to_string();
|
||||
let source = unescape_octal(right.next()?);
|
||||
Some(MountView {
|
||||
device,
|
||||
source,
|
||||
fstype,
|
||||
point,
|
||||
fs_root,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The kernel writes space, tab, newline and backslash in mount fields as
|
||||
/// three octal digits after a backslash. Decoded in one pass, so a name that
|
||||
/// really contains `\040` is not decoded twice.
|
||||
fn unescape_octal(field: &str) -> String {
|
||||
let bytes = field.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
let digits = bytes.get(index + 1..index + 4);
|
||||
let value = digits
|
||||
.filter(|_| bytes[index] == b'\\')
|
||||
.and_then(|digits| std::str::from_utf8(digits).ok())
|
||||
.and_then(|digits| u8::from_str_radix(digits, 8).ok());
|
||||
if let Some(value) = value {
|
||||
out.push(value);
|
||||
index += 4;
|
||||
} else {
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// Paths under `root` that show a directory the scan already reaches
|
||||
/// another way, so walking them would count the same files twice.
|
||||
///
|
||||
/// A bind mount, a second mount of the same disk, or the top of a Btrfs
|
||||
/// filesystem mounted beside its subvolumes all show one directory at two
|
||||
/// paths. Device numbers cannot tell: a bind mount has its original's. The
|
||||
/// mount table can, since each line names the filesystem and the directory
|
||||
/// of it that is shown. When one directory is visible twice, the view
|
||||
/// showing the widest part of the filesystem is kept, and the narrower one
|
||||
/// is left out. The scanned root itself is never left out; if it is the
|
||||
/// narrower view, its copy inside the wider one is.
|
||||
pub fn repeated_mounts(mounts: &[MountView], root: &Path) -> Vec<PathBuf> {
|
||||
repeated_mounts_excluding(mounts, root, &[])
|
||||
}
|
||||
|
||||
fn same_filesystem(left: &MountView, right: &MountView) -> bool {
|
||||
left.fstype == right.fstype
|
||||
&& (left.device == right.device
|
||||
// Btrfs assigns device numbers per subvolume. Its block device
|
||||
// identifies the filesystem shared by those different roots.
|
||||
|| (left.fstype == "btrfs"
|
||||
&& left.source.starts_with("/dev/")
|
||||
&& left.source == right.source))
|
||||
}
|
||||
|
||||
fn covering_mount<'a>(
|
||||
mounts: &'a [MountView],
|
||||
path: &Path,
|
||||
) -> Option<&'a MountView> {
|
||||
mounts
|
||||
.iter()
|
||||
.filter(|mount| path.starts_with(&mount.point))
|
||||
.max_by_key(|mount| mount.point.components().count())
|
||||
}
|
||||
|
||||
fn repeated_mounts_excluding(
|
||||
mounts: &[MountView],
|
||||
root: &Path,
|
||||
excluded: &[PathBuf],
|
||||
) -> Vec<PathBuf> {
|
||||
let own = covering_mount(mounts, root);
|
||||
let mut visible: Vec<&MountView> = mounts
|
||||
.iter()
|
||||
.filter(|mount| {
|
||||
(mount.point.starts_with(root) || Some(*mount) == own)
|
||||
&& !excluded.iter().any(|skip| mount.point.starts_with(skip))
|
||||
})
|
||||
.collect();
|
||||
visible.sort_by_key(|mount| {
|
||||
(
|
||||
mount.fs_root.components().count(),
|
||||
mount.point.components().count(),
|
||||
&mount.point,
|
||||
)
|
||||
});
|
||||
let mut kept: Vec<&MountView> = Vec::new();
|
||||
let mut repeated: Vec<PathBuf> = Vec::new();
|
||||
for mount in visible {
|
||||
let elsewhere = kept.iter().find_map(|wider| {
|
||||
if !same_filesystem(wider, mount) {
|
||||
return None;
|
||||
}
|
||||
let inside = mount.fs_root.strip_prefix(&wider.fs_root).ok()?;
|
||||
let path = wider.point.join(inside);
|
||||
if !path.starts_with(root)
|
||||
|| path == mount.point
|
||||
|| excluded
|
||||
.iter()
|
||||
.chain(&repeated)
|
||||
.any(|skip| path.starts_with(skip))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Another mount can hide the supposed original directory.
|
||||
let covering = covering_mount(mounts, &path)?;
|
||||
let relative = path.strip_prefix(&covering.point).ok()?;
|
||||
(same_filesystem(covering, mount)
|
||||
&& covering.fs_root.join(relative) == mount.fs_root)
|
||||
.then_some(path)
|
||||
});
|
||||
let skip = elsewhere.map(|copy| {
|
||||
if mount.point != root && mount.point.starts_with(root) {
|
||||
mount.point.clone()
|
||||
} else {
|
||||
copy
|
||||
}
|
||||
});
|
||||
if let Some(skip) = skip
|
||||
&& !root.starts_with(&skip)
|
||||
// A duplicate view can contain independently mounted data.
|
||||
// Keep it rather than hiding that data with its parent.
|
||||
&& !mounts.iter().any(|child| child.point != skip && child.point.starts_with(&skip))
|
||||
{
|
||||
if skip != mount.point {
|
||||
kept.push(mount);
|
||||
}
|
||||
repeated.push(skip);
|
||||
} else {
|
||||
kept.push(mount);
|
||||
}
|
||||
}
|
||||
repeated
|
||||
}
|
||||
|
||||
/// [`repeated_mounts`] for this machine, in `root`'s own spelling. Empty
|
||||
/// where there is no `/proc/self/mountinfo`.
|
||||
pub fn repeated_mounts_for(
|
||||
root: &Path,
|
||||
canonical: &Path,
|
||||
one_filesystem: bool,
|
||||
) -> Vec<PathBuf> {
|
||||
let Ok(table) = std::fs::read_to_string("/proc/self/mountinfo") else {
|
||||
return Vec::new();
|
||||
};
|
||||
let excluded = if one_filesystem {
|
||||
foreign_mounts_for(canonical).unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
repeated_mounts_excluding(&parse_mountinfo(&table), canonical, &excluded)
|
||||
.iter()
|
||||
.filter_map(|path| path.strip_prefix(canonical).ok())
|
||||
.map(|below| root.join(below))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The mount points in what macOS's `mount` prints.
|
||||
///
|
||||
/// One per line: `/dev/disk3s5 on /System/Volumes/Data (apfs, local, …)`.
|
||||
@@ -329,6 +523,171 @@ pub const fn foreign_mounts_for(_root: &Path) -> Option<Vec<PathBuf>> {
|
||||
Some(Vec::new())
|
||||
}
|
||||
|
||||
/// A mounted volume the picker can switch the scan to: where it is mounted
|
||||
/// and how much room it has. Listed by [`volumes`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Volume {
|
||||
/// Where the volume is mounted: `C:\` on Windows, `/` or `/home` on
|
||||
/// Linux, `/` on macOS.
|
||||
pub point: PathBuf,
|
||||
/// What is mounted there, when the table names it: a device such as
|
||||
/// `/dev/nvme0n1p2`, or a name like `tmpfs`.
|
||||
pub device: Option<String>,
|
||||
/// Free space on the volume now; `None` when it cannot be read.
|
||||
pub space: Option<SpaceInfo>,
|
||||
}
|
||||
|
||||
/// Every volume worth offering as a scan root, fullest first.
|
||||
///
|
||||
/// Pseudo filesystems (`/proc`, `/sys`, tmpfs, …), snapshot subvolumes and
|
||||
/// automount points are left out: switching the scan to one of those would
|
||||
/// measure the wrong thing, the same reason [`foreign_mounts`] keeps a scan
|
||||
/// from entering them. Duplicates from one device mounted twice (a btrfs
|
||||
/// subvolume at `/` and `/home`) collapse to the shortest mount point, which
|
||||
/// is the top of that disk.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub fn volumes() -> Vec<Volume> {
|
||||
let Ok(table) = std::fs::read_to_string("/proc/self/mounts") else {
|
||||
return Vec::new();
|
||||
};
|
||||
volumes_in(&parse_mounts(&table))
|
||||
}
|
||||
|
||||
/// [`volumes`] over a given mount table, for testing.
|
||||
pub fn volumes_in(mounts: &[Mount]) -> Vec<Volume> {
|
||||
let mut seen: Vec<&Mount> = Vec::new();
|
||||
for mount in mounts {
|
||||
if !is_volume_candidate(mount) {
|
||||
continue;
|
||||
}
|
||||
// One device mounted twice (a btrfs disk at `/`, `/home`,
|
||||
// `/var/log`) is one volume: keep the shortest mount point, which is
|
||||
// the top of that disk.
|
||||
if let Some(known) = seen.iter_mut().find(|known| {
|
||||
known.source == mount.source && known.fstype == mount.fstype
|
||||
}) {
|
||||
if mount.point.as_os_str().len() < known.point.as_os_str().len() {
|
||||
*known = mount;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
seen.push(mount);
|
||||
}
|
||||
let mut volumes: Vec<Volume> = seen
|
||||
.iter()
|
||||
.map(|mount| Volume {
|
||||
point: mount.point.clone(),
|
||||
device: Some(mount.source.clone()),
|
||||
space: space_info(&mount.point).ok(),
|
||||
})
|
||||
.collect();
|
||||
// The scarcest room is the most interesting to a cleanup tool, so the
|
||||
// fullest volume that still reads is first; unreadable ones sort last.
|
||||
sort_by_free_space(&mut volumes);
|
||||
volumes
|
||||
}
|
||||
|
||||
/// Fullest first; an unreadable volume sorts last.
|
||||
fn sort_by_free_space(volumes: &mut [Volume]) {
|
||||
volumes.sort_by_key(|volume| {
|
||||
(
|
||||
volume.space.is_none(),
|
||||
volume.space.map_or(0, |space| space.available),
|
||||
volume.point.clone(),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether the mount is a real disk worth scanning: a device-backed
|
||||
/// filesystem that is not a snapshot, an automount point, or one of the
|
||||
/// pseudo filesystems the scan itself refuses to enter.
|
||||
fn is_volume_candidate(mount: &Mount) -> bool {
|
||||
if is_snapshot(mount) {
|
||||
return false;
|
||||
}
|
||||
if mount
|
||||
.options
|
||||
.split(',')
|
||||
.any(|option| option == "automounted" || option.starts_with("autofs"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
!matches!(
|
||||
mount.fstype.as_str(),
|
||||
"autofs"
|
||||
| "cgroup"
|
||||
| "cgroup2"
|
||||
| "configfs"
|
||||
| "debugfs"
|
||||
| "devpts"
|
||||
| "devtmpfs"
|
||||
| "fuse.portal"
|
||||
| "fusectl"
|
||||
| "hugetlbfs"
|
||||
| "mqueue"
|
||||
| "nsfs"
|
||||
| "overlay"
|
||||
| "proc"
|
||||
| "pstore"
|
||||
| "securityfs"
|
||||
| "sysfs"
|
||||
| "tmpfs"
|
||||
| "tracefs"
|
||||
)
|
||||
}
|
||||
|
||||
/// Every volume worth offering as a scan root, fullest first.
|
||||
///
|
||||
/// The Data volume's second mount is the same disk under another name, so it
|
||||
/// is left out; the firmlinks joined into `/` mean `/` already shows it.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn volumes() -> Vec<Volume> {
|
||||
use std::process::Command;
|
||||
|
||||
let output = Command::new("mount")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok());
|
||||
let Some(output) = output else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut points = parse_macos_mounts(&output);
|
||||
points.retain(|point| {
|
||||
point.as_os_str() != MACOS_DATA_VOLUME && !point.as_os_str().is_empty()
|
||||
});
|
||||
let mut volumes: Vec<Volume> = points
|
||||
.iter()
|
||||
.map(|point| Volume {
|
||||
point: point.clone(),
|
||||
device: device_for(point),
|
||||
space: space_info(point).ok(),
|
||||
})
|
||||
.collect();
|
||||
sort_by_free_space(&mut volumes);
|
||||
volumes
|
||||
}
|
||||
|
||||
/// Every place a volume is mounted that can be scanned.
|
||||
///
|
||||
/// Drive roots such as `D:\` and folders a volume is mounted on. Unready
|
||||
/// drives (an empty card reader reports a path but no space) are left out,
|
||||
/// since there is nothing to measure there.
|
||||
#[cfg(windows)]
|
||||
pub fn volumes() -> Vec<Volume> {
|
||||
let mut volumes: Vec<Volume> = crate::windows::mount_points()
|
||||
.into_iter()
|
||||
.filter_map(|point| {
|
||||
space_info(&point).ok().map(|space| Volume {
|
||||
point,
|
||||
device: None,
|
||||
space: Some(space),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
sort_by_free_space(&mut volumes);
|
||||
volumes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -346,6 +705,156 @@ tmpfs /tmp tmpfs rw 0 0
|
||||
portal /run/user/1000/doc fuse.portal rw 0 0
|
||||
";
|
||||
|
||||
const MOUNTINFO: &str = "\
|
||||
22 1 0:21 /@ / rw,relatime - btrfs /dev/mapper/root rw,subvol=/@
|
||||
23 22 0:21 /@home /home rw,relatime - btrfs /dev/mapper/root rw,subvol=/@home
|
||||
24 22 0:21 /@log /var/log rw,relatime - btrfs /dev/mapper/root rw,subvol=/@log
|
||||
25 22 0:21 /@snapshots /.snapshots rw - btrfs /dev/mapper/root rw
|
||||
26 22 0:30 / /data rw,relatime shared:5 - btrfs /dev/mapper/data rw
|
||||
27 22 0:30 / /mnt/data rw,relatime shared:5 - btrfs /dev/mapper/data rw
|
||||
28 22 0:31 / /tmp rw - tmpfs tmpfs rw
|
||||
29 22 259:3 / /boot rw - vfat /dev/nvme0n1p1 rw
|
||||
";
|
||||
|
||||
fn repeated(table: &str, root: &str) -> Vec<PathBuf> {
|
||||
let mut paths =
|
||||
repeated_mounts(&parse_mountinfo(table), Path::new(root));
|
||||
paths.sort();
|
||||
paths
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subvolumes_are_not_repeats_but_a_second_mount_of_a_disk_is() {
|
||||
assert_eq!(repeated(MOUNTINFO, "/"), [PathBuf::from("/mnt/data")]);
|
||||
assert!(repeated(MOUNTINFO, "/home/tobi").is_empty());
|
||||
assert!(repeated(MOUNTINFO, "/data").is_empty());
|
||||
assert!(
|
||||
repeated(MOUNTINFO, "/mnt/data").is_empty(),
|
||||
"the view that was asked for is scanned"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bind_mount_inside_the_scan_is_left_out() {
|
||||
let table = format!(
|
||||
"{MOUNTINFO}30 23 0:21 /@home/tobi/src /srv/src rw - btrfs /dev/mapper/root rw\n"
|
||||
);
|
||||
assert_eq!(
|
||||
repeated(&table, "/"),
|
||||
[PathBuf::from("/mnt/data"), PathBuf::from("/srv/src")]
|
||||
);
|
||||
// From home, the original is outside the scan: nothing repeats.
|
||||
assert!(repeated(&table, "/home/tobi").is_empty());
|
||||
assert!(repeated(&table, "/srv").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_top_of_a_btrfs_disk_beside_its_subvolumes_is_counted_once() {
|
||||
let table = format!(
|
||||
"{MOUNTINFO}31 22 0:21 / /mnt/top rw - btrfs /dev/mapper/root rw\n"
|
||||
);
|
||||
// The root cannot be left out, so its copy under /mnt/top is; the
|
||||
// other subvolumes are seen under /mnt/top instead of twice.
|
||||
assert_eq!(
|
||||
repeated(&table, "/"),
|
||||
[
|
||||
PathBuf::from("/.snapshots"),
|
||||
PathBuf::from("/home"),
|
||||
PathBuf::from("/mnt/data"),
|
||||
PathBuf::from("/mnt/top/@"),
|
||||
PathBuf::from("/var/log"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_tmpfs_mounts_are_not_duplicates() {
|
||||
let table = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
|
||||
2 1 0:20 / /one rw - tmpfs tmpfs rw\n\
|
||||
3 1 0:21 / /two rw - tmpfs tmpfs rw\n";
|
||||
assert!(repeated(table, "/").is_empty());
|
||||
let alias =
|
||||
format!("{table}4 1 0:20 / /three rw - tmpfs different-name rw\n");
|
||||
assert_eq!(repeated(&alias, "/"), [PathBuf::from("/three")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_original_and_nested_mounts_are_preserved() {
|
||||
let hidden = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
|
||||
2 1 0:20 / /data rw - tmpfs tmpfs rw\n\
|
||||
3 2 8:1 /data/source /data/bind rw - ext4 /dev/root rw\n";
|
||||
assert!(repeated(hidden, "/").is_empty());
|
||||
let nested = "1 0 8:1 / / rw - ext4 /dev/root rw\n\
|
||||
2 1 8:1 /original /view rw - ext4 /dev/root rw\n\
|
||||
3 2 0:20 / /view/unique rw - tmpfs tmpfs rw\n";
|
||||
assert!(repeated(nested, "/").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_views_cannot_replace_visible_files() {
|
||||
let mounts = parse_mountinfo(
|
||||
"1 0 8:1 / / rw - ext4 /dev/root rw\n\
|
||||
2 1 8:1 /original /view rw - ext4 /dev/root rw\n",
|
||||
);
|
||||
assert!(
|
||||
repeated_mounts_excluding(
|
||||
&mounts,
|
||||
Path::new("/"),
|
||||
&[PathBuf::from("/original")]
|
||||
)
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn btrfs_subvolume_devices_can_differ() {
|
||||
let table = "1 0 0:20 /@ / rw - btrfs /dev/root rw\n\
|
||||
2 1 0:21 /@home /home rw - btrfs /dev/root rw\n\
|
||||
3 1 0:22 / /top rw - btrfs /dev/root rw\n";
|
||||
assert_eq!(
|
||||
repeated(table, "/"),
|
||||
[PathBuf::from("/home"), PathBuf::from("/top/@")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mountinfo_escapes_are_decoded_once() {
|
||||
let mounts = parse_mountinfo(
|
||||
"not a mount line\n\
|
||||
40 22 8:1 /a\\040b /media/My\\040Disk\\134040 rw - ext4 /dev/sda1 rw\n",
|
||||
);
|
||||
assert_eq!(mounts.len(), 1);
|
||||
assert_eq!(mounts[0].fs_root, Path::new("/a b"));
|
||||
assert_eq!(mounts[0].point, Path::new("/media/My Disk\\040"));
|
||||
assert_eq!(mounts[0].source, "/dev/sda1");
|
||||
assert_eq!(mounts[0].fstype, "ext4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volumes_with_least_space_come_first_and_unknowns_last() {
|
||||
let volume = |name: &str, available: Option<u64>| Volume {
|
||||
point: PathBuf::from(name),
|
||||
device: None,
|
||||
space: available.map(|available| SpaceInfo {
|
||||
total: 100,
|
||||
free: available,
|
||||
available,
|
||||
}),
|
||||
};
|
||||
let mut volumes = vec![
|
||||
volume("unknown", None),
|
||||
volume("roomy", Some(90)),
|
||||
volume("full", Some(0)),
|
||||
volume("nearly-full", Some(5)),
|
||||
];
|
||||
sort_by_free_space(&mut volumes);
|
||||
let names: Vec<_> = volumes.iter().map(|v| v.point.clone()).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
["full", "nearly-full", "roomy", "unknown"].map(PathBuf::from)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_volume_includes_its_subvolumes_and_nothing_else() {
|
||||
let mounts = parse_mounts(OMARCHY);
|
||||
@@ -366,6 +875,33 @@ portal /run/user/1000/doc fuse.portal rw 0 0
|
||||
assert_eq!(foreign, expected, "/home and /var/log are the same disk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_candidates_are_real_disks_not_pseudo_filesystems() {
|
||||
let mounts = parse_mounts(OMARCHY);
|
||||
let points: Vec<PathBuf> = volumes_in(&mounts)
|
||||
.iter()
|
||||
.map(|volume| volume.point.clone())
|
||||
.collect();
|
||||
// One btrfs disk (at `/`, collapsing `/home` and `/var/log`), plus
|
||||
// the boot disk; tmpfs, autofs, portals and snapshots are not scans.
|
||||
assert!(points.contains(&PathBuf::from("/")), "{points:?}");
|
||||
assert!(points.contains(&PathBuf::from("/boot")), "{points:?}");
|
||||
assert_eq!(points.len(), 2, "{points:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separate_home_disk_is_its_own_volume() {
|
||||
let separate = parse_mounts(
|
||||
"/dev/sda1 / ext4 rw 0 0\n/dev/sdb1 /home ext4 rw 0 0\n",
|
||||
);
|
||||
let points: Vec<PathBuf> = volumes_in(&separate)
|
||||
.iter()
|
||||
.map(|volume| volume.point.clone())
|
||||
.collect();
|
||||
assert!(points.contains(&PathBuf::from("/")), "{points:?}");
|
||||
assert!(points.contains(&PathBuf::from("/home")), "{points:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_whole_disk_is_the_top_of_the_home_volume() {
|
||||
let mounts = parse_mounts(OMARCHY);
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
//! The scanned tree.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{LazyLock, Mutex, OnceLock};
|
||||
|
||||
use rayon::prelude::*;
|
||||
use rustc_hash::FxHashSet;
|
||||
|
||||
use crate::classify::{Category, Reclaim};
|
||||
|
||||
@@ -235,7 +240,104 @@ impl Node {
|
||||
/// de-duplication rewrites a leaf's weight, and every total above it —
|
||||
/// including its parent's "direct" figure — follows without a second pass.
|
||||
pub fn aggregate(node: &mut Node, metric: Metric) {
|
||||
aggregate_at(node, metric, 0, None);
|
||||
}
|
||||
|
||||
/// [`aggregate`], charging a hardlinked file once: a leaf whose identity
|
||||
/// `seen` already holds weighs nothing. Which of a file's names is charged
|
||||
/// is whichever a worker reaches first, so two scans of an unchanged tree
|
||||
/// can split it differently between folders; the totals are the same.
|
||||
pub(crate) fn aggregate_deduped(node: &mut Node, metric: Metric, seen: &Seen) {
|
||||
aggregate_at(node, metric, 0, Some(seen));
|
||||
}
|
||||
|
||||
/// Identities a finish pass has met.
|
||||
///
|
||||
/// A hash set of every file on a disk is millions of random writes into a
|
||||
/// table too big for any cache. Inode and file record numbers are small
|
||||
/// integers, though, so a key on the first volume met whose whole number
|
||||
/// is below the bitmap's size gets one bit instead: an 8 MiB bitmap the
|
||||
/// workers set without locking. The file table reader's record numbers
|
||||
/// fit, as do most inodes. Anything else goes into the hash set, whole:
|
||||
/// a Windows file id keeps the record's reuse count in its top 16 bits,
|
||||
/// and that is what tells a file from an older one on the same record,
|
||||
/// which a subtree kept from an earlier scan can still hold. The set is
|
||||
/// sharded for the walk's millions of those: 4.1 million ids took 150 ms
|
||||
/// across 64 locks and 1.2 s behind one, in a synthetic run.
|
||||
pub(crate) struct Seen {
|
||||
/// The first volume met, which is the scanned root's in all but a scan
|
||||
/// that leaves its volume.
|
||||
volume: OnceLock<u64>,
|
||||
/// Made on the first key that fits: most Unix trees, where only files
|
||||
/// with more than one name carry an identity, never need it.
|
||||
bits: LazyLock<Box<[AtomicU64]>>,
|
||||
rest: Box<[Shard]>,
|
||||
}
|
||||
|
||||
/// One lock's part of the hash set.
|
||||
type Shard = Mutex<FxHashSet<(u64, u64)>>;
|
||||
|
||||
impl Seen {
|
||||
/// Numbers the bitmap covers: sixty-four million, more files than a
|
||||
/// desktop volume holds, for 8 MiB written once.
|
||||
const BITS: u64 = 1 << 26;
|
||||
|
||||
/// Hash set shards, as a power of two.
|
||||
const SHARD_BITS: u32 = 6;
|
||||
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
volume: OnceLock::new(),
|
||||
bits: LazyLock::new(|| {
|
||||
std::iter::repeat_with(|| AtomicU64::new(0))
|
||||
.take((Self::BITS / 64) as usize)
|
||||
.collect()
|
||||
}),
|
||||
rest: std::iter::repeat_with(Mutex::default)
|
||||
.take(1 << Self::SHARD_BITS)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `key` is new.
|
||||
fn insert(&self, key: (u64, u64)) -> bool {
|
||||
let (volume, number) = key;
|
||||
if *self.volume.get_or_init(|| volume) == volume && number < Self::BITS
|
||||
{
|
||||
let bit = 1 << (number % 64);
|
||||
let word = &self.bits[(number / 64) as usize];
|
||||
return word.fetch_or(bit, Ordering::Relaxed) & bit == 0;
|
||||
}
|
||||
// The top bits of a multiplicative hash, with another constant
|
||||
// than the set's own hasher, so a shard's keys still spread over
|
||||
// its table.
|
||||
let shard = (number.wrapping_mul(0x9E37_79B9_7F4A_7C15)
|
||||
>> (u64::BITS - Self::SHARD_BITS)) as usize;
|
||||
crate::scan::lock(&self.rest[shard]).insert(key)
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels whose subtrees are aggregated in parallel. A top level already
|
||||
/// splits a disk into enough work for every thread; below it a parallel
|
||||
/// frame per level would only cut the depth that fits in a worker's stack.
|
||||
pub(crate) const PARALLEL_LEVELS: usize = 4;
|
||||
|
||||
fn aggregate_at(
|
||||
node: &mut Node,
|
||||
metric: Metric,
|
||||
depth: usize,
|
||||
seen: Option<&Seen>,
|
||||
) {
|
||||
if !node.is_dir() {
|
||||
// Every name of a file has the file's size, so one that weighs
|
||||
// nothing need not be remembered to be charged once.
|
||||
if node.own_bytes > 0
|
||||
&& let Some(seen) = seen
|
||||
&& let Some(key) = node.inode
|
||||
&& !seen.insert(key)
|
||||
{
|
||||
node.own_bytes = 0;
|
||||
}
|
||||
node.bytes = node.own_bytes;
|
||||
node.files = node.own_files;
|
||||
node.dirs = 0;
|
||||
@@ -248,14 +350,23 @@ pub fn aggregate(node: &mut Node, metric: Metric) {
|
||||
let mut own_files = 0;
|
||||
let mut dirs: u64 = 1;
|
||||
let mut modified = 0;
|
||||
for child in &mut node.children {
|
||||
aggregate(child, metric);
|
||||
if depth < PARALLEL_LEVELS {
|
||||
node.children
|
||||
.par_iter_mut()
|
||||
.for_each(|child| aggregate_at(child, metric, depth + 1, seen));
|
||||
} else {
|
||||
for child in &mut node.children {
|
||||
aggregate_at(child, metric, depth + 1, seen);
|
||||
}
|
||||
}
|
||||
for child in &node.children {
|
||||
modified = modified.max(child.modified);
|
||||
bytes += child.bytes;
|
||||
// Saturating: a corrupt volume's file table can claim any size.
|
||||
bytes = child.bytes.saturating_add(bytes);
|
||||
files += child.files;
|
||||
dirs += child.dirs;
|
||||
if !child.is_dir() {
|
||||
own_bytes += child.bytes;
|
||||
own_bytes = child.bytes.saturating_add(own_bytes);
|
||||
own_files += child.files;
|
||||
}
|
||||
}
|
||||
@@ -267,8 +378,11 @@ pub fn aggregate(node: &mut Node, metric: Metric) {
|
||||
node.modified = modified;
|
||||
|
||||
// Largest first: a treemap lays out big tiles best, and the order is what
|
||||
// makes "descend into the largest child" meaningful.
|
||||
node.children.sort_by(|left, right| {
|
||||
// makes "descend into the largest child" meaningful. Unstable: names in
|
||||
// one directory are distinct, and the only ties are names that decoded
|
||||
// to the same lossy text, whose order does not matter, so the stable
|
||||
// sort's scratch allocation buys nothing.
|
||||
node.children.sort_unstable_by(|left, right| {
|
||||
right
|
||||
.value(metric)
|
||||
.cmp(&left.value(metric))
|
||||
@@ -300,6 +414,42 @@ mod tests {
|
||||
Node::entry(name, NodeKind::File, bytes)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seen_charges_an_identity_once_in_either_store() {
|
||||
let seen = Seen::new();
|
||||
// The first volume: the bitmap.
|
||||
assert!(seen.insert((7, 42)));
|
||||
assert!(!seen.insert((7, 42)));
|
||||
assert!(seen.insert((7, 43)));
|
||||
// A number past the bitmap, and another volume: the hash set.
|
||||
let far = Seen::BITS + 42;
|
||||
assert!(seen.insert((7, far)));
|
||||
assert!(!seen.insert((7, far)));
|
||||
assert!(seen.insert((8, 42)), "another volume's 42 is another file");
|
||||
assert!(!seen.insert((8, 42)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identities_that_differ_only_in_their_top_bits_are_two_files() {
|
||||
// Record 0x2A of one volume under two reuse counts, as a subtree kept
|
||||
// from an earlier scan and a later file can hold, and a real second
|
||||
// name of the newer one.
|
||||
let older = (7, (1 << 48) | 0x2A);
|
||||
let newer = (7, (2 << 48) | 0x2A);
|
||||
let mut root = Node::directory("root");
|
||||
for (name, bytes, key) in [
|
||||
("older", 4096, older),
|
||||
("newer", 8192, newer),
|
||||
("newer again", 8192, newer),
|
||||
] {
|
||||
let mut file = leaf(name, bytes);
|
||||
file.inode = Some(key);
|
||||
root.children.push(file);
|
||||
}
|
||||
aggregate_deduped(&mut root, Metric::Bytes, &Seen::new());
|
||||
assert_eq!(root.bytes, 4096 + 8192);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_derives_totals_and_orders_children() {
|
||||
let mut root = Node::directory("root");
|
||||
|
||||
@@ -23,20 +23,21 @@ 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, INVALID_HANDLE_VALUE,
|
||||
ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED, INVALID_HANDLE_VALUE, MAX_PATH,
|
||||
};
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_HIDDEN,
|
||||
FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, FILE_ATTRIBUTE_RECALL_ON_OPEN,
|
||||
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
|
||||
FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
|
||||
FileIdExtdDirectoryInfo, FindFirstVolumeW, FindNextVolumeW,
|
||||
FindVolumeClose, GetDiskFreeSpaceExW, GetFileInformationByHandleEx,
|
||||
GetVolumePathNameW, GetVolumePathNamesForVolumeNameW, SYNCHRONIZE,
|
||||
GetVolumeInformationW, GetVolumePathNameW,
|
||||
GetVolumePathNamesForVolumeNameW, SYNCHRONIZE,
|
||||
};
|
||||
|
||||
use crate::space::SpaceInfo;
|
||||
@@ -73,10 +74,15 @@ pub enum Kind {
|
||||
}
|
||||
|
||||
/// One directory entry, with what a measurement needs.
|
||||
///
|
||||
/// The name is decoded to text once, here, since that is what the tree
|
||||
/// keeps: the listing hands the walk one allocation per entry, not three.
|
||||
#[derive(Debug)]
|
||||
pub struct Entry {
|
||||
dir: Arc<Path>,
|
||||
name: OsString,
|
||||
name: Box<str>,
|
||||
/// The name as Windows spells it, only when `name` could not: an
|
||||
/// unpaired surrogate is shown as U+FFFD but must still open.
|
||||
exact: Option<Box<OsStr>>,
|
||||
kind: Kind,
|
||||
apparent: u64,
|
||||
allocated: u64,
|
||||
@@ -86,14 +92,29 @@ pub struct Entry {
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub fn path(&self) -> PathBuf {
|
||||
self.dir.join(&self.name)
|
||||
/// The entry's path inside `dir`, the directory it was listed from.
|
||||
pub fn path(&self, dir: &Path) -> PathBuf {
|
||||
dir.join(self.file_name())
|
||||
}
|
||||
|
||||
pub fn file_name(&self) -> &OsStr {
|
||||
self.exact
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| OsStr::new(&*self.name))
|
||||
}
|
||||
|
||||
/// The name as text; see [`Self::file_name`] for what it may lose.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// The name, moved out: the tree keeps it, so nothing copies it. The
|
||||
/// entry's other accessors keep working; `name`, `file_name` and
|
||||
/// `path` do not.
|
||||
pub fn take_name(&mut self) -> Box<str> {
|
||||
std::mem::take(&mut self.name)
|
||||
}
|
||||
|
||||
pub const fn kind(&self) -> Kind {
|
||||
self.kind
|
||||
}
|
||||
@@ -133,7 +154,7 @@ impl Entry {
|
||||
self.identity
|
||||
}
|
||||
|
||||
fn from_std(dir: &Arc<Path>, entry: &fs::DirEntry) -> io::Result<Self> {
|
||||
fn from_std(entry: &fs::DirEntry) -> io::Result<Self> {
|
||||
let meta = entry.metadata()?;
|
||||
let file_type = meta.file_type();
|
||||
let kind = if file_type.is_symlink() {
|
||||
@@ -143,9 +164,15 @@ impl Entry {
|
||||
} else {
|
||||
Kind::File
|
||||
};
|
||||
let (name, exact) = match entry.file_name().into_string() {
|
||||
Ok(name) => (name.into_boxed_str(), None),
|
||||
Err(raw) => {
|
||||
(raw.to_string_lossy().into(), Some(raw.into_boxed_os_str()))
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
dir: Arc::clone(dir),
|
||||
name: entry.file_name(),
|
||||
name,
|
||||
exact,
|
||||
kind,
|
||||
apparent: meta.len(),
|
||||
allocated: meta.len(),
|
||||
@@ -162,7 +189,6 @@ impl Entry {
|
||||
/// and `..`.
|
||||
#[derive(Debug)]
|
||||
pub struct ReadDir {
|
||||
dir: Arc<Path>,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
@@ -189,7 +215,12 @@ struct Records {
|
||||
}
|
||||
|
||||
/// List `dir`, with each entry's allocation and file id.
|
||||
pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
|
||||
///
|
||||
/// `volume` is the serial number of the volume `dir` is on, when the
|
||||
/// caller knows it for every directory of a walk (see [`walk_volume`]):
|
||||
/// asking per directory is several requests to the file system on top of
|
||||
/// the listing. `None` asks.
|
||||
pub fn read_dir(dir: &Path, volume: Option<u64>) -> io::Result<ReadDir> {
|
||||
let handle = OpenOptions::new()
|
||||
.access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE)
|
||||
// Needed to open a directory at all. Without
|
||||
@@ -197,9 +228,11 @@ pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
|
||||
// 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 volume = volume.or_else(|| {
|
||||
winapi_util::file::information(&handle)
|
||||
.ok()
|
||||
.map(|info| info.volume_serial_number())
|
||||
});
|
||||
let mut records = Records {
|
||||
handle,
|
||||
volume,
|
||||
@@ -207,17 +240,16 @@ pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
|
||||
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)?))
|
||||
Source::Std(Box::new(fs::read_dir(dir)?))
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(ReadDir { dir, source })
|
||||
Ok(ReadDir { source })
|
||||
}
|
||||
|
||||
impl Iterator for ReadDir {
|
||||
@@ -227,7 +259,7 @@ impl Iterator for ReadDir {
|
||||
let records = match &mut self.source {
|
||||
Source::Std(listing) => {
|
||||
return listing.next().map(|entry| {
|
||||
entry.and_then(|entry| Entry::from_std(&self.dir, &entry))
|
||||
entry.and_then(|entry| Entry::from_std(&entry))
|
||||
});
|
||||
}
|
||||
Source::Records(records) => records,
|
||||
@@ -243,7 +275,7 @@ impl Iterator for ReadDir {
|
||||
}
|
||||
continue;
|
||||
};
|
||||
match records.record(&self.dir, offset) {
|
||||
match records.record(offset) {
|
||||
Ok((entry, next)) => {
|
||||
records.next = next;
|
||||
if let Some(entry) = entry {
|
||||
@@ -304,7 +336,6 @@ impl Records {
|
||||
/// the buffer before it is used.
|
||||
fn record(
|
||||
&self,
|
||||
dir: &Arc<Path>,
|
||||
offset: usize,
|
||||
) -> io::Result<(Option<Entry>, Option<usize>)> {
|
||||
let malformed =
|
||||
@@ -333,11 +364,11 @@ impl Records {
|
||||
_ => return Err(malformed()),
|
||||
};
|
||||
|
||||
let name: Vec<u16> = name_bytes
|
||||
let units = 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] {
|
||||
.map(|pair| u16::from_ne_bytes([pair[0], pair[1]]));
|
||||
let (name, exact) = decode_name(units);
|
||||
if &*name == "." || &*name == ".." {
|
||||
return Ok((None, next));
|
||||
}
|
||||
|
||||
@@ -358,8 +389,8 @@ impl Records {
|
||||
header[id_at..id_at + 16].try_into().expect("sixteen"),
|
||||
);
|
||||
let entry = Entry {
|
||||
dir: Arc::clone(dir),
|
||||
name: OsString::from_wide(&name),
|
||||
name,
|
||||
exact,
|
||||
kind,
|
||||
apparent: bytes_from(signed(offset_of!(
|
||||
FILE_ID_EXTD_DIR_INFO,
|
||||
@@ -380,6 +411,27 @@ impl Records {
|
||||
}
|
||||
}
|
||||
|
||||
/// A UTF-16 name as text, decoded in one pass; nearly every name is ASCII,
|
||||
/// so one code unit is one byte and the text is allocated once, at its
|
||||
/// final size. An unpaired surrogate is replaced, and the exact name kept
|
||||
/// beside it so the path still opens.
|
||||
fn decode_name(
|
||||
units: impl Iterator<Item = u16> + Clone,
|
||||
) -> (Box<str>, Option<Box<OsStr>>) {
|
||||
let mut name = String::with_capacity(units.size_hint().0);
|
||||
let mut lossy = false;
|
||||
for unit in char::decode_utf16(units.clone()) {
|
||||
name.push(unit.unwrap_or_else(|_| {
|
||||
lossy = true;
|
||||
char::REPLACEMENT_CHARACTER
|
||||
}));
|
||||
}
|
||||
let exact = lossy.then(|| {
|
||||
OsString::from_wide(&units.collect::<Vec<u16>>()).into_boxed_os_str()
|
||||
});
|
||||
(name.into_boxed_str(), exact)
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -403,15 +455,35 @@ fn file_id(id: u128) -> Option<u64> {
|
||||
///
|
||||
/// [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 info = information(path)?;
|
||||
let index = info.file_index();
|
||||
(index != 0 && index != u64::MAX)
|
||||
.then(|| (info.volume_serial_number(), index))
|
||||
}
|
||||
|
||||
/// Serial number of the volume every directory under `canonical` is on,
|
||||
/// for a walk that does not follow links. Only a local drive has one:
|
||||
/// mounted folders there are reparse points the walk takes for links,
|
||||
/// while a share's DFS links are not, and lead to other servers' volumes.
|
||||
/// `None` for a share, or when the serial cannot be read.
|
||||
pub fn walk_volume(canonical: &Path) -> Option<u64> {
|
||||
let Some(Component::Prefix(prefix)) = canonical.components().next() else {
|
||||
return None;
|
||||
};
|
||||
if !matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)) {
|
||||
return None;
|
||||
}
|
||||
information(canonical).map(|info| info.volume_serial_number())
|
||||
}
|
||||
|
||||
/// What the file system says about `path`, following links.
|
||||
fn information(path: &Path) -> Option<winapi_util::file::Information> {
|
||||
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))
|
||||
winapi_util::file::information(&file).ok()
|
||||
}
|
||||
|
||||
/// Capacity and free space of the volume holding `path`.
|
||||
@@ -531,6 +603,175 @@ pub fn is_mount_point(path: &Path) -> bool {
|
||||
&& volume_root(path).is_some_and(|root| same(&root, path))
|
||||
}
|
||||
|
||||
/// Whether this process runs as an administrator, with the elevated token
|
||||
/// UAC hands out: what reading a volume directly takes.
|
||||
pub fn elevated() -> bool {
|
||||
// SAFETY: takes no arguments and only reads the process token.
|
||||
unsafe { windows_sys::Win32::UI::Shell::IsUserAnAdmin() != 0 }
|
||||
}
|
||||
|
||||
/// Whether `root` is a whole drive an administrator would read from its
|
||||
/// file table: a drive letter's root, formatted NTFS. Anything else, from
|
||||
/// a folder or a mounted folder to another file system, is walked either way.
|
||||
pub fn file_table_readable(root: &Path) -> bool {
|
||||
let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
|
||||
let Some(letter) = drive_letter(&canonical) else {
|
||||
return false;
|
||||
};
|
||||
let volume: Vec<u16> = format!("{letter}:\\\0").encode_utf16().collect();
|
||||
let mut name = [0_u16; MAX_PATH as usize + 1];
|
||||
let length = u32::try_from(name.len()).unwrap_or(u32::MAX);
|
||||
// SAFETY: `volume` is NUL-terminated and outlives the call, `name` is
|
||||
// writable for the length passed, and the other outputs may be null.
|
||||
let ok = unsafe {
|
||||
GetVolumeInformationW(
|
||||
volume.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null_mut(),
|
||||
name.as_mut_ptr(),
|
||||
length,
|
||||
)
|
||||
};
|
||||
let end = name.iter().position(|&unit| unit == 0).unwrap_or(0);
|
||||
ok != 0 && String::from_utf16_lossy(&name[..end]) == "NTFS"
|
||||
}
|
||||
|
||||
/// Start `program` with `args` as an administrator, through the UAC
|
||||
/// prompt. Returns once the prompt is answered; declining it is an error
|
||||
/// (`ERROR_CANCELLED`).
|
||||
pub fn run_elevated(program: &Path, args: &[OsString]) -> io::Result<()> {
|
||||
let file = wide(program, false)?;
|
||||
let mut line: Vec<u16> = Vec::new();
|
||||
for arg in args {
|
||||
if !line.is_empty() {
|
||||
line.push(u16::from(b' '));
|
||||
}
|
||||
line.extend(quoted(arg));
|
||||
}
|
||||
line.push(0);
|
||||
let verb: Vec<u16> = "runas\0".encode_utf16().collect();
|
||||
// SAFETY: every string is NUL-terminated and outlives the call; a null
|
||||
// window and directory are allowed.
|
||||
let instance = unsafe {
|
||||
windows_sys::Win32::UI::Shell::ShellExecuteW(
|
||||
std::ptr::null_mut(),
|
||||
verb.as_ptr(),
|
||||
file.as_ptr(),
|
||||
line.as_ptr(),
|
||||
std::ptr::null(),
|
||||
windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL,
|
||||
)
|
||||
};
|
||||
// Anything above 32 is success, by the function's own convention.
|
||||
if instance as usize > 32 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
|
||||
/// Write out what the file system holds only in memory for the volume
|
||||
/// holding `path`, its file table included. Flushing a volume takes write
|
||||
/// access, so an administrator. Only a volume mounted as a drive letter:
|
||||
/// for one mounted in a folder, `\\.\X:` would name the drive around it.
|
||||
pub fn flush_volume(path: &Path) -> io::Result<()> {
|
||||
let root = volume_root(path).ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::NotFound, "no volume holds the path")
|
||||
})?;
|
||||
let letter = drive_letter(&root)
|
||||
.ok_or_else(|| io::Error::from(io::ErrorKind::Unsupported))?;
|
||||
OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
|
||||
.open(format!(r"\\.\{letter}:"))?
|
||||
.sync_all()
|
||||
}
|
||||
|
||||
/// `C` when `canonical` is the root of drive `C:`; `None` for anything
|
||||
/// else, a folder or a volume mounted in one.
|
||||
pub fn drive_letter(canonical: &Path) -> Option<char> {
|
||||
let mut components = canonical.components();
|
||||
let Some(Component::Prefix(prefix)) = components.next() else {
|
||||
return None;
|
||||
};
|
||||
let (Prefix::Disk(letter) | Prefix::VerbatimDisk(letter)) = prefix.kind()
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
(components.next() == Some(Component::RootDir)
|
||||
&& components.next().is_none())
|
||||
.then_some(char::from(letter))
|
||||
}
|
||||
|
||||
/// The folder that holds every user's profile, `C:\Users` as installed,
|
||||
/// from Windows itself: it can be moved, so no path is assumed. `None`
|
||||
/// when Windows does not say.
|
||||
pub fn user_profiles_dir() -> Option<PathBuf> {
|
||||
use windows_sys::Win32::System::Com::CoTaskMemFree;
|
||||
use windows_sys::Win32::UI::Shell::{
|
||||
FOLDERID_UserProfiles, SHGetKnownFolderPath,
|
||||
};
|
||||
let mut raw: *mut u16 = std::ptr::null_mut();
|
||||
// SAFETY: the id outlives the call, a null token means this user, and
|
||||
// `raw` receives a string the shell allocates, freed below either way.
|
||||
let result = unsafe {
|
||||
SHGetKnownFolderPath(
|
||||
&FOLDERID_UserProfiles,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
&raw mut raw,
|
||||
)
|
||||
};
|
||||
let path = (result >= 0 && !raw.is_null()).then(|| {
|
||||
// SAFETY: on success `raw` is a NUL-terminated string, read up to
|
||||
// and not past its NUL.
|
||||
unsafe {
|
||||
let mut len = 0;
|
||||
while *raw.add(len) != 0 {
|
||||
len += 1;
|
||||
}
|
||||
PathBuf::from(OsString::from_wide(std::slice::from_raw_parts(
|
||||
raw, len,
|
||||
)))
|
||||
}
|
||||
});
|
||||
// SAFETY: `raw` came from the shell's allocator, or is null, which
|
||||
// the call accepts.
|
||||
unsafe { CoTaskMemFree(raw.cast()) };
|
||||
path
|
||||
}
|
||||
|
||||
/// `arg` quoted so a program's C runtime splits it back out whole: inside
|
||||
/// quotes, backslashes are literal except before a quote, where they must
|
||||
/// be doubled, so `C:\` becomes `"C:\\"` and not `"C:\"`.
|
||||
fn quoted(arg: &OsStr) -> Vec<u16> {
|
||||
let quote = u16::from(b'"');
|
||||
let backslash = u16::from(b'\\');
|
||||
let mut out = vec![quote];
|
||||
let mut slashes = 0;
|
||||
for unit in arg.encode_wide() {
|
||||
if unit == backslash {
|
||||
slashes += 1;
|
||||
continue;
|
||||
}
|
||||
let run = if unit == quote {
|
||||
2 * slashes + 1
|
||||
} else {
|
||||
slashes
|
||||
};
|
||||
out.extend(std::iter::repeat_n(backslash, run));
|
||||
slashes = 0;
|
||||
out.push(unit);
|
||||
}
|
||||
out.extend(std::iter::repeat_n(backslash, 2 * slashes));
|
||||
out.push(quote);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `left` and `right` name the same place, compared the way Windows
|
||||
/// compares names: see [`folded`].
|
||||
pub fn same(left: &Path, right: &Path) -> bool {
|
||||
@@ -615,7 +856,7 @@ fn bytes_from(value: i64) -> u64 {
|
||||
}
|
||||
|
||||
/// A `FILETIME` as Unix seconds, `0` before 1970.
|
||||
const fn unix_seconds(ticks: i64) -> i64 {
|
||||
pub const fn unix_seconds(ticks: i64) -> i64 {
|
||||
if ticks <= EPOCH_TICKS {
|
||||
0
|
||||
} else {
|
||||
@@ -623,6 +864,36 @@ const fn unix_seconds(ticks: i64) -> i64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes aligned to a page, for reads that bypass the file cache: those
|
||||
/// want memory aligned to the disk's sector, which a page always is.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Aligned {
|
||||
pages: Vec<Page>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[repr(C, align(4096))]
|
||||
struct Page([u8; 4096]);
|
||||
|
||||
impl Aligned {
|
||||
/// `len` bytes, their contents whatever the last use left.
|
||||
pub fn bytes(&mut self, len: usize) -> &mut [u8] {
|
||||
let pages = len.div_ceil(size_of::<Page>());
|
||||
if self.pages.len() < pages {
|
||||
self.pages.resize(pages, Page([0; 4096]));
|
||||
}
|
||||
// SAFETY: `Page` is a `repr(C)` byte array, so the pages are one
|
||||
// allocation of initialized bytes with no padding, and `len` fits
|
||||
// in it; the borrow of `self` keeps it alive and unaliased.
|
||||
unsafe {
|
||||
std::slice::from_raw_parts_mut(
|
||||
self.pages.as_mut_ptr().cast::<u8>(),
|
||||
len,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
@@ -643,6 +914,17 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn quoted_arguments_survive_the_command_line() {
|
||||
let quote =
|
||||
|arg: &str| String::from_utf16("ed(OsStr::new(arg))).unwrap();
|
||||
// A drive root's trailing backslash would otherwise escape the quote.
|
||||
assert_eq!(quote(r"C:\"), r#""C:\\""#);
|
||||
assert_eq!(quote(r"C:\Program Files\x"), r#""C:\Program Files\x""#);
|
||||
assert_eq!(quote(r#"a\"b"#), r#""a\\\"b""#);
|
||||
assert_eq!(quote("--metric"), r#""--metric""#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_volume_list_has_the_system_drive() {
|
||||
let drive =
|
||||
@@ -657,7 +939,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn listed(dir: &Path) -> Vec<Entry> {
|
||||
let mut entries: Vec<Entry> = read_dir(dir)
|
||||
let mut entries: Vec<Entry> = read_dir(dir, None)
|
||||
.expect("list")
|
||||
.collect::<io::Result<_>>()
|
||||
.expect("entries");
|
||||
@@ -677,11 +959,40 @@ mod tests {
|
||||
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[0].path(temp.path()), temp.path().join("data.bin"));
|
||||
assert_eq!(entries[1].kind(), Kind::Directory);
|
||||
assert!(entries[0].modified() > 0, "written just now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_text_is_shown_lossy_and_still_opens() {
|
||||
use std::os::windows::ffi::OsStringExt as _;
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
// An unpaired surrogate: NTFS takes it, text cannot hold it.
|
||||
let raw =
|
||||
OsString::from_wide(&[u16::from(b'a'), 0xD800, u16::from(b'b')]);
|
||||
fs::write(temp.path().join(&raw), b"x").expect("write");
|
||||
|
||||
let entries = listed(temp.path());
|
||||
let [entry] = &entries[..] else {
|
||||
panic!("one entry: {}", entries.len());
|
||||
};
|
||||
assert_eq!(entry.name(), "a\u{FFFD}b");
|
||||
assert_eq!(entry.file_name(), raw);
|
||||
assert!(fs::metadata(entry.path(temp.path())).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_local_drive_gives_a_walk_one_volume() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
let canonical = temp.path().canonicalize().expect("canonical");
|
||||
assert!(walk_volume(&canonical).is_some(), "{}", canonical.display());
|
||||
// A share's DFS links lead to other volumes; nothing is asked.
|
||||
for share in [r"\\server\share\dir", r"\\?\UNC\server\share\dir"] {
|
||||
assert_eq!(walk_volume(Path::new(share)), None, "{share}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_allocation_is_whole_clusters_of_the_data() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
@@ -746,11 +1057,15 @@ mod tests {
|
||||
};
|
||||
assert_eq!(kind("junction"), Some(Kind::Link));
|
||||
assert_eq!(kind("target"), Some(Kind::Directory));
|
||||
let through: Vec<OsString> = listed(&junction)
|
||||
let through: Vec<Box<str>> = listed(&junction)
|
||||
.into_iter()
|
||||
.map(|entry| entry.name)
|
||||
.collect();
|
||||
assert_eq!(through, ["inside.bin"], "a walk that enters one follows");
|
||||
assert_eq!(
|
||||
&*through[0], "inside.bin",
|
||||
"a walk that enters one follows"
|
||||
);
|
||||
assert_eq!(through.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -794,6 +1109,7 @@ mod tests {
|
||||
drive.display()
|
||||
);
|
||||
assert!(!is_mount_point(temp.path()));
|
||||
assert!(!file_table_readable(temp.path()), "a folder is walked");
|
||||
assert!(!is_mount_point(drive), "a drive is a root, not a folder");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# The workspace's MSRV, pinned so rustup provisions it automatically: a fresh
|
||||
# clone builds on a machine whose default stable is older, instead of failing
|
||||
# with cargo's `rustc ... is not supported` before anything compiles. CI pins
|
||||
# the same version (see .github/workflows), and `make lint` needs clippy and
|
||||
# rustfmt, so they come with it.
|
||||
[toolchain]
|
||||
channel = "1.97"
|
||||
components = ["clippy", "rustfmt"]
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
# Pass the compiled disktree-core unit test binary as the first argument.
|
||||
# All mounts and writes live in an isolated, temporary /run.
|
||||
set -eu
|
||||
exec unshare --user --map-root-user --mount sh -eu -c '
|
||||
mount --make-rprivate /
|
||||
mount -t tmpfs disktree-test-run /run
|
||||
mkdir -p /run/media/disktree-test /run/disktree-scan
|
||||
mount -t tmpfs tmpfs /run/media/disktree-test
|
||||
mkdir /run/media/disktree-test/nested
|
||||
mount -t tmpfs tmpfs /run/media/disktree-test/nested
|
||||
for dir in original alias one two; do mkdir /run/disktree-scan/$dir; done
|
||||
mkdir /run/disktree-scan/original/nested
|
||||
mount --bind /run/disktree-scan/original /run/disktree-scan/alias
|
||||
for dir in one two; do mount -t tmpfs tmpfs /run/disktree-scan/$dir; done
|
||||
for dir in original one two; do printf data > /run/disktree-scan/$dir/file; done
|
||||
"$1" --exact removal::tests::mounted_media_and_repeated_views --ignored --nocapture
|
||||
' sh "$1"
|
||||
Reference in New Issue
Block a user