From a8da67feacd7057714efe5490467b39ee32f1930 Mon Sep 17 00:00:00 2001 From: Tobi Lutke Date: Wed, 25 Nov 2026 17:23:26 -0500 Subject: [PATCH] feat: unify disktree-scan into disktree-cli, package predictable release binaries, and offer one-click SSH install --- .github/workflows/release.yml | 36 ++++- Cargo.lock | 12 +- Cargo.toml | 1 - Makefile | 16 ++- crates/disktree-app/src/main.rs | 4 +- crates/disktree-app/src/state.rs | 114 ++++++++++++++- crates/disktree-app/src/views.rs | 110 ++++++++++++++- crates/disktree-cli/Cargo.toml | 4 + crates/disktree-cli/src/main.rs | 9 ++ crates/disktree-cli/src/stdio.rs | 88 ++++++++++++ .../tests/stdio.rs | 4 +- crates/disktree-core/src/deployment.rs | 2 +- crates/disktree-core/src/remote.rs | 131 +++++++++++++++--- crates/disktree-scan/Cargo.toml | 20 --- crates/disktree-scan/src/main.rs | 93 ------------- packaging/install.sh | 3 + scripts/test-ssh.ts | 4 +- xtask/src/portable.rs | 4 +- 18 files changed, 481 insertions(+), 174 deletions(-) create mode 100644 crates/disktree-cli/src/stdio.rs rename crates/{disktree-scan => disktree-cli}/tests/stdio.rs (98%) delete mode 100644 crates/disktree-scan/Cargo.toml delete mode 100644 crates/disktree-scan/src/main.rs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ece034d..0d8e870 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -108,22 +108,32 @@ jobs: ARCH: ${{ matrix.arch }} run: | name="disktree-$VERSION-$ARCH-linux" + cli_bin="target/$ARCH-unknown-linux-musl/release/disktree-cli" mkdir -p "dist/$name" # portable strips before appending; stripping again loses helpers. cp target/portable/disktree "dist/$name/" + cp "$cli_bin" "dist/$name/disktree-cli" cp packaging/install.sh packaging/disktree.desktop.in \ assets/disktree.svg README.md LICENSE "dist/$name/" echo "$VERSION" > "dist/$name/VERSION" tar -C dist -czf "dist/$name.tar.gz" "$name" (cd dist && sha256sum "$name.tar.gz" > "$name.tar.gz.sha256") + cli_asset="disktree-cli-linux-$ARCH" + cp "$cli_bin" "dist/$cli_asset" + (cd dist && sha256sum "$cli_asset" > "$cli_asset.sha256") echo "archive=dist/$name.tar.gz" >> "$GITHUB_OUTPUT" + echo "cli=dist/$cli_asset" >> "$GITHUB_OUTPUT" - name: Upload env: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.release.outputs.tag }} ARCHIVE: ${{ steps.package.outputs.archive }} - run: gh release upload "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" --clobber + CLI: ${{ steps.package.outputs.cli }} + run: | + gh release upload "$TAG" \ + "$ARCHIVE" "$ARCHIVE.sha256" \ + "$CLI" "$CLI.sha256" --clobber macos: name: Build (macOS ${{ matrix.arch }}) @@ -203,6 +213,7 @@ jobs: fi fi cargo xtask bundle "${args[@]}" + cargo build --release --locked -p disktree-cli - name: Upload env: @@ -214,7 +225,14 @@ jobs: zip="target/bundle/disktree-$VERSION-$ARCH-macos.zip" (cd "$(dirname "$zip")" && shasum -a 256 "$(basename "$zip")" \ > "$(basename "$zip").sha256") - gh release upload "$TAG" "$zip" "$zip.sha256" --clobber + mkdir -p dist + cli="dist/disktree-cli-macos-$ARCH" + cp target/release/disktree-cli "$cli" + (cd dist && shasum -a 256 "$(basename "$cli")" \ + > "$(basename "$cli").sha256") + gh release upload "$TAG" \ + "$zip" "$zip.sha256" \ + "$cli" "$cli.sha256" --clobber windows: name: Build (Windows ${{ matrix.arch }}) @@ -248,7 +266,7 @@ jobs: run: cargo xtask test - name: Build - run: cargo build --release --locked -p disktree-app + run: cargo build --release --locked -p disktree-app -p disktree-cli - name: Package id: package @@ -259,12 +277,17 @@ jobs: run: | $name = "disktree-$env:VERSION-$env:ARCH-windows" New-Item -ItemType Directory -Force "dist/$name" | Out-Null - Copy-Item target/release/disktree.exe, README.md, LICENSE "dist/$name/" + Copy-Item target/release/disktree.exe, target/release/disktree-cli.exe, README.md, LICENSE "dist/$name/" Compress-Archive -Path "dist/$name" -DestinationPath "dist/$name.zip" $hash = (Get-FileHash "dist/$name.zip" -Algorithm SHA256).Hash.ToLower() # The format `sha256sum -c` reads, with a Unix line ending. [IO.File]::WriteAllText("dist/$name.zip.sha256", "$hash $name.zip`n") + $cli = "disktree-cli-windows-$env:ARCH.exe" + Copy-Item target/release/disktree-cli.exe "dist/$cli" + $cliHash = (Get-FileHash "dist/$cli" -Algorithm SHA256).Hash.ToLower() + [IO.File]::WriteAllText("dist/$cli.sha256", "$cliHash $cli`n") "archive=dist/$name.zip" >> $env:GITHUB_OUTPUT + "cli=dist/$cli" >> $env:GITHUB_OUTPUT - name: Install Inno Setup shell: pwsh @@ -291,9 +314,12 @@ jobs: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.release.outputs.tag }} ARCHIVE: ${{ steps.package.outputs.archive }} + CLI: ${{ steps.package.outputs.cli }} SETUP: ${{ steps.installer.outputs.setup }} run: | - gh release upload "$TAG" "$ARCHIVE" "$ARCHIVE.sha256" \ + gh release upload "$TAG" \ + "$ARCHIVE" "$ARCHIVE.sha256" \ + "$CLI" "$CLI.sha256" \ "$SETUP" "$SETUP.sha256" --clobber publish: diff --git a/Cargo.lock b/Cargo.lock index 7d426b0..b82118a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1626,9 +1626,11 @@ dependencies = [ "anyhow", "clap", "crossterm", + "disktree-core", "disktree-scanner", "ratatui", "rustc-hash 2.1.3", + "rustix 1.1.4", "serde", "serde_json", "tempfile", @@ -1651,16 +1653,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "disktree-scan" -version = "0.11.0" -dependencies = [ - "disktree-core", - "rustix 1.1.4", - "serde_json", - "tempfile", -] - [[package]] name = "disktree-scanner" version = "0.11.0" diff --git a/Cargo.toml b/Cargo.toml index fd3b875..ec7c6ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,6 @@ members = [ "crates/disktree-app", "crates/disktree-cli", "crates/disktree-core", - "crates/disktree-scan", "crates/disktree-scanner", "xtask", ] diff --git a/Makefile b/Makefile index 0a7865d..962ea89 100644 --- a/Makefile +++ b/Makefile @@ -47,14 +47,14 @@ define check_install_path fi endef -.PHONY: help build run install install-scan uninstall bundle lint test test-ssh ci fmt clean +.PHONY: help build run install install-cli install-scan uninstall bundle lint test test-ssh ci fmt clean help: @echo "disktree" @echo - @echo " make build release build" + @echo " make build release build (with embedded static SSH helpers on Linux)" @echo " make run build and scan your home directory" - @echo " make install-scan build/install the headless SSH helper only" + @echo " make install-cli build/install disktree-cli (TUI, JSON, SSH helper)" @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" @@ -77,11 +77,13 @@ else endif # For servers: no desktop, GPU, GPUI build, or elevated permissions needed. -install-scan: - $(CARGO) build --release -p disktree-scan +install-cli: + $(CARGO) build --release -p disktree-cli install -d "$(BINDIR)" - install -m755 target/release/disktree-scan "$(BINDIR)/disktree-scan" - $(call check_install_path,disktree-scan) + install -m755 target/release/disktree-cli "$(BINDIR)/disktree-cli" + $(call check_install_path,disktree-cli) + +install-scan: install-cli run: build $(TARGET) diff --git a/crates/disktree-app/src/main.rs b/crates/disktree-app/src/main.rs index 4245889..6e5c7b3 100644 --- a/crates/disktree-app/src/main.rs +++ b/crates/disktree-app/src/main.rs @@ -56,8 +56,8 @@ usage: disktree [OPTIONS] [PATH] disktree ssh HOST [OPTIONS] [PATH] disktree extract-scanner ARCH OUTPUT -Linux packaged builds deploy an embedded static scanner over SSH on demand. -Unbundled development builds need disktree-scan on the remote PATH or in +Linux packaged builds deploy an embedded static disktree-cli over SSH on demand. +Unbundled development builds need disktree-cli on the remote PATH or in ~/.local/bin. ARCH for extraction is x86_64 or aarch64. SSH uses your config, keys and agent; password prompts use the terminal. Remote sessions are read-only: mark, export list/prompt/delete script. diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index b2a3a4b..fa8ab64 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -740,6 +740,9 @@ pub mod discovery_machine { Loading { job: Option, }, + Installing { + host: String, + }, Ready, Failed(String), } @@ -750,6 +753,10 @@ pub mod discovery_machine { StartRemote { host: String, }, + StartInstall { + host: String, + command: String, + }, RemoteSpawned { epoch: u64, job: disktree_core::remote::RemoteRoots, @@ -763,9 +770,21 @@ pub mod discovery_machine { #[derive(Debug, PartialEq, Eq)] pub enum Effect { - SpawnLocalListing { epoch: u64 }, - DiscoverRemote { epoch: u64, host: String }, - PollRemote { epoch: u64 }, + SpawnLocalListing { + epoch: u64, + }, + DiscoverRemote { + epoch: u64, + host: String, + }, + InstallRemote { + epoch: u64, + host: String, + command: String, + }, + PollRemote { + epoch: u64, + }, } impl State { @@ -774,7 +793,10 @@ pub mod discovery_machine { } pub const fn is_loading(&self) -> bool { - matches!(self.phase, Phase::Loading { .. }) + matches!( + self.phase, + Phase::Loading { .. } | Phase::Installing { .. } + ) } pub const fn is_ready(&self) -> bool { @@ -784,7 +806,10 @@ pub mod discovery_machine { pub fn error(&self) -> Option<&str> { match &self.phase { Phase::Failed(error) => Some(error), - Phase::Idle | Phase::Loading { .. } | Phase::Ready => None, + Phase::Idle + | Phase::Loading { .. } + | Phase::Installing { .. } + | Phase::Ready => None, } } } @@ -797,6 +822,7 @@ pub mod discovery_machine { ( Phase::Idle | Phase::Loading { .. } + | Phase::Installing { .. } | Phase::Ready | Phase::Failed(_), Event::Reset, @@ -810,6 +836,7 @@ pub mod discovery_machine { ( Phase::Idle | Phase::Loading { .. } + | Phase::Installing { .. } | Phase::Ready | Phase::Failed(_), Event::StartLocal, @@ -826,6 +853,7 @@ pub mod discovery_machine { ( Phase::Idle | Phase::Loading { .. } + | Phase::Installing { .. } | Phase::Ready | Phase::Failed(_), Event::StartRemote { host }, @@ -842,6 +870,27 @@ pub mod discovery_machine { }], ) } + ( + Phase::Idle + | Phase::Loading { .. } + | Phase::Installing { .. } + | Phase::Ready + | Phase::Failed(_), + Event::StartInstall { host, command }, + ) => { + let next_epoch = epoch + 1; + ( + State { + epoch: next_epoch, + phase: Phase::Installing { host: host.clone() }, + }, + vec![Effect::InstallRemote { + epoch: next_epoch, + host, + command, + }], + ) + } ( Phase::Loading { .. }, Event::RemoteSpawned { @@ -858,6 +907,7 @@ pub mod discovery_machine { ( Phase::Idle | Phase::Loading { .. } + | Phase::Installing { .. } | Phase::Ready | Phase::Failed(_), Event::Completed { @@ -882,6 +932,7 @@ pub mod discovery_machine { ( phase @ (Phase::Idle | Phase::Loading { .. } + | Phase::Installing { .. } | Phase::Ready | Phase::Failed(_)), Event::RemoteSpawned { .. } | Event::Completed { .. }, @@ -1339,6 +1390,25 @@ impl Disktree { } } + /// Install `disktree-cli` into `~/.local/bin/disktree-cli` on `host` over + /// SSH and automatically reconnect once installed. + pub fn install_remote_cli( + &mut self, + host: String, + command: String, + cx: &mut Context<'_, Self>, + ) { + if !self.volumes_open { + return; + } + self.picker_error = None; + self.step_discovery( + discovery_machine::Event::StartInstall { host, command }, + cx, + ); + cx.notify(); + } + fn perform_discovery( &mut self, effect: discovery_machine::Effect, @@ -1356,6 +1426,40 @@ impl Disktree { } } } + discovery_machine::Effect::InstallRemote { + epoch, + host, + command, + } => { + let target = host.clone(); + let task = cx.background_executor().spawn(async move { + disktree_core::remote::install_remote_cli(&target, &command) + }); + cx.spawn(async move |this, cx| { + let result = task.await; + let _ = this.update(cx, |this, cx| { + if !this.volumes_open || this.discovery.epoch != epoch { + return; + } + match result { + Ok(()) => { + this.load_volume_source(Some(host), cx); + } + Err(error) => { + this.step_discovery( + discovery_machine::Event::Completed { + epoch, + outcome: Err(error.to_string()), + }, + cx, + ); + cx.notify(); + } + } + }); + }) + .detach(); + } discovery_machine::Effect::PollRemote { epoch } => { cx.spawn(async move |this, cx| { loop { diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index a945507..2d2462f 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -199,13 +199,111 @@ fn volumes_dialog( .child(dialog_description("Listing mounts…", cx)), ); } + crate::state::discovery_machine::Phase::Installing { host } => { + rows = rows.child(div().p(space::MD).child(dialog_description( + format!("Installing disktree-cli on {host}…"), + cx, + ))); + } crate::state::discovery_machine::Phase::Failed(error) => { - rows = rows.child( - div() - .p(space::MD) - .text_color(theme.danger) - .child(error.clone()), - ); + if let Some(cmd) = disktree_core::remote::install_cli_command(error) + { + let host_name = app + .volumes_source + .clone() + .unwrap_or_else(|| "the server".to_owned()); + let install_host = app.volumes_source.clone(); + let install_cmd = cmd.clone(); + let copy_cmd = cmd.clone(); + rows = rows.child( + div() + .flex() + .flex_col() + .gap(space::SM) + .p(space::MD) + .child( + div().text_color(theme.foreground).child(format!( + "disktree-cli is not installed on {host_name}." + )), + ) + .child( + div() + .p(space::SM) + .bg(theme.surface) + .border_1() + .border_color(theme.divider()) + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(cmd), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::SM) + .when_some(install_host, |row, host| { + let label = format!("Install on {host}"); + let cmd = install_cmd.clone(); + row.child( + button( + "source-install-cli", + label, + ButtonVariant::Primary, + cx, + ) + .debug_selector(|| { + "source-install-cli".into() + }) + .on_click(cx.listener( + move |this, _, _, cx| { + this.install_remote_cli( + host.clone(), + cmd.clone(), + cx, + ); + }, + )), + ) + }) + .child( + button( + "source-copy-install", + "Copy command", + ButtonVariant::Outline, + cx, + ) + .debug_selector(|| { + "source-copy-install".into() + }) + .on_click(cx.listener( + move |this, _, _, cx| { + cx.write_to_clipboard( + gpui_kit::ClipboardItem::new_string( + copy_cmd.clone(), + ), + ); + this.picker_error = None; + this.notice = Some(( + "Copied remote install command" + .into(), + gpui_omarchy::Status::Success, + )); + cx.notify(); + }, + )), + ), + ), + ); + } else { + rows = rows.child( + div() + .p(space::MD) + .text_color(theme.danger) + .child(error.clone()), + ); + } } crate::state::discovery_machine::Phase::Idle | crate::state::discovery_machine::Phase::Ready diff --git a/crates/disktree-cli/Cargo.toml b/crates/disktree-cli/Cargo.toml index 986eba5..95a4342 100644 --- a/crates/disktree-cli/Cargo.toml +++ b/crates/disktree-cli/Cargo.toml @@ -17,11 +17,15 @@ workspace = true anyhow = { workspace = true } clap = { version = "4", features = ["derive"] } crossterm = "0.28" +disktree-core = { path = "../disktree-core", default-features = false } disktree-scanner = { workspace = true } ratatui = "0.29" rustc-hash = { workspace = true } serde = { version = "1", features = ["derive"] } serde_json = "1" +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { version = "1.1", features = ["process"] } + [dev-dependencies] tempfile = "3" diff --git a/crates/disktree-cli/src/main.rs b/crates/disktree-cli/src/main.rs index 3363165..f975c2e 100644 --- a/crates/disktree-cli/src/main.rs +++ b/crates/disktree-cli/src/main.rs @@ -4,6 +4,7 @@ mod cli; mod format; mod json_out; +mod stdio; mod tui; use std::io::{self, IsTerminal as _, Write as _}; @@ -21,6 +22,14 @@ use crate::format::{human_age, human_bytes}; use crate::json_out::{build_document, write_ndjson_line, write_pretty}; fn main() -> Result<()> { + // Fast-path SSH remote protocol mode: skips clap/TUI startup and installs + // kernel resource limits before reading stdin. + let raw_args: Vec = + std::env::args_os().skip(1).collect(); + if raw_args.len() == 1 && raw_args[0] == "--stdio-v1" { + return stdio::serve_stdio_v1().map_err(Into::into); + } + let args = Cli::parse(); let policy = args.cache_policy(); let mode = args.storage_mode(); diff --git a/crates/disktree-cli/src/stdio.rs b/crates/disktree-cli/src/stdio.rs new file mode 100644 index 0000000..15d200d --- /dev/null +++ b/crates/disktree-cli/src/stdio.rs @@ -0,0 +1,88 @@ +//! Read-only `--stdio-v1` SSH remote protocol server. +//! +//! Invoked over SSH by `disktree` (auto-deployed from the portable binary or +//! found on the server's `PATH`). Enforces a 1 GiB address-space ceiling on +//! Linux, a 5-minute wall deadline, and exits immediately if the SSH pipe +//! closes so a blocked filesystem never outlives the connection. + +use std::io::{self, BufReader, BufWriter, Read as _}; +use std::time::Duration; + +pub fn serve_stdio_v1() -> io::Result<()> { + limit_resources()?; + // A live client is not permission to monopolise the server forever, + // including when a filesystem syscall cannot be cancelled. + std::thread::Builder::new() + .name("scan-deadline".into()) + .spawn(|| { + std::thread::park_timeout(Duration::from_mins(5)); + eprintln!( + "Remote scan exceeded five minutes; scan a smaller path." + ); + std::process::exit(1); + })?; + let mut input = BufReader::new(io::stdin()); + let session = disktree_core::remote::read_request(&mut input)?; + if session.watch_disconnect { + std::thread::Builder::new() + .name("scan-connection".into()) + .spawn(move || { + let mut byte = [0]; + loop { + match input.read(&mut byte) { + Err(error) + if error.kind() == io::ErrorKind::Interrupted => {} + Ok(0) => { + // Exit the process, not just a scan task: a + // blocked filesystem must not outlive SSH. + std::process::exit(0); + } + _ => { + eprintln!( + "Remote scan connection closed or sent unexpected input." + ); + std::process::exit(1); + } + } + } + })?; + } + disktree_core::remote::serve_session( + session, + &mut BufWriter::new(io::stdout().lock()), + ) +} + +/// Kernel-enforced, not a sampled RSS check that can miss an allocation +/// burst. Keep this in the helper: never constrain the desktop process. +#[cfg(target_os = "linux")] +fn limit_resources() -> io::Result<()> { + use rustix::process::{Resource, Rlimit, getrlimit, setrlimit}; + + const MAX_ADDRESS_SPACE: u64 = 1 << 30; + let inherited = getrlimit(Resource::As); + let maximum = inherited.maximum.unwrap_or(u64::MAX).min(MAX_ADDRESS_SPACE); + let current = inherited.current.unwrap_or(u64::MAX).min(maximum); + setrlimit( + Resource::As, + Rlimit { + current: Some(current), + maximum: Some(maximum), + }, + )?; + // An allocation failure must not write a potentially huge core dump. + setrlimit( + Resource::Core, + Rlimit { + current: Some(0), + maximum: Some(0), + }, + )?; + Ok(()) +} + +#[cfg(not(target_os = "linux"))] +#[allow(clippy::unnecessary_wraps, reason = "same fallible API as Linux")] +const fn limit_resources() -> io::Result<()> { + Ok(()) +} diff --git a/crates/disktree-scan/tests/stdio.rs b/crates/disktree-cli/tests/stdio.rs similarity index 98% rename from crates/disktree-scan/tests/stdio.rs rename to crates/disktree-cli/tests/stdio.rs index 005a996..b8d5444 100644 --- a/crates/disktree-scan/tests/stdio.rs +++ b/crates/disktree-cli/tests/stdio.rs @@ -14,7 +14,7 @@ fn executable_returns_a_read_only_snapshot() { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("data"); std::fs::write(&file, b"hello").unwrap(); - let mut child = Command::new(env!("CARGO_BIN_EXE_disktree-scan")) + let mut child = Command::new(env!("CARGO_BIN_EXE_disktree-cli")) .arg("--stdio-v1") .stdin(Stdio::piped()) .stdout(Stdio::piped()) @@ -54,7 +54,7 @@ impl Drop for Helper { fn supervised_helper() -> Helper { Helper( - Command::new(env!("CARGO_BIN_EXE_disktree-scan")) + Command::new(env!("CARGO_BIN_EXE_disktree-cli")) .arg("--stdio-v1") .stdin(Stdio::piped()) .stdout(Stdio::piped()) diff --git a/crates/disktree-core/src/deployment.rs b/crates/disktree-core/src/deployment.rs index 557f9aa..f546080 100644 --- a/crates/disktree-core/src/deployment.rs +++ b/crates/disktree-core/src/deployment.rs @@ -16,7 +16,7 @@ case "$size" in ''|*[!0-9]*) exit 2;; esac umask 077 dir="${XDG_CACHE_HOME:-$HOME/.cache}/disktree/ssh/$digest" mkdir -p "$dir" -helper="$dir/disktree-scan" +helper="$dir/disktree-cli" valid() { [ -x "$helper" ] || return 1 actual=$(sha256sum "$helper") || return 1 diff --git a/crates/disktree-core/src/remote.rs b/crates/disktree-core/src/remote.rs index 874d7d1..3432fc8 100644 --- a/crates/disktree-core/src/remote.rs +++ b/crates/disktree-core/src/remote.rs @@ -43,18 +43,84 @@ fn check_platform(platform: &str) -> io::Result<()> { Ok(()) } -// Non-interactive shells often omit ~/.local/bin. Do not require users to -// edit the server's startup files after the documented user-local install. -const REMOTE_COMMAND: &str = r#"if command -v disktree-scan >/dev/null 2>&1; then +// Non-interactive shells often omit ~/.local/bin. Try disktree-cli first, +// falling back to legacy disktree-scan if already present on an older server. +const REMOTE_COMMAND: &str = r#"if command -v disktree-cli >/dev/null 2>&1; then +exec disktree-cli --stdio-v1 +elif [ -x "$HOME/.local/bin/disktree-cli" ]; then +exec "$HOME/.local/bin/disktree-cli" --stdio-v1 +elif command -v disktree-scan >/dev/null 2>&1; then exec disktree-scan --stdio-v1 elif [ -x "$HOME/.local/bin/disktree-scan" ]; then exec "$HOME/.local/bin/disktree-scan" --stdio-v1 else -echo 'disktree-scan is not installed on this server.' >&2 -echo 'On the server, run make install-scan from the disktree checkout.' >&2 +printf 'disktree-cli is not installed on this server (%s %s).\n' "$(uname -s)" "$(uname -m)" >&2 exit 127 fi"#; +/// Base URL where predictable raw `disktree-cli--` binaries live. +pub const RELEASE_DOWNLOAD_BASE: &str = + "https://github.com/tobi/disktree/releases/latest/download"; + +/// When `reason` indicates `disktree-cli` is missing on an SSH server, return +/// the exact one-line command to install it into `~/.local/bin/disktree-cli` +/// for that server's OS and architecture. +#[must_use] +pub fn install_cli_command(reason: &str) -> Option { + if !reason.contains("not installed") && !reason.contains("not found") { + return None; + } + let asset = detected_release_asset(reason); + let url = match asset { + Some(name) => format!("{RELEASE_DOWNLOAD_BASE}/{name}"), + None => format!( + "{RELEASE_DOWNLOAD_BASE}/disktree-cli-$(uname -s | tr A-Z a-z | sed 's/darwin/macos/')-$(uname -m | sed 's/arm64/aarch64/')" + ), + }; + Some(format!( + "mkdir -p ~/.local/bin && curl -fsSL {url} -o ~/.local/bin/disktree-cli && chmod +x ~/.local/bin/disktree-cli" + )) +} + +fn detected_release_asset(reason: &str) -> Option<&'static str> { + let start = reason.find('(')?; + let end = reason[start + 1..].find(')')? + start + 1; + let mut parts = reason[start + 1..end].split_whitespace(); + let os = parts.next()?; + let arch = parts.next()?; + match (os, arch) { + ("Linux", "x86_64" | "amd64") => Some("disktree-cli-linux-x86_64"), + ("Linux", "aarch64" | "arm64") => Some("disktree-cli-linux-aarch64"), + ("Darwin", "arm64" | "aarch64") => Some("disktree-cli-macos-aarch64"), + ("Darwin", "x86_64") => Some("disktree-cli-macos-x86_64"), + _ => None, + } +} + +/// Install `disktree-cli` into `~/.local/bin/disktree-cli` on `host` over SSH +/// using the exact command produced by [`install_cli_command`]. +pub fn install_remote_cli(host: &str, command: &str) -> io::Result<()> { + validate_host(host)?; + let output = Command::new("ssh") + .args(["-T", "--", host, command]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output()?; + if output.status.success() { + return Ok(()); + } + let stderr = read_diagnostics(output.stderr.as_slice()); + let detail = if stderr.is_empty() { + format!("ssh exited with {}", output.status) + } else { + stderr + }; + Err(io::Error::other(format!( + "Could not install disktree-cli on {host}: {detail}" + ))) +} + #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Request { pub root: Option, @@ -550,11 +616,8 @@ fn ssh_error(host: &str, details: &str, fallback: &io::Error) -> io::Error { ) } else if reason.contains("Host key verification failed") { format!("Run ssh {host} in a terminal and verify its host key first.") - } else if reason.contains("not installed") || reason.contains("not found") { - format!( - "Install disktree-scan ON {host}, not on this computer. \ - Run make install-scan from the checkout on the server." - ) + } else if let Some(cmd) = install_cli_command(&reason) { + format!("Install disktree-cli on {host}:\n{cmd}") } else { "No incomplete scan is shown. Retry, or choose another root.".into() }; @@ -815,19 +878,51 @@ mod tests { assert!(error.contains("Permission denied"), "{error}"); assert!(error.contains("verify your credentials"), "{error}"); assert!(!error.contains("truncated"), "{error}"); - assert!(!error.contains("Install disktree-scan"), "{error}"); + assert!(!error.contains("install disktree-cli"), "{error}"); } #[cfg(unix)] #[test] fn missing_helper_diagnostics_name_the_server() { let error = failing_process( - "read -r request; echo 'disktree-scan: command not found' \ - >&2; exit 127", + "read -r request; echo 'disktree-cli is not installed on this \ + server (Linux x86_64).' >&2; exit 127", ) .to_string(); - assert!(error.contains("command not found"), "{error}"); - assert!(error.contains("ON dev, not on this computer"), "{error}"); + assert!(error.contains("not installed"), "{error}"); + assert!(error.contains("Install disktree-cli on dev"), "{error}"); + assert!( + error + .contains("releases/latest/download/disktree-cli-linux-x86_64"), + "{error}" + ); + } + + #[test] + fn install_cli_command_picks_the_servers_os_and_arch() { + for (reason, asset) in [ + ( + "disktree-cli is not installed on this server (Linux x86_64).", + "disktree-cli-linux-x86_64", + ), + ( + "disktree-cli is not installed on this server (Linux aarch64).", + "disktree-cli-linux-aarch64", + ), + ( + "disktree-cli is not installed on this server (Darwin arm64).", + "disktree-cli-macos-aarch64", + ), + ( + "disktree-cli is not installed on this server (Darwin x86_64).", + "disktree-cli-macos-x86_64", + ), + ] { + let cmd = install_cli_command(reason).expect("install command"); + assert!(cmd.contains(asset), "{cmd}"); + assert!(cmd.contains("~/.local/bin/disktree-cli"), "{cmd}"); + } + assert!(install_cli_command("Permission denied").is_none()); } #[cfg(unix)] @@ -919,7 +1014,7 @@ mod tests { let bin = home.path().join(".local/bin"); std::fs::create_dir_all(&bin).unwrap(); let helper = std::env::var("DISKTREE_TEST_HELPER").unwrap(); - std::os::unix::fs::symlink(helper, bin.join("disktree-scan")).unwrap(); + std::os::unix::fs::symlink(helper, bin.join("disktree-cli")).unwrap(); // Force the documented ~/.local/bin fallback, not the ambient PATH. let remote = format!( "HOME={} PATH=/nonexistent; export HOME PATH;\n{REMOTE_COMMAND}", @@ -1013,7 +1108,7 @@ mod tests { let cached = cache .join("disktree/ssh") .join(&entry.sha256) - .join("disktree-scan"); + .join("disktree-cli"); let request = Request { root: Some(data.path().into()), options: ScanOptions { @@ -1045,7 +1140,7 @@ mod tests { std::fs::rename(damaged, &cached).unwrap(); } } - assert!(!home.path().join(".local/bin/disktree-scan").exists()); + assert!(!home.path().join(".local/bin/disktree-cli").exists()); } #[cfg(unix)] diff --git a/crates/disktree-scan/Cargo.toml b/crates/disktree-scan/Cargo.toml deleted file mode 100644 index 1a61756..0000000 --- a/crates/disktree-scan/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "disktree-scan" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -description = "Read-only headless scanner for disktree SSH sessions" - -[lints] -workspace = true - -[dependencies] -disktree-core = { path = "../disktree-core", default-features = false } - -[target.'cfg(target_os = "linux")'.dependencies] -rustix = { version = "1.1", features = ["process"] } - -[dev-dependencies] -serde_json = "1" -tempfile = "3" diff --git a/crates/disktree-scan/src/main.rs b/crates/disktree-scan/src/main.rs deleted file mode 100644 index 2b9ad57..0000000 --- a/crates/disktree-scan/src/main.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! Headless helper: no GPUI dependency and no destructive command surface. -use std::io::{self, BufReader, BufWriter, Read as _}; -use std::time::Duration; - -fn main() -> io::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - if args == ["--stdio-v1"] { - limit_resources()?; - // A live client is not permission to monopolise the server forever, - // including when a filesystem syscall cannot be cancelled. - std::thread::Builder::new() - .name("scan-deadline".into()) - .spawn(|| { - std::thread::park_timeout(Duration::from_mins(5)); - eprintln!( - "Remote scan exceeded five minutes; scan a smaller path." - ); - std::process::exit(1); - })?; - let mut input = BufReader::new(io::stdin()); - let session = disktree_core::remote::read_request(&mut input)?; - if session.watch_disconnect { - std::thread::Builder::new() - .name("scan-connection".into()) - .spawn(move || { - let mut byte = [0]; - loop { - match input.read(&mut byte) { - Err(error) if error.kind() == io::ErrorKind::Interrupted => {} - Ok(0) => { - // Exit the process, not just a scan task: a - // blocked filesystem must not outlive SSH. - std::process::exit(0); - } - _ => { - eprintln!("Remote scan connection closed or sent unexpected input."); - std::process::exit(1); - } - } - } - })?; - } - disktree_core::remote::serve_session( - session, - &mut BufWriter::new(io::stdout().lock()), - ) - } else if args.is_empty() || args == ["--help"] || args == ["-h"] { - println!( - "disktree-scan — read-only SSH scan helper\n\ - usage: disktree-scan --stdio-v1\n\ - Used by: disktree ssh HOST [PATH]\n\ - Reads a versioned JSON request from stdin and streams a \ - snapshot to stdout. No deletion commands." - ); - Ok(()) - } else { - Err(io::Error::other("unknown option; try --help")) - } -} - -/// Kernel-enforced, not a sampled RSS check that can miss an allocation -/// burst. Keep this in the helper: never constrain the desktop process. -#[cfg(target_os = "linux")] -fn limit_resources() -> io::Result<()> { - use rustix::process::{Resource, Rlimit, getrlimit, setrlimit}; - - const MAX_ADDRESS_SPACE: u64 = 1 << 30; - let inherited = getrlimit(Resource::As); - let maximum = inherited.maximum.unwrap_or(u64::MAX).min(MAX_ADDRESS_SPACE); - let current = inherited.current.unwrap_or(u64::MAX).min(maximum); - setrlimit( - Resource::As, - Rlimit { - current: Some(current), - maximum: Some(maximum), - }, - )?; - // An allocation failure must not write a potentially huge core dump. - setrlimit( - Resource::Core, - Rlimit { - current: Some(0), - maximum: Some(0), - }, - )?; - Ok(()) -} - -#[cfg(not(target_os = "linux"))] -#[allow(clippy::unnecessary_wraps, reason = "same fallible API as Linux")] -const fn limit_resources() -> io::Result<()> { - Ok(()) -} diff --git a/packaging/install.sh b/packaging/install.sh index 92e1a4d..dec89a5 100755 --- a/packaging/install.sh +++ b/packaging/install.sh @@ -17,6 +17,9 @@ VERSION=$(cat "$here/VERSION") install -d "$BINDIR" "$APPDIR" "$ICONDIR" install -m755 "$here/disktree" "$BINDIR/disktree" +if [ -f "$here/disktree-cli" ]; then + install -m755 "$here/disktree-cli" "$BINDIR/disktree-cli" +fi install -m644 "$here/disktree.svg" "$ICONDIR/disktree.svg" sed -e "s|@BINDIR@|$BINDIR|" -e "s|@VERSION@|$VERSION|" \ "$here/disktree.desktop.in" > "$APPDIR/disktree.desktop" diff --git a/scripts/test-ssh.ts b/scripts/test-ssh.ts index 121a740..14460fc 100644 --- a/scripts/test-ssh.ts +++ b/scripts/test-ssh.ts @@ -45,11 +45,11 @@ try { const root = process.env.DISKTREE_PROFILE_ROOT; if (!root.startsWith(join(tmpdir(), 'disktree-profile-'))) throw new Error('Only disposable profile fixtures allowed'); const binary = join(process.cwd(), 'target/release/examples/profile_remote'); - const helper = join(process.cwd(), `target/${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl/release/disktree-scan`); + const helper = join(process.cwd(), `target/${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl/release/disktree-cli`); for (const mode of ['ssh-plain', 'ssh']) { for (let trial=0; trial<5; trial++) run(binary, [mode,root,client,helper]); } - } else run('cargo',['test','-p','disktree-core','real_ssh_transport_','--','--ignored','--nocapture'], {...process.env,DISKTREE_TEST_SSH_CONFIG:client,DISKTREE_TEST_HELPER:join(process.cwd(),`target/${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl/release/disktree-scan`),DISKTREE_TEST_ARCHIVE:join(process.cwd(),'target/portable/disktree')}); + } else run('cargo',['test','-p','disktree-core','real_ssh_transport_','--','--ignored','--nocapture'], {...process.env,DISKTREE_TEST_SSH_CONFIG:client,DISKTREE_TEST_HELPER:join(process.cwd(),`target/${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl/release/disktree-cli`),DISKTREE_TEST_ARCHIVE:join(process.cwd(),'target/portable/disktree')}); console.log(`${process.env.DISKTREE_PROFILE_ROOT ? 'SSH PROFILING COMPLETE' : 'REAL SSH SCAN PASSED'}. Temporary host key, client key and server will be removed.`); } finally { if (server && server.exitCode === null) { diff --git a/xtask/src/portable.rs b/xtask/src/portable.rs index b101dfb..1f96c29 100644 --- a/xtask/src/portable.rs +++ b/xtask/src/portable.rs @@ -43,7 +43,7 @@ pub fn build() -> Result<(), String> { "--release", "--locked", "-p", - "disktree-scan", + "disktree-cli", "--target", &triple, ]) @@ -58,7 +58,7 @@ pub fn build() -> Result<(), String> { } helpers.push(( arch.into(), - target.join(triple).join("release/disktree-scan"), + target.join(triple).join("release/disktree-cli"), )); } let output = target.join("portable/disktree");