diff --git a/Cargo.toml b/Cargo.toml index 28c1d82..cfca9d7 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,10 +16,8 @@ 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" [dev-dependencies] diff --git a/src/lib.rs b/src/lib.rs index 9c62a16..30aca61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,133 +1,100 @@ //! 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, -}; +pub use meta_plugin_protocol::{CommandResult, PlannedCommand, PluginRequestOptions}; use std::path::Path; -/// 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. A Cargo workspace that spans +/// repos runs in each of them; plain `cargo` in its root runs it once. 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 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); } - // 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 command_line(args) { + 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 (rust_dirs, other_dirs): (Vec, Vec) = filter_dirs(dirs, options) + .into_iter() + .partition(|dir| cwd.join(dir).join("Cargo.toml").is_file()); + + 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() { 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)) +/// `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()) } -/// Get help text for the plugin -pub fn get_help_text() -> &'static str { - r#"meta rust - Rust/Cargo Plugin +/// 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(" "))) +} -Commands: - meta cargo build Run cargo build across all Rust projects - meta cargo test Run cargo test across all Rust projects +/// 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()))); + } + if let Some(excludes) = &options.exclude_filters { + dirs.retain(|dir| { + !excludes + .iter() + .any(|f| dir.contains(f.trim_end_matches('/'))) + }); + } + dirs +} -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 +102,68 @@ 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(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(); } - #[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: &[&Path], options: &PluginRequestOptions) -> Vec { + let args: Vec = args.iter().map(|a| a.to_string()).collect(); + 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"), + } } #[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, 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 result = execute_command("cargo build", &[], false, &[], temp_dir.path()); + let args = ["fmt", "--check", "--", "--config", "a b"]; + let commands = plan(&args, &[root, &rust, &docs], &Default::default()); - match result { - CommandResult::Message(msg) => assert!(msg.contains("No Rust projects")), - _ => panic!("Expected Message result"), - } + let quoted = if cfg!(windows) { "a b" } else { "'a b'" }; + let expected = format!("{}: cargo fmt --check -- --config {quoted}", rust.display()); + assert_eq!(commands, [expected]); } #[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_in_their_own_repos_within_filters() { + let temp = TempDir::new().unwrap(); + 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"); + + let all = plan(&["run"], &[root, &member], &Default::default()); + let only_member = PluginRequestOptions { + include_filters: Some(vec!["member".to_string()]), + ..Default::default() + }; + let filtered = plan(&["run"], &[root, &member], &only_member); - match result { - CommandResult::Plan(commands, parallel) => { - 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)); - } - _ => panic!("Expected Plan result"), - } + 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)]); } #[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")); + 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(".")); + assert!(matches!(result, CommandResult::ShowHelp(None))); + } } } diff --git a/src/main.rs b/src/main.rs index 7538de7..f74cb52 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 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(), + ), }), }, 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) }