diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index 586a611..93cbc41 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -15,13 +15,19 @@ Execute any command in the root repo and every project at this meta level (add ` # Run 'make build' in every repo meta exec -- make build -# Run any shell command +# Any program with its arguments meta exec -- ls -la - -# Commands with arguments meta exec -- npm install --save-dev typescript ``` +Each argument meta receives reaches the program unchanged: meta runs the program directly, with no shell in between. Quotes, spaces, `$()`, `;`, `|`, `&&`, globs and `%` in an argument stay literal, so text from an issue, a commit message or a file name can't run commands once meta has it. Your own shell still parses the command line before meta runs (`"$(...)"` in double quotes runs there), so pass untrusted text in single quotes or as a separate argv element (as the MCP tools take it). When you want a shell (pipes, `&&`, redirects, globs), ask for one: + +```bash +meta exec -- sh -c 'npm ci && npm test' +``` + +A `.looprc` alias for the program is expanded into words (POSIX quoting rules, nothing expanded or run). On Windows meta does not wrap commands in `cmd /c` either. Batch files such as `npm.cmd` need their extension (`meta exec -- npm.cmd install`); Windows runs those through `cmd.exe`, and Rust escapes their arguments for it and refuses any it cannot pass safely. + The `--` separates meta options from the command to execute. The `--` is optional unless your command starts with `-`. ```bash @@ -52,16 +58,17 @@ Parallel mode: ## Filtering Options -Control which repos run the command. These options come from `loop`: +Control which repos run the command: ```bash -# Only directories whose path contains one of these (substring match) +# Only these repos: each value is a repo's .meta name or its path from the workspace root meta --include api,worker git status +meta --include libs/core,. git status # `.` is the root repo -# Skip directories whose path contains one of these +# Skip these repos meta --exclude legacy-service git push -# Filter by tag (meta-specific, applied before loop filtering) +# Filter by tag (applied before --include/--exclude) meta --tag backend exec -- make deploy # Combine: tag filter + directory filter @@ -70,10 +77,10 @@ meta --tag backend --include api git status **Filter precedence:** 1. `--tag` filters projects by tag (meta level) -2. `--include` limits to specific directories (loop level) -3. `--exclude` removes directories (loop level) +2. `--include` limits to the named repos +3. `--exclude` removes the named repos -Include/exclude match substrings of directory paths, so `api` also matches `api-tests`. The meta root repo stays included even when it doesn't match a tag. +A value names a whole repo, never part of a path: `api` does not match `api-tests`. A value that names no repo is an error, so a typo never runs a command in the repo you meant to skip. Inside a worktree set, a repo is named by its alias (its path in the set). A value starting with `./` is a path only; use it when a name is ambiguous (a value that names several repos is an error too). The meta root repo stays included even when it doesn't match a tag. ## Dry Run @@ -129,8 +136,8 @@ meta --silent exec -- npm install |--------|-------------| | `--parallel` | Run commands concurrently (the default) | | `--sequential` | Run one repo at a time | -| `--include ` | Only directories whose path contains these | -| `--exclude ` | Skip directories whose path contains these | +| `--include ` | Only these repos (`.meta` name or path from the root) | +| `--exclude ` | Skip these repos (`.meta` name or path from the root) | | `--tag ` | Filter by project tag(s) | | `--dry-run` | Preview without executing | | `--json` | Structured JSON output | @@ -161,8 +168,8 @@ meta --exclude large-monorepo exec -- cargo update ### Find Files Across Repos ```bash -# Quote the whole command: meta joins its arguments with spaces for the shell -meta exec -- 'find . -name "*.rs" -type f' | head -20 +# Arguments go to find as typed: "*.rs" is find's pattern, not a shell glob +meta exec -- find . -name '*.rs' -type f | head -20 ``` ### Clean Build Artifacts @@ -175,7 +182,7 @@ meta exec -- rm -rf node_modules dist | Use `meta exec` | Use Plugin (e.g., `meta git`) | |-----------------|-------------------------------| -| Generic shell commands | Git operations | +| Generic commands | Git operations | | Build/test commands | Commands needing special handling | | One-off scripts | Operations with meta-specific logic | | npm/cargo/make | Clone, update, snapshot | diff --git a/.claude/skills/meta-git/SKILL.md b/.claude/skills/meta-git/SKILL.md index 1a0098b..656fc64 100644 --- a/.claude/skills/meta-git/SKILL.md +++ b/.claude/skills/meta-git/SKILL.md @@ -19,6 +19,8 @@ meta git status # Shows status for every repo at once meta git commit -m "feat: update" # Commits in every repo with staged changes ``` +Any other git subcommand passes through to git in each repo. Meta passes the arguments it receives to git unchanged, with no shell in between: `meta git log --format='%h %s'` and a commit message containing `$(...)` or `;` are passed as-is. Your own shell still expands `$(...)` inside double quotes before meta runs, so put untrusted text in single quotes. + ## Cloning a Meta Repo ```bash @@ -87,13 +89,13 @@ meta git log --oneline -5 ## Filtering -Target specific repos. With `--tag`, the meta root repo stays included even when it isn't tagged; `--include`/`--exclude` match substrings of directory paths and can drop the root. +Target specific repos. With `--tag`, the meta root repo stays included even when it isn't tagged; `--include`/`--exclude` take whole repos (a `.meta` name or the path from the workspace root, `.` for the root), never part of a path, and can drop the root. A value that names no repo is an error. ```bash # By tag meta --tag backend git status -# By directory (substring match: `api` also matches `api-tests`) +# By repo: .meta name or path from the root (`api` does not match `api-tests`) meta --include api,web git push # Exclude repos @@ -139,7 +141,7 @@ When the meta MCP server is available, these tools provide structured JSON outpu ## Efficiency Tips -- **Targeted commits**: `meta --include repo1,repo2 git commit -m "msg"` commits only in repos whose path matches +- **Targeted commits**: `meta --include repo1,repo2 git commit -m "msg"` commits only in the named repos - **Tag-based push**: `meta --tag backend git push` pushes tagged repos (and the root) - **Per-repo messages**: Use `meta_git_multi_commit` when changes in different repos need different commit messages - **One-call status**: `meta git status` replaces N individual `cd && git status` sequences diff --git a/.claude/skills/meta-safety/SKILL.md b/.claude/skills/meta-safety/SKILL.md index ca03671..d584efb 100644 --- a/.claude/skills/meta-safety/SKILL.md +++ b/.claude/skills/meta-safety/SKILL.md @@ -15,7 +15,7 @@ Multi-repo workspaces are powerful but require awareness. Meta gives you precisi ## Precision Operations -Instead of cd-ing into repos one by one, use meta flags to target what you need. Include/exclude match substrings of directory paths; `--tag` keeps the meta root even when it isn't tagged: +Instead of cd-ing into repos one by one, use meta flags to target what you need. Include/exclude take whole repos (a `.meta` name or the path from the workspace root), never part of a path, and a value that names no repo is an error; `--tag` keeps the meta root even when it isn't tagged: ```bash # Target specific repos @@ -42,7 +42,7 @@ When modifying a repo that other repos depend on: ## Efficient Commits ```bash -# Commit only in repos whose path contains repo1 or repo2 (substring match) +# Commit only in repos repo1 and repo2 (.meta name or path from the root) meta --include repo1,repo2 git commit -m "feat: update shared API" # Push tagged repos (and the root) diff --git a/.claude/skills/meta-workspace/SKILL.md b/.claude/skills/meta-workspace/SKILL.md index fcb4617..859ca35 100644 --- a/.claude/skills/meta-workspace/SKILL.md +++ b/.claude/skills/meta-workspace/SKILL.md @@ -115,7 +115,7 @@ When the meta MCP server is available, these tools provide structured JSON for p ## Efficiency Tips - **One command, all repos**: `meta git status` replaces N individual `cd && git status` calls -- **Targeted operations**: `meta --include repo1,repo2 exec -- cmd` operates on only the repos whose path matches +- **Targeted operations**: `meta --include repo1,repo2 exec -- cmd` operates on only the named repos (`.meta` name or path from the workspace root) - **Tag-based filtering**: `meta --tag backend exec -- cargo test` scopes to tagged repos - **Dependency awareness**: `meta_analyze_impact ` shows who depends on a repo before you modify it — prevents cascading fix-up commits - **Session start**: Always run `meta project list --recursive --json` first to get the workspace map diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index c1f9b10..bc946be 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -127,9 +127,11 @@ meta git worktree exec auth-fix --exclude legacy -- npm test meta git worktree exec auth-fix --parallel -- cargo build ``` -`--include`/`--exclude` match text anywhere in each repo's absolute path, and -every path contains `.worktrees//`: pick filter text that isn't in the set -name (`--include auth` in set `auth-fix` matches every repo). +`--include`/`--exclude` name whole repos by alias, their path in the set +(`.` for the root repo), never part of a path. A value that names no repo in +the set is an error. They go after the set name: `meta --include x git +worktree ...` is refused. The command's arguments reach it as +typed, with no shell; use `-- sh -c '...'` when you want one. ## Context Detection @@ -229,7 +231,7 @@ it up with `remove`. | Option | Description | |--------|-------------| -| `--include ` | Only repos whose path contains it (comma-separated) | -| `--exclude ` | Skip repos whose path contains it (comma-separated) | +| `--include ` | Only these repos, by alias (comma-separated) | +| `--exclude ` | Skip these repos, by alias (comma-separated) | | `--parallel` | Run concurrently | | `--ephemeral` | Create, run, then remove (takes `--repo`/`--all`, `--branch`, `--from-pr`, `--meta`, a commit-ish) | diff --git a/src/lib.rs b/src/lib.rs index 5fa7ba4..17dbba7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,5 +3,6 @@ pub mod context; pub mod dependency_graph; pub mod git_utils; pub mod query; +pub mod repo_filter; pub mod subprocess_plugins; pub mod worktree; diff --git a/src/main.rs b/src/main.rs index 4fd374c..1ae0557 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,7 +11,7 @@ use std::path::PathBuf; mod init; mod registry; mod subprocess_plugins; -use meta_cli::worktree; +use meta_cli::{repo_filter, worktree}; use subprocess_plugins::{PluginRequestOptions, SubprocessPluginManager}; // === CLI Structs === @@ -47,7 +47,7 @@ struct Cli { long, global = true, value_delimiter = ',', - help = "Specify directories to exclude" + help = "Skip these repos: each value is a repo's .meta name or its whole path from the workspace root (. for the root), never part of one" )] exclude: Option>, @@ -56,7 +56,7 @@ struct Cli { long, global = true, value_delimiter = ',', - help = "Specify directories to include" + help = "Only run in these repos: each value is a repo's .meta name or its whole path from the workspace root (. for the root), never part of one" )] include: Option>, @@ -523,12 +523,18 @@ fn main() -> Result<()> { println!(); 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!("No shell parses it: each argument reaches the program as given, so"); + println!("quotes, $(), ;, | and globs stay literal. For a shell, ask for one."); + println!(); + println!("--include/--exclude take repos by .meta name or path from the root"); + println!("(. for the root), never part of a path."); println!(); println!("Examples:"); println!(" meta exec -- npm install"); println!(" meta exec -- cargo fmt --check"); println!(" meta exec -- make clean"); - println!(" meta exec --include api,web -- docker-compose up -d"); + println!(" meta --include api,web exec -- docker-compose up -d"); + println!(" meta exec -- sh -c 'npm ci && npm test'"); std::process::exit(0); } handle_command_dispatch(args.command, &cli, &subprocess_plugins, true) @@ -543,7 +549,11 @@ fn main() -> Result<()> { // Keep root plugin help fast and plugin-aware, but let nested help // requests reach the matched plugin command implementation. if let Some(first) = args.first() { - let wants_help = args.iter().any(|a| a == "--help" || a == "-h"); + // A --help after `--` is an argument for the command + let wants_help = args + .iter() + .take_while(|a| *a != "--") + .any(|a| a == "--help" || a == "-h"); let is_bare = args.len() == 1; let is_root_help = wants_help && args.len() == 2 @@ -604,7 +614,7 @@ fn handle_command_dispatch( if command_args.is_empty() { if is_explicit_exec { // Show usage error (help is handled at the caller level via cli.help) - eprintln!("Usage: meta exec [args...]"); + eprintln!("Usage: meta exec -- [args...]"); } else { print_help_with_plugins(plugins, true); } @@ -614,8 +624,6 @@ fn handle_command_dispatch( // All meta flags come from clap globals (before the command). // Command args pass through untouched to avoid collisions with // identically-named flags (e.g., grep --include, git clone --depth). - let include_filters: Vec = cli.include.clone().unwrap_or_default(); - let exclude_filters: Vec = cli.exclude.clone().unwrap_or_default(); let recursive = cli.recursive; let dry_run = cli.dry_run; let depth = cli.depth; @@ -638,7 +646,7 @@ fn handle_command_dispatch( defaults.parallel }; - let command_str = command_args.join(" "); + let command_str = loop_lib::display_command(&command_args); // Check if this is `git clone` - it doesn't require a .meta file because // its purpose is to clone the repo that contains the .meta file @@ -646,6 +654,9 @@ fn handle_command_dispatch( && command_args.get(1).map(|s| s == "clone").unwrap_or(false); if is_git_clone && !is_explicit_exec { + if cli.include.is_some() || cli.exclude.is_some() { + anyhow::bail!("meta git clone clones every repo in the meta repo; it does not take --include/--exclude"); + } // Handle git clone directly via plugin without requiring .meta file let subprocess_options = PluginRequestOptions { json_output: cli.json, @@ -723,6 +734,10 @@ fn handle_command_dispatch( .map(|p| p.display().to_string()) .collect(); + // A worktree member sits at its alias, so its path in the set + // is the name to select it by + let wt_directories = select_repos(cli, wt_directories, &task_dir, Vec::new)?; + if wt_directories.is_empty() { eprintln!( "{}: no projects match tag filter '{}' in worktree '{}'", @@ -742,14 +757,9 @@ fn handle_command_dispatch( ); } - let include_opt = none_if_empty(include_filters.clone()); - let exclude_opt = none_if_empty(exclude_filters.clone()); - let config = loop_lib::LoopConfig { directories: wt_directories.clone(), ignore: ignore_list, - include_filters: include_opt.clone(), - exclude_filters: exclude_opt.clone(), verbose: cli.verbose, silent: cli.silent, parallel, @@ -771,13 +781,13 @@ fn handle_command_dispatch( silent: cli.silent, recursive, depth, - include_filters: include_opt, - exclude_filters: exclude_opt, + include_filters: cli.include.clone(), + exclude_filters: cli.exclude.clone(), strict: cli.strict, }; if is_explicit_exec { - run(&config, &command_str)?; + run(&config, &command_args)?; } else if plugins.execute( &command_args, &wt_directories, @@ -808,14 +818,11 @@ fn handle_command_dispatch( let directories: Vec = wt_paths.iter().map(|p| p.display().to_string()).collect(); - let include_opt = none_if_empty(include_filters); - let exclude_opt = none_if_empty(exclude_filters); + let directories = select_repos(cli, directories, &task_dir, Vec::new)?; let config = loop_lib::LoopConfig { directories, ignore: vec![], - include_filters: include_opt, - exclude_filters: exclude_opt, verbose: cli.verbose, silent: cli.silent, parallel, // Use the determined parallel mode, not hardcoded false @@ -828,7 +835,7 @@ fn handle_command_dispatch( root_dir: Some(task_dir.clone()), }; - run(&config, &command_str)?; + run(&config, &command_args)?; return Ok(()); } } @@ -882,12 +889,18 @@ fn handle_command_dispatch( ); // If recursive mode is enabled, discover nested meta repos + let mut tree = vec![]; if recursive { if cli.verbose { let depth_str = depth.map_or("unlimited".to_string(), |d| d.to_string()); println!("Recursive mode enabled, max depth: {depth_str}"); } - let tree = config::walk_meta_tree(meta_dir, depth)?; + // The walk reads the default config file; with --config, start from + // the chosen one and walk only the nested meta repos + tree = match cli.config { + Some(_) => walk_from(meta_dir, &meta_projects, depth), + None => config::walk_meta_tree(meta_dir, depth)?, + }; project_paths = vec![meta_dir_str.clone()]; let flat = flatten_with_tag_filter(&tree, &cli.tag); project_paths.extend( @@ -896,16 +909,15 @@ fn handle_command_dispatch( ); } - // Prepare filter options (shared by both LoopConfig and PluginRequestOptions) - let include_opt = none_if_empty(include_filters); - let exclude_opt = none_if_empty(exclude_filters); + // Commands and plugins get only the selected repos + let project_paths = select_repos(cli, project_paths, meta_dir, || { + repo_filter::repo_names(meta_dir, &meta_projects, &tree) + })?; let config = loop_lib::LoopConfig { add_aliases_to_global_looprc: cli.add_aliases_to_global_looprc, directories: project_paths.clone(), ignore: ignore_list, - include_filters: include_opt.clone(), - exclude_filters: exclude_opt.clone(), verbose: cli.verbose, silent: cli.silent, parallel, @@ -926,8 +938,8 @@ fn handle_command_dispatch( silent: cli.silent, recursive, depth, - include_filters: include_opt, - exclude_filters: exclude_opt, + include_filters: cli.include.clone(), + exclude_filters: cli.exclude.clone(), strict: cli.strict, }; @@ -937,7 +949,7 @@ fn handle_command_dispatch( if cli.verbose { println!("{}", "Running command via loop (explicit exec).".green()); } - run(&config, &command_str)?; + run(&config, &command_args)?; } else if plugins.execute( &command_args, &project_paths, @@ -1267,6 +1279,8 @@ fn handle_plugin_command( /// subcommands (e.g. `worktree prune --dry-run`, `worktree exec --parallel`) /// define their own versions and need to see them. fn extract_global_flags(args: &mut Vec, cli: &mut Cli) { + // Everything from `--` on belongs to the command, untouched + let rest = args.split_off(args.iter().position(|a| a == "--").unwrap_or(args.len())); args.retain(|arg| { match arg.as_str() { "--json" => { @@ -1296,6 +1310,7 @@ fn extract_global_flags(args: &mut Vec, cli: &mut Cli) { _ => true, // keep in args } }); + args.extend(rest); } /// Check whether a project's tags match a comma-separated tag filter string. @@ -1304,13 +1319,20 @@ fn matches_tag_filter(tags: &[String], filter: &str) -> bool { tags.iter().any(|t| requested.contains(&t.as_str())) } -/// Convert an empty Vec into None, non-empty into Some. -fn none_if_empty(v: Vec) -> Option> { - if v.is_empty() { - None - } else { - Some(v) +/// The repos among `dirs` that `--include`/`--exclude` select (see +/// [`repo_filter::select`]); `names` lists the `.meta` names they may use. +fn select_repos( + cli: &Cli, + dirs: Vec, + root: &std::path::Path, + names: impl FnOnce() -> Vec<(String, String)>, +) -> Result> { + let include = cli.include.clone().unwrap_or_default(); + let exclude = cli.exclude.clone().unwrap_or_default(); + if include.is_empty() && exclude.is_empty() { + return Ok(dirs); } + repo_filter::select(&include, &exclude, &dirs, root, &names()) } /// Print unrecognized command error with suggestion and help, then exit. @@ -1327,7 +1349,7 @@ fn unrecognized_command_error( ); eprintln!(); eprintln!("To run '{command_str}' across all repos:"); - eprintln!(" meta exec {command_str}"); + eprintln!(" meta exec -- {command_str}"); eprintln!(); print_help_with_plugins(plugins, true); std::process::exit(1); @@ -1394,6 +1416,53 @@ fn check_and_warn_orphan() { } } +/// The meta tree whose top level is `projects` (from the config the user +/// chose), walked the way `walk_meta_tree` walks the default config: nested +/// meta repos `depth` levels down, each directory expanded at most once. +fn walk_from( + meta_dir: &std::path::Path, + projects: &[ProjectInfo], + depth: Option, +) -> Vec { + fn walk( + dir: &std::path::Path, + projects: &[ProjectInfo], + depth: Option, + visited: &mut std::collections::HashSet, + ) -> Vec { + let mut nodes: Vec = projects + .iter() + .map(|project| { + let project_dir = dir.join(&project.path); + let config = find_meta_config(&project_dir, None).filter(|(path, _)| { + project_dir.is_dir() && path.parent() == Some(&project_dir) + }); + let canonical = project_dir.canonicalize().unwrap_or(project_dir.clone()); + let children = match &config { + Some((path, _)) if depth != Some(0) && visited.insert(canonical) => { + parse_meta_config(path) + .map(|(nested, _)| { + let depth = depth.map(|d| d.saturating_sub(1)); + walk(&project_dir, &nested, depth, visited) + }) + .unwrap_or_default() + } + _ => vec![], + }; + MetaTreeNode { + info: project.clone(), + is_meta: config.is_some(), + children, + } + }) + .collect(); + nodes.sort_by(|a, b| a.info.name.cmp(&b.info.name)); + nodes + } + let root = meta_dir.canonicalize().unwrap_or(meta_dir.to_path_buf()); + walk(meta_dir, projects, depth, &mut [root].into_iter().collect()) +} + /// Flatten a meta tree into path strings, optionally filtering by tag. /// If tag_filter is Some, only includes nodes whose tags match (and recurses into them). fn flatten_with_tag_filter(nodes: &[MetaTreeNode], tag_filter: &Option) -> Vec { diff --git a/src/repo_filter.rs b/src/repo_filter.rs new file mode 100644 index 0000000..a245d17 --- /dev/null +++ b/src/repo_filter.rs @@ -0,0 +1,383 @@ +//! `--include` / `--exclude`: which repos a command runs in. + +use anyhow::{bail, Result}; +use meta_core::config::{MetaTreeNode, ProjectInfo}; +use std::path::{Component, Path, PathBuf}; + +/// (`.meta` name, path from `meta_dir`) for `projects`, and for every project +/// nested under `tree` (the result of walking the same meta root). Paths are +/// in the same form as [`select`] gives the repos it chooses among. +pub fn repo_names( + meta_dir: &Path, + projects: &[ProjectInfo], + tree: &[MetaTreeNode], +) -> Vec<(String, String)> { + fn walk(nodes: &[MetaTreeNode], dir: &Path, root: &Path, out: &mut Vec<(String, String)>) { + for node in nodes { + let path = dir.join(&node.info.path); + out.push((node.info.name.clone(), repo_path(&path, root))); + walk(&node.children, &path, root, out); + } + } + let mut names: Vec<(String, String)> = projects + .iter() + .map(|p| (p.name.clone(), repo_path(&meta_dir.join(&p.path), meta_dir))) + .collect(); + walk(tree, meta_dir, meta_dir, &mut names); + names +} + +/// The repos among `dirs` that `include` and `exclude` select, in order. +/// +/// A value names a repo by its `.meta` name (from `names`, see +/// [`repo_names`]) or by its whole path from `root` (`.` for the root; a +/// trailing `/` is ignored), never by a part of either. A value starting with +/// `./` is a path only. Repos are compared as directories, so excluding one +/// excludes every spelling of it (`api` and `libs/../api`). A value that names +/// none of `dirs` is an error, so a typo never runs a command in a repo it was +/// meant to leave out; so is a value that names several repos, and a selection +/// that leaves no repo. +pub fn select( + include: &[String], + exclude: &[String], + dirs: &[String], + root: &Path, + names: &[(String, String)], +) -> Result> { + if include.is_empty() && exclude.is_empty() { + return Ok(dirs.to_vec()); + } + let repos: Vec = dirs + .iter() + .map(|dir| Repo { + dir, + path: repo_path(Path::new(dir), root), + id: std::fs::canonicalize(dir).unwrap_or_else(|_| PathBuf::from(dir)), + }) + .collect(); + let named = |flag: &str, value: &str| -> Result> { + let wanted = path_value(value); + let by_path = distinct( + repos + .iter() + .filter(|r| wanted.as_deref() == Some(r.path.as_str())), + ); + let by_name = if value.starts_with("./") { + vec![] + } else { + distinct( + repos + .iter() + .filter(|r| names.iter().any(|(name, p)| name == value && *p == r.path)), + ) + }; + let listed = |repos: &[&Repo]| -> String { + repos + .iter() + .map(|r| r.path.as_str()) + .collect::>() + .join(", ") + }; + if by_name.len() > 1 { + bail!( + "{flag} '{value}' is the .meta name of the repos at {}; name one by its path, \ + as ./", + listed(&by_name) + ); + } + let ids = + |repos: &[&Repo]| -> Vec { repos.iter().map(|r| r.id.clone()).collect() }; + if !by_path.is_empty() && !by_name.is_empty() && ids(&by_path) != ids(&by_name) { + bail!( + "{flag} '{value}' names the repo at {} by path and the repo at {} by .meta \ + name; name the one you mean by its path, as ./", + listed(&by_path), + listed(&by_name) + ); + } + let hits = if by_path.is_empty() { by_name } else { by_path }; + if hits.is_empty() { + bail!( + "{flag} '{value}' names none of the repos this command runs in. Use a repo's \ + name from .meta or its path from the workspace root (`.` for the root), as \ + `meta project list` shows it; in a worktree set, its alias. --tag and \ + --recursive change which repos the command runs in." + ); + } + Ok(hits.iter().map(|r| r.id.as_path()).collect()) + }; + let mut included = Vec::new(); + for value in include { + included.extend(named("--include", value)?); + } + let mut excluded = Vec::new(); + for value in exclude { + excluded.extend(named("--exclude", value)?); + } + let selected: Vec = repos + .iter() + .filter(|r| include.is_empty() || included.contains(&r.id.as_path())) + .filter(|r| !excluded.contains(&r.id.as_path())) + .map(|r| r.dir.clone()) + .collect(); + if selected.is_empty() { + bail!("--include/--exclude leave no repo to run in"); + } + Ok(selected) +} + +/// A repo `select` chooses among: as given, as filters name it, and the +/// directory it is. +struct Repo<'a> { + dir: &'a String, + path: String, + id: PathBuf, +} + +/// `repos` with each directory once. +fn distinct<'a>(repos: impl Iterator>) -> Vec<&'a Repo<'a>> { + let mut out: Vec<&Repo> = Vec::new(); + for repo in repos { + if !out.iter().any(|r| r.id == repo.id) { + out.push(repo); + } + } + out +} + +/// `dir`'s path from `root`, `/`-separated and `.` for the root itself, with +/// `..` parts for a directory outside `root` (`../shared`); `dir` as given +/// when the two share no prefix (another drive). Relative paths are taken from +/// the current directory. +fn repo_path(dir: &Path, root: &Path) -> String { + let absolute = |path: &Path| { + std::env::current_dir() + .map(|cwd| cwd.join(path)) + .unwrap_or_else(|_| path.to_path_buf()) + }; + let (dir_abs, root_abs) = (absolute(dir), absolute(root)); + let shared = dir_abs + .components() + .zip(root_abs.components()) + .take_while(|(a, b)| a == b) + .count(); + if shared == 0 { + return dir.display().to_string(); + } + let up = root_abs + .components() + .skip(shared) + .map(|_| Component::ParentDir); + let rel: PathBuf = up.chain(dir_abs.components().skip(shared)).collect(); + match normalize(&rel.to_string_lossy()) { + rel if rel.is_empty() => ".".to_string(), + rel => rel, + } +} + +/// A filter value as the path it names from the root: `.` for the root, +/// otherwise [`normalize`]d. None for a value that cannot be such a path +/// (empty or absolute). +fn path_value(value: &str) -> Option { + let absolute = Path::new(value) + .components() + .any(|c| matches!(c, Component::RootDir | Component::Prefix(_))); + match normalize(value) { + _ if absolute || value.is_empty() => None, + path if path.is_empty() => Some(".".to_string()), + path => Some(path), + } +} + +/// `path` `/`-separated, without `.` parts or a trailing `/`; `.` alone +/// becomes empty. `..` parts stay: dropping them would give two different +/// directories the same name. +fn normalize(path: &str) -> String { + let parts: Vec<_> = Path::new(path) + .components() + .filter(|c| !matches!(c, Component::CurDir)) + .map(|c| c.as_os_str().to_string_lossy()) + .collect(); + parts.join("/") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(values: &[&str]) -> Vec { + values.iter().map(|s| s.to_string()).collect() + } + + fn project(name: &str, path: &str) -> ProjectInfo { + ProjectInfo { + name: name.to_string(), + path: path.to_string(), + repo: None, + tags: vec![], + provides: vec![], + depends_on: vec![], + meta: false, + } + } + + #[test] + fn values_name_whole_repos_never_parts_of_paths() { + let root = std::env::temp_dir().join("ws").join("a"); + let rels = ["", "api", "api-legacy", "libs/core"]; + let dirs: Vec = rels + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let names = repo_names(&root, &[project("core-lib", "./libs/core/")], &[]); + let select = |include: &[&str], exclude: &[&str]| { + select(&strings(include), &strings(exclude), &dirs, &root, &names) + }; + let picked = |include: &[&str], exclude: &[&str]| -> Vec { + let dir = |rel: &str| root.join(rel).display().to_string(); + let chosen = select(include, exclude).unwrap(); + rels.iter() + .filter(|rel| chosen.contains(&dir(rel))) + .map(|rel| if rel.is_empty() { "." } else { rel }.to_string()) + .collect() + }; + + assert_eq!(picked(&["api"], &[]), ["api"]); + assert_eq!(picked(&["./api/"], &[]), ["api"]); + assert_eq!(picked(&["."], &[]), ["."]); + assert_eq!(picked(&["libs/core"], &[]), ["libs/core"]); + assert_eq!(picked(&["core-lib"], &[]), ["libs/core"]); + // `./` makes a value a path only + assert_eq!(picked(&["./libs/core/"], &[]), ["libs/core"]); + assert!(select(&["./core-lib"], &[]).is_err()); + assert_eq!(picked(&[], &["api"]), [".", "api-legacy", "libs/core"]); + assert_eq!(picked(&["api", "api-legacy"], &["api"]), ["api-legacy"]); + assert_eq!(picked(&[], &[]), [".", "api", "api-legacy", "libs/core"]); + // Parts of a name or of the absolute path name nothing + let absolute = root.join("api").display().to_string(); + for value in ["a", "ap", "core", "ws", absolute.as_str(), ""] { + let err = select(&[value], &[]).unwrap_err().to_string(); + assert!(err.contains("names none of the repos"), "{value}: {err}"); + let err = select(&[], &[value]).unwrap_err().to_string(); + assert!(err.contains("--exclude"), "{value}: {err}"); + } + let err = select(&["api"], &["api"]).unwrap_err().to_string(); + assert!(err.contains("leave no repo"), "{err}"); + } + + #[test] + fn repos_are_directories_not_spellings() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("ws"); + for dir in ["api", "libs", "child"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + let rels = ["", "api", "libs/../api", "child/.."]; + let dirs: Vec = rels + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let names = repo_names(&root, &[project("outer", "libs/../api")], &[]); + let picked = |include: &[&str], exclude: &[&str]| -> Vec<&str> { + let chosen = + select(&strings(include), &strings(exclude), &dirs, &root, &names).unwrap(); + rels.iter() + .zip(&dirs) + .filter(|(_, dir)| chosen.contains(dir)) + .map(|(rel, _)| *rel) + .collect() + }; + // Excluding a repo excludes every spelling of its directory + assert_eq!(picked(&[], &["api"]), ["", "child/.."]); + assert_eq!(picked(&[], &["."]), ["api", "libs/../api"]); + assert_eq!(picked(&["outer"], &[]), ["api", "libs/../api"]); + // `..` is kept: the workspace's parent is not the workspace + let parent = repo_names(&root, &[project("parent", "..")], &[]); + let up = [root.join("..").display().to_string()]; + let err = select(&strings(&["."]), &[], &up, &root, &parent).unwrap_err(); + assert!(err.to_string().contains("names none"), "{err}"); + } + + #[test] + fn names_from_the_tree_match_nested_and_top_level_repos() { + let root = std::env::temp_dir().join("ws").join("a"); + let dirs: Vec = ["", "parent", "parent/libs/core"] + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let node = |info: ProjectInfo, children| MetaTreeNode { + info, + is_meta: true, + children, + }; + let tree = [node( + project("top", "parent"), + vec![node(project("core-lib", "./libs/core"), vec![])], + )]; + let names = repo_names(&root, &[], &tree); + for (value, rel) in [("top", "parent"), ("core-lib", "parent/libs/core")] { + let chosen = select(&strings(&[value]), &[], &dirs, &root, &names).unwrap(); + assert_eq!(chosen, [root.join(rel).display().to_string()], "{value}"); + } + } + + #[test] + fn absolute_paths_and_ambiguous_names() { + let root = std::env::temp_dir().join("ws").join("a"); + let outside = std::env::temp_dir().join("elsewhere"); + let dirs: Vec = [ + root.join("libs/core"), + root.join("web"), + root.join("frontend"), + outside.clone(), + ] + .iter() + .map(|dir| dir.display().to_string()) + .collect(); + let absolute = |dir: &std::path::Path| dir.display().to_string(); + let names = repo_names( + &root, + &[ + project("core-lib", &absolute(&root.join("libs/core"))), + project("far", &absolute(&outside)), + project("web", "frontend"), + ], + &[], + ); + let select = |value: &str| select(&strings(&[value]), &[], &dirs, &root, &names); + assert_eq!(select("core-lib").unwrap(), [dirs[0].clone()]); + assert_eq!(select("far").unwrap(), [dirs[3].clone()]); + // A repo outside the root has a ../ path + assert_eq!(select("../../elsewhere").unwrap(), [dirs[3].clone()]); + assert_eq!(select("./../../elsewhere").unwrap(), [dirs[3].clone()]); + // `web` is one repo's path and another's name + let err = select("web").unwrap_err().to_string(); + assert!( + err.contains("names the repo at web by path and the repo at frontend by .meta name"), + "{err}" + ); + } + + #[test] + fn a_name_shared_by_two_repos_is_ambiguous_and_relative_roots_work() { + let root = std::path::PathBuf::from("ws-relative"); + let dirs: Vec = ["api", "group/api"] + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let names = repo_names( + &root, + &[project("api", "api"), project("api", "group/api")], + &[], + ); + let select = |value: &str| select(&strings(&[value]), &[], &dirs, &root, &names); + let err = select("api").unwrap_err().to_string(); + assert!( + err.contains("is the .meta name of the repos at api, group/api"), + "{err}" + ); + // A ./ path picks one, with a relative root as with an absolute one + assert_eq!(select("./api").unwrap(), [dirs[0].clone()]); + assert_eq!(select("group/api").unwrap(), [dirs[1].clone()]); + } +} diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 0dbe732..4d93761 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -177,8 +177,10 @@ impl SubprocessPluginManager { /// `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). + /// word owns that namespace and gets that word as its command, with the + /// rest as args, and handles subcommands it does not implement itself + /// (e.g. meta-git runs raw git). Only claimed words are joined into the + /// request's command; what the user typed stays separate args. fn route(&self, args: &[String]) -> Option<(&SubprocessPlugin, usize)> { let first = args.first()?; let claims = || { @@ -201,7 +203,7 @@ impl SubprocessPluginManager { .or_else(|| { claims() .find(|(_, words)| words.first() == Some(&first.as_str())) - .map(|(plugin, _)| (plugin, args.len())) + .map(|(plugin, _)| (plugin, 1)) }) } @@ -286,14 +288,22 @@ impl SubprocessPluginManager { return Ok(true); } - // Parse the plugin response + // A plan meta cannot read must not pass for success: an older plugin + // still sends `cmd` strings, and printing them would run nothing + let is_plan = serde_json::from_str::(&stdout_str) + .is_ok_and(|value| value.get("plan").is_some()); match serde_json::from_str::(&stdout_str) { Ok(response) => { // Plugin returned an execution plan - execute it via loop_lib self.execute_plan(&response.plan, root_dir, options) } + Err(e) if is_plan => anyhow::bail!( + "plugin {} sent an execution plan this meta cannot read ({e}); \ + upgrade the plugin to match this meta", + plugin.path.display() + ), Err(_) => { - // Couldn't parse as our protocol - print output as-is (legacy behavior) + // Not a plan - print output as-is print!("{stdout_str}"); Ok(true) } @@ -322,8 +332,6 @@ impl SubprocessPluginManager { verbose: options.verbose, silent: true, // Pre-commands run silently unless verbose add_aliases_to_global_looprc: false, - include_filters: None, - exclude_filters: None, parallel: false, // Sequential execution dry_run: false, // Pre-commands always run (setup is required) json_output: false, @@ -336,7 +344,7 @@ impl SubprocessPluginManager { for pre_cmd in &plan.pre_commands { let cmd = DirCommand { dir: pre_cmd.dir.clone(), - cmd: pre_cmd.cmd.clone(), + argv: pre_cmd.argv.clone(), env: pre_cmd.env.clone(), }; // Ignore failures for pre_commands (e.g., SSH socket already exists) @@ -356,7 +364,7 @@ impl SubprocessPluginManager { .iter() .map(|c| DirCommand { dir: c.dir.clone(), - cmd: c.cmd.clone(), + argv: c.argv.clone(), env: c.env.clone(), }) .collect(); @@ -373,8 +381,6 @@ impl SubprocessPluginManager { verbose: options.verbose, silent: options.silent, add_aliases_to_global_looprc: false, - include_filters: options.include_filters.clone(), - exclude_filters: options.exclude_filters.clone(), parallel: plan.parallel.unwrap_or(options.parallel), dry_run: options.dry_run, json_output: options.json_output, @@ -395,8 +401,6 @@ impl SubprocessPluginManager { verbose: options.verbose, silent: true, add_aliases_to_global_looprc: false, - include_filters: None, - exclude_filters: None, parallel: false, dry_run: false, json_output: false, @@ -409,7 +413,7 @@ impl SubprocessPluginManager { for post_cmd in &plan.post_commands { let cmd = DirCommand { dir: post_cmd.dir.clone(), - cmd: post_cmd.cmd.clone(), + argv: post_cmd.argv.clone(), env: post_cmd.env.clone(), }; if let Err(e) = run_commands(&post_config, &[cmd]) { @@ -760,15 +764,15 @@ mod tests { 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" + // Unclaimed subcommands go to the namespace owner as its first word, + // the rest staying args; words match whole, so "buildx" is not "build" assert_eq!( routed(&manager, &["cargo", "--version"]), - Some(("rust".to_string(), 2)) + Some(("rust".to_string(), 1)) ); assert_eq!( routed(&manager, &["cargo", "buildx", "x"]), - Some(("rust".to_string(), 3)) + Some(("rust".to_string(), 1)) ); assert_eq!(routed(&manager, &["gitx", "status"]), None); assert_eq!(routed(&manager, &["npm", "install"]), None); @@ -972,17 +976,17 @@ mod tests { let json = r#"{ "plan": { "commands": [ - {"dir": "./repo1", "cmd": "git status"}, - {"dir": "./repo2", "cmd": "git status"} + {"dir": "./repo1", "argv": ["git", "status"]}, + {"dir": "./repo2", "argv": ["git", "status"]} ] } }"#; let response: PluginResponse = serde_json::from_str(json).unwrap(); assert_eq!(response.plan.commands.len(), 2); assert_eq!(response.plan.commands[0].dir, "./repo1"); - assert_eq!(response.plan.commands[0].cmd, "git status"); + assert_eq!(response.plan.commands[0].argv, ["git", "status"]); assert_eq!(response.plan.commands[1].dir, "./repo2"); - assert_eq!(response.plan.commands[1].cmd, "git status"); + assert_eq!(response.plan.commands[1].argv, ["git", "status"]); assert!(response.plan.parallel.is_none()); } @@ -991,7 +995,7 @@ mod tests { let json = r#"{ "plan": { "commands": [ - {"dir": "/abs/path", "cmd": "npm install"} + {"dir": "/abs/path", "argv": ["npm", "install"]} ], "parallel": true } @@ -1006,7 +1010,7 @@ mod tests { let json = r#"{ "plan": { "commands": [ - {"dir": ".", "cmd": "echo hello"} + {"dir": ".", "argv": ["echo", "hello"]} ], "parallel": false } @@ -1032,17 +1036,17 @@ mod tests { fn test_execution_plan_deserialization() { let json = r#"{ "commands": [ - {"dir": "proj1", "cmd": "make build"}, - {"dir": "proj2", "cmd": "cargo build"} + {"dir": "proj1", "argv": ["make", "build"]}, + {"dir": "proj2", "argv": ["cargo", "build"]} ], "parallel": true }"#; let plan: ExecutionPlan = serde_json::from_str(json).unwrap(); assert_eq!(plan.commands.len(), 2); assert_eq!(plan.commands[0].dir, "proj1"); - assert_eq!(plan.commands[0].cmd, "make build"); + assert_eq!(plan.commands[0].argv, ["make", "build"]); assert_eq!(plan.commands[1].dir, "proj2"); - assert_eq!(plan.commands[1].cmd, "cargo build"); + assert_eq!(plan.commands[1].argv, ["cargo", "build"]); assert_eq!(plan.parallel, Some(true)); } @@ -1050,7 +1054,7 @@ mod tests { fn test_execution_plan_no_parallel_field() { let json = r#"{ "commands": [ - {"dir": ".", "cmd": "ls"} + {"dir": ".", "argv": ["ls"]} ] }"#; let plan: ExecutionPlan = serde_json::from_str(json).unwrap(); @@ -1061,27 +1065,33 @@ mod tests { #[test] fn test_planned_command_deserialization() { - let json = r#"{"dir": "/home/user/project", "cmd": "git pull --rebase"}"#; + let json = r#"{"dir": "/home/user/project", "argv": ["git", "pull", "--rebase"]}"#; let cmd: PlannedCommand = serde_json::from_str(json).unwrap(); assert_eq!(cmd.dir, "/home/user/project"); - assert_eq!(cmd.cmd, "git pull --rebase"); + assert_eq!(cmd.argv, ["git", "pull", "--rebase"]); } #[test] fn test_planned_command_relative_dir() { - let json = r#"{"dir": "./relative/path", "cmd": "npm test"}"#; + let json = r#"{"dir": "./relative/path", "argv": ["npm", "test"]}"#; let cmd: PlannedCommand = serde_json::from_str(json).unwrap(); assert_eq!(cmd.dir, "./relative/path"); - assert_eq!(cmd.cmd, "npm test"); + assert_eq!(cmd.argv, ["npm", "test"]); } #[test] fn test_planned_command_complex_command() { - let json = r#"{"dir": ".", "cmd": "git clone https://github.com/org/repo.git --depth 1"}"#; + let json = r#"{"dir": ".", "argv": ["git", "clone", "https://github.com/org/repo.git", "--depth", "1"]}"#; let cmd: PlannedCommand = serde_json::from_str(json).unwrap(); assert_eq!( - cmd.cmd, - "git clone https://github.com/org/repo.git --depth 1" + cmd.argv, + [ + "git", + "clone", + "https://github.com/org/repo.git", + "--depth", + "1" + ] ); } @@ -1161,19 +1171,19 @@ mod tests { // Test a realistic execution plan with different commands per directory let json = r#"{ "commands": [ - {"dir": "./frontend", "cmd": "npm install"}, - {"dir": "./backend", "cmd": "cargo build"}, - {"dir": "./scripts", "cmd": "python setup.py install"}, - {"dir": "./docs", "cmd": "make html"} + {"dir": "./frontend", "argv": ["npm", "install"]}, + {"dir": "./backend", "argv": ["cargo", "build"]}, + {"dir": "./scripts", "argv": ["python", "setup.py", "install"]}, + {"dir": "./docs", "argv": ["make", "html"]} ], "parallel": false }"#; let plan: ExecutionPlan = serde_json::from_str(json).unwrap(); assert_eq!(plan.commands.len(), 4); - assert_eq!(plan.commands[0].cmd, "npm install"); - assert_eq!(plan.commands[1].cmd, "cargo build"); - assert_eq!(plan.commands[2].cmd, "python setup.py install"); - assert_eq!(plan.commands[3].cmd, "make html"); + assert_eq!(plan.commands[0].argv, ["npm", "install"]); + assert_eq!(plan.commands[1].argv, ["cargo", "build"]); + assert_eq!(plan.commands[2].argv, ["python", "setup.py", "install"]); + assert_eq!(plan.commands[3].argv, ["make", "html"]); } #[test] @@ -1181,17 +1191,17 @@ mod tests { // Test ExecutionPlan with pre_commands (e.g., SSH setup) let json = r#"{ "pre_commands": [ - {"dir": ".", "cmd": "ssh -fNM -o ControlMaster=auto git@github.com"} + {"dir": ".", "argv": ["ssh", "-fNM", "-o", "ControlMaster=auto", "git@github.com"]} ], "commands": [ - {"dir": "./repo1", "cmd": "git push"}, - {"dir": "./repo2", "cmd": "git push"} + {"dir": "./repo1", "argv": ["git", "push"]}, + {"dir": "./repo2", "argv": ["git", "push"]} ], "parallel": true }"#; let plan: ExecutionPlan = serde_json::from_str(json).unwrap(); assert_eq!(plan.pre_commands.len(), 1); - assert!(plan.pre_commands[0].cmd.contains("ssh")); + assert!(plan.pre_commands[0].argv[0] == "ssh"); assert_eq!(plan.commands.len(), 2); assert_eq!(plan.parallel, Some(true)); } @@ -1201,10 +1211,10 @@ mod tests { // Test ExecutionPlan with post_commands (e.g., cleanup) let json = r#"{ "commands": [ - {"dir": ".", "cmd": "make build"} + {"dir": ".", "argv": ["make", "build"]} ], "post_commands": [ - {"dir": ".", "cmd": "make clean"} + {"dir": ".", "argv": ["make", "clean"]} ], "parallel": false }"#; @@ -1212,14 +1222,14 @@ mod tests { assert!(plan.pre_commands.is_empty()); assert_eq!(plan.commands.len(), 1); assert_eq!(plan.post_commands.len(), 1); - assert!(plan.post_commands[0].cmd.contains("clean")); + assert!(plan.post_commands[0].argv.contains(&"clean".to_string())); } #[test] fn test_execution_plan_backward_compatible() { // Test that old JSON without pre/post_commands still works let json = r#"{ - "commands": [{"dir": ".", "cmd": "ls"}] + "commands": [{"dir": ".", "argv": ["ls"]}] }"#; let plan: ExecutionPlan = serde_json::from_str(json).unwrap(); assert!(plan.pre_commands.is_empty()); @@ -1229,10 +1239,13 @@ mod tests { #[test] fn test_planned_command_with_special_characters() { - let json = r#"{"dir": "./path with spaces", "cmd": "echo \"hello world\" && echo 'single quotes'"}"#; + let json = r#"{"dir": "./path with spaces", "argv": ["echo", "\"hello world\" && echo 'single quotes'"]}"#; let cmd: PlannedCommand = serde_json::from_str(json).unwrap(); assert_eq!(cmd.dir, "./path with spaces"); - assert_eq!(cmd.cmd, "echo \"hello world\" && echo 'single quotes'"); + assert_eq!( + cmd.argv, + ["echo", "\"hello world\" && echo 'single quotes'"] + ); } // ============ get_plugin_for_command Tests ============ diff --git a/tests/plugin_git.rs b/tests/plugin_git.rs index a802514..a2d2aef 100644 --- a/tests/plugin_git.rs +++ b/tests/plugin_git.rs @@ -4,8 +4,13 @@ //! Uncomment them when running full integration tests. use std::fs; +use std::path::Path; use tempfile::tempdir; +fn touch(path: &Path) -> Vec { + vec!["touch".to_string(), path.display().to_string()] +} + /// Test that loop_lib properly respects dry_run flag throughout the execution chain #[test] fn test_dry_run_integration_loop_lib() { @@ -22,7 +27,7 @@ fn test_dry_run_integration_loop_lib() { ..Default::default() }; - let cmd = format!("touch {}", marker_file.display()); + let cmd = touch(&marker_file); let result = run(&config, &cmd); assert!(result.is_ok(), "dry_run should succeed"); assert!( @@ -34,7 +39,7 @@ fn test_dry_run_integration_loop_lib() { let marker_file2 = dir.path().join("also_should_not_exist.txt"); let commands = vec![DirCommand { dir: dir.path().to_str().unwrap().to_string(), - cmd: format!("touch {}", marker_file2.display()), + argv: touch(&marker_file2), env: None, }]; @@ -57,8 +62,6 @@ fn test_loop_config_full_serialization_round_trip() { verbose: true, silent: false, add_aliases_to_global_looprc: false, - include_filters: Some(vec!["frontend".to_string()]), - exclude_filters: Some(vec!["tests".to_string()]), parallel: true, dry_run: true, json_output: true, @@ -75,8 +78,6 @@ fn test_loop_config_full_serialization_round_trip() { assert_eq!(restored.ignore, config.ignore); assert_eq!(restored.verbose, config.verbose); assert_eq!(restored.silent, config.silent); - assert_eq!(restored.include_filters, config.include_filters); - assert_eq!(restored.exclude_filters, config.exclude_filters); assert_eq!(restored.parallel, config.parallel); assert_eq!(restored.dry_run, config.dry_run); assert_eq!(restored.json_output, config.json_output); @@ -106,12 +107,12 @@ fn test_different_commands_per_directory() { let commands = vec![ DirCommand { dir: dir1.to_str().unwrap().to_string(), - cmd: format!("touch {}", file1.display()), + argv: touch(&file1), env: None, }, DirCommand { dir: dir2.to_str().unwrap().to_string(), - cmd: format!("touch {}", file2.display()), + argv: touch(&file2), env: None, }, ]; @@ -131,8 +132,8 @@ fn test_execution_plan_protocol_compatibility() { let plugin_output = r#"{ "plan": { "commands": [ - {"dir": "./repo1", "cmd": "git status"}, - {"dir": "./repo2", "cmd": "git status"} + {"dir": "./repo1", "argv": ["git", "status"]}, + {"dir": "./repo2", "argv": ["git", "status"]} ], "parallel": false } @@ -143,9 +144,9 @@ fn test_execution_plan_protocol_compatibility() { assert_eq!(response.plan.commands.len(), 2); assert_eq!(response.plan.commands[0].dir, "./repo1"); - assert_eq!(response.plan.commands[0].cmd, "git status"); + assert_eq!(response.plan.commands[0].argv, ["git", "status"]); assert_eq!(response.plan.commands[1].dir, "./repo2"); - assert_eq!(response.plan.commands[1].cmd, "git status"); + assert_eq!(response.plan.commands[1].argv, ["git", "status"]); assert_eq!(response.plan.parallel, Some(false)); } @@ -196,26 +197,6 @@ fn test_plugin_request_options_silent_and_filters() { assert!(json.contains("tests")); } -/// Test that DirCommand properly converts to loop_lib format -#[test] -fn test_dir_command_conversion() { - use loop_lib::DirCommand as LoopDirCommand; - - // Simulate what the plugin returns (as JSON) - let planned_json = r#"{"dir": "/home/user/project", "cmd": "npm install"}"#; - let parsed: serde_json::Value = serde_json::from_str(planned_json).unwrap(); - - // subprocess_plugins converts it to loop_lib format - let loop_cmd = LoopDirCommand { - dir: parsed["dir"].as_str().unwrap().to_string(), - cmd: parsed["cmd"].as_str().unwrap().to_string(), - env: None, - }; - - assert_eq!(loop_cmd.dir, "/home/user/project"); - assert_eq!(loop_cmd.cmd, "npm install"); -} - /// Test that parallel execution works correctly with different commands #[test] fn test_parallel_execution_with_different_commands() { @@ -244,7 +225,7 @@ fn test_parallel_execution_with_different_commands() { let file = d.join(format!("file{i}.txt")); DirCommand { dir: d.to_str().unwrap().to_string(), - cmd: format!("touch {}", file.display()), + argv: touch(&file), env: None, } }) @@ -296,8 +277,6 @@ fn test_backward_compatibility_config_parsing() { assert!(!config.dry_run); assert!(!config.json_output); assert!(!config.parallel); - assert!(config.include_filters.is_none()); - assert!(config.exclude_filters.is_none()); } /* diff --git a/tests/plugin_routing.rs b/tests/plugin_routing.rs index 2934e72..50ed27f 100644 --- a/tests/plugin_routing.rs +++ b/tests/plugin_routing.rs @@ -36,7 +36,16 @@ esac } fn meta(root: &Path, args: &[&str]) { - let output = std::process::Command::new(env!("CARGO_BIN_EXE_meta")) + let output = run_meta(root, args); + assert!( + output.status.success(), + "meta {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); +} + +fn run_meta(root: &Path, args: &[&str]) -> std::process::Output { + std::process::Command::new(env!("CARGO_BIN_EXE_meta")) .args(args) .current_dir(root) .env("HOME", root) @@ -50,12 +59,7 @@ fn meta(root: &Path, args: &[&str]) { .unwrap(), ) .output() - .unwrap(); - assert!( - output.status.success(), - "meta {args:?} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); + .unwrap() } #[test] @@ -91,3 +95,33 @@ fn plugin_subcommand_still_routes_to_the_plugin() { "meta ran the plugin's command raw" ); } + +#[test] +fn a_plan_meta_cannot_read_fails_and_names_the_plugin() { + let temp = tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + workspace(&root); + // An older plugin that still plans `cmd` strings instead of `argv` + let plugin = root.join("bin").join("meta-oldplan"); + fs::write( + &plugin, + r#"#!/bin/sh +case "$1" in + --meta-plugin-info) echo '{"name":"oldplan","version":"1.0.0","commands":["oldplan"]}' ;; + --meta-plugin-exec) cat >/dev/null; echo '{"plan":{"commands":[{"dir":".","cmd":"touch ran"}]}}' ;; +esac +"#, + ) + .unwrap(); + fs::set_permissions(&plugin, fs::Permissions::from_mode(0o755)).unwrap(); + + let output = run_meta(&root, &["oldplan", "run"]); + + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "an unreadable plan passed as success" + ); + assert!(stderr.contains("upgrade the plugin"), "{stderr}"); + assert!(stderr.contains(&plugin.display().to_string()), "{stderr}"); +}