mirror of
https://github.com/tobi/disktree.git
synced 2026-11-28 08:00:53 +00:00
app: explore SSH scans read-only and export host-guarded cleanup
This commit is contained in:
@@ -42,6 +42,9 @@ use state::Disktree;
|
||||
#[derive(Debug)]
|
||||
struct Args {
|
||||
root: PathBuf,
|
||||
remote: Option<String>,
|
||||
remote_disk: bool,
|
||||
check: bool,
|
||||
options: ScanOptions,
|
||||
depth: u32,
|
||||
power: Option<power::PowerEfficiency>,
|
||||
@@ -51,6 +54,15 @@ const USAGE: &str = "\
|
||||
disktree — a treemap of what is using your disk
|
||||
|
||||
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
|
||||
~/.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.
|
||||
Use --check with ssh to deploy and scan without opening a window.
|
||||
|
||||
arguments:
|
||||
PATH directory to scan (default: the home directory)
|
||||
@@ -91,6 +103,9 @@ fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
if extract_scanner()? {
|
||||
return Ok(());
|
||||
}
|
||||
let saved = power::settings_path()
|
||||
.map_or_else(
|
||||
|| Ok(power::PowerEfficiency::default()),
|
||||
@@ -102,6 +117,37 @@ fn run() -> Result<()> {
|
||||
});
|
||||
let args = parse_args_with_power(std::env::args_os().skip(1), saved)?;
|
||||
|
||||
if args.check {
|
||||
let host = args
|
||||
.remote
|
||||
.as_deref()
|
||||
.context("--check requires disktree ssh HOST")?;
|
||||
let scan = disktree_core::remote::RemoteScan::spawn(
|
||||
host,
|
||||
&disktree_core::remote::Request {
|
||||
root: (!args.root.as_os_str().is_empty())
|
||||
.then(|| args.root.clone()),
|
||||
disk: args.remote_disk,
|
||||
options: args.options,
|
||||
},
|
||||
)?;
|
||||
loop {
|
||||
if let Some(result) = scan.poll() {
|
||||
let snapshot = result?;
|
||||
println!(
|
||||
"{}:{} — {} bytes, {} files, {} directories",
|
||||
host,
|
||||
snapshot.header.root.display(),
|
||||
snapshot.tree.bytes,
|
||||
snapshot.tree.files,
|
||||
snapshot.tree.dirs
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
// When the app executable is reached through the command-line symlink,
|
||||
// cmux sends SIGTERM to its foreground process group as AppKit takes
|
||||
// focus. Spawn once into a separate group before AppKit starts. Restrict
|
||||
@@ -179,10 +225,12 @@ fn run() -> Result<()> {
|
||||
appearance::follow(window);
|
||||
}
|
||||
cx.new(|cx| {
|
||||
let mut app = Disktree::new(
|
||||
let mut app = Disktree::open(
|
||||
root_for_app.clone(),
|
||||
options.clone(),
|
||||
depth,
|
||||
args.remote.clone(),
|
||||
args.remote_disk,
|
||||
cx,
|
||||
);
|
||||
app.power_choice = args.power;
|
||||
@@ -203,6 +251,37 @@ fn run() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Extraction works without a display or GPUI initialization.
|
||||
fn extract_scanner() -> Result<bool> {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args.first().is_none_or(|arg| arg != "extract-scanner") {
|
||||
return Ok(false);
|
||||
}
|
||||
anyhow::ensure!(
|
||||
args.len() == 3,
|
||||
"usage: disktree extract-scanner ARCH OUTPUT"
|
||||
);
|
||||
let archive = disktree_core::payload::Archive::current()?
|
||||
.context("no embedded scanners; build with cargo xtask portable")?;
|
||||
let arch = args[1].to_str().context("ARCH must be x86_64 or aarch64")?;
|
||||
let (_, bytes) = archive.load(arch)?;
|
||||
let mut output = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&args[2])?;
|
||||
std::io::Write::write_all(&mut output, &bytes)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
output.set_permissions(std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
println!(
|
||||
"Extracted Linux {arch} scanner to {}",
|
||||
PathBuf::from(&args[2]).display()
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Read the command line, program name already skipped.
|
||||
#[cfg(test)]
|
||||
fn parse_args(args: impl Iterator<Item = std::ffi::OsString>) -> Result<Args> {
|
||||
@@ -210,7 +289,7 @@ fn parse_args(args: impl Iterator<Item = std::ffi::OsString>) -> Result<Args> {
|
||||
}
|
||||
|
||||
fn parse_args_with_power(
|
||||
mut args: impl Iterator<Item = std::ffi::OsString>,
|
||||
args: impl Iterator<Item = std::ffi::OsString>,
|
||||
preset: power::PowerEfficiency,
|
||||
) -> Result<Args> {
|
||||
let mut root: Option<PathBuf> = None;
|
||||
@@ -229,6 +308,16 @@ fn parse_args_with_power(
|
||||
.and_then(|value| value.into_string().ok())
|
||||
.with_context(|| need.to_owned())
|
||||
};
|
||||
let mut check = false;
|
||||
let mut args = args.peekable();
|
||||
let remote = if args.peek().is_some_and(|arg| arg == "ssh") {
|
||||
args.next();
|
||||
let host = text(args.next(), "ssh needs a host, e.g. disktree ssh dev")?;
|
||||
disktree_core::remote::validate_host(&host)?;
|
||||
Some(host)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.to_str().unwrap_or_default() {
|
||||
@@ -244,6 +333,7 @@ fn parse_args_with_power(
|
||||
"-x" | "--one-filesystem" => options.one_filesystem = true,
|
||||
"-X" | "--cross-filesystems" => options.one_filesystem = false,
|
||||
"-D" | "--disk" => disk = true,
|
||||
"--check" => check = true,
|
||||
"-d" | "--depth" => {
|
||||
let value = text(args.next(), "--depth needs a number")?;
|
||||
depth = value.parse().context("--depth needs a number")?;
|
||||
@@ -333,6 +423,17 @@ fn parse_args_with_power(
|
||||
!(disk && root.is_some()),
|
||||
"--disk and a PATH cannot be combined"
|
||||
);
|
||||
if remote.is_some() {
|
||||
return Ok(Args {
|
||||
root: root.unwrap_or_default(),
|
||||
remote,
|
||||
remote_disk: disk,
|
||||
check,
|
||||
power,
|
||||
options,
|
||||
depth,
|
||||
});
|
||||
}
|
||||
let home = std::env::home_dir();
|
||||
let root = match root {
|
||||
_ if disk => home
|
||||
@@ -354,6 +455,9 @@ fn parse_args_with_power(
|
||||
|
||||
Ok(Args {
|
||||
root,
|
||||
remote: None,
|
||||
remote_disk: false,
|
||||
check,
|
||||
options,
|
||||
depth: depth.clamp(1, 6),
|
||||
power,
|
||||
@@ -431,6 +535,38 @@ mod argument_tests {
|
||||
assert_eq!(args.options.threads.system_cpu_limit, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ssh_keeps_worker_options_without_inspecting_the_remote_root() {
|
||||
let args = parse_args(
|
||||
[
|
||||
"ssh",
|
||||
"dev",
|
||||
"--check",
|
||||
"--scan-threads",
|
||||
"4",
|
||||
"/only-on-the-remote-machine",
|
||||
]
|
||||
.into_iter()
|
||||
.map(std::ffi::OsString::from),
|
||||
)
|
||||
.expect("remote arguments");
|
||||
assert_eq!(args.remote.as_deref(), Some("dev"));
|
||||
assert!(args.check);
|
||||
assert_eq!(args.options.threads.max_threads, 4);
|
||||
assert_eq!(args.root, PathBuf::from("/only-on-the-remote-machine"));
|
||||
assert!(args.power.is_none());
|
||||
|
||||
let args = parse_args(
|
||||
["ssh", "dev", "--disk"]
|
||||
.into_iter()
|
||||
.map(std::ffi::OsString::from),
|
||||
)
|
||||
.expect("remote volume");
|
||||
assert!(args.remote_disk);
|
||||
assert!(args.root.as_os_str().is_empty());
|
||||
assert!(args.power.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_power_is_loaded_before_cli_overrides() {
|
||||
use power::PowerEfficiency as Power;
|
||||
|
||||
@@ -61,12 +61,12 @@ impl Marks {
|
||||
|
||||
/// Re-read sizes from a freshly scanned tree and drop marks whose path no
|
||||
/// longer exists, so the tally never claims space that is already gone.
|
||||
pub fn refresh(&mut self, root_path: &Path, root: &Node, metric: Metric) {
|
||||
pub fn refresh(&mut self, root_path: &Path, root: &Node, _metric: Metric) {
|
||||
let mut resolved = Vec::with_capacity(self.items.len());
|
||||
for item in &self.items {
|
||||
match find(root_path, root, &item.path) {
|
||||
Some(node) => resolved.push(Target {
|
||||
bytes: node.value(metric),
|
||||
bytes: node.bytes,
|
||||
is_dir: node.is_dir(),
|
||||
hidden: is_hidden(&item.path),
|
||||
path: item.path.clone(),
|
||||
|
||||
@@ -325,6 +325,11 @@ pub struct RunSummary {
|
||||
pub struct Disktree {
|
||||
/// The directory the tree was scanned from.
|
||||
pub root_path: PathBuf,
|
||||
pub remote: Option<String>,
|
||||
remote_disk: bool,
|
||||
pub remote_scan: Option<disktree_core::remote::RemoteScan>,
|
||||
remote_platform: String,
|
||||
pub remote_identity: Option<disktree_core::identity::HostIdentity>,
|
||||
pub home: Option<PathBuf>,
|
||||
pub options: ScanOptions,
|
||||
pub power_choice: Option<crate::power::PowerEfficiency>,
|
||||
@@ -458,17 +463,39 @@ pub struct Disktree {
|
||||
}
|
||||
|
||||
impl Disktree {
|
||||
#[cfg(test)]
|
||||
pub fn new(
|
||||
root_path: PathBuf,
|
||||
options: ScanOptions,
|
||||
depth: u32,
|
||||
cx: &mut Context<'_, Self>,
|
||||
) -> Self {
|
||||
let home = std::env::home_dir();
|
||||
let space = space_info(&root_path).ok();
|
||||
Self::open(root_path, options, depth, None, false, cx)
|
||||
}
|
||||
|
||||
pub fn open(
|
||||
root_path: PathBuf,
|
||||
options: ScanOptions,
|
||||
depth: u32,
|
||||
remote: Option<String>,
|
||||
remote_disk: bool,
|
||||
cx: &mut Context<'_, Self>,
|
||||
) -> Self {
|
||||
let local = remote.is_none();
|
||||
let home = if local { std::env::home_dir() } else { None };
|
||||
let space = if local {
|
||||
space_info(&root_path).ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let trash_backend = detect_trash_backend();
|
||||
let mut tree = Self {
|
||||
root_path,
|
||||
remote,
|
||||
remote_disk,
|
||||
remote_scan: None,
|
||||
remote_platform: String::new(),
|
||||
remote_identity: None,
|
||||
home,
|
||||
options,
|
||||
power_choice: None,
|
||||
@@ -552,18 +579,22 @@ impl Disktree {
|
||||
scan_elapsed: None,
|
||||
scanned_at: now_seconds(),
|
||||
};
|
||||
tree.device = device_for(&tree.root_path);
|
||||
tree.full_disk_access = tree
|
||||
.home
|
||||
.as_deref()
|
||||
.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);
|
||||
tree.file_table = file_table_readable(&tree.root_path);
|
||||
disktree_core::removal::prime_mount_points();
|
||||
if local {
|
||||
tree.device = device_for(&tree.root_path);
|
||||
tree.full_disk_access = tree
|
||||
.home
|
||||
.as_deref()
|
||||
.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);
|
||||
tree.file_table = file_table_readable(&tree.root_path);
|
||||
disktree_core::removal::prime_mount_points();
|
||||
}
|
||||
tree.start_scan(cx);
|
||||
Self::start_space_ticker(cx);
|
||||
if local {
|
||||
Self::start_space_ticker(cx);
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
@@ -597,6 +628,12 @@ impl Disktree {
|
||||
/// Scan a different root from scratch. Marks are kept; a mark outside
|
||||
/// the new root is shown as kept back, never removed.
|
||||
pub fn set_root(&mut self, root: PathBuf, cx: &mut Context<'_, Self>) {
|
||||
if self.remote.is_some() {
|
||||
self.root_path = root;
|
||||
self.remote_disk = false;
|
||||
self.start_scan(cx);
|
||||
return;
|
||||
}
|
||||
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
|
||||
@@ -615,6 +652,10 @@ impl Disktree {
|
||||
/// where it is reached, so only what is new at the wider level is read,
|
||||
/// and the current view stays on screen until the wider tree lands.
|
||||
pub fn widen_to(&mut self, above: PathBuf, cx: &mut Context<'_, Self>) {
|
||||
if self.remote.is_some() {
|
||||
self.set_root(above, cx);
|
||||
return;
|
||||
}
|
||||
let Some(tree) = self.tree.clone() else {
|
||||
self.set_root(above, cx);
|
||||
return;
|
||||
@@ -650,6 +691,9 @@ impl Disktree {
|
||||
/// is left alone until a volume is picked; picking calls [`set_root`],
|
||||
/// which cancels it.
|
||||
pub fn open_volumes(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
self.volume_epoch += 1;
|
||||
let epoch = self.volume_epoch;
|
||||
let root_path = self.root_path.clone();
|
||||
@@ -761,7 +805,10 @@ impl Disktree {
|
||||
|
||||
/// Ask git about `path` once, off the UI thread, if it is a checkout.
|
||||
pub fn ensure_git(&mut self, path: &Path, cx: &Context<'_, Self>) {
|
||||
if self.git.contains_key(path) || self.git_pending.contains(path) {
|
||||
if self.remote.is_some()
|
||||
|| self.git.contains_key(path)
|
||||
|| self.git_pending.contains(path)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let path = path.to_path_buf();
|
||||
@@ -801,6 +848,14 @@ impl Disktree {
|
||||
/// were the whole one: a first scan leaves the panel saying it stopped,
|
||||
/// and a widening scan leaves the tree it started from on screen.
|
||||
pub fn cancel_scan(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.remote_scan.take().is_some() {
|
||||
self.scan_epoch += 1;
|
||||
self.progress.cancelled = true;
|
||||
self.progress.finished = true;
|
||||
self.scan_elapsed = self.scan_started.map(|t| t.elapsed());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
let Some(scan) = self.scan.take() else {
|
||||
return;
|
||||
};
|
||||
@@ -940,6 +995,24 @@ impl Disktree {
|
||||
self.scan_started = Some(Instant::now());
|
||||
self.scan_elapsed = None;
|
||||
self.scan_root.clone_from(&self.root_path);
|
||||
self.remote_scan = None;
|
||||
if let Some(host) = &self.remote {
|
||||
let request = disktree_core::remote::Request {
|
||||
root: (!self.root_path.as_os_str().is_empty())
|
||||
.then(|| self.root_path.clone()),
|
||||
disk: self.remote_disk,
|
||||
options: self.options.clone(),
|
||||
};
|
||||
match disktree_core::remote::RemoteScan::spawn(host, &request) {
|
||||
Ok(scan) => {
|
||||
self.remote_scan = Some(scan);
|
||||
Self::poll_scan(epoch, cx);
|
||||
}
|
||||
Err(error) => self.scan_error = Some(error.to_string()),
|
||||
}
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
self.scan = Some(ScanHandle::spawn(
|
||||
self.root_path.clone(),
|
||||
self.options.clone(),
|
||||
@@ -976,6 +1049,42 @@ impl Disktree {
|
||||
if epoch != self.scan_epoch {
|
||||
return false;
|
||||
}
|
||||
if let Some(scan) = &self.remote_scan {
|
||||
let Some(outcome) = scan.poll() else {
|
||||
cx.notify();
|
||||
return true;
|
||||
};
|
||||
match outcome {
|
||||
Ok(snapshot) => {
|
||||
self.root_path = snapshot.header.root;
|
||||
self.home = snapshot.header.home;
|
||||
self.disk_root = snapshot.header.disk_root;
|
||||
self.space = snapshot.header.space;
|
||||
self.remote_platform = snapshot.header.platform;
|
||||
self.remote_identity = snapshot.header.identity;
|
||||
self.device = self.remote.as_ref().map(|host| {
|
||||
format!("{host} · read-only · space at scan")
|
||||
});
|
||||
let node = snapshot.tree;
|
||||
self.marks.refresh(
|
||||
&self.root_path,
|
||||
&node,
|
||||
self.options.metric,
|
||||
);
|
||||
self.tree = Some(Arc::new(node));
|
||||
self.refresh_insights();
|
||||
self.select_largest(cx);
|
||||
self.scan_elapsed = self.scan_started.map(|t| t.elapsed());
|
||||
}
|
||||
Err(error) => {
|
||||
self.scan_error = Some(error.to_string());
|
||||
}
|
||||
}
|
||||
self.remote_scan = None;
|
||||
self.progress.finished = true;
|
||||
cx.notify();
|
||||
return false;
|
||||
}
|
||||
let Some(scan) = &self.scan else {
|
||||
return false;
|
||||
};
|
||||
@@ -1749,7 +1858,7 @@ impl Disktree {
|
||||
Some(Target {
|
||||
hidden: is_hidden(&path),
|
||||
path,
|
||||
bytes: node.value(self.options.metric),
|
||||
bytes: node.bytes,
|
||||
is_dir: node.is_dir(),
|
||||
})
|
||||
}
|
||||
@@ -1767,6 +1876,25 @@ impl Disktree {
|
||||
|
||||
/// The plan the review screen shows and the removal runs.
|
||||
pub fn plan(&self) -> Plan {
|
||||
if self.remote.is_some() {
|
||||
// Never judge remote paths against this machine's filesystem.
|
||||
// This is an export selection, not an executable removal plan.
|
||||
let mut selection = Plan::default();
|
||||
selection.targets = self
|
||||
.marks
|
||||
.items()
|
||||
.iter()
|
||||
.filter(|target| {
|
||||
target.path != self.root_path
|
||||
&& target.path.starts_with(&self.root_path)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
selection.root.clone_from(&self.root_path);
|
||||
// Remote volume attribution is unknown; never infer it from
|
||||
// this computer's mounts or project an unmeasured saving.
|
||||
return selection;
|
||||
}
|
||||
plan(self.marks.items(), &self.root_path)
|
||||
}
|
||||
|
||||
@@ -2111,7 +2239,7 @@ impl Disktree {
|
||||
/// The review screen's commit: move to the trash at once, or ask first for
|
||||
/// a permanent deletion, which cannot be undone.
|
||||
pub fn commit(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.plan().is_empty() {
|
||||
if self.remote.is_some() || self.plan().is_empty() {
|
||||
return;
|
||||
}
|
||||
match self.removal_mode {
|
||||
@@ -2182,6 +2310,9 @@ impl Disktree {
|
||||
}
|
||||
|
||||
pub fn begin_removal(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let plan = self.plan();
|
||||
if plan.is_empty() {
|
||||
self.notice = Some(("nothing is marked".into(), Status::Warning));
|
||||
@@ -2401,7 +2532,10 @@ impl Disktree {
|
||||
|
||||
/// 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>) {
|
||||
pub fn open_folder(&self, cx: &Context<'_, Self>) {
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let chosen = cx.prompt_for_paths(gpui_kit::PathPromptOptions {
|
||||
files: false,
|
||||
directories: true,
|
||||
@@ -2432,18 +2566,34 @@ impl Disktree {
|
||||
/// Save what the plan would act on as a list of paths, one per line,
|
||||
/// wherever the user chooses: for a script, or for later.
|
||||
pub fn save_delete_list(&mut self, cx: &mut Context<'_, Self>) {
|
||||
self.save_export(false, cx);
|
||||
}
|
||||
|
||||
pub fn save_delete_script(&mut self, cx: &mut Context<'_, Self>) {
|
||||
self.save_export(true, cx);
|
||||
}
|
||||
|
||||
fn save_export(&mut self, script: bool, cx: &mut Context<'_, Self>) {
|
||||
let plan = self.plan();
|
||||
if plan.is_empty() {
|
||||
self.notice = Some(("nothing to save".into(), Status::Warning));
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
let list = disktree_core::export::delete_list(&plan.targets);
|
||||
let list = if script {
|
||||
self.delete_script(&plan.targets)
|
||||
} else {
|
||||
disktree_core::export::delete_list(&plan.targets)
|
||||
};
|
||||
let count = plan.targets.len();
|
||||
let directory =
|
||||
self.home.clone().unwrap_or_else(|| self.root_path.clone());
|
||||
let chosen = cx
|
||||
.prompt_for_new_path(&directory, Some("disktree-delete-list.txt"));
|
||||
std::env::home_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
let filename = if script {
|
||||
"disktree-delete.sh"
|
||||
} else {
|
||||
"disktree-delete-list.txt"
|
||||
};
|
||||
let chosen = cx.prompt_for_new_path(&directory, Some(filename));
|
||||
cx.spawn(async move |this, cx| {
|
||||
let Ok(Ok(Some(path))) = chosen.await else {
|
||||
return;
|
||||
@@ -2470,6 +2620,35 @@ impl Disktree {
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn delete_script(&self, targets: &[Target]) -> String {
|
||||
let identity = if self.remote.is_some() {
|
||||
self.remote_identity.clone()
|
||||
} else {
|
||||
disktree_core::identity::HostIdentity::current()
|
||||
};
|
||||
disktree_core::export::delete_script_for(
|
||||
targets,
|
||||
&self.root_path,
|
||||
self.remote.as_deref(),
|
||||
identity.as_ref(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn copy_delete_script(&mut self, cx: &mut Context<'_, Self>) {
|
||||
let plan = self.plan();
|
||||
if plan.is_empty() {
|
||||
self.notice = Some(("nothing to copy".into(), Status::Warning));
|
||||
} else {
|
||||
let script = self.delete_script(&plan.targets);
|
||||
cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(script));
|
||||
self.notice = Some((
|
||||
"copied delete script; previews by default, checks host before deletion".into(),
|
||||
Status::Success,
|
||||
));
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Copy instructions for a coding agent to free the space by removing
|
||||
/// what the plan would act on, after checking each path.
|
||||
pub fn copy_agent_prompt(&mut self, cx: &mut Context<'_, Self>) {
|
||||
@@ -2479,11 +2658,30 @@ impl Disktree {
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
let prompt = disktree_core::export::agent_prompt(
|
||||
&plan.targets,
|
||||
&self.root_path,
|
||||
self.space,
|
||||
);
|
||||
let mut prompt = if self.remote.is_some() {
|
||||
disktree_core::export::agent_prompt_for(
|
||||
&plan.targets,
|
||||
&self.root_path,
|
||||
self.space,
|
||||
&self.remote_platform,
|
||||
self.remote_identity.as_ref(),
|
||||
)
|
||||
} else {
|
||||
disktree_core::export::agent_prompt(
|
||||
&plan.targets,
|
||||
&self.root_path,
|
||||
self.space,
|
||||
)
|
||||
};
|
||||
if let Some(host) = &self.remote {
|
||||
prompt = format!(
|
||||
"The scan is from remote SSH host {host} ({}), NOT this \
|
||||
computer. All paths below belong to that server. Connect \
|
||||
via SSH; verify the host and paths before acting. \
|
||||
Free space is a snapshot, not live.\n\n{prompt}",
|
||||
self.remote_platform
|
||||
);
|
||||
}
|
||||
cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(prompt));
|
||||
let count = plan.targets.len();
|
||||
self.notice = Some((
|
||||
@@ -2499,6 +2697,9 @@ impl Disktree {
|
||||
|
||||
/// Show the tile a key acts on in Finder (or the file manager), selected.
|
||||
pub fn reveal_target(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.remote.is_some() {
|
||||
return;
|
||||
}
|
||||
let crumbs =
|
||||
self.action_target().unwrap_or_else(|| self.crumbs.clone());
|
||||
let Some(path) = self.path_at(&crumbs) else {
|
||||
@@ -2679,7 +2880,9 @@ impl Disktree {
|
||||
"backspace" | "u" if !control => self.ascend(cx),
|
||||
// A filter is the first thing Escape takes away.
|
||||
"escape" if self.matches.is_some() => self.clear_filter(),
|
||||
"escape" if self.scan.is_some() => self.cancel_scan(cx),
|
||||
"escape" if self.scan.is_some() || self.remote_scan.is_some() => {
|
||||
self.cancel_scan(cx);
|
||||
}
|
||||
"escape" => {
|
||||
if self.selected.is_some() {
|
||||
self.selected = None;
|
||||
@@ -2753,6 +2956,13 @@ impl Disktree {
|
||||
}
|
||||
|
||||
fn on_review_key(&mut self, key: &str, cx: &mut Context<'_, Self>) {
|
||||
if self.remote.is_some() && matches!(key, "m" | "p" | "enter") {
|
||||
return;
|
||||
}
|
||||
if key == "e" {
|
||||
self.save_delete_script(cx);
|
||||
return;
|
||||
}
|
||||
match key {
|
||||
"escape" => {
|
||||
self.screen = Screen::Explore;
|
||||
@@ -2770,6 +2980,7 @@ impl Disktree {
|
||||
}
|
||||
"s" => self.save_delete_list(cx),
|
||||
"a" => self.copy_agent_prompt(cx),
|
||||
"y" => self.copy_delete_script(cx),
|
||||
"?" => {
|
||||
self.show_help = true;
|
||||
cx.notify();
|
||||
@@ -3049,7 +3260,7 @@ impl Disktree {
|
||||
/// Declined, nothing changes. Not while a removal runs: quitting would
|
||||
/// stop a permanent delete halfway.
|
||||
pub fn restart_as_administrator(&mut self, cx: &mut Context<'_, Self>) {
|
||||
if self.restarting || self.run.is_some() {
|
||||
if self.remote.is_some() || self.restarting || self.run.is_some() {
|
||||
return;
|
||||
}
|
||||
self.restarting = true;
|
||||
@@ -3192,7 +3403,10 @@ impl Render for Disktree {
|
||||
// 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 · {}",
|
||||
"disktree{} · {}",
|
||||
self.remote.as_ref().map_or_else(String::new, |host| {
|
||||
format!(" · {host} · read-only")
|
||||
}),
|
||||
crate::marks::display_path(
|
||||
&self.current_path(),
|
||||
self.home.as_deref()
|
||||
|
||||
@@ -92,6 +92,66 @@ fn read<R>(
|
||||
view.read_with(cx, |app, _| f(app))
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn remote_review_never_deletes_even_through_direct_actions(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, cx| {
|
||||
app.remote = Some("dev".into());
|
||||
let crumbs = app.crumbs_for_path(&temp.path().join("junk")).unwrap();
|
||||
app.select(Some(crumbs), cx);
|
||||
app.toggle_mark_selected(cx);
|
||||
app.screen = Screen::Review;
|
||||
});
|
||||
draw(cx);
|
||||
press(cx, "enter");
|
||||
press(cx, "p");
|
||||
press(cx, "m");
|
||||
update(&view, cx, |app, cx| {
|
||||
app.commit(cx);
|
||||
app.confirm_delete(cx);
|
||||
app.begin_removal(cx);
|
||||
assert!(!app.confirm_open);
|
||||
assert!(app.run.is_none());
|
||||
assert_eq!(app.screen, Screen::Review);
|
||||
let selection = app.plan();
|
||||
assert_eq!(selection.targets.len(), 1);
|
||||
assert!(selection.bytes() > 0);
|
||||
assert_eq!(selection.reclaim(), 0);
|
||||
assert_eq!(selection.foreign(), 0);
|
||||
assert_eq!(selection.unattributed(), selection.bytes());
|
||||
app.open_volumes(cx);
|
||||
app.restart_as_administrator(cx);
|
||||
assert!(!app.volumes_open);
|
||||
assert!(!app.restarting);
|
||||
});
|
||||
draw(cx);
|
||||
assert!(temp.path().join("junk/blob.bin").exists());
|
||||
assert!(temp.path().join("keep/notes.txt").exists());
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn a_failed_remote_scan_stops_showing_the_reading_screen(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, _| {
|
||||
app.tree = None;
|
||||
app.scan = None;
|
||||
app.remote = Some("dev".into());
|
||||
app.scan_error =
|
||||
Some("SSH dev: Permission denied (publickey,password).".into());
|
||||
});
|
||||
draw(cx);
|
||||
assert!(cx.debug_bounds("scan-error").is_some());
|
||||
assert!(cx.debug_bounds("scan-reading").is_none());
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn the_window_draws_a_treemap_with_tiles(cx: &mut TestAppContext) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
@@ -791,6 +851,50 @@ fn the_review_screen_copies_the_list_as_an_agent_prompt(
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui_kit::test]
|
||||
fn remote_review_copies_host_guarded_script_and_prompt(
|
||||
cx: &mut TestAppContext,
|
||||
) {
|
||||
cx.update(gpui_omarchy::init);
|
||||
let temp = fixture();
|
||||
let (view, cx) = view_over(temp.path(), cx);
|
||||
update(&view, cx, |app, cx| {
|
||||
app.remote = Some("dev-alias".into());
|
||||
app.remote_identity = Some(disktree_core::identity::HostIdentity {
|
||||
hostname: "actual-server".into(),
|
||||
machine_id: Some("abcdefabcdefabcdefabcdefabcdefab".into()),
|
||||
});
|
||||
app.marks.toggle(disktree_core::removal::Target {
|
||||
path: temp.path().join("junk"),
|
||||
bytes: 300_000,
|
||||
is_dir: true,
|
||||
hidden: false,
|
||||
});
|
||||
app.screen = Screen::Review;
|
||||
cx.notify();
|
||||
});
|
||||
draw(cx);
|
||||
press(cx, "y");
|
||||
let script = cx
|
||||
.read_from_clipboard()
|
||||
.and_then(|item| item.text())
|
||||
.expect("script on clipboard");
|
||||
assert!(script.contains("actual-server"));
|
||||
assert!(script.contains("/etc/machine-id"));
|
||||
assert!(script.contains("Wrong hostname"));
|
||||
assert!(script.contains("ssh -T"));
|
||||
assert!(script.contains("PREVIEW ONLY"));
|
||||
press(cx, "a");
|
||||
let prompt = cx
|
||||
.read_from_clipboard()
|
||||
.and_then(|item| item.text())
|
||||
.expect("prompt on clipboard");
|
||||
assert!(prompt.contains("actual-server"));
|
||||
assert!(prompt.contains("abcdefabcdefabcdefabcdefabcdefab"));
|
||||
assert!(prompt.contains("MANDATORY HOST CHECK"));
|
||||
assert!(temp.path().join("junk/blob.bin").exists());
|
||||
}
|
||||
|
||||
/// Escape in the alert dialog cancels: the dialog closes, the review screen
|
||||
/// stays, and nothing on disk changes.
|
||||
#[gpui_kit::test]
|
||||
|
||||
@@ -66,7 +66,7 @@ pub fn root(
|
||||
.on_action(cx.listener(
|
||||
|this, _: &crate::app_menu::OpenFolder, _, cx| {
|
||||
if this.can_start_over() {
|
||||
Disktree::open_folder(cx);
|
||||
this.open_folder(cx);
|
||||
}
|
||||
},
|
||||
))
|
||||
@@ -409,6 +409,9 @@ fn explore(
|
||||
|
||||
/// The selection, when it is a checkout git can say something about.
|
||||
fn selection_checkout(app: &Disktree) -> Option<std::path::PathBuf> {
|
||||
if app.remote.is_some() {
|
||||
return None;
|
||||
}
|
||||
let target = app.action_target()?;
|
||||
let node = app.node_at(&target)?;
|
||||
if !node.is_dir() {
|
||||
@@ -1442,7 +1445,8 @@ fn selection_section(
|
||||
))
|
||||
.child(widgets::bar(share, highlight, cx));
|
||||
|
||||
let fourth = if node.is_dir()
|
||||
let fourth = if app.remote.is_none()
|
||||
&& node.is_dir()
|
||||
&& let Some(path) = &path
|
||||
&& crate::git::is_checkout(path)
|
||||
{
|
||||
@@ -1939,7 +1943,11 @@ fn administrator_line(
|
||||
theme: &Theme,
|
||||
cx: &Context<'_, Disktree>,
|
||||
) -> Option<Div> {
|
||||
if app.administrator != Some(false) || app.restarting || app.run.is_some() {
|
||||
if app.remote.is_some()
|
||||
|| app.administrator != Some(false)
|
||||
|| app.restarting
|
||||
|| app.run.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let errors = app.progress.errors;
|
||||
@@ -2254,7 +2262,7 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
.child(format!("{:.1}\u{00d7}", app.view.scale)),
|
||||
);
|
||||
}
|
||||
let scan = if app.scan.is_some() {
|
||||
let scan = if app.scan.is_some() || app.remote_scan.is_some() {
|
||||
format!(
|
||||
"scanning \u{00b7} {} entries \u{00b7} {}",
|
||||
widgets::human_count(app.progress.files),
|
||||
@@ -2286,13 +2294,46 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
|
||||
/// What the viewport shows while the first scan is running.
|
||||
fn scanning_panel(
|
||||
app: &Disktree,
|
||||
theme: &Theme,
|
||||
cx: &Context<'_, Disktree>,
|
||||
app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>,
|
||||
) -> Div {
|
||||
if let Some(error) = &app.scan_error {
|
||||
return div()
|
||||
.debug_selector(|| "scan-error".into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_1()
|
||||
.min_h_0()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(space::LG)
|
||||
.bg(theme.inset)
|
||||
.child(
|
||||
gpui_omarchy::icon(gpui_omarchy::IconName::X)
|
||||
.size(icon::LG)
|
||||
.text_color(theme.danger),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::TITLE)
|
||||
.text_color(theme.bright)
|
||||
.child("Scan failed"),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.max_w(size::HELP)
|
||||
.p(space::MD)
|
||||
.border_1()
|
||||
.border_color(theme.danger)
|
||||
.text_color(theme.danger)
|
||||
.text_size(text::BODY)
|
||||
.child(error.clone()),
|
||||
)
|
||||
.child(widgets::hint("r", "retry scan", cx));
|
||||
}
|
||||
let progress = &app.progress;
|
||||
let cancelled = app.scan.is_none() && progress.cancelled;
|
||||
let mut panel = div()
|
||||
let cancelled = app.scan.is_none() && app.remote_scan.is_none() && progress.cancelled;
|
||||
div()
|
||||
.debug_selector(|| "scan-reading".into())
|
||||
.flex()
|
||||
.flex_col()
|
||||
.flex_1()
|
||||
@@ -2366,7 +2407,7 @@ fn scanning_panel(
|
||||
}),
|
||||
)
|
||||
// A failed scan has nothing left to cancel either.
|
||||
.child(if app.scan.is_none() {
|
||||
.child(if app.scan.is_none() && app.remote_scan.is_none() {
|
||||
button("scan-again", "Scan again", ButtonVariant::Outline, cx)
|
||||
.on_click(cx.listener(|this, _, window, cx| {
|
||||
this.start_scan(cx);
|
||||
@@ -2378,21 +2419,7 @@ fn scanning_panel(
|
||||
this.cancel_scan(cx);
|
||||
window.focus(&this.focus, cx);
|
||||
}))
|
||||
});
|
||||
|
||||
if let Some(error) = &app.scan_error {
|
||||
panel = panel.child(
|
||||
div()
|
||||
.max_w(size::HELP)
|
||||
.p(space::MD)
|
||||
.border_1()
|
||||
.border_color(theme.danger)
|
||||
.text_color(theme.danger)
|
||||
.text_size(text::BODY)
|
||||
.child(error.clone()),
|
||||
);
|
||||
}
|
||||
panel
|
||||
})
|
||||
}
|
||||
|
||||
fn find_field(app: &Disktree, theme: &Theme) -> Div {
|
||||
@@ -2739,13 +2766,20 @@ fn review_summary(
|
||||
cx,
|
||||
);
|
||||
|
||||
let explanation = match app.removal_mode {
|
||||
RemovalMode::Trash => format!(
|
||||
"Recoverable from the trash until it is emptied. Uses {}.",
|
||||
app.trash_backend.label()
|
||||
),
|
||||
RemovalMode::Permanent => {
|
||||
"Deleted at once, like rm -rf. Nothing is recoverable.".to_string()
|
||||
let explanation = if app.remote.is_some() {
|
||||
"Read-only SSH session. Export the selection; nothing is \
|
||||
deleted here. Free space is sampled at scan time."
|
||||
.to_string()
|
||||
} else {
|
||||
match app.removal_mode {
|
||||
RemovalMode::Trash => format!(
|
||||
"Recoverable from the trash until it is emptied. Uses {}.",
|
||||
app.trash_backend.label()
|
||||
),
|
||||
RemovalMode::Permanent => {
|
||||
"Deleted at once, like rm -rf. Nothing is recoverable."
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2765,7 +2799,7 @@ fn review_summary(
|
||||
.flex_col()
|
||||
.gap(space::SM)
|
||||
.child(widgets::section("What happens", cx))
|
||||
.child(mode)
|
||||
.children(app.remote.is_none().then_some(mode))
|
||||
.child(
|
||||
div()
|
||||
.text_size(text::CAPTION)
|
||||
@@ -2846,7 +2880,7 @@ fn review_summary(
|
||||
.child(div().flex_1())
|
||||
.children(notice_line(app, theme, cx))
|
||||
.child(export_controls(plan, cx))
|
||||
.child(commit_controls(app, plan, cx))
|
||||
.children(app.remote.is_none().then(|| commit_controls(app, plan, cx)))
|
||||
}
|
||||
|
||||
/// The list handed on instead of acted on: saved as paths, or copied as a
|
||||
@@ -2857,7 +2891,7 @@ fn export_controls(
|
||||
) -> Div {
|
||||
div()
|
||||
.flex()
|
||||
.flex_row()
|
||||
.flex_col()
|
||||
.justify_end()
|
||||
.gap(space::SM)
|
||||
.child(
|
||||
@@ -2884,6 +2918,30 @@ fn export_controls(
|
||||
this.copy_agent_prompt(cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
button(
|
||||
"save-script",
|
||||
"Save delete script…",
|
||||
ButtonVariant::Secondary,
|
||||
cx,
|
||||
)
|
||||
.disabled(plan.is_empty())
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
this.save_delete_script(cx);
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
button(
|
||||
"copy-script",
|
||||
"Copy delete script",
|
||||
ButtonVariant::Secondary,
|
||||
cx,
|
||||
)
|
||||
.disabled(plan.is_empty())
|
||||
.on_click(cx.listener(|this, _, _, cx| {
|
||||
this.copy_delete_script(cx);
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// The screen's one commitment. Moving to the trash is the default commit,
|
||||
@@ -2948,9 +3006,23 @@ fn review_footer(app: &Disktree, theme: &Theme, cx: &App) -> Div {
|
||||
.py(space::SM)
|
||||
.border_t_1()
|
||||
.border_color(theme.divider())
|
||||
.child(widgets::hint("enter", commit, cx))
|
||||
.child(widgets::hint("m", "trash", cx))
|
||||
.child(widgets::hint("p", "permanent", cx))
|
||||
.children(
|
||||
app.remote
|
||||
.is_none()
|
||||
.then(|| widgets::hint("enter", commit, cx)),
|
||||
)
|
||||
.children(
|
||||
app.remote
|
||||
.is_none()
|
||||
.then(|| widgets::hint("m", "trash", cx)),
|
||||
)
|
||||
.children(
|
||||
app.remote
|
||||
.is_none()
|
||||
.then(|| widgets::hint("p", "permanent", cx)),
|
||||
)
|
||||
.child(widgets::hint("e", "save script", cx))
|
||||
.child(widgets::hint("y", "copy script", cx))
|
||||
.child(widgets::hint("!", "unmark all", cx))
|
||||
.child(widgets::hint("s", "save list", cx))
|
||||
.child(widgets::hint("a", "copy as prompt", cx))
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
use std::fmt::Write as _;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::identity::HostIdentity;
|
||||
use crate::removal::Target;
|
||||
use crate::size::human_bytes;
|
||||
use crate::space::SpaceInfo;
|
||||
@@ -44,6 +45,23 @@ pub fn agent_prompt(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
space: Option<SpaceInfo>,
|
||||
) -> String {
|
||||
agent_prompt_for(
|
||||
targets,
|
||||
root,
|
||||
space,
|
||||
platform(),
|
||||
HostIdentity::current().as_ref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Same prompt, with the scanned machine's platform rather than the UI host's.
|
||||
pub fn agent_prompt_for(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
space: Option<SpaceInfo>,
|
||||
platform: &str,
|
||||
identity: Option<&HostIdentity>,
|
||||
) -> String {
|
||||
let total: u64 = targets.iter().map(|target| target.bytes).sum();
|
||||
let mut prompt = String::new();
|
||||
@@ -52,10 +70,35 @@ pub fn agent_prompt(
|
||||
"I need to free up disk space on this {} machine. I used disktree \
|
||||
to look through {} and picked the directories and files below for \
|
||||
deletion, {} in all.",
|
||||
platform(),
|
||||
platform,
|
||||
line(root).text(),
|
||||
human_bytes(total),
|
||||
);
|
||||
if let Some(identity) = identity {
|
||||
let _ = writeln!(
|
||||
prompt,
|
||||
"\nMANDATORY HOST CHECK before any destructive action:\n\
|
||||
Run hostname on the target and require the exact value {}.\n\
|
||||
An SSH alias is not proof of machine identity.",
|
||||
shell_quote(&identity.hostname),
|
||||
);
|
||||
if let Some(id) = &identity.machine_id {
|
||||
let _ = writeln!(
|
||||
prompt,
|
||||
"Read /etc/machine-id on the target and require {}.",
|
||||
shell_quote(id)
|
||||
);
|
||||
}
|
||||
prompt.push_str(
|
||||
"If either check fails, cannot be performed, or differs, STOP \
|
||||
and ask me. Do not delete anything or bypass these checks.\n",
|
||||
);
|
||||
} else {
|
||||
prompt.push_str(
|
||||
"\nHOST IDENTITY WAS NOT CAPTURED. Before deleting anything, STOP \
|
||||
and ask me to confirm the actual target hostname and machine ID.\n",
|
||||
);
|
||||
}
|
||||
if let Some(space) = space {
|
||||
let _ = writeln!(
|
||||
prompt,
|
||||
@@ -107,6 +150,131 @@ pub fn agent_prompt(
|
||||
prompt
|
||||
}
|
||||
|
||||
/// A POSIX shell literal, including embedded quotes. Never interpolate paths
|
||||
/// as shell source, even when the path came from our own scanner.
|
||||
pub fn shell_quote(text: &str) -> String {
|
||||
format!("'{}'", text.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
/// Export only; preview by default.
|
||||
///
|
||||
/// Remote scripts send their payload to the
|
||||
/// named SSH host, so running the export locally cannot remove local paths.
|
||||
/// GNU/Linux tools are required. This is deliberately more conservative than
|
||||
/// the app: symlinks and changed canonical paths are refused.
|
||||
pub fn delete_script(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
host: Option<&str>,
|
||||
) -> String {
|
||||
let identity = if host.is_none() {
|
||||
HostIdentity::current()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
delete_script_for(targets, root, host, identity.as_ref())
|
||||
}
|
||||
|
||||
/// Use the identity captured by the scanner, not the UI machine or SSH alias.
|
||||
pub fn delete_script_for(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
host: Option<&str>,
|
||||
identity: Option<&HostIdentity>,
|
||||
) -> String {
|
||||
let mut body = String::from("set -eu\n");
|
||||
body.push_str(&host_guard(identity));
|
||||
body.push_str(
|
||||
"command -v realpath >/dev/null\ncommand -v findmnt >/dev/null\n",
|
||||
);
|
||||
let _ = writeln!(body, "root={}", shell_quote(&root.to_string_lossy()));
|
||||
body.push_str(r#"remove() {
|
||||
p=$1
|
||||
case "$root" in /) prefix=/;; *) prefix=$root/;; esac
|
||||
case "$p" in "$prefix"*) ;; *) echo "Outside scan: $p" >&2; return 1;; esac
|
||||
[ "$p" != "$root" ] || return 1
|
||||
real=$(realpath -e -- "$p") || return 1
|
||||
[ "$real" = "$p" ] || {
|
||||
echo "Changed or linked path: $p" >&2; return 1;
|
||||
}
|
||||
case "$HOME/" in "$p/"*) echo "Contains home: $p" >&2; return 1;; esac
|
||||
for system in /etc /usr /boot /bin /sbin /lib /lib64 /dev /proc /sys /run /var/lib /nix /gnu; do
|
||||
case "$p/" in "$system/"*) echo "System path: $p" >&2; return 1;; esac
|
||||
case "$system/" in "$p/"*) echo "Contains system: $p" >&2; return 1;; esac
|
||||
done
|
||||
mounts=$(findmnt -rn --raw -o TARGET) || return 1
|
||||
printf '%s\n' "$mounts" | while IFS= read -r mount; do
|
||||
mount=$(env printf '%b' "$mount") || exit 1
|
||||
case "$mount/" in "$p/"*) echo "Contains mount: $p" >&2; exit 1;; esac
|
||||
done
|
||||
rm -rf --one-file-system --preserve-root=all -- "$p"
|
||||
}
|
||||
"#);
|
||||
for target in targets {
|
||||
if let Line::Plain(path) = line(&target.path) {
|
||||
let _ = writeln!(body, "remove {}", shell_quote(&path));
|
||||
}
|
||||
}
|
||||
let mut script = String::from(
|
||||
r#"#!/bin/sh
|
||||
(
|
||||
# Generated by disktree; review every path before running.
|
||||
# GNU/Linux only. Races, shared blocks and changed sizes are possible.
|
||||
# This is NOT a substitute for checking git work and tool-owned data.
|
||||
set -eu
|
||||
if [ "${1-}" != --delete ]; then
|
||||
"#,
|
||||
);
|
||||
let preview = format!(
|
||||
"PREVIEW ONLY. Target: {}. Review this script, then pass --delete.\n{}",
|
||||
host.unwrap_or("this machine"),
|
||||
delete_list(targets)
|
||||
);
|
||||
let _ = writeln!(
|
||||
script,
|
||||
"printf '%s\\n' {}\nexit 0\nfi",
|
||||
shell_quote(&preview)
|
||||
);
|
||||
if let Some(host) = host {
|
||||
let _ = writeln!(
|
||||
script,
|
||||
"printf '%s' {} | ssh -T -- {} 'sh -s'",
|
||||
shell_quote(&body),
|
||||
shell_quote(host)
|
||||
);
|
||||
} else {
|
||||
script.push_str(&body);
|
||||
}
|
||||
script.push_str("\n)\n");
|
||||
script
|
||||
}
|
||||
|
||||
fn host_guard(identity: Option<&HostIdentity>) -> String {
|
||||
let Some(identity) = identity else {
|
||||
return "echo 'Refusing deletion: scan has no host identity.' >&2\n\
|
||||
exit 1\n"
|
||||
.into();
|
||||
};
|
||||
let mut guard = String::from(
|
||||
"# Refuse to operate on any machine other than the scanned host.\n\
|
||||
IFS= read -r actual_host < /proc/sys/kernel/hostname || exit 1\n",
|
||||
);
|
||||
let _ = writeln!(
|
||||
guard,
|
||||
"[ \"$actual_host\" = {} ] || {{ echo 'Wrong hostname; refusing deletion.' >&2; exit 1; }}",
|
||||
shell_quote(&identity.hostname),
|
||||
);
|
||||
if let Some(id) = &identity.machine_id {
|
||||
guard.push_str("IFS= read -r actual_id < /etc/machine-id || exit 1\n");
|
||||
let _ = writeln!(
|
||||
guard,
|
||||
"[ \"$actual_id\" = {} ] || {{ echo 'Wrong machine ID; refusing deletion.' >&2; exit 1; }}",
|
||||
shell_quote(id),
|
||||
);
|
||||
}
|
||||
guard
|
||||
}
|
||||
|
||||
/// How a path can be written on one line.
|
||||
enum Line {
|
||||
/// As it is.
|
||||
@@ -168,6 +336,141 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn scripts_quote_paths_preview_and_remove_only_the_selection() {
|
||||
use std::process::Command;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let chosen = dir.path().join("quote'; $(touch injected)");
|
||||
let keep = dir.path().join("keep");
|
||||
std::fs::write(&chosen, b"chosen").unwrap();
|
||||
std::fs::write(&keep, b"keep").unwrap();
|
||||
let targets = [target(chosen.to_str().unwrap(), 6, false)];
|
||||
let script_path = dir.path().join("export.sh");
|
||||
let script = delete_script(&targets, dir.path(), None);
|
||||
std::fs::write(&script_path, script).unwrap();
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg("-n")
|
||||
.arg(&script_path)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg(&script_path)
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(chosen.exists(), "preview never deletes");
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg(&script_path)
|
||||
.arg("--delete")
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(!chosen.exists());
|
||||
assert!(keep.exists());
|
||||
|
||||
let remote = delete_script(&targets, dir.path(), Some("dev"));
|
||||
assert!(remote.contains("| ssh -T -- 'dev'"));
|
||||
std::fs::write(&script_path, remote).unwrap();
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg("-n")
|
||||
.arg(&script_path)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg(&script_path)
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn scripts_refuse_paths_reached_through_symlinks() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let keep = outside.path().join("keep");
|
||||
std::fs::write(&keep, b"keep").unwrap();
|
||||
symlink(outside.path(), dir.path().join("link")).unwrap();
|
||||
let path = dir.path().join("link/keep");
|
||||
let script = delete_script(
|
||||
&[target(path.to_str().unwrap(), 4, false)],
|
||||
dir.path(),
|
||||
None,
|
||||
);
|
||||
let file = dir.path().join("export.sh");
|
||||
std::fs::write(&file, script).unwrap();
|
||||
assert!(
|
||||
!std::process::Command::new("sh")
|
||||
.arg(file)
|
||||
.arg("--delete")
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(keep.exists());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn wrong_host_missing_identity_and_wrong_machine_id_cannot_delete() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("keep");
|
||||
std::fs::write(&file, b"keep").unwrap();
|
||||
let targets = [target(file.to_str().unwrap(), 4, false)];
|
||||
let actual = HostIdentity::current().unwrap();
|
||||
let mut wrong_host = actual.clone();
|
||||
wrong_host.hostname = "this-is-not-the-scanned-host".into();
|
||||
let mut wrong_id = actual.clone();
|
||||
wrong_id.machine_id = Some("00000000000000000000000000000000".into());
|
||||
for identity in [Some(wrong_host), Some(wrong_id), None] {
|
||||
let script = delete_script_for(
|
||||
&targets,
|
||||
dir.path(),
|
||||
None,
|
||||
identity.as_ref(),
|
||||
);
|
||||
let path = dir.path().join("script.sh");
|
||||
std::fs::write(&path, script).unwrap();
|
||||
let output = std::process::Command::new("sh")
|
||||
.arg(path)
|
||||
.arg("--delete")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(file.exists(), "host check must precede removal");
|
||||
}
|
||||
let prompt = agent_prompt_for(
|
||||
&targets,
|
||||
dir.path(),
|
||||
None,
|
||||
"linux",
|
||||
Some(&actual),
|
||||
);
|
||||
assert!(prompt.contains("MANDATORY HOST CHECK"));
|
||||
assert!(prompt.contains(&actual.hostname));
|
||||
if let Some(id) = actual.machine_id {
|
||||
assert!(prompt.contains(&id));
|
||||
}
|
||||
assert!(prompt.contains("Do not delete anything or bypass"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_is_one_path_per_line() {
|
||||
let targets = [
|
||||
|
||||
Reference in New Issue
Block a user