Merge pull request #17 from tobi/cross-platform

macOS and Windows support, merged PRs, and a security pass
This commit is contained in:
Tobias Lütke
2026-09-25 09:58:28 -06:00
committed by GitHub
28 changed files with 4791 additions and 265 deletions
+55
View File
@@ -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
+151 -1
View File
@@ -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
+13 -2
View File
@@ -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` |
Generated
+28
View File
@@ -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"
+36 -1
View File
@@ -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
+116 -12
View File
@@ -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=<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)$
+4
View File
@@ -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 = [
+108
View File
@@ -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),
]),
]);
}
+43
View File
@@ -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();
}
+287 -25
View File
@@ -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<usize>,
pub stashes: usize,
/// Commits ahead of the upstream; `None` when there is no upstream.
pub unpushed: Option<usize>,
@@ -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<GitState> {
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<GitState> {
})
}
/// 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<bool> = 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<String> {
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<std::process::Output> {
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 <t@t> 0 +0000\ncommitter t <t@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");
}
}
+75 -10
View File
@@ -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<Args> {
),
};
}
// 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<Args> {
!(disk && root.is_some()),
"--disk and a PATH cannot be combined"
);
let home = std::env::var_os("HOME").map(PathBuf::from);
let home = std::env::home_dir();
let root = match root {
_ if disk => home
.as_deref()
.and_then(disktree_core::space::volume_root_for)
.unwrap_or_else(|| PathBuf::from("/")),
Some(root) => root,
None => std::env::var_os("HOME")
.map(PathBuf::from)
.context("no path given and HOME is not set")?,
None => home.context("no path given and no home directory")?,
};
// Store the depth as the initial view setting rather than a scan option: it
// is a display choice the run-time `[` and `]` keys also change.
// Canonical, so a later widening recognises this tree in the wider walk.
let root = root.canonicalize().unwrap_or(root);
// Canonical, so a later widening recognises this tree in the wider walk;
// through dunce, so Windows gets `C:\Users\…` rather than the `\\?\C:\…`
// form nothing else is written in.
let root = dunce::canonicalize(&root).unwrap_or(root);
let metadata = std::fs::metadata(&root)
.with_context(|| format!("cannot read {}", root.display()))?;
anyhow::ensure!(metadata.is_dir(), "{} is not a directory", root.display());
@@ -198,3 +231,35 @@ fn parse_args() -> Result<Args> {
depth: depth.clamp(1, 6),
})
}
/// The console of the terminal disktree was started from, if any: a
/// windowed program on Windows gets none of its own.
#[cfg(windows)]
mod console {
#![allow(
unsafe_code,
reason = "two Win32 calls that take no pointers to get wrong"
)]
use windows_sys::Win32::System::Console::{
ATTACH_PARENT_PROCESS, AttachConsole, FreeConsole,
};
/// Borrow the parent's console so printed text reaches it. Does
/// nothing when started from Explorer, which has none.
pub fn attach() {
// SAFETY: takes a process id by value, and failure only means
// there was no console to attach to.
unsafe {
AttachConsole(ATTACH_PARENT_PROCESS);
}
}
/// Let go of it again, so the shell redraws its prompt.
pub fn detach() {
// SAFETY: no arguments; a process without a console is left as is.
unsafe {
FreeConsole();
}
}
}
+8 -4
View File
@@ -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");
+271 -18
View File
@@ -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<PathBuf>,
pub forward: Vec<PathBuf>,
}
/// 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<usize>,
pub selected: Option<Vec<usize>>,
pub hovered: Option<Vec<usize>>,
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<bool>,
/// 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<FocusTarget>,
/// 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<PathBuf>,
/// The device the scanned volume is mounted from.
pub device: Option<String>,
/// 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<bool>,
/// The top of the disk the scanned root lives on: what "Whole disk"
/// scans. Follows the root when a folder is opened.
pub disk_root: Option<PathBuf>,
/// The 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<usize>, 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<usize>, 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<usize>)> {
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<usize>, 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<usize>, 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)
}
}
+119 -2
View File
@@ -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<Disktree>, 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::<usize>::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::<usize>::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::<usize>::new()
);
}
+263 -40
View File
@@ -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<Div> {
)
}
/// 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<Div> {
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<Div> {
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<Div> {
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> {
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"),
("", ""),
(
+16 -1
View File
@@ -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"
+49
View File
@@ -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<bool> {
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);
}
}
}
+48 -4
View File
@@ -122,9 +122,15 @@ pub fn category_of_name(name: &str) -> Option<Category> {
| ".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<Category> {
| "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();
+3
View File
@@ -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;
File diff suppressed because it is too large Load Diff
+369 -87
View File
@@ -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<Node> {
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<FxHashSet<PathBuf>>,
/// Directories no scan enters, on any volume setting: see
/// [`crate::space::never_scanned`].
never_scanned: OnceLock<FxHashSet<PathBuf>>,
/// Directories already entered, so followed symlinks cannot loop.
visited_dirs: Mutex<FxHashSet<(u64, u64)>>,
/// 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<str> =
entry.file_name().to_string_lossy().into_owned().into();
let name = entry.display_name();
if !self.options.include_hidden && name.starts_with('.') {
return Classified::Skipped;
}
if file_type.is_symlink() {
return self.classify_symlink(&path, name);
}
if file_type.is_dir() {
// 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<str>,
) -> Classified {
if self
.never_scanned
.get()
.is_some_and(|never| never.contains(&path))
{
return Classified::Skipped;
}
// Read at most once per directory: macOS needs it for the dataless
// flag, and the device check below wherever the mount table cannot
// be read, which on macOS is everywhere.
let directory_cell = std::cell::OnceCell::new();
let directory = || directory_cell.get_or_init(|| entry.directory());
if EVICTED_IS_KNOWN
&& directory()
.as_ref()
.is_ok_and(|directory| directory.evicted)
{
return Classified::Skipped;
}
// Memoized: the subtree a narrower scan already measured is taken
// whole, before any volume rule, since it was measured under the same
// rules.
if let Some(known) = &self.known
&& known.path == path
{
let tree = (*known.tree).clone();
self.progress.files.fetch_add(tree.files, Ordering::Relaxed);
self.progress.bytes.fetch_add(tree.bytes, Ordering::Relaxed);
self.progress.dirs.fetch_add(tree.dirs, Ordering::Relaxed);
let mut tree = tree;
tree.name = name;
return Classified::Entry(tree);
}
if self.options.one_filesystem
&& let Some(foreign) = self.foreign_mounts.get()
{
// Checked by path before anything reads the directory, so an
// automount point is never triggered.
if foreign.contains(&path) {
return Classified::Skipped;
}
} else if self.options.one_filesystem {
match (directory(), self.root_device(&path)) {
(Ok(directory), Some(root_device))
if directory.device != root_device =>
{
return Classified::Skipped;
}
(Err(error), _) => {
self.progress.record_error(&path, error);
return Classified::Skipped;
}
_ => {}
}
}
self.progress.count_dir();
Classified::Subdirectory(path)
}
fn classify_symlink(&self, path: &Path, name: Box<str>) -> Classified {
if !self.options.follow_links {
// Not followed: the link occupies only its target string, which
// `du` reports as a handful of bytes or nothing at all.
return match fs::symlink_metadata(path) {
Ok(meta) => {
let size = measure(&meta, self.options.apparent_size);
self.progress.count_file(size);
let facts = Facts::of(&meta, self.options.apparent_size);
self.progress.count_file(facts.size);
Classified::Entry(leaf_node(
name,
NodeKind::Symlink,
size,
&meta,
&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<str>,
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<str>;
fn listing(&self) -> io::Result<Listing>;
/// Size, identity and age of a leaf.
fn facts(&self, apparent_size: bool) -> io::Result<Facts>;
/// What a directory is, read before the walk enters it.
fn directory(&self) -> io::Result<Directory>;
}
/// Whether [`Directory::evicted`] can ever be true here, so a platform that
/// cannot say never pays for asking.
const EVICTED_IS_KNOWN: bool = cfg!(any(target_os = "macos", windows));
/// What the walk needs to know about a directory before entering it.
struct Directory {
/// The device it is on, for staying on one volume when the mount table
/// cannot be read.
device: u64,
/// Its contents live only in the cloud (iCloud Drive or a File Provider
/// on macOS, `OneDrive` or another cloud files provider on Windows).
/// Listing it would make the provider fetch them, so a disk scan must
/// not; it holds no local blocks, so skipping it loses nothing.
evicted: bool,
}
/// What an entry is, as far as the walk is concerned.
enum Listing {
Directory,
Symlink,
Leaf(NodeKind),
}
/// What a leaf contributes.
struct Facts {
size: u64,
identity: Option<(u64, u64)>,
modified: i64,
/// The file may have another name the walk could meet: its identity is
/// worth keeping for hardlink de-duplication.
shared: bool,
}
impl Facts {
fn of(meta: &Metadata, apparent_size: bool) -> Self {
Self {
size: measure(meta, apparent_size),
identity: file_identity(meta),
modified: modified_seconds(meta),
shared: shares_inode(meta),
}
}
}
#[cfg(not(windows))]
impl Listed for DirEntry {
fn entry_path(&self) -> PathBuf {
self.path()
}
fn display_name(&self) -> Box<str> {
self.file_name().to_string_lossy().into_owned().into()
}
fn listing(&self) -> io::Result<Listing> {
let file_type = self.file_type()?;
Ok(if file_type.is_symlink() {
Listing::Symlink
} else if file_type.is_dir() {
Listing::Directory
} else if file_type.is_file() {
Listing::Leaf(NodeKind::File)
} else {
Listing::Leaf(NodeKind::Other)
})
}
fn facts(&self, apparent_size: bool) -> io::Result<Facts> {
self.metadata().map(|meta| Facts::of(&meta, apparent_size))
}
fn directory(&self) -> io::Result<Directory> {
self.metadata().map(|meta| Directory {
device: device_of(&meta),
evicted: is_dataless(&meta),
})
}
}
#[cfg(windows)]
impl Listed for crate::windows::Entry {
fn entry_path(&self) -> PathBuf {
self.path()
}
fn display_name(&self) -> Box<str> {
self.file_name().to_string_lossy().into_owned().into()
}
fn listing(&self) -> io::Result<Listing> {
Ok(match self.kind() {
crate::windows::Kind::Link => Listing::Symlink,
crate::windows::Kind::Directory => Listing::Directory,
crate::windows::Kind::File => Listing::Leaf(NodeKind::File),
})
}
fn facts(&self, apparent_size: bool) -> io::Result<Facts> {
Ok(Facts {
size: if apparent_size {
self.apparent()
} else {
self.allocated()
},
identity: self.identity(),
modified: self.modified(),
// The listing has no link count; a file id is free here, so
// every file keeps one.
shared: true,
})
}
/// The device is never consulted: see
/// [`crate::space::foreign_mounts_for`]. The same answer as
/// [`device_of`], so the two could only ever agree.
fn directory(&self) -> io::Result<Directory> {
Ok(Directory {
device: 0,
evicted: self.evicted(),
})
}
}
/// List a directory the way [`Listed`] describes.
#[cfg(not(windows))]
fn list(path: &Path) -> io::Result<fs::ReadDir> {
fs::read_dir(path)
}
#[cfg(windows)]
fn list(path: &Path) -> io::Result<crate::windows::ReadDir> {
crate::windows::read_dir(path)
}
/// What a directory entry turned out to be.
enum Classified {
/// Descend into this directory on a new task.
@@ -478,15 +670,17 @@ fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {
format!("{} is not a directory", root.display()),
));
}
let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let never = crate::space::never_scanned(root, &canonical);
let _ = 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<PendingDir>, context: &Arc<WalkContext>) {
let mut subdirs: Vec<Arc<PendingDir>> = Vec::new();
let mut leaves: Vec<Node> = Vec::new();
match fs::read_dir(&dir.path) {
match list(&dir.path) {
Ok(entries) => {
for entry in entries {
if context.cancelled() {
@@ -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<str>,
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<u64> {
}
#[cfg(not(unix))]
fn allocated_bytes(_meta: &Metadata) -> Option<u64> {
const fn allocated_bytes(_meta: &Metadata) -> Option<u64> {
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 <sys/stat.h>; 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<u8> = (0..100_000)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state.to_le_bytes()[0]
})
.collect();
fs::write(temp.path().join("data.bin"), noise).expect("write");
let tree = scan_dir(temp.path(), &ScanOptions::default());
assert!(tree.bytes >= 100_000, "{}", tree.bytes);
assert_eq!(tree.bytes % 512, 0, "{}", tree.bytes);
let apparent = scan_dir(temp.path(), &options());
assert_eq!(apparent.bytes, 100_000);
}
#[test]
fn max_depth_stops_descending_but_keeps_direct_files() {
let temp = TempDir::new().expect("tempdir");
@@ -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");
+191
View File
@@ -49,6 +49,13 @@ impl SpaceInfo {
}
/// Read the space on the volume containing `path`.
#[cfg(windows)]
pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
crate::windows::space_info(path)
}
/// Read the space on the volume containing `path`.
#[cfg(not(windows))]
pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
let stat = rustix::fs::statvfs(path)?;
// `f_frsize` is the fragment size the block counts are expressed in;
@@ -66,9 +73,17 @@ pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
})
}
/// The volume a path is on, as Windows names it: `C:\`, a share, or the
/// folder a volume is mounted on.
#[cfg(windows)]
pub fn device_for(path: &Path) -> Option<String> {
crate::windows::volume_root(path).map(|root| root.display().to_string())
}
/// The device a path's filesystem is mounted from, such as
/// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in
/// `/proc/self/mounts`. `None` where that table cannot be read.
#[cfg(not(any(target_os = "macos", windows)))]
pub fn device_for(path: &Path) -> Option<String> {
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
@@ -186,19 +201,134 @@ pub fn volume_root(mounts: &[Mount], path: &Path) -> Option<PathBuf> {
}
/// [`volume_root`] for this machine.
#[cfg(not(any(target_os = "macos", windows)))]
pub fn volume_root_for(path: &Path) -> Option<PathBuf> {
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
volume_root(&parse_mounts(&table), &path)
}
/// The top of the volume `path` lives on: its drive, such as `C:\`.
#[cfg(windows)]
pub fn volume_root_for(path: &Path) -> Option<PathBuf> {
crate::windows::volume_root(path)
}
/// [`foreign_mounts`] for this machine; `None` when the mount table cannot
/// be read, so the caller can fall back to comparing devices.
#[cfg(not(windows))]
pub fn foreign_mounts_for(root: &Path) -> Option<Vec<PathBuf>> {
let table = std::fs::read_to_string("/proc/self/mounts").ok()?;
Some(foreign_mounts(&parse_mounts(&table), root))
}
/// The mount points in what macOS's `mount` prints.
///
/// One per line: `/dev/disk3s5 on /System/Volumes/Data (apfs, local, …)`.
/// The point is
/// between the first ` on ` and the last ` (`, so a name with spaces or
/// brackets in it survives.
pub fn parse_macos_mounts(output: &str) -> Vec<PathBuf> {
output
.lines()
.filter_map(|line| {
let (_, rest) = line.split_once(" on ")?;
let (point, _) = rest.rsplit_once(" (")?;
Some(PathBuf::from(point))
})
.collect()
}
/// Where the Data volume is mounted on macOS.
///
/// Since Catalina `/` is a read-only system volume, and everything the user
/// can write — `/Users`,
/// `/Applications`, `/Library`, `/private`, … — lives on the Data volume,
/// joined into `/` by firmlinks. The two report the same device, and
/// `/Users` and `/System/Volumes/Data/Users` are the same inode.
pub const MACOS_DATA_VOLUME: &str = "/System/Volumes/Data";
/// Directories under `root` a scan must never enter, whatever the volume
/// rules say, given where `root` really is (`canonical`).
///
/// On macOS: the Data volume's second mount, which is every firmlinked
/// directory again under another name, so walking it counts the disk twice;
/// and `/Network`, an automount point that would reach for a server. The
/// paths are returned in `root`'s own spelling, because that is how the walk
/// names what it finds.
pub fn never_scanned(root: &Path, canonical: &Path) -> Vec<PathBuf> {
if !cfg!(target_os = "macos") {
return Vec::new();
}
[MACOS_DATA_VOLUME, "/Network"]
.iter()
.filter_map(|skip| Path::new(skip).strip_prefix(canonical).ok())
.filter(|below| !below.as_os_str().is_empty())
.map(|below| root.join(below))
.collect()
}
/// The top of the disk `path` lives on: its mount point, from `statfs`.
///
/// The Data volume answers `/System/Volumes/Data`, but the disk a user
/// thinks of is `/`, which shows the same files under the names Finder uses
/// and adds the system volume beside them.
#[cfg(target_os = "macos")]
pub fn volume_root_for(path: &Path) -> Option<PathBuf> {
let stat = rustix::fs::statfs(path).ok()?;
let mount = PathBuf::from(c_chars(&stat.f_mntonname));
if mount.as_os_str().is_empty() {
return None;
}
Some(if mount == Path::new(MACOS_DATA_VOLUME) {
PathBuf::from("/")
} else {
mount
})
}
/// The device a path's filesystem is mounted from, such as
/// `/dev/disk3s5`, from `statfs`.
#[cfg(target_os = "macos")]
pub fn device_for(path: &Path) -> Option<String> {
// `/` is a snapshot of the system volume (`disk3s1s1`); name the disk
// the user's files are on instead, which is what the meter measures.
let path = if path == Path::new("/") {
Path::new(MACOS_DATA_VOLUME)
} else {
path
};
let stat = rustix::fs::statfs(path).ok()?;
let device = c_chars(&stat.f_mntfromname);
(!device.is_empty()).then_some(device)
}
/// A NUL-terminated C string field as text.
#[cfg(target_os = "macos")]
fn c_chars(field: &[std::ffi::c_char]) -> String {
let bytes: Vec<u8> = field
.iter()
.take_while(|&&byte| byte != 0)
.map(|&byte| byte as u8)
.collect();
String::from_utf8_lossy(&bytes).into_owned()
}
/// Nothing to leave out by path on Windows.
///
/// There, the only way into another volume below `root` is a folder that
/// volume is mounted on, which is a reparse point the walk treats as a link
/// and does not enter unless links are followed; other drives are separate
/// trees altogether.
#[cfg(windows)]
#[allow(
clippy::unnecessary_wraps,
reason = "the Option is the Unix answer when the mount table is missing"
)]
pub const fn foreign_mounts_for(_root: &Path) -> Option<Vec<PathBuf>> {
Some(Vec::new())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -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<PathBuf> = [
"/",
"/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();
+752
View File
@@ -0,0 +1,752 @@
//! What a walk on Windows needs beyond the standard library.
//!
//! `std::fs::read_dir` lists a directory with `FindNextFileW`, whose records
//! carry neither the space a file occupies nor a file id. Asking for them
//! file by file costs an open per file: on a home directory of 1.3 million
//! files that made the walk seven times slower. `GetFileInformationByHandleEx`
//! with `FileIdExtdDirectoryInfo` returns both for a whole buffer of entries,
//! for what the listing costs anyway.
//!
//! The rest is small: the volume a path is on, its free space, and comparing
//! paths the way Windows does.
#![allow(
unsafe_code,
reason = "Win32 calls std does not wrap; each block says why it is sound"
)]
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::mem::offset_of;
use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _};
use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _};
use std::os::windows::io::AsRawHandle as _;
use std::path::{Component, Path, PathBuf, Prefix};
use std::sync::Arc;
use windows_sys::Win32::Foundation::{
ERROR_INVALID_FUNCTION, ERROR_INVALID_LEVEL, ERROR_INVALID_PARAMETER,
ERROR_NO_MORE_FILES, ERROR_NOT_SUPPORTED,
};
use windows_sys::Win32::Storage::FileSystem::{
FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS,
FILE_ATTRIBUTE_RECALL_ON_OPEN, FILE_ATTRIBUTE_REPARSE_POINT,
FILE_FLAG_BACKUP_SEMANTICS, FILE_ID_EXTD_DIR_INFO, FILE_LIST_DIRECTORY,
FILE_READ_ATTRIBUTES, FileIdExtdDirectoryInfo, GetDiskFreeSpaceExW,
GetFileInformationByHandleEx, GetVolumePathNameW, SYNCHRONIZE,
};
use crate::space::SpaceInfo;
/// Bytes the file system fills per call: some hundreds of entries.
const BUFFER_BYTES: usize = 64 * 1024;
/// Where a record's name starts; everything before it has a fixed size.
const NAME_AT: usize = offset_of!(FILE_ID_EXTD_DIR_INFO, FileName);
/// Reparse tags with this bit stand for another path: symbolic links,
/// junctions and mounted folders. These are exactly what the standard
/// library calls symlinks, so this listing agrees with `std::fs::FileType`.
const NAME_SURROGATE: u32 = 0x2000_0000;
/// A `FILETIME` counts 100 ns ticks from 1601; this many precede 1970.
/// A cloud files placeholder (`OneDrive` and the like) with nothing local:
/// opening or listing it makes the provider fetch it. `RECALL_ON_OPEN` marks
/// a directory whose entries are not local, `RECALL_ON_DATA_ACCESS` one whose
/// files are all online-only.
const EVICTED: u32 =
FILE_ATTRIBUTE_RECALL_ON_OPEN | FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS;
const EPOCH_TICKS: i64 = 116_444_736_000_000_000;
const TICKS_PER_SECOND: i64 = 10_000_000;
/// What an entry is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Directory,
/// A symbolic link, a junction or a mounted folder.
Link,
File,
}
/// One directory entry, with what a measurement needs.
#[derive(Debug)]
pub struct Entry {
dir: Arc<Path>,
name: OsString,
kind: Kind,
apparent: u64,
allocated: u64,
modified: i64,
identity: Option<(u64, u64)>,
attributes: u32,
}
impl Entry {
pub fn path(&self) -> PathBuf {
self.dir.join(&self.name)
}
pub fn file_name(&self) -> &OsStr {
&self.name
}
pub const fn kind(&self) -> Kind {
self.kind
}
/// The length, in bytes.
pub const fn apparent(&self) -> u64 {
self.apparent
}
/// Bytes the volume has allocated to the file, in whole clusters: less
/// than the length for a compressed or sparse file, and zero for one
/// whose data is kept in its file record. Where the listing could not say
/// (see [`read_dir`]), the length.
pub const fn allocated(&self) -> u64 {
self.allocated
}
/// Last write, in Unix seconds; `0` when earlier or unknown.
pub const fn modified(&self) -> i64 {
self.modified
}
/// Whether this is a directory the cloud files provider holds and the
/// disk does not: see [`EVICTED`].
pub const fn evicted(&self) -> bool {
matches!(self.kind, Kind::Directory) && self.attributes & EVICTED != 0
}
/// `(volume serial, file id)`: the same for two names of one file.
pub const fn identity(&self) -> Option<(u64, u64)> {
self.identity
}
fn from_std(dir: &Arc<Path>, entry: &fs::DirEntry) -> io::Result<Self> {
let meta = entry.metadata()?;
let file_type = meta.file_type();
let kind = if file_type.is_symlink() {
Kind::Link
} else if file_type.is_dir() {
Kind::Directory
} else {
Kind::File
};
Ok(Self {
dir: Arc::clone(dir),
name: entry.file_name(),
kind,
apparent: meta.len(),
allocated: meta.len(),
modified: unix_seconds(
i64::try_from(meta.last_write_time()).unwrap_or(0),
),
identity: None,
attributes: meta.file_attributes(),
})
}
}
/// A directory being listed; like `std::fs::ReadDir`, it leaves out `.`
/// and `..`.
#[derive(Debug)]
pub struct ReadDir {
dir: Arc<Path>,
source: Source,
}
#[derive(Debug)]
enum Source {
Records(Records),
/// A file system or network share that does not implement the listing
/// with ids: the standard one, which has lengths but not allocations.
/// Boxed, being ten times the size of the common case.
Std(Box<fs::ReadDir>),
}
#[derive(Debug)]
struct Records {
handle: File,
/// Serial number of the directory's volume, which with a file id names
/// a file. `None` when it cannot be read; nothing is de-duplicated then.
volume: Option<u64>,
/// `u64`s for the eight-byte alignment the records are laid out in.
buffer: Box<[u64]>,
/// Where the next record starts, or `None` once the buffer is used up.
next: Option<usize>,
done: bool,
}
/// List `dir`, with each entry's allocation and file id.
pub fn read_dir(dir: &Path) -> io::Result<ReadDir> {
let handle = OpenOptions::new()
.access_mode(FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | SYNCHRONIZE)
// Needed to open a directory at all. Without
// `FILE_FLAG_OPEN_REPARSE_POINT` a link is followed, which is what
// a walk that chose to enter one wants.
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(dir)?;
let volume = winapi_util::file::information(&handle)
.ok()
.map(|info| info.volume_serial_number());
let mut records = Records {
handle,
volume,
buffer: vec![0; BUFFER_BYTES / 8].into_boxed_slice(),
next: None,
done: false,
};
let dir: Arc<Path> = Arc::from(dir);
// The first fill shows whether the file system implements this listing,
// before any entry has been handed out.
let source = match records.fill() {
Ok(()) => Source::Records(records),
Err(error) if unsupported(&error) => {
Source::Std(Box::new(fs::read_dir(&dir)?))
}
Err(error) => return Err(error),
};
Ok(ReadDir { dir, source })
}
impl Iterator for ReadDir {
type Item = io::Result<Entry>;
fn next(&mut self) -> Option<Self::Item> {
let records = match &mut self.source {
Source::Std(listing) => {
return listing.next().map(|entry| {
entry.and_then(|entry| Entry::from_std(&self.dir, &entry))
});
}
Source::Records(records) => records,
};
loop {
if records.done {
return None;
}
let Some(offset) = records.next else {
if let Err(error) = records.fill() {
records.done = true;
return Some(Err(error));
}
continue;
};
match records.record(&self.dir, offset) {
Ok((entry, next)) => {
records.next = next;
if let Some(entry) = entry {
return Some(Ok(entry));
}
}
Err(error) => {
records.done = true;
return Some(Err(error));
}
}
}
}
}
impl Records {
/// Ask the file system for the next buffer of records.
fn fill(&mut self) -> io::Result<()> {
// SAFETY: the handle is an open directory handle owned by `self`;
// the pointer and length describe `self.buffer`, which is writable
// for that many bytes and not otherwise borrowed during the call;
// and the class is the one the records are read as.
let filled = unsafe {
GetFileInformationByHandleEx(
self.handle.as_raw_handle(),
FileIdExtdDirectoryInfo,
self.buffer.as_mut_ptr().cast(),
BUFFER_BYTES as u32,
)
};
if filled != 0 {
self.next = Some(0);
return Ok(());
}
let error = io::Error::last_os_error();
if code(&error) == Some(ERROR_NO_MORE_FILES) {
self.done = true;
return Ok(());
}
Err(error)
}
/// The buffer as the bytes the file system wrote.
fn bytes(&self) -> &[u8] {
// SAFETY: `[u64]` can be read as `u8`s of eight times its length:
// one allocation, no alignment requirement for `u8`, and every byte
// initialized, since the buffer starts zeroed.
unsafe {
std::slice::from_raw_parts(
self.buffer.as_ptr().cast::<u8>(),
size_of_val(&*self.buffer),
)
}
}
/// The entry at `offset`, or `None` for `.` and `..`, and where the next
/// record starts. Every length the file system wrote is checked against
/// the buffer before it is used.
fn record(
&self,
dir: &Arc<Path>,
offset: usize,
) -> io::Result<(Option<Entry>, Option<usize>)> {
let malformed =
|| io::Error::other("the file system returned a malformed record");
let bytes = self.bytes();
let header =
bytes.get(offset..offset + NAME_AT).ok_or_else(malformed)?;
let field = |at: usize| {
u32::from_ne_bytes(header[at..at + 4].try_into().expect("four"))
};
let signed = |at: usize| {
i64::from_ne_bytes(header[at..at + 8].try_into().expect("eight"))
};
let name_len =
field(offset_of!(FILE_ID_EXTD_DIR_INFO, FileNameLength)) as usize;
let name_bytes = bytes
.get(offset + NAME_AT..offset + NAME_AT + name_len)
.filter(|name| name.len() % 2 == 0)
.ok_or_else(malformed)?;
let next =
match field(offset_of!(FILE_ID_EXTD_DIR_INFO, NextEntryOffset)) {
0 => None,
step if step as usize >= NAME_AT + name_len => {
Some(offset + step as usize)
}
_ => return Err(malformed()),
};
let name: Vec<u16> = name_bytes
.chunks_exact(2)
.map(|pair| u16::from_ne_bytes([pair[0], pair[1]]))
.collect();
if name == [u16::from(b'.')] || name == [u16::from(b'.'); 2] {
return Ok((None, next));
}
let attributes =
field(offset_of!(FILE_ID_EXTD_DIR_INFO, FileAttributes));
let tag = field(offset_of!(FILE_ID_EXTD_DIR_INFO, ReparsePointTag));
let kind = if attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0
&& tag & NAME_SURROGATE != 0
{
Kind::Link
} else if attributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
Kind::Directory
} else {
Kind::File
};
let id_at = offset_of!(FILE_ID_EXTD_DIR_INFO, FileId);
let id = u128::from_le_bytes(
header[id_at..id_at + 16].try_into().expect("sixteen"),
);
let entry = Entry {
dir: Arc::clone(dir),
name: OsString::from_wide(&name),
kind,
apparent: bytes_from(signed(offset_of!(
FILE_ID_EXTD_DIR_INFO,
EndOfFile
))),
allocated: bytes_from(signed(offset_of!(
FILE_ID_EXTD_DIR_INFO,
AllocationSize
))),
modified: unix_seconds(signed(offset_of!(
FILE_ID_EXTD_DIR_INFO,
LastWriteTime
))),
identity: self.volume.zip(file_id(id)),
attributes,
};
Ok((Some(entry), next))
}
}
/// The part of a 128-bit file id that names a file by itself.
///
/// NTFS keeps the high half zero ([MS-FSCC] 2.1.10), so the low half is the
/// id. Zero is what a file system without ids reports; FAT and exFAT do,
/// and their 64-bit ids are documented as not unique, so trusting them could
/// merge two files into one.
///
/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/98860416-1caf-4c80-a9ab-8d61e1ccf5a5
fn file_id(id: u128) -> Option<u64> {
// TODO(refs-hardlinks): ReFS ids use both halves, which a (u64, u64)
// key cannot hold together with the volume, so hardlinks on ReFS (Dev
// Drives) are counted once per name. That overcounts; it never drops a
// file's size.
u64::try_from(id).ok().filter(|&low| low != 0)
}
/// `(volume serial, file index)` of what `path` names, following links: how
/// a walk that follows links notices it has been somewhere before. `None`
/// where there is no usable index; zero and all ones mean exactly that
/// ([MS-FSCC] 2.1.9).
///
/// [MS-FSCC]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/2d3333fe-fc98-4a6f-98a2-4bb805aff407
pub fn identity(path: &Path) -> Option<(u64, u64)> {
let file = OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)
.ok()?;
let info = winapi_util::file::information(&file).ok()?;
let index = info.file_index();
(index != 0 && index != u64::MAX)
.then(|| (info.volume_serial_number(), index))
}
/// Capacity and free space of the volume holding `path`.
pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
// A network share is only accepted with a trailing separator.
let directory = wide(path, true)?;
let (mut available, mut total, mut free) = (0_u64, 0_u64, 0_u64);
// SAFETY: `directory` is NUL-terminated and outlives the call, and each
// out pointer is to a live, writable `u64`.
let ok = unsafe {
GetDiskFreeSpaceExW(
directory.as_ptr(),
&raw mut available,
&raw mut total,
&raw mut free,
)
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
Ok(SpaceInfo {
total,
free,
available,
})
}
/// Where the volume holding `path` is mounted: a drive such as `C:\`, a
/// share, or a folder another volume is mounted on.
pub fn volume_root(path: &Path) -> Option<PathBuf> {
let name = wide(path, false).ok()?;
// The answer is a prefix of the path made absolute; the path's length
// plus room for the longest drive and directory it could gain is ample.
let mut root = vec![0_u16; name.len() + 260];
// SAFETY: `name` is NUL-terminated and outlives the call, and `root` is
// writable for the length passed.
let ok = unsafe {
GetVolumePathNameW(
name.as_ptr(),
root.as_mut_ptr(),
u32::try_from(root.len()).ok()?,
)
};
if ok == 0 {
return None;
}
let end = root.iter().position(|&unit| unit == 0)?;
Some(PathBuf::from(OsString::from_wide(&root[..end])))
}
/// Whether `path` is a folder another volume is mounted on. Removing one
/// would reach onto that volume, which nobody marked.
pub fn is_mount_point(path: &Path) -> bool {
path.parent().is_some()
&& volume_root(path).is_some_and(|root| same(&root, path))
}
/// Whether `left` and `right` name the same place, compared the way Windows
/// compares names: see [`folded`].
pub fn same(left: &Path, right: &Path) -> bool {
folded(left) == folded(right)
}
/// `path` in the one spelling the removal guards compare: [`folded`], put
/// back together, so `Path::starts_with` on two keys is containment as
/// Windows sees it.
pub fn guard_key(path: &Path) -> PathBuf {
folded(path).into_iter().collect()
}
/// Each component in the form Windows would treat as equal: without regard
/// to case, so `C:\WINDOWS\System32` is inside `C:\Windows`, and with
/// `\\?\C:\` the same place as `C:\`.
fn folded(path: &Path) -> Vec<String> {
path.components()
.map(|component| match component {
Component::Prefix(prefix) => match prefix.kind() {
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => {
format!("{}:", char::from(letter.to_ascii_lowercase()))
}
Prefix::UNC(server, share)
| Prefix::VerbatimUNC(server, share) => format!(
r"\\{}\{}",
server.to_string_lossy(),
share.to_string_lossy()
)
.to_lowercase(),
Prefix::Verbatim(_) | Prefix::DeviceNS(_) => {
prefix.as_os_str().to_string_lossy().to_lowercase()
}
},
other => other.as_os_str().to_string_lossy().to_lowercase(),
})
.collect()
}
/// `path` as a NUL-terminated wide string, with a trailing separator when
/// `directory` is set.
fn wide(path: &Path, directory: bool) -> io::Result<Vec<u16>> {
let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
if wide.contains(&0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"a path cannot contain NUL",
));
}
let separator =
|unit: &u16| *unit == u16::from(b'\\') || *unit == u16::from(b'/');
if directory && !wide.last().is_some_and(separator) {
wide.push(u16::from(b'\\'));
}
wide.push(0);
Ok(wide)
}
/// Errors a file system or redirector gives for a listing it does not
/// implement.
fn unsupported(error: &io::Error) -> bool {
matches!(
code(error),
Some(
ERROR_INVALID_FUNCTION
| ERROR_NOT_SUPPORTED
| ERROR_INVALID_PARAMETER
| ERROR_INVALID_LEVEL
)
)
}
fn code(error: &io::Error) -> Option<u32> {
error
.raw_os_error()
.and_then(|code| u32::try_from(code).ok())
}
/// A byte count the file system reports as signed; it never is negative.
fn bytes_from(value: i64) -> u64 {
u64::try_from(value).unwrap_or(0)
}
/// A `FILETIME` as Unix seconds, `0` before 1970.
const fn unix_seconds(ticks: i64) -> i64 {
if ticks <= EPOCH_TICKS {
0
} else {
(ticks - EPOCH_TICKS) / TICKS_PER_SECOND
}
}
/// Make a directory junction for a test: unlike a symbolic link, one needs
/// no privilege to create. `false` when there is no `cmd` to make it with.
#[cfg(test)]
pub fn make_junction(link: &Path, target: &Path) -> bool {
// Rebuilt from components, because `mklink` takes no `/` in a path, and
// a test's `root.join("sub/loop")` has one.
let native = |path: &Path| path.components().collect::<PathBuf>();
std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(native(link))
.arg(native(target))
.output()
.is_ok_and(|output| output.status.success())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn listed(dir: &Path) -> Vec<Entry> {
let mut entries: Vec<Entry> = read_dir(dir)
.expect("list")
.collect::<io::Result<_>>()
.expect("entries");
entries.sort_by(|left, right| left.name.cmp(&right.name));
entries
}
#[test]
fn a_listing_has_names_kinds_lengths_and_no_dot_entries() {
let temp = TempDir::new().expect("tempdir");
fs::create_dir(temp.path().join("sub")).expect("mkdir");
fs::write(temp.path().join("data.bin"), vec![7_u8; 100_000])
.expect("write");
let entries = listed(temp.path());
let names: Vec<&OsStr> = entries.iter().map(Entry::file_name).collect();
assert_eq!(names, ["data.bin", "sub"]);
assert_eq!(entries[0].kind(), Kind::File);
assert_eq!(entries[0].apparent(), 100_000);
assert_eq!(entries[0].path(), temp.path().join("data.bin"));
assert_eq!(entries[1].kind(), Kind::Directory);
assert!(entries[0].modified() > 0, "written just now");
}
#[test]
fn the_allocation_is_whole_clusters_of_the_data() {
let temp = TempDir::new().expect("tempdir");
// Noise, so a compressed folder cannot store it in less.
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
let noise: Vec<u8> = (0..100_000)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state.to_le_bytes()[0]
})
.collect();
fs::write(temp.path().join("data.bin"), noise).expect("write");
let entry = &listed(temp.path())[0];
// Clusters are powers of two between 512 bytes and 2 MiB, so the
// allocation covers the data and is a whole number of sectors.
assert!(entry.allocated() >= 100_000, "{}", entry.allocated());
assert!(entry.allocated() < 100_000 + 2 * 1024 * 1024);
assert_eq!(entry.allocated() % 512, 0);
}
#[test]
fn two_names_of_one_file_share_an_identity() {
let temp = TempDir::new().expect("tempdir");
let original = temp.path().join("original.bin");
fs::write(&original, b"payload").expect("write");
fs::hard_link(&original, temp.path().join("link.bin"))
.expect("hard link");
fs::write(temp.path().join("other.bin"), b"payload").expect("write");
let entries = listed(temp.path());
let id = |name: &str| {
entries
.iter()
.find(|entry| entry.file_name() == name)
.and_then(Entry::identity)
};
assert!(id("original.bin").is_some(), "NTFS gives ids");
assert_eq!(id("link.bin"), id("original.bin"));
assert_ne!(id("other.bin"), id("original.bin"));
assert_eq!(identity(&original), id("original.bin"), "one id scheme");
}
#[test]
fn a_junction_is_a_link_and_listing_it_lists_its_target() {
let temp = TempDir::new().expect("tempdir");
let target = temp.path().join("target");
fs::create_dir(&target).expect("mkdir");
fs::write(target.join("inside.bin"), b"x").expect("write");
let junction = temp.path().join("junction");
if !make_junction(&junction, &target) {
return; // no cmd.exe to make one with
}
let entries = listed(temp.path());
let kind = |name: &str| {
entries
.iter()
.find(|entry| entry.file_name() == name)
.map(Entry::kind)
};
assert_eq!(kind("junction"), Some(Kind::Link));
assert_eq!(kind("target"), Some(Kind::Directory));
let through: Vec<OsString> = listed(&junction)
.into_iter()
.map(|entry| entry.name)
.collect();
assert_eq!(through, ["inside.bin"], "a walk that enters one follows");
}
#[test]
fn a_large_directory_spans_several_buffers() {
let temp = TempDir::new().expect("tempdir");
// Long names so the records overflow one 64 KiB buffer many times.
for index in 0..2000 {
let name = format!("{index:04}-{}", "n".repeat(120));
fs::write(temp.path().join(name), b"").expect("write");
}
let entries = listed(temp.path());
assert_eq!(entries.len(), 2000);
assert!(
entries[1999]
.file_name()
.to_string_lossy()
.starts_with("1999")
);
}
#[test]
fn free_space_is_plausible_and_a_missing_path_is_not_found() {
let temp = TempDir::new().expect("tempdir");
let space = space_info(temp.path()).expect("space");
assert!(space.total > 0 && space.free <= space.total, "{space:?}");
assert!(space.available <= space.free, "{space:?}");
let error = space_info(&temp.path().join("absent"))
.expect_err("no such directory");
assert_eq!(error.kind(), io::ErrorKind::NotFound);
}
#[test]
fn a_path_is_on_its_drive_and_a_folder_is_no_mount_point() {
let temp = TempDir::new().expect("tempdir");
let drive = temp.path().ancestors().last().expect("a drive");
let root = volume_root(temp.path()).expect("a volume");
assert!(
same(&root, drive),
"{} on {}",
root.display(),
drive.display()
);
assert!(!is_mount_point(temp.path()));
assert!(!is_mount_point(drive), "a drive is a root, not a folder");
}
/// Containment as the removal guards judge it.
fn within(path: &Path, base: &Path) -> bool {
guard_key(path).starts_with(guard_key(base))
}
#[test]
fn paths_compare_without_case_or_verbatim_prefixes() {
let windows = Path::new(r"C:\Windows");
assert!(within(Path::new(r"c:\WINDOWS\System32"), windows));
assert!(within(Path::new(r"\\?\C:\Windows\Temp"), windows));
assert!(!within(Path::new(r"C:\Windows.old"), windows), "components");
assert!(!within(Path::new(r"D:\Windows"), windows));
assert!(same(
Path::new(r"\\server\Share\Dir"),
Path::new(r"\\?\UNC\SERVER\share\dir")
));
assert!(within(
Path::new(r"C:\Users\Олег\x"),
Path::new(r"c:\users\ОЛЕГ")
));
}
#[test]
fn times_convert_to_unix_seconds() {
assert_eq!(unix_seconds(0), 0, "before 1970");
assert_eq!(unix_seconds(EPOCH_TICKS), 0);
assert_eq!(unix_seconds(EPOCH_TICKS + 90 * TICKS_PER_SECOND), 90);
}
#[test]
fn only_whole_ids_name_a_file() {
assert_eq!(file_id(0), None, "no id at all");
assert_eq!(file_id(0x0005_0000_0000_1234), Some(0x0005_0000_0000_1234));
assert_eq!(file_id((1 << 64) | 7), None, "a ReFS id needs both halves");
}
}
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- disktree's mark (assets/disktree.svg) on the macOS icon grid: an 824 pt
rounded square centred on a 1024 pt canvas, the rest transparent. A
full-bleed square would be shrunk into a grey tile on macOS 26. -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
<defs>
<clipPath id="tile">
<rect x="100" y="100" width="824" height="824" rx="185" ry="185"/>
</clipPath>
</defs>
<g clip-path="url(#tile)">
<!-- 64 units of the mark become 824 pt. -->
<g transform="translate(100 100) scale(12.875)">
<rect width="64" height="64" fill="#1a1b26"/>
<rect x="5" y="5" width="54" height="54" fill="#3a4152"/>
<rect x="5" y="5" width="54" height="9" fill="#7aa2f7"/>
<rect x="8" y="17" width="30" height="39" fill="#2a653b"/>
<rect x="8" y="17" width="30" height="7" fill="#9ece6a"/>
<rect x="41" y="17" width="15" height="24" fill="#362f5e"/>
<rect x="41" y="17" width="15" height="6" fill="#bb9af7"/>
<rect x="41" y="44" width="15" height="12" fill="#e0af68"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- Rendered by `cargo xtask bundle`, which fills in @VERSION@.
The bundle identifier is what macOS keys Full Disk Access and folder
permissions to: changing it makes every user grant them again. -->
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>io.github.tobi.disktree</string>
<key>CFBundleName</key>
<string>disktree</string>
<key>CFBundleDisplayName</key>
<string>disktree</string>
<key>CFBundleExecutable</key>
<string>disktree</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleShortVersionString</key>
<string>@VERSION@</string>
<key>CFBundleVersion</key>
<string>@VERSION@</string>
<key>LSMinimumSystemVersion</key>
<string>11.0</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.utilities</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>MIT License</string>
<!-- Shown in the prompts macOS raises the first time a scan reaches
each of these. Full Disk Access has no prompt and no string: it is
granted in System Settings, which the app links to. -->
<key>NSDesktopFolderUsageDescription</key>
<string>disktree measures the Desktop folder to show what is using your disk. It reads sizes and names only.</string>
<key>NSDocumentsFolderUsageDescription</key>
<string>disktree measures the Documents folder to show what is using your disk. It reads sizes and names only.</string>
<key>NSDownloadsFolderUsageDescription</key>
<string>disktree measures the Downloads folder to show what is using your disk. It reads sizes and names only.</string>
<key>NSRemovableVolumesUsageDescription</key>
<string>disktree measures removable disks you scan to show what is using them. It reads sizes and names only.</string>
<key>NSNetworkVolumesUsageDescription</key>
<string>disktree measures network disks you scan to show what is using them. It reads sizes and names only.</string>
</dict>
</plist>
+1 -1
View File
@@ -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
+339
View File
@@ -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<String>,
notarize: bool,
}
fn parse(args: &[String]) -> Result<Options, String> {
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<String> {
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!("<string>{EXECUTABLE}</string>")));
assert!(plist.contains("@VERSION@"));
assert!(
plist.contains(&format!("<string>{DEPLOYMENT_TARGET}</string>"))
);
}
}
+8 -1
View File
@@ -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;