mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
Merge remote-tracking branch 'origin/pr/40' into windows-integration
# Conflicts: # crates/disktree-app/src/tests.rs
This commit is contained in:
@@ -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` |
|
||||
|
||||
@@ -288,14 +288,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
|
||||
|
||||
@@ -73,7 +73,7 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
let args = parse_args()?;
|
||||
let args = parse_args(std::env::args_os().skip(1))?;
|
||||
let root = args.root.clone();
|
||||
let depth = args.depth;
|
||||
let title_root = root.clone();
|
||||
@@ -150,15 +150,25 @@ fn run() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_args() -> 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();
|
||||
let mut depth = 3_u32;
|
||||
let mut disk = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
// `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);
|
||||
@@ -172,7 +182,7 @@ fn parse_args() -> 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),
|
||||
@@ -180,7 +190,7 @@ fn parse_args() -> Result<Args> {
|
||||
);
|
||||
}
|
||||
"--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,
|
||||
@@ -195,9 +205,9 @@ fn parse_args() -> 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,6 +417,15 @@ 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>,
|
||||
@@ -505,6 +515,9 @@ 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,
|
||||
panel_rems: PANEL_REMS,
|
||||
scan_started: None,
|
||||
@@ -520,6 +533,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);
|
||||
@@ -562,6 +576,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);
|
||||
@@ -692,7 +707,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;
|
||||
@@ -759,10 +774,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 =
|
||||
@@ -1826,7 +1842,7 @@ impl Disktree {
|
||||
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,
|
||||
@@ -1951,6 +1967,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;
|
||||
@@ -2763,6 +2789,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()
|
||||
@@ -2772,6 +2872,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;
|
||||
|
||||
@@ -1012,6 +1012,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 +1041,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);
|
||||
@@ -1485,3 +1491,45 @@ fn mouse_side_buttons_go_back_and_forward(cx: &mut TestAppContext) {
|
||||
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,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1003,6 +1003,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 +1582,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,
|
||||
|
||||
@@ -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,
|
||||
@@ -165,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
|
||||
@@ -206,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)
|
||||
@@ -224,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,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> {
|
||||
@@ -540,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 size;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -400,6 +400,15 @@ 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) {
|
||||
@@ -616,6 +625,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.
|
||||
@@ -929,6 +961,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,
|
||||
@@ -1479,7 +1523,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
refuse(Path::new("/home/other"), Path::new("/"), Some(&home), &[]),
|
||||
None,
|
||||
"a sibling of home is not"
|
||||
"a sibling of home is not above it"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2155,6 +2199,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() {
|
||||
|
||||
+287
-109
@@ -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,13 +22,13 @@ 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::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;
|
||||
@@ -105,13 +105,21 @@ pub struct ScanSnapshot {
|
||||
}
|
||||
|
||||
impl ScanProgress {
|
||||
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) {
|
||||
@@ -191,6 +199,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();
|
||||
|
||||
@@ -240,6 +249,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();
|
||||
@@ -264,6 +274,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 {
|
||||
@@ -281,33 +295,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
|
||||
}
|
||||
}
|
||||
@@ -315,9 +337,8 @@ impl WalkContext {
|
||||
|
||||
fn classify_dir(
|
||||
&self,
|
||||
entry: &impl Listed,
|
||||
entry: &mut impl Listed,
|
||||
path: PathBuf,
|
||||
name: Box<str>,
|
||||
) -> Classified {
|
||||
if self
|
||||
.never_scanned
|
||||
@@ -344,12 +365,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
|
||||
@@ -374,8 +391,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 {
|
||||
@@ -385,7 +404,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,
|
||||
@@ -422,8 +440,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);
|
||||
@@ -439,7 +459,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;
|
||||
@@ -454,10 +473,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>;
|
||||
@@ -515,18 +538,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() {
|
||||
@@ -539,11 +573,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),
|
||||
})
|
||||
@@ -552,12 +588,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> {
|
||||
@@ -600,19 +640,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.
|
||||
@@ -627,15 +681,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 {
|
||||
@@ -643,21 +707,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,
|
||||
@@ -669,7 +737,7 @@ impl PendingDir {
|
||||
modified: 0,
|
||||
category: crate::classify::Category::Other,
|
||||
reclaim: None,
|
||||
children: std::mem::take(&mut *lock(&self.children)),
|
||||
children: partial.children,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -682,23 +750,64 @@ 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 never = crate::space::never_scanned(root, canonical);
|
||||
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));
|
||||
rayon::scope(|scope| walk(scope, &root_dir, context));
|
||||
let root_dir = Arc::new(PendingDir::new(
|
||||
root.to_path_buf(),
|
||||
file_name(root),
|
||||
None,
|
||||
0,
|
||||
));
|
||||
let context: &WalkContext = context;
|
||||
WALK_POOL.install(|| rayon::scope(|scope| walk(scope, &root_dir, context)));
|
||||
|
||||
let node = lock(&context.root).take();
|
||||
let node = node.ok_or_else(|| {
|
||||
@@ -707,32 +816,101 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
|
||||
Ok(finish_tree(node, &context.options))
|
||||
}
|
||||
|
||||
/// 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 walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
|
||||
fn walk<'scope>(
|
||||
scope: &Scope<'scope>,
|
||||
dir: &Arc<PendingDir>,
|
||||
context: &'scope WalkContext,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
@@ -744,6 +922,7 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
|
||||
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.
|
||||
@@ -751,20 +930,30 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
|
||||
.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);
|
||||
}
|
||||
if descend {
|
||||
for subdir in subdirs {
|
||||
if context.cancelled() {
|
||||
break;
|
||||
}
|
||||
dir.pending.fetch_add(1, Ordering::AcqRel);
|
||||
let subdir = Arc::clone(&subdir);
|
||||
let context = Arc::clone(context);
|
||||
scope.spawn(move |scope| walk(scope, &subdir, &context));
|
||||
scope.spawn(move |scope| walk(scope, &subdir, context));
|
||||
}
|
||||
}
|
||||
lock(&dir.children).extend(leaves);
|
||||
|
||||
signal_done(&Arc::clone(dir), context);
|
||||
signal_done(dir, context);
|
||||
}
|
||||
|
||||
/// Report that one task for `dir` is done: either its own scan, or one of its
|
||||
@@ -773,44 +962,32 @@ fn walk(scope: &Scope<'_>, dir: &Arc<PendingDir>, context: &Arc<WalkContext>) {
|
||||
/// 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
|
||||
@@ -958,7 +1135,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(),
|
||||
@@ -969,7 +1146,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)
|
||||
}
|
||||
|
||||
@@ -1269,6 +1446,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));
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user