From f9daca8996fbf9e7cfc1592ba99418eb28feaa71 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 04:34:53 -0700 Subject: [PATCH 01/14] fix!: run commands as typed; --include/--exclude name whole repos meta exec and plugin plans run as argv with no shell. The plugin router no longer joins an unclaimed subcommand and its arguments into the request's command string: the namespace word is the command, the rest stay args. --include/--exclude take a repo's .meta name or its path from the workspace root, resolved against the repos in scope; a value that names no repo is an error. Implements [[tasks/harmony-2756]] --- .claude/skills/meta-exec/SKILL.md | 35 +++++---- .claude/skills/meta-git/SKILL.md | 6 +- .claude/skills/meta-safety/SKILL.md | 2 +- .claude/skills/meta-workspace/SKILL.md | 2 +- .claude/skills/meta-worktree/SKILL.md | 11 +-- src/lib.rs | 1 + src/main.rs | 66 +++++++++++----- src/repo_filter.rs | 100 ++++++++++++++++++++++++ src/subprocess_plugins.rs | 103 ++++++++++++++----------- tests/plugin_git.rs | 43 ++++------- 10 files changed, 250 insertions(+), 119 deletions(-) create mode 100644 src/repo_filter.rs diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index 586a611..a9815c3 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 reaches the program exactly as you typed it: 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. 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 there is no `cmd /c` either: run batch shims as `meta exec -- cmd /c npm install` (or `npm.cmd install`). + The `--` separates meta options from the command to execute. The `--` is optional unless your command starts with `-`. ```bash @@ -52,13 +58,14 @@ 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) @@ -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. 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..8fa3b3b 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. Arguments reach git exactly as typed, with no shell in between: `meta git log --format='%h %s'` and a commit message containing `$(...)` or `;` are passed as-is. + ## Cloning a Meta Repo ```bash @@ -87,7 +89,7 @@ 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 @@ -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..479badd 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 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..d039a9a 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -127,9 +127,10 @@ 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: a repo's `.meta` name or its path +from the worktree root (`.` for the root repo), never part of a path. A value +that names no repo in the set is an error. The command's arguments reach it as +typed, with no shell; use `-- sh -c '...'` when you want one. ## Context Detection @@ -229,7 +230,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: `.meta` name or path from the worktree root (comma-separated) | +| `--exclude ` | Skip these repos, named the same way (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..b993cdc 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) @@ -614,8 +620,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 +642,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 @@ -742,8 +746,8 @@ fn handle_command_dispatch( ); } - let include_opt = none_if_empty(include_filters.clone()); - let exclude_opt = none_if_empty(exclude_filters.clone()); + let (include_opt, exclude_opt) = + resolve_filters(cli, &wt_directories, &task_dir, config_path.parent())?; let config = loop_lib::LoopConfig { directories: wt_directories.clone(), @@ -777,7 +781,7 @@ fn handle_command_dispatch( }; if is_explicit_exec { - run(&config, &command_str)?; + run(&config, &command_args)?; } else if plugins.execute( &command_args, &wt_directories, @@ -808,8 +812,7 @@ 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 (include_opt, exclude_opt) = resolve_filters(cli, &directories, &task_dir, None)?; let config = loop_lib::LoopConfig { directories, @@ -828,7 +831,7 @@ fn handle_command_dispatch( root_dir: Some(task_dir.clone()), }; - run(&config, &command_str)?; + run(&config, &command_args)?; return Ok(()); } } @@ -897,8 +900,8 @@ 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); + let (include_opt, exclude_opt) = + resolve_filters(cli, &project_paths, meta_dir, Some(meta_dir))?; let config = loop_lib::LoopConfig { add_aliases_to_global_looprc: cli.add_aliases_to_global_looprc, @@ -937,7 +940,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, @@ -1305,12 +1308,33 @@ fn matches_tag_filter(tags: &[String], filter: &str) -> bool { } /// 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) +/// An `--include` or `--exclude` list, when given. +type Filter = Option>; + +/// `--include` and `--exclude` as the paths from `root` of the repos among +/// `dirs` they name (see [`repo_filter::resolve`]); names come from the `.meta` +/// tree at `meta_dir`. +fn resolve_filters( + cli: &Cli, + dirs: &[String], + root: &std::path::Path, + meta_dir: Option<&std::path::Path>, +) -> Result<(Filter, Filter)> { + let given = |values: &Filter| values.clone().filter(|v| !v.is_empty()); + let (include, exclude) = (given(&cli.include), given(&cli.exclude)); + if include.is_none() && exclude.is_none() { + return Ok((None, None)); } + let names = meta_dir.map(repo_filter::repo_names).unwrap_or_default(); + let resolve = |flag, values: Filter| { + values + .map(|values| repo_filter::resolve(flag, &values, dirs, root, &names)) + .transpose() + }; + Ok(( + resolve("--include", include)?, + resolve("--exclude", exclude)?, + )) } /// Print unrecognized command error with suggestion and help, then exit. diff --git a/src/repo_filter.rs b/src/repo_filter.rs new file mode 100644 index 0000000..2848def --- /dev/null +++ b/src/repo_filter.rs @@ -0,0 +1,100 @@ +//! Which repos an `--include` / `--exclude` value names. + +use anyhow::{bail, Result}; +use meta_core::config::{walk_meta_tree, MetaTreeNode}; +use std::path::Path; + +/// Every project under the meta repo at `meta_dir`, nested ones included, as +/// (`.meta` name, path from `meta_dir`). +pub fn repo_names(meta_dir: &Path) -> Vec<(String, String)> { + fn walk(nodes: &[MetaTreeNode], prefix: &str, out: &mut Vec<(String, String)>) { + for node in nodes { + let path = if prefix.is_empty() { + node.info.path.clone() + } else { + format!("{prefix}/{}", node.info.path) + }; + out.push((node.info.name.clone(), path.clone())); + walk(&node.children, &path, out); + } + } + let mut names = Vec::new(); + walk( + &walk_meta_tree(meta_dir, None).unwrap_or_default(), + "", + &mut names, + ); + names +} + +/// The paths from `root` of the repos among `dirs` that `values` name, for +/// loop_lib to match whole. A value names a repo by its `.meta` name (from +/// `names`, see [`repo_names`]) or by its path from `root` (`.` for the root), +/// never by a part of either. 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. +pub fn resolve( + flag: &str, + values: &[String], + dirs: &[String], + root: &Path, + names: &[(String, String)], +) -> Result> { + let mut paths: Vec = Vec::new(); + for value in values { + let mut found = false; + for dir in dirs { + let path = loop_lib::repo_path(dir, root).unwrap_or_else(|| dir.clone()); + let by_name = names.iter().any(|(name, p)| name == value && *p == path); + if by_name || loop_lib::filter_matches(value, dir, Some(root)) { + found = true; + if !paths.contains(&path) { + paths.push(path); + } + } + } + if !found { + bail!( + "{flag} '{value}' names no repo here. Use a repo's name from .meta or its path \ + from the workspace root (`.` for the root), as `meta project list` shows it." + ); + } + } + Ok(paths) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(values: &[&str]) -> Vec { + values.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn values_name_whole_repos_never_parts_of_paths() { + let root = std::env::temp_dir().join("ws").join("a"); + let dirs: Vec = ["", "api", "api-legacy", "libs/core"] + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let names = vec![("core-lib".to_string(), "libs/core".to_string())]; + let resolve = + |values: &[&str]| resolve("--include", &strings(values), &dirs, &root, &names); + + assert_eq!(resolve(&["api"]).unwrap(), strings(&["api"])); + assert_eq!(resolve(&["./api/"]).unwrap(), strings(&["api"])); + assert_eq!(resolve(&["."]).unwrap(), strings(&["."])); + assert_eq!(resolve(&["libs/core"]).unwrap(), strings(&["libs/core"])); + assert_eq!(resolve(&["core-lib"]).unwrap(), strings(&["libs/core"])); + assert_eq!( + resolve(&["api", "api-legacy"]).unwrap(), + strings(&["api", "api-legacy"]) + ); + // 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 = resolve(&[value]).unwrap_err().to_string(); + assert!(err.contains("names no repo"), "{value}: {err}"); + } + } +} diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 0dbe732..d97ef7a 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)) }) } @@ -336,7 +338,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 +358,7 @@ impl SubprocessPluginManager { .iter() .map(|c| DirCommand { dir: c.dir.clone(), - cmd: c.cmd.clone(), + argv: c.argv.clone(), env: c.env.clone(), }) .collect(); @@ -409,7 +411,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 +762,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 +974,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 +993,7 @@ mod tests { let json = r#"{ "plan": { "commands": [ - {"dir": "/abs/path", "cmd": "npm install"} + {"dir": "/abs/path", "argv": ["npm", "install"]} ], "parallel": true } @@ -1006,7 +1008,7 @@ mod tests { let json = r#"{ "plan": { "commands": [ - {"dir": ".", "cmd": "echo hello"} + {"dir": ".", "argv": ["echo", "hello"]} ], "parallel": false } @@ -1032,17 +1034,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 +1052,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 +1063,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 +1169,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 +1189,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 +1209,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 +1220,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 +1237,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..1718fce 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, }]; @@ -106,12 +111,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 +136,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 +148,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 +201,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 +229,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, } }) From 651bfde71f7435a187da132564ab07b02482b561 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 04:55:43 -0700 Subject: [PATCH 02/14] fix: select repos once and pass only those to loop and plugins --include/--exclude now pick the repos before anything runs, so plugins that act on their project list honor them too. Names come from the config chosen with --config, and .meta paths are normalized. Implements [[tasks/harmony-2756]] --- .claude/skills/meta-exec/SKILL.md | 2 +- src/main.rs | 72 +++++------ src/repo_filter.rs | 191 +++++++++++++++++++++--------- src/subprocess_plugins.rs | 6 - tests/plugin_git.rs | 6 - 5 files changed, 169 insertions(+), 108 deletions(-) diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index a9815c3..7e477b1 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -26,7 +26,7 @@ Each argument reaches the program exactly as you typed it: meta runs the program 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 there is no `cmd /c` either: run batch shims as `meta exec -- cmd /c npm install` (or `npm.cmd install`). +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 `-`. diff --git a/src/main.rs b/src/main.rs index b993cdc..9b4973d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -746,14 +746,19 @@ fn handle_command_dispatch( ); } - let (include_opt, exclude_opt) = - resolve_filters(cli, &wt_directories, &task_dir, config_path.parent())?; + let wt_directories = select_repos(cli, wt_directories, &task_dir, || { + // Nested names come from the tree only when no --config + // picked a different file than the walk would find + let tree = match (cli.config.as_ref(), config_path.parent()) { + (None, Some(dir)) => config::walk_meta_tree(dir, None).unwrap_or_default(), + _ => vec![], + }; + repo_filter::repo_names(&meta_projects, &tree) + })?; 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, @@ -775,8 +780,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, }; @@ -812,13 +817,11 @@ fn handle_command_dispatch( let directories: Vec = wt_paths.iter().map(|p| p.display().to_string()).collect(); - let (include_opt, exclude_opt) = resolve_filters(cli, &directories, &task_dir, None)?; + 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 @@ -885,12 +888,13 @@ 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)?; + tree = 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( @@ -899,16 +903,15 @@ fn handle_command_dispatch( ); } - // Prepare filter options (shared by both LoopConfig and PluginRequestOptions) - let (include_opt, exclude_opt) = - resolve_filters(cli, &project_paths, meta_dir, Some(meta_dir))?; + // Commands and plugins get only the selected repos + let project_paths = select_repos(cli, project_paths, meta_dir, || { + repo_filter::repo_names(&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, @@ -929,8 +932,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, }; @@ -1308,33 +1311,20 @@ fn matches_tag_filter(tags: &[String], filter: &str) -> bool { } /// Convert an empty Vec into None, non-empty into Some. -/// An `--include` or `--exclude` list, when given. -type Filter = Option>; - -/// `--include` and `--exclude` as the paths from `root` of the repos among -/// `dirs` they name (see [`repo_filter::resolve`]); names come from the `.meta` -/// tree at `meta_dir`. -fn resolve_filters( +/// 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: &[String], + dirs: Vec, root: &std::path::Path, - meta_dir: Option<&std::path::Path>, -) -> Result<(Filter, Filter)> { - let given = |values: &Filter| values.clone().filter(|v| !v.is_empty()); - let (include, exclude) = (given(&cli.include), given(&cli.exclude)); - if include.is_none() && exclude.is_none() { - return Ok((None, None)); + 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); } - let names = meta_dir.map(repo_filter::repo_names).unwrap_or_default(); - let resolve = |flag, values: Filter| { - values - .map(|values| repo_filter::resolve(flag, &values, dirs, root, &names)) - .transpose() - }; - Ok(( - resolve("--include", include)?, - resolve("--exclude", exclude)?, - )) + repo_filter::select(&include, &exclude, &dirs, root, &names()) } /// Print unrecognized command error with suggestion and help, then exit. diff --git a/src/repo_filter.rs b/src/repo_filter.rs index 2848def..6f14ce5 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -1,65 +1,126 @@ -//! Which repos an `--include` / `--exclude` value names. +//! `--include` / `--exclude`: which repos a command runs in. use anyhow::{bail, Result}; -use meta_core::config::{walk_meta_tree, MetaTreeNode}; -use std::path::Path; +use meta_core::config::{MetaTreeNode, ProjectInfo}; +use std::path::{Component, Path}; -/// Every project under the meta repo at `meta_dir`, nested ones included, as -/// (`.meta` name, path from `meta_dir`). -pub fn repo_names(meta_dir: &Path) -> Vec<(String, String)> { +/// (`.meta` name, path from the meta root) for `projects`, and for every +/// project nested under `tree` (the result of walking the same meta root). +pub fn repo_names(projects: &[ProjectInfo], tree: &[MetaTreeNode]) -> Vec<(String, String)> { fn walk(nodes: &[MetaTreeNode], prefix: &str, out: &mut Vec<(String, String)>) { for node in nodes { - let path = if prefix.is_empty() { - node.info.path.clone() - } else { - format!("{prefix}/{}", node.info.path) - }; + let path = normalize(&format!("{prefix}/{}", node.info.path)); out.push((node.info.name.clone(), path.clone())); walk(&node.children, &path, out); } } - let mut names = Vec::new(); - walk( - &walk_meta_tree(meta_dir, None).unwrap_or_default(), - "", - &mut names, - ); + let mut names: Vec<(String, String)> = projects + .iter() + .map(|p| (p.name.clone(), normalize(&p.path))) + .collect(); + walk(tree, "", &mut names); names } -/// The paths from `root` of the repos among `dirs` that `values` name, for -/// loop_lib to match whole. A value names a repo by its `.meta` name (from -/// `names`, see [`repo_names`]) or by its path from `root` (`.` for the root), -/// never by a part of either. 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. -pub fn resolve( - flag: &str, - values: &[String], +/// 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 +/// leading `./` and a trailing `/` are ignored), never by a part of either. +/// 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 selection that leaves +/// no repo. +pub fn select( + include: &[String], + exclude: &[String], dirs: &[String], root: &Path, names: &[(String, String)], ) -> Result> { - let mut paths: Vec = Vec::new(); - for value in values { - let mut found = false; - for dir in dirs { - let path = loop_lib::repo_path(dir, root).unwrap_or_else(|| dir.clone()); - let by_name = names.iter().any(|(name, p)| name == value && *p == path); - if by_name || loop_lib::filter_matches(value, dir, Some(root)) { - found = true; - if !paths.contains(&path) { - paths.push(path); - } - } - } - if !found { + if include.is_empty() && exclude.is_empty() { + return Ok(dirs.to_vec()); + } + let paths: Vec = dirs.iter().map(|dir| repo_path(dir, root)).collect(); + let named = |flag: &str, value: &str| -> Result> { + let wanted = path_value(value); + let hits: Vec<&str> = paths + .iter() + .filter(|path| { + wanted.as_deref() == Some(path.as_str()) + || names.iter().any(|(name, p)| name == value && p == *path) + }) + .map(String::as_str) + .collect(); + if hits.is_empty() { bail!( "{flag} '{value}' names no repo here. Use a repo's name from .meta or its path \ from the workspace root (`.` for the root), as `meta project list` shows it." ); } + Ok(hits) + }; + 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 = dirs + .iter() + .zip(&paths) + .filter(|(_, path)| include.is_empty() || included.contains(&path.as_str())) + .filter(|(_, path)| !excluded.contains(&path.as_str())) + .map(|(dir, _)| dir.clone()) + .collect(); + if selected.is_empty() { + bail!("--include/--exclude leave no repo to run in"); + } + Ok(selected) +} + +/// `dir`'s path from `root`, `/`-separated and `.` for the root itself; `dir` +/// as given when it is not under `root`. A relative `dir` is taken from the +/// current directory. +fn repo_path(dir: &str, root: &Path) -> String { + let absolute = std::env::current_dir() + .map(|cwd| cwd.join(dir)) + .unwrap_or_else(|_| dir.into()); + match absolute.strip_prefix(root) { + Ok(rel) => match normalize(&rel.to_string_lossy()) { + rel if rel.is_empty() => ".".to_string(), + rel => rel, + }, + Err(_) => dir.to_string(), } - Ok(paths) +} + +/// 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, +/// absolute, or with `..`). +fn path_value(value: &str) -> Option { + let escapes = Path::new(value) + .components() + .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir)); + match normalize(value) { + _ if escapes || value.is_empty() => None, + path if path.is_empty() => Some(".".to_string()), + path => Some(path), + } +} + +/// `path` as `/`-separated names, without `.` parts or a trailing `/`; `.` +/// alone becomes empty. +fn normalize(path: &str) -> String { + let parts: Vec<_> = Path::new(path) + .components() + .filter_map(|c| match c { + Component::Normal(name) => Some(name.to_string_lossy()), + _ => None, + }) + .collect(); + parts.join("/") } #[cfg(test)] @@ -73,28 +134,50 @@ mod tests { #[test] fn values_name_whole_repos_never_parts_of_paths() { let root = std::env::temp_dir().join("ws").join("a"); - let dirs: Vec = ["", "api", "api-legacy", "libs/core"] + let rels = ["", "api", "api-legacy", "libs/core"]; + let dirs: Vec = rels .iter() .map(|rel| root.join(rel).display().to_string()) .collect(); - let names = vec![("core-lib".to_string(), "libs/core".to_string())]; - let resolve = - |values: &[&str]| resolve("--include", &strings(values), &dirs, &root, &names); + let projects = [ProjectInfo { + name: "core-lib".to_string(), + path: "./libs/core/".to_string(), + repo: None, + tags: vec![], + provides: vec![], + depends_on: vec![], + meta: false, + }]; + let names = repo_names(&projects, &[]); + 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!(resolve(&["api"]).unwrap(), strings(&["api"])); - assert_eq!(resolve(&["./api/"]).unwrap(), strings(&["api"])); - assert_eq!(resolve(&["."]).unwrap(), strings(&["."])); - assert_eq!(resolve(&["libs/core"]).unwrap(), strings(&["libs/core"])); - assert_eq!(resolve(&["core-lib"]).unwrap(), strings(&["libs/core"])); - assert_eq!( - resolve(&["api", "api-legacy"]).unwrap(), - strings(&["api", "api-legacy"]) - ); + 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"]); + 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 = resolve(&[value]).unwrap_err().to_string(); + let err = select(&[value], &[]).unwrap_err().to_string(); assert!(err.contains("names no repo"), "{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}"); } } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index d97ef7a..73a5945 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -324,8 +324,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, @@ -375,8 +373,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, @@ -397,8 +393,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, diff --git a/tests/plugin_git.rs b/tests/plugin_git.rs index 1718fce..a2d2aef 100644 --- a/tests/plugin_git.rs +++ b/tests/plugin_git.rs @@ -62,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, @@ -80,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); @@ -281,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()); } /* From cbfc69fcd38766e556d27cc156fa2e03e18af094 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:05:24 -0700 Subject: [PATCH 03/14] fix: leave everything after -- to the command extract_global_flags took --json, --silent and friends from anywhere in a plugin command, so a file named --json in 'meta git add -- --json' never reached git. It now stops at --. Implements [[tasks/harmony-2756]] --- src/main.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 9b4973d..997225c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1273,6 +1273,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" => { @@ -1302,6 +1304,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. @@ -1310,7 +1313,6 @@ 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. /// The repos among `dirs` that `--include`/`--exclude` select (see /// [`repo_filter::select`]); `names` lists the `.meta` names they may use. fn select_repos( From 3159b51292bae266042a3ac7fb03a7012d6c2586 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:08:44 -0700 Subject: [PATCH 04/14] fix: --recursive walks the config chosen with --config; names normalize like paths Recursive discovery reloaded the default config file, so --config was ignored with --recursive. It now starts from the chosen config and walks only the nested meta repos. A name selector also ignores a leading ./ and trailing /. Implements [[tasks/harmony-2756]] --- src/main.rs | 36 +++++++++++++++++++++++++++++++++++- src/repo_filter.rs | 5 ++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 997225c..c3ba646 100644 --- a/src/main.rs +++ b/src/main.rs @@ -894,7 +894,12 @@ fn handle_command_dispatch( let depth_str = depth.map_or("unlimited".to_string(), |d| d.to_string()); println!("Recursive mode enabled, max depth: {depth_str}"); } - 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( @@ -1410,6 +1415,35 @@ fn check_and_warn_orphan() { } } +/// The meta tree whose top level is `projects` (from the config the user +/// chose), each nested meta repo walked from its own config, `depth` levels +/// down as `walk_meta_tree` counts them. +fn walk_from( + meta_dir: &std::path::Path, + projects: &[ProjectInfo], + depth: Option, +) -> Vec { + projects + .iter() + .map(|project| { + let dir = meta_dir.join(&project.path); + let is_meta = find_meta_config(&dir, None) + .is_some_and(|(path, _)| path.parent() == Some(dir.as_path())); + let children = match depth { + Some(0) => vec![], + _ if is_meta => config::walk_meta_tree(&dir, depth.map(|d| d.saturating_sub(1))) + .unwrap_or_default(), + _ => vec![], + }; + MetaTreeNode { + info: project.clone(), + is_meta, + children, + } + }) + .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 index 6f14ce5..f2c0398 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -47,7 +47,9 @@ pub fn select( .iter() .filter(|path| { wanted.as_deref() == Some(path.as_str()) - || names.iter().any(|(name, p)| name == value && p == *path) + || names.iter().any(|(name, p)| { + (name == value || wanted.as_deref() == Some(name.as_str())) && p == *path + }) }) .map(String::as_str) .collect(); @@ -166,6 +168,7 @@ mod tests { assert_eq!(picked(&["."], &[]), ["."]); assert_eq!(picked(&["libs/core"], &[]), ["libs/core"]); assert_eq!(picked(&["core-lib"], &[]), ["libs/core"]); + assert_eq!(picked(&["./core-lib/"], &[]), ["libs/core"]); 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"]); From 8d88344505ccb9d97f9fc209f46e32caa24e130b Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:10:21 -0700 Subject: [PATCH 05/14] docs(skills): whole-repo filter comments; the caller's shell still parses its own line Implements [[tasks/harmony-2756]] --- .claude/skills/meta-exec/SKILL.md | 2 +- .claude/skills/meta-git/SKILL.md | 4 ++-- .claude/skills/meta-safety/SKILL.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index 7e477b1..746724b 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -20,7 +20,7 @@ meta exec -- ls -la meta exec -- npm install --save-dev typescript ``` -Each argument reaches the program exactly as you typed it: 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. When you want a shell (pipes, `&&`, redirects, globs), ask for one: +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' diff --git a/.claude/skills/meta-git/SKILL.md b/.claude/skills/meta-git/SKILL.md index 8fa3b3b..656fc64 100644 --- a/.claude/skills/meta-git/SKILL.md +++ b/.claude/skills/meta-git/SKILL.md @@ -19,7 +19,7 @@ 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. Arguments reach git exactly as typed, with no shell in between: `meta git log --format='%h %s'` and a commit message containing `$(...)` or `;` are passed as-is. +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 @@ -95,7 +95,7 @@ Target specific repos. With `--tag`, the meta root repo stays included even when # 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 diff --git a/.claude/skills/meta-safety/SKILL.md b/.claude/skills/meta-safety/SKILL.md index 479badd..d584efb 100644 --- a/.claude/skills/meta-safety/SKILL.md +++ b/.claude/skills/meta-safety/SKILL.md @@ -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) From 7745b8a44977137ee0570dbd89c35884597ee205 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:17:49 -0700 Subject: [PATCH 06/14] fix: keep .. in repo paths; --help after -- is the command's Dropping .. parts gave different repos the same selection name (a '..' project matched '.'). Help detection also stops at --. Implements [[tasks/harmony-2756]] --- src/main.rs | 6 ++++- src/repo_filter.rs | 67 +++++++++++++++++++++++++++++++--------------- 2 files changed, 51 insertions(+), 22 deletions(-) diff --git a/src/main.rs b/src/main.rs index c3ba646..2ff4265 100644 --- a/src/main.rs +++ b/src/main.rs @@ -549,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 diff --git a/src/repo_filter.rs b/src/repo_filter.rs index f2c0398..a47dcd1 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -99,28 +99,27 @@ fn repo_path(dir: &str, root: &Path) -> String { } /// 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, -/// absolute, or with `..`). +/// otherwise [`normalize`]d. None for a value that cannot be such a path +/// (empty or absolute). fn path_value(value: &str) -> Option { - let escapes = Path::new(value) + let absolute = Path::new(value) .components() - .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir)); + .any(|c| matches!(c, Component::RootDir | Component::Prefix(_))); match normalize(value) { - _ if escapes || value.is_empty() => None, + _ if absolute || value.is_empty() => None, path if path.is_empty() => Some(".".to_string()), path => Some(path), } } -/// `path` as `/`-separated names, without `.` parts or a trailing `/`; `.` -/// alone becomes empty. +/// `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_map(|c| match c { - Component::Normal(name) => Some(name.to_string_lossy()), - _ => None, - }) + .filter(|c| !matches!(c, Component::CurDir)) + .map(|c| c.as_os_str().to_string_lossy()) .collect(); parts.join("/") } @@ -133,6 +132,18 @@ mod tests { 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"); @@ -141,16 +152,7 @@ mod tests { .iter() .map(|rel| root.join(rel).display().to_string()) .collect(); - let projects = [ProjectInfo { - name: "core-lib".to_string(), - path: "./libs/core/".to_string(), - repo: None, - tags: vec![], - provides: vec![], - depends_on: vec![], - meta: false, - }]; - let names = repo_names(&projects, &[]); + let names = repo_names(&[project("core-lib", "./libs/core/")], &[]); let select = |include: &[&str], exclude: &[&str]| { select(&strings(include), &strings(exclude), &dirs, &root, &names) }; @@ -183,4 +185,27 @@ mod tests { let err = select(&["api"], &["api"]).unwrap_err().to_string(); assert!(err.contains("leave no repo"), "{err}"); } + + #[test] + fn parent_parts_keep_different_repos_apart() { + let root = std::env::temp_dir().join("ws").join("a"); + let rels = ["", "..", "api", "libs/../api"]; + let dirs: Vec = rels + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let names = repo_names( + &[project("parent", ".."), project("outer", "libs/../api")], + &[], + ); + for (value, rel) in [ + (".", ""), + ("parent", ".."), + ("api", "api"), + ("outer", "libs/../api"), + ] { + let chosen = select(&strings(&[value]), &[], &dirs, &root, &names).unwrap(); + assert_eq!(chosen, [root.join(rel).display().to_string()], "{value}"); + } + } } From 1eee68616f4d2dca9d7e66934267f752e3157f52 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:22:26 -0700 Subject: [PATCH 07/14] fix: repo names from the meta tree keep relative paths Joining with an empty prefix gave /libs/core, so names from the tree (nested repos, worktree exec) never matched. Implements [[tasks/harmony-2756]] --- src/repo_filter.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/repo_filter.rs b/src/repo_filter.rs index a47dcd1..1c585c2 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -9,7 +9,7 @@ use std::path::{Component, Path}; pub fn repo_names(projects: &[ProjectInfo], tree: &[MetaTreeNode]) -> Vec<(String, String)> { fn walk(nodes: &[MetaTreeNode], prefix: &str, out: &mut Vec<(String, String)>) { for node in nodes { - let path = normalize(&format!("{prefix}/{}", node.info.path)); + let path = normalize(&Path::new(prefix).join(&node.info.path).to_string_lossy()); out.push((node.info.name.clone(), path.clone())); walk(&node.children, &path, out); } @@ -208,4 +208,27 @@ mod tests { assert_eq!(chosen, [root.join(rel).display().to_string()], "{value}"); } } + + #[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(&[], &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}"); + } + } } From 3529348f71cae3ccac5dce136b9e5aaa96ee7cb4 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:38:41 -0700 Subject: [PATCH 08/14] fix: name selection by alias in worktrees; reject ambiguous and clone filters - In a worktree set a member sits at its alias, so values select by its path in the set; .meta names map to primary-checkout paths and could pick a different member. - .meta names resolve in the same root-relative form as the repos (absolute configured paths work). - A value that is one repo's path and another repo's name is an error. - meta git clone refuses --include/--exclude instead of dropping them. Implements [[tasks/harmony-2756]] --- .claude/skills/meta-exec/SKILL.md | 2 +- .claude/skills/meta-worktree/SKILL.md | 11 +-- src/main.rs | 17 ++-- src/repo_filter.rs | 108 +++++++++++++++++++------- 4 files changed, 95 insertions(+), 43 deletions(-) diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index 746724b..75dc191 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -80,7 +80,7 @@ meta --tag backend --include api git status 2. `--include` limits to the named repos 3. `--exclude` removes the named repos -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. 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). The meta root repo stays included even when it doesn't match a tag. ## Dry Run diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index d039a9a..bc946be 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -127,9 +127,10 @@ meta git worktree exec auth-fix --exclude legacy -- npm test meta git worktree exec auth-fix --parallel -- cargo build ``` -`--include`/`--exclude` name whole repos: a repo's `.meta` name or its path -from the worktree root (`.` for the root repo), never part of a path. A value -that names no repo in the set is an error. The command's arguments reach it as +`--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 @@ -230,7 +231,7 @@ it up with `remove`. | Option | Description | |--------|-------------| -| `--include ` | Only these repos: `.meta` name or path from the worktree root (comma-separated) | -| `--exclude ` | Skip these repos, named the same way (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/main.rs b/src/main.rs index 2ff4265..979213b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -654,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, @@ -750,15 +753,9 @@ fn handle_command_dispatch( ); } - let wt_directories = select_repos(cli, wt_directories, &task_dir, || { - // Nested names come from the tree only when no --config - // picked a different file than the walk would find - let tree = match (cli.config.as_ref(), config_path.parent()) { - (None, Some(dir)) => config::walk_meta_tree(dir, None).unwrap_or_default(), - _ => vec![], - }; - repo_filter::repo_names(&meta_projects, &tree) - })?; + // 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)?; let config = loop_lib::LoopConfig { directories: wt_directories.clone(), @@ -914,7 +911,7 @@ fn handle_command_dispatch( // Commands and plugins get only the selected repos let project_paths = select_repos(cli, project_paths, meta_dir, || { - repo_filter::repo_names(&meta_projects, &tree) + repo_filter::repo_names(meta_dir, &meta_projects, &tree) })?; let config = loop_lib::LoopConfig { diff --git a/src/repo_filter.rs b/src/repo_filter.rs index 1c585c2..0db9de7 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -4,21 +4,26 @@ use anyhow::{bail, Result}; use meta_core::config::{MetaTreeNode, ProjectInfo}; use std::path::{Component, Path}; -/// (`.meta` name, path from the meta root) for `projects`, and for every -/// project nested under `tree` (the result of walking the same meta root). -pub fn repo_names(projects: &[ProjectInfo], tree: &[MetaTreeNode]) -> Vec<(String, String)> { - fn walk(nodes: &[MetaTreeNode], prefix: &str, out: &mut Vec<(String, String)>) { +/// (`.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 = normalize(&Path::new(prefix).join(&node.info.path).to_string_lossy()); - out.push((node.info.name.clone(), path.clone())); - walk(&node.children, &path, out); + 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(), normalize(&p.path))) + .map(|p| (p.name.clone(), repo_path(&meta_dir.join(&p.path), meta_dir))) .collect(); - walk(tree, "", &mut names); + walk(tree, meta_dir, meta_dir, &mut names); names } @@ -40,26 +45,40 @@ pub fn select( if include.is_empty() && exclude.is_empty() { return Ok(dirs.to_vec()); } - let paths: Vec = dirs.iter().map(|dir| repo_path(dir, root)).collect(); + let paths: Vec = dirs + .iter() + .map(|dir| repo_path(Path::new(dir), root)) + .collect(); let named = |flag: &str, value: &str| -> Result> { let wanted = path_value(value); - let hits: Vec<&str> = paths + let is_name = |name: &String| name == value || wanted.as_deref() == Some(name.as_str()); + let by_path: Vec<&str> = paths + .iter() + .filter(|path| wanted.as_deref() == Some(path.as_str())) + .map(String::as_str) + .collect(); + let by_name: Vec<&str> = paths .iter() - .filter(|path| { - wanted.as_deref() == Some(path.as_str()) - || names.iter().any(|(name, p)| { - (name == value || wanted.as_deref() == Some(name.as_str())) && p == *path - }) - }) + .filter(|path| names.iter().any(|(name, p)| is_name(name) && p == *path)) .map(String::as_str) .collect(); - if hits.is_empty() { + if !by_path.is_empty() && !by_name.is_empty() && by_path != by_name { bail!( - "{flag} '{value}' names no repo here. Use a repo's name from .meta or its path \ - from the workspace root (`.` for the root), as `meta project list` shows it." + "{flag} '{value}' is the path of {} and the .meta name of {}; name the repo by \ + its path", + by_path.join(", "), + by_name.join(", ") ); } - Ok(hits) + if by_path.is_empty() && by_name.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(if by_path.is_empty() { by_name } else { by_path }) }; let mut included = Vec::new(); for value in include { @@ -85,16 +104,16 @@ pub fn select( /// `dir`'s path from `root`, `/`-separated and `.` for the root itself; `dir` /// as given when it is not under `root`. A relative `dir` is taken from the /// current directory. -fn repo_path(dir: &str, root: &Path) -> String { +fn repo_path(dir: &Path, root: &Path) -> String { let absolute = std::env::current_dir() .map(|cwd| cwd.join(dir)) - .unwrap_or_else(|_| dir.into()); + .unwrap_or_else(|_| dir.to_path_buf()); match absolute.strip_prefix(root) { Ok(rel) => match normalize(&rel.to_string_lossy()) { rel if rel.is_empty() => ".".to_string(), rel => rel, }, - Err(_) => dir.to_string(), + Err(_) => dir.display().to_string(), } } @@ -152,7 +171,7 @@ mod tests { .iter() .map(|rel| root.join(rel).display().to_string()) .collect(); - let names = repo_names(&[project("core-lib", "./libs/core/")], &[]); + let names = repo_names(&root, &[project("core-lib", "./libs/core/")], &[]); let select = |include: &[&str], exclude: &[&str]| { select(&strings(include), &strings(exclude), &dirs, &root, &names) }; @@ -178,7 +197,7 @@ mod tests { 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 no repo"), "{value}: {err}"); + assert!(err.contains("names none of the repos"), "{value}: {err}"); let err = select(&[], &[value]).unwrap_err().to_string(); assert!(err.contains("--exclude"), "{value}: {err}"); } @@ -195,6 +214,7 @@ mod tests { .map(|rel| root.join(rel).display().to_string()) .collect(); let names = repo_names( + &root, &[project("parent", ".."), project("outer", "libs/../api")], &[], ); @@ -225,10 +245,44 @@ mod tests { project("top", "parent"), vec![node(project("core-lib", "./libs/core"), vec![])], )]; - let names = repo_names(&[], &tree); + 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()]); + // `web` is one repo's path and another's name + let err = select("web").unwrap_err().to_string(); + assert!( + err.contains("is the path of web and the .meta name of frontend"), + "{err}" + ); + } } From 30ce9234cc254ec8bb1c135ce37ebcd124c22109 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 05:54:42 -0700 Subject: [PATCH 09/14] fix: validate filters before a worktree's empty-tag exit; walk --config trees once - Inside a worktree set, --include/--exclude were not checked when --tag left no member, so a typo exited 0. - walk_from walks the chosen config like walk_meta_tree, with one visited set seeded with the root, so a nested '..' back-edge doesn't expand the root again and run commands twice. Implements [[tasks/harmony-2756]] --- src/main.rs | 68 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 25 deletions(-) diff --git a/src/main.rs b/src/main.rs index 979213b..b0e84b0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -734,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 '{}'", @@ -753,10 +757,6 @@ fn handle_command_dispatch( ); } - // 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)?; - let config = loop_lib::LoopConfig { directories: wt_directories.clone(), ignore: ignore_list, @@ -1417,32 +1417,50 @@ fn check_and_warn_orphan() { } /// The meta tree whose top level is `projects` (from the config the user -/// chose), each nested meta repo walked from its own config, `depth` levels -/// down as `walk_meta_tree` counts them. +/// 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 { - projects - .iter() - .map(|project| { - let dir = meta_dir.join(&project.path); - let is_meta = find_meta_config(&dir, None) - .is_some_and(|(path, _)| path.parent() == Some(dir.as_path())); - let children = match depth { - Some(0) => vec![], - _ if is_meta => config::walk_meta_tree(&dir, depth.map(|d| d.saturating_sub(1))) - .unwrap_or_default(), - _ => vec![], - }; - MetaTreeNode { - info: project.clone(), - is_meta, - children, - } - }) - .collect() + 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. From 6ca4477b8082e6392319ac591e7189236ec6b577 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 06:18:41 -0700 Subject: [PATCH 10/14] fix: a name shared by several repos is ambiguous; relative roots match - --include api, where nested meta repos both name a project api, used to select both; it is now an error that lists their paths. - repo_path makes the root absolute like the dirs, so a relative META_WORKTREES no longer breaks worktree filters. Implements [[tasks/harmony-2756]] --- .claude/skills/meta-exec/SKILL.md | 2 +- src/repo_filter.rs | 39 +++++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index 75dc191..1bd3edd 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -68,7 +68,7 @@ meta --include libs/core,. git status # `.` is the root repo # 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 diff --git a/src/repo_filter.rs b/src/repo_filter.rs index 0db9de7..c83a586 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -62,6 +62,12 @@ pub fn select( .filter(|path| names.iter().any(|(name, p)| is_name(name) && p == *path)) .map(String::as_str) .collect(); + if by_name.len() > 1 { + bail!( + "{flag} '{value}' is the .meta name of {}; name the repo by its path", + by_name.join(", ") + ); + } if !by_path.is_empty() && !by_name.is_empty() && by_path != by_name { bail!( "{flag} '{value}' is the path of {} and the .meta name of {}; name the repo by \ @@ -102,13 +108,15 @@ pub fn select( } /// `dir`'s path from `root`, `/`-separated and `.` for the root itself; `dir` -/// as given when it is not under `root`. A relative `dir` is taken from the +/// as given when it is not under `root`. Relative paths are taken from the /// current directory. fn repo_path(dir: &Path, root: &Path) -> String { - let absolute = std::env::current_dir() - .map(|cwd| cwd.join(dir)) - .unwrap_or_else(|_| dir.to_path_buf()); - match absolute.strip_prefix(root) { + let absolute = |path: &Path| { + std::env::current_dir() + .map(|cwd| cwd.join(path)) + .unwrap_or_else(|_| path.to_path_buf()) + }; + match absolute(dir).strip_prefix(absolute(root)) { Ok(rel) => match normalize(&rel.to_string_lossy()) { rel if rel.is_empty() => ".".to_string(), rel => rel, @@ -285,4 +293,25 @@ mod tests { "{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 = ["a/api", "b/api"] + .iter() + .map(|rel| root.join(rel).display().to_string()) + .collect(); + let names = repo_names( + &root, + &[project("api", "a/api"), project("api", "b/api")], + &[], + ); + let err = select(&strings(&["api"]), &[], &dirs, &root, &names) + .unwrap_err() + .to_string(); + assert!(err.contains("is the .meta name of a/api, b/api"), "{err}"); + // Paths still pick one, with a relative root as with an absolute one + let chosen = select(&strings(&["b/api"]), &[], &dirs, &root, &names).unwrap(); + assert_eq!(chosen, [dirs[1].clone()]); + } } From f9289697e0d00d3d539e3700be7a8d96061439d1 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 06:34:07 -0700 Subject: [PATCH 11/14] fix: compare repos as directories; ./ makes a filter value a path - Two spellings of one directory (api and libs/../api, or the root and child/..) are one repo, so --exclude skips both. - A value starting with ./ is a path only, so a path that is also an ambiguous name can still be selected. Implements [[tasks/harmony-2756]] --- .claude/skills/meta-exec/SKILL.md | 2 +- src/repo_filter.rs | 165 +++++++++++++++++++----------- 2 files changed, 107 insertions(+), 60 deletions(-) diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index 1bd3edd..93cbc41 100644 --- a/.claude/skills/meta-exec/SKILL.md +++ b/.claude/skills/meta-exec/SKILL.md @@ -80,7 +80,7 @@ meta --tag backend --include api git status 2. `--include` limits to the named repos 3. `--exclude` removes the named repos -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). 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 diff --git a/src/repo_filter.rs b/src/repo_filter.rs index c83a586..b88ccde 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -2,7 +2,7 @@ use anyhow::{bail, Result}; use meta_core::config::{MetaTreeNode, ProjectInfo}; -use std::path::{Component, Path}; +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 @@ -31,10 +31,12 @@ pub fn repo_names( /// /// 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 -/// leading `./` and a trailing `/` are ignored), never by a part of either. -/// 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 selection that leaves -/// no repo. +/// 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], @@ -45,38 +47,55 @@ pub fn select( if include.is_empty() && exclude.is_empty() { return Ok(dirs.to_vec()); } - let paths: Vec = dirs + let repos: Vec = dirs .iter() - .map(|dir| repo_path(Path::new(dir), root)) + .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 named = |flag: &str, value: &str| -> Result> { let wanted = path_value(value); - let is_name = |name: &String| name == value || wanted.as_deref() == Some(name.as_str()); - let by_path: Vec<&str> = paths - .iter() - .filter(|path| wanted.as_deref() == Some(path.as_str())) - .map(String::as_str) - .collect(); - let by_name: Vec<&str> = paths - .iter() - .filter(|path| names.iter().any(|(name, p)| is_name(name) && p == *path)) - .map(String::as_str) - .collect(); + 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 {}; name the repo by its path", - by_name.join(", ") + "{flag} '{value}' is the .meta name of {}; name the repo by its path, as ./", + listed(&by_name) ); } - if !by_path.is_empty() && !by_name.is_empty() && by_path != 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}' is the path of {} and the .meta name of {}; name the repo by \ - its path", - by_path.join(", "), - by_name.join(", ") + its path, as ./", + listed(&by_path), + listed(&by_name) ); } - if by_path.is_empty() && by_name.is_empty() { + 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 \ @@ -84,7 +103,7 @@ pub fn select( --recursive change which repos the command runs in." ); } - Ok(if by_path.is_empty() { by_name } else { by_path }) + Ok(hits.iter().map(|r| r.id.as_path()).collect()) }; let mut included = Vec::new(); for value in include { @@ -94,12 +113,11 @@ pub fn select( for value in exclude { excluded.extend(named("--exclude", value)?); } - let selected: Vec = dirs + let selected: Vec = repos .iter() - .zip(&paths) - .filter(|(_, path)| include.is_empty() || included.contains(&path.as_str())) - .filter(|(_, path)| !excluded.contains(&path.as_str())) - .map(|(dir, _)| dir.clone()) + .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"); @@ -107,6 +125,25 @@ pub fn select( 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; `dir` /// as given when it is not under `root`. Relative paths are taken from the /// current directory. @@ -197,7 +234,9 @@ mod tests { assert_eq!(picked(&["."], &[]), ["."]); assert_eq!(picked(&["libs/core"], &[]), ["libs/core"]); assert_eq!(picked(&["core-lib"], &[]), ["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"]); @@ -214,27 +253,36 @@ mod tests { } #[test] - fn parent_parts_keep_different_repos_apart() { - let root = std::env::temp_dir().join("ws").join("a"); - let rels = ["", "..", "api", "libs/../api"]; + 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("parent", ".."), project("outer", "libs/../api")], - &[], - ); - for (value, rel) in [ - (".", ""), - ("parent", ".."), - ("api", "api"), - ("outer", "libs/../api"), - ] { - let chosen = select(&strings(&[value]), &[], &dirs, &root, &names).unwrap(); - assert_eq!(chosen, [root.join(rel).display().to_string()], "{value}"); - } + 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] @@ -297,21 +345,20 @@ mod tests { #[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 = ["a/api", "b/api"] + let dirs: Vec = ["api", "group/api"] .iter() .map(|rel| root.join(rel).display().to_string()) .collect(); let names = repo_names( &root, - &[project("api", "a/api"), project("api", "b/api")], + &[project("api", "api"), project("api", "group/api")], &[], ); - let err = select(&strings(&["api"]), &[], &dirs, &root, &names) - .unwrap_err() - .to_string(); - assert!(err.contains("is the .meta name of a/api, b/api"), "{err}"); - // Paths still pick one, with a relative root as with an absolute one - let chosen = select(&strings(&["b/api"]), &[], &dirs, &root, &names).unwrap(); - assert_eq!(chosen, [dirs[1].clone()]); + 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 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()]); } } From 7ca960299940b59fb96e2d1bf0a5c0e81286b321 Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 06:47:52 -0700 Subject: [PATCH 12/14] fix: a repo outside the workspace root has a ../ path to select it by Implements [[tasks/harmony-2756]] --- src/repo_filter.rs | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/repo_filter.rs b/src/repo_filter.rs index b88ccde..75ac8dd 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -144,21 +144,33 @@ fn distinct<'a>(repos: impl Iterator>) -> Vec<&'a Repo<'a>> out } -/// `dir`'s path from `root`, `/`-separated and `.` for the root itself; `dir` -/// as given when it is not under `root`. Relative paths are taken from the -/// current directory. +/// `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()) }; - match absolute(dir).strip_prefix(absolute(root)) { - Ok(rel) => match normalize(&rel.to_string_lossy()) { - rel if rel.is_empty() => ".".to_string(), - rel => rel, - }, - Err(_) => dir.display().to_string(), + 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, } } @@ -334,6 +346,9 @@ mod tests { 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!( From 8c6e67a1c7b53a69326ecd0b23a2b5978064145f Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 06:59:16 -0700 Subject: [PATCH 13/14] fix: ambiguity errors say which repo each spelling names Implements [[tasks/harmony-2756]] --- src/repo_filter.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/repo_filter.rs b/src/repo_filter.rs index 75ac8dd..a245d17 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -80,7 +80,8 @@ pub fn select( }; if by_name.len() > 1 { bail!( - "{flag} '{value}' is the .meta name of {}; name the repo by its path, as ./", + "{flag} '{value}' is the .meta name of the repos at {}; name one by its path, \ + as ./", listed(&by_name) ); } @@ -88,8 +89,8 @@ pub fn select( |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}' is the path of {} and the .meta name of {}; name the repo by \ - its path, as ./", + "{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) ); @@ -352,7 +353,7 @@ mod tests { // `web` is one repo's path and another's name let err = select("web").unwrap_err().to_string(); assert!( - err.contains("is the path of web and the .meta name of frontend"), + err.contains("names the repo at web by path and the repo at frontend by .meta name"), "{err}" ); } @@ -371,7 +372,10 @@ mod tests { ); 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 api, group/api"), "{err}"); + 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()]); From 403f59e72f2a4e0b2e59285b69d42ced2aaca43e Mon Sep 17 00:00:00 2001 From: t Date: Sun, 25 Oct 2026 15:32:32 -0700 Subject: [PATCH 14/14] fix: a plugin plan meta cannot read is an error, not success An older plugin (e.g. a meta-git in .meta/plugins or ~/.meta/plugins, found before PATH) still sends {"cmd": ...}. Such a plan no longer parses, and was printed and treated as success, so 'meta git push' pushed nothing and exited 0. JSON with a plan key that does not parse now fails, naming the plugin and saying to upgrade it. Usage and the unrecognized-command hint show 'meta exec --'. Implements [[tasks/harmony-2756]] --- src/main.rs | 4 ++-- src/subprocess_plugins.rs | 12 ++++++++-- tests/plugin_routing.rs | 48 +++++++++++++++++++++++++++++++++------ 3 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index b0e84b0..1ae0557 100644 --- a/src/main.rs +++ b/src/main.rs @@ -614,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); } @@ -1349,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); diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 73a5945..4d93761 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -288,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) } 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}"); +}