Skip to content
This repository was archived by the owner on Nov 3, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
13 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand All @@ -33,6 +34,3 @@ console = "0.15"
log = "0.4"
colored = "2"
indexmap = "2"

[dev-dependencies]
tempfile = "3.3"
2 changes: 1 addition & 1 deletion src/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
));
Expand Down
57 changes: 49 additions & 8 deletions src/clone_worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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);
Expand Down Expand Up @@ -98,6 +107,19 @@ 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() {
// 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{}{failed}",
errors.join("\n")
);
}
Ok(())
}

Expand All @@ -112,11 +134,12 @@ pub(crate) fn report_failures(queue: &CloneQueue) -> Option<String> {
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();
Expand All @@ -137,7 +160,14 @@ fn clone_single_repo(
queue: &Arc<CloneQueue>,
pb: &ProgressBar,
ssh_cmd: Option<&str>,
nested_errors: &Mutex<Vec<String>>,
) {
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
Expand All @@ -152,7 +182,12 @@ 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;
}
Expand All @@ -179,7 +214,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();
Expand Down Expand Up @@ -208,9 +244,14 @@ 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);
}
}
}
Expand Down
104 changes: 85 additions & 19 deletions src/commands/worktree/add.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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)?;

Expand All @@ -25,46 +26,100 @@ 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
let existing = discover_worktree_repos(&wt_dir)?;

let mut added = Vec::new();
for spec in repo_specs {
// 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() {
// 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!("Repo '{}' already exists in worktree '{name}'", spec.alias);
anyhow::bail!(
"Repo '{}' already exists in worktree '{name}'",
escape(&spec.alias)
);
}

// 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);
// 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)
)
})?;
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());
// 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() {
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;
}
}
}

if verbose {
eprintln!(
"Adding worktree for '{}' at {} (branch: {})",
spec.alias,
dest.display(),
branch
escape(&spec.alias),
escape_path(&dest),
escape(&branch)
);
}

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(),
Expand All @@ -73,9 +128,16 @@ pub(crate) fn handle_add(args: AddArgs, verbose: bool, json: bool, strict: bool)
});
}

// Update centralized store
let new_repos: Vec<StoreRepoEntry> = added.iter().map(StoreRepoEntry::from).collect();
super::warn_store_error(store_extend_repos(&wt_dir, new_repos), strict)?;
// 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<StoreRepoEntry> = 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 {
Expand All @@ -89,13 +151,17 @@ 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
);
}
}

Ok(())
match (failed, stored) {
(Some(e), Err(store)) => Err(e.context(format!("{store:#}"))),
(Some(e), Ok(())) => Err(e),
(None, stored) => stored,
}
}
Loading
Loading