diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index b32f853..586a611 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -156,7 +156,7 @@ meta exec -- cargo test meta --tag frontend exec -- npm update # Exclude slow repos (meta options go before `exec`) -meta --exclude large-monorepo exec -- cargo update # fails if meta-rust is installed (see below) +meta --exclude large-monorepo exec -- cargo update ``` ### Find Files Across Repos @@ -167,7 +167,7 @@ meta exec -- 'find . -name "*.rs" -type f' | head -20 ### Clean Build Artifacts ```bash -meta exec -- cargo clean # fails if meta-rust is installed (see below) +meta exec -- cargo clean meta exec -- rm -rf node_modules dist ``` @@ -180,7 +180,7 @@ meta exec -- rm -rf node_modules dist | One-off scripts | Operations with meta-specific logic | | npm/cargo/make | Clone, update, snapshot | -`meta exec -- ` still offers the command to plugins first: `meta exec -- git ...` goes to the git plugin, and every `meta exec -- cargo ...` goes to meta-rust when it is installed. meta-rust only handles `build` and `test`, so with it installed other cargo commands (`cargo update`, `cargo clean`) fail. Plugins intercept command patterns and provide enhanced behavior. `meta git clone` doesn't run `git clone` in each repo—it reads `.meta` and clones the entire graph. +`meta exec -- ` always runs the command as typed, never through a plugin: `meta exec -- git status` runs plain `git status` in each repo, while `meta git status` uses the git plugin. Prefer `meta git ` for git: any git subcommand passes through it, and it runs remote commands (`fetch`, `pull`, `push`) without credential prompts that would hang parallel runs. Plugins intercept only their own subcommands (`meta git ...`, `meta cargo ...`) and provide enhanced behavior. `meta git clone` doesn't run `git clone` in each repo—it reads `.meta` and clones the entire graph. ## Worktree Context Detection diff --git a/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index 0fdb788..809fb30 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -43,13 +43,14 @@ meta project check # Verify all repos exist meta project dependents # Projects that depend on one ``` -### Rust Plugin (`meta-rust`, if installed) +### Rust Plugin (`meta-rust`) -Cargo workspace awareness. Check `meta --help` for it; without it, use `meta exec -- cargo build`. +Runs any cargo command in each selected repo that has a `Cargo.toml`, skipping the rest (listed on stderr). `meta exec -- cargo ...` runs cargo in every repo instead. ```bash -meta rust build # cargo build in each repo with a Cargo.toml -meta rust test # cargo test in each repo with a Cargo.toml (no dependency ordering) +meta cargo build --release # cargo build --release in each Rust repo +meta cargo fmt --check # any cargo subcommand passes through +meta --include api cargo clippy --all-targets -- -D warnings ``` ## Plugin Discovery diff --git a/src/main.rs b/src/main.rs index d705c7b..4fd374c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -521,12 +521,12 @@ fn main() -> Result<()> { println!("Arguments:"); println!(" ... Command and arguments to run"); println!(); - println!("The command runs in each project directory defined in .meta."); - println!("Use this for any command not explicitly handled by a plugin."); + println!("The command runs as typed in each project directory defined in .meta,"); + println!("never through a plugin (use `meta git ...` for the git plugin)."); println!(); println!("Examples:"); println!(" meta exec -- npm install"); - println!(" meta exec -- git fetch --all"); + println!(" meta exec -- cargo fmt --check"); println!(" meta exec -- make clean"); println!(" meta exec --include api,web -- docker-compose up -d"); std::process::exit(0); @@ -564,7 +564,6 @@ fn main() -> Result<()> { } if wants_help { - let command_str = args.join(" "); let options = PluginRequestOptions { json_output: cli.json, verbose: cli.verbose, @@ -577,7 +576,7 @@ fn main() -> Result<()> { exclude_filters: cli.exclude.clone(), strict: cli.strict, }; - if subprocess_plugins.execute(&command_str, &args, &[], None, options)? { + if subprocess_plugins.execute(&args, &[], None, options)? { return Ok(()); } } @@ -589,10 +588,13 @@ fn main() -> Result<()> { // === Command Dispatch (shared by exec and external) === -/// Dispatch a command to plugins or loop execution. +/// Run a command across the selected repos. /// -/// Used by both `meta exec` (is_explicit_exec=true) and external subcommands -/// (is_explicit_exec=false). +/// `meta exec` (is_explicit_exec=true) runs the command as typed and never +/// offers it to plugins, so a plugin's claimed command (e.g. meta-rust's +/// `cargo`) cannot shadow a raw one. External subcommands +/// (is_explicit_exec=false, e.g. `meta git status`) go to the plugin that owns +/// them, or fail as unrecognized. fn handle_command_dispatch( command_args: Vec, cli: &Cli, @@ -643,7 +645,7 @@ fn handle_command_dispatch( let is_git_clone = command_args.first().map(|s| s == "git").unwrap_or(false) && command_args.get(1).map(|s| s == "clone").unwrap_or(false); - if is_git_clone { + if is_git_clone && !is_explicit_exec { // Handle git clone directly via plugin without requiring .meta file let subprocess_options = PluginRequestOptions { json_output: cli.json, @@ -658,7 +660,7 @@ fn handle_command_dispatch( strict: cli.strict, }; - if plugins.execute("git clone", &command_args, &[], None, subprocess_options)? { + if plugins.execute(&command_args, &[], None, subprocess_options)? { if cli.verbose { println!("{}", "Git clone handled by subprocess plugin.".green()); } @@ -760,7 +762,7 @@ fn handle_command_dispatch( root_dir: Some(task_dir.clone()), }; - // Try plugin dispatch first (full feature parity with normal path) + // Plugin dispatch (full feature parity with normal path) let subprocess_options = PluginRequestOptions { json_output: cli.json, verbose: cli.verbose, @@ -774,8 +776,9 @@ fn handle_command_dispatch( strict: cli.strict, }; - if plugins.execute( - &command_str, + if is_explicit_exec { + run(&config, &command_str)?; + } else if plugins.execute( &command_args, &wt_directories, Some(&task_dir), @@ -787,8 +790,6 @@ fn handle_command_dispatch( "Command handled by subprocess plugin (worktree).".green() ); } - } else if is_explicit_exec { - run(&config, &command_str)?; } else { unrecognized_command_error(&command_args, &command_str, plugins); } @@ -916,7 +917,7 @@ fn handle_command_dispatch( root_dir: Some(meta_dir.to_path_buf()), }; - // Try subprocess plugins first (preferred) + // Plugin dispatch for external subcommands let subprocess_options = PluginRequestOptions { json_output: cli.json, verbose: cli.verbose, @@ -930,8 +931,14 @@ fn handle_command_dispatch( strict: cli.strict, }; - if plugins.execute( - &command_str, + if is_explicit_exec { + // User explicitly requested exec, run the command in all repos + log::info!("Explicit exec requested, running command via loop"); + if cli.verbose { + println!("{}", "Running command via loop (explicit exec).".green()); + } + run(&config, &command_str)?; + } else if plugins.execute( &command_args, &project_paths, Some(meta_dir), @@ -941,13 +948,6 @@ fn handle_command_dispatch( if cli.verbose { println!("{}", "Command handled by subprocess plugin.".green()); } - } else if is_explicit_exec { - // User explicitly requested exec, run the command in all repos - log::info!("Explicit exec requested, running command via loop"); - if cli.verbose { - println!("{}", "Running command via loop (explicit exec).".green()); - } - run(&config, &command_str)?; } else { unrecognized_command_error(&command_args, &command_str, plugins); } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index f5c0d3a..0dbe732 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -172,96 +172,71 @@ impl SubprocessPluginManager { Ok(()) } - /// Check if any plugin handles the given command - #[allow(dead_code)] - pub fn handles_command(&self, command: &str) -> bool { - let cmd_parts: Vec<&str> = command.split_whitespace().collect(); - if cmd_parts.is_empty() { - return false; - } - - for plugin in self.plugins.values() { - for plugin_cmd in &plugin.info.commands { - // Check if the input command starts with this plugin command - if command == plugin_cmd || command.starts_with(&format!("{plugin_cmd} ")) { - return true; - } - // Also check single-word match for fallback - if plugin_cmd == cmd_parts[0] { - return true; - } - } - } - false + /// Find the plugin that owns a command, and how many leading args name it. + /// + /// `args` is the command as typed after `meta` (e.g. `["git", "status"]`). + /// The plugin whose claimed command is the longest whole-word prefix of + /// `args` gets it. Otherwise a plugin claiming commands under the first + /// word owns that namespace and gets the whole command, and handles + /// subcommands it does not implement itself (e.g. meta-git runs raw git). + fn route(&self, args: &[String]) -> Option<(&SubprocessPlugin, usize)> { + let first = args.first()?; + let claims = || { + self.plugins.values().flat_map(|plugin| { + plugin + .info + .commands + .iter() + .map(move |cmd| (plugin, cmd.split_whitespace().collect::>())) + }) + }; + claims() + .filter(|(_, words)| { + !words.is_empty() + && words.len() <= args.len() + && words.iter().zip(args).all(|(word, arg)| word == arg) + }) + .map(|(plugin, words)| (plugin, words.len())) + .max_by_key(|(_, len)| *len) + .or_else(|| { + claims() + .find(|(_, words)| words.first() == Some(&first.as_str())) + .map(|(plugin, _)| (plugin, args.len())) + }) } - /// Execute a command via the appropriate plugin + /// Execute a command via the plugin that owns it; false if none does. pub fn execute( &self, - command: &str, args: &[String], projects: &[String], root_dir: Option<&Path>, options: PluginRequestOptions, ) -> Result { - let cmd_parts: Vec<&str> = command.split_whitespace().collect(); - if cmd_parts.is_empty() { - return Ok(false); - } - - // Find the best (longest) matching command across all plugins - let mut best_match: Option<(&SubprocessPlugin, &str)> = None; - let mut best_match_len = 0; - - for plugin in self.plugins.values() { - for plugin_cmd in &plugin.info.commands { - // Check if the input command starts with this plugin command - if command == plugin_cmd || command.starts_with(&format!("{plugin_cmd} ")) { - let cmd_len = plugin_cmd.split_whitespace().count(); - if cmd_len > best_match_len { - best_match = Some((plugin, plugin_cmd)); - best_match_len = cmd_len; - } - } - // Also check if the first word of plugin command matches first word of input - // This allows "project blablabla" to route to the project plugin - else if best_match_len == 0 { - let plugin_cmd_first = plugin_cmd.split_whitespace().next().unwrap_or(""); - if plugin_cmd_first == cmd_parts[0] { - // Use the full input command (plugin will handle unknown subcommand) - best_match = Some((plugin, command)); - best_match_len = 1; - } - } + match self.route(args) { + Some((plugin, len)) => { + self.execute_plugin(plugin, args, len, projects, root_dir, &options) } + None => Ok(false), } - - if let Some((plugin, matched_cmd)) = best_match { - return self.execute_plugin(plugin, matched_cmd, args, projects, root_dir, &options); - } - - Ok(false) } - /// Execute a specific plugin + /// Execute a specific plugin with the first `command_len` args as its command fn execute_plugin( &self, plugin: &SubprocessPlugin, - command: &str, args: &[String], + command_len: usize, projects: &[String], root_dir: Option<&Path>, options: &PluginRequestOptions, ) -> Result { - // Extract the remaining args after the matched command - // e.g., if command is "git snapshot create" and args is ["git", "snapshot", "create", "test-snapshot"] - // then remaining_args should be ["test-snapshot"] - let cmd_word_count = command.split_whitespace().count(); - let remaining_args: Vec = args.iter().skip(cmd_word_count).cloned().collect(); + let (command, remaining_args) = args.split_at_checked(command_len).unwrap_or((args, &[])); + let command = command.join(" "); let request = PluginRequest { - command: command.to_string(), - args: remaining_args, + command, + args: remaining_args.to_vec(), projects: projects.to_vec(), cwd: std::env::current_dir()?.to_string_lossy().to_string(), options: options.clone(), @@ -272,7 +247,7 @@ impl SubprocessPluginManager { if self.verbose { println!( "Executing plugin {} for command '{}'", - plugin.info.name, command + plugin.info.name, request.command ); } @@ -689,13 +664,6 @@ mod tests { assert!(manager.plugins.is_empty()); } - #[test] - fn test_handles_command_empty() { - let manager = SubprocessPluginManager::new(); - assert!(!manager.handles_command("")); - assert!(!manager.handles_command("git status")); - } - #[test] fn test_plugin_info_serialization() { let info = PluginInfo { @@ -751,29 +719,60 @@ mod tests { assert!(options.exclude_filters.is_none()); } + fn routed(manager: &SubprocessPluginManager, args: &[&str]) -> Option<(String, usize)> { + let args: Vec = args.iter().map(|a| a.to_string()).collect(); + manager + .route(&args) + .map(|(plugin, len)| (plugin.info.name.clone(), len)) + } + #[test] - fn test_handles_command_matching() { + fn test_route_matches_whole_words() { let mut manager = SubprocessPluginManager::new(); + for (name, commands) in [ + ("rust", vec!["cargo build", "cargo test"]), + ( + "git", + vec!["git status", "git snapshot", "git snapshot create"], + ), + ] { + manager.plugins.insert( + name.to_string(), + SubprocessPlugin { + path: std::path::PathBuf::from(format!("/fake/path/meta-{name}")), + info: PluginInfo { + name: name.to_string(), + version: "1.0.0".to_string(), + commands: commands.into_iter().map(String::from).collect(), + description: None, + help: None, + }, + }, + ); + } - // Manually add a plugin for testing - let plugin = SubprocessPlugin { - path: std::path::PathBuf::from("/fake/path/meta-test"), - info: PluginInfo { - name: "test".to_string(), - version: "1.0.0".to_string(), - commands: vec!["test".to_string(), "test run".to_string()], - description: None, - help: None, - }, - }; - manager.plugins.insert("test".to_string(), plugin); - - // Should match single-word command - assert!(manager.handles_command("test")); - // Should match two-word command - assert!(manager.handles_command("test run")); - // Should not match unknown command - assert!(!manager.handles_command("unknown")); + // The longest claimed command wins; the rest are the plugin's args + assert_eq!( + routed(&manager, &["git", "snapshot", "create", "x"]), + Some(("git".to_string(), 3)) + ); + assert_eq!( + routed(&manager, &["cargo", "build", "--release"]), + Some(("rust".to_string(), 2)) + ); + // Unclaimed subcommands go whole to the namespace owner; words match + // whole, so "buildx" is not "build" + assert_eq!( + routed(&manager, &["cargo", "--version"]), + Some(("rust".to_string(), 2)) + ); + assert_eq!( + routed(&manager, &["cargo", "buildx", "x"]), + Some(("rust".to_string(), 3)) + ); + assert_eq!(routed(&manager, &["gitx", "status"]), None); + assert_eq!(routed(&manager, &["npm", "install"]), None); + assert_eq!(routed(&manager, &[]), None); } #[test] diff --git a/tests/plugin_git.rs b/tests/plugin_git.rs index e91ea1d..a802514 100644 --- a/tests/plugin_git.rs +++ b/tests/plugin_git.rs @@ -300,162 +300,6 @@ fn test_backward_compatibility_config_parsing() { assert!(config.exclude_filters.is_none()); } -/// Test that git clone detection works correctly for bootstrap scenario -/// (when no .meta file exists yet because we're cloning the meta repo) -#[test] -fn test_git_clone_bootstrap_detection() { - // Simulate command parsing logic from main.rs - let commands: Vec = vec![ - "git".to_string(), - "clone".to_string(), - "git@github.com:example/repo.git".to_string(), - ]; - - // This is the detection logic from main.rs - let is_git_clone_bootstrap = commands.first().map(|s| s == "git").unwrap_or(false) - && commands.get(1).map(|s| s == "clone").unwrap_or(false); - - assert!( - is_git_clone_bootstrap, - "Should detect 'git clone' as bootstrap command" - ); - - // Verify that command_args should be passed as-is to plugins.execute() - // The plugin will calculate remaining_args by skipping command words - // This is the fix: we pass full command_args, not pre-stripped args - assert_eq!(commands.len(), 3); - assert_eq!(commands[0], "git"); - assert_eq!(commands[1], "clone"); - assert_eq!(commands[2], "git@github.com:example/repo.git"); -} - -/// Test that subprocess_plugins correctly extracts remaining args from full command_args -/// This verifies the fix for git clone argument passing -#[test] -fn test_remaining_args_calculation_for_git_clone() { - // Simulate what subprocess_plugins does when receiving a git clone command - // command = "git clone", args = ["git", "clone", "git@github.com:example/repo.git"] - let command = "git clone"; - let args: Vec = vec![ - "git".to_string(), - "clone".to_string(), - "git@github.com:example/repo.git".to_string(), - ]; - - // This is the calculation from subprocess_plugins.rs:257-258 - let cmd_word_count = command.split_whitespace().count(); - let remaining_args: Vec = args.iter().skip(cmd_word_count).cloned().collect(); - - assert_eq!(cmd_word_count, 2, "git clone has 2 words"); - assert_eq!( - remaining_args.len(), - 1, - "Should have 1 remaining arg (the URL)" - ); - assert_eq!(remaining_args[0], "git@github.com:example/repo.git"); -} - -/// Test remaining args calculation with multiple clone options -#[test] -fn test_remaining_args_with_clone_options() { - let command = "git clone"; - let args: Vec = vec![ - "git".to_string(), - "clone".to_string(), - "--depth".to_string(), - "1".to_string(), - "--recursive".to_string(), - "git@github.com:example/repo.git".to_string(), - "target-dir".to_string(), - ]; - - let cmd_word_count = command.split_whitespace().count(); - let remaining_args: Vec = args.iter().skip(cmd_word_count).cloned().collect(); - - assert_eq!(remaining_args.len(), 5); - assert_eq!(remaining_args[0], "--depth"); - assert_eq!(remaining_args[1], "1"); - assert_eq!(remaining_args[2], "--recursive"); - assert_eq!(remaining_args[3], "git@github.com:example/repo.git"); - assert_eq!(remaining_args[4], "target-dir"); -} - -/// Test that passing pre-stripped args would result in empty remaining_args (the bug) -#[test] -fn test_pre_stripped_args_bug_scenario() { - // This demonstrates the bug that was fixed: - // If args were pre-stripped (skipping "git" and "clone"), remaining_args would be empty - let command = "git clone"; - let pre_stripped_args: Vec = vec!["git@github.com:example/repo.git".to_string()]; - - let cmd_word_count = command.split_whitespace().count(); // 2 - let remaining_args: Vec = pre_stripped_args - .iter() - .skip(cmd_word_count) - .cloned() - .collect(); - - // This shows the bug: remaining_args is empty because we skipped 2 from a 1-element vec - assert_eq!( - remaining_args.len(), - 0, - "Pre-stripped args results in empty remaining_args (the bug)" - ); -} - -/// Test that git clone with options extracts args correctly -#[test] -fn test_git_clone_bootstrap_with_options() { - let commands: Vec = vec![ - "git".to_string(), - "clone".to_string(), - "--depth".to_string(), - "1".to_string(), - "git@github.com:example/repo.git".to_string(), - "target-dir".to_string(), - ]; - - let is_git_clone_bootstrap = commands.first().map(|s| s == "git").unwrap_or(false) - && commands.get(1).map(|s| s == "clone").unwrap_or(false); - - assert!(is_git_clone_bootstrap); - - let clone_args: Vec = commands.iter().skip(2).cloned().collect(); - assert_eq!(clone_args.len(), 4); - assert_eq!( - clone_args, - vec![ - "--depth", - "1", - "git@github.com:example/repo.git", - "target-dir" - ] - ); -} - -/// Test that non-clone git commands are not detected as bootstrap -#[test] -fn test_git_non_clone_not_bootstrap() { - let test_cases = vec![ - vec!["git", "status"], - vec!["git", "pull"], - vec!["git", "push"], - vec!["git", "commit", "-m", "message"], - vec!["npm", "install"], - ]; - - for commands in test_cases { - let commands: Vec = commands.iter().map(|s| s.to_string()).collect(); - let is_git_clone_bootstrap = commands.first().map(|s| s == "git").unwrap_or(false) - && commands.get(1).map(|s| s == "clone").unwrap_or(false); - - assert!( - !is_git_clone_bootstrap, - "Command {commands:?} should NOT be detected as git clone bootstrap" - ); - } -} - /* // These tests require the meta binary to be built // Uncomment when running full integration tests with `cargo nextest run` diff --git a/tests/plugin_routing.rs b/tests/plugin_routing.rs new file mode 100644 index 0000000..2934e72 --- /dev/null +++ b/tests/plugin_routing.rs @@ -0,0 +1,93 @@ +//! `meta exec` runs commands as typed; plugins only get `meta `. +#![cfg(unix)] + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use tempfile::tempdir; + +/// A workspace with repos `a` and `b`, and a plugin on PATH that claims +/// `touch` and logs each request it receives instead of running it. +fn workspace(root: &Path) { + fs::write( + root.join(".meta"), + r#"{"projects":{"a":"https://example.invalid/a.git","b":"https://example.invalid/b.git"}}"#, + ) + .unwrap(); + fs::create_dir_all(root.join("a")).unwrap(); + fs::create_dir_all(root.join("b")).unwrap(); + let bin = root.join("bin"); + fs::create_dir_all(&bin).unwrap(); + let plugin = bin.join("meta-touchy"); + fs::write( + &plugin, + format!( + r#"#!/bin/sh +case "$1" in + --meta-plugin-info) echo '{{"name":"touchy","version":"1.0.0","commands":["touch"]}}' ;; + --meta-plugin-exec) cat >> "{}" ;; +esac +"#, + root.join("plugin.log").display() + ), + ) + .unwrap(); + fs::set_permissions(&plugin, fs::Permissions::from_mode(0o755)).unwrap(); +} + +fn meta(root: &Path, args: &[&str]) { + let output = std::process::Command::new(env!("CARGO_BIN_EXE_meta")) + .args(args) + .current_dir(root) + .env("HOME", root) + .env("META_DATA_DIR", root.join("data")) + .env( + "PATH", + std::env::join_paths( + std::iter::once(root.join("bin")) + .chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())), + ) + .unwrap(), + ) + .output() + .unwrap(); + assert!( + output.status.success(), + "meta {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn exec_runs_a_plugin_claimed_command_verbatim() { + let temp = tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + workspace(&root); + + meta(&root, &["exec", "--", "touch", "ran"]); + + for repo in [&root, &root.join("a"), &root.join("b")] { + assert!(repo.join("ran").exists(), "not run in {}", repo.display()); + } + assert!( + !root.join("plugin.log").exists(), + "meta exec handed the command to the plugin" + ); +} + +#[test] +fn plugin_subcommand_still_routes_to_the_plugin() { + let temp = tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + workspace(&root); + + meta(&root, &["touch", "ran"]); + + let request = fs::read_to_string(root.join("plugin.log")).unwrap(); + assert!(request.contains(r#""command":"touch""#), "{request}"); + assert!(request.contains(r#""args":["ran"]"#), "{request}"); + assert!( + !root.join("ran").exists(), + "meta ran the plugin's command raw" + ); +}