mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
Merge remote-tracking branch 'pr/13' into cross-platform
# Conflicts: # README.md # crates/disktree-app/src/git.rs # crates/disktree-core/src/removal.rs
This commit is contained in:
@@ -43,3 +43,30 @@ 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
|
||||
|
||||
@@ -86,3 +86,92 @@ 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
|
||||
run: |
|
||||
tag="${{ inputs.tag || github.ref_name }}"
|
||||
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
|
||||
|
||||
@@ -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,6 +31,11 @@ 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.
|
||||
|
||||
|
||||
Generated
+24
@@ -1439,6 +1439,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"rustix",
|
||||
"tempfile",
|
||||
"trash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7071,6 +7072,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 +7246,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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -43,6 +43,49 @@ 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
|
||||
```
|
||||
|
||||
## Use
|
||||
|
||||
```sh
|
||||
@@ -99,9 +142,7 @@ 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 `>`, beside the
|
||||
Size / Files / Age switch, go back and forward through the directories visited,
|
||||
as do `alt ←` `alt →` and the mouse's side buttons. `+` and `-` magnify without
|
||||
depth, and Backspace or Escape goes up one level. `+` and `-` magnify without
|
||||
going in; `0` resets.
|
||||
|
||||
### Removing
|
||||
@@ -109,9 +150,11 @@ going in; `0` resets.
|
||||
`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.
|
||||
|
||||
@@ -123,17 +166,16 @@ 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 |
|
||||
@@ -142,9 +184,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.
|
||||
|
||||
@@ -167,7 +214,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
|
||||
@@ -196,18 +245,25 @@ tested:
|
||||
- the filesystem root, the scanned root and your home directory are refused;
|
||||
- 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 device boundary rather than descending into one;
|
||||
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. The window
|
||||
class is `disktree`.
|
||||
It is designed for a roomy window; float it, or give it a rule:
|
||||
|
||||
```
|
||||
windowrule = float, class:^(disktree)$
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
//! 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,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// 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` and `ShowInFinder` 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),
|
||||
]);
|
||||
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),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
+154
-20
@@ -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,11 +58,19 @@ 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 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())
|
||||
};
|
||||
let stashes =
|
||||
run(path, &["stash", "list"]).map_or(0, |list| list.lines().count());
|
||||
let unpushed = run(path, &["rev-list", "--count", "@{upstream}..HEAD"])
|
||||
@@ -72,14 +82,82 @@ 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")
|
||||
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.
|
||||
// command-line `-c` outranks the repository's config. (From
|
||||
// tobi/disktree#10.)
|
||||
.args([
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
@@ -95,11 +173,7 @@ fn run(path: &Path, args: &[&str]) -> Option<String> {
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
output
|
||||
.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
.ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -109,21 +183,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]
|
||||
@@ -143,7 +227,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -170,7 +254,7 @@ mod tests {
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
};
|
||||
if !git(&["init", "-q"]) {
|
||||
if !git_installed() || !git(&["init", "-q"]) {
|
||||
return; // no git on this machine
|
||||
}
|
||||
let hook = hook.to_string_lossy();
|
||||
@@ -178,4 +262,54 @@ mod tests {
|
||||
assert!(state(dir.path()).is_some());
|
||||
assert!(!marker.exists(), "the checkout's fsmonitor ran");
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
//! live free-space meter. Marking is non-destructive until the review screen
|
||||
//! is confirmed.
|
||||
|
||||
mod app_menu;
|
||||
mod appearance;
|
||||
mod git;
|
||||
mod marks;
|
||||
mod palette;
|
||||
@@ -65,6 +67,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::var_os("HOME").map(PathBuf::from);
|
||||
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,9 +90,7 @@ fn main() -> Result<()> {
|
||||
"disktree · {}",
|
||||
marks::display_path(
|
||||
&title_root,
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.as_deref(),
|
||||
home.as_deref(),
|
||||
)
|
||||
)
|
||||
.into(),
|
||||
@@ -102,7 +108,10 @@ fn main() -> Result<()> {
|
||||
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(),
|
||||
@@ -165,6 +174,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}");
|
||||
}
|
||||
|
||||
@@ -368,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.
|
||||
@@ -411,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,
|
||||
@@ -473,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,
|
||||
@@ -498,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,
|
||||
@@ -506,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
|
||||
@@ -543,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);
|
||||
@@ -2091,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
|
||||
@@ -2121,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;
|
||||
}
|
||||
@@ -2296,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();
|
||||
@@ -2618,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -56,23 +56,32 @@ 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);
|
||||
},
|
||||
))
|
||||
.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()
|
||||
@@ -978,6 +987,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))
|
||||
}
|
||||
|
||||
@@ -1502,6 +1512,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,
|
||||
@@ -2852,13 +2916,27 @@ fn node_card(
|
||||
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); 25] = [
|
||||
("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"),
|
||||
(
|
||||
@@ -2874,7 +2952,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",
|
||||
@@ -2886,6 +2964,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"),
|
||||
("", ""),
|
||||
(
|
||||
|
||||
@@ -17,3 +17,9 @@ rustc-hash = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
# 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 }
|
||||
|
||||
@@ -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::var_os("HOME").expect("HOME is set");
|
||||
assert_eq!(full_disk_access(Path::new(&home)), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
//! * [`RemovalMode::Permanent`] — `rm -rf --one-file-system` semantics,
|
||||
//! implemented here rather than by shelling out, so no path ever reaches a
|
||||
//! shell and no filename can be misread as an option.
|
||||
//! * [`RemovalMode::Trash`] — move to the desktop trash, using `trash-put`,
|
||||
//! then `gio trash`, then a built-in XDG implementation. The backend is
|
||||
//! detected once and named in the UI so the user knows what actually happens.
|
||||
//! * [`RemovalMode::Trash`] — move to the desktop trash. On macOS that is
|
||||
//! always the system Trash, through `NSFileManager`. Elsewhere it is
|
||||
//! `trash-put`, then `gio trash`, then a built-in XDG implementation. The
|
||||
//! backend is detected once and named in the UI so the user knows what
|
||||
//! actually happens.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
@@ -92,17 +94,19 @@ impl Plan {
|
||||
/// looking at is the only thing they consented to act on.
|
||||
pub fn plan(targets: &[Target], root: &Path) -> Plan {
|
||||
let root = normalize(root);
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let mut plan = Plan::default();
|
||||
let mut accepted: Vec<Target> = Vec::new();
|
||||
|
||||
if targets.is_empty() {
|
||||
return plan;
|
||||
}
|
||||
let mounts = mount_points();
|
||||
// Once per plan, not per target: the review screen plans every frame.
|
||||
let home = std::env::var_os("HOME").map(|home| Home::of(Path::new(&home)));
|
||||
|
||||
for target in targets {
|
||||
let path = normalize(&target.path);
|
||||
if let Some(reason) = refuse(&path, &root, home.as_deref(), &mounts) {
|
||||
if let Some(reason) = refuse(&path, &root, home.as_ref(), &mounts) {
|
||||
plan.blocked.push(Blocked {
|
||||
path: target.path.clone(),
|
||||
reason,
|
||||
@@ -133,13 +137,19 @@ pub fn plan(targets: &[Target], root: &Path) -> Plan {
|
||||
plan
|
||||
}
|
||||
|
||||
/// Why this path must not be removed, if it must not.
|
||||
/// Trees the operating system owns. A whole-disk scan shows them, because
|
||||
/// they are part of what fills the disk, but files there belong to packages
|
||||
/// and removing them by hand breaks the system; pacman, paccache and
|
||||
/// `journalctl --vacuum` are the right tools. Refused even where
|
||||
/// permissions would allow it, and even inside them.
|
||||
const SYSTEM_TREES: [&str; 14] = [
|
||||
/// and removing them by hand breaks the system; pacman, paccache,
|
||||
/// `journalctl --vacuum` or `brew cleanup` are the right tools. Refused even
|
||||
/// where permissions would allow it, and even inside them.
|
||||
///
|
||||
/// One list for every platform: a macOS tree never exists on Linux, and the
|
||||
/// other way round, so the extra entries cost nothing. On macOS `/etc`,
|
||||
/// `/var` and `/tmp` are links into `/private`, which a whole-disk scan
|
||||
/// reaches by its real name. `/Applications` is left out on purpose: moving
|
||||
/// an app to the Trash is how macOS uninstalls it, and the apps macOS ships
|
||||
/// live on the read-only system volume anyway.
|
||||
const SYSTEM_TREES: [&str; 20] = [
|
||||
"/bin",
|
||||
"/boot",
|
||||
"/dev",
|
||||
@@ -154,41 +164,134 @@ const SYSTEM_TREES: [&str; 14] = [
|
||||
"/usr",
|
||||
"/var/lib",
|
||||
"/efi",
|
||||
// macOS.
|
||||
"/System",
|
||||
"/Library",
|
||||
"/private",
|
||||
"/cores",
|
||||
"/opt/homebrew",
|
||||
"/Network",
|
||||
];
|
||||
|
||||
/// The system tree `path` is in, if any. The home directory is never
|
||||
/// system, wherever it lives.
|
||||
fn system_tree(path: &Path, home: Option<&Path>) -> Option<&'static str> {
|
||||
if home.is_some_and(|home| path.starts_with(normalize(home))) {
|
||||
/// How the guards compare paths: lexically normalized, and on macOS also in
|
||||
/// the form Finder shows and without case.
|
||||
///
|
||||
/// macOS reaches the same directory under two names — `/Users/x` and
|
||||
/// `/System/Volumes/Data/Users/x` — and its disks ignore case by default, so
|
||||
/// `/library/caches` is `/Library/Caches`. A guard that compared the spelling
|
||||
/// would be passed by the other one. Only for judging: what is removed is
|
||||
/// always the path as marked.
|
||||
fn guard_key(path: &Path) -> PathBuf {
|
||||
guard_key_for(path, cfg!(target_os = "macos"))
|
||||
}
|
||||
|
||||
fn guard_key_for(path: &Path, macos: bool) -> PathBuf {
|
||||
let path = normalize(path);
|
||||
if !macos {
|
||||
return path;
|
||||
}
|
||||
// The Data volume's own root stays as it is: it is under /System.
|
||||
let path = match path.strip_prefix(crate::space::MACOS_DATA_VOLUME) {
|
||||
Ok(rest) if !rest.as_os_str().is_empty() => Path::new("/").join(rest),
|
||||
_ => path,
|
||||
};
|
||||
PathBuf::from(path.to_string_lossy().to_lowercase())
|
||||
}
|
||||
|
||||
/// [`SYSTEM_TREES`] with their guard keys, computed once: the review screen
|
||||
/// plans on every frame, for every mark.
|
||||
fn system_tree_keys() -> &'static [(&'static str, PathBuf)] {
|
||||
static KEYS: std::sync::LazyLock<Vec<(&'static str, PathBuf)>> =
|
||||
std::sync::LazyLock::new(|| {
|
||||
SYSTEM_TREES
|
||||
.iter()
|
||||
.map(|tree| (*tree, guard_key(Path::new(tree))))
|
||||
.collect()
|
||||
});
|
||||
&KEYS
|
||||
}
|
||||
|
||||
/// The system tree the path keyed `key` is in, if any. The home directory is
|
||||
/// never system, wherever it lives.
|
||||
fn system_tree(key: &Path, home: Option<&Path>) -> Option<&'static str> {
|
||||
if home.is_some_and(|home| key.starts_with(home)) {
|
||||
return None;
|
||||
}
|
||||
SYSTEM_TREES
|
||||
system_tree_keys()
|
||||
.iter()
|
||||
.find(|tree| path.starts_with(tree))
|
||||
.copied()
|
||||
.find(|(_, tree)| key.starts_with(tree))
|
||||
.map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
/// A system tree strictly inside the path keyed `key`: removing `/opt` takes
|
||||
/// `/opt/homebrew` with it, and `/var` takes `/var/lib`.
|
||||
fn system_tree_below(key: &Path) -> Option<&'static str> {
|
||||
system_tree_keys()
|
||||
.iter()
|
||||
.find(|(_, tree)| tree != key && tree.starts_with(key))
|
||||
.map(|(name, _)| *name)
|
||||
}
|
||||
|
||||
/// The home directory, as the guards compare it: by key, and by identity.
|
||||
#[derive(Debug)]
|
||||
struct Home {
|
||||
key: PathBuf,
|
||||
/// Device and inode, so a spelling [`guard_key`] cannot fold still
|
||||
/// matches.
|
||||
id: Option<(u64, u64)>,
|
||||
}
|
||||
|
||||
impl Home {
|
||||
fn of(path: &Path) -> Self {
|
||||
Self {
|
||||
key: guard_key(path),
|
||||
id: fs::metadata(path).ok().and_then(|meta| file_id(&meta)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refuse(
|
||||
path: &Path,
|
||||
root: &Path,
|
||||
home: Option<&Path>,
|
||||
home: Option<&Home>,
|
||||
mounts: &[PathBuf],
|
||||
) -> Option<String> {
|
||||
let key = guard_key(path);
|
||||
let home_key = home.map(|home| home.key.as_path());
|
||||
if path.parent().is_none() {
|
||||
return Some("the filesystem root cannot be removed".into());
|
||||
}
|
||||
if path == root {
|
||||
return Some("the scanned root cannot be removed".into());
|
||||
}
|
||||
if home.is_some_and(|home| path == normalize(home)) {
|
||||
if home_key.is_some_and(|home| key == home)
|
||||
|| home.and_then(|home| home.id).is_some_and(|id| {
|
||||
fs::symlink_metadata(path)
|
||||
.ok()
|
||||
.and_then(|meta| file_id(&meta))
|
||||
== Some(id)
|
||||
})
|
||||
{
|
||||
return Some("the home directory cannot be removed".into());
|
||||
}
|
||||
// On Linux `/home` is usually a mount point of its own and refused as
|
||||
// one; on macOS `/Users` is on the same volume as `/`, and removing it
|
||||
// would empty the home directory before failing on `/Users` itself.
|
||||
if home_key.is_some_and(|home| home.starts_with(&key)) {
|
||||
return Some("it contains the home directory".into());
|
||||
}
|
||||
if !path.starts_with(root) {
|
||||
return Some("outside the scanned root".into());
|
||||
}
|
||||
if let Some(system) = system_tree(path, home) {
|
||||
if let Some(system) = system_tree(&key, home_key) {
|
||||
return Some(format!(
|
||||
"part of the system under {system}: use the package manager"
|
||||
"part of the system under {system}: remove it with the tool \
|
||||
that installed it"
|
||||
));
|
||||
}
|
||||
if let Some(system) = system_tree_below(&key) {
|
||||
return Some(format!(
|
||||
"it contains {system}, which is part of the system"
|
||||
));
|
||||
}
|
||||
if is_mount_point(path) {
|
||||
@@ -197,7 +300,7 @@ fn refuse(
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
if let Some(mount) = mount_below(path, mounts) {
|
||||
if let Some(mount) = mount_below(&key, mounts) {
|
||||
return Some(format!(
|
||||
"{} is mounted inside it: removing it would reach into another \
|
||||
filesystem",
|
||||
@@ -207,26 +310,114 @@ fn refuse(
|
||||
None
|
||||
}
|
||||
|
||||
/// Every mount point on this machine, from the mount table. Empty where the
|
||||
/// table cannot be read; the removal walker still stops at a device boundary.
|
||||
fn mount_points() -> Vec<PathBuf> {
|
||||
std::fs::read_to_string("/proc/self/mounts")
|
||||
.map(|table| {
|
||||
/// `(device, inode)`: what makes two spellings one directory entry.
|
||||
#[allow(
|
||||
clippy::unnecessary_wraps,
|
||||
reason = "the Option is the non-Unix answer, so both arms must agree"
|
||||
)]
|
||||
#[cfg(unix)]
|
||||
fn file_id(meta: &fs::Metadata) -> Option<(u64, u64)> {
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
Some((meta.dev(), meta.ino()))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
const fn file_id(_meta: &fs::Metadata) -> Option<(u64, u64)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// How long a read of the mount table is used before it is read again. A
|
||||
/// disk plugged in is noticed within this, and the removal itself stops at a
|
||||
/// mount boundary whatever the table said.
|
||||
const MOUNTS_FRESH: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// The last read of the mount table, and whether a read is under way.
|
||||
struct MountCache {
|
||||
read: Option<std::time::Instant>,
|
||||
mounts: Option<Arc<Vec<PathBuf>>>,
|
||||
refreshing: bool,
|
||||
}
|
||||
|
||||
static MOUNTS: std::sync::Mutex<MountCache> =
|
||||
std::sync::Mutex::new(MountCache {
|
||||
read: None,
|
||||
mounts: None,
|
||||
refreshing: false,
|
||||
});
|
||||
|
||||
/// Every mount point on this machine, as guard keys, as last read.
|
||||
///
|
||||
/// Never blocks on the read: the review screen plans on every frame, and on
|
||||
/// macOS the table comes from running `mount`. A stale table starts a read on
|
||||
/// its own thread and is used meanwhile; before the first read lands it is
|
||||
/// empty, which is why the app primes it at start with
|
||||
/// [`prime_mount_points`].
|
||||
fn mount_points() -> Arc<Vec<PathBuf>> {
|
||||
let mut cache = MOUNTS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let fresh = cache.read.is_some_and(|read| read.elapsed() < MOUNTS_FRESH);
|
||||
if !fresh && !cache.refreshing {
|
||||
cache.refreshing = true;
|
||||
let spawned = thread::Builder::new()
|
||||
.name("disktree-mounts".into())
|
||||
.spawn(|| {
|
||||
let mounts = Arc::new(read_mount_points());
|
||||
let mut cache = MOUNTS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
cache.mounts = Some(mounts);
|
||||
cache.read = Some(std::time::Instant::now());
|
||||
cache.refreshing = false;
|
||||
});
|
||||
if spawned.is_err() {
|
||||
cache.refreshing = false;
|
||||
}
|
||||
}
|
||||
cache.mounts.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Start reading the mount table, so it is there by the time anything is
|
||||
/// marked.
|
||||
pub fn prime_mount_points() {
|
||||
let _ = mount_points();
|
||||
}
|
||||
|
||||
/// Read the mount points now: from `/proc/self/mounts`, or on macOS from
|
||||
/// `mount`, which has no `/proc`. Empty where neither can be read.
|
||||
fn read_mount_points() -> Vec<PathBuf> {
|
||||
let points: Vec<PathBuf> =
|
||||
if let Ok(table) = fs::read_to_string("/proc/self/mounts") {
|
||||
crate::space::parse_mounts(&table)
|
||||
.into_iter()
|
||||
.map(|mount| mount.point)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Command::new("/sbin/mount")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.map(|output| {
|
||||
crate::space::parse_macos_mounts(&String::from_utf8_lossy(
|
||||
&output.stdout,
|
||||
))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
points.iter().map(|point| guard_key(point)).collect()
|
||||
}
|
||||
|
||||
/// A mount point strictly inside `path`, if there is one. A scan that stays
|
||||
/// on one filesystem never shows what is mounted there, so the user cannot
|
||||
/// have meant to remove it.
|
||||
fn mount_below<'a>(path: &Path, mounts: &'a [PathBuf]) -> Option<&'a Path> {
|
||||
/// A mount point strictly inside the path keyed `key`, if there is one. A
|
||||
/// scan that stays on one filesystem never shows what is mounted there, so
|
||||
/// the user cannot have meant to remove it.
|
||||
fn mount_below<'a>(key: &Path, mounts: &'a [PathBuf]) -> Option<&'a Path> {
|
||||
mounts
|
||||
.iter()
|
||||
.find(|mount| mount.as_path() != path && mount.starts_with(path))
|
||||
.find(|mount| mount.as_path() != key && mount.starts_with(key))
|
||||
.map(PathBuf::as_path)
|
||||
}
|
||||
|
||||
@@ -289,6 +480,9 @@ pub fn normalize(path: &Path) -> PathBuf {
|
||||
/// Which tool, if any, moves files to the desktop trash.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum TrashBackend {
|
||||
/// The macOS Trash, through `NSFileManager`: the same move as Finder's
|
||||
/// Move to Trash, into the Trash of the volume the item is on.
|
||||
MacOs,
|
||||
/// `trash-put` from trash-cli.
|
||||
TrashPut,
|
||||
/// `gio trash`, present anywhere `GLib` is installed.
|
||||
@@ -303,13 +497,14 @@ pub enum TrashBackend {
|
||||
impl TrashBackend {
|
||||
pub const fn is_available(self) -> bool {
|
||||
match self {
|
||||
Self::TrashPut | Self::Gio | Self::XdgHome => true,
|
||||
Self::MacOs | Self::TrashPut | Self::Gio | Self::XdgHome => true,
|
||||
Self::Unavailable => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::MacOs => "the Trash",
|
||||
Self::TrashPut => "trash-put",
|
||||
Self::Gio => "gio trash",
|
||||
Self::XdgHome => "XDG trash",
|
||||
@@ -319,6 +514,7 @@ impl TrashBackend {
|
||||
|
||||
pub const fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Self::MacOs => "the same Trash as Finder, on the item's own disk",
|
||||
Self::TrashPut => {
|
||||
"uses trash-cli, the same trash as your file manager"
|
||||
}
|
||||
@@ -334,6 +530,17 @@ impl TrashBackend {
|
||||
}
|
||||
|
||||
/// Detect the best available trash backend for this machine.
|
||||
///
|
||||
/// On macOS the system Trash is always there, and the Linux tools are not
|
||||
/// a substitute: Homebrew's `trash-put` writes the XDG layout, which Finder
|
||||
/// never shows, so their files would look recoverable and not be.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub const fn detect_trash_backend() -> TrashBackend {
|
||||
TrashBackend::MacOs
|
||||
}
|
||||
|
||||
/// Detect the best available trash backend for this machine.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn detect_trash_backend() -> TrashBackend {
|
||||
if which("trash-put") {
|
||||
TrashBackend::TrashPut
|
||||
@@ -346,6 +553,7 @@ pub fn detect_trash_backend() -> TrashBackend {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn which(program: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
@@ -486,6 +694,7 @@ fn run(
|
||||
/// empty it before failing on the mount point itself, so the walk is done here
|
||||
/// instead: every directory is opened relative to its parent with
|
||||
/// `O_NOFOLLOW`, and one on a different device or mount stops the removal.
|
||||
/// (From tobi/disktree#10.)
|
||||
#[cfg(unix)]
|
||||
pub fn remove_permanently(path: &Path) -> io::Result<()> {
|
||||
let meta = fs::symlink_metadata(path)?;
|
||||
@@ -512,9 +721,8 @@ pub fn remove_permanently(path: &Path) -> io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
struct Volume {
|
||||
device: rustix::fs::Stat,
|
||||
/// The mount the directory belongs to, where the kernel reports it. A bind
|
||||
/// mount of the same filesystem keeps its `st_dev`, so the device alone
|
||||
/// cannot see it.
|
||||
/// The mount the directory belongs to, where the kernel reports it (Linux,
|
||||
/// `statx`). See [`Self::contains`].
|
||||
mount: Option<u64>,
|
||||
}
|
||||
|
||||
@@ -527,8 +735,17 @@ impl Volume {
|
||||
})
|
||||
}
|
||||
|
||||
fn contains(&self, other: &Self) -> bool {
|
||||
self.device.st_dev == other.device.st_dev && self.mount == other.mount
|
||||
/// Whether `other` is on the same mount. Where the kernel names mounts,
|
||||
/// that decides: a btrfs subvolume that is not mounted has its own
|
||||
/// `st_dev` but is the same mount, and the scan showed it as part of the
|
||||
/// volume, so it goes with the directory it is in; a bind mount keeps
|
||||
/// `st_dev` but is a mount of its own, and stops the removal. Without
|
||||
/// mount IDs (macOS) the device decides.
|
||||
const fn contains(&self, other: &Self) -> bool {
|
||||
match (self.mount, other.mount) {
|
||||
(Some(one), Some(two)) => one == two,
|
||||
_ => self.device.st_dev == other.device.st_dev,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,7 +801,6 @@ fn remove_contents(
|
||||
}
|
||||
|
||||
for (name, kind) in entries {
|
||||
let child_path = path.join(OsStr::from_bytes(name.to_bytes()));
|
||||
if !matches!(kind, FileType::Directory | FileType::Unknown) {
|
||||
unlinkat(dir, &name, AtFlags::empty())?;
|
||||
continue;
|
||||
@@ -599,6 +815,8 @@ fn remove_contents(
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
// Only directories need their path, for the message below.
|
||||
let child_path = path.join(OsStr::from_bytes(name.to_bytes()));
|
||||
if !top.contains(&Volume::of(&child)?) {
|
||||
return Err(io::Error::other(format!(
|
||||
"stopped at {}: another filesystem is mounted there, and \
|
||||
@@ -619,12 +837,46 @@ pub fn move_to_trash(path: &Path, backend: TrashBackend) -> io::Result<()> {
|
||||
TrashBackend::TrashPut => run_tool(Path::new("trash-put"), &[], path),
|
||||
TrashBackend::Gio => run_tool(Path::new("gio"), &["trash"], path),
|
||||
TrashBackend::XdgHome => trash_via_xdg(path),
|
||||
TrashBackend::MacOs => trash_via_macos(path),
|
||||
TrashBackend::Unavailable => Err(io::Error::other(
|
||||
"no trash tool is installed; use permanent deletion instead",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Move one path to the macOS Trash.
|
||||
///
|
||||
/// The `trash` crate resolves the parent directory and keeps the final name,
|
||||
/// so a symlink is trashed itself and its target is left alone. A name that is
|
||||
/// not UTF-8 is refused rather than handed over: the crate would
|
||||
/// percent-encode it into a different path.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn trash_via_macos(path: &Path) -> io::Result<()> {
|
||||
use trash::macos::{DeleteMethod, TrashContextExtMacos as _};
|
||||
|
||||
if path.to_str().is_none() {
|
||||
return Err(io::Error::other(
|
||||
"the name is not UTF-8, which the Trash cannot take; \
|
||||
use permanent deletion",
|
||||
));
|
||||
}
|
||||
let mut context = trash::TrashContext::default();
|
||||
// Finder's method asks for permission to control Finder and plays a
|
||||
// sound per call; NSFileManager does neither.
|
||||
context.set_delete_method(DeleteMethod::NsFileManager);
|
||||
context.delete(path).map_err(|error| {
|
||||
io::Error::other(format!(
|
||||
"could not move to the Trash ({error}); network and read-only \
|
||||
disks have none, so use permanent deletion there"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn trash_via_macos(_path: &Path) -> io::Result<()> {
|
||||
Err(io::Error::other("the macOS Trash only exists on macOS"))
|
||||
}
|
||||
|
||||
/// Run one trash tool on one path.
|
||||
///
|
||||
/// `--` is passed before the path so that a file named `-rf` is read as a path
|
||||
@@ -762,6 +1014,11 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`system_tree`] for plain paths, keyed the way [`refuse`] keys them.
|
||||
fn tree_of(path: &Path, home: &Path) -> Option<&'static str> {
|
||||
system_tree(&guard_key(path), Some(&guard_key(home)))
|
||||
}
|
||||
|
||||
fn tree() -> TempDir {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
fs::create_dir_all(temp.path().join("a/b")).expect("mkdir");
|
||||
@@ -853,17 +1110,72 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_holding_the_home_directory_is_refused() {
|
||||
// /Users in a whole-disk scan on macOS: the same volume as /, so no
|
||||
// mount point, and removing it would empty home first.
|
||||
let home = Path::new("/Users/tobi");
|
||||
let reason = refuse(
|
||||
Path::new("/Users"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
)
|
||||
.expect("refused");
|
||||
assert!(reason.contains("home directory"), "{reason}");
|
||||
assert!(
|
||||
refuse(
|
||||
Path::new("/Users/tobi/src"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[]
|
||||
)
|
||||
.is_none(),
|
||||
"inside home is the user's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_directory_holding_a_system_tree_is_refused() {
|
||||
let home = Path::new("/Users/tobi");
|
||||
for (path, inside) in [("/opt", "/opt/homebrew"), ("/var", "/var/lib")]
|
||||
{
|
||||
let reason = refuse(
|
||||
Path::new(path),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
)
|
||||
.expect("refused");
|
||||
assert!(reason.contains(inside), "{path}: {reason}");
|
||||
}
|
||||
assert!(
|
||||
refuse(
|
||||
Path::new("/opt/local"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[]
|
||||
)
|
||||
.is_none(),
|
||||
"a sibling of a system tree is not its parent"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_with_a_mount_inside_is_refused() {
|
||||
let temp = tree();
|
||||
let root = temp.path();
|
||||
let mounts = vec![root.join("a/b"), root.join("other")];
|
||||
let mounts =
|
||||
vec![guard_key(&root.join("a/b")), guard_key(&root.join("other"))];
|
||||
assert_eq!(
|
||||
mount_below(&root.join("a"), &mounts),
|
||||
Some(root.join("a/b").as_path())
|
||||
mount_below(&guard_key(&root.join("a")), &mounts),
|
||||
Some(guard_key(&root.join("a/b")).as_path())
|
||||
);
|
||||
assert_eq!(
|
||||
mount_below(&guard_key(&root.join("a/b")), &mounts),
|
||||
None,
|
||||
"itself"
|
||||
);
|
||||
assert_eq!(mount_below(&root.join("a/b"), &mounts), None, "itself");
|
||||
assert_eq!(mount_below(&root.join("a/one.bin"), &mounts), None);
|
||||
let reason =
|
||||
refuse(&root.join("a"), root, None, &mounts).expect("refused");
|
||||
assert!(reason.contains("mounted inside"), "{reason}");
|
||||
@@ -871,9 +1183,119 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_home_scan_has_nothing_mounted_below_a_temp_dir() {
|
||||
fn nothing_is_mounted_below_a_temp_dir() {
|
||||
let temp = tree();
|
||||
assert_eq!(mount_below(temp.path(), &mount_points()), None);
|
||||
assert_eq!(
|
||||
mount_below(&guard_key(temp.path()), &read_mount_points()),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn this_macs_mount_table_is_read_without_proc() {
|
||||
let mounts = read_mount_points();
|
||||
assert!(mounts.contains(&guard_key(Path::new("/"))), "{mounts:?}");
|
||||
// Asked of `mount_below` itself: `refuse` would turn /System/Volumes
|
||||
// away as a system tree before it looked at the mounts.
|
||||
assert!(
|
||||
mount_below(&guard_key(Path::new("/System/Volumes")), &mounts)
|
||||
.is_some(),
|
||||
"the Data volume is mounted there"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mount_table_is_read_off_the_calling_thread_and_then_kept() {
|
||||
prime_mount_points();
|
||||
// The first read lands on its own thread; wait for it, briefly.
|
||||
let mut mounts = mount_points();
|
||||
for _ in 0..500 {
|
||||
if !mounts.is_empty() {
|
||||
break;
|
||||
}
|
||||
thread::sleep(std::time::Duration::from_millis(10));
|
||||
mounts = mount_points();
|
||||
}
|
||||
assert_eq!(*mounts, read_mount_points(), "the same table, cached");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_volume_is_judged_by_its_mount_where_the_kernel_names_one() {
|
||||
let temp = tree();
|
||||
let dir = open_dir(rustix::fs::CWD, temp.path()).expect("open");
|
||||
let here = Volume::of(&dir).expect("volume");
|
||||
let mut other = Volume::of(&dir).expect("volume");
|
||||
assert!(here.contains(&other));
|
||||
// A btrfs subvolume: another device, the same mount.
|
||||
other.device.st_dev = other.device.st_dev.wrapping_add(1);
|
||||
other.mount = Some(7);
|
||||
let mount = Volume {
|
||||
device: here.device,
|
||||
mount: Some(7),
|
||||
};
|
||||
assert!(mount.contains(&other), "same mount, other device");
|
||||
// A bind mount: the same device, another mount.
|
||||
let bind = Volume {
|
||||
device: here.device,
|
||||
mount: Some(8),
|
||||
};
|
||||
assert!(!mount.contains(&bind));
|
||||
// No mount IDs, as on macOS: the device decides.
|
||||
let (mut plain, mut moved) = (
|
||||
Volume::of(&dir).expect("volume"),
|
||||
Volume::of(&dir).expect("volume"),
|
||||
);
|
||||
plain.mount = None;
|
||||
moved.mount = None;
|
||||
moved.device.st_dev = moved.device.st_dev.wrapping_add(1);
|
||||
assert!(!plain.contains(&moved));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_guard_keys_fold_the_data_volume_and_case() {
|
||||
let key = |path: &str| guard_key_for(Path::new(path), true);
|
||||
assert_eq!(
|
||||
key("/System/Volumes/Data/Users/Tobi/src"),
|
||||
PathBuf::from("/users/tobi/src")
|
||||
);
|
||||
assert_eq!(key("/Library/./Caches"), PathBuf::from("/library/caches"));
|
||||
assert_eq!(
|
||||
key("/System/Volumes/Data"),
|
||||
PathBuf::from("/system/volumes/data"),
|
||||
"the Data volume itself stays under /System"
|
||||
);
|
||||
assert_eq!(
|
||||
guard_key_for(Path::new("/Library/X"), false),
|
||||
PathBuf::from("/Library/X"),
|
||||
"Linux paths are compared as spelled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_guards_see_through_other_spellings() {
|
||||
let home = Path::new("/Users/tobi");
|
||||
let data = Path::new(crate::space::MACOS_DATA_VOLUME);
|
||||
assert!(
|
||||
refuse(
|
||||
&data.join("Users/tobi/src"),
|
||||
data,
|
||||
Some(&Home::of(home)),
|
||||
&[]
|
||||
)
|
||||
.is_none(),
|
||||
"home under the Data volume's name is still home"
|
||||
);
|
||||
let reason = refuse(
|
||||
Path::new("/library/caches"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
)
|
||||
.expect("refused");
|
||||
assert!(reason.contains("/Library"), "{reason}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1082,6 +1504,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn detection_prefers_a_tool_this_machine_has() {
|
||||
let backend = detect_trash_backend();
|
||||
if which("trash-put") {
|
||||
@@ -1090,34 +1513,92 @@ mod tests {
|
||||
assert!(backend.is_available());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn macos_always_uses_the_system_trash() {
|
||||
// Whatever Homebrew put on PATH: its trash tools write a trash
|
||||
// Finder never shows.
|
||||
assert_eq!(detect_trash_backend(), TrashBackend::MacOs);
|
||||
assert!(TrashBackend::MacOs.is_available());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
#[ignore = "puts a file in this Mac's real Trash"]
|
||||
fn the_macos_trash_takes_a_file_and_leaves_a_linked_target() {
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
let file = temp.path().join("disktree-trash-check.txt");
|
||||
fs::write(&file, b"x").expect("write");
|
||||
let keep = temp.path().join("keep.txt");
|
||||
fs::write(&keep, b"kept").expect("write");
|
||||
let link = temp.path().join("disktree-trash-check-link");
|
||||
std::os::unix::fs::symlink(&keep, &link).expect("symlink");
|
||||
|
||||
move_to_trash(&file, TrashBackend::MacOs).expect("trashed");
|
||||
move_to_trash(&link, TrashBackend::MacOs).expect("trashed");
|
||||
|
||||
assert!(!file.exists());
|
||||
assert!(fs::symlink_metadata(&link).is_err(), "the link went");
|
||||
assert_eq!(fs::read(&keep).expect("read"), b"kept", "not its target");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn a_name_that_is_not_utf8_is_refused_before_the_trash_sees_it() {
|
||||
use std::os::unix::ffi::OsStrExt as _;
|
||||
let temp = TempDir::new().expect("tempdir");
|
||||
let odd = temp
|
||||
.path()
|
||||
.join(std::ffi::OsStr::from_bytes(b"not-\xff-utf8"));
|
||||
let error = trash_via_macos(&odd).expect_err("refused");
|
||||
assert!(error.to_string().contains("UTF-8"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_trees_are_refused_in_a_whole_disk_scan() {
|
||||
let home = Path::new("/home/tobi");
|
||||
assert_eq!(
|
||||
system_tree(Path::new("/usr/lib/libfoo.so"), Some(home)),
|
||||
tree_of(Path::new("/usr/lib/libfoo.so"), home),
|
||||
Some("/usr")
|
||||
);
|
||||
assert_eq!(
|
||||
system_tree(Path::new("/var/lib/pacman"), Some(home)),
|
||||
tree_of(Path::new("/var/lib/pacman"), home),
|
||||
Some("/var/lib")
|
||||
);
|
||||
assert_eq!(tree_of(Path::new("/var/cache/pacman/pkg"), home), None);
|
||||
assert_eq!(tree_of(Path::new("/opt/thing"), home), None);
|
||||
assert_eq!(
|
||||
system_tree(Path::new("/var/cache/pacman/pkg"), Some(home)),
|
||||
None
|
||||
);
|
||||
assert_eq!(system_tree(Path::new("/opt/thing"), Some(home)), None);
|
||||
assert_eq!(
|
||||
system_tree(Path::new("/usrlocal"), Some(home)),
|
||||
tree_of(Path::new("/usrlocal"), home),
|
||||
None,
|
||||
"components, not prefixes"
|
||||
);
|
||||
let odd_home = Path::new("/usr/home/tobi");
|
||||
assert_eq!(
|
||||
system_tree(Path::new("/usr/home/tobi/.cache"), Some(odd_home)),
|
||||
None
|
||||
assert_eq!(tree_of(Path::new("/usr/home/tobi/.cache"), odd_home), None);
|
||||
let reason = refuse(
|
||||
Path::new("/etc/hosts"),
|
||||
Path::new("/"),
|
||||
Some(&Home::of(home)),
|
||||
&[],
|
||||
);
|
||||
let reason =
|
||||
refuse(Path::new("/etc/hosts"), Path::new("/"), Some(home), &[]);
|
||||
assert!(reason.is_some_and(|reason| reason.contains("/etc")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_system_trees_are_refused_but_apps_are_not() {
|
||||
let home = Path::new("/Users/tobi");
|
||||
for (path, tree) in [
|
||||
("/System/Library/Fonts", "/System"),
|
||||
("/Library/Caches/com.apple.x", "/Library"),
|
||||
("/private/etc/hosts", "/private"),
|
||||
("/private/var/folders/xy", "/private"),
|
||||
("/opt/homebrew/Cellar/git", "/opt/homebrew"),
|
||||
] {
|
||||
assert_eq!(tree_of(Path::new(path), home), Some(tree));
|
||||
}
|
||||
// An app is uninstalled by moving it to the Trash, and a user's own
|
||||
// Library is theirs.
|
||||
for path in ["/Applications/Xcode.app", "/Users/tobi/Library/Caches"] {
|
||||
assert_eq!(tree_of(Path::new(path), home), None, "{path}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,10 +114,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 +186,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 +235,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 +255,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.
|
||||
@@ -297,6 +303,23 @@ impl WalkContext {
|
||||
}
|
||||
|
||||
if file_type.is_dir() {
|
||||
if self
|
||||
.never_scanned
|
||||
.get()
|
||||
.is_some_and(|never| never.contains(&path))
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
// `lstat` at most once per directory: macOS reads the dataless
|
||||
// flag from it, and the device check below needs it wherever the
|
||||
// mount table cannot be read, which on macOS is everywhere.
|
||||
let meta_cell = std::cell::OnceCell::new();
|
||||
let meta = || meta_cell.get_or_init(|| entry.metadata());
|
||||
if cfg!(target_os = "macos")
|
||||
&& meta().as_ref().is_ok_and(is_dataless)
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
// Memoized: the subtree a narrower scan already measured is
|
||||
// taken whole, before any volume rule, since it was measured
|
||||
// under the same rules.
|
||||
@@ -320,18 +343,18 @@ impl WalkContext {
|
||||
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 =>
|
||||
{
|
||||
let device = match meta() {
|
||||
Ok(meta) => device_of(meta),
|
||||
Err(error) => {
|
||||
self.progress.record_error(&path, error);
|
||||
return Classified::Skipped;
|
||||
}
|
||||
(Err(error), _) => {
|
||||
self.progress.record_error(&path, &error);
|
||||
return Classified::Skipped;
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
if self
|
||||
.root_device(&path)
|
||||
.is_some_and(|root_device| device != root_device)
|
||||
{
|
||||
return Classified::Skipped;
|
||||
}
|
||||
}
|
||||
self.progress.count_dir();
|
||||
@@ -360,6 +383,7 @@ impl WalkContext {
|
||||
NodeKind::Symlink,
|
||||
size,
|
||||
&meta,
|
||||
shares_inode(&meta),
|
||||
))
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -381,6 +405,11 @@ impl WalkContext {
|
||||
};
|
||||
|
||||
if meta.is_dir() {
|
||||
// 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) = file_identity(&meta)
|
||||
&& !lock(&self.visited_dirs).insert(key)
|
||||
{
|
||||
@@ -401,7 +430,10 @@ impl WalkContext {
|
||||
) -> Classified {
|
||||
let size = measure(meta, self.options.apparent_size);
|
||||
self.progress.count_file(size);
|
||||
Classified::Entry(leaf_node(name, kind, size, meta))
|
||||
// A followed link reaches a file a second way, whatever its link
|
||||
// count says.
|
||||
let track = self.options.follow_links || shares_inode(meta);
|
||||
Classified::Entry(leaf_node(name, kind, size, meta, track))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,10 +510,12 @@ 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());
|
||||
}
|
||||
}
|
||||
@@ -607,14 +641,20 @@ fn mark_duplicate_hardlinks(node: &mut Node, seen: &mut FxHashSet<(u64, u64)>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A leaf. Its `(device, inode)` is kept only when `track` says the walk
|
||||
/// could meet the same file again: a hardlink de-duplication set of every
|
||||
/// file on a disk is millions of entries, nearly all for files with one name.
|
||||
fn leaf_node(
|
||||
name: Box<str>,
|
||||
kind: NodeKind,
|
||||
size: u64,
|
||||
meta: &Metadata,
|
||||
track: bool,
|
||||
) -> Node {
|
||||
let mut node = Node::entry(name, kind, size);
|
||||
node.inode = file_identity(meta);
|
||||
if track {
|
||||
node.inode = file_identity(meta);
|
||||
}
|
||||
node.modified = modified_seconds(meta);
|
||||
node
|
||||
}
|
||||
@@ -658,6 +698,37 @@ 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 _;
|
||||
@@ -948,6 +1019,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),
|
||||
});
|
||||
|
||||
@@ -69,6 +69,7 @@ pub fn space_info(path: &Path) -> io::Result<SpaceInfo> {
|
||||
/// The device a path's filesystem is mounted from, such as
|
||||
/// `/dev/nvme0n1p2`: the mount with the longest prefix of `path` in
|
||||
/// `/proc/self/mounts`. `None` where that table cannot be read.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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,6 +187,7 @@ pub fn volume_root(mounts: &[Mount], path: &Path) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
/// [`volume_root`] for this machine.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
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());
|
||||
@@ -199,6 +201,98 @@ pub fn foreign_mounts_for(root: &Path) -> Option<Vec<PathBuf>> {
|
||||
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()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -271,6 +365,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();
|
||||
|
||||
@@ -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 |
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user