From 794c8075f8b981905b7e036708d10c5217a5aae9 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:19:07 -0700 Subject: [PATCH 1/4] fix: pass every meta cargo command through to cargo meta-rust only handled cargo build/test and answered everything else (fmt, clippy, --version, ...) with its help. It now runs cargo with the given args in each selected repo that has a Cargo.toml, skips the others with a note, quotes args for the shell, stops running the meta root twice, and runs a Cargo workspace once from its root instead of again in each member repo. The rust build/test aliases are gone; meta cargo is the one command. Implements [[tasks/harmony-2746]] --- Cargo.toml | 5 +- src/lib.rs | 360 ++++++++++++++++++++++++++++------------------------ src/main.rs | 41 +++--- 3 files changed, 208 insertions(+), 198 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 28c1d82..11bf88e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ version.workspace = true edition.workspace = true license.workspace = true repository.workspace = true -description = "Rust plugin for meta CLI to run cargo commands across Rust projects" +description = "Rust plugin for meta CLI to run any cargo command across Rust repos" [[bin]] name = "meta-rust" @@ -16,8 +16,7 @@ path = "src/lib.rs" [dependencies] meta_plugin_protocol = { path = "../meta_plugin_protocol" } -meta_core = { path = "../meta_core" } -anyhow = "1" +shlex = "1" colored = "2" serde_json = "1" indexmap = "2" diff --git a/src/lib.rs b/src/lib.rs index 9c62a16..b8aeeb5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,133 +1,164 @@ //! meta-rust library //! -//! Provides Rust/Cargo commands for meta repositories. +//! Runs any cargo command across the Rust repos of a meta workspace. -pub use meta_plugin_protocol::{ - output_execution_plan, CommandResult, ExecutionPlan, PlanResponse, PlannedCommand, -}; -use std::path::Path; +pub use meta_plugin_protocol::{CommandResult, PlannedCommand, PluginRequestOptions}; +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::process::Command; -/// Get all project directories from .meta config (including root ".") -/// If provided_projects is not empty, uses that list instead (for --recursive support) -fn get_project_directories( - provided_projects: &[String], - cwd: &Path, -) -> anyhow::Result> { - // If we have provided projects from meta_cli (e.g., when --recursive is used), use them - if !provided_projects.is_empty() { - // Include root "." plus all provided project paths - let mut dirs = vec![".".to_string()]; - for p in provided_projects { - dirs.push(p.clone()); - } - return Ok(dirs); - } - - // Use canonical config parsing (supports JSON + YAML) - let tree = match meta_core::config::walk_meta_tree(cwd, Some(0)) { - Ok(t) => t, - Err(_) => return Ok(vec![".".to_string()]), - }; - let mut dirs = vec![".".to_string()]; - let mut paths: Vec = tree.iter().map(|n| n.info.path.clone()).collect(); - paths.sort(); - dirs.extend(paths); - Ok(dirs) -} - -/// Filter directories to only those with Cargo.toml -fn filter_rust_projects(dirs: &[String], cwd: &Path) -> Vec { - dirs.iter() - .filter(|dir| { - let cargo_path = if *dir == "." { - cwd.join("Cargo.toml") - } else { - cwd.join(dir).join("Cargo.toml") - }; - cargo_path.exists() - }) - .cloned() - .collect() -} - -/// Execute a Rust/Cargo command and return the result +/// Plan `cargo ` in every selected repo that has a `Cargo.toml`. /// -/// If `provided_projects` is not empty, it will be used instead of reading from .meta file. -/// This allows meta_cli to pass in the full project list when --recursive is used. +/// `projects` is the repo list from meta_cli (it includes the meta root); +/// when it is empty the plan runs in `cwd` only. Include/exclude filters are +/// applied here, the same way loop_lib applies them, so that workspace +/// members are only skipped when their workspace root is really selected. pub fn execute_command( - command: &str, args: &[String], - parallel: bool, - provided_projects: &[String], + options: &PluginRequestOptions, + projects: &[String], cwd: &Path, ) -> CommandResult { - // Intercept --help/-h before dispatching to subcommand handlers - if command - .split_whitespace() - .chain(args.iter().map(String::as_str)) - .any(|a| a == "--help" || a == "-h") - { + // `meta cargo` and `meta cargo --help` show this plugin's help + // instead of running cargo once per repo. Args after `--` belong to cargo. + let mut before_separator = args.iter().take_while(|a| *a != "--"); + if args.is_empty() || before_separator.any(|a| a == "--help" || a == "-h") { return CommandResult::ShowHelp(None); } - // Get all project directories - let dirs = match get_project_directories(provided_projects, cwd) { - Ok(d) => d, - Err(e) => return CommandResult::Error(format!("Failed to get project directories: {e}")), + let cmd = match shlex::try_join(std::iter::once("cargo").chain(args.iter().map(String::as_str))) + { + Ok(cmd) => cmd, + Err(e) => return CommandResult::Error(format!("Cannot quote cargo arguments: {e}")), }; - // Filter to Rust projects only - let rust_dirs = filter_rust_projects(&dirs, cwd); + let dirs: Vec = if projects.is_empty() { + vec![".".to_string()] + } else { + projects.to_vec() + }; + // Notes name repos by their path from the meta root, which meta_cli lists first. + let root = cwd.join(dirs.first().map_or(".", String::as_str)); + let dirs = filter_dirs(dirs, options); + let (mut rust_dirs, other_dirs): (Vec, Vec) = dirs + .into_iter() + .partition(|dir| cwd.join(dir).join("Cargo.toml").is_file()); + let workspaces = workspace_members(&rust_dirs, cwd); + rust_dirs.retain(|dir| !workspaces.iter().any(|(_, members)| members.contains(dir))); + + if !options.silent { + note(&other_dirs, "no Cargo.toml", &root); + for (workspace, members) in &workspaces { + let reason = format!( + "cargo runs on them from the workspace at {}", + display(workspace, &root) + ); + note(members, &reason, &root); + } + } if rust_dirs.is_empty() { return CommandResult::Message("No Rust projects found (no Cargo.toml files)".to_string()); } - // Build the cargo command - let cargo_cmd = match command { - "cargo build" | "rust build" => { - let mut cmd = "cargo build".to_string(); - for arg in args { - cmd.push(' '); - cmd.push_str(arg); - } - cmd - } - "cargo test" | "rust test" => { - let mut cmd = "cargo test".to_string(); - for arg in args { - cmd.push(' '); - cmd.push_str(arg); - } - cmd - } - _ => return CommandResult::ShowHelp(Some(format!("unrecognized command '{command}'"))), - }; - - // Build execution plan - let commands: Vec = rust_dirs - .iter() + let commands = rust_dirs + .into_iter() .map(|dir| PlannedCommand { - dir: dir.clone(), - cmd: cargo_cmd.clone(), + dir, + cmd: cmd.clone(), env: None, }) .collect(); + CommandResult::Plan(commands, Some(options.parallel)) +} - CommandResult::Plan(commands, Some(parallel)) +/// Keep the dirs loop_lib will run in (substring match, like loop_lib). +fn filter_dirs(mut dirs: Vec, options: &PluginRequestOptions) -> Vec { + if let Some(includes) = options.include_filters.as_ref().filter(|f| !f.is_empty()) { + dirs.retain(|dir| includes.iter().any(|f| dir.contains(f.as_str()))); + } + if let Some(excludes) = &options.exclude_filters { + dirs.retain(|dir| { + !excludes + .iter() + .any(|f| dir.contains(f.trim_end_matches('/'))) + }); + } + dirs +} + +/// Each dir in `rust_dirs` that is a workspace root, with the other dirs in +/// `rust_dirs` whose package it builds by default. Cargo in the root already +/// runs on those members. +fn workspace_members(rust_dirs: &[String], cwd: &Path) -> Vec<(String, Vec)> { + let manifest = |dir: &str| cwd.join(dir).join("Cargo.toml").canonicalize().ok(); + let mut workspaces = Vec::new(); + for root in rust_dirs { + let root_path = cwd.join(root); + let nested = || { + rust_dirs + .iter() + .filter(|dir| *dir != root && cwd.join(dir).starts_with(&root_path)) + }; + if nested().next().is_none() { + continue; + } + let manifests = default_member_manifests(&root_path); + let members: Vec = nested() + .filter(|dir| manifest(dir).is_some_and(|m| manifests.contains(&m))) + .cloned() + .collect(); + if !members.is_empty() { + workspaces.push((root.clone(), members)); + } + } + workspaces } -/// Get help text for the plugin -pub fn get_help_text() -> &'static str { - r#"meta rust - Rust/Cargo Plugin +/// Manifests of the packages `cargo` in `root` acts on by default, or none if +/// `root` is not a workspace root or some members are not default members. +fn default_member_manifests(root: &Path) -> Vec { + let Ok(output) = Command::new("cargo") + .args(["metadata", "--no-deps", "--format-version", "1"]) + .current_dir(root) + .output() + else { + return Vec::new(); + }; + let Ok(meta) = serde_json::from_slice::(&output.stdout) else { + return Vec::new(); + }; + let is_root = meta["workspace_root"] + .as_str() + .and_then(|r| Path::new(r).canonicalize().ok()) + .zip(root.canonicalize().ok()) + .is_some_and(|(a, b)| a == b); + if !is_root || meta["workspace_members"] != meta["workspace_default_members"] { + return Vec::new(); + } + meta["packages"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p["manifest_path"].as_str()) + .filter_map(|m| Path::new(m).canonicalize().ok()) + .collect() +} -Commands: - meta cargo build Run cargo build across all Rust projects - meta cargo test Run cargo test across all Rust projects +fn note(dirs: &[String], reason: &str, root: &Path) { + if dirs.is_empty() { + return; + } + let names: Vec = dirs.iter().map(|dir| display(dir, root)).collect(); + eprintln!("meta-rust: skipping {} ({reason})", names.join(", ")); +} -This plugin detects Rust projects (by presence of Cargo.toml) and runs -the specified cargo command. Non-Rust directories are skipped. -"# +fn display(dir: &str, root: &Path) -> String { + match root.join(dir).strip_prefix(root) { + Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(), + Ok(rel) => rel.display().to_string(), + Err(_) => dir.to_string(), + } } #[cfg(test)] @@ -135,88 +166,79 @@ mod tests { use super::*; use tempfile::TempDir; - #[test] - fn test_unknown_command() { - let result = execute_command("cargo unknown", &[], false, &[], Path::new(".")); - match result { - CommandResult::ShowHelp(Some(msg)) => assert!(msg.contains("unrecognized command")), - _ => panic!("Expected ShowHelp result"), - } + fn write(path: PathBuf, contents: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, contents).unwrap(); } - #[test] - fn test_get_help_text() { - let help = get_help_text(); - assert!(help.contains("cargo build")); - assert!(help.contains("cargo test")); + fn plan(args: &[&str], projects: &[&str], cwd: &Path) -> Vec { + let args: Vec = args.iter().map(|a| a.to_string()).collect(); + let projects: Vec = projects.iter().map(|p| p.to_string()).collect(); + let options = PluginRequestOptions::default(); + match execute_command(&args, &options, &projects, cwd) { + CommandResult::Plan(commands, _) => commands, + _ => panic!("Expected Plan result"), + } } #[test] - fn test_no_rust_projects() { - let temp_dir = TempDir::new().unwrap(); - - // Create .meta with no Rust projects - std::fs::write(temp_dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap(); + fn any_cargo_command_runs_in_rust_repos_only() { + let temp = TempDir::new().unwrap(); + let root = temp.path().display().to_string(); + let rust = temp.path().join("rust").display().to_string(); + let docs = temp.path().join("docs").display().to_string(); + write( + temp.path().join("rust/Cargo.toml"), + "[package]\nname = \"rust\"\n", + ); + std::fs::create_dir_all(temp.path().join("docs")).unwrap(); - let result = execute_command("cargo build", &[], false, &[], temp_dir.path()); + let commands = plan( + &["fmt", "--check", "--", "--config", "a b"], + &[&root, &rust, &docs], + temp.path(), + ); - match result { - CommandResult::Message(msg) => assert!(msg.contains("No Rust projects")), - _ => panic!("Expected Message result"), - } + assert_eq!(commands.len(), 1); + assert_eq!(commands[0].dir, rust); + assert_eq!(commands[0].cmd, "cargo fmt --check -- --config 'a b'"); } #[test] - fn test_cargo_build_returns_plan() { - let temp_dir = TempDir::new().unwrap(); - - // Create a Cargo.toml in root - std::fs::write( - temp_dir.path().join("Cargo.toml"), - "[package]\nname = \"test\"\n", - ) - .unwrap(); - std::fs::write(temp_dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap(); - - let result = execute_command( - "cargo build", - &["--release".to_string()], - true, - &[], - temp_dir.path(), + fn workspace_members_run_once_from_the_root() { + let temp = TempDir::new().unwrap(); + let root = temp.path().display().to_string(); + let member = temp.path().join("member").display().to_string(); + let own = temp.path().join("own").display().to_string(); + write( + temp.path().join("Cargo.toml"), + "[workspace]\nmembers = [\"member\"]\nexclude = [\"own\"]\n", ); + for name in ["member", "own"] { + write( + temp.path().join(name).join("Cargo.toml"), + &format!("[package]\nname = \"{name}\"\n"), + ); + write(temp.path().join(name).join("src/lib.rs"), ""); + } - match result { - CommandResult::Plan(commands, parallel) => { + let commands = plan(&["--version"], &[&root, &member, &own], temp.path()); + let dirs: Vec<&str> = commands.iter().map(|c| c.dir.as_str()).collect(); + assert_eq!(dirs, [root.as_str(), own.as_str()]); + + // With the root filtered out, the member runs on its own. + let options = PluginRequestOptions { + include_filters: Some(vec!["member".to_string()]), + ..Default::default() + }; + let args = vec!["--version".to_string()]; + let projects = vec![root, member.clone(), own]; + match execute_command(&args, &options, &projects, temp.path()) { + CommandResult::Plan(commands, _) => { assert_eq!(commands.len(), 1); - assert_eq!(commands[0].dir, "."); - assert!(commands[0].cmd.contains("cargo build")); - assert!(commands[0].cmd.contains("--release")); - assert_eq!(parallel, Some(true)); + assert_eq!(commands[0].dir, member); } _ => panic!("Expected Plan result"), } } - - #[test] - fn test_execution_plan_serialization() { - let commands = vec![PlannedCommand { - dir: ".".to_string(), - cmd: "cargo test".to_string(), - env: None, - }]; - let plan = ExecutionPlan { - pre_commands: vec![], - commands, - post_commands: vec![], - parallel: Some(true), - max_parallel: None, - spawn_stagger_ms: None, - }; - let response = PlanResponse { plan }; - let json = serde_json::to_string(&response).unwrap(); - assert!(json.contains("\"plan\"")); - assert!(json.contains("\"commands\"")); - assert!(json.contains("cargo test")); - } } diff --git a/src/main.rs b/src/main.rs index 7538de7..a1e34ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,37 +9,32 @@ use std::path::PathBuf; fn main() { let mut help_commands = IndexMap::new(); help_commands.insert( - "build".to_string(), - "Build all Rust projects in the workspace".to_string(), - ); - help_commands.insert( - "test".to_string(), - "Run tests across all Rust projects".to_string(), + "cargo".to_string(), + "Run cargo with your args in each selected repo that has a Cargo.toml".to_string(), ); run_plugin(PluginDefinition { info: PluginInfo { name: "rust".to_string(), version: env!("CARGO_PKG_VERSION").to_string(), - commands: vec![ - "cargo build".to_string(), - "cargo test".to_string(), - "rust build".to_string(), - "rust test".to_string(), - ], - description: Some("Rust/Cargo commands for meta repositories".to_string()), + commands: vec!["cargo".to_string()], + description: Some("Run cargo across the Rust repos of a meta workspace".to_string()), help: Some(PluginHelp { - usage: "meta cargo [args...]\n meta rust [args...]" - .to_string(), + usage: "meta cargo ".to_string(), commands: help_commands, command_sections: IndexMap::new(), examples: vec![ - "meta cargo build".to_string(), - "meta cargo test".to_string(), - "meta rust build".to_string(), "meta cargo build --release".to_string(), + "meta cargo fmt --check".to_string(), + "meta --include api cargo clippy --all-targets -- -D warnings".to_string(), + "meta cargo --version".to_string(), ], - note: Some("To run raw cargo commands: meta exec -- cargo ".to_string()), + note: Some( + "Repos without a Cargo.toml are skipped. A repo whose package is a default \ + member of a Cargo workspace rooted at another selected repo is skipped too: \ + cargo already runs on it from that root. For cargo's own help: cargo help " + .to_string(), + ), }), }, execute, @@ -56,11 +51,5 @@ fn execute(request: PluginRequest) -> CommandResult { PathBuf::from(&request.cwd) }; - meta_rust_cli::execute_command( - &request.command, - &request.args, - request.options.parallel, - &request.projects, - &cwd, - ) + meta_rust_cli::execute_command(&request.args, &request.options, &request.projects, &cwd) } From c6d85a79611185607a69a7130f57e88db4a5a99f Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:22:39 -0700 Subject: [PATCH 2/4] fix: run cargo in every selected Rust repo, workspace members too Skipping members of a workspace rooted at another selected repo is wrong for commands that depend on the current package (run, add, install --path ., third-party subcommands). Drop it; plain cargo in the root runs a cross-repo workspace once. Implements [[tasks/harmony-2746]] --- Cargo.toml | 1 - src/lib.rs | 178 ++++++++++++---------------------------------------- src/main.rs | 6 +- 3 files changed, 43 insertions(+), 142 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 11bf88e..cfca9d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,6 @@ path = "src/lib.rs" meta_plugin_protocol = { path = "../meta_plugin_protocol" } shlex = "1" colored = "2" -serde_json = "1" indexmap = "2" [dev-dependencies] diff --git a/src/lib.rs b/src/lib.rs index b8aeeb5..efa2e4d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,16 +3,13 @@ //! Runs any cargo command across the Rust repos of a meta workspace. pub use meta_plugin_protocol::{CommandResult, PlannedCommand, PluginRequestOptions}; -use serde_json::Value; -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; /// Plan `cargo ` in every selected repo that has a `Cargo.toml`. /// /// `projects` is the repo list from meta_cli (it includes the meta root); -/// when it is empty the plan runs in `cwd` only. Include/exclude filters are -/// applied here, the same way loop_lib applies them, so that workspace -/// members are only skipped when their workspace root is really selected. +/// when it is empty the plan runs in `cwd` only. A Cargo workspace that spans +/// repos runs in each of them; plain `cargo` in its root runs it once. pub fn execute_command( args: &[String], options: &PluginRequestOptions, @@ -39,22 +36,13 @@ pub fn execute_command( }; // Notes name repos by their path from the meta root, which meta_cli lists first. let root = cwd.join(dirs.first().map_or(".", String::as_str)); - let dirs = filter_dirs(dirs, options); - let (mut rust_dirs, other_dirs): (Vec, Vec) = dirs + let (rust_dirs, other_dirs): (Vec, Vec) = filter_dirs(dirs, options) .into_iter() .partition(|dir| cwd.join(dir).join("Cargo.toml").is_file()); - let workspaces = workspace_members(&rust_dirs, cwd); - rust_dirs.retain(|dir| !workspaces.iter().any(|(_, members)| members.contains(dir))); - - if !options.silent { - note(&other_dirs, "no Cargo.toml", &root); - for (workspace, members) in &workspaces { - let reason = format!( - "cargo runs on them from the workspace at {}", - display(workspace, &root) - ); - note(members, &reason, &root); - } + + if !options.silent && !other_dirs.is_empty() { + let names: Vec = other_dirs.iter().map(|dir| display(dir, &root)).collect(); + eprintln!("meta-rust: skipping {} (no Cargo.toml)", names.join(", ")); } if rust_dirs.is_empty() { @@ -72,7 +60,8 @@ pub fn execute_command( CommandResult::Plan(commands, Some(options.parallel)) } -/// Keep the dirs loop_lib will run in (substring match, like loop_lib). +/// Keep the dirs loop_lib will run in (its substring match), so the skip note +/// names only selected repos. fn filter_dirs(mut dirs: Vec, options: &PluginRequestOptions) -> Vec { if let Some(includes) = options.include_filters.as_ref().filter(|f| !f.is_empty()) { dirs.retain(|dir| includes.iter().any(|f| dir.contains(f.as_str()))); @@ -87,72 +76,6 @@ fn filter_dirs(mut dirs: Vec, options: &PluginRequestOptions) -> Vec Vec<(String, Vec)> { - let manifest = |dir: &str| cwd.join(dir).join("Cargo.toml").canonicalize().ok(); - let mut workspaces = Vec::new(); - for root in rust_dirs { - let root_path = cwd.join(root); - let nested = || { - rust_dirs - .iter() - .filter(|dir| *dir != root && cwd.join(dir).starts_with(&root_path)) - }; - if nested().next().is_none() { - continue; - } - let manifests = default_member_manifests(&root_path); - let members: Vec = nested() - .filter(|dir| manifest(dir).is_some_and(|m| manifests.contains(&m))) - .cloned() - .collect(); - if !members.is_empty() { - workspaces.push((root.clone(), members)); - } - } - workspaces -} - -/// Manifests of the packages `cargo` in `root` acts on by default, or none if -/// `root` is not a workspace root or some members are not default members. -fn default_member_manifests(root: &Path) -> Vec { - let Ok(output) = Command::new("cargo") - .args(["metadata", "--no-deps", "--format-version", "1"]) - .current_dir(root) - .output() - else { - return Vec::new(); - }; - let Ok(meta) = serde_json::from_slice::(&output.stdout) else { - return Vec::new(); - }; - let is_root = meta["workspace_root"] - .as_str() - .and_then(|r| Path::new(r).canonicalize().ok()) - .zip(root.canonicalize().ok()) - .is_some_and(|(a, b)| a == b); - if !is_root || meta["workspace_members"] != meta["workspace_default_members"] { - return Vec::new(); - } - meta["packages"] - .as_array() - .into_iter() - .flatten() - .filter_map(|p| p["manifest_path"].as_str()) - .filter_map(|m| Path::new(m).canonicalize().ok()) - .collect() -} - -fn note(dirs: &[String], reason: &str, root: &Path) { - if dirs.is_empty() { - return; - } - let names: Vec = dirs.iter().map(|dir| display(dir, root)).collect(); - eprintln!("meta-rust: skipping {} ({reason})", names.join(", ")); -} - fn display(dir: &str, root: &Path) -> String { match root.join(dir).strip_prefix(root) { Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(), @@ -166,17 +89,20 @@ mod tests { use super::*; use tempfile::TempDir; - fn write(path: PathBuf, contents: &str) { + fn write(dir: &Path, file: &str, contents: &str) { + let path = dir.join(file); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, contents).unwrap(); } - fn plan(args: &[&str], projects: &[&str], cwd: &Path) -> Vec { + fn plan(args: &[&str], projects: &[&Path], options: &PluginRequestOptions) -> Vec { let args: Vec = args.iter().map(|a| a.to_string()).collect(); - let projects: Vec = projects.iter().map(|p| p.to_string()).collect(); - let options = PluginRequestOptions::default(); - match execute_command(&args, &options, &projects, cwd) { - CommandResult::Plan(commands, _) => commands, + let projects: Vec = projects.iter().map(|p| p.display().to_string()).collect(); + match execute_command(&args, options, &projects, Path::new(".")) { + CommandResult::Plan(commands, _) => commands + .into_iter() + .map(|c| format!("{}: {}", c.dir, c.cmd)) + .collect(), _ => panic!("Expected Plan result"), } } @@ -184,61 +110,37 @@ mod tests { #[test] fn any_cargo_command_runs_in_rust_repos_only() { let temp = TempDir::new().unwrap(); - let root = temp.path().display().to_string(); - let rust = temp.path().join("rust").display().to_string(); - let docs = temp.path().join("docs").display().to_string(); - write( - temp.path().join("rust/Cargo.toml"), - "[package]\nname = \"rust\"\n", - ); - std::fs::create_dir_all(temp.path().join("docs")).unwrap(); - - let commands = plan( - &["fmt", "--check", "--", "--config", "a b"], - &[&root, &rust, &docs], + let (root, rust, docs) = ( temp.path(), + temp.path().join("rust"), + temp.path().join("docs"), ); + write(&rust, "Cargo.toml", "[package]\nname = \"rust\"\n"); + write(&docs, "README.md", ""); + + let args = ["fmt", "--check", "--", "--config", "a b"]; + let commands = plan(&args, &[root, &rust, &docs], &Default::default()); - assert_eq!(commands.len(), 1); - assert_eq!(commands[0].dir, rust); - assert_eq!(commands[0].cmd, "cargo fmt --check -- --config 'a b'"); + let expected = format!("{}: cargo fmt --check -- --config 'a b'", rust.display()); + assert_eq!(commands, [expected]); } #[test] - fn workspace_members_run_once_from_the_root() { + fn workspace_members_run_in_their_own_repos_within_filters() { let temp = TempDir::new().unwrap(); - let root = temp.path().display().to_string(); - let member = temp.path().join("member").display().to_string(); - let own = temp.path().join("own").display().to_string(); - write( - temp.path().join("Cargo.toml"), - "[workspace]\nmembers = [\"member\"]\nexclude = [\"own\"]\n", - ); - for name in ["member", "own"] { - write( - temp.path().join(name).join("Cargo.toml"), - &format!("[package]\nname = \"{name}\"\n"), - ); - write(temp.path().join(name).join("src/lib.rs"), ""); - } - - let commands = plan(&["--version"], &[&root, &member, &own], temp.path()); - let dirs: Vec<&str> = commands.iter().map(|c| c.dir.as_str()).collect(); - assert_eq!(dirs, [root.as_str(), own.as_str()]); + let (root, member) = (temp.path(), temp.path().join("member")); + write(root, "Cargo.toml", "[workspace]\nmembers = [\"member\"]\n"); + write(&member, "Cargo.toml", "[package]\nname = \"member\"\n"); - // With the root filtered out, the member runs on its own. - let options = PluginRequestOptions { + let all = plan(&["run"], &[root, &member], &Default::default()); + let only_member = PluginRequestOptions { include_filters: Some(vec!["member".to_string()]), ..Default::default() }; - let args = vec!["--version".to_string()]; - let projects = vec![root, member.clone(), own]; - match execute_command(&args, &options, &projects, temp.path()) { - CommandResult::Plan(commands, _) => { - assert_eq!(commands.len(), 1); - assert_eq!(commands[0].dir, member); - } - _ => panic!("Expected Plan result"), - } + let filtered = plan(&["run"], &[root, &member], &only_member); + + let run_in = |dir: &Path| format!("{}: cargo run", dir.display()); + assert_eq!(all, [run_in(root), run_in(&member)]); + assert_eq!(filtered, [run_in(&member)]); } } diff --git a/src/main.rs b/src/main.rs index a1e34ad..f74cb52 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,9 +30,9 @@ fn main() { "meta cargo --version".to_string(), ], note: Some( - "Repos without a Cargo.toml are skipped. A repo whose package is a default \ - member of a Cargo workspace rooted at another selected repo is skipped too: \ - cargo already runs on it from that root. For cargo's own help: cargo help " + "Repos without a Cargo.toml are skipped. A Cargo workspace that spans repos \ + runs in each of them; for one run from its root, use plain cargo there. \ + For cargo's own help: cargo help " .to_string(), ), }), From 8ae8c34c9ea177ac9273da44cadbf1c687320d7f Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:23:57 -0700 Subject: [PATCH 3/4] test: help stops at the -- separator Implements [[tasks/harmony-2746]] --- src/lib.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index efa2e4d..6247115 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -143,4 +143,16 @@ mod tests { assert_eq!(all, [run_in(root), run_in(&member)]); assert_eq!(filtered, [run_in(&member)]); } + + #[test] + fn help_stops_at_the_separator() { + let help = |args: &[&str]| { + let args: Vec = args.iter().map(|a| a.to_string()).collect(); + let result = execute_command(&args, &Default::default(), &[], Path::new(".")); + matches!(result, CommandResult::ShowHelp(None)) + }; + assert!(help(&[])); + assert!(help(&["build", "--help"])); + assert!(!help(&["run", "--", "--help"])); + } } From 6b44b9ba6930194a73a8c167ad4e39ff4b17064d Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:31:06 -0700 Subject: [PATCH 4/4] fix: keep Windows args unquoted and show help for any --help cmd.exe has no POSIX quoting, so shlex quoting broke args like --features=foo,bar there; Windows keeps the plain join. meta_cli sends help requests without the repo list, so any --help/-h shows the plugin help again instead of running cargo in the current directory only. Implements [[tasks/harmony-2746]] --- src/lib.rs | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6247115..30aca61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,15 +16,14 @@ pub fn execute_command( projects: &[String], cwd: &Path, ) -> CommandResult { - // `meta cargo` and `meta cargo --help` show this plugin's help - // instead of running cargo once per repo. Args after `--` belong to cargo. - let mut before_separator = args.iter().take_while(|a| *a != "--"); - if args.is_empty() || before_separator.any(|a| a == "--help" || a == "-h") { + // `meta cargo` and any `--help`/`-h` show this plugin's help instead of + // running cargo once per repo. meta_cli sends help requests without the + // repo list, so cargo's own help could not reach each repo anyway. + if args.is_empty() || args.iter().any(|a| a == "--help" || a == "-h") { return CommandResult::ShowHelp(None); } - let cmd = match shlex::try_join(std::iter::once("cargo").chain(args.iter().map(String::as_str))) - { + let cmd = match command_line(args) { Ok(cmd) => cmd, Err(e) => return CommandResult::Error(format!("Cannot quote cargo arguments: {e}")), }; @@ -60,6 +59,20 @@ pub fn execute_command( CommandResult::Plan(commands, Some(options.parallel)) } +/// `cargo ` quoted for the `$SHELL -c` that loop_lib runs plans with. +#[cfg(not(windows))] +fn command_line(args: &[String]) -> Result { + shlex::try_join(std::iter::once("cargo").chain(args.iter().map(String::as_str))) + .map_err(|e| e.to_string()) +} + +/// loop_lib runs plans with `cmd.exe /c`, which has no POSIX quoting, so the +/// args are joined as given. +#[cfg(windows)] +fn command_line(args: &[String]) -> Result { + Ok(format!("cargo {}", args.join(" "))) +} + /// Keep the dirs loop_lib will run in (its substring match), so the skip note /// names only selected repos. fn filter_dirs(mut dirs: Vec, options: &PluginRequestOptions) -> Vec { @@ -121,7 +134,8 @@ mod tests { let args = ["fmt", "--check", "--", "--config", "a b"]; let commands = plan(&args, &[root, &rust, &docs], &Default::default()); - let expected = format!("{}: cargo fmt --check -- --config 'a b'", rust.display()); + let quoted = if cfg!(windows) { "a b" } else { "'a b'" }; + let expected = format!("{}: cargo fmt --check -- --config {quoted}", rust.display()); assert_eq!(commands, [expected]); } @@ -145,14 +159,11 @@ mod tests { } #[test] - fn help_stops_at_the_separator() { - let help = |args: &[&str]| { + fn bare_or_help_shows_plugin_help() { + for args in [&[][..], &["test", "--", "--help"][..]] { let args: Vec = args.iter().map(|a| a.to_string()).collect(); let result = execute_command(&args, &Default::default(), &[], Path::new(".")); - matches!(result, CommandResult::ShowHelp(None)) - }; - assert!(help(&[])); - assert!(help(&["build", "--help"])); - assert!(!help(&["run", "--", "--help"])); + assert!(matches!(result, CommandResult::ShowHelp(None))); + } } }