From e67e40f8c41521e7b88f6787a188f005224057ca Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:59:58 -0700 Subject: [PATCH 01/13] fix: escape untrusted text in worktree, clone and plugin output; store write failures fail the command Rebased onto meta-git-safety as one commit (both changed the same worktree code). Keeps that PR's create rollback, remove and prune checks, and adds this PR's part: - Each child worktree destination is checked to stay inside the set before git adds it. - remove and prune fail, instead of warning, when the store cannot be updated; remove reads the record before deleting. - One repo given twice on different branches is refused. - Names, paths, git output and errors printed by worktree, clone, update and ssh go through meta_core::display::escape. - Two safety tests that used a worktrees_dir the config rules refuse ('.' and '../link') assert the refusal, or use a link inside the workspace. Implements [[tasks/harmony-2749]] --- Cargo.toml | 4 +- src/clone_worker.rs | 39 ++++++++++-- src/commands/worktree/add.rs | 31 ++++++---- src/commands/worktree/create.rs | 101 ++++++++++++++++++++++++-------- src/commands/worktree/diff.rs | 3 +- src/commands/worktree/exec.rs | 57 +++++++++++++----- src/commands/worktree/list.rs | 34 ++++++++--- src/commands/worktree/mod.rs | 49 +++------------- src/commands/worktree/prune.rs | 29 +++++++-- src/commands/worktree/remove.rs | 22 ++++--- src/commands/worktree/status.rs | 6 +- src/commit.rs | 20 ++++--- src/lib.rs | 4 +- src/main.rs | 10 ++++ src/ssh.rs | 10 ++-- src/update.rs | 12 +++- tests/safety.rs | 15 +++-- 17 files changed, 300 insertions(+), 146 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 90e59bf..37179c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ name = "meta_git_cli" path = "src/lib.rs" [dependencies] +tempfile = "3.3" meta_plugin_protocol = { path = "../meta_plugin_protocol" } meta_core = { path = "../meta_core" } meta_git_lib = { path = "../meta_git_lib" } @@ -33,6 +34,3 @@ console = "0.15" log = "0.4" colored = "2" indexmap = "2" - -[dev-dependencies] -tempfile = "3.3" diff --git a/src/clone_worker.rs b/src/clone_worker.rs index 9e37db4..da862fb 100644 --- a/src/clone_worker.rs +++ b/src/clone_worker.rs @@ -29,6 +29,8 @@ pub(crate) fn clone_with_queue( let work_signal = Arc::new((Mutex::new(false), Condvar::new())); let ssh_cmd = Arc::new(ssh_cmd.map(|s| s.to_string())); + // Nested .meta configs that failed to parse or validate + let nested_errors = Arc::new(Mutex::new(Vec::new())); // Spawn worker threads let handles: Vec<_> = (0..parallelism) @@ -39,6 +41,7 @@ pub(crate) fn clone_with_queue( let mp = mp.clone(); let style = spinner_style.clone(); let ssh_cmd = Arc::clone(&ssh_cmd); + let nested_errors = Arc::clone(&nested_errors); std::thread::spawn(move || { loop { @@ -61,7 +64,13 @@ pub(crate) fn clone_with_queue( pb.enable_steady_tick(Duration::from_millis(100)); // Clone the repo (this may add new tasks to queue) - clone_single_repo(&task, &queue, &pb, ssh_cmd.as_deref()); + clone_single_repo( + &task, + &queue, + &pb, + ssh_cmd.as_deref(), + &nested_errors, + ); // Mark worker as inactive active.fetch_sub(1, Ordering::SeqCst); @@ -98,6 +107,15 @@ pub(crate) fn clone_with_queue( handle.join().expect("Worker thread panicked"); } + // A nested config that is refused leaves its repos uncloned, so the + // command must not report success + let errors = nested_errors.lock().unwrap_or_else(|e| e.into_inner()); + if !errors.is_empty() { + anyhow::bail!( + "Could not read nested .meta configs:\n{}", + errors.join("\n") + ); + } Ok(()) } @@ -112,11 +130,12 @@ pub(crate) fn report_failures(queue: &CloneQueue) -> Option { eprintln!( "{} {} ({})", style("Failed to clone").red().bold(), - failure.name, - failure.url + meta_core::display::escape(&failure.name), + meta_core::display::escape(&failure.url) ); + // git's error names paths from the filesystem for line in failure.error.lines() { - eprintln!(" {line}"); + eprintln!(" {}", meta_core::display::escape(line)); } } let (finished, _) = queue.get_counts(); @@ -137,7 +156,14 @@ fn clone_single_repo( queue: &Arc, pb: &ProgressBar, ssh_cmd: Option<&str>, + nested_errors: &Mutex>, ) { + let record = |e: anyhow::Error| { + nested_errors + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(format!(" {}: {e:#}", task.name)); + }; // Skip if target exists if task.target_path.exists() && task @@ -153,6 +179,7 @@ fn clone_single_repo( // Still mark as completed and check for nested .meta if let Err(e) = queue.mark_completed(task) { debug!("Failed to check nested .meta for {}: {}", task.name, e); + record(e); } return; } @@ -179,7 +206,8 @@ fn clone_single_repo( let pb_clone = pb.clone(); let task_name = task.name.clone(); let tail = StderrTail::spawn(child.stderr.take(), move |line| { - pb_clone.set_message(format!("{task_name}: {line}")) + // git's progress names paths from the filesystem + pb_clone.set_message(format!("{task_name}: {}", meta_core::display::escape(line))) }); let status = child.wait(); @@ -211,6 +239,7 @@ fn clone_single_repo( style(format!("Cloned {} (meta parse error: {})", task.name, e)) .yellow() )); + record(e); } } } diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index 7969a5c..5e1f73d 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -1,5 +1,6 @@ -use anyhow::Result; +use anyhow::{Context, Result}; use colored::*; +use meta_core::display::{escape, escape_path}; use meta_cli::worktree::discover_worktree_repos; use meta_git_lib::worktree::git_ops::git_worktree_add; @@ -9,7 +10,7 @@ use meta_git_lib::worktree::types::*; use super::cli_types::AddArgs; -pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) -> Result<()> { +pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> { let name = &args.name; validate_worktree_name(name)?; @@ -25,10 +26,10 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) let meta_dir = require_meta_dir()?; let worktree_root = resolve_worktree_root(Some(&meta_dir))?; - let wt_dir = worktree_root.join(name); + let wt_dir = worktree_set_dir(&worktree_root, name)?; if !wt_dir.exists() { - anyhow::bail!("Worktree '{}' not found at {}", name, wt_dir.display()); + anyhow::bail!("Worktree '{}' not found at {}", name, escape_path(&wt_dir)); } // Check existing repos in the worktree @@ -47,6 +48,14 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) // Preserve the full alias as the destination path so that relative // references (e.g., Cargo.toml workspace members) remain valid. let dest = wt_dir.join(&spec.alias); + // A checkout already in the worktree (such as the root repo's) may + // hold a symlink where this one goes; git must not follow it out + meta_core::config::resolve_inside(&wt_dir, &spec.alias).map_err(|why| { + anyhow::anyhow!( + "Refusing to add the worktree for '{}': {why}", + escape(&spec.alias) + ) + })?; // Ensure parent directories exist for nested paths (e.g., "vendor/") if let Some(parent) = dest.parent() { @@ -58,9 +67,9 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) if verbose { eprintln!( "Adding worktree for '{}' at {} (branch: {})", - spec.alias, - dest.display(), - branch + escape(&spec.alias), + escape_path(&dest), + escape(&branch) ); } @@ -75,7 +84,9 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) // Update centralized store let new_repos: Vec = added.iter().map(StoreRepoEntry::from).collect(); - super::warn_store_error(store_extend_repos(&wt_dir, new_repos), strict)?; + store_extend_repos(&wt_dir, new_repos).with_context(|| { + format!("Added repos to worktree '{name}', but could not update the worktree store") + })?; if json { let output = AddOutput { @@ -89,9 +100,9 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool) println!( "{} Added '{}' to worktree '{}' (branch: {}{})", "✓".green(), - r.alias, + escape(&r.alias), name, - r.branch, + escape(&r.branch), branch_note ); } diff --git a/src/commands/worktree/create.rs b/src/commands/worktree/create.rs index ced5d31..90098f0 100644 --- a/src/commands/worktree/create.rs +++ b/src/commands/worktree/create.rs @@ -1,6 +1,7 @@ use anyhow::{Context, Result}; use chrono::Utc; use colored::*; +use meta_core::display::{escape, escape_path}; use std::collections::{HashMap, HashSet}; use meta_cli::dependency_graph::{DependencyGraph, ProjectDependencies}; @@ -66,6 +67,25 @@ pub(crate) fn handle_create( if repo_specs.is_empty() && !use_all { anyhow::bail!("Specify repos with --repo or use --all"); } + // A repeated --repo is one worktree; two branches for it cannot both be + // checked out there, and keeping one would drop the other unnoticed + for (i, spec) in repo_specs.iter().enumerate() { + let other = repo_specs + .iter() + .skip(i + 1) + .find(|o| o.alias == spec.alias && o.branch != spec.branch); + if let Some(other) = other { + let branch = |s: &meta_git_lib::worktree::RepoSpec| { + escape(s.branch.as_deref().unwrap_or("(default)")).into_owned() + }; + anyhow::bail!( + "Repo '{}' is given twice, on branches '{}' and '{}'", + escape(&spec.alias), + branch(spec), + branch(other) + ); + } + } let nearest_meta_dir = require_meta_dir()?; let meta_dir = if recursive { @@ -76,12 +96,12 @@ pub(crate) fn handle_create( let worktree_root = resolve_worktree_root(Some(&meta_dir))?; // Check if worktree already exists - let wt_dir = worktree_root.join(name); + let wt_dir = worktree_set_dir(&worktree_root, name)?; if wt_dir.exists() { anyhow::bail!( "Worktree '{}' already exists at {}. Use 'meta worktree remove {}' first.", name, - wt_dir.display(), + escape_path(&wt_dir), name ); } @@ -141,8 +161,11 @@ pub(crate) fn handle_create( // For nested aliases like "gitkb/core", ensure intermediate meta: true // parents ("gitkb") get worktrees too — the thin spine from root to target. - let repos_to_create = + let mut repos_to_create = ensure_intermediate_parents(&meta_dir, repos_to_create, name, branch_flag)?; + // One worktree per alias: a repeated --repo would try the same add twice + let mut seen = HashSet::new(); + repos_to_create.retain(|(alias, _, _)| seen.insert(alias.clone())); if dry_run { let plan = CreateDryRunPlan { @@ -160,7 +183,6 @@ pub(crate) fn handle_create( } // Resolve/apply --from-pr: get PR head branch, override branch for the matching repo, and fetch - let mut repos_to_create = repos_to_create; let from_pr_info = from_pr_spec.map(resolve_from_pr).transpose()?; if let Some((ref pr_repo_spec, _pr_num, ref pr_branch)) = from_pr_info { let (alias, source, branch) = repos_to_create @@ -184,9 +206,12 @@ pub(crate) fn handle_create( } if let Err(e) = std::fs::create_dir(&wt_dir) { if e.kind() == std::io::ErrorKind::AlreadyExists { - anyhow::bail!("Worktree '{name}' already exists at {}", wt_dir.display()); + anyhow::bail!( + "Worktree '{name}' already exists at {}", + escape_path(&wt_dir) + ); } - return Err(e).with_context(|| format!("Cannot create {}", wt_dir.display())); + return Err(e).with_context(|| format!("Cannot create {}", escape_path(&wt_dir))); } // Anything that fails from here rolls back what this call created. @@ -203,8 +228,8 @@ pub(crate) fn handle_create( if verbose { eprintln!( "Creating meta repo worktree at {} (branch: {})", - wt_dir.display(), - branch + escape_path(&wt_dir), + escape(branch) ); } let created_branch = journal_new_branch(source, branch, &mut new_branches, || { @@ -235,6 +260,14 @@ pub(crate) fn handle_create( // "vendor/tree-sitter-markdown" -> "vendor/tree-sitter-markdown" // Simple aliases are unchanged: "core" -> "core" let dest = wt_dir.join(alias); + // A checkout already in the worktree (such as the root repo's) may + // hold a symlink where this one goes; git must not follow it out + meta_core::config::resolve_inside(&wt_dir, alias).map_err(|why| { + anyhow::anyhow!( + "Refusing to add the worktree for '{}': {why}", + escape(alias) + ) + })?; // Ensure parent directories exist for nested paths (e.g., "vendor/") if let Some(parent) = dest.parent() { @@ -246,9 +279,9 @@ pub(crate) fn handle_create( if verbose { eprintln!( "Creating worktree for '{}' at {} (branch: {})", - alias, - dest.display(), - branch + escape(alias), + escape_path(&dest), + escape(branch) ); } @@ -322,11 +355,16 @@ pub(crate) fn handle_create( "{} Created worktree '{}' at {}", "✓".green(), name.bold(), - wt_dir.display() + escape_path(&wt_dir) ); for r in &created_repos { let branch_note = if r.created_branch { " (new)" } else { "" }; - println!(" {} -> {}{}", r.alias, r.branch, branch_note); + println!( + " {} -> {}{}", + escape(&r.alias), + escape(&r.branch), + branch_note + ); } if ephemeral { println!(" {}", "[ephemeral]".dimmed()); @@ -374,7 +412,7 @@ fn journal_new_branch( .context(format!( "branch '{branch}' now exists in {} and was kept: meta can't tell whether this \ create made it", - repo.display() + escape_path(repo) ))), Err(e) => Err(e), } @@ -399,11 +437,11 @@ fn roll_back( "{error:#}\nThe partly created worktree at {} was left in place ({undo:#}); \ delete it yourself and run 'git worktree prune' in its repositories. \ Branches this create made: {}", - wt_dir.display(), + escape_path(wt_dir), if branches.is_empty() { "none".to_string() } else { - branches.join(", ") + escape(&branches.join(", ")).into_owned() } ); } @@ -437,7 +475,7 @@ fn print_create_dry_run(plan: &CreateDryRunPlan<'_>) { println!( "[DRY RUN] Would create worktree set '{}' at {}", plan.name, - plan.wt_dir.display() + escape_path(plan.wt_dir) ); println!(); @@ -484,11 +522,11 @@ fn print_create_dry_run(plan: &CreateDryRunPlan<'_>) { cmd.push(' '); cmd.push_str(&shell_quote(from_ref)); } - println!(" {alias}:"); - println!(" source: {}", source.display()); - println!(" dest: {}", dest.display()); - println!(" branch: {branch}"); - println!(" bash: {cmd}"); + println!(" {}:", escape(alias)); + println!(" source: {}", escape_path(source)); + println!(" dest: {}", escape_path(&dest)); + println!(" branch: {}", escape(branch)); + println!(" bash: {}", escape(&cmd)); } println!(); @@ -741,9 +779,26 @@ fn ensure_intermediate_parents( // Resolve the parent's source path via config lookup (respects custom // `path` settings) with a fallback to direct path joining. + // A fallback directory must lie inside the workspace and not be a + // symlink: it becomes a source repo for git let parent_source = match lookup_nested_project(meta_dir, &parent_alias) { Ok((source, _project)) => source, - Err(_) => meta_dir.join(&parent_alias), + Err(_) => { + let candidate = meta_dir.join(&parent_alias); + let is_link = candidate + .symlink_metadata() + .is_ok_and(|meta| meta.file_type().is_symlink()); + if is_link + || meta_core::config::resolve_inside(meta_dir, &parent_alias).is_err() + { + log::warn!( + "Intermediate parent '{}' is not a plain directory inside the workspace, skipping", + escape(&parent_alias) + ); + continue; + } + candidate + } }; if !parent_source.exists() { log::warn!( diff --git a/src/commands/worktree/diff.rs b/src/commands/worktree/diff.rs index 82b4481..1b94fef 100644 --- a/src/commands/worktree/diff.rs +++ b/src/commands/worktree/diff.rs @@ -1,5 +1,6 @@ use anyhow::Result; use colored::*; +use meta_core::display::escape; use rayon::prelude::*; use meta_git_lib::worktree::git_ops::git_diff_stat; @@ -65,7 +66,7 @@ pub(crate) fn handle_diff(args: DiffArgs, _verbose: bool, json: bool) -> Result< let deletions = d.deletions; println!( " {:12} {} {} ({} files)", - d.alias, + escape(&d.alias), format!("+{insertions}").green(), format!("-{deletions}").red(), d.files_changed, diff --git a/src/commands/worktree/exec.rs b/src/commands/worktree/exec.rs index 0f7f9da..d3f619a 100644 --- a/src/commands/worktree/exec.rs +++ b/src/commands/worktree/exec.rs @@ -1,5 +1,6 @@ use anyhow::Result; use colored::*; +use meta_core::display::escape_lines; use std::path::Path; use meta_cli::repo_filter; @@ -45,16 +46,18 @@ fn build_loop_config( }) } -/// RAII guard that removes an ephemeral worktree on drop. -/// Ensures cleanup even if the exec command panics. +/// RAII guard that removes an ephemeral worktree. +/// `finish` removes it and reports failure; drop is the fallback that still +/// cleans up after an early return or a panic. struct EphemeralGuard { name: String, verbose: bool, json: bool, + finished: bool, } -impl Drop for EphemeralGuard { - fn drop(&mut self) { +impl EphemeralGuard { + fn remove(&self) -> Result<()> { if self.verbose { eprintln!("Removing ephemeral worktree '{}'...", self.name); } @@ -62,12 +65,26 @@ impl Drop for EphemeralGuard { name: self.name.clone(), force: true, }; - // Ephemeral cleanup uses strict=false to ensure best-effort cleanup - if let Err(e) = super::remove::handle_remove(destroy_args, self.verbose, self.json, false) { + super::remove::handle_remove(destroy_args, self.verbose, self.json) + } + + fn finish(mut self) -> Result<()> { + self.finished = true; + self.remove() + } +} + +impl Drop for EphemeralGuard { + fn drop(&mut self) { + if self.finished { + return; + } + if let Err(e) = self.remove() { eprintln!( - "{} Failed to remove ephemeral worktree '{}': {e}", + "{} Failed to remove ephemeral worktree '{}': {}", "warning:".yellow().bold(), - self.name + self.name, + escape_lines(&format!("{e:#}")) ); eprintln!( " Run 'meta worktree remove {} --force' or 'meta worktree prune' to clean up.", @@ -142,12 +159,13 @@ fn handle_ephemeral_exec(args: ExecArgs, verbose: bool, json: bool) -> Result<() name: name.clone(), verbose, json, + finished: false, }; // Resolve worktree path for exec let meta_dir = find_meta_dir(); let worktree_root = resolve_worktree_root(meta_dir.as_deref())?; - let wt_dir = worktree_root.join(&name); + let wt_dir = worktree_set_dir(&worktree_root, &name)?; // Run the command let repos = discover_worktree_repos(&wt_dir)?; @@ -164,10 +182,19 @@ fn handle_ephemeral_exec(args: ExecArgs, verbose: bool, json: bool) -> Result<() let exec_result = config.and_then(|config| loop_lib::run(&config, &cmd_parts)); - // Explicitly drop guard to trigger cleanup before propagating result - drop(guard); - - // Propagate exec result - exec_result?; - Ok(()) + // Clean up before propagating the result; a failed cleanup (such as an + // unwritable store) fails the command too + let cleanup = guard.finish(); + match (exec_result, cleanup) { + (Err(e), Err(cleanup_error)) => { + eprintln!( + "{} {}", + "warning:".yellow().bold(), + escape_lines(&format!("{cleanup_error:#}")) + ); + Err(e) + } + (Err(e), Ok(())) => Err(e), + (Ok(()), cleanup) => cleanup, + } } diff --git a/src/commands/worktree/list.rs b/src/commands/worktree/list.rs index bb580c7..e3bed38 100644 --- a/src/commands/worktree/list.rs +++ b/src/commands/worktree/list.rs @@ -1,6 +1,7 @@ use anyhow::Result; use chrono::Utc; use colored::*; +use meta_core::display::{escape, escape_path}; use rayon::prelude::*; use serde::Serialize; use std::collections::HashMap; @@ -114,11 +115,11 @@ pub(crate) fn handle_list( let selected = match args.name.as_ref() { Some(name) => { validate_worktree_name(name)?; - let path = worktree_root.join(name); + let path = worktree_set_dir(&worktree_root, name)?; anyhow::ensure!( path.is_dir(), "Worktree '{name}' not found at {}", - path.display() + escape_path(&path) ); Some((name.clone(), path)) } @@ -152,7 +153,15 @@ pub(crate) fn handle_list( } sets }; - let store_data = store_list().unwrap_or_default(); + // Listing still works without the store (no TTL or ephemeral marks), but + // say why it is missing + let store_data = store_list().unwrap_or_else(|e| { + eprintln!( + "warning: not using the worktree store: {}", + meta_core::display::escape_lines(&format!("{e:#}")) + ); + Default::default() + }); let now = Utc::now().timestamp(); let results: Vec>> = sets .par_iter() @@ -228,7 +237,7 @@ pub(crate) fn handle_list( ); } for entry in worktrees { - let mut header = entry.name.bold().to_string(); + let mut header = escape(&entry.name).bold().to_string(); if entry.ephemeral == Some(true) { header.push_str(&format!(" {}", "[ephemeral]".dimmed())); } @@ -247,21 +256,32 @@ pub(crate) fn handle_list( println!("{header}"); for repo in entry.repos { match repo { - RepoEntry::Metadata(repo) => println!(" {} {}", repo.alias, repo.path.display()), + RepoEntry::Metadata(repo) => { + println!(" {} {}", escape(&repo.alias), escape_path(&repo.path)) + } RepoEntry::Observed(repo) => { let status = if repo.dirty { "modified".yellow().to_string() } else { "clean".green().to_string() }; - println!(" {:12} -> {:20} ({})", repo.alias, repo.branch, status); + println!( + " {:12} -> {:20} ({})", + escape(&repo.alias), + escape(&repo.branch), + status + ); } } } println!(); } for warning in warnings { - eprintln!("Warning: {}: {}", warning.name, warning.message); + eprintln!( + "Warning: {}: {}", + escape(&warning.name), + escape(&warning.message) + ); } Ok(()) } diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs index 6dd8d71..4c41969 100644 --- a/src/commands/worktree/mod.rs +++ b/src/commands/worktree/mod.rs @@ -13,6 +13,7 @@ mod status; use anyhow::Result; use clap::Parser; use colored::*; +use meta_core::display::escape_lines; use meta_plugin_protocol::{CommandResult, PluginRequestOptions}; use std::path::Path; @@ -122,9 +123,9 @@ fn handle_worktree_command( ) -> Result<()> { match command { WorktreeCommands::Create(args) => create::handle_create(args, verbose, json, global_strict), - WorktreeCommands::Add(args) => add::handle_add(args, verbose, json, global_strict), + WorktreeCommands::Add(args) => add::handle_add(args, verbose, json), WorktreeCommands::Remove(args) | WorktreeCommands::Destroy(args) => { - remove::handle_remove(args, verbose, json, global_strict) + remove::handle_remove(args, verbose, json) } WorktreeCommands::List(args) => list::handle_list(args, verbose, json, cwd), WorktreeCommands::Status(args) => status::handle_status(args, verbose, json), @@ -155,22 +156,16 @@ pub(crate) fn warn_or_bail(strict: bool, message: impl std::fmt::Display) -> any if strict { anyhow::bail!("{message} (strict mode)") } else { - eprintln!("{} {}", "warning:".yellow().bold(), message); + // the message can carry paths and names from git and the filesystem + eprintln!( + "{} {}", + "warning:".yellow().bold(), + escape_lines(&message.to_string()) + ); Ok(()) } } -/// Log a store operation error as a warning, or propagate in strict mode. -/// -/// In strict mode, returns the error to fail the command. -/// In normal mode, prints a warning and continues. -pub(crate) fn warn_store_error(result: anyhow::Result<()>, strict: bool) -> anyhow::Result<()> { - match result { - Ok(()) => Ok(()), - Err(e) => warn_or_bail(strict, format!("Failed to update store: {e}")), - } -} - /// Print worktree help text to stdout. pub fn print_worktree_help() { write_worktree_help(&mut std::io::stdout()); @@ -291,30 +286,4 @@ mod tests { let err = result.unwrap_err(); assert!(err.to_string().contains("specific error details")); } - - // ── warn_store_error tests ───────────────────────────── - - #[test] - fn warn_store_error_passes_through_ok() { - let result = warn_store_error(Ok(()), false); - assert!(result.is_ok()); - - let result_strict = warn_store_error(Ok(()), true); - assert!(result_strict.is_ok()); - } - - #[test] - fn warn_store_error_returns_ok_for_error_in_normal_mode() { - let result = warn_store_error(Err(anyhow::anyhow!("store failed")), false); - assert!(result.is_ok()); - } - - #[test] - fn warn_store_error_returns_err_in_strict_mode() { - let result = warn_store_error(Err(anyhow::anyhow!("store failed")), true); - assert!(result.is_err()); - let err = result.unwrap_err(); - assert!(err.to_string().contains("Failed to update store")); - assert!(err.to_string().contains("store failed")); - } } diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index 1e120f7..095d2f4 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -1,6 +1,7 @@ -use anyhow::Result; +use anyhow::{Context, Result}; use chrono::Utc; use colored::*; +use meta_core::display::escape; use std::path::Path; use meta_git_lib::worktree::helpers::{find_meta_dir, lookup_nested_project}; @@ -218,7 +219,12 @@ pub(crate) fn handle_prune( } else { println!("Would prune {} worktree(s):", would_remove.len()); for entry in &would_remove { - println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); + println!( + " {} ({}) — {}", + escape(&entry.name), + escape(&entry.reason), + escape(&entry.path) + ); } } print_kept(&kept); @@ -272,7 +278,8 @@ pub(crate) fn handle_prune( Some((e.path.clone(), entry.created_at.clone())) }) .collect(); - super::warn_store_error(store_remove_batch(&records), strict)?; + store_remove_batch(&records) + .context("Pruned worktrees, but could not update the worktree store")?; // Fire post-prune hook let meta_dir = find_meta_dir(); @@ -290,13 +297,18 @@ pub(crate) fn handle_prune( } else { println!("{} Pruned {} worktree(s):", "✓".green(), removed.len()); for entry in &removed { - println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); + println!( + " {} ({}) — {}", + escape(&entry.name), + escape(&entry.reason), + escape(&entry.path) + ); } print_kept(&kept); } if !failed.is_empty() { - anyhow::bail!("Failed to prune: {}", failed.join(", ")); + anyhow::bail!("Failed to prune: {}", escape(&failed.join(", "))); } warn_kept(&kept, strict) } @@ -307,7 +319,12 @@ fn print_kept(kept: &[PruneEntry]) { } println!("Kept {} worktree(s):", kept.len()); for entry in kept { - println!(" {} ({}) — {}", entry.name, entry.reason, entry.path); + println!( + " {} ({}) — {}", + escape(&entry.name), + escape(&entry.reason), + escape(&entry.path) + ); } } diff --git a/src/commands/worktree/remove.rs b/src/commands/worktree/remove.rs index b0824f5..294ed06 100644 --- a/src/commands/worktree/remove.rs +++ b/src/commands/worktree/remove.rs @@ -1,5 +1,6 @@ -use anyhow::Result; +use anyhow::{Context, Result}; use colored::*; +use meta_core::display::{escape, escape_path}; use meta_git_lib::worktree::helpers::*; use meta_git_lib::worktree::hooks::fire_post_destroy; @@ -9,22 +10,17 @@ use meta_git_lib::worktree::types::*; use super::cli_types::DestroyArgs; -pub(crate) fn handle_remove( - args: DestroyArgs, - verbose: bool, - json: bool, - strict: bool, -) -> Result<()> { +pub(crate) fn handle_remove(args: DestroyArgs, verbose: bool, json: bool) -> Result<()> { let name = &args.name; validate_worktree_name(name)?; let force = args.force; let meta_dir = find_meta_dir(); let worktree_root = resolve_worktree_root(meta_dir.as_deref())?; - let wt_dir = worktree_root.join(name); + let wt_dir = worktree_set_dir(&worktree_root, name)?; if !wt_dir.exists() { - anyhow::bail!("Worktree '{}' not found at {}", name, wt_dir.display()); + anyhow::bail!("Worktree '{}' not found at {}", name, escape_path(&wt_dir)); } // Only delete what meta created: the store records every worktree set it made. @@ -33,7 +29,7 @@ pub(crate) fn handle_remove( "Refusing to remove {}: meta has no record of creating a worktree there.\n\ If it is a worktree whose record was lost, delete it yourself and run \ 'git worktree prune' in its repositories.", - wt_dir.display() + escape_path(&wt_dir) ); }; @@ -46,7 +42,7 @@ pub(crate) fn handle_remove( .chain( nested .iter() - .map(|k| format!("{k}: another worktree set; remove it first")), + .map(|k| format!("{}: another worktree set; remove it first", escape(k))), ) .collect(); if !blockers.is_empty() { @@ -76,7 +72,9 @@ pub(crate) fn handle_remove( // Remove from centralized store // By the key read before deleting: the deleted path can't be resolved again. let record = [(record_key, record.created_at)]; - super::warn_store_error(store_remove_batch(&record), strict)?; + store_remove_batch(&record).with_context(|| { + format!("Removed worktree '{name}', but could not update the worktree store") + })?; // Fire post-destroy hook fire_post_destroy(name, &wt_dir, force, meta_dir.as_deref()); diff --git a/src/commands/worktree/status.rs b/src/commands/worktree/status.rs index 62998d8..b34360e 100644 --- a/src/commands/worktree/status.rs +++ b/src/commands/worktree/status.rs @@ -1,5 +1,6 @@ use anyhow::Result; use colored::*; +use meta_core::display::escape; use rayon::prelude::*; use meta_git_lib::worktree::git_ops::*; @@ -87,7 +88,10 @@ pub(crate) fn handle_status(args: StatusArgs, _verbose: bool, json: bool) -> Res }; println!( " {} {:12} {:20} {}", - status_icon, s.alias, s.branch, detail_str + status_icon, + escape(&s.alias), + escape(&s.branch), + detail_str ); } } diff --git a/src/commit.rs b/src/commit.rs index 2cc4743..c55be6b 100644 --- a/src/commit.rs +++ b/src/commit.rs @@ -1,5 +1,6 @@ use console::style; use meta_core::config; +use meta_core::display::escape_path; use meta_plugin_protocol::{CommandResult, PlannedCommand, PluginRequestOptions}; use std::process::Command; @@ -43,7 +44,7 @@ pub(crate) fn execute_git_commit( let Some((meta_path, _format)) = config::find_meta_config_in(cwd) else { return Ok(CommandResult::Message(format!( "No .meta config found in {}", - cwd.display() + escape_path(cwd) ))); }; let (projects, _) = config::parse_meta_config(&meta_path)?; @@ -172,12 +173,16 @@ fn execute_editor_commit(repos: &[(String, String, Vec)]) -> anyhow::Res template.push_str("# Enter commit message above this line\n\n"); } - // Write to temp file - let temp_dir = std::env::temp_dir(); - let temp_file = temp_dir.join("META_COMMIT_EDITMSG"); - let mut file = std::fs::File::create(&temp_file)?; + // Write to a new temp file (created exclusively, mode 0600, removed on + // drop) in meta's private data dir, never in a shared directory like /tmp + let mut file = tempfile::Builder::new() + .prefix("META_COMMIT_EDITMSG-") + .tempfile_in(meta_core::data_dir::data_subdir("tmp")?)?; file.write_all(template.as_bytes())?; - drop(file); + file.flush()?; + // Close it (some editors on Windows cannot replace an open file); the + // path is still removed on drop + let temp_file = file.into_temp_path(); // Get editor from environment let editor = std::env::var("EDITOR") @@ -195,8 +200,7 @@ fn execute_editor_commit(repos: &[(String, String, Vec)]) -> anyhow::Res let content = std::fs::read_to_string(&temp_file)?; let commits = parse_multi_commit_file(&content); - // Clean up temp file - let _ = std::fs::remove_file(&temp_file); + drop(temp_file); if commits.is_empty() { println!("No commits to make (all messages were empty or deleted)."); diff --git a/src/lib.rs b/src/lib.rs index b254232..4198f6c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -81,7 +81,7 @@ pub fn execute_command( match result { Ok(cmd_result) => cmd_result, - Err(e) => CommandResult::Error(format!("{e}")), + Err(e) => CommandResult::Error(format!("{e:#}")), } } @@ -193,7 +193,7 @@ fn execute_raw_git_command( // Get project directories let dirs = match get_project_directories_with_fallback(projects, cwd) { Ok(d) => d, - Err(e) => return CommandResult::Error(format!("Failed to get project directories: {e}")), + Err(e) => return CommandResult::Error(format!("Failed to get project directories: {e:#}")), }; // The git argv: the command words (e.g. "git" or "git add") and the diff --git a/src/main.rs b/src/main.rs index 52eb9ec..6b2f10d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ //! Use RUST_LOG=meta_git_cli=debug for debug output. use indexmap::IndexMap; +use meta_core::display::escape_lines; use meta_plugin_protocol::{ run_plugin, CommandResult, PluginDefinition, PluginHelp, PluginInfo, PluginRequest, }; @@ -88,7 +89,16 @@ fn main() { }); } +/// Errors carry paths and names from git and the filesystem, so they are +/// escaped before they reach the terminal. fn execute(request: PluginRequest) -> CommandResult { + match execute_request(request) { + CommandResult::Error(e) => CommandResult::Error(escape_lines(&e).into_owned()), + other => other, + } +} + +fn execute_request(request: PluginRequest) -> CommandResult { let cwd = if request.cwd.is_empty() { match std::env::current_dir() { Ok(d) => d, diff --git a/src/ssh.rs b/src/ssh.rs index 4a561ba..af7c329 100644 --- a/src/ssh.rs +++ b/src/ssh.rs @@ -1,4 +1,5 @@ use console::style; +use meta_core::display::escape; use std::collections::BTreeSet; use std::path::Path; @@ -90,9 +91,9 @@ pub(crate) fn warn_remote_mismatches(cwd: &Path) { ); for m in &mismatches { - eprintln!(" {}", style(&m.name).bold()); - eprintln!(" actual: {}", style(&m.actual).red()); - eprintln!(" expected: {}", style(&m.expected).green()); + eprintln!(" {}", style(escape(&m.name)).bold()); + eprintln!(" actual: {}", style(escape(&m.actual)).red()); + eprintln!(" expected: {}", style(escape(&m.expected)).green()); } eprintln!(); @@ -100,7 +101,8 @@ pub(crate) fn warn_remote_mismatches(cwd: &Path) { for m in &mismatches { eprintln!( " git -C '{}' remote set-url origin '{}'", - m.path, m.expected + escape(&m.path), + escape(&m.expected) ); } } diff --git a/src/update.rs b/src/update.rs index 73b9170..0c3a114 100644 --- a/src/update.rs +++ b/src/update.rs @@ -3,6 +3,7 @@ use crate::ssh_setup; use console::style; use indicatif::MultiProgress; use meta_core::config; +use meta_core::display::{escape, escape_path}; use meta_git_lib::clone_queue::CloneQueue; use meta_plugin_protocol::CommandResult; use std::collections::HashSet; @@ -69,11 +70,12 @@ pub(crate) fn execute_git_update( } else { dir.join(name).to_string_lossy().to_string() }; + let shown = escape(&relative_path); eprintln!( "{} {} exists locally but is not in .meta. To remove: rm -rf {}", style("⚠").yellow(), - style(&relative_path).yellow().bold(), - relative_path + style(&shown).yellow().bold(), + shown ); } } @@ -107,7 +109,11 @@ pub(crate) fn execute_git_update( ); let tasks = queue.drain_all(); for task in tasks { - println!(" git clone {} {}", task.url, task.target_path.display()); + println!( + " git clone {} {}", + escape(&task.url), + escape_path(&task.target_path) + ); } return Ok(CommandResult::Message(String::new())); } diff --git a/tests/safety.rs b/tests/safety.rs index d32b960..9501bc9 100644 --- a/tests/safety.rs +++ b/tests/safety.rs @@ -112,8 +112,9 @@ fn remove_refuses_directories_meta_did_not_create() { assert!(stderr(&out).contains("no record"), "{}", stderr(&out)); assert!(ws.join(".worktrees/notawt/data").exists()); - // worktrees_dir "." makes the primary clone `a` look like a worktree. Even - // with a forged store record, a primary checkout is never deleted. + // worktrees_dir "." would make the primary clone `a` look like a worktree. + // Such a config is refused, so even with a forged store record the + // primary checkout is never deleted. let config = json!({"worktrees_dir": ".", "projects": {"a": "unused"}}); fs::write(ws.join(".meta"), config.to_string()).unwrap(); let key = ws.join("a").canonicalize().unwrap(); @@ -125,7 +126,7 @@ fn remove_refuses_directories_meta_did_not_create() { let out = worktree(root, &ws, &["remove", "a", "--force"]); assert!(!out.status.success()); assert!( - stderr(&out).contains("not a linked worktree"), + stderr(&out).contains("Invalid worktrees_dir"), "{}", stderr(&out) ); @@ -640,9 +641,11 @@ fn remove_drops_the_record_when_the_worktrees_dir_is_a_link() { let temp = tempfile::tempdir().unwrap(); let root = temp.path(); let ws = workspace(root, &["a"]); - fs::create_dir(root.join("real")).unwrap(); - std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap(); - let config = json!({"worktrees_dir": "../link", "projects": {"a": "unused"}}); + // worktrees_dir must stay inside the workspace; a link there still + // resolves to another path than the one written + fs::create_dir(ws.join("real")).unwrap(); + std::os::unix::fs::symlink(ws.join("real"), ws.join("link")).unwrap(); + let config = json!({"worktrees_dir": "link", "projects": {"a": "unused"}}); fs::write(ws.join(".meta"), config.to_string()).unwrap(); let out = worktree(root, &ws, &["create", "t", "--repo", "a", "--no-deps"]); From 39119e5d7dce3b42d039397108de659441262c84 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:15:22 -0700 Subject: [PATCH 02/13] fix: prune keeps a set whose recorded path no longer resolves to itself The store records each set's resolved path. If a directory above it became a symlink since, the path can lead into another, live set, which the removal check accepts because it compares resolved paths. Prune now keeps such a set and says why, checked before inspecting it and again before deleting it. Implements [[tasks/harmony-2749]] --- src/commands/worktree/prune.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index 095d2f4..e66ab02 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -176,6 +176,15 @@ pub(crate) fn handle_prune( candidates.push((entry, None)); continue; } + if leads_elsewhere(wt_path) { + kept.push(create_prune_entry( + entry.name, + entry.path, + format!("{}, but {LEADS_ELSEWHERE}", entry.reason), + entry.age_seconds, + )); + continue; + } // Deleting a set would delete any recorded set inside it. let nested: Vec<&str> = store .worktrees @@ -241,6 +250,16 @@ pub(crate) fn handle_prune( for (prune_entry, check) in candidates { let wt_path = Path::new(&prune_entry.path); let removal = match &check { + // Checked again: a directory above may have become a link since + Some(_) if leads_elsewhere(wt_path) => { + kept.push(create_prune_entry( + prune_entry.name, + prune_entry.path, + format!("{}, but {LEADS_ELSEWHERE}", prune_entry.reason), + prune_entry.age_seconds, + )); + continue; + } Some(check) => delete_checked_set(wt_path, check, false, false), // A missing directory only loses its record. One that has // reappeared since was never checked: keep it, nothing failed. @@ -313,6 +332,21 @@ pub(crate) fn handle_prune( warn_kept(&kept, strict) } +const LEADS_ELSEWHERE: &str = "a directory above it now leads elsewhere through a symlink"; + +/// Whether the recorded path no longer resolves to itself because a +/// directory above it became a symlink, which could lead into another set. +/// The store records each set's resolved path when it is created. A link at +/// the set directory itself is left to the removal check, which refuses it. +fn leads_elsewhere(path: &Path) -> bool { + match path.symlink_metadata() { + Ok(meta) if !meta.file_type().is_symlink() => { + path.canonicalize().ok().as_deref() != Some(path) + } + _ => false, + } +} + fn print_kept(kept: &[PruneEntry]) { if kept.is_empty() { return; From 637aeee0fb0f3d2bb41b763fbca0a9a8e38dfea4 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:32:04 -0700 Subject: [PATCH 03/13] fix: refuse one repo on two branches after resolving aliases; escape a nested-config debug error '--repo core:one --repo group/core:two' passed the check on the typed aliases and the resolved map kept only one branch. Implements [[tasks/harmony-2749]] --- src/clone_worker.rs | 6 ++++- src/commands/worktree/create.rs | 46 ++++++++++++++------------------- 2 files changed, 24 insertions(+), 28 deletions(-) diff --git a/src/clone_worker.rs b/src/clone_worker.rs index da862fb..75f7d16 100644 --- a/src/clone_worker.rs +++ b/src/clone_worker.rs @@ -178,7 +178,11 @@ fn clone_single_repo( )); // Still mark as completed and check for nested .meta if let Err(e) = queue.mark_completed(task) { - debug!("Failed to check nested .meta for {}: {}", task.name, e); + debug!( + "Failed to check nested .meta for {}: {}", + task.name, + meta_core::display::escape_lines(&format!("{e:#}")) + ); record(e); } return; diff --git a/src/commands/worktree/create.rs b/src/commands/worktree/create.rs index 90098f0..6fa2451 100644 --- a/src/commands/worktree/create.rs +++ b/src/commands/worktree/create.rs @@ -67,26 +67,6 @@ pub(crate) fn handle_create( if repo_specs.is_empty() && !use_all { anyhow::bail!("Specify repos with --repo or use --all"); } - // A repeated --repo is one worktree; two branches for it cannot both be - // checked out there, and keeping one would drop the other unnoticed - for (i, spec) in repo_specs.iter().enumerate() { - let other = repo_specs - .iter() - .skip(i + 1) - .find(|o| o.alias == spec.alias && o.branch != spec.branch); - if let Some(other) = other { - let branch = |s: &meta_git_lib::worktree::RepoSpec| { - escape(s.branch.as_deref().unwrap_or("(default)")).into_owned() - }; - anyhow::bail!( - "Repo '{}' is given twice, on branches '{}' and '{}'", - escape(&spec.alias), - branch(spec), - branch(other) - ); - } - } - let nearest_meta_dir = require_meta_dir()?; let meta_dir = if recursive { meta_core::config::find_root_meta_dir(&nearest_meta_dir) @@ -630,13 +610,25 @@ fn resolve_repos_with_dependencies( // Precompute a mapping from resolved alias to per-repo branch so we avoid // repeated graph scans inside the per-repo loop below. - let resolved_branch_map: HashMap> = repo_specs - .iter() - .filter_map(|r| { - let resolved = resolve_alias_in_graph(&graph, &r.alias).ok()?; - Some((resolved, r.branch.as_deref())) - }) - .collect(); + // Two specs naming one repo (say `core` and `group/core`) on different + // branches can't both be honoured: refuse rather than keep one. + let mut resolved_branch_map: HashMap> = HashMap::new(); + for spec in repo_specs { + let Ok(resolved) = resolve_alias_in_graph(&graph, &spec.alias) else { + continue; + }; + let branch = spec.branch.as_deref(); + if let Some(first) = resolved_branch_map.insert(resolved.clone(), branch) { + if first != branch { + anyhow::bail!( + "Repo '{}' is given twice, on branches '{}' and '{}'", + escape(&resolved), + escape(first.unwrap_or("(default)")), + escape(branch.unwrap_or("(default)")) + ); + } + } + } // Add other repos for alias in &repos_to_include { From 9e1be6f939f3e6710b0efb7dc36320f7196d0654 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:48:00 -0700 Subject: [PATCH 04/13] fix: refuse one repo on two branches in every mode; report failed clones with a nested-config error; run hooks and print results before a store error Implements [[tasks/harmony-2749]] --- src/clone_worker.rs | 6 +++++- src/commands/worktree/create.rs | 21 +++++++++++++++++++++ src/commands/worktree/prune.rs | 6 ++++-- src/commands/worktree/remove.rs | 7 ++++--- 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/clone_worker.rs b/src/clone_worker.rs index 75f7d16..892be4d 100644 --- a/src/clone_worker.rs +++ b/src/clone_worker.rs @@ -111,8 +111,12 @@ pub(crate) fn clone_with_queue( // command must not report success let errors = nested_errors.lock().unwrap_or_else(|e| e.into_inner()); if !errors.is_empty() { + // Failed clones are reported too, not hidden behind this error + let failed = report_failures(&queue) + .map(|summary| format!("\n{summary}")) + .unwrap_or_default(); anyhow::bail!( - "Could not read nested .meta configs:\n{}", + "Could not read nested .meta configs:\n{}{failed}", errors.join("\n") ); } diff --git a/src/commands/worktree/create.rs b/src/commands/worktree/create.rs index 6fa2451..b88a9ee 100644 --- a/src/commands/worktree/create.rs +++ b/src/commands/worktree/create.rs @@ -67,6 +67,27 @@ pub(crate) fn handle_create( if repo_specs.is_empty() && !use_all { anyhow::bail!("Specify repos with --repo or use --all"); } + // A repeated --repo is one worktree; two branches for it cannot both be + // checked out there, and keeping one would drop the other unnoticed. + // (Two aliases of one repo are caught again once resolved.) + for (i, spec) in repo_specs.iter().enumerate() { + let other = repo_specs + .iter() + .skip(i + 1) + .find(|o| o.alias == spec.alias && o.branch != spec.branch); + if let Some(other) = other { + let branch = |s: &meta_git_lib::worktree::RepoSpec| { + escape(s.branch.as_deref().unwrap_or("(default)")).into_owned() + }; + anyhow::bail!( + "Repo '{}' is given twice, on branches '{}' and '{}'", + escape(&spec.alias), + branch(spec), + branch(other) + ); + } + } + let nearest_meta_dir = require_meta_dir()?; let meta_dir = if recursive { meta_core::config::find_root_meta_dir(&nearest_meta_dir) diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index e66ab02..cf2f9c4 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -297,8 +297,9 @@ pub(crate) fn handle_prune( Some((e.path.clone(), entry.created_at.clone())) }) .collect(); - store_remove_batch(&records) - .context("Pruned worktrees, but could not update the worktree store")?; + // A failure is reported after the hook and output: the sets are gone + let stored = store_remove_batch(&records) + .context("Pruned worktrees, but could not update the worktree store"); // Fire post-prune hook let meta_dir = find_meta_dir(); @@ -326,6 +327,7 @@ pub(crate) fn handle_prune( print_kept(&kept); } + stored?; if !failed.is_empty() { anyhow::bail!("Failed to prune: {}", escape(&failed.join(", "))); } diff --git a/src/commands/worktree/remove.rs b/src/commands/worktree/remove.rs index 294ed06..283a2f4 100644 --- a/src/commands/worktree/remove.rs +++ b/src/commands/worktree/remove.rs @@ -72,9 +72,10 @@ pub(crate) fn handle_remove(args: DestroyArgs, verbose: bool, json: bool) -> Res // Remove from centralized store // By the key read before deleting: the deleted path can't be resolved again. let record = [(record_key, record.created_at)]; - store_remove_batch(&record).with_context(|| { + // A failure is reported after the hook and output: the worktree is gone + let stored = store_remove_batch(&record).with_context(|| { format!("Removed worktree '{name}', but could not update the worktree store") - })?; + }); // Fire post-destroy hook fire_post_destroy(name, &wt_dir, force, meta_dir.as_deref()); @@ -89,5 +90,5 @@ pub(crate) fn handle_remove(args: DestroyArgs, verbose: bool, json: bool) -> Res } else { println!("{} Removed worktree '{}'", "✓".green(), name.bold()); } - Ok(()) + stored } From d6e3aad1e2fa39bb0ee62a7beff3b3d6e3924219 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:05:13 -0700 Subject: [PATCH 05/13] fix: prune does not take an unreadable nested config as a removed repo A nested .meta that fails to read or validate said nothing about its repos, but prune counted them as removed and deleted the live set. Implements [[tasks/harmony-2749]] --- src/commands/worktree/prune.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index cf2f9c4..6f65d97 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -4,7 +4,7 @@ use colored::*; use meta_core::display::escape; use std::path::Path; -use meta_git_lib::worktree::helpers::{find_meta_dir, lookup_nested_project}; +use meta_git_lib::worktree::helpers::find_meta_dir; use meta_git_lib::worktree::hooks::fire_post_prune; use meta_git_lib::worktree::safety::{check_worktree_removal, delete_checked_set}; use meta_git_lib::worktree::store::{entry_ttl_remaining, store_list, store_remove_batch}; @@ -62,8 +62,7 @@ fn check_repo_orphaned( .filter(|alias| { *alias != "." && !projects.iter().any(|p| p.name == *alias) - && !(alias.contains('/') - && lookup_nested_project(Path::new(&entry.project), alias).is_ok()) + && !(alias.contains('/') && nested_alias_present(Path::new(&entry.project), alias)) }) .count(); @@ -74,6 +73,17 @@ fn check_repo_orphaned( } } +/// Whether nested alias `alias` still names a repo of `project`. A nested +/// config that can't be read or is refused says nothing about the repo, so +/// it counts as present: only a tree that reads cleanly without the alias +/// makes the repo removed. +fn nested_alias_present(project: &Path, alias: &str) -> bool { + match meta_core::config::walk_meta_tree(project, None) { + Ok(tree) => meta_core::config::build_project_map(&tree, project, "").contains_key(alias), + Err(_) => true, + } +} + /// Only a path that is really gone counts as missing. A dangling link or a /// path prune can't inspect (permission denied) exists, so it gets checked /// and kept, never forgotten. From f5300dcbf13acbab6ffb3881d693af1944101a38 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:30:23 -0700 Subject: [PATCH 06/13] fix: a refused .meta is an error for the plugin's own repo list; prune says when a path cannot be resolved; escape the clone progress error Implements [[tasks/harmony-2749]] --- src/clone_worker.rs | 8 ++++-- src/commands/worktree/prune.rs | 45 ++++++++++++++++++---------------- src/helpers.rs | 10 +++++--- src/lib.rs | 17 +++++++++++++ 4 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/clone_worker.rs b/src/clone_worker.rs index 892be4d..deac63b 100644 --- a/src/clone_worker.rs +++ b/src/clone_worker.rs @@ -244,8 +244,12 @@ fn clone_single_repo( Err(e) => { pb.finish_with_message(format!( "{}", - style(format!("Cloned {} (meta parse error: {})", task.name, e)) - .yellow() + style(format!( + "Cloned {} (meta parse error: {})", + task.name, + meta_core::display::escape_lines(&format!("{e:#}")) + )) + .yellow() )); record(e); } diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index 6f65d97..27339ff 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -186,11 +186,11 @@ pub(crate) fn handle_prune( candidates.push((entry, None)); continue; } - if leads_elsewhere(wt_path) { + if let Some(why) = path_moved(wt_path) { kept.push(create_prune_entry( entry.name, entry.path, - format!("{}, but {LEADS_ELSEWHERE}", entry.reason), + format!("{}, but {why}", entry.reason), entry.age_seconds, )); continue; @@ -261,16 +261,18 @@ pub(crate) fn handle_prune( let wt_path = Path::new(&prune_entry.path); let removal = match &check { // Checked again: a directory above may have become a link since - Some(_) if leads_elsewhere(wt_path) => { - kept.push(create_prune_entry( - prune_entry.name, - prune_entry.path, - format!("{}, but {LEADS_ELSEWHERE}", prune_entry.reason), - prune_entry.age_seconds, - )); - continue; - } - Some(check) => delete_checked_set(wt_path, check, false, false), + Some(check) => match path_moved(wt_path) { + None => delete_checked_set(wt_path, check, false, false), + Some(why) => { + kept.push(create_prune_entry( + prune_entry.name, + prune_entry.path, + format!("{}, but {why}", prune_entry.reason), + prune_entry.age_seconds, + )); + continue; + } + }, // A missing directory only loses its record. One that has // reappeared since was never checked: keep it, nothing failed. None if !is_missing(wt_path) => { @@ -344,18 +346,19 @@ pub(crate) fn handle_prune( warn_kept(&kept, strict) } -const LEADS_ELSEWHERE: &str = "a directory above it now leads elsewhere through a symlink"; - -/// Whether the recorded path no longer resolves to itself because a -/// directory above it became a symlink, which could lead into another set. +/// Why the recorded path no longer resolves to itself, if it doesn't: a +/// directory above it became a symlink, which could lead into another set, +/// or it can't be resolved at all. /// The store records each set's resolved path when it is created. A link at /// the set directory itself is left to the removal check, which refuses it. -fn leads_elsewhere(path: &Path) -> bool { +fn path_moved(path: &Path) -> Option { match path.symlink_metadata() { - Ok(meta) if !meta.file_type().is_symlink() => { - path.canonicalize().ok().as_deref() != Some(path) - } - _ => false, + Ok(meta) if !meta.file_type().is_symlink() => match path.canonicalize() { + Ok(resolved) if resolved == path => None, + Ok(_) => Some("a directory above it now leads elsewhere through a symlink".to_string()), + Err(e) => Some(format!("its path cannot be resolved ({e})")), + }, + _ => None, } } diff --git a/src/helpers.rs b/src/helpers.rs index f83231a..0788e28 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -16,10 +16,12 @@ pub(crate) fn get_project_directories_with_fallback( } pub(crate) fn get_project_directories(cwd: &Path) -> anyhow::Result> { - let tree = match config::walk_meta_tree(cwd, Some(0)) { - Ok(t) => t, - Err(_) => return Ok(vec![".".to_string()]), - }; + // Without a .meta there is only the root; a .meta that is refused is an + // error, not a reason to act on the root alone + if config::find_meta_config(cwd, None).is_none() { + return Ok(vec![".".to_string()]); + } + let tree = config::walk_meta_tree(cwd, Some(0))?; let mut dirs = vec![".".to_string()]; let mut paths: Vec = tree.iter().map(|n| n.info.path.clone()).collect(); paths.sort(); diff --git a/src/lib.rs b/src/lib.rs index 4198f6c..cd6ae3f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -747,6 +747,23 @@ the only commit message assert_eq!(dirs, vec!["."]); } + #[test] + fn test_get_project_directories_refuses_a_bad_meta_file() { + // A refused config is an error, not "just the root" + let temp_dir = TempDir::new().unwrap(); + std::fs::write( + temp_dir.path().join(".meta"), + r#"{"projects": {"evil": {"repo": "u", "path": "../../x"}}}"#, + ) + .unwrap(); + + let err = get_project_directories(temp_dir.path()).unwrap_err(); + assert!( + format!("{err:#}").contains("must not contain '..'"), + "{err:#}" + ); + } + #[test] fn test_get_project_directories_with_meta_file() { let temp_dir = TempDir::new().unwrap(); From 3801f79dc39ec05945b1b2d7c525b5d736511a86 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:56:39 -0700 Subject: [PATCH 07/13] fix: clone, update and commit fail on a config they cannot read; test the primary-checkout refusal under META_WORKTREES Implements [[tasks/harmony-2749]] --- src/clone.rs | 2 +- src/commands/worktree/prune.rs | 13 +++++++----- src/commit.rs | 2 +- src/update.rs | 26 +++++++++++++----------- tests/safety.rs | 37 ++++++++++++++++++++++++++++++++++ 5 files changed, 61 insertions(+), 19 deletions(-) diff --git a/src/clone.rs b/src/clone.rs index 864ad5b..bc5b27e 100644 --- a/src/clone.rs +++ b/src/clone.rs @@ -143,7 +143,7 @@ pub(crate) fn execute_git_clone( // Parse meta config inside cloned repo let clone_dir_path = cwd.join(&clone_dir); - if config::find_meta_config_in(&clone_dir_path).is_none() { + if config::find_meta_config_in(&clone_dir_path)?.is_none() { return Ok(CommandResult::Message( "No .meta config found in cloned repository".to_string(), )); diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index 27339ff..9022a62 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -41,11 +41,14 @@ fn check_repo_orphaned( .entry(entry.project.clone()) .or_insert_with(|| { let project_path = Path::new(&entry.project); - meta_core::config::find_meta_config_in(project_path).and_then(|(meta_path, _)| { - meta_core::config::parse_meta_config(&meta_path) - .ok() - .map(|(projects, _)| projects) - }) + meta_core::config::find_meta_config_in(project_path) + .ok() + .flatten() + .and_then(|(meta_path, _)| { + meta_core::config::parse_meta_config(&meta_path) + .ok() + .map(|(projects, _)| projects) + }) }); let Some(projects) = config else { diff --git a/src/commit.rs b/src/commit.rs index c55be6b..e8ec22a 100644 --- a/src/commit.rs +++ b/src/commit.rs @@ -41,7 +41,7 @@ pub(crate) fn execute_git_commit( projects.to_vec() } else { // Fall back to reading local meta config - let Some((meta_path, _format)) = config::find_meta_config_in(cwd) else { + let Some((meta_path, _format)) = config::find_meta_config_in(cwd)? else { return Ok(CommandResult::Message(format!( "No .meta config found in {}", escape_path(cwd) diff --git a/src/update.rs b/src/update.rs index 0c3a114..d0b2b1c 100644 --- a/src/update.rs +++ b/src/update.rs @@ -21,17 +21,19 @@ pub(crate) fn execute_git_update( // Build list of directories to check for .meta files let dirs_to_check: Vec = if recursive { // In recursive mode, check each directory that has a .meta file - projects - .iter() - .map(|p| { - if p == "." { - cwd.to_path_buf() - } else { - cwd.join(p) - } - }) - .filter(|path| config::find_meta_config_in(path).is_some()) - .collect() + // A .meta that can't be examined is an error, not "no nested repos" + let mut dirs = Vec::new(); + for p in projects { + let path = if p == "." { + cwd.to_path_buf() + } else { + cwd.join(p) + }; + if config::find_meta_config_in(&path)?.is_some() { + dirs.push(path); + } + } + dirs } else { // Normal mode - just check current directory vec![cwd.to_path_buf()] @@ -44,7 +46,7 @@ pub(crate) fn execute_git_update( // First pass: check for orphaned repos and warn user for dir in &dirs_to_check { - let Some((meta_path, _format)) = config::find_meta_config_in(dir) else { + let Some((meta_path, _format)) = config::find_meta_config_in(dir)? else { continue; }; diff --git a/tests/safety.rs b/tests/safety.rs index 9501bc9..273ae43 100644 --- a/tests/safety.rs +++ b/tests/safety.rs @@ -63,6 +63,18 @@ fn workspace(root: &Path, projects: &[&str]) -> std::path::PathBuf { /// Invoke the plugin protocol in `cwd` with an isolated store under `root/data`. fn meta_git(root: &Path, cwd: &Path, command: &str, args: &[&str], options: Value) -> Output { + meta_git_in(root, cwd, command, args, options, None) +} + +/// [`meta_git`], with `META_WORKTREES` set to `worktrees` if given. +fn meta_git_in( + root: &Path, + cwd: &Path, + command: &str, + args: &[&str], + options: Value, + worktrees: Option<&Path>, +) -> Output { let request = json!({"command": command, "args": args, "cwd": cwd, "options": options}); let mut cmd = Command::new(env!("CARGO_BIN_EXE_meta-git")); if root.join("bin").is_dir() { @@ -75,6 +87,7 @@ fn meta_git(root: &Path, cwd: &Path, command: &str, args: &[&str], options: Valu .current_dir(cwd) .env("META_DATA_DIR", root.join("data")) .env_remove("META_WORKTREES") + .envs(worktrees.map(|dir| ("META_WORKTREES", dir))) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -131,6 +144,30 @@ fn remove_refuses_directories_meta_did_not_create() { stderr(&out) ); assert!(ws.join("a/README").exists()); + + // META_WORKTREES may point anywhere, the workspace root included: there + // the primary clone `a` looks like a set, and the forged record would + // remove it. The removal check refuses a primary checkout. + fs::write( + ws.join(".meta"), + json!({"projects": {"a": "unused"}}).to_string(), + ) + .unwrap(); + let out = meta_git_in( + root, + &ws, + "git worktree remove", + &["a", "--force"], + json!({}), + Some(&ws), + ); + assert!(!out.status.success()); + assert!( + stderr(&out).contains("not a linked worktree"), + "{}", + stderr(&out) + ); + assert!(ws.join("a/README").exists()); } #[test] From 9380ae248d786aef73efd8612fe2b70dcab61f72 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:29:10 -0700 Subject: [PATCH 08/13] fix: worktree add refuses a repo given twice before adding anything Implements [[tasks/harmony-2749]] --- src/commands/worktree/add.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index 5e1f73d..fc5b746 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -35,12 +35,22 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> // Check existing repos in the worktree let existing = discover_worktree_repos(&wt_dir)?; - let mut added = Vec::new(); - for spec in repo_specs { + // A repo given twice can't be added twice: refuse before adding anything, + // or the first add would be left out of the store + for (i, spec) in repo_specs.iter().enumerate() { + if repo_specs.iter().take(i).any(|o| o.alias == spec.alias) { + anyhow::bail!("Repo '{}' is given twice", escape(&spec.alias)); + } if existing.iter().any(|r| r.alias == spec.alias) { - anyhow::bail!("Repo '{}' already exists in worktree '{name}'", spec.alias); + anyhow::bail!( + "Repo '{}' already exists in worktree '{name}'", + escape(&spec.alias) + ); } + } + let mut added = Vec::new(); + for spec in repo_specs { // Use recursive lookup for nested paths (containing '/') let (source, _project) = lookup_nested_project(&meta_dir, &spec.alias)?; From 3710af4c91279e2363c070c1a9194a56649be4eb Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:43:26 -0700 Subject: [PATCH 09/13] fix: escape repo paths and the subject line in meta git commit output Implements [[tasks/harmony-2749]] --- src/commit.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/commit.rs b/src/commit.rs index e8ec22a..c6b430e 100644 --- a/src/commit.rs +++ b/src/commit.rs @@ -1,6 +1,6 @@ use console::style; use meta_core::config; -use meta_core::display::escape_path; +use meta_core::display::{escape, escape_path}; use meta_plugin_protocol::{CommandResult, PlannedCommand, PluginRequestOptions}; use std::process::Command; @@ -105,7 +105,7 @@ pub(crate) fn execute_git_commit( // No message provided, show what would be committed println!("Repositories with staged changes:"); for (name, _path, files) in &repos_with_changes { - println!(" {} ({} files)", style(name).cyan(), files.len()); + println!(" {} ({} files)", style(escape(name)).cyan(), files.len()); } println!(); println!( @@ -222,7 +222,7 @@ fn execute_editor_commit(repos: &[(String, String, Vec)]) -> anyhow::Res println!( "{} Committing {}...", style("→").cyan(), - style(repo_name).bold() + style(escape(repo_name)).bold() ); let status = Command::new("git") @@ -238,7 +238,7 @@ fn execute_editor_commit(repos: &[(String, String, Vec)]) -> anyhow::Res println!( " {} {}", style("✓").green(), - message.lines().next().unwrap_or("") + escape(message.lines().next().unwrap_or("")) ); succeeded += 1; } From 4d0007a1567850e370ea4f93f5b93506bdc71c7c Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:02:02 -0700 Subject: [PATCH 10/13] fix: worktree add checks every repo before adding any and records what it added on failure; quote the ssh remote hint Implements [[tasks/harmony-2749]] --- src/commands/worktree/add.rs | 28 +++++++++++++++++++++------- src/commands/worktree/create.rs | 12 +----------- src/helpers.rs | 13 +++++++++++++ src/ssh.rs | 6 +++--- 4 files changed, 38 insertions(+), 21 deletions(-) diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index fc5b746..e01dd34 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -35,8 +35,9 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> // Check existing repos in the worktree let existing = discover_worktree_repos(&wt_dir)?; - // A repo given twice can't be added twice: refuse before adding anything, - // or the first add would be left out of the store + // Check every repo before adding any: one refused after others were + // added would leave those out of the store + let mut planned = Vec::new(); for (i, spec) in repo_specs.iter().enumerate() { if repo_specs.iter().take(i).any(|o| o.alias == spec.alias) { anyhow::bail!("Repo '{}' is given twice", escape(&spec.alias)); @@ -47,14 +48,10 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> escape(&spec.alias) ); } - } - let mut added = Vec::new(); - for spec in repo_specs { // Use recursive lookup for nested paths (containing '/') let (source, _project) = lookup_nested_project(&meta_dir, &spec.alias)?; - let branch = resolve_branch(name, None, spec.branch.as_deref()); // Preserve the full alias as the destination path so that relative // references (e.g., Cargo.toml workspace members) remain valid. let dest = wt_dir.join(&spec.alias); @@ -66,6 +63,13 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> escape(&spec.alias) ) })?; + planned.push((spec, source, dest)); + } + + let mut added = Vec::new(); + let mut failed = None; + for (spec, source, dest) in planned { + let branch = resolve_branch(name, None, spec.branch.as_deref()); // Ensure parent directories exist for nested paths (e.g., "vendor/") if let Some(parent) = dest.parent() { @@ -83,7 +87,14 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> ); } - let created_branch = git_worktree_add(&source, &dest, &branch, None)?.is_some(); + // A failed add stops here, but what was added is still recorded + let created_branch = match git_worktree_add(&source, &dest, &branch, None) { + Ok(created) => created.is_some(), + Err(e) => { + failed = Some(e); + break; + } + }; added.push(CreateRepoEntry { alias: spec.alias.clone(), path: dest.display().to_string(), @@ -97,6 +108,9 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> store_extend_repos(&wt_dir, new_repos).with_context(|| { format!("Added repos to worktree '{name}', but could not update the worktree store") })?; + if let Some(e) = failed { + return Err(e); + } if json { let output = AddOutput { diff --git a/src/commands/worktree/create.rs b/src/commands/worktree/create.rs index b88a9ee..c0ad8cc 100644 --- a/src/commands/worktree/create.rs +++ b/src/commands/worktree/create.rs @@ -15,6 +15,7 @@ use meta_git_lib::worktree::types::{ }; use super::cli_types::CreateArgs; +use crate::helpers::shell_quote; pub(crate) fn handle_create( args: CreateArgs, @@ -534,17 +535,6 @@ fn print_create_dry_run(plan: &CreateDryRunPlan<'_>) { println!("No directories, branches, store entries, hooks, or .gitignore changes were written."); } -fn shell_quote(value: &str) -> String { - if value - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')) - { - value.to_string() - } else { - format!("'{}'", value.replace('\'', "'\\''")) - } -} - /// Resolve repos with automatic dependency resolution. /// /// When --repo is specified without --no-deps: diff --git a/src/helpers.rs b/src/helpers.rs index 0788e28..7ea2151 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -28,3 +28,16 @@ pub(crate) fn get_project_directories(cwd: &Path) -> anyhow::Result> dirs.extend(paths); Ok(dirs) } + +/// `value` quoted for a POSIX shell, for commands meta prints for the user +/// to paste: plain words stay as they are. +pub(crate) fn shell_quote(value: &str) -> String { + if value + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | ':')) + { + value.to_string() + } else { + format!("'{}'", value.replace('\'', "'\\''")) + } +} diff --git a/src/ssh.rs b/src/ssh.rs index af7c329..0c06c36 100644 --- a/src/ssh.rs +++ b/src/ssh.rs @@ -100,9 +100,9 @@ pub(crate) fn warn_remote_mismatches(cwd: &Path) { eprintln!(" Fix manually with:"); for m in &mismatches { eprintln!( - " git -C '{}' remote set-url origin '{}'", - escape(&m.path), - escape(&m.expected) + " git -C {} remote set-url origin {}", + escape(&crate::helpers::shell_quote(&m.path)), + escape(&crate::helpers::shell_quote(&m.expected)) ); } } From 7a27e548529692ae8b64a2b821fd2adb09df2c68 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:16:46 -0700 Subject: [PATCH 11/13] fix: worktree add checks each destination again right before adding it An earlier add in the same call (a parent repo on another branch) can put a symlink where a later repo goes, so the up-front check is not enough; create already checks before each add. A repeated --repo on the same branch is now one worktree, as in create. Implements [[tasks/harmony-2749]] --- src/commands/worktree/add.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index e01dd34..8123dd3 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -39,8 +39,18 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> // added would leave those out of the store let mut planned = Vec::new(); for (i, spec) in repo_specs.iter().enumerate() { - if repo_specs.iter().take(i).any(|o| o.alias == spec.alias) { - anyhow::bail!("Repo '{}' is given twice", escape(&spec.alias)); + // As in create: a repeat is one worktree, a repeat on another branch + // is refused + if let Some(first) = repo_specs.iter().take(i).find(|o| o.alias == spec.alias) { + if first.branch != spec.branch { + anyhow::bail!( + "Repo '{}' is given twice, on branches '{}' and '{}'", + escape(&spec.alias), + escape(first.branch.as_deref().unwrap_or("(default)")), + escape(spec.branch.as_deref().unwrap_or("(default)")) + ); + } + continue; } if existing.iter().any(|r| r.alias == spec.alias) { anyhow::bail!( @@ -70,6 +80,15 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> let mut failed = None; for (spec, source, dest) in planned { let branch = resolve_branch(name, None, spec.branch.as_deref()); + // Again now: a checkout added above (a parent repo's) may have put a + // symlink where this one goes + if let Err(why) = meta_core::config::resolve_inside(&wt_dir, &spec.alias) { + failed = Some(anyhow::anyhow!( + "Refusing to add the worktree for '{}': {why}", + escape(&spec.alias) + )); + break; + } // Ensure parent directories exist for nested paths (e.g., "vendor/") if let Some(parent) = dest.parent() { From 49dff7fa6538e3d4543877f085ffa0fa805db090 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:34:51 -0700 Subject: [PATCH 12/13] fix: worktree add records what it added when a parent dir cannot be created Implements [[tasks/harmony-2749]] --- src/commands/worktree/add.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index 8123dd3..5e1b486 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -93,7 +93,13 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> // Ensure parent directories exist for nested paths (e.g., "vendor/") if let Some(parent) = dest.parent() { if parent != wt_dir { - std::fs::create_dir_all(parent)?; + if let Err(e) = std::fs::create_dir_all(parent) { + failed = Some( + anyhow::Error::from(e) + .context(format!("Cannot create {}", escape_path(parent))), + ); + break; + } } } From af2ac75a49d76d19cb61a0368b2f0cca3000c954 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:54:02 -0700 Subject: [PATCH 13/13] fix: worktree add reports what it added and both errors; prune reports every failure Implements [[tasks/harmony-2749]] --- src/commands/worktree/add.rs | 24 +++++++++++++++--------- src/commands/worktree/prune.rs | 11 +++++++++-- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/commands/worktree/add.rs b/src/commands/worktree/add.rs index 5e1b486..fe35359 100644 --- a/src/commands/worktree/add.rs +++ b/src/commands/worktree/add.rs @@ -128,14 +128,16 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> }); } - // Update centralized store - let new_repos: Vec = added.iter().map(StoreRepoEntry::from).collect(); - store_extend_repos(&wt_dir, new_repos).with_context(|| { - format!("Added repos to worktree '{name}', but could not update the worktree store") - })?; - if let Some(e) = failed { - return Err(e); - } + // Record what was added (if anything), then report it, then any error: + // a failed add and a failed store write are both shown + let stored = if added.is_empty() { + Ok(()) + } else { + let new_repos: Vec = added.iter().map(StoreRepoEntry::from).collect(); + store_extend_repos(&wt_dir, new_repos).with_context(|| { + format!("Added repos to worktree '{name}', but could not update the worktree store") + }) + }; if json { let output = AddOutput { @@ -157,5 +159,9 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool) -> Result<()> } } - Ok(()) + match (failed, stored) { + (Some(e), Err(store)) => Err(e.context(format!("{store:#}"))), + (Some(e), Ok(())) => Err(e), + (None, stored) => stored, + } } diff --git a/src/commands/worktree/prune.rs b/src/commands/worktree/prune.rs index 9022a62..6a5e96c 100644 --- a/src/commands/worktree/prune.rs +++ b/src/commands/worktree/prune.rs @@ -342,9 +342,16 @@ pub(crate) fn handle_prune( print_kept(&kept); } - stored?; + // Every failure is reported, the store's and the sets' alike + let mut problems = Vec::new(); + if let Err(e) = stored { + problems.push(format!("{e:#}")); + } if !failed.is_empty() { - anyhow::bail!("Failed to prune: {}", escape(&failed.join(", "))); + problems.push(format!("Failed to prune: {}", escape(&failed.join(", ")))); + } + if !problems.is_empty() { + anyhow::bail!("{}", problems.join("\n")); } warn_kept(&kept, strict) }