diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d14d6e..e97abec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,10 @@ on: branches: [main] pull_request: +# Pull requests run here, so the token can read and nothing more. +permissions: + contents: read + concurrency: group: ci-${{ github.ref }} cancel-in-progress: true @@ -43,3 +47,54 @@ jobs: - name: Test run: cargo xtask test + + check-macos: + name: Lint and test (macOS) + # Apple silicon. No system libraries to install, and no Metal toolchain + # either: gpui-kit builds GPUI with runtime shader compilation, so the + # shaders compile when the app starts, not here. + runs-on: macos-15 + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + components: clippy, rustfmt + + - uses: Swatinem/rust-cache@v2 + + - name: Lint + run: cargo xtask lint + + - name: Test + run: cargo xtask test + + # The app bundle, signed ad hoc: catches a broken Info.plist, icon or + # signature before a release does. + - name: Bundle + run: cargo xtask bundle + + windows: + name: Lint and test (Windows) + runs-on: windows-2025 + steps: + # Check out with the repository's own line endings, as on Linux. + - run: git config --global core.autocrlf false + + - uses: actions/checkout@v5 + + # Pinned with the Linux job, for the same reason. GPUI needs nothing + # beyond the Windows SDK the runner already has. + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + components: clippy, rustfmt + + - uses: Swatinem/rust-cache@v2 + + - name: Lint + run: cargo xtask lint + + - name: Test + run: cargo xtask test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed382d8..b3cc857 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,6 +23,9 @@ jobs: # The oldest supported runner: its glibc is what the binary needs at # least, so building here runs on the most systems. runs-on: ubuntu-22.04 + outputs: + tag: ${{ steps.version.outputs.tag }} + version: ${{ steps.version.outputs.version }} steps: - uses: actions/checkout@v5 with: @@ -30,8 +33,12 @@ jobs: - name: Version id: version + # Through the environment, not spliced into the script: a tag typed + # into the dispatch form is text, never shell. + env: + TAG: ${{ inputs.tag || github.ref_name }} run: | - tag="${{ inputs.tag || github.ref_name }}" + tag="$TAG" version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) if [ "$tag" != "v$version" ]; then echo "tag $tag does not match Cargo.toml version $version" >&2 @@ -86,3 +93,146 @@ jobs: gh release create "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" \ --title "disktree ${TAG#v}" --generate-notes fi + + release-macos: + name: Build and publish (macOS) + # After the Linux job, which creates the release: two jobs racing to + # create it would leave one failing. + needs: release + runs-on: macos-15 + env: + # Signing and notarizing happen only when the repository has these + # secrets; without them the app is signed ad hoc, and a downloaded + # copy needs "Open Anyway" in System Settings once. + # MACOS_CERTIFICATE base64 of the Developer ID .p12 + # MACOS_CERTIFICATE_PASSWORD its password + # MACOS_SIGN_IDENTITY "Developer ID Application: Name (TEAMID)" + # NOTARY_KEY_P8 base64 of an App Store Connect API key + # NOTARY_KEY_ID, NOTARY_ISSUER that key's ID and issuer + MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} + MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} + MACOS_SIGN_IDENTITY: ${{ secrets.MACOS_SIGN_IDENTITY }} + NOTARY_KEY_P8: ${{ secrets.NOTARY_KEY_P8 }} + NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }} + NOTARY_ISSUER: ${{ secrets.NOTARY_ISSUER }} + steps: + - uses: actions/checkout@v5 + with: + ref: ${{ inputs.tag || github.ref }} + + - name: Version + id: version + # Through the environment, not spliced into the script: a tag typed + # into the dispatch form is text, never shell. + env: + TAG: ${{ inputs.tag || github.ref_name }} + run: | + tag="$TAG" + version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) + if [ "$tag" != "v$version" ]; then + echo "tag $tag does not match Cargo.toml version $version" >&2 + exit 1 + fi + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + + - uses: Swatinem/rust-cache@v2 + + - name: Test + run: cargo xtask test + + # A keychain of its own for the certificate, deleted with the runner. + - name: Signing certificate + if: env.MACOS_CERTIFICATE != '' + run: | + keychain="$RUNNER_TEMP/signing.keychain-db" + password=$(uuidgen) + echo "$MACOS_CERTIFICATE" | base64 --decode > "$RUNNER_TEMP/cert.p12" + security create-keychain -p "$password" "$keychain" + security set-keychain-settings -lut 3600 "$keychain" + security unlock-keychain -p "$password" "$keychain" + security import "$RUNNER_TEMP/cert.p12" -k "$keychain" \ + -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign + security set-key-partition-list -S apple-tool:,apple: \ + -s -k "$password" "$keychain" + security list-keychains -d user -s "$keychain" \ + $(security list-keychains -d user | tr -d '"') + rm "$RUNNER_TEMP/cert.p12" + + - name: Bundle + run: | + args=() + if [ -n "$MACOS_CERTIFICATE" ]; then + args+=(--sign "$MACOS_SIGN_IDENTITY") + if [ -n "$NOTARY_KEY_P8" ]; then + echo "$NOTARY_KEY_P8" | base64 --decode \ + > "$RUNNER_TEMP/AuthKey.p8" + export NOTARY_KEY="$RUNNER_TEMP/AuthKey.p8" + args+=(--notarize) + fi + fi + cargo xtask bundle "${args[@]}" + + - name: Publish + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.version.outputs.tag }} + run: | + zip="target/bundle/disktree-${{ steps.version.outputs.version }}-aarch64-macos.zip" + (cd "$(dirname "$zip")" && shasum -a 256 "$(basename "$zip")" \ + > "$(basename "$zip").sha256") + gh release upload "$TAG" "$zip" "$zip.sha256" --clobber + + windows: + name: Build and publish (Windows) + # After the Linux job, which checks the tag and creates the release. + needs: release + runs-on: windows-2025 + env: + # The C runtime linked in, so disktree.exe also runs where the Visual + # C++ runtime was never installed. For the tests too, so both steps + # share one build. + RUSTFLAGS: -C target-feature=+crt-static + steps: + - run: git config --global core.autocrlf false + + - uses: actions/checkout@v5 + with: + ref: ${{ inputs.tag || github.ref }} + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.97" + + - uses: Swatinem/rust-cache@v2 + + - name: Test + run: cargo xtask test + + - name: Build + run: cargo build --release --locked -p disktree-app + + - name: Package + id: package + shell: pwsh + run: | + $name = "disktree-${{ needs.release.outputs.version }}-x86_64-windows" + New-Item -ItemType Directory -Force "dist/$name" | Out-Null + Copy-Item target/release/disktree.exe, README.md, LICENSE "dist/$name/" + Compress-Archive -Path "dist/$name" -DestinationPath "dist/$name.zip" + $hash = (Get-FileHash "dist/$name.zip" -Algorithm SHA256).Hash.ToLower() + # The format `sha256sum -c` reads, with a Unix line ending. + [IO.File]::WriteAllText("dist/$name.zip.sha256", "$hash $name.zip`n") + "archive=dist/$name.zip" >> $env:GITHUB_OUTPUT + + - name: Publish + shell: bash + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.release.outputs.tag }} + ARCHIVE: ${{ steps.package.outputs.archive }} + run: gh release upload "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" --clobber diff --git a/AGENTS.md b/AGENTS.md index 30a5414..ff8491b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ make run # build and run, scanning $HOME make install # ~/.local: binary, desktop entry, icon make install PREFIX=/usr/local # system-wide (needs root) make uninstall +make bundle # macOS: target/bundle/disktree.app and its zip make lint # rustfmt --check, then clippy --all-targets -D warnings make test # core and window-harness tests make ci # lint, then test @@ -30,8 +31,15 @@ prefix and the crate version) and `assets/disktree.svg`. Keep the desktop entry's `Categories` to a single main category plus additional ones, or `desktop-file-validate` complains. +On macOS `make install` installs `target/bundle/disktree.app` into +`~/Applications` instead, built by `cargo xtask bundle` from +`packaging/macos/` (the `Info.plist` template and the icon's SVG). The bundle +identifier there keys every macOS permission grant; do not change it lightly. + `cargo xtask lint` is the gate. It must be green before anything is called done, and it must not fix anything: a red local run is the same signal CI gives. +On Windows, where there is no make, run `cargo xtask lint`, `cargo xtask test` +and `cargo build --release` directly; CI runs the gate on both systems. ## House rules @@ -54,7 +62,8 @@ done, and it must not fix anything: a red local run is the same signal CI gives. ## Invariants 1. **Sizes come from `st_blocks * 512` unless apparent size was asked for.** - That is the number that comes back when a file is deleted. + That is the number that comes back when a file is deleted. On Windows it + is the allocation the directory listing reports; see `windows.rs`. 2. **`own_bytes`/`own_files` are derived, never tracked.** `tree::aggregate` computes the totals from the children. Hardlink de-duplication rewrites a leaf's weight and re-aggregates; anything that patches `bytes` directly will @@ -63,7 +72,8 @@ done, and it must not fix anything: a red local run is the same signal CI gives. has finished.** That is the `+1` sentinel in `PendingDir::pending`. Building early silently drops whole subtrees — it has happened once. 4. **Only paths under the scanned root may be removed**, and mount points, the - root, the home directory and symlink targets are refused. + root, the home directory, any directory holding it, and symlink targets are + refused. 5. **Marks are keyed by absolute path**, not tree position, so they survive a re-scan; `Marks::refresh` re-reads their sizes and drops what is gone. 6. **The treemap is painted, not composed of elements.** Thousands of @@ -88,6 +98,7 @@ done, and it must not fix anything: a red local run is the same signal CI gives. | tile geometry, nesting, the merged tail | `crates/disktree-core/src/treemap.rs` | | anything that deletes, or refuses to | `crates/disktree-core/src/removal.rs` | | free space and projections | `crates/disktree-core/src/space.rs` | +| what Windows lists, measures and compares differently | `crates/disktree-core/src/windows.rs` — the only `unsafe` | | a key, a screen transition, a mark | `crates/disktree-app/src/state.rs` | | spacing, type and size | `crates/disktree-app/src/ui.rs` — tokens only, no `px` in layout | | the mosaic's painting or labels | `crates/disktree-app/src/treemap_view.rs` | diff --git a/Cargo.lock b/Cargo.lock index 4047a24..ee104b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1424,10 +1424,12 @@ version = "0.9.1" dependencies = [ "anyhow", "disktree-core", + "dunce", "gpui-kit", "gpui-omarchy", "rustc-hash 2.1.3", "tempfile", + "windows-sys 0.61.2", ] [[package]] @@ -1439,6 +1441,9 @@ dependencies = [ "rustc-hash 2.1.3", "rustix", "tempfile", + "trash", + "winapi-util", + "windows-sys 0.61.2", ] [[package]] @@ -7071,6 +7076,23 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "trash" +version = "5.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317" +dependencies = [ + "libc", + "log", + "objc2 0.6.4", + "objc2-foundation 0.3.2", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows 0.62.2", +] + [[package]] name = "triomphe" version = "0.1.16" @@ -7228,6 +7250,12 @@ dependencies = [ "serde", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "usvg" version = "0.45.1" diff --git a/Makefile b/Makefile index 1e86866..b3c8fcc 100644 --- a/Makefile +++ b/Makefile @@ -6,19 +6,27 @@ # # make install # ~/.local/bin/disktree # sudo make install PREFIX=/usr/local # system-wide +# +# On macOS it installs disktree.app into ~/Applications instead (APPS to +# change that), plus a `disktree` command in BINDIR that runs the app's +# binary, so both Spotlight and a terminal find it. PREFIX ?= $(HOME)/.local BINDIR ?= $(PREFIX)/bin APPDIR ?= $(PREFIX)/share/applications ICONDIR ?= $(PREFIX)/share/icons/hicolor/scalable/apps +APPS ?= $(HOME)/Applications +BUNDLE = target/bundle/disktree.app +UNAME := $(shell uname -s) + MANIFEST = Cargo.toml CARGO ?= cargo TARGET = target/release/disktree ICON = assets/disktree.svg DESKTOP = packaging/disktree.desktop.in -.PHONY: help build run install uninstall lint test ci fmt clean +.PHONY: help build run install uninstall bundle lint test ci fmt clean help: @echo "disktree" @@ -26,6 +34,8 @@ help: @echo " make build release build" @echo " make run build and run, scanning $$HOME" @echo " make install install to $(PREFIX): binary, desktop entry, icon" + @echo " (macOS: disktree.app into $(APPS))" + @echo " make bundle macOS: build target/bundle/disktree.app and its zip" @echo " make uninstall remove what install put there" @echo " make lint rustfmt --check and clippy -D warnings" @echo " make test core and window-harness tests" @@ -53,6 +63,27 @@ ci: lint test fmt: $(CARGO) xtask fmt-fix +ifeq ($(UNAME),Darwin) +# Replaced whole rather than copied over: a stale file left inside a signed +# bundle breaks its signature. +install: + $(CARGO) xtask bundle + install -d "$(APPS)" "$(BINDIR)" + rm -rf "$(APPS)/disktree.app" + ditto "$(BUNDLE)" "$(APPS)/disktree.app" + ln -sf "$(APPS)/disktree.app/Contents/MacOS/disktree" "$(BINDIR)/disktree" + @echo + @echo "installed:" + @echo " $(APPS)/disktree.app" + @echo " $(BINDIR)/disktree -> the app's binary" + @case ":$$PATH:" in *":$(BINDIR):"*) ;; *) \ + echo; echo "note: $(BINDIR) is not on PATH in this shell";; esac + +uninstall: + rm -rf "$(APPS)/disktree.app" + @if [ -L "$(BINDIR)/disktree" ]; then rm -f "$(BINDIR)/disktree"; fi + @echo "removed" +else install: build install -d $(BINDIR) $(APPDIR) $(ICONDIR) install -m755 $(TARGET) $(BINDIR)/disktree @@ -81,6 +112,10 @@ uninstall: update-desktop-database $(APPDIR) 2>/dev/null || true; \ fi @echo "removed" +endif + +bundle: + $(CARGO) xtask bundle clean: $(CARGO) clean diff --git a/README.md b/README.md index e1c1580..cb9d37e 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,63 @@ removes exactly what was installed. You need Rust 1.97 or newer and a Wayland or X11 session with a GPU that GPUI can drive (Vulkan). +### macOS + +Download `disktree-*-aarch64-macos.zip` from the +[latest release](https://github.com/tobi/disktree/releases/latest), unzip it, +and drag `disktree.app` into Applications. Apple silicon and macOS 11 or +newer. A release that was not signed and notarized is stopped by Gatekeeper +the first time: open it once, then choose **Open Anyway** in System Settings +› Privacy & Security. + +Or build it, with Rust 1.97 or newer and Xcode or its Command Line Tools: + +```sh +make install # ~/Applications/disktree.app, and ~/.local/bin/disktree +make uninstall +``` + +To see everything, give disktree **Full Disk Access** in System Settings › +Privacy & Security (the panel offers a button when it is missing), then +reopen it. Without it macOS hides Mail, Messages, Safari, other apps' data +and the Trash, and disktree counts them as unreadable. Started from a +terminal, it is the terminal that needs the access. macOS also asks once +each for Desktop, Documents and Downloads. + +What is different from Linux: + +- **Free space** is what `df` reports. Finder's figure is larger: it counts + purgeable space (caches and local snapshots macOS will clear on its own). +- **Cloned files** (copies APFS shares blocks between, as Finder's Duplicate + makes) are each counted in full, so a total can exceed what deleting them + frees. +- **Time Machine's local snapshots** are not files and do not appear; they + are part of the gap between the scan and the disk's used space. +- **Cloud-only folders** (iCloud Drive, Dropbox and the like, evicted to the + server) are not opened, so a scan never downloads them. + +To sign and notarize a build for others, with a Developer ID certificate in +the keychain and credentials saved by `xcrun notarytool store-credentials`: + +```sh +NOTARY_PROFILE= cargo xtask bundle \ + --sign "Developer ID Application: Name (TEAMID)" --notarize +``` + +### Windows + +On Windows 10 or 11, download `disktree-*-x86_64-windows.zip` from the same +release, unpack it anywhere and run `disktree.exe`. Or build it with the MSVC +toolchain (Visual Studio Build Tools, C++ workload): + +```powershell +git clone https://github.com/tobi/disktree +cd disktree +cargo build --release # target\release\disktree.exe +``` + +See [On Windows](#on-windows) for what differs there. + ## Use ```sh @@ -99,17 +156,21 @@ Scroll to magnify toward the pointer. The wheel magnifies until the directory under the pointer fills the view, and the next notch goes into it — one continuous motion, with the directory's contents growing into place. Scroll the other way to come back out. Enter goes into the selected directory at any -depth, and Backspace or Escape goes up one level. `+` and `-` magnify without -going in; `0` resets. +depth, and Backspace or Escape goes up one level. `<` and `>`, beside the +Size / Files / Age switch, go back and forward through the directories visited, +as do `alt ←` `alt →` (also `⌘[` `⌘]` on macOS) and the mouse's side +buttons. `+` and `-` magnify without going in; `0` resets. ### Removing `c` (or **Review…**) opens the list of everything marked. Unmark anything there, then choose: -- **Move to trash** — the default when a trash is available (`trash-put` from - trash-cli, then `gio trash`, then a built-in XDG trash). Recoverable until - the trash is emptied, so it commits directly. +- **Move to trash** — the default when a trash is available. On macOS that is + the system Trash, the same move as Finder's (on another disk, that disk's + own Trash; network shares often have none). Elsewhere it is `trash-put` + from trash-cli, then `gio trash`, then a built-in XDG trash. Recoverable + until the trash is emptied, so it commits directly. - **Delete permanently** — `rm -rf` semantics. It always asks first, in a dialog that names what goes and how much comes back. @@ -121,16 +182,17 @@ and shows how much free space was actually gained. | key | does | | --- | --- | | `space` / `x` | mark or unmark the tile you point at | -| `ctrl`-click | mark without moving the selection | +| `ctrl`-click (`⌘`-click on macOS) | mark without moving the selection | | `enter` | open that directory, at any depth | | `⌫` / `esc` | go up one directory | +| `alt ←` `alt →` | back and forward through where you have been | | `←` `↑` `↓` `→` | move between tiles at this level | | `tab` | next largest sibling | | scroll | zoom toward a directory, then go into it | | `shift`-scroll | pan the magnified view | | `[` `]` | draw fewer or more levels at once | | `-` `=` `0` | magnify, shrink, reset the view | -| `ctrl =` `ctrl -` `ctrl 0` | interface zoom | +| `ctrl =` `ctrl -` `ctrl 0` (`⌘` on macOS) | interface zoom | | `/` | filter by name: only matches keep their colour; `enter` shows only them, `esc` clears | | `c` | review the marked list | | `t` | rank by size or by file count | @@ -139,9 +201,14 @@ and shows how much free space was actually gained. | `r` | scan again | | `g` | the whole disk | | `p` | show or hide the selection line | +| `o` | show it in Finder or the file manager | | `?` | every key | | `q` | quit | +On macOS the menu bar also has ⌘O to open a folder, ⌘⇧R to show the +selection in Finder, ⌘R to rescan, and ⌘Q, ⌘H and ⌘W (closing the window +quits); other ⌘ chords are left to the system. + On the review screen: `m` trash, `p` permanent, `!` unmark all, `enter` commits, `esc` goes back. @@ -164,7 +231,9 @@ and removes duplicate hardlinks. Click `/` (or any directory above the scanned root) in the trail, press `g`, run `disktree --disk`, or use the launcher's *Scan the whole disk* action. `g` and `--disk` scan the disk your home directory lives on — `/` -on Omarchy. +on Omarchy and on macOS. On macOS the Data volume's second mount, +`/System/Volumes/Data`, is skipped: it is `/Users`, `/Applications` and the +rest again under other names. Widening is memoized: the tree already measured is handed to the wider walk and reused where it is reached, so going from `~` to `/` reads only what is @@ -184,6 +253,31 @@ twice. `-X` crosses into everything. Without root, some system directories cannot be read; they are counted as unreadable in the top bar rather than guessed at. +## On Windows + +The same program, with Windows' answers to the questions above: + +- **Disk usage** is the allocation NTFS reports for each file: whole + clusters, less for a compressed or sparse file, nothing for one small + enough to live in its file record. It arrives with the directory listing + itself (`FileIdExtdDirectoryInfo`), so it costs no more than the walk. + Hardlinks count once on NTFS. +- **The whole disk** is the drive your profile is on, usually `C:\`. A + folder another volume is mounted on is a link, like a junction, and is + not entered, so a scan stays on one volume; `-l` follows links, and with + them mounted folders. +- **Move to trash** is the Recycle Bin, through the shell, which asks + before destroying anything it cannot recycle. +- **Refused besides the rules below:** Windows, Program Files and + ProgramData, what Windows keeps at the top of its drive (System Volume + Information, Recovery, Boot), and any folder holding your profile, such as + `C:\Users`. Names compare without regard to case, as Windows compares + them. +- **Hidden** still means a name starting with a dot; the hidden attribute is + not consulted, so `-H` does not drop `AppData`. +- **The theme** is gpui-omarchy's default, since there is no Omarchy theme + to follow. + ## What it refuses to do The removal rules live in `crates/disktree-core/src/removal.rs`, and each one is @@ -191,18 +285,28 @@ tested: - only paths under the scanned root can be removed; - the filesystem root, the scanned root and your home directory are refused; -- a mount point is refused, since removing it would reach into another - filesystem; +- a mount point is refused, and so is anything with a mount point inside it, + since removing it would reach into another filesystem; permanent deletion + also stops at a mount boundary rather than descending into one (a btrfs + subvolume that is not mounted goes with its directory, as the scan shows + it); +- a directory holding your home directory or a system tree is refused (on + macOS `/Users` is on the same volume as `/`, and `/opt` holds + `/opt/homebrew`); - system trees (`/usr`, `/etc`, `/boot`, `/var/lib`, `/nix/store`, …) are refused even where permissions would allow it: packages own them, and pacman, paccache or `journalctl --vacuum` are the tools; - a symlink is unlinked, never followed; -- nothing is passed through a shell — a file called `-rf` is just a file. +- nothing is passed through a shell — a file called `-rf` is just a file; +- selecting a checkout never runs a program it names: git is asked with its + fsmonitor, hooks and pager off, and a checkout that defines its own filter + drivers is not asked for its status at all ("changes unknown"). ## On Hyprland Hyprland tiles new windows, so disktree opens into whatever tile it is given. -It is designed for a roomy window; float it, or give it a rule: +It is designed for a roomy window; float it, or give it a rule. The window +class is `disktree`. ``` windowrule = float, class:^(disktree)$ diff --git a/crates/disktree-app/Cargo.toml b/crates/disktree-app/Cargo.toml index 63644e0..02d93aa 100644 --- a/crates/disktree-app/Cargo.toml +++ b/crates/disktree-app/Cargo.toml @@ -18,8 +18,12 @@ gpui-kit = { version = "=0.6.1", default-features = false, features = ["assets"] gpui-omarchy = "0.1.2" disktree-core = { workspace = true } anyhow = { workspace = true } +dunce = "1.0.5" rustc-hash = { workspace = true } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_System_Console"] } + [dev-dependencies] # The window harness: it lets the tests draw a real frame and press real keys. gpui-kit = { version = "=0.6.1", default-features = false, features = [ diff --git a/crates/disktree-app/src/app_menu.rs b/crates/disktree-app/src/app_menu.rs new file mode 100644 index 0000000..00804ca --- /dev/null +++ b/crates/disktree-app/src/app_menu.rs @@ -0,0 +1,108 @@ +//! The menu bar and the application-wide shortcuts. +//! +//! GPUI adds neither on its own. On macOS an app without them has an empty +//! menu bar and no ⌘Q, so this is where disktree becomes a Mac app; on +//! Linux the desktop owns quitting and there is no menu bar to fill, so only +//! "closing the window quits" applies there. + +use gpui_kit::{App, KeyBinding, Menu, MenuItem, SystemMenuType}; + +pub use menu_actions::*; + +#[allow( + clippy::derive_partial_eq_without_eq, + reason = "GPUI's actions! macro writes the derives, not us" +)] +mod menu_actions { + use gpui_kit::actions; + + actions!( + disktree, + [ + /// Quit the application. + Quit, + /// Hide the application's windows. + Hide, + /// Hide every other application. + HideOthers, + /// Show every application again. + ShowAll, + /// Close the focused window, which quits: there is only one. + CloseWindow, + /// Scan the current root again. + Rescan, + /// Choose a directory to scan. + OpenFolder, + /// Reveal the tile a key acts on in Finder. + ShowInFinder, + /// Back through the directories visited. + GoBack, + /// Forward again, after going back. + GoForward, + ] + ); +} + +/// Install the menus, the shortcuts and the quit-on-close rule. +pub fn install(cx: &mut App) { + // A single-window utility has nothing left to show once its window is + // gone; staying alive would leave a Dock icon with no window behind it. + cx.on_window_closed(|cx, _| { + if cx.windows().is_empty() { + cx.quit(); + } + }) + .detach(); + + if !cfg!(target_os = "macos") { + return; + } + cx.on_action(|_: &Quit, cx| cx.quit()); + cx.on_action(|_: &Hide, cx| cx.hide()); + cx.on_action(|_: &HideOthers, cx| cx.hide_other_apps()); + cx.on_action(|_: &ShowAll, cx| cx.unhide_other_apps()); + cx.on_action(|_: &CloseWindow, cx| { + if let Some(window) = cx.active_window() { + let _ = window.update(cx, |_, window, _| window.remove_window()); + } + }); + // `Rescan`, `OpenFolder`, `ShowInFinder` and the history are handled by + // the window, which owns the scan and the selection; see `views::root`. + cx.bind_keys([ + KeyBinding::new("cmd-q", Quit, None), + KeyBinding::new("cmd-h", Hide, None), + KeyBinding::new("alt-cmd-h", HideOthers, None), + KeyBinding::new("cmd-w", CloseWindow, None), + KeyBinding::new("cmd-r", Rescan, None), + KeyBinding::new("cmd-o", OpenFolder, None), + // ⌘R is taken by Rescan, as in a browser; Xcode uses ⌘⇧R-like + // chords for its reveals, and `o` does the same without a modifier. + KeyBinding::new("cmd-shift-r", ShowInFinder, None), + // Finder's and Safari's back and forward; alt-arrows work too. + KeyBinding::new("cmd-[", GoBack, None), + KeyBinding::new("cmd-]", GoForward, None), + ]); + cx.set_menus([ + Menu::new("disktree").items([ + MenuItem::os_submenu("Services", SystemMenuType::Services), + MenuItem::separator(), + MenuItem::action("Hide disktree", Hide), + MenuItem::action("Hide Others", HideOthers), + MenuItem::action("Show All", ShowAll), + MenuItem::separator(), + MenuItem::action("Quit disktree", Quit), + ]), + Menu::new("File").items([ + MenuItem::action("Open Folder\u{2026}", OpenFolder), + MenuItem::action("Show in Finder", ShowInFinder), + MenuItem::separator(), + MenuItem::action("Rescan", Rescan), + MenuItem::separator(), + MenuItem::action("Close Window", CloseWindow), + ]), + Menu::new("Go").items([ + MenuItem::action("Back", GoBack), + MenuItem::action("Forward", GoForward), + ]), + ]); +} diff --git a/crates/disktree-app/src/appearance.rs b/crates/disktree-app/src/appearance.rs new file mode 100644 index 0000000..caa1eb6 --- /dev/null +++ b/crates/disktree-app/src/appearance.rs @@ -0,0 +1,43 @@ +//! Light or dark when there is no Omarchy theme to follow. +//! +//! On Omarchy, gpui-omarchy follows the desktop's theme files. A Mac has none, +//! and gpui-omarchy would then stay on its dark default whatever the system +//! is set to; there the app follows the system appearance instead, with the +//! crate's own dark and light palettes, and switches when it does. + +use std::path::Path; + +use gpui_kit::{App, Window, WindowAppearance}; +use gpui_omarchy::Theme; + +/// Whether the system appearance, rather than an Omarchy theme, decides the +/// colours: on macOS, unless an Omarchy theme is installed there anyway. +pub fn follows_system(home: Option<&Path>) -> bool { + cfg!(target_os = "macos") + && !home.is_some_and(|home| { + [".local/state/omarchy/current", ".config/omarchy/current"] + .iter() + .any(|theme| home.join(theme).exists()) + }) +} + +/// Apply the palette for `appearance`. Applying an explicit theme also stops +/// gpui-omarchy watching for theme files that are not there. +pub fn apply(appearance: WindowAppearance, cx: &mut App) { + let theme = match appearance { + WindowAppearance::Light | WindowAppearance::VibrantLight => { + Theme::flexoki_light() + } + WindowAppearance::Dark | WindowAppearance::VibrantDark => { + Theme::tokyo_night() + } + }; + theme.apply(cx); +} + +/// Follow `window`'s appearance from now on. +pub fn follow(window: &Window) { + window + .observe_window_appearance(|window, cx| apply(window.appearance(), cx)) + .detach(); +} diff --git a/crates/disktree-app/src/git.rs b/crates/disktree-app/src/git.rs index 5c52eb6..ec88f55 100644 --- a/crates/disktree-app/src/git.rs +++ b/crates/disktree-app/src/git.rs @@ -12,7 +12,9 @@ use std::process::{Command, Stdio}; #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct GitState { /// Paths `git status --porcelain` lists: changed, staged or untracked. - pub changed: usize, + /// `None` when asking would run a program the checkout names; see + /// [`names_its_own_filters`]. + pub changed: Option, pub stashes: usize, /// Commits ahead of the upstream; `None` when there is no upstream. pub unpushed: Option, @@ -21,7 +23,7 @@ pub struct GitState { impl GitState { /// Nothing would be lost by deleting it. pub const fn is_clean(&self) -> bool { - self.changed == 0 + matches!(self.changed, Some(0)) && self.stashes == 0 && matches!(self.unpushed, Some(0)) } @@ -29,10 +31,10 @@ impl GitState { /// One short line: `clean, no stash`, `3 changed, 1 stash, 2 unpushed`. pub fn summary(&self) -> String { let mut parts = Vec::new(); - parts.push(if self.changed == 0 { - "clean".to_string() - } else { - format!("{} changed", self.changed) + parts.push(match self.changed { + Some(0) => "clean".to_string(), + Some(count) => format!("{count} changed"), + None => "changes unknown".to_string(), }); parts.push(match self.stashes { 0 => "no stash".to_string(), @@ -56,13 +58,28 @@ pub fn is_checkout(path: &Path) -> bool { /// Ask git. `None` when `path` is not a checkout or git is not installed. pub fn state(path: &Path) -> Option { - if !is_checkout(path) { + if !is_checkout(path) || !git_installed() { return None; } - let status = run(path, &["status", "--porcelain=v1", "-z"])?; - let changed = status.split('\0').filter(|line| !line.is_empty()).count(); - let stashes = - run(path, &["stash", "list"]).map_or(0, |list| list.lines().count()); + let changed = if names_its_own_filters(path) { + None + } else { + // Submodules are other checkouts with configs of their own. + let status = run( + path, + &["status", "--porcelain=v1", "-z", "--ignore-submodules=all"], + )?; + Some(status.split('\0').filter(|line| !line.is_empty()).count()) + }; + // Counted from the reflog, not listed: `stash list` is `git log`, which + // verifies signatures with the checkout's `gpg.program` when its config + // sets `log.showSignature`. + let stashes = run( + path, + &["rev-list", "--walk-reflogs", "--count", "refs/stash"], + ) + .and_then(|count| count.trim().parse().ok()) + .unwrap_or(0); let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"]) .and_then(|count| count.trim().parse().ok()); Some(GitState { @@ -72,24 +89,115 @@ pub fn state(path: &Path) -> Option { }) } +/// Whether running `git` runs git. On macOS `/usr/bin/git` is there even +/// without the developer tools, as a stub that opens an "install the command +/// line developer tools" dialog, which selecting a checkout must not do. +/// `xcode-select -p` answers without prompting. It names the selected +/// developer directory even after that directory was deleted, so the path +/// must also still be there. Asked once. +fn git_installed() -> bool { + static INSTALLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *INSTALLED.get_or_init(|| { + if !cfg!(target_os = "macos") { + return true; + } + Command::new("xcode-select") + .arg("-p") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .is_ok_and(|output| { + output.status.success() + && Path::new(String::from_utf8_lossy(&output.stdout).trim()) + .is_dir() + }) + }) +} + +/// Whether the checkout's own config defines filter drivers. +/// +/// `git status` runs a file's `clean` filter to compare it with the index, +/// and a downloaded repository can name any program as one in `.git/config` +/// and switch it on from its `.gitattributes`. No `-c` can turn off drivers +/// whose names are not known in advance, so a checkout that defines any is +/// not asked for its status at all. Filters from the user's own config, such +/// as git-lfs, are theirs and still run. Reading config runs nothing; if it +/// cannot be read, the answer is the cautious one. +fn names_its_own_filters(path: &Path) -> bool { + let Some(output) = git( + path, + &[ + "config", + "--show-scope", + "--includes", + "--get-regexp", + r"^filter\.", + ], + ) else { + return true; + }; + match output.status.code() { + // No filter anywhere. + Some(1) => false, + Some(0) => { + String::from_utf8_lossy(&output.stdout).lines().any(|line| { + matches!(line.split('\t').next(), Some("local" | "worktree")) + }) + } + _ => true, + } +} + fn run(path: &Path, args: &[&str]) -> Option { - let output = Command::new("git") - .arg("-C") - .arg(path) - .args(args) - // Never prompt, never page, never take a lock for the index refresh. - .env("GIT_TERMINAL_PROMPT", "0") - .env("GIT_OPTIONAL_LOCKS", "0") - .stdin(Stdio::null()) - .stderr(Stdio::null()) - .output() - .ok()?; + let output = git(path, args)?; output .status .success() .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) } +fn git(path: &Path, args: &[&str]) -> Option { + Command::new("git") + .arg("-C") + .arg(path) + // A checkout's own config can name programs for git to run: an + // fsmonitor on every `status`, hooks, a pager. Selecting a directory + // in a disk viewer must not execute anything it contains, and a + // command-line `-c` outranks the repository's config. (From + // tobi/disktree#10.) Also a signature verifier, and whatever a + // partial clone would run to fetch a missing object: nothing here + // may reach the network either. + .args([ + "-c", + "core.fsmonitor=false", + "-c", + "core.hooksPath=/dev/null", + "-c", + "core.pager=cat", + "-c", + "log.showSignature=false", + "-c", + "gpg.program=false", + "-c", + "gpg.ssh.program=false", + "-c", + "gpg.x509.program=false", + "-c", + "core.sshCommand=false", + "-c", + "protocol.allow=never", + ]) + .args(args) + // Never prompt, never page, never take a lock for the index refresh. + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_OPTIONAL_LOCKS", "0") + .env("GIT_NO_LAZY_FETCH", "1") + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok() +} + #[cfg(test)] mod tests { use super::*; @@ -97,21 +205,31 @@ mod tests { #[test] fn summaries_say_what_would_be_lost() { let clean = GitState { + changed: Some(0), unpushed: Some(0), ..GitState::default() }; assert!(clean.is_clean()); assert_eq!(clean.summary(), "clean, no stash"); let busy = GitState { - changed: 3, + changed: Some(3), stashes: 1, unpushed: Some(2), }; assert!(!busy.is_clean()); assert_eq!(busy.summary(), "3 changed, 1 stash, 2 unpushed"); - let local = GitState::default(); + let local = GitState { + changed: Some(0), + ..GitState::default() + }; assert_eq!(local.summary(), "clean, no stash, no upstream"); assert!(!local.is_clean(), "unpushed history could be lost"); + let guarded = GitState { + unpushed: Some(0), + ..GitState::default() + }; + assert_eq!(guarded.summary(), "changes unknown, no stash"); + assert!(!guarded.is_clean(), "unknown is not clean"); } #[test] @@ -131,7 +249,151 @@ mod tests { } std::fs::write(dir.path().join("a.txt"), "hi").expect("write"); let state = state(dir.path()).expect("a checkout"); - assert_eq!(state.changed, 1, "one untracked file"); + assert_eq!(state.changed, Some(1), "one untracked file"); assert_eq!(state.stashes, 0); } + + #[cfg(unix)] + #[test] + fn a_checkout_cannot_make_git_run_its_programs() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let hook = dir.path().join("hook.sh"); + std::fs::write( + &hook, + format!("#!/bin/sh\ntouch '{}'\n", marker.display()), + ) + .expect("write hook"); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)) + .expect("chmod"); + let git = |args: &[&str]| { + Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(args) + .output() + .is_ok_and(|output| output.status.success()) + }; + if !git_installed() || !git(&["init", "-q"]) { + return; // no git on this machine + } + let hook = hook.to_string_lossy(); + assert!(git(&["config", "core.fsmonitor", &hook])); + assert!(state(dir.path()).is_some()); + assert!(!marker.exists(), "the checkout's fsmonitor ran"); + } + + /// A signed stash and `log.showSignature`: listing stashes the way + /// `git stash list` does would run the checkout's `gpg.program`. + #[cfg(unix)] + #[test] + fn a_checkout_cannot_make_git_verify_a_signature_with_its_program() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let gpg = dir.path().join("gpg.sh"); + std::fs::write( + &gpg, + format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display()), + ) + .expect("write gpg"); + std::fs::set_permissions(&gpg, std::fs::Permissions::from_mode(0o755)) + .expect("chmod"); + let git = |args: &[&str], input: Option<&str>| { + use std::io::Write as _; + let mut child = Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .ok()?; + let mut stdin = child.stdin.take()?; + stdin.write_all(input.unwrap_or("").as_bytes()).ok()?; + drop(stdin); + let output = child.wait_with_output().ok()?; + output.status.success().then(|| { + String::from_utf8_lossy(&output.stdout).trim().to_owned() + }) + }; + if !git_installed() || git(&["init", "-q"], None).is_none() { + return; // no git on this machine + } + let tree = git(&["mktree"], None).expect("empty tree"); + let commit = format!( + "tree {tree}\nauthor t 0 +0000\ncommitter t 0 +0000\n\ + gpgsig -----BEGIN PGP SIGNATURE-----\n \n \ + -----END PGP SIGNATURE-----\n\nstash\n" + ); + let id = git( + &["hash-object", "-t", "commit", "-w", "--stdin"], + Some(&commit), + ) + .expect("a signed commit"); + assert!( + git(&["update-ref", "--create-reflog", "refs/stash", &id], None) + .is_some() + ); + let gpg = gpg.to_string_lossy(); + assert!(git(&["config", "log.showSignature", "true"], None).is_some()); + assert!(git(&["config", "gpg.program", &gpg], None).is_some()); + + let state = state(dir.path()).expect("a checkout"); + assert!(!marker.exists(), "the checkout's gpg.program ran"); + assert_eq!(state.stashes, 1, "the stash is still counted"); + } + + #[cfg(unix)] + #[test] + fn a_checkouts_own_filter_is_never_run() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().expect("tempdir"); + let marker = dir.path().join("ran"); + let filter = dir.path().join("filter.sh"); + // A clean filter reads the file on stdin and writes it back. + std::fs::write( + &filter, + format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display()), + ) + .expect("write filter"); + std::fs::set_permissions( + &filter, + std::fs::Permissions::from_mode(0o755), + ) + .expect("chmod"); + let git = |args: &[&str]| { + Command::new("git") + .arg("-C") + .arg(dir.path()) + .args(["-c", "user.name=t", "-c", "user.email=t@t"]) + .args(args) + .output() + .is_ok_and(|output| output.status.success()) + }; + if !git_installed() || !git(&["init", "-q"]) { + return; // no git on this machine + } + std::fs::write(dir.path().join("file.txt"), "x").expect("write"); + std::fs::write( + dir.path().join(".gitattributes"), + "*.txt filter=evil\n", + ) + .expect("write attributes"); + assert!(git(&["add", "."]) && git(&["commit", "-qm", "one"])); + std::fs::remove_file(&marker).ok(); + let filter = filter.to_string_lossy(); + assert!(git(&["config", "filter.evil.clean", &filter])); + // Same content, new timestamp: git must re-read the file, through + // the filter, to know whether it changed. + std::fs::write(dir.path().join("file.txt"), "x").expect("rewrite"); + + let state = state(dir.path()).expect("a checkout"); + assert_eq!(state.changed, None, "not asked"); + assert!(!marker.exists(), "the checkout's filter ran"); + } } diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 22b8265..7ce0180 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -5,6 +5,14 @@ //! live free-space meter. Marking is non-destructive until the review screen //! is confirmed. +// A window, not a console program: on Windows, opening it from Explorer or +// the Start menu should not bring a console window along. `main` attaches to +// the console of a terminal it was started from, so `--help` and errors still +// reach one. Ignored elsewhere. +#![windows_subsystem = "windows"] + +mod app_menu; +mod appearance; mod git; mod marks; mod palette; @@ -56,6 +64,15 @@ options: "; fn main() -> Result<()> { + #[cfg(windows)] + console::attach(); + let outcome = run(); + #[cfg(windows)] + console::detach(); + outcome +} + +fn run() -> Result<()> { let args = parse_args()?; let root = args.root.clone(); let depth = args.depth; @@ -65,6 +82,12 @@ fn main() -> Result<()> { .with_assets(gpui_kit::assets::Assets) .run(move |cx| { gpui_omarchy::init(cx); + app_menu::install(cx); + let home = std::env::home_dir(); + let native_look = appearance::follows_system(home.as_deref()); + if native_look { + appearance::apply(cx.window_appearance(), cx); + } let options = args.options.clone(); let root_for_app = root.clone(); let window = cx @@ -82,21 +105,28 @@ fn main() -> Result<()> { "disktree · {}", marks::display_path( &title_root, - std::env::var_os("HOME") - .map(PathBuf::from) - .as_deref(), + home.as_deref(), ) ) .into(), ), ..Default::default() }), + // Wayland app id. Hyprland reports it as the window + // class, and the desktop entry's StartupWMClass and + // the documented window rule both match `disktree`. + // Left unset, the class is empty and that rule never + // matches. + app_id: Some("disktree".to_owned()), // Below this the treemap stops being readable, so ask // the compositor not to go there. window_min_size: Some(size(px(900.), px(600.))), ..Default::default() }, - move |_, cx| { + move |window, cx| { + if native_look { + appearance::follow(window); + } cx.new(|cx| { Disktree::new( root_for_app.clone(), @@ -159,6 +189,9 @@ fn parse_args() -> Result { ), }; } + // Launch Services added a process serial number when opening an + // app from Finder until OS X 10.9, and some launchers still do. + other if other.starts_with("-psn_") => {} other if other.starts_with('-') => { anyhow::bail!("unknown option {other}\n\n{USAGE}"); } @@ -173,21 +206,21 @@ fn parse_args() -> Result { !(disk && root.is_some()), "--disk and a PATH cannot be combined" ); - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let root = match root { _ if disk => home .as_deref() .and_then(disktree_core::space::volume_root_for) .unwrap_or_else(|| PathBuf::from("/")), Some(root) => root, - None => std::env::var_os("HOME") - .map(PathBuf::from) - .context("no path given and HOME is not set")?, + None => home.context("no path given and no home directory")?, }; // Store the depth as the initial view setting rather than a scan option: it // is a display choice the run-time `[` and `]` keys also change. - // Canonical, so a later widening recognises this tree in the wider walk. - let root = root.canonicalize().unwrap_or(root); + // Canonical, so a later widening recognises this tree in the wider walk; + // through dunce, so Windows gets `C:\Users\…` rather than the `\\?\C:\…` + // form nothing else is written in. + let root = dunce::canonicalize(&root).unwrap_or(root); let metadata = std::fs::metadata(&root) .with_context(|| format!("cannot read {}", root.display()))?; anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display()); @@ -198,3 +231,35 @@ fn parse_args() -> Result { depth: depth.clamp(1, 6), }) } + +/// The console of the terminal disktree was started from, if any: a +/// windowed program on Windows gets none of its own. +#[cfg(windows)] +mod console { + #![allow( + unsafe_code, + reason = "two Win32 calls that take no pointers to get wrong" + )] + + use windows_sys::Win32::System::Console::{ + ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole, + }; + + /// Borrow the parent's console so printed text reaches it. Does + /// nothing when started from Explorer, which has none. + pub fn attach() { + // SAFETY: takes a process id by value, and failure only means + // there was no console to attach to. + unsafe { + AttachConsole(ATTACH_PARENT_PROCESS); + } + } + + /// Let go of it again, so the shell redraws its prompt. + pub fn detach() { + // SAFETY: no arguments; a process without a console is left as is. + unsafe { + FreeConsole(); + } + } +} diff --git a/crates/disktree-app/src/marks.rs b/crates/disktree-app/src/marks.rs index 51483ce..89141ae 100644 --- a/crates/disktree-app/src/marks.rs +++ b/crates/disktree-app/src/marks.rs @@ -107,13 +107,16 @@ pub fn is_hidden(path: &Path) -> bool { } /// Shorten a path for display: `~` for the home directory, and the path with -/// the home prefix replaced when it is below it. +/// the home prefix replaced when it is below it. The separator after `~` is +/// the platform's, so Windows shows `~\AppData\Local`, not `~/AppData\Local`. pub fn display_path(path: &Path, home: Option<&Path>) -> String { match home .and_then(|home| path.strip_prefix(home).ok().map(|rest| (home, rest))) { Some((_, rest)) if rest.as_os_str().is_empty() => "~".to_string(), - Some((_, rest)) => format!("~/{}", rest.display()), + Some((_, rest)) => { + format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()) + } None => path.display().to_string(), } } @@ -220,9 +223,10 @@ mod tests { #[test] fn display_path_shortens_the_home_prefix() { let home = Path::new("/home/tobi"); + let separator = std::path::MAIN_SEPARATOR; assert_eq!( - display_path(Path::new("/home/tobi/.cache/npm"), Some(home)), - "~/.cache/npm" + display_path(&home.join(".cache").join("npm"), Some(home)), + format!("~{separator}.cache{separator}npm") ); assert_eq!(display_path(home, Some(home)), "~"); assert_eq!(display_path(Path::new("/var/log"), Some(home)), "/var/log"); diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 6a2212a..55efda9 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -26,8 +26,8 @@ use disktree_core::treemap::{ }; use gpui_kit::{ Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, - MouseMoveEvent, Pixels, Point, Render, ScrollDelta, ScrollWheelEvent, Size, - Window, px, size, + MouseMoveEvent, NavigationDirection, Pixels, Point, Render, ScrollDelta, + ScrollWheelEvent, Size, Window, px, size, }; use gpui_omarchy::Status; use rustc_hash::{FxHashMap, FxHashSet}; @@ -297,6 +297,20 @@ struct LayoutKey { filter: u64, } +/// Directories left behind and come back from, for `<` and `>`. +/// +/// Kept as absolute paths, not crumbs: a re-scan or a widening renumbers the +/// tree, and crumbs would then silently point at other directories. +#[derive(Clone, Debug, Default)] +pub struct History { + pub back: Vec, + pub forward: Vec, +} + +/// How many directories back is remembered. Far more than anyone clicks +/// through, and small enough that pruning after a scan costs nothing. +const HISTORY_DEPTH: usize = 100; + /// Result of the removal run, summarised for the final screen. #[derive(Clone, Debug, Default)] pub struct RunSummary { @@ -323,6 +337,10 @@ pub struct Disktree { pub crumbs: Vec, pub selected: Option>, pub hovered: Option>, + pub history: History, + /// The history button under the pointer, `true` for `<`: its card is + /// drawn below it for as long as it is. + pub history_hover: Option, /// The pointer moved more recently than the keyboard navigated. Then the /// tile under the pointer is what Space, X and Enter act on; after an /// arrow or Tab it is the keyboard selection again. @@ -350,6 +368,8 @@ pub struct Disktree { /// Focus to move on the next occasion a window is in hand. Key handling /// has no window, and opening or closing the dialog must move focus. pub focus_request: Option, + /// What the titlebar says, so it is only set when it changes. + window_title: String, /// The window's `rem` in pixels, read each frame. The mosaic is laid out /// in pixels, so its header band and label thresholds are scaled by this /// to follow interface zoom like the rest of the interface. @@ -393,8 +413,11 @@ pub struct Disktree { git_pending: FxHashSet, /// The device the scanned volume is mounted from. pub device: Option, - /// The top of the disk the home directory lives on: what "Whole disk" - /// scans. + /// 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, + /// 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, /// The side panel's width, in rem; dragged from its left edge. pub panel_rems: f32, @@ -414,7 +437,7 @@ impl Disktree { depth: u32, cx: &mut Context<'_, Self>, ) -> Self { - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let space = space_info(&root_path).ok(); let trash_backend = detect_trash_backend(); let mut tree = Self { @@ -430,6 +453,8 @@ impl Disktree { crumbs: Vec::new(), selected: None, hovered: None, + history: History::default(), + history_hover: None, pointer_active: false, view: View::default(), transition: None, @@ -453,6 +478,7 @@ impl Disktree { confirm_open: false, confirm_focus: cx.focus_handle(), focus_request: None, + window_title: String::new(), rem: crate::ui::BASE_REM, run: None, run_epoch: 0, @@ -478,6 +504,7 @@ impl Disktree { git: FxHashMap::default(), git_pending: FxHashSet::default(), device: None, + full_disk_access: None, disk_root: None, panel_rems: PANEL_REMS, scan_started: None, @@ -486,11 +513,14 @@ impl Disktree { scanned_at: now_seconds(), }; tree.device = device_for(&tree.root_path); - tree.disk_root = tree + tree.full_disk_access = tree .home .as_deref() - .or(Some(tree.root_path.as_path())) - .and_then(volume_root_for); + .and_then(disktree_core::access::full_disk_access); + // 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); + disktree_core::removal::prime_mount_points(); tree.start_scan(cx); Self::start_space_ticker(cx); tree @@ -523,6 +553,10 @@ impl Disktree { pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) { self.space = space_info(&root).ok(); self.device = device_for(&root); + // "Whole disk" means the disk of what is on screen, which a new root + // can change: an external drive has its own. + self.disk_root = + volume_root_for(&root).or_else(|| self.disk_root.take()); self.root_path = root; self.screen = Screen::Explore; self.start_scan(cx); @@ -551,6 +585,7 @@ impl Disktree { self.scan_started = Some(Instant::now()); self.scan_elapsed = None; self.scan_root.clone_from(&above); + self.remember(); let known = Known { path: self.root_path.clone(), tree, @@ -632,6 +667,10 @@ impl Disktree { let epoch = self.scan_epoch; self.progress = ScanSnapshot::default(); self.scan_error = None; + // A new scan starts at its root; where it was is one `<` away. + if !self.crumbs.is_empty() { + self.remember(); + } self.tree = None; self.crumbs.clear(); self.selected = None; @@ -718,6 +757,7 @@ impl Disktree { }); } self.keep_selection_valid(); + self.prune_history(); self.select_largest(cx); } Err(error) => self.scan_error = Some(error.to_string()), @@ -988,6 +1028,7 @@ impl Disktree { if !node.is_dir() || node.children.is_empty() { return; } + self.remember(); self.selected = Some(target.clone()); self.crumbs = target; self.forget_hover(); @@ -1040,18 +1081,27 @@ impl Disktree { /// Ascend to the parent directory, keeping the directory we came from in /// view so the motion reads as zooming out. pub fn ascend(&mut self, cx: &mut Context<'_, Self>) { - let Some(parent_crumbs) = self.parent_crumbs() else { - return; - }; + if let Some(parent_crumbs) = self.parent_crumbs() { + self.ascend_to(parent_crumbs, cx); + } + } + + /// Make `ancestor`, a directory above the current root, the root. + /// + /// The directory we leave shrinks back into its tile when that tile is + /// drawn at the new level; from further up it is too small to track, and + /// the new level simply lands. + fn ascend_to(&mut self, ancestor: Vec, cx: &mut Context<'_, Self>) { + self.remember(); // The region we are looking at now, and where it sits in the layout // we are going back to. let area = self.treemap_size.get(); let child_crumbs = self.crumbs.clone(); let src = self.view.visible_base(area); - self.crumbs.clone_from(&parent_crumbs); + self.crumbs.clone_from(&ancestor); self.forget_hover(); self.cache = None; - self.selected = Some(parent_crumbs); + self.selected = Some(ancestor); self.view = View::IDENTITY; self.transition = self .tile_body(&child_crumbs) @@ -1075,6 +1125,10 @@ impl Disktree { /// it lands immediately, the way selecting a folder does. pub fn go_to(&mut self, crumbs: Vec, cx: &mut Context<'_, Self>) { self.crumb_menu = None; + // A reveal in the directory on screen goes nowhere. + if crumbs != self.crumbs { + self.remember(); + } self.crumbs.clone_from(&crumbs); self.selected = Some(crumbs); self.forget_hover(); @@ -1084,6 +1138,117 @@ impl Disktree { cx.notify(); } + /// Note the directory on screen as one to come back to, before leaving + /// it. A new departure ends whatever was ahead, as in a browser. + fn remember(&mut self) { + if self.tree.is_none() { + return; + } + let here = self.current_path(); + if self.history.back.last() != Some(&here) { + self.history.back.push(here); + } + if self.history.back.len() > HISTORY_DEPTH { + self.history.back.remove(0); + } + self.history.forward.clear(); + } + + /// Drop what a new tree no longer holds: a removed directory, or one + /// outside a new root. What is left always resolves, so `<` and `>` are + /// enabled exactly when they would go somewhere. + fn prune_history(&mut self) { + let mut history = std::mem::take(&mut self.history); + history + .back + .retain(|path| self.crumbs_for_path(path).is_some()); + history + .forward + .retain(|path| self.crumbs_for_path(path).is_some()); + self.history = history; + } + + /// Whether `<` would go anywhere: what drives its button's disabled state. + pub fn can_go_back(&self) -> bool { + self.history_target(true).is_some() + } + + /// Whether `>` would go anywhere. + pub fn can_go_forward(&self) -> bool { + self.history_target(false).is_some() + } + + /// `<`: the directory on screen before this one. + pub fn go_back(&mut self, cx: &mut Context<'_, Self>) { + self.step_history(true, cx); + } + + /// `>`: undo a `<`. + pub fn go_forward(&mut self, cx: &mut Context<'_, Self>) { + self.step_history(false, cx); + } + + /// Where `<` (or `>`) would go, and its place on that stack: the newest + /// entry that is somewhere else. An entry can be where we already are, + /// after a widening that was superseded; it is skipped rather than spend + /// a click on nothing. Every other entry resolves, being pruned whenever + /// a tree lands. + pub fn history_target(&self, back: bool) -> Option<(usize, Vec)> { + self.tree.as_ref()?; + let stack = if back { + &self.history.back + } else { + &self.history.forward + }; + stack.iter().enumerate().rev().find_map(|(at, path)| { + self.crumbs_for_path(path) + .filter(|crumbs| *crumbs != self.crumbs) + .map(|crumbs| (at, crumbs)) + }) + } + + fn step_history(&mut self, back: bool, cx: &mut Context<'_, Self>) { + let Some((at, target)) = self.history_target(back) else { + return; + }; + let here = self.current_path(); + let mut history = std::mem::take(&mut self.history); + let (from, to) = if back { + (&mut history.back, &mut history.forward) + } else { + (&mut history.forward, &mut history.back) + }; + from.truncate(at); + to.push(here); + // The move is an ordinary one, animation and all; it records itself + // like any other, so the stacks are put back afterwards. + self.travel(target, cx); + self.history = history; + cx.notify(); + } + + /// Go to `target` with the motion that fits: grow into a directory + /// below, shrink back out to one above, or land on one beside. + fn travel(&mut self, target: Vec, cx: &mut Context<'_, Self>) { + let enterable = self + .node_at(&target) + .is_some_and(|node| node.is_dir() && !node.children.is_empty()); + if target.len() > self.crumbs.len() + && target.starts_with(&self.crumbs) + && enterable + { + let from = + self.tile_body(&target).map(|rect| self.view.project(rect)); + self.enter(target, from, cx); + } else if target.len() < self.crumbs.len() + && self.crumbs.starts_with(&target) + { + self.ascend_to(target, cx); + } else { + self.go_to(target, cx); + } + } + /// Show `crumbs` in its directory, selected: what a "worth a look" row /// or a found name does. pub fn reveal(&mut self, crumbs: Vec, cx: &mut Context<'_, Self>) { @@ -1940,16 +2105,72 @@ impl Disktree { // ── input ─────────────────────────────────────────────────────────── - /// Handle a key press. Returns whether the directory on screen changed, - /// which is what keeps the window title honest. + /// Handle a key press. pub fn on_key_down( &mut self, event: &KeyDownEvent, cx: &mut Context<'_, Self>, - ) -> bool { - let before = self.crumbs.clone(); + ) { self.dispatch_key(event, cx); - self.crumbs != before + } + + /// Whether a menu command may replace the tree: where `r` would, not + /// behind the confirmation, and not under the review list or a removal + /// that is still running. + pub fn can_start_over(&self) -> bool { + self.screen == Screen::Explore && !self.confirm_open + } + + /// Ask for a directory and scan it: an app opened from the Dock has no + /// command line to name one. + pub fn open_folder(cx: &Context<'_, Self>) { + let chosen = cx.prompt_for_paths(gpui_kit::PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Scan".into()), + }); + cx.spawn(async move |this, cx| { + let Ok(Ok(Some(paths))) = chosen.await else { + return; + }; + let Some(path) = paths.into_iter().next() else { + return; + }; + // Canonical, like a root from the command line, so a later + // widening recognises this tree in the wider walk. + let path = path.canonicalize().unwrap_or(path); + // The panel does not block the window: the review list or a + // removal may have started while it was open. + let _ = this.update(cx, |this, cx| { + if this.can_start_over() { + this.set_root(path, cx); + } + }); + }) + .detach(); + } + + /// Show the tile a key acts on in Finder (or the file manager), selected. + pub fn reveal_target(&mut self, cx: &mut Context<'_, Self>) { + let crumbs = + self.action_target().unwrap_or_else(|| self.crumbs.clone()); + let Some(path) = self.path_at(&crumbs) else { + return; + }; + // GPUI's reveal cannot report failure, so check what it can't. + if std::fs::symlink_metadata(&path).is_err() { + self.notice = Some(( + format!( + "{} is no longer on disk", + crate::marks::display_path(&path, self.home.as_deref()) + ), + Status::Warning, + )); + cx.notify(); + return; + } + cx.reveal_path(&path); } /// Every binding, in reading order of the hint bar, so the keys and the @@ -1962,6 +2183,7 @@ impl Disktree { let key = event.keystroke.key.as_str(); let control = event.keystroke.modifiers.control; let shift = event.keystroke.modifiers.shift; + let alt = event.keystroke.modifiers.alt; // The alert dialog owns Enter and Escape while it is open; a key that // bubbles up to here must not also act on the screen behind it. @@ -1969,6 +2191,14 @@ impl Disktree { return; } + // ⌘ chords belong to the menu bar (⌘Q, ⌘W, ⌘R) or to the system. + // Read as plain letters they would act twice or by surprise: ⌘D + // would re-scan with apparent sizes, ⌘H would hide *and* toggle. + // Zoom (⌘= ⌘- ⌘0) is handled before this, with a window in hand. + if event.keystroke.modifiers.platform { + return; + } + if self.crumb_menu.is_some() && self.on_menu_key(key, cx) { return; } @@ -2012,6 +2242,9 @@ impl Disktree { } match self.screen { + // Alt-arrows are history in every browser and file manager. + Screen::Explore if alt && key == "left" => self.go_back(cx), + Screen::Explore if alt && key == "right" => self.go_forward(cx), Screen::Explore => self.on_explore_key(key, control, shift, cx), Screen::Review => self.on_review_key(key, cx), Screen::Running => { @@ -2141,6 +2374,7 @@ impl Disktree { self.show_selection = !self.show_selection; cx.notify(); } + "o" if !control => self.reveal_target(cx), "?" => { self.show_help = true; cx.notify(); @@ -2271,6 +2505,12 @@ impl Disktree { self.toggle_mark(&crumbs, cx); } } + MouseButton::Navigate(NavigationDirection::Back) => { + self.go_back(cx); + } + MouseButton::Navigate(NavigationDirection::Forward) => { + self.go_forward(cx); + } _ => {} } } @@ -2457,6 +2697,19 @@ impl Render for Disktree { ) -> impl gpui_kit::IntoElement { self.rem = window.rem_size().as_f32(); self.tick_transition(window); + // The titlebar names the directory on screen, however it got there: + // a key, a click, a rescan or a folder chosen from the menu. + let title = format!( + "disktree · {}", + crate::marks::display_path( + &self.current_path(), + self.home.as_deref() + ) + ); + if title != self.window_title { + window.set_window_title(&title); + self.window_title = title; + } crate::views::root(self, window, cx) } } diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rs index 946b06a..032d1b0 100644 --- a/crates/disktree-app/src/tests.rs +++ b/crates/disktree-app/src/tests.rs @@ -466,6 +466,38 @@ fn the_help_overlay_opens_and_closes(cx: &mut TestAppContext) { assert!(!read(&view, cx, |app| app.show_help)); } +#[gpui_kit::test] +fn showing_a_tile_that_is_gone_says_so_instead(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + // The selection is .cache, the largest; take it away behind the tree. + std::fs::remove_dir_all(temp.path().join(".cache")).expect("remove"); + press(cx, "o"); + let notice = read(&view, cx, |app| app.notice.clone()); + let (message, _) = notice.expect("a notice"); + assert!(message.contains("no longer on disk"), "{message}"); +} + +#[gpui_kit::test] +fn command_chords_are_not_read_as_plain_letters(cx: &mut TestAppContext) { + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + draw(cx); + + // ⌘P and ⌘D are the menu bar's or nobody's; read as `p` and `d` they + // would hide the selection and re-scan. + let shown = read(&view, cx, |app| app.show_selection); + press(cx, "cmd-p cmd-d"); + assert_eq!(read(&view, cx, |app| app.show_selection), shown); + assert!(read(&view, cx, |app| app.options.apparent_size)); + press(cx, "p"); + assert_eq!(read(&view, cx, |app| app.show_selection), !shown); +} + #[gpui_kit::test] fn the_treemap_zooms_with_the_wheel_and_resets(cx: &mut TestAppContext) { cx.update(gpui_omarchy::init); @@ -943,9 +975,11 @@ fn widening_reuses_the_tree_it_has_and_reads_only_the_rest( }); let before = read(&view, cx, |app| app.tree().map(|tree| tree.files)); - // The trail runs from "/", and the scanned root sits under its parents. + // The trail runs from the top of the filesystem — "/", or a drive such + // as "C:\" — and the scanned root sits under its parents. let trail = read(&view, cx, Disktree::breadcrumbs); - assert_eq!(trail[0].0, "/"); + let top = temp.path().ancestors().last().expect("a top"); + assert_eq!(trail[0].0, top.display().to_string()); assert!( trail.contains(&( temp.path() @@ -1165,3 +1199,86 @@ fn marking_a_directory_marks_everything_inside_it(cx: &mut TestAppContext) { update(&view, cx, |app, cx| app.toggle_mark(&junk, cx)); assert!(read(&view, cx, |app| app.marks.is_empty())); } + +/// `<` and `>` retrace the directories visited, are disabled when there is +/// nowhere to go, and a fresh move ends what was ahead. +#[gpui_kit::test] +fn back_and_forward_retrace_where_you_have_been(cx: &mut TestAppContext) { + use gpui_kit::Modifiers; + + cx.update(gpui_omarchy::init); + let temp = fixture(); + let (view, cx) = view_over(temp.path(), cx); + cx.simulate_resize(gpui_kit::size(px(1400.), px(900.))); + draw(cx); + let can = |view: &Entity, cx: &Window| { + read(view, cx, |app| (app.can_go_back(), app.can_go_forward())) + }; + assert_eq!(can(&view, cx), (false, false), "nowhere to go yet"); + + let (junk, deeper, keep) = update(&view, cx, |app, cx| { + let junk = child_crumbs(app, &[], "junk"); + let deeper = child_crumbs(app, &junk, "deeper"); + let keep = child_crumbs(app, &[], "keep"); + app.select(Some(deeper.clone()), cx); + app.descend(cx); + (junk, deeper, keep) + }); + draw(cx); + assert_eq!(can(&view, cx), (true, false)); + + // Hovering `<` shows the card for where it goes, as hovering a tile + // does: here, the scanned root. It hangs below the button, never on it. + let back = cx + .debug_bounds("history-back") + .expect("the button is drawn"); + cx.simulate_mouse_move(back.center(), None, Modifiers::none()); + draw(cx); + let card = cx.debug_bounds("history-tip").expect("the card is shown"); + assert!(card.top() >= back.bottom(), "{card:?} covers {back:?}"); + assert_eq!( + read(&view, cx, |app| app.history_target(true)), + Some((0, Vec::new())) + ); + + let click = |cx: &mut Window, selector: &'static str| { + let bounds = cx.debug_bounds(selector).expect("the button is drawn"); + cx.simulate_click(bounds.center(), Modifiers::none()); + draw(cx); + }; + click(cx, "history-back"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); + assert_eq!(can(&view, cx), (false, true), "back at the start"); + + click(cx, "history-forward"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + assert_eq!(can(&view, cx), (true, false)); + + // Up a level is a move of its own, and the keys retrace it too. + press(cx, "backspace"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), junk); + press(cx, "alt-left"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + press(cx, "alt-left"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); + press(cx, "alt-right"); + assert_eq!(read(&view, cx, |app| app.crumbs.clone()), deeper); + + // Going somewhere new from the middle of the history drops what was + // ahead of it, as in a browser. + press(cx, "alt-left"); + update(&view, cx, |app, cx| app.go_to(keep, cx)); + draw(cx); + assert_eq!(can(&view, cx), (true, false), "the forward trail is gone"); + press(cx, "alt-left"); + assert_eq!( + read(&view, cx, |app| app.crumbs.clone()), + Vec::::new() + ); +} diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index ca7b193..fc5541e 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -56,23 +56,45 @@ pub fn root( .debug_selector(|| "disktree-root".into()) .track_focus(&app.focus) .key_context("Disktree") - // The listener is the only place with a window in hand, so it is also - // where the titlebar is kept in step with the directory on screen. + .on_action(cx.listener(|this, _: &crate::app_menu::Rescan, _, cx| { + // Where `r` would: not behind the confirmation, and not under + // the review list or a removal that is still running. + if this.can_start_over() { + this.start_scan(cx); + } + })) + .on_action(cx.listener( + |this, _: &crate::app_menu::OpenFolder, _, cx| { + if this.can_start_over() { + Disktree::open_folder(cx); + } + }, + )) + .on_action(cx.listener( + |this, _: &crate::app_menu::ShowInFinder, _, cx| { + this.reveal_target(cx); + }, + )) + // Only where the history buttons are: the review screen has none. + .on_action(cx.listener(|this, _: &crate::app_menu::GoBack, _, cx| { + if this.screen == Screen::Explore { + this.go_back(cx); + } + })) + .on_action(cx.listener( + |this, _: &crate::app_menu::GoForward, _, cx| { + if this.screen == Screen::Explore { + this.go_forward(cx); + } + }, + )) .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { if this.zoom_interface(event, window) { cx.notify(); return; } - let moved = this.on_key_down(event, cx); + this.on_key_down(event, cx); this.apply_focus(window, cx); - if moved { - let path = this.current_path(); - let title = format!( - "disktree · {}", - crate::marks::display_path(&path, this.home.as_deref()) - ); - window.set_window_title(&title); - } })) .relative() .flex() @@ -363,11 +385,13 @@ fn trail(app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>) -> Div { /// Steps a trail shows before it folds its middle into an ellipsis. const TRAIL_STEPS: usize = 7; +/// The platform's path separator, so the trail reads like the paths shown +/// elsewhere: `/` here, `\` on Windows. fn separator_glyph(theme: &Theme) -> Div { div() .text_color(theme.secondary.opacity(0.5)) .text_size(text::BODY) - .child("/") + .child(std::path::MAIN_SEPARATOR_STR) } /// A crumb in the tree. Its label goes there (the current one opens the @@ -688,6 +712,84 @@ fn view_settings( }; let theme = cx.omarchy().clone(); + // Back and forward through the directories visited, beside the choices + // that change how the one on screen is drawn. + let travel = |id: &'static str, + label: &'static str, + enabled: bool, + back: bool, + go: fn(&mut Disktree, &mut Context<'_, Disktree>), + cx: &mut Context<'_, Disktree>| { + let shown = app.history_hover == Some(back); + div() + .id(ElementId::Name(format!("{id}-hover").into())) + .debug_selector(move || id.into()) + .relative() + .on_hover(cx.listener(move |this, hovered: &bool, _, cx| { + // Leaving one button can be reported after entering the + // other; only the button that owns the card takes it away. + if *hovered { + this.history_hover = Some(back); + } else if this.history_hover == Some(back) { + this.history_hover = None; + } + cx.notify(); + })) + .child( + button(id, label, ButtonVariant::Secondary, cx) + .tab_stop(false) + .disabled(!enabled) + // Borderless: glyphs on the bar, not controls in a + // frame. Hover keeps the fill but not the outline it + // would add. + .hover(|style| { + style + .bg(theme.hover_fill()) + .border_color(theme.foreground.opacity(0.)) + }) + .on_click(cx.listener(move |this, _, window, cx| { + go(this, cx); + window.focus(&this.focus, cx); + })), + ) + .when(shown, |this| { + // Anchored to a holder pinned at the button's bottom edge, so + // the card hangs below it and never covers it; deferred so it + // paints over the mosaic. + this.child( + div().absolute().top_full().left_0().child( + deferred( + anchored() + .snap_to_window_with_margin(px(8.)) + .offset(gpui_kit::point(px(0.), px(4.))) + .child(history_card(app, back, cx)), + ) + .with_priority(2), + ), + ) + }) + }; + let history = div() + .flex() + .flex_row() + .items_center() + .child(travel( + "history-back", + "<", + app.can_go_back(), + true, + Disktree::go_back, + cx, + )) + .child(travel( + "history-forward", + ">", + app.can_go_forward(), + false, + Disktree::go_forward, + cx, + )); + let depth = app.layout_options.max_depth; let stepper = |id: &'static str, label: &'static str, @@ -727,6 +829,7 @@ fn view_settings( .items_center() .gap(space::SM) .flex_shrink_0() + .child(history) .child(mode) .child(hidden) .child(apparent) @@ -899,6 +1002,7 @@ fn side_panel( .child(marked_section(app, theme, cx)), ) .children(notice_line(app, theme, cx)) + .children(privacy_line(app, theme, cx)) .child(disk_section(app, theme, cx)) } @@ -1423,6 +1527,60 @@ fn notice_line(app: &Disktree, theme: &Theme, cx: &App) -> Option
{ ) } +/// Why folders were unreadable on macOS, and the one place to fix it. +/// +/// Only once the scan has hit something it could not read and the process is +/// known to lack Full Disk Access: an unreadable folder has other causes, and +/// the hint must not nag when it would not help. A grant needs a relaunch, and +/// started from a terminal it is the terminal that needs it. +fn privacy_line( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + if app.progress.errors == 0 || app.full_disk_access != Some(false) { + return None; + } + let color = theme.warning; + let errors = app.progress.errors; + let noun = if errors == 1 { "item" } else { "items" }; + 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(format!( + "macOS kept {} {noun} unreadable. Give disktree Full Disk \ + Access, or your terminal if you started it there, then \ + reopen it.", + widgets::human_count(errors) + ))) + .child( + button( + "privacy", + "Open Privacy Settings", + ButtonVariant::Outline, + cx, + ) + .tab_stop(false) + .justify_center() + .on_click(cx.listener( + |this, _, window, cx| { + cx.open_url( + disktree_core::access::FULL_DISK_ACCESS_SETTINGS, + ); + window.focus(&this.focus, cx); + }, + )), + ), + ) +} + /// Free space on the volume now, and after the marks go. fn disk_section( app: &Disktree, @@ -2592,37 +2750,80 @@ pub fn cursor_tooltip( anchor_y + gap }; - // The same surface treatment as Omarchy's tooltip, square and bordered, - // so an anchored surface of this app does not drift from the system's. - // Translucent so the mosaic stays visible underneath it. - let theme = cx.omarchy(); Some( - div() + card_surface(cx) .absolute() .left(px(x)) .top(px(y)) - .w(size::TOOLTIP) - .flex() - .flex_col() - .gap(space::XS) - .px(space::SM) - .py(space::SM) - .border_1() - .border_color(theme.control_border()) - .bg(theme.background.opacity(0.93)) - .text_color(theme.foreground) - .font_family(theme.font.clone()) - .text_size(text::CAPTION) .child(content), ) } +/// The same surface treatment as Omarchy's tooltip, square and bordered, +/// so an anchored surface of this app does not drift from the system's. +/// Translucent so the mosaic stays visible underneath it. +fn card_surface(cx: &gpui_kit::App) -> Div { + let theme = cx.omarchy(); + div() + .w(size::TOOLTIP) + .flex() + .flex_col() + .gap(space::XS) + .px(space::SM) + .py(space::SM) + .border_1() + .border_color(theme.control_border()) + .bg(theme.background.opacity(0.93)) + .text_color(theme.foreground) + .font_family(theme.font.clone()) + .text_size(text::CAPTION) +} + +/// The card under `<` or `>` while it is hovered: what hovering a tile +/// shows, for the directory the button goes to, so where it leads is known +/// before going. Drawn by the app rather than as a tooltip, which GPUI puts +/// at the pointer, over the button itself. +fn history_card(app: &Disktree, back: bool, cx: &gpui_kit::App) -> Div { + let (label, keys) = if back { + ("Back", "alt \u{2190} back") + } else { + ("Forward", "alt \u{2192} forward") + }; + let card = app + .history_target(back) + .and_then(|(_, crumbs)| node_card(app, &crumbs, keys, cx)); + card_surface(cx) + .debug_selector(|| "history-tip".into()) + .map(|surface| match card { + Some(card) => surface.child(card), + // Nowhere to go: the button is disabled; say what it is for. + None => surface.child(format!("{label} \u{00b7} {keys}")), + }) +} + /// The tooltip content for the hovered tile: everything the tile cannot show. pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ + let crumbs = app.hovered.as_deref()?; + let is_dir = app.node_at(crumbs)?.is_dir(); + let keys = if is_dir { + "space mark · enter open" + } else { + "space mark" + }; + node_card(app, crumbs, keys, cx) +} + +/// What is known about the node at `crumbs`, as a card: name, path, size and +/// share, counts, and badges, with `keys` for what can be done from there. +fn node_card( + app: &Disktree, + crumbs: &[usize], + keys: &str, + cx: &gpui_kit::App, +) -> Option
{ let theme = cx.omarchy(); - let crumbs = app.hovered.clone()?; - let node = app.node_at(&crumbs)?; - let path = app.path_at(&crumbs); + let node = app.node_at(crumbs)?; + let path = app.path_at(crumbs); let parent = crumbs[..crumbs.len().saturating_sub(1)].to_vec(); let parent_value = app.node_at(&parent).map_or(0, |node| node.bytes); let marked = path.as_deref().is_some_and(|path| app.marks.contains(path)); @@ -2725,24 +2926,38 @@ pub fn hover_tooltip(app: &Disktree, cx: &gpui_kit::App) -> Option
{ div() .text_size(text::CAPTION) .text_color(theme.secondary.opacity(0.7)) - .child(if node.is_dir() { - "space mark · enter open" - } else { - "space mark" - }), + .child(keys.to_string()), ); Some(tip) } +/// The modifier the help names for clicks and interface zoom. Both are +/// accepted everywhere; this is the one each platform's users reach for, and +/// on macOS ctrl-click is a right-click. +const MODIFIER_CLICK: &str = if cfg!(target_os = "macos") { + "\u{2318}-click" +} else { + "ctrl-click" +}; +const MODIFIER_ZOOM: &str = if cfg!(target_os = "macos") { + "\u{2318} = / - / 0" +} else { + "ctrl = / - / 0" +}; + fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { let theme = cx.omarchy(); // Sentence case, and the tile a key acts on is always the one under the // pointer if the pointer moved last, else the keyboard selection. - let rows: [(&str, &str); 24] = [ + let rows: [(&str, &str); 26] = [ ("space / x", "Mark or unmark the tile you point at"), - ("ctrl-click", "Mark without moving the selection"), + (MODIFIER_CLICK, "Mark without moving the selection"), ("enter", "Open that directory, at any depth"), ("\u{232b} / esc", "Go up one directory"), + ( + "alt \u{2190} / \u{2192}", + "Back or forward through where you have been", + ), ( "\u{2190} \u{2191} \u{2193} \u{2192}", "Move between tiles at this level", @@ -2752,7 +2967,7 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("shift-scroll", "Pan the magnified view"), ("[ / ]", "Draw fewer or more levels at once"), ("- / = / 0", "Magnify, shrink, or reset the view"), - ("ctrl = / - / 0", "Interface zoom"), + (MODIFIER_ZOOM, "Interface zoom"), ( "/", "Filter by name: only matches keep their colour; enter shows only them", @@ -2764,6 +2979,14 @@ fn help_overlay(app: &Disktree, cx: &gpui_kit::App) -> Div { ("d", "Disk usage or apparent size"), ("i", "Include or skip hidden entries"), ("p", "Show or hide the selection line"), + ( + "o", + if cfg!(target_os = "macos") { + "Show it in Finder" + } else { + "Show it in the file manager" + }, + ), ("q", "Quit"), ("", ""), ( diff --git a/crates/disktree-core/Cargo.toml b/crates/disktree-core/Cargo.toml index 21ac328..a1eb131 100644 --- a/crates/disktree-core/Cargo.toml +++ b/crates/disktree-core/Cargo.toml @@ -12,8 +12,23 @@ workspace = true [dependencies] chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } rayon = { workspace = true } -rustix = { version = "1.1", features = ["fs"] } rustc-hash = { workspace = true } +# rustix has no filesystem calls on Windows; `windows.rs` covers them there. +[target.'cfg(not(windows))'.dependencies] +rustix = { version = "1.1", features = ["fs"] } + +[target.'cfg(windows)'.dependencies] +# The Recycle Bin, through the shell's own file operation. +trash = { version = "5.2.9", default-features = false, features = ["coinit_apartmentthreaded"] } +winapi-util = "0.1.11" +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] } + +# The system trash, through NSFileManager: what Finder's Move to Trash does, +# without asking to control Finder. Only this backend is used; the crate's +# Linux and Windows code is not built. +[target.'cfg(target_os = "macos")'.dependencies] +trash = { version = "5.2.9", default-features = false } + [dev-dependencies] tempfile = "3" diff --git a/crates/disktree-core/src/access.rs b/crates/disktree-core/src/access.rs new file mode 100644 index 0000000..d19abc1 --- /dev/null +++ b/crates/disktree-core/src/access.rs @@ -0,0 +1,49 @@ +//! What the operating system keeps private from a scan. +//! +//! On macOS a process without Full Disk Access is refused parts of the home +//! directory — Mail, Messages, Safari, other apps' containers, the Trash — +//! 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. + +use std::path::Path; + +/// System Settings, opened at Privacy & Security › Full Disk Access. +pub const FULL_DISK_ACCESS_SETTINGS: &str = + "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"; + +/// Whether this process has Full Disk Access: `Some(false)` when it is +/// refused, `None` where the question does not apply or cannot be answered. +/// +/// The privacy database itself is protected by Full Disk Access, so opening +/// it for reading is the test. It never shows a prompt, unlike touching +/// Desktop or Documents would. +pub fn full_disk_access(home: &Path) -> Option { + if !cfg!(target_os = "macos") { + return None; + } + let database = + home.join("Library/Application Support/com.apple.TCC/TCC.db"); + match std::fs::File::open(database) { + Ok(_) => Some(true), + Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => { + Some(false) + } + Err(_) => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_macos_has_an_answer_and_a_missing_database_is_not_a_refusal() { + let temp = tempfile::TempDir::new().expect("tempdir"); + assert_eq!(full_disk_access(temp.path()), None); + if !cfg!(target_os = "macos") { + let home = std::env::home_dir().expect("a home directory"); + assert_eq!(full_disk_access(&home), None); + } + } +} diff --git a/crates/disktree-core/src/classify.rs b/crates/disktree-core/src/classify.rs index 2fb4fe6..098e5de 100644 --- a/crates/disktree-core/src/classify.rs +++ b/crates/disktree-core/src/classify.rs @@ -122,9 +122,15 @@ pub fn category_of_name(name: &str) -> Option { | ".espressif" | ".arduino15" | ".config" | ".vscode" | ".zig" | ".rye" | ".conda" | "anaconda3" | "miniconda3" | ".opam" | ".ghcup" | ".stack" | ".julia" | ".dotnet" | ".android" - | ".sdkman" | ".volta" | ".yarn" | ".java" => Category::Toolchain, + | ".sdkman" | ".volta" | ".yarn" | ".java" + // macOS: Xcode's and the simulators' state in ~/Library/Developer. + // Not `Developer` itself: ~/Developer is where Apple puts projects. + | "xcode" | "coresimulator" => Category::Toolchain, "sync" | "dropbox" | "nextcloud" | "google drive" | "onedrive" - | "pclouddrive" | "mega" | ".stversions" => Category::Synced, + | "pclouddrive" | "mega" | ".stversions" + // macOS: iCloud Drive, and the File Provider clients (Dropbox, + // Google Drive, OneDrive) since macOS 12. + | "mobile documents" | "cloudstorage" => Category::Synced, ".git" => Category::Git, "pictures" | "photos" | "music" | "videos" | "movies" | "steam" | "models" | ".ollama" | ".lmstudio" | "games" | "wineprefix" => { @@ -134,7 +140,8 @@ pub fn category_of_name(name: &str) -> Option { | "obsidian" | "public" | "templates" => Category::Documents, ".cache" | "cache" | "caches" | ".ccache" | ".sccache" | "_cacache" | "__pycache__" | "node_modules" | "trash" | ".trash" | "tmp" - | ".tmp" => Category::Cache, + | ".tmp" | "deriveddata" | "ios devicesupport" + | "watchos devicesupport" => Category::Cache, _ => return None, }; Some(category) @@ -155,7 +162,14 @@ pub fn reclaim_of( ".stversions" => Reclaim::SyncHistory, ".pnpm-store" | "pnpm" => Reclaim::PackageStore, "__pycache__" | ".pytest_cache" | ".mypy_cache" | ".ruff_cache" - | ".next" | ".turbo" | ".parcel-cache" => Reclaim::BuildOutput, + | ".next" | ".turbo" | ".parcel-cache" + // Xcode's build products and indexes, rebuilt on the next build. + | "deriveddata" => Reclaim::BuildOutput, + // Symbols Xcode copies off a device it meets, and copies again the + // next time that device is plugged in. + "ios devicesupport" | "watchos devicesupport" => Reclaim::Regenerable, + // ~/Library/Logs, told apart from a project's logs by its neighbour. + "logs" if has_sibling("Application Support") => Reclaim::Temporary, // Too common to trust alone: only a build directory beside a manifest. "target" if has_sibling("Cargo.toml") => Reclaim::BuildOutput, "node_modules" if has_sibling("package.json") => Reclaim::Reinstallable, @@ -425,6 +439,36 @@ mod tests { ); } + #[test] + fn macos_developer_leftovers_are_reclaimable_and_its_risks_are_not() { + let none = |_: &str| false; + assert_eq!( + reclaim_of("DerivedData", Category::Toolchain, none), + Some(Reclaim::BuildOutput) + ); + assert_eq!( + reclaim_of("iOS DeviceSupport", Category::Toolchain, none), + Some(Reclaim::Regenerable) + ); + let library = |name: &str| name == "Application Support"; + assert_eq!( + reclaim_of("Logs", Category::Other, library), + Some(Reclaim::Temporary) + ); + assert_eq!(reclaim_of("logs", Category::Code, none), None); + // Big, but not safe to offer: Archives hold the symbols crash + // reports need, and Backup is an iPhone's only backup. + assert_eq!(reclaim_of("Archives", Category::Toolchain, none), None); + assert_eq!(reclaim_of("Backup", Category::Other, none), None); + assert_eq!( + category_of_name("Mobile Documents"), + Some(Category::Synced) + ); + // ~/Developer holds a user's projects, not a toolchain. + assert_eq!(category_of_name("Developer"), None); + assert_eq!(category_of_name("Xcode"), Some(Category::Toolchain)); + } + #[test] fn the_legend_lists_every_named_category_once() { let mut seen = std::collections::HashSet::new(); diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rs index d7cdb24..edc53be 100644 --- a/crates/disktree-core/src/lib.rs +++ b/crates/disktree-core/src/lib.rs @@ -5,6 +5,7 @@ //! hardlink de-duplication, aspect-ratio layout, and what may be deleted — can //! be built and tested without GPUI, a display, or a GPU. +pub mod access; pub mod classify; pub mod filter; pub mod insights; @@ -14,3 +15,5 @@ pub mod size; pub mod space; pub mod tree; pub mod treemap; +#[cfg(windows)] +mod windows; diff --git a/crates/disktree-core/src/removal.rs b/crates/disktree-core/src/removal.rs index c15ad04..3874564 100644 --- a/crates/disktree-core/src/removal.rs +++ b/crates/disktree-core/src/removal.rs @@ -6,12 +6,14 @@ //! //! Two mechanisms are offered: //! -//! * [`RemovalMode::Permanent`] — `rm -rf` semantics, implemented with the -//! standard library rather than by shelling out, so no path ever reaches a +//! * [`RemovalMode::Permanent`] — `rm -rf --one-file-system` semantics, +//! implemented here rather than by shelling out, so no path ever reaches a //! shell and no filename can be misread as an option. -//! * [`RemovalMode::Trash`] — move to the desktop trash, using `trash-put`, -//! then `gio trash`, then a built-in XDG implementation. The backend is -//! detected once and named in the UI so the user knows what actually happens. +//! * [`RemovalMode::Trash`] — move to the desktop trash. On macOS that is +//! always the system Trash, through `NSFileManager`, and on Windows the +//! Recycle Bin. Elsewhere it is `trash-put`, then `gio trash`, then a +//! built-in XDG implementation. The backend is detected once and named in +//! the UI so the user knows what actually happens. use std::fs; use std::io; @@ -74,6 +76,8 @@ pub struct Plan { pub covered: Vec, /// Marked paths that must not be touched. pub blocked: Vec, + /// The scanned root the targets were judged against. + pub root: PathBuf, } impl Plan { @@ -92,13 +96,27 @@ impl Plan { /// looking at is the only thing they consented to act on. pub fn plan(targets: &[Target], root: &Path) -> Plan { let root = normalize(root); - let home = std::env::var_os("HOME").map(PathBuf::from); - let mut plan = Plan::default(); + let mut plan = Plan { + root: root.clone(), + ..Plan::default() + }; let mut accepted: Vec = Vec::new(); + if targets.is_empty() { + return plan; + } + let mounts = mount_points(); + // Once per plan, not per target: the review screen plans every frame. + let home = std::env::home_dir().map(|home| Home::of(&home)); + let real_root = fs::canonicalize(&root).ok(); + for target in targets { let path = normalize(&target.path); - if let Some(reason) = refuse(&path, &root, home.as_deref()) { + let reason = + refuse(&path, &root, home.as_ref(), &mounts).or_else(|| { + linked(&path, &root, real_root.as_deref(), home.as_ref()) + }); + if let Some(reason) = reason { plan.blocked.push(Blocked { path: target.path.clone(), reason, @@ -118,7 +136,7 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { for target in accepted { if outer .iter() - .any(|candidate| target.path.starts_with(&candidate.path)) + .any(|candidate| within(&target.path, &candidate.path)) { plan.covered.push(target); } else { @@ -129,13 +147,20 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan { plan } -/// Why this path must not be removed, if it must not. /// Trees the operating system owns. A whole-disk scan shows them, because /// they are part of what fills the disk, but files there belong to packages -/// and removing them by hand breaks the system; pacman, paccache and -/// `journalctl --vacuum` are the right tools. Refused even where -/// permissions would allow it, and even inside them. -const SYSTEM_TREES: [&str; 14] = [ +/// and removing them by hand breaks the system; pacman, paccache, +/// `journalctl --vacuum` or `brew cleanup` are the right tools. Refused even +/// where permissions would allow it, and even inside them. +/// +/// One list for every platform: a macOS tree never exists on Linux, and the +/// other way round, so the extra entries cost nothing. On macOS `/etc`, +/// `/var` and `/tmp` are links into `/private`, which a whole-disk scan +/// reaches by its real name. `/Applications` is left out on purpose: moving +/// an app to the Trash is how macOS uninstalls it, and the apps macOS ships +/// live on the read-only system volume anyway. +#[cfg(not(windows))] +const SYSTEM_TREES: [&str; 20] = [ "/bin", "/boot", "/dev", @@ -150,36 +175,234 @@ const SYSTEM_TREES: [&str; 14] = [ "/usr", "/var/lib", "/efi", + // macOS. + "/System", + "/Library", + "/private", + "/cores", + "/opt/homebrew", + "/Network", ]; -/// The system tree `path` is in, if any. The home directory is never -/// system, wherever it lives. -fn system_tree(path: &Path, home: Option<&Path>) -> Option<&'static str> { - if home.is_some_and(|home| path.starts_with(normalize(home))) { - return None; +/// How the guards compare paths: lexically normalized, and where the +/// platform has more than one spelling for a place, in one of them. +/// +/// macOS reaches the same directory under two names — `/Users/x` and +/// `/System/Volumes/Data/Users/x` — and its disks ignore case by default, so +/// `/library/caches` is `/Library/Caches`. Windows ignores case too, and +/// `\\?\C:\` is `C:\`. A guard that compared the spelling would be passed by +/// the other one. Only for judging: what is removed is always the path as +/// marked. +fn guard_key(path: &Path) -> PathBuf { + if cfg!(windows) { + return windows_key(&normalize(path)); } - SYSTEM_TREES - .iter() - .find(|tree| path.starts_with(tree)) - .copied() + guard_key_for(path, cfg!(target_os = "macos")) } -fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { +fn guard_key_for(path: &Path, macos: bool) -> PathBuf { + let path = normalize(path); + if !macos { + return path; + } + // The Data volume's own root stays as it is: it is under /System. + let path = match path.strip_prefix(crate::space::MACOS_DATA_VOLUME) { + Ok(rest) if !rest.as_os_str().is_empty() => Path::new("/").join(rest), + _ => path, + }; + PathBuf::from(path.to_string_lossy().to_lowercase()) +} + +#[cfg(windows)] +fn windows_key(path: &Path) -> PathBuf { + crate::windows::guard_key(path) +} + +#[cfg(not(windows))] +fn windows_key(path: &Path) -> PathBuf { + path.to_path_buf() +} + +/// `path` is `base` or inside it, by whole components, as the guards +/// compare them. +fn within(path: &Path, base: &Path) -> bool { + guard_key(path).starts_with(guard_key(base)) +} + +/// The system trees with their guard keys, computed once: the review screen +/// plans on every frame, for every mark. +fn system_tree_keys() -> &'static [(String, PathBuf)] { + static KEYS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| { + system_trees() + .into_iter() + .map(|tree| { + let key = guard_key(&tree); + (tree.display().to_string(), key) + }) + .collect() + }); + &KEYS +} + +#[cfg(not(windows))] +fn system_trees() -> Vec { + SYSTEM_TREES.iter().map(PathBuf::from).collect() +} + +/// [`SYSTEM_TREES`] on Windows: Windows itself, installed programs and +/// their machine-wide data, and what Windows keeps at the top of its drive +/// for restore points, recovery and booting. Taken from the environment, so +/// a system elsewhere is still recognized, and the usual places on the +/// system drive besides. +#[cfg(windows)] +fn system_trees() -> Vec { + let drive = system_drive(); + let mut trees: Vec = [ + "SystemRoot", + "ProgramFiles", + "ProgramFiles(x86)", + "ProgramW6432", + "ProgramData", + ] + .into_iter() + .filter_map(std::env::var_os) + .map(PathBuf::from) + // An empty or relative value would match too much or nothing at all. + .filter(|tree| tree.is_absolute()) + .collect(); + trees.extend( + [ + "Windows", + "Program Files", + "Program Files (x86)", + "ProgramData", + "System Volume Information", + "$Recycle.Bin", + "Recovery", + "Boot", + "bootmgr", + ] + .map(|name| drive.join(name)), + ); + trees +} + +/// The root of the drive Windows runs from, such as `C:\`. +#[cfg(windows)] +fn system_drive() -> PathBuf { + let mut drive = + std::env::var_os("SystemDrive").unwrap_or_else(|| "C:".into()); + // `C:` alone is the current directory on C:, not its root. + drive.push(r"\"); + PathBuf::from(drive) +} + +/// What to use instead, said when a system tree is refused. +#[cfg(not(windows))] +const SYSTEM_TOOLS: &str = "remove it with the tool that installed it"; + +#[cfg(windows)] +const SYSTEM_TOOLS: &str = "use Settings, or the program's own uninstaller"; + +/// The system tree the path keyed `key` is in, if any. The home directory is +/// never system, wherever it lives. +fn system_tree(key: &Path, home: Option<&Path>) -> Option<&'static str> { + if home.is_some_and(|home| key.starts_with(home)) { + return None; + } + system_tree_keys() + .iter() + .find(|(_, tree)| key.starts_with(tree)) + .map(|(name, _)| name.as_str()) +} + +/// A system tree strictly inside the path keyed `key`: removing `/opt` takes +/// `/opt/homebrew` with it, and `/var` takes `/var/lib`. +fn system_tree_below(key: &Path) -> Option<&'static str> { + system_tree_keys() + .iter() + .find(|(_, tree)| tree != key && tree.starts_with(key)) + .map(|(name, _)| name.as_str()) +} + +/// The home directory, as the guards compare it: by key, and by identity. +#[derive(Debug)] +struct Home { + key: PathBuf, + /// The key of the path with every link resolved: `/home` may be a link + /// to `/data/home`, and a scan of `/data` then shows home under a + /// spelling [`Self::key`] does not match. + real: Option, + /// Device and inode (volume and file id on Windows), so a spelling + /// [`guard_key`] cannot fold still matches. + id: Option<(u64, u64)>, +} + +impl Home { + fn of(path: &Path) -> Self { + Self { + key: guard_key(path), + real: fs::canonicalize(path).ok().map(|real| guard_key(&real)), + id: identity(path, true), + } + } +} + +fn refuse( + path: &Path, + root: &Path, + home: Option<&Home>, + mounts: &[PathBuf], +) -> Option { + let key = guard_key(path); + let root_key = guard_key(root); + let home_key = home.map(|home| home.key.as_path()); if path.parent().is_none() { return Some("the filesystem root cannot be removed".into()); } - if path == root { + if key == root_key { return Some("the scanned root cannot be removed".into()); } - if home.is_some_and(|home| path == normalize(home)) { + if cfg!(windows) + && let Some(name) = path.components().find_map(|part| match part { + Component::Normal(name) => { + misread_by_win32(&name.to_string_lossy()).then_some(name) + } + _ => None, + }) + { + return Some(format!( + "Windows would read {} as a different name, and remove that", + name.display() + )); + } + if home_key.is_some_and(|home| key == home) + || home + .and_then(|home| home.id) + .is_some_and(|id| identity(path, false) == Some(id)) + { return Some("the home directory cannot be removed".into()); } - if !path.starts_with(root) { + // On Linux `/home` is usually a mount point of its own and refused as + // one; on macOS `/Users` is on the same volume as `/`, and removing it + // would empty the home directory before failing on `/Users` itself. + if home_key.is_some_and(|home| home.starts_with(&key)) { + return Some("it contains the home directory".into()); + } + // By spelling too: the Data volume's root keeps its name as a key, while + // everything under it is keyed as under `/`. + if !key.starts_with(&root_key) && !path.starts_with(root) { return Some("outside the scanned root".into()); } - if let Some(system) = system_tree(path, home) { + if let Some(system) = system_tree(&key, home_key) { return Some(format!( - "part of the system under {system}: use the package manager" + "part of the system under {system}: {SYSTEM_TOOLS}" + )); + } + if let Some(system) = system_tree_below(&key) { + return Some(format!( + "it contains {system}, which is part of the system" )); } if is_mount_point(path) { @@ -188,9 +411,199 @@ fn refuse(path: &Path, root: &Path, home: Option<&Path>) -> Option { .into(), ); } + if let Some(mount) = mount_below(&key, mounts) { + return Some(format!( + "{} is mounted inside it: removing it would reach into another \ + filesystem", + mount.display() + )); + } None } +/// A name Win32 reads as some other one. It strips trailing dots and +/// spaces, so `C:\Users.` opens `C:\Users`; it reads `NUL` or `COM1` in +/// any directory as a device; and after a colon comes a stream of another +/// file. NTFS keeps such names when they arrive through `\\?\` or WSL, +/// and the scan lists them as stored, but the trash and the removal open +/// them through Win32. +fn misread_by_win32(name: &str) -> bool { + const DEVICES: [&str; 4] = ["con", "prn", "aux", "nul"]; + if name.ends_with(['.', ' ']) || name.contains(':') { + return true; + } + // `nul.txt` was a device too, before Windows 11: refused either way. + let stem = name + .split('.') + .next() + .unwrap_or(name) + .trim_end() + .to_lowercase(); + let numbered = ["com", "lpt"].iter().any(|device| { + stem.strip_prefix(device).is_some_and(|number| { + matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8") + || matches!(number, "9" | "\u{b9}" | "\u{b2}" | "\u{b3}") + }) + }); + numbered || DEVICES.contains(&stem.as_str()) +} + +/// Why `path`, inside `root` as spelled, is somewhere else in fact, if it +/// is. The guards compare spellings, and a link or junction on the way +/// down makes a spelling inside the root name something outside it: the +/// trash, and removal on Windows, follow it. Links above the root are the +/// user's own choice of root, so the real path is compared with the real +/// root. The home directory is looked for again by real path, too. +/// +/// Anything that cannot be resolved passes: the removal of a path that is +/// gone fails on its own. +fn linked( + path: &Path, + root: &Path, + real_root: Option<&Path>, + home: Option<&Home>, +) -> Option { + let (parent, name) = (path.parent()?, path.file_name()?); + let real = guard_key(&fs::canonicalize(parent).ok()?.join(name)); + if let (Some(real_root), Ok(rest)) = (real_root, path.strip_prefix(root)) + && real != guard_key(&real_root.join(rest)) + { + return Some(format!( + "reached through a link: it is really {}", + real.display() + )); + } + if home + .and_then(|home| home.real.as_ref()) + .is_some_and(|home| home.starts_with(&real)) + { + return Some("it contains the home directory".into()); + } + None +} + +/// `(device, inode)`: what makes two spellings one directory entry. +/// `follow` decides whether a symlink at `path` answers for itself or for +/// what it points to. +#[cfg(unix)] +fn identity(path: &Path, follow: bool) -> Option<(u64, u64)> { + use std::os::unix::fs::MetadataExt as _; + let meta = if follow { + fs::metadata(path) + } else { + fs::symlink_metadata(path) + }; + meta.ok().map(|meta| (meta.dev(), meta.ino())) +} + +/// `(volume serial, file id)`. Always what a link leads to: a junction to +/// the home directory is refused as the home directory, which is only ever +/// too careful. +#[cfg(windows)] +fn identity(path: &Path, _follow: bool) -> Option<(u64, u64)> { + crate::windows::identity(path) +} + +#[cfg(not(any(unix, windows)))] +const fn identity(_path: &Path, _follow: bool) -> Option<(u64, u64)> { + None +} + +/// How long a read of the mount table is used before it is read again. A +/// disk plugged in is noticed within this, and the removal itself stops at a +/// mount boundary whatever the table said. +const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2); + +/// The last read of the mount table, and whether a read is under way. +struct MountCache { + read: Option, + mounts: Option>>, + refreshing: bool, +} + +static MOUNTS: std::sync::Mutex = + std::sync::Mutex::new(MountCache { + read: None, + mounts: None, + refreshing: false, + }); + +/// Every mount point on this machine, as guard keys, as last read. +/// +/// Never blocks on the read: the review screen plans on every frame, and on +/// macOS the table comes from running `mount`. A stale table starts a read on +/// its own thread and is used meanwhile; before the first read lands it is +/// empty, which is why the app primes it at start with +/// [`prime_mount_points`]. +fn mount_points() -> Arc> { + let mut cache = MOUNTS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let fresh = cache.read.is_some_and(|read| read.elapsed() < MOUNTS_FRESH); + if !fresh && !cache.refreshing { + cache.refreshing = true; + let spawned = thread::Builder::new() + .name("disktree-mounts".into()) + .spawn(|| { + let mounts = Arc::new(read_mount_points()); + let mut cache = MOUNTS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + cache.mounts = Some(mounts); + cache.read = Some(std::time::Instant::now()); + cache.refreshing = false; + }); + if spawned.is_err() { + cache.refreshing = false; + } + } + cache.mounts.clone().unwrap_or_default() +} + +/// Start reading the mount table, so it is there by the time anything is +/// marked. +pub fn prime_mount_points() { + let _ = mount_points(); +} + +/// Read the mount points now: from `/proc/self/mounts`, or on macOS from +/// `mount`, which has no `/proc`. Empty where neither can be read. +fn read_mount_points() -> Vec { + let points: Vec = + if let Ok(table) = fs::read_to_string("/proc/self/mounts") { + crate::space::parse_mounts(&table) + .into_iter() + .map(|mount| mount.point) + .collect() + } else if cfg!(target_os = "macos") { + Command::new("/sbin/mount") + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .filter(|output| output.status.success()) + .map(|output| { + crate::space::parse_macos_mounts(&String::from_utf8_lossy( + &output.stdout, + )) + }) + .unwrap_or_default() + } else { + Vec::new() + }; + points.iter().map(|point| guard_key(point)).collect() +} + +/// A mount point strictly inside the path keyed `key`, if there is one. A +/// scan that stays on one filesystem never shows what is mounted there, so +/// the user cannot have meant to remove it. +fn mount_below<'a>(key: &Path, mounts: &'a [PathBuf]) -> Option<&'a Path> { + mounts + .iter() + .find(|mount| mount.as_path() != key && mount.starts_with(key)) + .map(PathBuf::as_path) +} + /// Whether `path` sits on a different device than its parent, i.e. is a /// mount point. Descending into one would delete data the user never marked. #[cfg(unix)] @@ -212,7 +625,13 @@ pub fn is_mount_point(path: &Path) -> bool { } } -#[cfg(not(unix))] +/// Whether `path` is a folder another volume is mounted on. +#[cfg(windows)] +pub fn is_mount_point(path: &Path) -> bool { + crate::windows::is_mount_point(path) +} + +#[cfg(not(any(unix, windows)))] pub fn is_mount_point(_path: &Path) -> bool { false } @@ -250,12 +669,17 @@ pub fn normalize(path: &Path) -> PathBuf { /// Which tool, if any, moves files to the desktop trash. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TrashBackend { + /// The macOS Trash, through `NSFileManager`: the same move as Finder's + /// Move to Trash, into the Trash of the volume the item is on. + MacOs, /// `trash-put` from trash-cli. TrashPut, /// `gio trash`, present anywhere `GLib` is installed. Gio, /// The XDG trash directory, implemented here. XdgHome, + /// The Windows Recycle Bin, through the shell's own file operation. + RecycleBin, /// No way to move files to a trash on this machine. #[default] Unavailable, @@ -264,22 +688,29 @@ pub enum TrashBackend { impl TrashBackend { pub const fn is_available(self) -> bool { match self { - Self::TrashPut | Self::Gio | Self::XdgHome => true, + Self::MacOs + | Self::TrashPut + | Self::Gio + | Self::XdgHome + | Self::RecycleBin => true, Self::Unavailable => false, } } pub const fn label(self) -> &'static str { match self { + Self::MacOs => "the Trash", Self::TrashPut => "trash-put", Self::Gio => "gio trash", Self::XdgHome => "XDG trash", + Self::RecycleBin => "the Recycle Bin", Self::Unavailable => "no trash tool found", } } pub const fn detail(self) -> &'static str { match self { + Self::MacOs => "the same Trash as Finder, on the item's own disk", Self::TrashPut => { "uses trash-cli, the same trash as your file manager" } @@ -287,6 +718,7 @@ impl TrashBackend { Self::XdgHome => { "moves into ~/.local/share/Trash on the same volume" } + Self::RecycleBin => "the same Recycle Bin as File Explorer", Self::Unavailable => { "install trash-cli or keep deleting permanently" } @@ -294,7 +726,25 @@ impl TrashBackend { } } +/// Detect the best available trash backend for this machine. Windows +/// always has its Recycle Bin. +#[cfg(windows)] +pub const fn detect_trash_backend() -> TrashBackend { + TrashBackend::RecycleBin +} + /// Detect the best available trash backend for this machine. +/// +/// On macOS the system Trash is always there, and the Linux tools are not +/// a substitute: Homebrew's `trash-put` writes the XDG layout, which Finder +/// never shows, so their files would look recoverable and not be. +#[cfg(target_os = "macos")] +pub const fn detect_trash_backend() -> TrashBackend { + TrashBackend::MacOs +} + +/// Detect the best available trash backend for this machine. +#[cfg(not(any(target_os = "macos", windows)))] pub fn detect_trash_backend() -> TrashBackend { if which("trash-put") { TrashBackend::TrashPut @@ -307,6 +757,7 @@ pub fn detect_trash_backend() -> TrashBackend { } } +#[cfg(not(any(target_os = "macos", windows)))] fn which(program: &str) -> bool { let Some(path) = std::env::var_os("PATH") else { return false; @@ -411,14 +862,37 @@ fn run( let mut removed = 0_u64; let mut bytes = 0_u64; let mut failed = 0_usize; + // The plan was judged against a mount table up to `MOUNTS_FRESH` old, + // or, right after start, not read yet. Judged again against a fresh + // read, here on the worker, before anything is touched. + let mounts = read_mount_points(); + // Links too: one put on the way down since the plan was made would lead + // the trash out of the root. Permanent removal on Unix refuses that by + // itself; see [`open_parent`]. + let home = std::env::home_dir().map(|home| Home::of(&home)); + let real_root = fs::canonicalize(&plan.root).ok(); for target in &plan.targets { if cancel.load(Ordering::Relaxed) { break; } - let outcome = match mode { - RemovalMode::Permanent => remove_permanently(&target.path), - RemovalMode::Trash => move_to_trash(&target.path, backend), + let reason = mounted(&target.path, &mounts).or_else(|| { + linked( + &target.path, + &plan.root, + real_root.as_deref(), + home.as_ref(), + ) + }); + let outcome = if let Some(reason) = reason { + Err(io::Error::other(reason)) + } else { + match mode { + RemovalMode::Permanent => { + remove_permanently(&target.path, &plan.root) + } + RemovalMode::Trash => move_to_trash(&target.path, backend), + } }; if outcome.is_ok() { removed += 1; @@ -440,28 +914,340 @@ fn run( }); } -/// `rm -rf` semantics: a symlink is unlinked, never followed. -pub fn remove_permanently(path: &Path) -> io::Result<()> { +/// Why `path` would reach into another filesystem, if it would: the +/// mount-point rules of [`refuse`], asked again at removal time. +fn mounted(path: &Path, mounts: &[PathBuf]) -> Option { + if is_mount_point(path) { + return Some("it became a mount point since it was marked".into()); + } + mount_below(&guard_key(path), mounts).map(|mount| { + format!( + "{} is mounted inside it: removing it would reach into another \ + filesystem", + mount.display() + ) + }) +} + +/// `rm -rf --one-file-system` semantics: a symlink is unlinked, never +/// followed, and nothing on another filesystem is touched. +/// +/// `fs::remove_dir_all` would descend into anything mounted inside `path` and +/// empty it before failing on the mount point itself, so the walk is done here +/// instead: every directory is opened relative to its parent with +/// `O_NOFOLLOW`, and one on a different device or mount stops the removal. +/// (From tobi/disktree#10.) +/// +/// The same goes for the way down to `path` from `root`, the scanned root: +/// see [`open_parent`]. +#[cfg(unix)] +pub fn remove_permanently(path: &Path, root: &Path) -> io::Result<()> { + use rustix::fs::{AtFlags, FileType, statat, unlinkat}; + + let (parent, name) = open_parent(path, root)?; + let stat = statat(&parent, name, AtFlags::SYMLINK_NOFOLLOW)?; + if FileType::from_raw_mode(stat.st_mode) != FileType::Directory { + unlinkat(&parent, name, AtFlags::empty())?; + return Ok(()); + } + let dir = open_dir(&parent, name)?; + let top = Volume::of(&dir)?; + remove_contents(&dir, &top, path)?; + drop(dir); + unlinkat(&parent, name, AtFlags::REMOVEDIR)?; + Ok(()) +} + +/// The directory holding `path`, and `path`'s own name in it. +/// +/// Opened one component at a time from `root`, none of them followed if it +/// is a symlink. The scan does not follow links, so no marked path has one +/// between the root and itself; one that does now was put there after the +/// scan, and following it would remove whatever it points to — a directory +/// swapped for a link to `~` would take `~/x` in place of the `/tmp/d/x` +/// that was marked. `rm -rf` has the same race; this closes it. Links above +/// the root are followed: they are how the user named it, and on macOS +/// `/tmp` and `/var` are links themselves. +#[cfg(unix)] +fn open_parent<'a>( + path: &'a Path, + root: &Path, +) -> io::Result<(std::os::fd::OwnedFd, &'a std::ffi::OsStr)> { + use rustix::io::Errno; + + let not_marked = || { + io::Error::other(format!( + "{} is not an absolute, normalized path", + path.display() + )) + }; + let name = path.file_name().ok_or_else(not_marked)?; + let below = path + .parent() + .and_then(|parent| parent.strip_prefix(root).ok()) + .ok_or_else(|| { + io::Error::other(format!( + "{} is not inside the scanned root {}", + path.display(), + root.display() + )) + })?; + let mut dir = open_root(root)?; + for component in below.components() { + match component { + Component::Normal(part) => { + dir = open_step(&dir, part).map_err(|error| match error { + Errno::LOOP | Errno::NOTDIR => io::Error::other(format!( + "{} changed since the scan: {} is no longer a \ + directory, so nothing was removed", + path.display(), + part.display() + )), + error => error.into(), + })?; + } + _ => return Err(not_marked()), + } + } + Ok((dir, name)) +} + +/// Open the scanned root, following links: see [`open_parent`]. +#[cfg(unix)] +fn open_root(root: &Path) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, open}; + #[cfg(any(target_os = "linux", target_os = "android"))] + let access = OFlags::PATH; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let access = OFlags::RDONLY; + open( + root, + access | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) +} + +/// Open a directory on the way down to a target, not following a symlink. +/// Only a handle to walk through: on Linux `O_PATH`, which needs no read +/// permission, just as a path lookup does not. +#[cfg(unix)] +fn open_step( + parent: impl std::os::fd::AsFd, + name: P, +) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, openat}; + #[cfg(any(target_os = "linux", target_os = "android"))] + let access = OFlags::PATH; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + let access = OFlags::RDONLY; + openat( + parent, + name, + access | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) +} + +#[cfg(not(unix))] +pub fn remove_permanently(path: &Path, _root: &Path) -> io::Result<()> { let meta = fs::symlink_metadata(path)?; if meta.is_dir() { fs::remove_dir_all(path) + } else if is_dir_link(&meta) { + // Windows removes a link to a directory, a junction or a directory + // symlink, as a directory: `RemoveDirectoryW` takes the link and + // leaves its target alone. + fs::remove_dir(path) } else { fs::remove_file(path) } } +/// Where a directory lives, as far as crossing into another filesystem goes. +#[cfg(unix)] +struct Volume { + device: rustix::fs::Stat, + /// The mount the directory belongs to, where the kernel reports it (Linux, + /// `statx`). See [`Self::contains`]. + mount: Option, +} + +#[cfg(unix)] +impl Volume { + fn of(dir: &std::os::fd::OwnedFd) -> io::Result { + Ok(Self { + device: rustix::fs::fstat(dir)?, + mount: mount_id(dir), + }) + } + + /// Whether `other` is on the same mount. Where the kernel names mounts, + /// that decides: a btrfs subvolume that is not mounted has its own + /// `st_dev` but is the same mount, and the scan showed it as part of the + /// volume, so it goes with the directory it is in; a bind mount keeps + /// `st_dev` but is a mount of its own, and stops the removal. Without + /// mount IDs (macOS) the device decides. + const fn contains(&self, other: &Self) -> bool { + match (self.mount, other.mount) { + (Some(one), Some(two)) => one == two, + _ => self.device.st_dev == other.device.st_dev, + } + } +} + +#[cfg(target_os = "linux")] +fn mount_id(dir: &std::os::fd::OwnedFd) -> Option { + use rustix::fs::{AtFlags, StatxFlags, statx}; + statx(dir, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID) + .ok() + .filter(|stat| stat.stx_mask & StatxFlags::MNT_ID.bits() != 0) + .map(|stat| stat.stx_mnt_id) +} + +#[cfg(all(unix, not(target_os = "linux")))] +const fn mount_id(_dir: &std::os::fd::OwnedFd) -> Option { + None +} + +#[cfg(unix)] +fn open_dir( + parent: impl std::os::fd::AsFd, + name: P, +) -> rustix::io::Result { + use rustix::fs::{Mode, OFlags, openat}; + openat( + parent, + name, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::empty(), + ) +} + +/// Empty the directory open at `dir`, staying on the volume of `top`. +#[cfg(unix)] +fn remove_contents( + dir: &std::os::fd::OwnedFd, + top: &Volume, + path: &Path, +) -> io::Result<()> { + use rustix::fs::{AtFlags, Dir, FileType, unlinkat}; + use rustix::io::Errno; + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt as _; + + // Names first, then removal: unlinking while a directory stream is open + // on the same directory may skip entries. + let mut entries = Vec::new(); + for entry in Dir::read_from(dir)? { + let entry = entry?; + let name = entry.file_name(); + if name != c"." && name != c".." { + entries.push((name.to_owned(), entry.file_type())); + } + } + + for (name, kind) in entries { + if !matches!(kind, FileType::Directory | FileType::Unknown) { + unlinkat(dir, &name, AtFlags::empty())?; + continue; + } + let child = match open_dir(dir, &name) { + Ok(child) => child, + // Not a directory after all: a symlink, or a file on a + // filesystem that does not report types. + Err(Errno::NOTDIR | Errno::LOOP) => { + unlinkat(dir, &name, AtFlags::empty())?; + continue; + } + Err(error) => return Err(error.into()), + }; + // Only directories need their path, for the message below. + let child_path = path.join(OsStr::from_bytes(name.to_bytes())); + if !top.contains(&Volume::of(&child)?) { + return Err(io::Error::other(format!( + "stopped at {}: another filesystem is mounted there, and \ + nothing on it was touched", + child_path.display() + ))); + } + remove_contents(&child, top, &child_path)?; + drop(child); + unlinkat(dir, &name, AtFlags::REMOVEDIR)?; + } + Ok(()) +} + +#[cfg(windows)] +fn is_dir_link(meta: &fs::Metadata) -> bool { + use std::os::windows::fs::FileTypeExt as _; + meta.file_type().is_symlink_dir() +} + +#[cfg(not(any(unix, windows)))] +const fn is_dir_link(_meta: &fs::Metadata) -> bool { + false +} + /// Move one path to the desktop trash. pub fn move_to_trash(path: &Path, backend: TrashBackend) -> io::Result<()> { match backend { TrashBackend::TrashPut => run_tool(Path::new("trash-put"), &[], path), TrashBackend::Gio => run_tool(Path::new("gio"), &["trash"], path), TrashBackend::XdgHome => trash_via_xdg(path), + TrashBackend::MacOs => trash_via_macos(path), + TrashBackend::RecycleBin => recycle(path), TrashBackend::Unavailable => Err(io::Error::other( "no trash tool is installed; use permanent deletion instead", )), } } +/// Move one path to the macOS Trash. +/// +/// The `trash` crate resolves the parent directory and keeps the final name, +/// so a symlink is trashed itself and its target is left alone. A name that is +/// not UTF-8 is refused rather than handed over: the crate would +/// percent-encode it into a different path. +#[cfg(target_os = "macos")] +fn trash_via_macos(path: &Path) -> io::Result<()> { + use trash::macos::{DeleteMethod, TrashContextExtMacos as _}; + + if path.to_str().is_none() { + return Err(io::Error::other( + "the name is not UTF-8, which the Trash cannot take; \ + use permanent deletion", + )); + } + let mut context = trash::TrashContext::default(); + // Finder's method asks for permission to control Finder and plays a + // sound per call; NSFileManager does neither. + context.set_delete_method(DeleteMethod::NsFileManager); + context.delete(path).map_err(|error| { + io::Error::other(format!( + "could not move to the Trash ({error}); network and read-only \ + disks have none, so use permanent deletion there" + )) + }) +} + +#[cfg(not(target_os = "macos"))] +fn trash_via_macos(_path: &Path) -> io::Result<()> { + Err(io::Error::other("the macOS Trash only exists on macOS")) +} + +/// Hand `path` to the Recycle Bin. `trash` asks the shell to warn before it +/// destroys anything rather than recycling it (`FOF_WANTNUKEWARNING`), so +/// the reversible path cannot turn into a permanent one silently. +#[cfg(windows)] +fn recycle(path: &Path) -> io::Result<()> { + trash::delete(path).map_err(io::Error::other) +} + +#[cfg(not(windows))] +fn recycle(_path: &Path) -> io::Result<()> { + Err(io::Error::other("the Recycle Bin is only on Windows")) +} + /// Run one trash tool on one path. /// /// `--` is passed before the path so that a file named `-rf` is read as a path @@ -547,6 +1333,7 @@ pub fn trash_into(_path: &Path, _trash: &Path) -> io::Result<()> { } /// `name`, or `name.1`, `name.2`, … until the name is free in `dir`. +#[cfg(unix)] fn unique_name(dir: &Path, name: &str) -> (PathBuf, String) { let first = dir.join(name); if !first.exists() { @@ -579,6 +1366,7 @@ pub fn percent_encode(input: &str) -> String { out } +#[cfg(unix)] fn deletion_date() -> String { // The specification wants ISO 8601 in local time; chrono is already in the // dependency graph, so use it rather than approximating the offset. @@ -599,6 +1387,12 @@ mod tests { } } + /// [`system_tree`] for plain paths, keyed the way [`refuse`] keys them. + #[cfg(not(windows))] + fn tree_of(path: &Path, home: &Path) -> Option<&'static str> { + system_tree(&guard_key(path), Some(&guard_key(home))) + } + fn tree() -> TempDir { let temp = TempDir::new().expect("tempdir"); fs::create_dir_all(temp.path().join("a/b")).expect("mkdir"); @@ -631,7 +1425,7 @@ mod tests { fn the_root_and_home_are_refused() { let temp = tree(); let root = temp.path(); - let home = std::env::var_os("HOME").map(PathBuf::from); + let home = std::env::home_dir(); let mut targets = vec![target(Path::new("/"), 0), target(root, 0)]; if let Some(home) = &home { targets.push(target(home, 0)); @@ -648,6 +1442,25 @@ mod tests { ); } + /// Removing a directory takes what is inside it, so the directories + /// above home are refused too: in a whole-disk scan, `C:\Users` is an + /// ordinary directory, and so is `/home` without a separate volume. + #[test] + fn the_directories_above_home_are_refused() { + let home = Home::of(Path::new("/home/disktree-test-user")); + let reason = + refuse(Path::new("/home"), Path::new("/"), Some(&home), &[]); + assert!( + reason.is_some_and(|reason| reason.contains("home directory")), + "the home directory is inside it" + ); + assert_eq!( + refuse(Path::new("/home/other"), Path::new("/"), Some(&home), &[]), + None, + "a sibling of home is not" + ); + } + #[test] fn paths_outside_the_root_are_refused() { let temp = tree(); @@ -690,33 +1503,417 @@ mod tests { } } + #[test] + fn a_directory_holding_the_home_directory_is_refused() { + // /Users in a whole-disk scan on macOS: the same volume as /, so no + // mount point, and removing it would empty home first. + let home = Path::new("/Users/tobi"); + let reason = refuse( + Path::new("/Users"), + Path::new("/"), + Some(&Home::of(home)), + &[], + ) + .expect("refused"); + assert!(reason.contains("home directory"), "{reason}"); + assert!( + refuse( + Path::new("/Users/tobi/src"), + Path::new("/"), + Some(&Home::of(home)), + &[] + ) + .is_none(), + "inside home is the user's" + ); + } + + #[cfg(not(windows))] + #[test] + fn a_directory_holding_a_system_tree_is_refused() { + let home = Path::new("/Users/tobi"); + for (path, inside) in [("/opt", "/opt/homebrew"), ("/var", "/var/lib")] + { + let reason = refuse( + Path::new(path), + Path::new("/"), + Some(&Home::of(home)), + &[], + ) + .expect("refused"); + assert!(reason.contains(inside), "{path}: {reason}"); + } + assert!( + refuse( + Path::new("/opt/local"), + Path::new("/"), + Some(&Home::of(home)), + &[] + ) + .is_none(), + "a sibling of a system tree is not its parent" + ); + } + + #[test] + fn a_target_with_a_mount_inside_is_refused() { + let temp = tree(); + let root = temp.path(); + let mounts = + vec![guard_key(&root.join("a/b")), guard_key(&root.join("other"))]; + assert_eq!( + mount_below(&guard_key(&root.join("a")), &mounts), + Some(guard_key(&root.join("a/b")).as_path()) + ); + assert_eq!( + mount_below(&guard_key(&root.join("a/b")), &mounts), + None, + "itself" + ); + let reason = + refuse(&root.join("a"), root, None, &mounts).expect("refused"); + assert!(reason.contains("mounted inside"), "{reason}"); + assert_eq!(refuse(&root.join("a/one.bin"), root, None, &mounts), None); + } + + #[test] + fn nothing_is_mounted_below_a_temp_dir() { + let temp = tree(); + assert_eq!( + mount_below(&guard_key(temp.path()), &read_mount_points()), + None + ); + } + + #[test] + #[cfg(target_os = "macos")] + fn this_macs_mount_table_is_read_without_proc() { + let mounts = read_mount_points(); + assert!(mounts.contains(&guard_key(Path::new("/"))), "{mounts:?}"); + // Asked of `mount_below` itself: `refuse` would turn /System/Volumes + // away as a system tree before it looked at the mounts. + assert!( + mount_below(&guard_key(Path::new("/System/Volumes")), &mounts) + .is_some(), + "the Data volume is mounted there" + ); + } + + #[test] + fn the_mount_table_is_read_off_the_calling_thread_and_then_kept() { + prime_mount_points(); + // The first read lands on its own thread; wait for it, briefly. + let mut mounts = mount_points(); + for _ in 0..500 { + if !mounts.is_empty() { + break; + } + thread::sleep(std::time::Duration::from_millis(10)); + mounts = mount_points(); + } + assert_eq!(*mounts, read_mount_points(), "the same table, cached"); + } + + #[test] + #[cfg(unix)] + fn a_volume_is_judged_by_its_mount_where_the_kernel_names_one() { + let temp = tree(); + let dir = open_dir(rustix::fs::CWD, temp.path()).expect("open"); + let here = Volume::of(&dir).expect("volume"); + let mut other = Volume::of(&dir).expect("volume"); + assert!(here.contains(&other)); + // A btrfs subvolume: another device, the same mount. + other.device.st_dev = other.device.st_dev.wrapping_add(1); + other.mount = Some(7); + let mount = Volume { + device: here.device, + mount: Some(7), + }; + assert!(mount.contains(&other), "same mount, other device"); + // A bind mount: the same device, another mount. + let bind = Volume { + device: here.device, + mount: Some(8), + }; + assert!(!mount.contains(&bind)); + // No mount IDs, as on macOS: the device decides. + let (mut plain, mut moved) = ( + Volume::of(&dir).expect("volume"), + Volume::of(&dir).expect("volume"), + ); + plain.mount = None; + moved.mount = None; + moved.device.st_dev = moved.device.st_dev.wrapping_add(1); + assert!(!plain.contains(&moved)); + } + + #[test] + fn macos_guard_keys_fold_the_data_volume_and_case() { + let key = |path: &str| guard_key_for(Path::new(path), true); + assert_eq!( + key("/System/Volumes/Data/Users/Tobi/src"), + PathBuf::from("/users/tobi/src") + ); + assert_eq!(key("/Library/./Caches"), PathBuf::from("/library/caches")); + assert_eq!( + key("/System/Volumes/Data"), + PathBuf::from("/system/volumes/data"), + "the Data volume itself stays under /System" + ); + assert_eq!( + guard_key_for(Path::new("/Library/X"), false), + PathBuf::from("/Library/X"), + "Linux paths are compared as spelled" + ); + } + + #[test] + #[cfg(target_os = "macos")] + fn macos_guards_see_through_other_spellings() { + let home = Path::new("/Users/tobi"); + let data = Path::new(crate::space::MACOS_DATA_VOLUME); + assert!( + refuse( + &data.join("Users/tobi/src"), + data, + Some(&Home::of(home)), + &[] + ) + .is_none(), + "home under the Data volume's name is still home" + ); + let reason = refuse( + Path::new("/library/caches"), + Path::new("/"), + Some(&Home::of(home)), + &[], + ) + .expect("refused"); + assert!(reason.contains("/Library"), "{reason}"); + } + + #[test] + fn permanent_removal_takes_nested_trees_and_hidden_files() { + let temp = tree(); + let doomed = temp.path().join("a"); + fs::create_dir_all(doomed.join("b/c/d")).expect("mkdir"); + fs::write(doomed.join("b/c/d/.hidden"), "x").expect("write"); + fs::write(doomed.join("b/c/f"), "x").expect("write"); + remove_permanently(&doomed, temp.path()).expect("remove tree"); + assert!(!doomed.exists()); + assert!(temp.path().join("other").exists()); + } + + #[test] + fn permanent_removal_unlinks_nested_symlinks_without_following_them() { + let temp = tree(); + let outside = TempDir::new().expect("tempdir"); + fs::write(outside.path().join("keep"), "x").expect("write"); + link_dir(outside.path(), &temp.path().join("a/link")); + remove_permanently(&temp.path().join("a"), temp.path()) + .expect("remove tree"); + assert!(outside.path().join("keep").exists()); + } + #[test] fn permanent_removal_takes_directories_and_leaves_siblings() { let temp = tree(); let doomed = temp.path().join("a/b"); - remove_permanently(&doomed).expect("remove dir"); + remove_permanently(&doomed, temp.path()).expect("remove dir"); assert!(!doomed.exists()); assert!(temp.path().join("a/c.bin").exists()); } + /// A link to a directory: a symbolic link on Unix, a junction on + /// Windows, which needs no privilege to make. + fn link_dir(target: &Path, link: &Path) { + #[cfg(unix)] + std::os::unix::fs::symlink(target, link).expect("symlink"); + #[cfg(windows)] + assert!(crate::windows::make_junction(link, target), "junction"); + } + #[test] fn permanent_removal_unlinks_a_symlink_instead_of_following_it() { let temp = tree(); let keep = TempDir::new().expect("tempdir"); fs::write(keep.path().join("precious.bin"), b"data").expect("write"); let link = temp.path().join("link"); - std::os::unix::fs::symlink(keep.path(), &link).expect("symlink"); + link_dir(keep.path(), &link); - remove_permanently(&link).expect("remove link"); - assert!(!link.exists()); + remove_permanently(&link, temp.path()).expect("remove link"); + assert!(fs::symlink_metadata(&link).is_err(), "the link is gone"); assert!(keep.path().join("precious.bin").exists()); } + /// Marked as `a/b/x`, then `a/b` swapped for a link to somewhere else + /// holding an `x`: that other `x` must survive. + #[test] + #[cfg(unix)] + fn permanent_removal_does_not_follow_a_link_put_on_the_way_down() { + let temp = tree(); + let keep = TempDir::new().expect("tempdir"); + fs::create_dir(keep.path().join("x")).expect("mkdir"); + fs::write(keep.path().join("x/precious.bin"), b"data").expect("write"); + let marked = temp.path().join("a/b/x"); + fs::remove_dir_all(temp.path().join("a/b")).expect("clear"); + link_dir(keep.path(), &temp.path().join("a/b")); + + let error = + remove_permanently(&marked, temp.path()).expect_err("refused"); + assert!(error.to_string().contains("changed since"), "{error}"); + assert!(keep.path().join("x/precious.bin").exists()); + } + + #[test] + fn a_target_reached_through_a_link_is_refused() { + let temp = tree(); + let keep = TempDir::new().expect("tempdir"); + fs::write(keep.path().join("precious.bin"), b"data").expect("write"); + link_dir(keep.path(), &temp.path().join("link")); + + let plan = plan( + &[target(&temp.path().join("link/precious.bin"), 4)], + temp.path(), + ); + assert!(plan.is_empty()); + assert!( + plan.blocked[0].reason.contains("through a link"), + "{}", + plan.blocked[0].reason + ); + } + + /// The trash follows links on the way down, so the worker asks again, + /// whatever the mode. + #[test] + fn a_link_put_on_the_way_down_after_planning_stops_the_worker() { + let temp = tree(); + let keep = TempDir::new().expect("tempdir"); + fs::create_dir(keep.path().join("x")).expect("mkdir"); + fs::write(keep.path().join("x/precious.bin"), b"data").expect("write"); + fs::create_dir(temp.path().join("a/b/x")).expect("mkdir"); + let plan = plan(&[target(&temp.path().join("a/b/x"), 0)], temp.path()); + assert_eq!(plan.targets.len(), 1); + fs::remove_dir_all(temp.path().join("a/b")).expect("clear"); + link_dir(keep.path(), &temp.path().join("a/b")); + + let handle = spawn(plan, RemovalMode::Permanent); + let mut outcome = None; + for _ in 0..2000 { + while let Some(event) = handle.poll() { + if let RemovalEvent::Item { outcome: item, .. } = event { + outcome = Some(item); + } + } + if outcome.is_some() { + break; + } + thread::sleep(std::time::Duration::from_millis(1)); + } + let error = outcome.expect("an item").expect_err("refused"); + assert!(error.contains("through a link"), "{error}"); + assert!(keep.path().join("x/precious.bin").exists()); + } + + #[test] + fn home_is_found_by_its_real_path_too() { + let temp = tree(); + let real = temp.path().join("data"); + fs::create_dir_all(real.join("home/user")).expect("mkdir"); + let spelled = TempDir::new().expect("tempdir"); + link_dir(&real.join("home"), &spelled.path().join("home")); + let home = Home::of(&spelled.path().join("home/user")); + let root = fs::canonicalize(temp.path()).expect("real root"); + + let reason = + linked(&root.join("data"), &root, Some(&root), Some(&home)) + .expect("refused"); + assert!(reason.contains("home directory"), "{reason}"); + assert_eq!( + linked(&root.join("other"), &root, Some(&root), Some(&home)), + None + ); + } + + #[test] + fn names_win32_would_misread_are_recognized() { + for name in [ + "Users.", + "Users ", + "a. .", + "NUL", + "nul.txt", + "Com1", + "LPT9.log", + "con ", + "file:stream", + "COM\u{b9}", + ] { + assert!(misread_by_win32(name), "{name:?}"); + } + for name in ["Users", ".git", "..hidden", "console", "COM0", "LPT10"] { + assert!(!misread_by_win32(name), "{name:?}"); + } + } + + /// On macOS the temporary directory is under `/var`, itself a link to + /// `/private/var`: a link above the scanned root is how it was named. + #[test] + fn permanent_removal_follows_links_above_the_root() { + let temp = tree(); + let spelled = TempDir::new().expect("tempdir"); + let root = spelled.path().join("root"); + link_dir(temp.path(), &root); + + remove_permanently(&root.join("a/b"), &root).expect("removed"); + assert!(!temp.path().join("a/b").exists()); + assert!(temp.path().join("a/one.bin").exists()); + } + + #[test] + fn a_mount_below_a_target_is_caught_again_at_removal_time() { + let temp = tree(); + let root = temp.path(); + let mounts = vec![guard_key(&root.join("a/b"))]; + let reason = mounted(&root.join("a"), &mounts).expect("caught"); + assert!(reason.contains("mounted inside"), "{reason}"); + assert_eq!(mounted(&root.join("other"), &mounts), None); + } + + /// Git keeps its objects read-only, which on Windows stops a plain + /// delete; clearing an old checkout must still work. + #[test] + fn read_only_files_are_removed_too() { + let temp = tree(); + let objects = temp.path().join("a/b/objects"); + fs::create_dir_all(&objects).expect("mkdir"); + let object = objects.join("pack.idx"); + fs::write(&object, b"x").expect("write"); + let mut permissions = + fs::metadata(&object).expect("stat").permissions(); + permissions.set_readonly(true); + fs::set_permissions(&object, permissions).expect("read-only"); + let lone = temp.path().join("a/lone.idx"); + fs::write(&lone, b"x").expect("write"); + let mut permissions = fs::metadata(&lone).expect("stat").permissions(); + permissions.set_readonly(true); + fs::set_permissions(&lone, permissions).expect("read-only"); + + remove_permanently(&lone, temp.path()).expect("a read-only file"); + remove_permanently(&temp.path().join("a/b"), temp.path()) + .expect("a directory"); + assert!(!lone.exists()); + assert!(!temp.path().join("a/b").exists()); + assert!(temp.path().join("a/c.bin").exists()); + } + #[test] fn a_missing_target_reports_not_found() { let temp = tree(); - let error = remove_permanently(&temp.path().join("absent")) - .expect_err("missing"); + let error = + remove_permanently(&temp.path().join("absent"), temp.path()) + .expect_err("missing"); assert_eq!(error.kind(), io::ErrorKind::NotFound); } @@ -728,6 +1925,7 @@ mod tests { assert_eq!(percent_encode("/a\nb"), "/a%0Ab"); } + #[cfg(unix)] #[test] fn trash_names_avoid_collisions() { let temp = TempDir::new().expect("tempdir"); @@ -740,6 +1938,7 @@ mod tests { assert_ne!(first, second); } + #[cfg(unix)] #[test] fn the_xdg_trash_moves_a_file_and_records_where_it_came_from() { // A private trash directory keeps the test out of the real trash can. @@ -762,6 +1961,7 @@ mod tests { assert!(info.contains("DeletionDate=")); } + #[cfg(unix)] #[test] fn a_trash_info_path_is_restorable() { let trash = TempDir::new().expect("tempdir"); @@ -830,6 +2030,7 @@ mod tests { assert!(root.join("a/one.bin").exists()); } + #[cfg(unix)] #[test] fn a_trash_tool_is_called_with_the_path_after_a_separator() { use std::os::unix::fs::PermissionsExt as _; @@ -858,6 +2059,7 @@ mod tests { assert!(doomed.exists(), "the real tool would have moved it"); } + #[cfg(unix)] #[test] fn a_failing_trash_tool_reports_its_stderr() { use std::os::unix::fs::PermissionsExt as _; @@ -872,7 +2074,9 @@ mod tests { assert!(error.to_string().contains("no trash here"), "{error}"); } + #[cfg(not(windows))] #[test] + #[cfg(not(any(target_os = "macos", windows)))] fn detection_prefers_a_tool_this_machine_has() { let backend = detect_trash_backend(); if which("trash-put") { @@ -881,34 +2085,140 @@ mod tests { assert!(backend.is_available()); } + #[cfg(windows)] #[test] + fn windows_trashes_into_the_recycle_bin() { + let backend = detect_trash_backend(); + assert_eq!(backend, TrashBackend::RecycleBin); + assert!(backend.is_available()); + } + + #[cfg(windows)] + #[test] + fn windows_system_trees_are_refused_in_a_whole_disk_scan() { + let drive = system_drive(); + let home = drive.join(r"Users\tobi"); + let system = |relative: &str| { + system_tree( + &guard_key(&drive.join(relative)), + Some(&guard_key(&home)), + ) + .map(str::to_lowercase) + }; + let windows = drive.join("Windows").display().to_string(); + assert!( + system(r"WINDOWS\System32\drivers\etc\hosts").is_some(), + "without regard to case" + ); + assert!(system(r"Program Files\App\app.exe").is_some()); + assert!(system(r"Program Files (x86)\App").is_some()); + assert!(system(r"ProgramData\Vendor\state.db").is_some()); + assert!(system("System Volume Information").is_some()); + assert_eq!(system("Windows.old"), None, "components, not prefixes"); + assert_eq!(system(r"Users\tobi\AppData\Local\Temp"), None); + assert_eq!(system("Games"), None); + let reason = refuse( + &drive.join(r"Windows\Temp"), + &drive, + Some(&Home::of(&home)), + &[], + ); + assert!( + reason.is_some_and(|reason| reason + .to_lowercase() + .contains(&windows.to_lowercase())), + "refused as part of {windows}" + ); + } + + #[test] + #[cfg(target_os = "macos")] + fn macos_always_uses_the_system_trash() { + // Whatever Homebrew put on PATH: its trash tools write a trash + // Finder never shows. + assert_eq!(detect_trash_backend(), TrashBackend::MacOs); + assert!(TrashBackend::MacOs.is_available()); + } + + #[test] + #[cfg(target_os = "macos")] + #[ignore = "puts a file in this Mac's real Trash"] + fn the_macos_trash_takes_a_file_and_leaves_a_linked_target() { + let temp = TempDir::new().expect("tempdir"); + let file = temp.path().join("disktree-trash-check.txt"); + fs::write(&file, b"x").expect("write"); + let keep = temp.path().join("keep.txt"); + fs::write(&keep, b"kept").expect("write"); + let link = temp.path().join("disktree-trash-check-link"); + std::os::unix::fs::symlink(&keep, &link).expect("symlink"); + + move_to_trash(&file, TrashBackend::MacOs).expect("trashed"); + move_to_trash(&link, TrashBackend::MacOs).expect("trashed"); + + assert!(!file.exists()); + assert!(fs::symlink_metadata(&link).is_err(), "the link went"); + assert_eq!(fs::read(&keep).expect("read"), b"kept", "not its target"); + } + + #[test] + #[cfg(target_os = "macos")] + fn a_name_that_is_not_utf8_is_refused_before_the_trash_sees_it() { + use std::os::unix::ffi::OsStrExt as _; + let temp = TempDir::new().expect("tempdir"); + let odd = temp + .path() + .join(std::ffi::OsStr::from_bytes(b"not-\xff-utf8")); + let error = trash_via_macos(&odd).expect_err("refused"); + assert!(error.to_string().contains("UTF-8"), "{error}"); + } + + #[test] + #[cfg(not(windows))] fn system_trees_are_refused_in_a_whole_disk_scan() { let home = Path::new("/home/tobi"); assert_eq!( - system_tree(Path::new("/usr/lib/libfoo.so"), Some(home)), + tree_of(Path::new("/usr/lib/libfoo.so"), home), Some("/usr") ); assert_eq!( - system_tree(Path::new("/var/lib/pacman"), Some(home)), + tree_of(Path::new("/var/lib/pacman"), home), Some("/var/lib") ); + assert_eq!(tree_of(Path::new("/var/cache/pacman/pkg"), home), None); + assert_eq!(tree_of(Path::new("/opt/thing"), home), None); assert_eq!( - system_tree(Path::new("/var/cache/pacman/pkg"), Some(home)), - None - ); - assert_eq!(system_tree(Path::new("/opt/thing"), Some(home)), None); - assert_eq!( - system_tree(Path::new("/usrlocal"), Some(home)), + tree_of(Path::new("/usrlocal"), home), None, "components, not prefixes" ); let odd_home = Path::new("/usr/home/tobi"); - assert_eq!( - system_tree(Path::new("/usr/home/tobi/.cache"), Some(odd_home)), - None + assert_eq!(tree_of(Path::new("/usr/home/tobi/.cache"), odd_home), None); + let reason = refuse( + Path::new("/etc/hosts"), + Path::new("/"), + Some(&Home::of(home)), + &[], ); - let reason = - refuse(Path::new("/etc/hosts"), Path::new("/"), Some(home)); assert!(reason.is_some_and(|reason| reason.contains("/etc"))); } + + #[test] + #[cfg(not(windows))] + fn macos_system_trees_are_refused_but_apps_are_not() { + let home = Path::new("/Users/tobi"); + for (path, tree) in [ + ("/System/Library/Fonts", "/System"), + ("/Library/Caches/com.apple.x", "/Library"), + ("/private/etc/hosts", "/private"), + ("/private/var/folders/xy", "/private"), + ("/opt/homebrew/Cellar/git", "/opt/homebrew"), + ] { + assert_eq!(tree_of(Path::new(path), home), Some(tree)); + } + // An app is uninstalled by moving it to the Trash, and a user's own + // Library is theirs. + for path in ["/Applications/Xcode.app", "/Users/tobi/Library/Caches"] { + assert_eq!(tree_of(Path::new(path), home), None, "{path}"); + } + } } diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index be5f2ff..2dd0ed7 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -15,7 +15,9 @@ //! poll without locking, and cooperative cancellation so a re-scan can abandon //! a walk of a large home directory instead of queueing behind it. -use std::fs::{self, DirEntry, Metadata}; +#[cfg(not(windows))] +use std::fs::DirEntry; +use std::fs::{self, Metadata}; use std::io; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; @@ -114,10 +116,11 @@ impl ScanProgress { fn record_error(&self, path: &Path, error: &io::Error) { self.errors.fetch_add(1, Ordering::Relaxed); - let message = format!("{}: {error}", path.display()); + // A scan without Full Disk Access can refuse thousands of paths; + // only the ones that will be kept are worth formatting. let mut messages = lock(&self.messages); if messages.len() < MAX_ERROR_DETAIL { - messages.push(message); + messages.push(format!("{}: {error}", path.display())); } drop(messages); } @@ -185,6 +188,7 @@ impl ScanHandle { progress: Arc::clone(&progress), root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), + never_scanned: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), root: Mutex::new(None), }); @@ -233,6 +237,7 @@ pub fn scan(root: &Path, options: ScanOptions) -> io::Result { progress: Arc::clone(&progress), root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), + never_scanned: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), root: Mutex::new(None), }); @@ -252,6 +257,9 @@ struct WalkContext { /// Mount points `one_filesystem` keeps out, from the mount table. Unset /// when the table cannot be read, and devices are compared instead. foreign_mounts: OnceLock>, + /// Directories no scan enters, on any volume setting: see + /// [`crate::space::never_scanned`]. + never_scanned: OnceLock>, /// Directories already entered, so followed symlinks cannot loop. visited_dirs: Mutex>, /// Set by the root's `complete`, read after the scope joins. @@ -274,72 +282,28 @@ impl WalkContext { } /// Decide what to do with an entry, and account for the work it implies. - fn classify(&self, entry: &DirEntry) -> Classified { - let path = entry.path(); - let file_type = match entry.file_type() { - Ok(file_type) => file_type, + fn classify(&self, entry: &impl Listed) -> Classified { + let path = entry.entry_path(); + let listing = match entry.listing() { + Ok(listing) => listing, Err(error) => { self.progress.record_error(&path, &error); return Classified::Skipped; } }; - // Non-UTF-8 names are lossy for display. The scan still measures them - // correctly; only the reported name is approximate. - let name: Box = - entry.file_name().to_string_lossy().into_owned().into(); + let name = entry.display_name(); if !self.options.include_hidden && name.starts_with('.') { return Classified::Skipped; } - if file_type.is_symlink() { - return self.classify_symlink(&path, name); - } - - if file_type.is_dir() { - // Memoized: the subtree a narrower scan already measured is - // taken whole, before any volume rule, since it was measured - // under the same rules. - if let Some(known) = &self.known - && known.path == path - { - let tree = (*known.tree).clone(); - self.progress.files.fetch_add(tree.files, Ordering::Relaxed); - self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed); - self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed); - let mut tree = tree; - tree.name = name; - return Classified::Entry(tree); - } - if self.options.one_filesystem - && let Some(foreign) = self.foreign_mounts.get() - { - // Checked by path before anything reads the directory, so an - // automount point is never triggered. - if foreign.contains(&path) { - return Classified::Skipped; - } - } else if self.options.one_filesystem { - let device = entry.metadata().map(|meta| device_of(&meta)); - match (device, self.root_device(&path)) { - (Ok(device), Some(root_device)) - if device != root_device => - { - return Classified::Skipped; - } - (Err(error), _) => { - self.progress.record_error(&path, &error); - return Classified::Skipped; - } - _ => {} - } - } - self.progress.count_dir(); - return Classified::Subdirectory(path); - } - - match entry.metadata() { - Ok(meta) => self.leaf(name, kind_of(&meta, file_type), &meta), + let kind = match listing { + Listing::Symlink => return self.classify_symlink(&path, name), + Listing::Directory => return self.classify_dir(entry, path, name), + Listing::Leaf(kind) => kind, + }; + match entry.facts(self.options.apparent_size) { + Ok(facts) => self.leaf(name, kind, &facts), Err(error) => { self.progress.record_error(&path, &error); Classified::Skipped @@ -347,19 +311,84 @@ impl WalkContext { } } + fn classify_dir( + &self, + entry: &impl Listed, + path: PathBuf, + name: Box, + ) -> Classified { + if self + .never_scanned + .get() + .is_some_and(|never| never.contains(&path)) + { + return Classified::Skipped; + } + // Read at most once per directory: macOS needs it for the dataless + // flag, and the device check below wherever the mount table cannot + // be read, which on macOS is everywhere. + let directory_cell = std::cell::OnceCell::new(); + let directory = || directory_cell.get_or_init(|| entry.directory()); + if EVICTED_IS_KNOWN + && directory() + .as_ref() + .is_ok_and(|directory| directory.evicted) + { + return Classified::Skipped; + } + // Memoized: the subtree a narrower scan already measured is taken + // whole, before any volume rule, since it was measured under the same + // rules. + if let Some(known) = &self.known + && known.path == path + { + let tree = (*known.tree).clone(); + self.progress.files.fetch_add(tree.files, Ordering::Relaxed); + self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed); + self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed); + let mut tree = tree; + tree.name = name; + return Classified::Entry(tree); + } + if self.options.one_filesystem + && let Some(foreign) = self.foreign_mounts.get() + { + // Checked by path before anything reads the directory, so an + // automount point is never triggered. + if foreign.contains(&path) { + return Classified::Skipped; + } + } else if self.options.one_filesystem { + match (directory(), self.root_device(&path)) { + (Ok(directory), Some(root_device)) + if directory.device != root_device => + { + return Classified::Skipped; + } + (Err(error), _) => { + self.progress.record_error(&path, error); + return Classified::Skipped; + } + _ => {} + } + } + self.progress.count_dir(); + Classified::Subdirectory(path) + } + fn classify_symlink(&self, path: &Path, name: Box) -> Classified { if !self.options.follow_links { // Not followed: the link occupies only its target string, which // `du` reports as a handful of bytes or nothing at all. return match fs::symlink_metadata(path) { Ok(meta) => { - let size = measure(&meta, self.options.apparent_size); - self.progress.count_file(size); + let facts = Facts::of(&meta, self.options.apparent_size); + self.progress.count_file(facts.size); Classified::Entry(leaf_node( name, NodeKind::Symlink, - size, - &meta, + &facts, + facts.shared, )) } Err(error) => { @@ -381,7 +410,12 @@ impl WalkContext { }; if meta.is_dir() { - if let Some(key) = file_identity(&meta) + // A link into an evicted cloud folder is left alone for the + // same reason the folder itself is. + if is_dataless(&meta) { + return Classified::Skipped; + } + if let Some(key) = identity_of(path, &meta) && !lock(&self.visited_dirs).insert(key) { return Classified::Skipped; @@ -390,21 +424,179 @@ impl WalkContext { return Classified::Subdirectory(path.to_path_buf()); } - self.leaf(name, kind_of(&meta, meta.file_type()), &meta) + let mut facts = Facts::of(&meta, self.options.apparent_size); + // What the link leads to, so a file that is also reached directly is + // charged once. + facts.identity = identity_of(path, &meta); + self.leaf(name, kind_of(&meta, meta.file_type()), &facts) } fn leaf( &self, name: Box, kind: NodeKind, - meta: &Metadata, + facts: &Facts, ) -> Classified { - let size = measure(meta, self.options.apparent_size); - self.progress.count_file(size); - Classified::Entry(leaf_node(name, kind, size, meta)) + 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; + Classified::Entry(leaf_node(name, kind, facts, track)) } } +/// What the walk reads about one directory entry. +/// +/// `std::fs::DirEntry` everywhere but Windows. There the standard listing +/// has neither the allocated size nor a file id, so measuring like `du` +/// would cost an open per file; [`crate::windows`] lists a directory with +/// both instead. +trait Listed { + fn entry_path(&self) -> PathBuf; + /// Non-UTF-8 names are lossy for display. The scan still measures them + /// correctly; only the reported name is approximate. + fn display_name(&self) -> Box; + fn listing(&self) -> io::Result; + /// Size, identity and age of a leaf. + fn facts(&self, apparent_size: bool) -> io::Result; + /// What a directory is, read before the walk enters it. + fn directory(&self) -> io::Result; +} + +/// Whether [`Directory::evicted`] can ever be true here, so a platform that +/// cannot say never pays for asking. +const EVICTED_IS_KNOWN: bool = cfg!(any(target_os = "macos", windows)); + +/// What the walk needs to know about a directory before entering it. +struct Directory { + /// The device it is on, for staying on one volume when the mount table + /// cannot be read. + device: u64, + /// Its contents live only in the cloud (iCloud Drive or a File Provider + /// on macOS, `OneDrive` or another cloud files provider on Windows). + /// Listing it would make the provider fetch them, so a disk scan must + /// not; it holds no local blocks, so skipping it loses nothing. + evicted: bool, +} + +/// What an entry is, as far as the walk is concerned. +enum Listing { + Directory, + Symlink, + Leaf(NodeKind), +} + +/// What a leaf contributes. +struct Facts { + size: u64, + identity: Option<(u64, u64)>, + modified: i64, + /// The file may have another name the walk could meet: its identity is + /// worth keeping for hardlink de-duplication. + shared: bool, +} + +impl Facts { + fn of(meta: &Metadata, apparent_size: bool) -> Self { + Self { + size: measure(meta, apparent_size), + identity: file_identity(meta), + modified: modified_seconds(meta), + shared: shares_inode(meta), + } + } +} + +#[cfg(not(windows))] +impl Listed for DirEntry { + fn entry_path(&self) -> PathBuf { + self.path() + } + + fn display_name(&self) -> Box { + self.file_name().to_string_lossy().into_owned().into() + } + + fn listing(&self) -> io::Result { + let file_type = self.file_type()?; + Ok(if file_type.is_symlink() { + Listing::Symlink + } else if file_type.is_dir() { + Listing::Directory + } else if file_type.is_file() { + Listing::Leaf(NodeKind::File) + } else { + Listing::Leaf(NodeKind::Other) + }) + } + + fn facts(&self, apparent_size: bool) -> io::Result { + self.metadata().map(|meta| Facts::of(&meta, apparent_size)) + } + + fn directory(&self) -> io::Result { + self.metadata().map(|meta| Directory { + device: device_of(&meta), + evicted: is_dataless(&meta), + }) + } +} + +#[cfg(windows)] +impl Listed for crate::windows::Entry { + fn entry_path(&self) -> PathBuf { + self.path() + } + + fn display_name(&self) -> Box { + self.file_name().to_string_lossy().into_owned().into() + } + + fn listing(&self) -> io::Result { + Ok(match self.kind() { + crate::windows::Kind::Link => Listing::Symlink, + crate::windows::Kind::Directory => Listing::Directory, + crate::windows::Kind::File => Listing::Leaf(NodeKind::File), + }) + } + + fn facts(&self, apparent_size: bool) -> io::Result { + Ok(Facts { + size: if apparent_size { + self.apparent() + } else { + self.allocated() + }, + identity: self.identity(), + modified: self.modified(), + // The listing has no link count; a file id is free here, so + // every file keeps one. + shared: true, + }) + } + + /// The device is never consulted: see + /// [`crate::space::foreign_mounts_for`]. The same answer as + /// [`device_of`], so the two could only ever agree. + fn directory(&self) -> io::Result { + Ok(Directory { + device: 0, + evicted: self.evicted(), + }) + } +} + +/// List a directory the way [`Listed`] describes. +#[cfg(not(windows))] +fn list(path: &Path) -> io::Result { + fs::read_dir(path) +} + +#[cfg(windows)] +fn list(path: &Path) -> io::Result { + crate::windows::read_dir(path) +} + /// What a directory entry turned out to be. enum Classified { /// Descend into this directory on a new task. @@ -478,15 +670,17 @@ fn scan_blocking(root: &Path, context: &Arc) -> io::Result { 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 _ = context.never_scanned.set(never.into_iter().collect()); if context.options.one_filesystem { *lock(&context.root_device) = Some(device_of(&root_meta)); - let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); - if let Some(foreign) = crate::space::foreign_mounts_for(&root) { + if let Some(foreign) = crate::space::foreign_mounts_for(&canonical) { let _ = context.foreign_mounts.set(foreign.into_iter().collect()); } } if context.options.follow_links - && let Some(key) = file_identity(&root_meta) + && let Some(key) = identity_of(root, &root_meta) { lock(&context.visited_dirs).insert(key); } @@ -508,7 +702,7 @@ fn walk(scope: &Scope<'_>, dir: &Arc, context: &Arc) { let mut subdirs: Vec> = Vec::new(); let mut leaves: Vec = Vec::new(); - match fs::read_dir(&dir.path) { + match list(&dir.path) { Ok(entries) => { for entry in entries { if context.cancelled() { @@ -607,15 +801,20 @@ fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) { } } +/// A leaf. Its identity is kept only when `track` says the walk could meet +/// the same file again: a hardlink de-duplication set of every file on a +/// disk is millions of entries, nearly all for files with one name. fn leaf_node( name: Box, kind: NodeKind, - size: u64, - meta: &Metadata, + facts: &Facts, + track: bool, ) -> Node { - let mut node = Node::entry(name, kind, size); - node.inode = file_identity(meta); - node.modified = modified_seconds(meta); + let mut node = Node::entry(name, kind, facts.size); + if track { + node.inode = facts.identity; + } + node.modified = facts.modified; node } @@ -654,10 +853,41 @@ fn allocated_bytes(meta: &Metadata) -> Option { } #[cfg(not(unix))] -fn allocated_bytes(_meta: &Metadata) -> Option { +const fn allocated_bytes(_meta: &Metadata) -> Option { None } +/// Whether a directory's contents are only in the cloud: an iCloud Drive or +/// File Provider folder macOS has evicted. Listing one makes macOS fetch its +/// entries from the server, so a disk scan must not; the folder holds no +/// local blocks, so skipping it loses nothing a scan measures. +/// +/// A `stat` or `lstat` carries the flag without touching the contents. +#[cfg(target_os = "macos")] +fn is_dataless(meta: &Metadata) -> bool { + use std::os::macos::fs::MetadataExt as _; + // `SF_DATALESS` from ; the libc crate does not name it. + const SF_DATALESS: u32 = 0x4000_0000; + meta.st_flags() & SF_DATALESS != 0 +} + +#[cfg(not(target_os = "macos"))] +const fn is_dataless(_meta: &Metadata) -> bool { + false +} + +/// Whether the file has more than one name, so the walk can count it twice. +#[cfg(unix)] +fn shares_inode(meta: &Metadata) -> bool { + use std::os::unix::fs::MetadataExt as _; + meta.nlink() > 1 +} + +#[cfg(not(unix))] +const fn shares_inode(_meta: &Metadata) -> bool { + false +} + #[cfg(unix)] fn device_of(meta: &Metadata) -> u64 { use std::os::unix::fs::MetadataExt as _; @@ -665,13 +895,15 @@ fn device_of(meta: &Metadata) -> u64 { } #[cfg(not(unix))] -fn device_of(_meta: &Metadata) -> u64 { +const fn device_of(_meta: &Metadata) -> u64 { 0 } /// `(device, inode)`, or `None` where the platform does not expose them. /// Hardlink de-duplication and symlink loop detection both depend on this, so -/// they are simply unavailable rather than silently wrong elsewhere. +/// they are simply unavailable rather than silently wrong elsewhere. Windows +/// has no file id in `Metadata` on stable Rust; its listing carries one +/// instead (see [`crate::windows`]). #[allow( clippy::unnecessary_wraps, reason = "the Option is the non-Unix answer, so both arms must agree" @@ -683,10 +915,23 @@ fn file_identity(meta: &Metadata) -> Option<(u64, u64)> { } #[cfg(not(unix))] -fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> { +const fn file_identity(_meta: &Metadata) -> Option<(u64, u64)> { None } +/// The identity of what `path` leads to, `meta` being its followed +/// metadata: how a walk that follows links recognizes a directory it has +/// entered before, and a file it has already charged. +#[cfg(not(windows))] +fn identity_of(_path: &Path, meta: &Metadata) -> Option<(u64, u64)> { + file_identity(meta) +} + +#[cfg(windows)] +fn identity_of(path: &Path, _meta: &Metadata) -> Option<(u64, u64)> { + crate::windows::identity(path) +} + fn kind_of(meta: &Metadata, file_type: fs::FileType) -> NodeKind { if meta.is_dir() || file_type.is_dir() { NodeKind::Directory @@ -838,6 +1083,20 @@ mod tests { assert_eq!(without.bytes, 100); } + /// A link to a directory: a symbolic link on Unix, a junction on + /// Windows, which needs no privilege to make. `false` if it could not be + /// made. + fn link_dir(target: &Path, link: &Path) -> bool { + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(windows)] + { + crate::windows::make_junction(link, target) + } + } + #[test] fn symlinks_are_not_followed_by_default() { let temp = TempDir::new().expect("tempdir"); @@ -845,8 +1104,7 @@ mod tests { write(outside.path(), "elsewhere.bin", 5000); let root = temp.path(); write(root, "real.bin", 100); - std::os::unix::fs::symlink(outside.path(), root.join("link")) - .expect("symlink"); + assert!(link_dir(outside.path(), &root.join("link")), "a link"); let tree = scan_dir(root, &options()); // Only the real file's bytes; the link itself holds just its target @@ -862,8 +1120,7 @@ mod tests { let temp = TempDir::new().expect("tempdir"); let root = temp.path(); write(root, "sub/leaf.bin", 42); - std::os::unix::fs::symlink(root, root.join("sub/loop")) - .expect("symlink"); + assert!(link_dir(root, &root.join("sub/loop")), "a link"); let tree = scan_dir( root, @@ -875,6 +1132,29 @@ mod tests { assert_eq!(tree.bytes, 42); } + /// Disk usage is what the volume allocated, not the length: whole + /// blocks, so it covers the data and ends on a block boundary. + #[test] + fn disk_usage_is_whole_allocation_units() { + let temp = TempDir::new().expect("tempdir"); + // Noise, so a compressing filesystem cannot store it in less. + let mut state = 0x2545_f491_4f6c_dd1d_u64; + let noise: Vec = (0..100_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state.to_le_bytes()[0] + }) + .collect(); + fs::write(temp.path().join("data.bin"), noise).expect("write"); + let tree = scan_dir(temp.path(), &ScanOptions::default()); + assert!(tree.bytes >= 100_000, "{}", tree.bytes); + assert_eq!(tree.bytes % 512, 0, "{}", tree.bytes); + let apparent = scan_dir(temp.path(), &options()); + assert_eq!(apparent.bytes, 100_000); + } + #[test] fn max_depth_stops_descending_but_keeps_direct_files() { let temp = TempDir::new().expect("tempdir"); @@ -927,6 +1207,7 @@ mod tests { assert_eq!(by_files.children[0].files, 5); } + #[cfg(unix)] #[test] fn an_unreadable_directory_is_recorded_not_fatal() { use std::os::unix::fs::PermissionsExt as _; @@ -948,6 +1229,7 @@ mod tests { progress: Arc::clone(&progress), root_device: Mutex::new(None), foreign_mounts: OnceLock::new(), + never_scanned: OnceLock::new(), visited_dirs: Mutex::new(FxHashSet::default()), root: Mutex::new(None), }); @@ -1040,7 +1322,7 @@ mod tests { #[test] #[ignore = "walks the whole disk"] fn whole_disk_smoke() { - let home = std::env::var_os("HOME").map(PathBuf::from).expect("HOME"); + let home = std::env::home_dir().expect("a home directory"); let root = crate::space::volume_root_for(&home).expect("a volume root"); let started = std::time::Instant::now(); let tree = scan(&root, ScanOptions::default()).expect("scan"); diff --git a/crates/disktree-core/src/space.rs b/crates/disktree-core/src/space.rs index 008eec3..f7b5bb4 100644 --- a/crates/disktree-core/src/space.rs +++ b/crates/disktree-core/src/space.rs @@ -49,6 +49,13 @@ impl SpaceInfo { } /// Read the space on the volume containing `path`. +#[cfg(windows)] +pub fn space_info(path: &Path) -> io::Result { + crate::windows::space_info(path) +} + +/// Read the space on the volume containing `path`. +#[cfg(not(windows))] pub fn space_info(path: &Path) -> io::Result { let stat = rustix::fs::statvfs(path)?; // `f_frsize` is the fragment size the block counts are expressed in; @@ -66,9 +73,17 @@ pub fn space_info(path: &Path) -> io::Result { }) } +/// The volume a path is on, as Windows names it: `C:\`, a share, or the +/// folder a volume is mounted on. +#[cfg(windows)] +pub fn device_for(path: &Path) -> Option { + crate::windows::volume_root(path).map(|root| root.display().to_string()) +} + /// The device a path's filesystem is mounted from, such as /// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in /// `/proc/self/mounts`. `None` where that table cannot be read. +#[cfg(not(any(target_os = "macos", windows)))] pub fn device_for(path: &Path) -> Option { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); @@ -186,19 +201,134 @@ pub fn volume_root(mounts: &[Mount], path: &Path) -> Option { } /// [`volume_root`] for this machine. +#[cfg(not(any(target_os = "macos", windows)))] pub fn volume_root_for(path: &Path) -> Option { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); volume_root(&parse_mounts(&table), &path) } +/// The top of the volume `path` lives on: its drive, such as `C:\`. +#[cfg(windows)] +pub fn volume_root_for(path: &Path) -> Option { + crate::windows::volume_root(path) +} + /// [`foreign_mounts`] for this machine; `None` when the mount table cannot /// be read, so the caller can fall back to comparing devices. +#[cfg(not(windows))] pub fn foreign_mounts_for(root: &Path) -> Option> { let table = std::fs::read_to_string("/proc/self/mounts").ok()?; Some(foreign_mounts(&parse_mounts(&table), root)) } +/// The mount points in what macOS's `mount` prints. +/// +/// One per line: `/dev/disk3s5 on /System/Volumes/Data (apfs, local, …)`. +/// The point is +/// between the first ` on ` and the last ` (`, so a name with spaces or +/// brackets in it survives. +pub fn parse_macos_mounts(output: &str) -> Vec { + output + .lines() + .filter_map(|line| { + let (_, rest) = line.split_once(" on ")?; + let (point, _) = rest.rsplit_once(" (")?; + Some(PathBuf::from(point)) + }) + .collect() +} + +/// Where the Data volume is mounted on macOS. +/// +/// Since Catalina `/` is a read-only system volume, and everything the user +/// can write — `/Users`, +/// `/Applications`, `/Library`, `/private`, … — lives on the Data volume, +/// joined into `/` by firmlinks. The two report the same device, and +/// `/Users` and `/System/Volumes/Data/Users` are the same inode. +pub const MACOS_DATA_VOLUME: &str = "/System/Volumes/Data"; + +/// Directories under `root` a scan must never enter, whatever the volume +/// rules say, given where `root` really is (`canonical`). +/// +/// On macOS: the Data volume's second mount, which is every firmlinked +/// directory again under another name, so walking it counts the disk twice; +/// and `/Network`, an automount point that would reach for a server. The +/// paths are returned in `root`'s own spelling, because that is how the walk +/// names what it finds. +pub fn never_scanned(root: &Path, canonical: &Path) -> Vec { + if !cfg!(target_os = "macos") { + return Vec::new(); + } + [MACOS_DATA_VOLUME, "/Network"] + .iter() + .filter_map(|skip| Path::new(skip).strip_prefix(canonical).ok()) + .filter(|below| !below.as_os_str().is_empty()) + .map(|below| root.join(below)) + .collect() +} + +/// The top of the disk `path` lives on: its mount point, from `statfs`. +/// +/// The Data volume answers `/System/Volumes/Data`, but the disk a user +/// thinks of is `/`, which shows the same files under the names Finder uses +/// and adds the system volume beside them. +#[cfg(target_os = "macos")] +pub fn volume_root_for(path: &Path) -> Option { + let stat = rustix::fs::statfs(path).ok()?; + let mount = PathBuf::from(c_chars(&stat.f_mntonname)); + if mount.as_os_str().is_empty() { + return None; + } + Some(if mount == Path::new(MACOS_DATA_VOLUME) { + PathBuf::from("/") + } else { + mount + }) +} + +/// The device a path's filesystem is mounted from, such as +/// `/dev/disk3s5`, from `statfs`. +#[cfg(target_os = "macos")] +pub fn device_for(path: &Path) -> Option { + // `/` is a snapshot of the system volume (`disk3s1s1`); name the disk + // the user's files are on instead, which is what the meter measures. + let path = if path == Path::new("/") { + Path::new(MACOS_DATA_VOLUME) + } else { + path + }; + let stat = rustix::fs::statfs(path).ok()?; + let device = c_chars(&stat.f_mntfromname); + (!device.is_empty()).then_some(device) +} + +/// A NUL-terminated C string field as text. +#[cfg(target_os = "macos")] +fn c_chars(field: &[std::ffi::c_char]) -> String { + let bytes: Vec = field + .iter() + .take_while(|&&byte| byte != 0) + .map(|&byte| byte as u8) + .collect(); + String::from_utf8_lossy(&bytes).into_owned() +} + +/// Nothing to leave out by path on Windows. +/// +/// There, the only way into another volume below `root` is a folder that +/// volume is mounted on, which is a reparse point the walk treats as a link +/// and does not enter unless links are followed; other drives are separate +/// trees altogether. +#[cfg(windows)] +#[allow( + clippy::unnecessary_wraps, + reason = "the Option is the Unix answer when the mount table is missing" +)] +pub const fn foreign_mounts_for(_root: &Path) -> Option> { + Some(Vec::new()) +} + #[cfg(test)] mod tests { use super::*; @@ -271,6 +401,67 @@ tmpfs /tmp tmpfs rw 0 0 ); } + #[test] + fn macos_mount_points_keep_spaces_and_brackets() { + let output = "\ +/dev/disk3s1s1 on / (apfs, sealed, local, read-only, journaled) +devfs on /dev (devfs, local, nobrowse) +/dev/disk3s5 on /System/Volumes/Data (apfs, local, journaled, nobrowse) +map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse) +/dev/disk5s1 on /Volumes/My Disk (2) (apfs, local, nodev, nosuid) +//tobi@nas/share on /Volumes/share on nas (smbfs, nodev, nosuid) +"; + let points: Vec = [ + "/", + "/dev", + MACOS_DATA_VOLUME, + "/System/Volumes/Data/home", + "/Volumes/My Disk (2)", + "/Volumes/share on nas", + ] + .iter() + .map(PathBuf::from) + .collect(); + assert_eq!(parse_macos_mounts(output), points); + } + + #[test] + fn only_macos_skips_the_data_volume_and_in_the_roots_spelling() { + let skipped = never_scanned(Path::new("/"), Path::new("/")); + let below_system = + never_scanned(Path::new("/System/"), Path::new("/System")); + let inside = + never_scanned(Path::new("/Users/tobi"), Path::new("/Users/tobi")); + let itself = never_scanned( + Path::new(MACOS_DATA_VOLUME), + Path::new(MACOS_DATA_VOLUME), + ); + if cfg!(target_os = "macos") { + assert_eq!( + skipped, + vec![PathBuf::from(MACOS_DATA_VOLUME), "/Network".into()] + ); + assert_eq!( + below_system, + vec![PathBuf::from("/System/Volumes/Data")] + ); + } else { + assert!(skipped.is_empty() && below_system.is_empty()); + } + assert!(inside.is_empty()); + assert!(itself.is_empty(), "asking for it by name scans it"); + } + + #[test] + #[cfg(target_os = "macos")] + fn the_home_disk_on_macos_is_the_root_and_has_a_device() { + let home = std::env::var_os("HOME").map(PathBuf::from); + let home = home.expect("HOME is set"); + assert_eq!(volume_root_for(&home), Some(PathBuf::from("/"))); + let device = device_for(Path::new("/")).expect("a device"); + assert!(device.starts_with("/dev/disk"), "{device}"); + } + #[test] fn a_real_volume_reports_plausible_numbers() { let temp = std::env::temp_dir(); diff --git a/crates/disktree-core/src/windows.rs b/crates/disktree-core/src/windows.rs new file mode 100644 index 0000000..6e2ef8c --- /dev/null +++ b/crates/disktree-core/src/windows.rs @@ -0,0 +1,752 @@ +//! What a walk on Windows needs beyond the standard library. +//! +//! `std::fs::read_dir` lists a directory with `FindNextFileW`, whose records +//! carry neither the space a file occupies nor a file id. Asking for them +//! file by file costs an open per file: on a home directory of 1.3 million +//! files that made the walk seven times slower. `GetFileInformationByHandleEx` +//! with `FileIdExtdDirectoryInfo` returns both for a whole buffer of entries, +//! for what the listing costs anyway. +//! +//! The rest is small: the volume a path is on, its free space, and comparing +//! paths the way Windows does. + +#![allow( + unsafe_code, + reason = "Win32 calls std does not wrap; each block says why it is sound" +)] + +use std::ffi::{OsStr, OsString}; +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::mem::offset_of; +use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _}; +use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _}; +use std::os::windows::io::AsRawHandle as _; +use std::path::{Component, Path, PathBuf, Prefix}; +use std::sync::Arc; + +use windows_sys::Win32::Foundation::{ + ERROR_INVALID_FUNCTION, ERROR_INVALID_LEVEL, ERROR_INVALID_PARAMETER, + ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED, +}; +use windows_sys::Win32::Storage::FileSystem::{ + FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, + FILE_ATTRIBUTE_RECALL_ON_OPEN, FILE_ATTRIBUTE_REPARSE_POINT, + FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY, + FILE_READ_ATTRIBUTES, FileIdExtdDirectoryInfo, GetDiskFreeSpaceExW, + GetFileInformationByHandleEx, GetVolumePathNameW, SYNCHRONIZE, +}; + +use crate::space::SpaceInfo; + +/// Bytes the file system fills per call: some hundreds of entries. +const BUFFER_BYTES: usize = 64 * 1024; + +/// Where a record's name starts; everything before it has a fixed size. +const NAME_AT: usize = offset_of!(FILE_ID_EXTD_DIR_INFO, FileName); + +/// Reparse tags with this bit stand for another path: symbolic links, +/// junctions and mounted folders. These are exactly what the standard +/// library calls symlinks, so this listing agrees with `std::fs::FileType`. +const NAME_SURROGATE: u32 = 0x2000_0000; + +/// A `FILETIME` counts 100 ns ticks from 1601; this many precede 1970. +/// A cloud files placeholder (`OneDrive` and the like) with nothing local: +/// opening or listing it makes the provider fetch it. `RECALL_ON_OPEN` marks +/// a directory whose entries are not local, `RECALL_ON_DATA_ACCESS` one whose +/// files are all online-only. +const EVICTED: u32 = + FILE_ATTRIBUTE_RECALL_ON_OPEN | FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS; + +const EPOCH_TICKS: i64 = 116_444_736_000_000_000; +const TICKS_PER_SECOND: i64 = 10_000_000; + +/// What an entry is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Directory, + /// A symbolic link, a junction or a mounted folder. + Link, + File, +} + +/// One directory entry, with what a measurement needs. +#[derive(Debug)] +pub struct Entry { + dir: Arc, + name: OsString, + kind: Kind, + apparent: u64, + allocated: u64, + modified: i64, + identity: Option<(u64, u64)>, + attributes: u32, +} + +impl Entry { + pub fn path(&self) -> PathBuf { + self.dir.join(&self.name) + } + + pub fn file_name(&self) -> &OsStr { + &self.name + } + + pub const fn kind(&self) -> Kind { + self.kind + } + + /// The length, in bytes. + pub const fn apparent(&self) -> u64 { + self.apparent + } + + /// Bytes the volume has allocated to the file, in whole clusters: less + /// than the length for a compressed or sparse file, and zero for one + /// whose data is kept in its file record. Where the listing could not say + /// (see [`read_dir`]), the length. + pub const fn allocated(&self) -> u64 { + self.allocated + } + + /// Last write, in Unix seconds; `0` when earlier or unknown. + pub const fn modified(&self) -> i64 { + self.modified + } + + /// Whether this is a directory the cloud files provider holds and the + /// disk does not: see [`EVICTED`]. + pub const fn evicted(&self) -> bool { + matches!(self.kind, Kind::Directory) && self.attributes & EVICTED != 0 + } + + /// `(volume serial, file id)`: the same for two names of one file. + pub const fn identity(&self) -> Option<(u64, u64)> { + self.identity + } + + fn from_std(dir: &Arc, entry: &fs::DirEntry) -> io::Result { + let meta = entry.metadata()?; + let file_type = meta.file_type(); + let kind = if file_type.is_symlink() { + Kind::Link + } else if file_type.is_dir() { + Kind::Directory + } else { + Kind::File + }; + Ok(Self { + dir: Arc::clone(dir), + name: entry.file_name(), + kind, + apparent: meta.len(), + allocated: meta.len(), + modified: unix_seconds( + i64::try_from(meta.last_write_time()).unwrap_or(0), + ), + identity: None, + attributes: meta.file_attributes(), + }) + } +} + +/// A directory being listed; like `std::fs::ReadDir`, it leaves out `.` +/// and `..`. +#[derive(Debug)] +pub struct ReadDir { + dir: Arc, + source: Source, +} + +#[derive(Debug)] +enum Source { + Records(Records), + /// A file system or network share that does not implement the listing + /// with ids: the standard one, which has lengths but not allocations. + /// Boxed, being ten times the size of the common case. + Std(Box), +} + +#[derive(Debug)] +struct Records { + handle: File, + /// Serial number of the directory's volume, which with a file id names + /// a file. `None` when it cannot be read; nothing is de-duplicated then. + volume: Option, + /// `u64`s for the eight-byte alignment the records are laid out in. + buffer: Box<[u64]>, + /// Where the next record starts, or `None` once the buffer is used up. + next: Option, + done: bool, +} + +/// List `dir`, with each entry's allocation and file id. +pub fn read_dir(dir: &Path) -> io::Result { + let handle = OpenOptions::new() + .access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE) + // Needed to open a directory at all. Without + // `FILE_FLAG_OPEN_REPARSE_POINT` a link is followed, which is what + // a walk that chose to enter one wants. + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(dir)?; + let volume = winapi_util::file::information(&handle) + .ok() + .map(|info| info.volume_serial_number()); + let mut records = Records { + handle, + volume, + buffer: vec![0; BUFFER_BYTES / 8].into_boxed_slice(), + next: None, + done: false, + }; + let dir: Arc = Arc::from(dir); + // The first fill shows whether the file system implements this listing, + // before any entry has been handed out. + let source = match records.fill() { + Ok(()) => Source::Records(records), + Err(error) if unsupported(&error) => { + Source::Std(Box::new(fs::read_dir(&dir)?)) + } + Err(error) => return Err(error), + }; + Ok(ReadDir { dir, source }) +} + +impl Iterator for ReadDir { + type Item = io::Result; + + fn next(&mut self) -> Option { + let records = match &mut self.source { + Source::Std(listing) => { + return listing.next().map(|entry| { + entry.and_then(|entry| Entry::from_std(&self.dir, &entry)) + }); + } + Source::Records(records) => records, + }; + loop { + if records.done { + return None; + } + let Some(offset) = records.next else { + if let Err(error) = records.fill() { + records.done = true; + return Some(Err(error)); + } + continue; + }; + match records.record(&self.dir, offset) { + Ok((entry, next)) => { + records.next = next; + if let Some(entry) = entry { + return Some(Ok(entry)); + } + } + Err(error) => { + records.done = true; + return Some(Err(error)); + } + } + } + } +} + +impl Records { + /// Ask the file system for the next buffer of records. + fn fill(&mut self) -> io::Result<()> { + // SAFETY: the handle is an open directory handle owned by `self`; + // the pointer and length describe `self.buffer`, which is writable + // for that many bytes and not otherwise borrowed during the call; + // and the class is the one the records are read as. + let filled = unsafe { + GetFileInformationByHandleEx( + self.handle.as_raw_handle(), + FileIdExtdDirectoryInfo, + self.buffer.as_mut_ptr().cast(), + BUFFER_BYTES as u32, + ) + }; + if filled != 0 { + self.next = Some(0); + return Ok(()); + } + let error = io::Error::last_os_error(); + if code(&error) == Some(ERROR_NO_MORE_FILES) { + self.done = true; + return Ok(()); + } + Err(error) + } + + /// The buffer as the bytes the file system wrote. + fn bytes(&self) -> &[u8] { + // SAFETY: `[u64]` can be read as `u8`s of eight times its length: + // one allocation, no alignment requirement for `u8`, and every byte + // initialized, since the buffer starts zeroed. + unsafe { + std::slice::from_raw_parts( + self.buffer.as_ptr().cast::(), + size_of_val(&*self.buffer), + ) + } + } + + /// The entry at `offset`, or `None` for `.` and `..`, and where the next + /// record starts. Every length the file system wrote is checked against + /// the buffer before it is used. + fn record( + &self, + dir: &Arc, + offset: usize, + ) -> io::Result<(Option, Option)> { + let malformed = + || io::Error::other("the file system returned a malformed record"); + let bytes = self.bytes(); + let header = + bytes.get(offset..offset + NAME_AT).ok_or_else(malformed)?; + let field = |at: usize| { + u32::from_ne_bytes(header[at..at + 4].try_into().expect("four")) + }; + let signed = |at: usize| { + i64::from_ne_bytes(header[at..at + 8].try_into().expect("eight")) + }; + let name_len = + field(offset_of!(FILE_ID_EXTD_DIR_INFO, FileNameLength)) as usize; + let name_bytes = bytes + .get(offset + NAME_AT..offset + NAME_AT + name_len) + .filter(|name| name.len() % 2 == 0) + .ok_or_else(malformed)?; + let next = + match field(offset_of!(FILE_ID_EXTD_DIR_INFO, NextEntryOffset)) { + 0 => None, + step if step as usize >= NAME_AT + name_len => { + Some(offset + step as usize) + } + _ => return Err(malformed()), + }; + + let name: Vec = name_bytes + .chunks_exact(2) + .map(|pair| u16::from_ne_bytes([pair[0], pair[1]])) + .collect(); + if name == [u16::from(b'.')] || name == [u16::from(b'.'); 2] { + return Ok((None, next)); + } + + let attributes = + field(offset_of!(FILE_ID_EXTD_DIR_INFO, FileAttributes)); + let tag = field(offset_of!(FILE_ID_EXTD_DIR_INFO, ReparsePointTag)); + let kind = if attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 + && tag & NAME_SURROGATE != 0 + { + Kind::Link + } else if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 { + Kind::Directory + } else { + Kind::File + }; + let id_at = offset_of!(FILE_ID_EXTD_DIR_INFO, FileId); + let id = u128::from_le_bytes( + header[id_at..id_at + 16].try_into().expect("sixteen"), + ); + let entry = Entry { + dir: Arc::clone(dir), + name: OsString::from_wide(&name), + kind, + apparent: bytes_from(signed(offset_of!( + FILE_ID_EXTD_DIR_INFO, + EndOfFile + ))), + allocated: bytes_from(signed(offset_of!( + FILE_ID_EXTD_DIR_INFO, + AllocationSize + ))), + modified: unix_seconds(signed(offset_of!( + FILE_ID_EXTD_DIR_INFO, + LastWriteTime + ))), + identity: self.volume.zip(file_id(id)), + attributes, + }; + Ok((Some(entry), next)) + } +} + +/// The part of a 128-bit file id that names a file by itself. +/// +/// NTFS keeps the high half zero ([MS-FSCC] 2.1.10), so the low half is the +/// id. Zero is what a file system without ids reports; FAT and exFAT do, +/// and their 64-bit ids are documented as not unique, so trusting them could +/// merge two files into one. +/// +/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/98860416-1caf-4c80-a9ab-8d61e1ccf5a5 +fn file_id(id: u128) -> Option { + // TODO(refs-hardlinks): ReFS ids use both halves, which a (u64, u64) + // key cannot hold together with the volume, so hardlinks on ReFS (Dev + // Drives) are counted once per name. That overcounts; it never drops a + // file's size. + u64::try_from(id).ok().filter(|&low| low != 0) +} + +/// `(volume serial, file index)` of what `path` names, following links: how +/// a walk that follows links notices it has been somewhere before. `None` +/// where there is no usable index; zero and all ones mean exactly that +/// ([MS-FSCC] 2.1.9). +/// +/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/2d3333fe-fc98-4a6f-98a2-4bb805aff407 +pub fn identity(path: &Path) -> Option<(u64, u64)> { + let file = OpenOptions::new() + .access_mode(FILE_READ_ATTRIBUTES) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(path) + .ok()?; + let info = winapi_util::file::information(&file).ok()?; + let index = info.file_index(); + (index != 0 && index != u64::MAX) + .then(|| (info.volume_serial_number(), index)) +} + +/// Capacity and free space of the volume holding `path`. +pub fn space_info(path: &Path) -> io::Result { + // A network share is only accepted with a trailing separator. + let directory = wide(path, true)?; + let (mut available, mut total, mut free) = (0_u64, 0_u64, 0_u64); + // SAFETY: `directory` is NUL-terminated and outlives the call, and each + // out pointer is to a live, writable `u64`. + let ok = unsafe { + GetDiskFreeSpaceExW( + directory.as_ptr(), + &raw mut available, + &raw mut total, + &raw mut free, + ) + }; + if ok == 0 { + return Err(io::Error::last_os_error()); + } + Ok(SpaceInfo { + total, + free, + available, + }) +} + +/// Where the volume holding `path` is mounted: a drive such as `C:\`, a +/// share, or a folder another volume is mounted on. +pub fn volume_root(path: &Path) -> Option { + let name = wide(path, false).ok()?; + // The answer is a prefix of the path made absolute; the path's length + // plus room for the longest drive and directory it could gain is ample. + let mut root = vec![0_u16; name.len() + 260]; + // SAFETY: `name` is NUL-terminated and outlives the call, and `root` is + // writable for the length passed. + let ok = unsafe { + GetVolumePathNameW( + name.as_ptr(), + root.as_mut_ptr(), + u32::try_from(root.len()).ok()?, + ) + }; + if ok == 0 { + return None; + } + let end = root.iter().position(|&unit| unit == 0)?; + Some(PathBuf::from(OsString::from_wide(&root[..end]))) +} + +/// Whether `path` is a folder another volume is mounted on. Removing one +/// would reach onto that volume, which nobody marked. +pub fn is_mount_point(path: &Path) -> bool { + path.parent().is_some() + && volume_root(path).is_some_and(|root| same(&root, path)) +} + +/// Whether `left` and `right` name the same place, compared the way Windows +/// compares names: see [`folded`]. +pub fn same(left: &Path, right: &Path) -> bool { + folded(left) == folded(right) +} + +/// `path` in the one spelling the removal guards compare: [`folded`], put +/// back together, so `Path::starts_with` on two keys is containment as +/// Windows sees it. +pub fn guard_key(path: &Path) -> PathBuf { + folded(path).into_iter().collect() +} + +/// Each component in the form Windows would treat as equal: without regard +/// to case, so `C:\WINDOWS\System32` is inside `C:\Windows`, and with +/// `\\?\C:\` the same place as `C:\`. +fn folded(path: &Path) -> Vec { + path.components() + .map(|component| match component { + Component::Prefix(prefix) => match prefix.kind() { + Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => { + format!("{}:", char::from(letter.to_ascii_lowercase())) + } + Prefix::UNC(server, share) + | Prefix::VerbatimUNC(server, share) => format!( + r"\\{}\{}", + server.to_string_lossy(), + share.to_string_lossy() + ) + .to_lowercase(), + Prefix::Verbatim(_) | Prefix::DeviceNS(_) => { + prefix.as_os_str().to_string_lossy().to_lowercase() + } + }, + other => other.as_os_str().to_string_lossy().to_lowercase(), + }) + .collect() +} + +/// `path` as a NUL-terminated wide string, with a trailing separator when +/// `directory` is set. +fn wide(path: &Path, directory: bool) -> io::Result> { + let mut wide: Vec = path.as_os_str().encode_wide().collect(); + if wide.contains(&0) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "a path cannot contain NUL", + )); + } + let separator = + |unit: &u16| *unit == u16::from(b'\\') || *unit == u16::from(b'/'); + if directory && !wide.last().is_some_and(separator) { + wide.push(u16::from(b'\\')); + } + wide.push(0); + Ok(wide) +} + +/// Errors a file system or redirector gives for a listing it does not +/// implement. +fn unsupported(error: &io::Error) -> bool { + matches!( + code(error), + Some( + ERROR_INVALID_FUNCTION + | ERROR_NOT_SUPPORTED + | ERROR_INVALID_PARAMETER + | ERROR_INVALID_LEVEL + ) + ) +} + +fn code(error: &io::Error) -> Option { + error + .raw_os_error() + .and_then(|code| u32::try_from(code).ok()) +} + +/// A byte count the file system reports as signed; it never is negative. +fn bytes_from(value: i64) -> u64 { + u64::try_from(value).unwrap_or(0) +} + +/// A `FILETIME` as Unix seconds, `0` before 1970. +const fn unix_seconds(ticks: i64) -> i64 { + if ticks <= EPOCH_TICKS { + 0 + } else { + (ticks - EPOCH_TICKS) / TICKS_PER_SECOND + } +} + +/// Make a directory junction for a test: unlike a symbolic link, one needs +/// no privilege to create. `false` when there is no `cmd` to make it with. +#[cfg(test)] +pub fn make_junction(link: &Path, target: &Path) -> bool { + // Rebuilt from components, because `mklink` takes no `/` in a path, and + // a test's `root.join("sub/loop")` has one. + let native = |path: &Path| path.components().collect::(); + std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(native(link)) + .arg(native(target)) + .output() + .is_ok_and(|output| output.status.success()) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::TempDir; + + fn listed(dir: &Path) -> Vec { + let mut entries: Vec = read_dir(dir) + .expect("list") + .collect::>() + .expect("entries"); + entries.sort_by(|left, right| left.name.cmp(&right.name)); + entries + } + + #[test] + fn a_listing_has_names_kinds_lengths_and_no_dot_entries() { + let temp = TempDir::new().expect("tempdir"); + fs::create_dir(temp.path().join("sub")).expect("mkdir"); + fs::write(temp.path().join("data.bin"), vec![7_u8; 100_000]) + .expect("write"); + + let entries = listed(temp.path()); + let names: Vec<&OsStr> = entries.iter().map(Entry::file_name).collect(); + assert_eq!(names, ["data.bin", "sub"]); + assert_eq!(entries[0].kind(), Kind::File); + assert_eq!(entries[0].apparent(), 100_000); + assert_eq!(entries[0].path(), temp.path().join("data.bin")); + assert_eq!(entries[1].kind(), Kind::Directory); + assert!(entries[0].modified() > 0, "written just now"); + } + + #[test] + fn the_allocation_is_whole_clusters_of_the_data() { + let temp = TempDir::new().expect("tempdir"); + // Noise, so a compressed folder cannot store it in less. + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let noise: Vec = (0..100_000) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state.to_le_bytes()[0] + }) + .collect(); + fs::write(temp.path().join("data.bin"), noise).expect("write"); + let entry = &listed(temp.path())[0]; + // Clusters are powers of two between 512 bytes and 2 MiB, so the + // allocation covers the data and is a whole number of sectors. + assert!(entry.allocated() >= 100_000, "{}", entry.allocated()); + assert!(entry.allocated() < 100_000 + 2 * 1024 * 1024); + assert_eq!(entry.allocated() % 512, 0); + } + + #[test] + fn two_names_of_one_file_share_an_identity() { + let temp = TempDir::new().expect("tempdir"); + let original = temp.path().join("original.bin"); + fs::write(&original, b"payload").expect("write"); + fs::hard_link(&original, temp.path().join("link.bin")) + .expect("hard link"); + fs::write(temp.path().join("other.bin"), b"payload").expect("write"); + + let entries = listed(temp.path()); + let id = |name: &str| { + entries + .iter() + .find(|entry| entry.file_name() == name) + .and_then(Entry::identity) + }; + assert!(id("original.bin").is_some(), "NTFS gives ids"); + assert_eq!(id("link.bin"), id("original.bin")); + assert_ne!(id("other.bin"), id("original.bin")); + assert_eq!(identity(&original), id("original.bin"), "one id scheme"); + } + + #[test] + fn a_junction_is_a_link_and_listing_it_lists_its_target() { + let temp = TempDir::new().expect("tempdir"); + let target = temp.path().join("target"); + fs::create_dir(&target).expect("mkdir"); + fs::write(target.join("inside.bin"), b"x").expect("write"); + let junction = temp.path().join("junction"); + if !make_junction(&junction, &target) { + return; // no cmd.exe to make one with + } + + let entries = listed(temp.path()); + let kind = |name: &str| { + entries + .iter() + .find(|entry| entry.file_name() == name) + .map(Entry::kind) + }; + assert_eq!(kind("junction"), Some(Kind::Link)); + assert_eq!(kind("target"), Some(Kind::Directory)); + let through: Vec = listed(&junction) + .into_iter() + .map(|entry| entry.name) + .collect(); + assert_eq!(through, ["inside.bin"], "a walk that enters one follows"); + } + + #[test] + fn a_large_directory_spans_several_buffers() { + let temp = TempDir::new().expect("tempdir"); + // Long names so the records overflow one 64 KiB buffer many times. + for index in 0..2000 { + let name = format!("{index:04}-{}", "n".repeat(120)); + fs::write(temp.path().join(name), b"").expect("write"); + } + let entries = listed(temp.path()); + assert_eq!(entries.len(), 2000); + assert!( + entries[1999] + .file_name() + .to_string_lossy() + .starts_with("1999") + ); + } + + #[test] + fn free_space_is_plausible_and_a_missing_path_is_not_found() { + let temp = TempDir::new().expect("tempdir"); + let space = space_info(temp.path()).expect("space"); + assert!(space.total > 0 && space.free <= space.total, "{space:?}"); + assert!(space.available <= space.free, "{space:?}"); + let error = space_info(&temp.path().join("absent")) + .expect_err("no such directory"); + assert_eq!(error.kind(), io::ErrorKind::NotFound); + } + + #[test] + fn a_path_is_on_its_drive_and_a_folder_is_no_mount_point() { + let temp = TempDir::new().expect("tempdir"); + let drive = temp.path().ancestors().last().expect("a drive"); + let root = volume_root(temp.path()).expect("a volume"); + assert!( + same(&root, drive), + "{} on {}", + root.display(), + drive.display() + ); + assert!(!is_mount_point(temp.path())); + assert!(!is_mount_point(drive), "a drive is a root, not a folder"); + } + + /// Containment as the removal guards judge it. + fn within(path: &Path, base: &Path) -> bool { + guard_key(path).starts_with(guard_key(base)) + } + + #[test] + fn paths_compare_without_case_or_verbatim_prefixes() { + let windows = Path::new(r"C:\Windows"); + assert!(within(Path::new(r"c:\WINDOWS\System32"), windows)); + assert!(within(Path::new(r"\\?\C:\Windows\Temp"), windows)); + assert!(!within(Path::new(r"C:\Windows.old"), windows), "components"); + assert!(!within(Path::new(r"D:\Windows"), windows)); + assert!(same( + Path::new(r"\\server\Share\Dir"), + Path::new(r"\\?\UNC\SERVER\share\dir") + )); + assert!(within( + Path::new(r"C:\Users\Олег\x"), + Path::new(r"c:\users\ОЛЕГ") + )); + } + + #[test] + fn times_convert_to_unix_seconds() { + assert_eq!(unix_seconds(0), 0, "before 1970"); + assert_eq!(unix_seconds(EPOCH_TICKS), 0); + assert_eq!(unix_seconds(EPOCH_TICKS + 90 * TICKS_PER_SECOND), 90); + } + + #[test] + fn only_whole_ids_name_a_file() { + assert_eq!(file_id(0), None, "no id at all"); + assert_eq!(file_id(0x0005_0000_0000_1234), Some(0x0005_0000_0000_1234)); + assert_eq!(file_id((1 << 64) | 7), None, "a ReFS id needs both halves"); + } +} diff --git a/packaging/macos/AppIcon.svg b/packaging/macos/AppIcon.svg new file mode 100644 index 0000000..4732a05 --- /dev/null +++ b/packaging/macos/AppIcon.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/macos/Info.plist.in b/packaging/macos/Info.plist.in new file mode 100644 index 0000000..7e87cda --- /dev/null +++ b/packaging/macos/Info.plist.in @@ -0,0 +1,48 @@ + + + + + + CFBundleIdentifier + io.github.tobi.disktree + CFBundleName + disktree + CFBundleDisplayName + disktree + CFBundleExecutable + disktree + CFBundleIconFile + AppIcon + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + CFBundleShortVersionString + @VERSION@ + CFBundleVersion + @VERSION@ + LSMinimumSystemVersion + 11.0 + LSApplicationCategoryType + public.app-category.utilities + NSHighResolutionCapable + + NSHumanReadableCopyright + MIT License + + NSDesktopFolderUsageDescription + disktree measures the Desktop folder to show what is using your disk. It reads sizes and names only. + NSDocumentsFolderUsageDescription + disktree measures the Documents folder to show what is using your disk. It reads sizes and names only. + NSDownloadsFolderUsageDescription + disktree measures the Downloads folder to show what is using your disk. It reads sizes and names only. + NSRemovableVolumesUsageDescription + disktree measures removable disks you scan to show what is using them. It reads sizes and names only. + NSNetworkVolumesUsageDescription + disktree measures network disks you scan to show what is using them. It reads sizes and names only. + + diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 6120e59..3571573 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true rust-version.workspace = true license.workspace = true publish = false -description = "Check entry points for disktree: one command per gate" +description = "Check and packaging entry points for disktree: one command per gate" [lints] workspace = true diff --git a/xtask/src/bundle.rs b/xtask/src/bundle.rs new file mode 100644 index 0000000..63e3113 --- /dev/null +++ b/xtask/src/bundle.rs @@ -0,0 +1,339 @@ +//! `cargo xtask bundle`: the macOS app, from a release build. +//! +//! Plain Apple tools and nothing to install: `sips` and `iconutil` draw the +//! icon from its SVG, `codesign` signs, `ditto` zips the way Finder does +//! (keeping the signature's extended attributes), and `notarytool` and +//! `stapler` notarize. Everything lands in `target/bundle/`. +//! +//! Signing is ad hoc unless an identity is given. An ad-hoc app runs on the +//! Mac that built it; a downloaded one needs a Developer ID signature and +//! notarization, or Gatekeeper stops it. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +const APP: &str = "disktree.app"; +const EXECUTABLE: &str = "disktree"; +/// What the binary is built for at least; `LSMinimumSystemVersion` in +/// `packaging/macos/Info.plist.in` says the same, and GPUI needs 10.15.7. +const DEPLOYMENT_TARGET: &str = "11.0"; + +/// The iconset `iconutil` expects: each point size at 1x and 2x. +const ICON_SIZES: [(&str, u32); 10] = [ + ("icon_16x16.png", 16), + ("icon_16x16@2x.png", 32), + ("icon_32x32.png", 32), + ("icon_32x32@2x.png", 64), + ("icon_128x128.png", 128), + ("icon_128x128@2x.png", 256), + ("icon_256x256.png", 256), + ("icon_256x256@2x.png", 512), + ("icon_512x512.png", 512), + ("icon_512x512@2x.png", 1024), +]; + +/// What `bundle` was asked to do. +#[derive(Debug, Default)] +struct Options { + /// A `Developer ID Application: …` identity from the keychain; ad hoc + /// when absent. + identity: Option, + notarize: bool, +} + +fn parse(args: &[String]) -> Result { + let mut options = Options::default(); + let mut args = args.iter(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--sign" => { + let identity = args + .next() + .ok_or("--sign needs an identity, e.g. \"Developer ID Application: Name (TEAMID)\"")?; + // An empty identity is what CI passes when a secret is + // missing; codesign would fail on it without saying why. + if identity.trim().is_empty() { + return Err("--sign got an empty identity".into()); + } + options.identity = Some(identity.clone()); + } + "--notarize" => options.notarize = true, + other => return Err(format!("unknown bundle option {other}")), + } + } + if options.notarize && options.identity.is_none() { + return Err("--notarize needs --sign: Apple notarizes Developer ID \ + signatures only" + .into()); + } + Ok(options) +} + +pub fn bundle(args: &[String]) -> Result<(), String> { + if !cfg!(target_os = "macos") { + return Err("the app bundle is built on macOS".into()); + } + let options = parse(args)?; + let root = workspace_root(); + let version = env!("CARGO_PKG_VERSION"); + let out = root.join("target/bundle"); + let app = out.join(APP); + + // The target directory is named rather than inherited: a + // `CARGO_TARGET_DIR` or `build.target-dir` elsewhere would put the fresh + // binary there and leave a stale one here to be bundled. + let target = root.join("target"); + let cargo = option_env!("CARGO").unwrap_or("cargo"); + tool( + Command::new(cargo) + .current_dir(&root) + .args(["build", "--release", "--locked", "-p", "disktree-app"]) + .arg("--target-dir") + .arg(&target) + .env("MACOSX_DEPLOYMENT_TARGET", DEPLOYMENT_TARGET), + )?; + + // Only ever the bundle this task made, never anything else in target/. + if app.exists() { + fs::remove_dir_all(&app) + .map_err(|err| format!("cannot clear {}: {err}", app.display()))?; + } + let contents = app.join("Contents"); + let macos = contents.join("MacOS"); + let resources = contents.join("Resources"); + for dir in [&macos, &resources] { + fs::create_dir_all(dir) + .map_err(|err| format!("cannot create {}: {err}", dir.display()))?; + } + + let binary = macos.join(EXECUTABLE); + copy(&target.join("release").join(EXECUTABLE), &binary)?; + // Local symbols only: the backtrace of a panic still names functions. + tool(Command::new("strip").arg("-x").arg(&binary))?; + + let plist = fs::read_to_string(root.join("packaging/macos/Info.plist.in")) + .map_err(|err| format!("cannot read the Info.plist template: {err}"))?; + write( + &contents.join("Info.plist"), + &plist.replace("@VERSION@", version), + )?; + tool( + Command::new("plutil") + .arg("-lint") + .arg(contents.join("Info.plist")), + )?; + + icon( + &root.join("packaging/macos/AppIcon.svg"), + &out, + &resources.join("AppIcon.icns"), + )?; + + sign(&app, options.identity.as_deref())?; + + let zip = out.join(format!( + "disktree-{version}-{}-macos.zip", + std::env::consts::ARCH + )); + archive(&app, &zip)?; + + if options.notarize { + notarize(&zip)?; + // The ticket is stapled to the app, so zip it again: a zip itself + // cannot carry one. + tool(Command::new("xcrun").args(["stapler", "staple"]).arg(&app))?; + archive(&app, &zip)?; + tool( + Command::new("spctl") + .args(["--assess", "--type", "execute", "-vv"]) + .arg(&app), + )?; + } + + println!("\n{}\n{}", app.display(), zip.display()); + Ok(()) +} + +/// `AppIcon.icns` from the SVG, through an iconset of every size. +fn icon(svg: &Path, scratch: &Path, icns: &Path) -> Result<(), String> { + let iconset = scratch.join("AppIcon.iconset"); + if iconset.exists() { + fs::remove_dir_all(&iconset).map_err(|err| { + format!("cannot clear {}: {err}", iconset.display()) + })?; + } + fs::create_dir_all(&iconset) + .map_err(|err| format!("cannot create {}: {err}", iconset.display()))?; + for (name, pixels) in ICON_SIZES { + let pixels = pixels.to_string(); + tool( + Command::new("sips") + .args(["-s", "format", "png", "-z", &pixels, &pixels]) + .arg(svg) + .arg("--out") + .arg(iconset.join(name)) + // sips names every file it writes; the errors still show. + .stdout(Stdio::null()), + )?; + } + tool( + Command::new("iconutil") + .args(["-c", "icns"]) + .arg(&iconset) + .arg("-o") + .arg(icns), + ) +} + +/// Sign the bundle, then check the signature holds. +/// +/// A real identity gets the hardened runtime and a secure timestamp, both of +/// which notarization requires. No entitlements: the app needs none of what +/// the hardened runtime withholds, and the Trash is reached through +/// `NSFileManager`, which asks for no permission. +fn sign(app: &Path, identity: Option<&str>) -> Result<(), String> { + let mut command = Command::new("codesign"); + command.arg("--force"); + match identity { + Some(identity) => { + command + .args(["--timestamp", "--options", "runtime", "--sign"]) + .arg(identity); + } + None => { + command.args(["--sign", "-"]); + } + } + tool(command.arg(app))?; + tool( + Command::new("codesign") + .args(["--verify", "--strict", "--verbose=2"]) + .arg(app), + ) +} + +fn archive(app: &Path, zip: &Path) -> Result<(), String> { + if zip.exists() { + fs::remove_file(zip).map_err(|err| { + format!("cannot replace {}: {err}", zip.display()) + })?; + } + tool( + Command::new("ditto") + .args(["-c", "-k", "--sequesterRsrc", "--keepParent"]) + .arg(app) + .arg(zip), + ) +} + +/// Submit `zip` and wait for Apple's verdict. +/// +/// Credentials come from the environment, never the command line, so they +/// stay out of shell history and CI logs: `NOTARY_PROFILE`, a keychain +/// profile saved with `xcrun notarytool store-credentials`, or an App Store +/// Connect API key as `NOTARY_KEY` (the `.p8` file), `NOTARY_KEY_ID` and +/// `NOTARY_ISSUER`. +fn notarize(zip: &Path) -> Result<(), String> { + let mut command = Command::new("xcrun"); + command + .args(["notarytool", "submit"]) + .arg(zip) + .arg("--wait"); + if let Ok(profile) = std::env::var("NOTARY_PROFILE") { + command.arg("--keychain-profile").arg(profile); + } else { + let var = |name: &str| { + std::env::var(name).map_err(|_| { + format!( + "--notarize needs NOTARY_PROFILE, or NOTARY_KEY, \ + NOTARY_KEY_ID and NOTARY_ISSUER; {name} is not set" + ) + }) + }; + command + .arg("--key") + .arg(var("NOTARY_KEY")?) + .arg("--key-id") + .arg(var("NOTARY_KEY_ID")?) + .arg("--issuer") + .arg(var("NOTARY_ISSUER")?); + } + tool(&mut command) +} + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .map_or_else(|| PathBuf::from("."), Path::to_path_buf) +} + +fn copy(from: &Path, to: &Path) -> Result<(), String> { + fs::copy(from, to).map(drop).map_err(|err| { + format!("cannot copy {} to {}: {err}", from.display(), to.display()) + }) +} + +fn write(path: &Path, contents: &str) -> Result<(), String> { + fs::write(path, contents) + .map_err(|err| format!("cannot write {}: {err}", path.display())) +} + +/// Run one tool, inheriting the terminal so its own report is seen. +fn tool(command: &mut Command) -> Result<(), String> { + let display = format!("{command:?}"); + let status = command + .stdin(Stdio::null()) + .status() + .map_err(|err| format!("could not start {display}: {err}"))?; + if status.success() { + Ok(()) + } else { + Err(format!("{display} failed")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(list: &[&str]) -> Vec { + list.iter().map(ToString::to_string).collect() + } + + #[test] + fn signing_is_ad_hoc_unless_an_identity_is_given() { + let options = parse(&[]).expect("no options"); + assert!(options.identity.is_none() && !options.notarize); + let options = parse(&args(&["--sign", "Developer ID Application: X"])) + .expect("an identity"); + assert_eq!( + options.identity.as_deref(), + Some("Developer ID Application: X") + ); + } + + #[test] + fn notarizing_needs_a_real_signature() { + let error = parse(&args(&["--notarize"])).expect_err("no identity"); + assert!(error.contains("--sign"), "{error}"); + assert!( + parse(&args(&["--sign"])).is_err(), + "an identity is required" + ); + assert!( + parse(&args(&["--sign", ""])).is_err(), + "an empty identity is not one" + ); + } + + #[test] + fn the_plist_template_names_the_executable_and_takes_the_version() { + let plist = include_str!("../../packaging/macos/Info.plist.in"); + assert!(plist.contains(&format!("{EXECUTABLE}"))); + assert!(plist.contains("@VERSION@")); + assert!( + plist.contains(&format!("{DEPLOYMENT_TARGET}")) + ); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 6f3c3c3..ce225e5 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,4 +1,4 @@ -//! Check entry points for disktree. +//! Check and packaging entry points for disktree. //! //! Each gate is reachable on its own (`cargo xtask fmt`) and through the //! aggregate CI runs (`cargo xtask lint`), mirroring how omatrack exposes every @@ -6,6 +6,8 @@ //! anything: it reports the diff and fails, so a red local run is the same //! signal CI gives. +mod bundle; + use std::process::{Command, ExitCode, Stdio}; const USAGE: &str = "\ @@ -18,6 +20,10 @@ tasks: clippy clippy --workspace --all-targets -- -D warnings test cargo test --workspace ci lint, then test + bundle macOS: target/bundle/disktree.app and its zip + --sign IDENTITY sign with a Developer ID (default: ad hoc) + --notarize notarize and staple; needs NOTARY_PROFILE, or + NOTARY_KEY, NOTARY_KEY_ID and NOTARY_ISSUER "; fn main() -> ExitCode { @@ -31,6 +37,7 @@ fn main() -> ExitCode { "clippy" => clippy(), "test" => test(), "ci" => fmt(false).and_then(|()| clippy()).and_then(|()| test()), + "bundle" => bundle::bundle(&args[1..]), "help" | "-h" | "--help" => { println!("{USAGE}"); return ExitCode::SUCCESS;