diff --git a/.claude/skills/meta-exec/SKILL.md b/.claude/skills/meta-exec/SKILL.md index e53a941..683eb76 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). 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. +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 the same holds: a repo sits at its project's path, so it is named by its `.meta` name or that path, from the set's root. 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/.claude/skills/meta-plugins/SKILL.md b/.claude/skills/meta-plugins/SKILL.md index 4711bad..dec16fe 100644 --- a/.claude/skills/meta-plugins/SKILL.md +++ b/.claude/skills/meta-plugins/SKILL.md @@ -55,11 +55,21 @@ meta --include api cargo clippy --all-targets -- -D warnings ## Plugin Discovery Plugins are discovered from: -1. `.meta/plugins/` in the current directory and each parent -2. `~/.meta/plugins/` (moved by `META_DATA_DIR`) +1. `.meta/plugins/` next to the nearest meta config, then next to each parent + meta config that lists it as a project (one workspace), nearest first; a + parent that doesn't list it is not read. Inside a worktree set, a checkout's + own plugins come first, then those of the checkout it stands for (the one + it was made from) and its workspace. `meta plugin install --local` + installs into the nearest one +2. `~/.meta/plugins/` (moved by `META_DATA_DIR`), where `meta plugin install` installs 3. Executables named `meta-*` in PATH -The first plugin found with a given name wins. +The first plugin found with a given name wins. A plugins folder meta can't read, +and a plugin that doesn't answer `--meta-plugin-info` within 5 seconds, are +skipped with a warning naming them. + +Project-local plugins are binaries: `--local` writes `.meta/plugins/.gitignore` +(`*`) so they stay out of git as untracked files. ## Plugin Management @@ -75,8 +85,14 @@ meta plugin install # Uninstall meta plugin uninstall + +# The same for this meta repo only (.meta/plugins/ next to the nearest meta config) +meta plugin install --local +meta plugin list --local ``` +`--local` outside a meta workspace fails with "not in a meta workspace". + ## Understanding Command Flow ``` diff --git a/.claude/skills/meta-safety/SKILL.md b/.claude/skills/meta-safety/SKILL.md index d584efb..55b2dce 100644 --- a/.claude/skills/meta-safety/SKILL.md +++ b/.claude/skills/meta-safety/SKILL.md @@ -74,11 +74,10 @@ meta --strict git worktree prune **What becomes an error in strict mode:** - Missing refs when using a commit-ish (worktree create) -- Failed PR branch fetches, or no repo matching `--from-pr` (worktree create) - The root repo skipped because a commit-ish is missing there (worktree create) - Invalid `--meta` format values (worktree create) - Failed directory removal (worktree prune) -- Store update failures (worktree create, add, remove, prune) +- Any set prune keeps: one holding work, a worktree meta has no record of, a worktree from another workspace, or a record it can't read (worktree prune) **When to use --strict:** - CI pipelines testing a specific release tag across all repos @@ -93,13 +92,9 @@ meta --strict git worktree prune ### Ephemeral Cleanup Behavior -`meta git worktree exec --ephemeral` creates and cleans up in best-effort mode (`strict=false`), even if you specified `--strict`. Cleanup only runs if creation succeeded. This ensures: +`meta git worktree exec --ephemeral` creates the set in best-effort mode (`strict=false`, so a repo missing a ref is skipped), even if you specified `--strict`, runs the command, then removes the set. Cleanup only runs if creation succeeded. -- The command result (success/failure) reflects the actual executed command, not cleanup issues -- Cleanup failures are logged as warnings, not errors -- Partial cleanup succeeds even if some repos have open file handles or permissions issues - -If you need to ensure cleanup completed fully, follow up with `meta git worktree list` to verify. +If cleanup fails, meta prints the error and exits non-zero even when the command itself succeeded, and the set may be left in place. Check with `meta git worktree list` and remove it with `meta git worktree remove `. ### Worktree-specific --strict diff --git a/.claude/skills/meta-workspace/SKILL.md b/.claude/skills/meta-workspace/SKILL.md index 859ca35..f2c78e1 100644 --- a/.claude/skills/meta-workspace/SKILL.md +++ b/.claude/skills/meta-workspace/SKILL.md @@ -29,27 +29,27 @@ In a meta repo, changes often span multiple repositories. Using `meta` commands - **Maintain consistency** - same commit message, same branch across repos - **Never miss a repo** - meta tracks them all -## The .meta File - -The `.meta` file defines child repositories: - -```json -{ - "projects": { - "api": "git@github.com:org/api.git", - "web": { - "repo": "git@github.com:org/web.git", - "path": "./frontend/web", - "tags": ["frontend", "typescript"] - } - } -} +## The Meta Config + +One config file in the workspace root defines the child repositories: +`.meta.yaml` (or `.meta.yml`), or `.meta.json`. + +```yaml +projects: + api: git@github.com:org/api.git + web: + repo: git@github.com:org/web.git + path: frontend/web + tags: [frontend, typescript] ``` -**Simple format**: `"name": "git-url"` - clones to `./name` +**Simple format**: `name: git-url` - clones to `./name` **Extended format**: Object with `repo`, optional `path`, optional `tags` -`.meta.json`, `.meta.yaml` and `.meta.yml` are also supported. +An older repo may use the legacy `.meta` file (JSON, no extension). It still +works, but it takes the name of meta's `.meta/` folder (skills and +project-local plugins): rename it with `git mv .meta .meta.json` (same content). +Two config files in one directory are an error that names both; keep one. ## Discovering What's Here diff --git a/.claude/skills/meta-worktree/SKILL.md b/.claude/skills/meta-worktree/SKILL.md index 2cceb6a..fa91890 100644 --- a/.claude/skills/meta-worktree/SKILL.md +++ b/.claude/skills/meta-worktree/SKILL.md @@ -26,9 +26,9 @@ Read-only work (reading code, searching, answering questions) may stay in the primary checkout. Create one set per task, with only the repos it touches, and remove it once the -work is pushed. Before a session ends, remove every set it created. Run -`meta git worktree` commands from the primary checkout: inside a set they look -for sets under that set (only `list` understands the current set). +work is pushed. Before a session ends, remove every set it created. Inside a +set, `meta git worktree` commands find sets where the checkout the set was +made from keeps them, so running them there acts on the workspace's sets. ## Creating Worktrees @@ -36,7 +36,7 @@ for sets under that set (only `list` understands the current set). # Specific repos (the root repo and their dependencies are added automatically) meta git worktree create auth-fix --repo backend --repo frontend -# Only the named repos (and, for nested aliases, their parent repos) +# Only the named repos (and, for a repo nested inside another project's path, that parent project) meta git worktree create auth-fix --repo backend --no-deps # Every repo configured at this meta level @@ -63,12 +63,14 @@ meta git worktree create auth-fix --repo backend --dry-run Add a repo to an existing set with `meta git worktree add auth-fix --repo another-service`. +A set lays its repos out as the workspace does: each repo sits at its `path` +from the meta config, so relative references between repos keep working. + `--from-pr` uses the PR's head branch name and fetches it from the child repo whose `origin` matches; it does not check out a fork's branch or pin the head -SHA. It never applies to the root repo. When no repo matches it only warns and -keeps the set's own branch; when the fetch fails it warns and still uses a branch -named after the PR, without the PR's commits (add `--strict` to make either an -error). To continue a PR on the root repo, check out its branch directly: +SHA. It never applies to the root repo. When no selected repo matches, or the +fetch fails, create fails and makes nothing. To continue a PR on the root repo, +check out its branch directly: ```bash git fetch origin my-feature:my-feature # create or fast-forward the local branch @@ -76,8 +78,7 @@ meta git worktree create review --repo .:my-feature --repo backend --strict ``` Don't pass `origin/my-feature` as the commit-ish here: with a commit-ish, create -always makes a new branch, which fails when `my-feature` already exists locally -(and without `--strict` that failure is only a warning). +always makes a new branch, which fails when `my-feature` already exists locally. With `--from-pr` on a child repo whose PR branch already exists locally, `create` checks that branch out as it is (the fetch only updates `origin/`), so @@ -96,9 +97,10 @@ meta git worktree create ci-check --all --ephemeral --meta agent=review-bot --me meta git worktree exec --ephemeral lint-check --all -- make lint ``` -`prune` removes sets whose TTL has expired and sets it considers orphaned (none -of its repos are in the project any more); for a set whose directory is gone it -only forgets meta's record. `--ephemeral` alone only records metadata. A TTL is a backstop for a session that +`prune` removes sets whose TTL has expired; for a set whose directory is gone +it only forgets meta's record. Once its repos are taken out of the meta config, +or the checkout it was made from is moved or deleted, a set is no longer the +workspace's: remove it with `git worktree remove`. `--ephemeral` alone only records metadata. A TTL is a backstop for a session that dies before removing its sets. ## Inspecting Worktrees @@ -124,8 +126,8 @@ meta git worktree exec auth-fix --exclude legacy -- npm test meta git worktree exec auth-fix --parallel -- cargo build ``` -`--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 +`--include`/`--exclude` name whole repos as in the workspace: a project's name +or its 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. @@ -157,20 +159,22 @@ run it from the primary checkout to be sure it uses the primary repos. meta git worktree remove auth-fix # refuses a set with work it would lose meta git worktree remove auth-fix --force # discards that work meta git worktree prune --dry-run # preview -meta git worktree prune # remove expired (TTL) and orphaned sets +meta git worktree prune # remove expired (TTL) and orphaned sets of this workspace ``` `remove` and `prune` delete only sets meta created, and check every repo in the set first, nested ones included: uncommitted or untracked changes, commits on no branch, and files outside every repo count as work. `remove` refuses such a -set unless `--force`; `prune` keeps it. `prune` sees the sets recorded in the -current workspace's repositories (including sets made from other checkouts of -them), not every set on the machine. `--force` and `exec --ephemeral` discard that work: commit and -push first. +set unless `--force`; `prune` keeps it. Both act only on sets of the current +workspace: sets whose every worktree is recorded in one of the workspace's +repositories. Another workspace's set is never touched, even when both share a +`META_WORKTREES` directory; `remove` refuses it and names its workspace. Run +from inside a set, they act on the workspace the set was made from. +`--force` and `exec --ephemeral` discard that work: commit and push first. ## Lifecycle Hooks -Configure hooks in the meta config (`.meta`, `.meta.json`, `.meta.yaml` or `.meta.yml`): +Configure hooks in the meta config (`.meta.yaml`, `.meta.yml`, `.meta.json` or the legacy `.meta`): ```yaml worktree: @@ -180,7 +184,9 @@ worktree: post-prune: my-tool worktree on-prune ``` -Each hook gets a JSON description of the action on stdin. Hook failures don't +Each hook runs in the directory of the config that names it (the workspace's, +also when run from inside a set) and gets a JSON description of the action on +stdin. Hook failures don't block the operation; they are logged as warnings, shown only with `RUST_LOG=warn`. ## Where Meta Keeps Its Records @@ -190,14 +196,17 @@ into git's own directory for that worktree, `/.git/worktrees//meta-wor with the set's path, its project, when it was created, and its TTL, ephemeral flag and custom metadata. Git deletes the record with the worktree. The record is how `remove` and `prune` know meta made a set: a set made by hand, or by a -meta from before records, is refused; remove it with `git worktree remove`. +meta from before records, is refused, and so is a set holding a worktree meta +has no record of (one added by hand with `git worktree add`); remove those with +`git worktree remove`. `list` scans this project's `.worktrees/` and shows each set's record. ## Strict Mode `--strict` on `create` (or global `meta --strict`) turns warnings such as a missing commit-ish in one repo into errors. A create that fails is rolled back: -the worktrees and branches it made are deleted again. +the worktrees and branches it made are deleted again. If the rollback itself +can't delete something, the error says what was left behind. ## Command Reference @@ -219,7 +228,7 @@ the worktrees and branches it made are deleted again. | `[]` | Start from a tag, SHA or branch (positional) | | `--repo [:]` | Add specific repo(s) | | `--all` | Add all repos at this meta level | -| `--no-deps` | Skip automatic root and dependency selection (nested aliases still get their parents) | +| `--no-deps` | Skip automatic root and dependency selection (a repo nested inside another project's path still gets that parent project) | | `-r, --recursive` | Resolve across nested meta repos (root-relative aliases) | | `--branch ` | Override the branch name | | `--from-pr ` | Start a child repo from a PR's head branch | @@ -233,7 +242,7 @@ the worktrees and branches it made are deleted again. | Option | Description | |--------|-------------| -| `--include ` | Only these repos, by alias (comma-separated) | -| `--exclude ` | Skip these repos, by alias (comma-separated) | +| `--include ` | Only these repos, by name or path (comma-separated) | +| `--exclude ` | Skip these repos, by name or path (comma-separated) | | `--parallel` | Run concurrently | | `--ephemeral` | Create, run, then remove (takes `--repo`/`--all`, `--branch`, `--from-pr`, `--meta`, a commit-ish) | diff --git a/Cargo.toml b/Cargo.toml index 6670c04..7d8828f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,9 +31,13 @@ flate2 = "1.0" tar = "0.4" zip = { version = "9.0.4", default-features = false, features = ["aes-crypto", "bzip2", "deflate", "time", "zstd"] } +tempfile = "3.3" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [dev-dependencies] assert_cmd = "2.0" -tempfile = "3.3" predicates = "2.1" indexmap = "2" diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..2d41864 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,38 @@ +//! Command-line errors that never echo control characters. + +use meta_core::display::escape; +use std::ffi::OsStr; + +/// The error to show for `args` that `P` rejected. Clap quotes rejected +/// values as given, so the error comes from parsing the escaped arguments: +/// the same error, with values that can't move the cursor or forge a line. +/// If the escaped arguments parse, a plain error stands in. +pub fn escaped_error( + args: impl IntoIterator>, +) -> clap::Error { + let shown = args + .into_iter() + .map(|arg| escape(&arg.as_ref().to_string_lossy()).into_owned()) + .collect::>(); + match P::try_parse_from(shown) { + Err(e) => e, + Ok(_) => P::command().error( + clap::error::ErrorKind::InvalidValue, + "an argument contains a control character", + ), + } +} + +/// Parse `P` from this process's arguments, exiting on an error with +/// [`escaped_error`] (help and version print as usual, and so does clap's +/// invalid UTF-8 error, which doesn't echo the value). +pub fn parse() -> P { + use clap::error::ErrorKind; + P::try_parse().unwrap_or_else(|e| match e.kind() { + ErrorKind::DisplayHelp + | ErrorKind::DisplayVersion + | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand + | ErrorKind::InvalidUtf8 => e.exit(), + _ => escaped_error::

(std::env::args_os()).exit(), + }) +} diff --git a/src/context.rs b/src/context.rs index 12d82a8..a8114ef 100644 --- a/src/context.rs +++ b/src/context.rs @@ -103,7 +103,7 @@ fn is_cache_valid(cached: &CachedContext, current_root: &PathBuf) -> bool { pub fn handle_context(json: bool, no_status: bool, no_cache: bool, verbose: bool) -> Result<()> { let cwd = std::env::current_dir().context("Failed to get current directory")?; - let (config_path, _format) = config::find_meta_config(&cwd, None) + let (config_path, _format) = config::find_meta_config(&cwd, None)? .ok_or_else(|| anyhow::anyhow!("Not a meta workspace (no .meta config found)"))?; let meta_dir = config_path diff --git a/src/init.rs b/src/init.rs index e2d66cf..c66338d 100644 --- a/src/init.rs +++ b/src/init.rs @@ -115,7 +115,7 @@ pub enum InitCommand { None, /// Install Claude Code skills, rules, and hooks Claude { - /// Overwrite all existing files including settings + /// Refresh skills and rules, merge meta hooks into settings force: bool, /// Update skills and rules only, skip settings (preserves user customizations) update: bool, @@ -143,13 +143,13 @@ fn print_init_help() { println!(" claude Install Claude Code skills, rules, and hooks for this meta repo"); println!(); println!("OPTIONS:"); - println!(" -f, --force Overwrite all existing files including settings"); + println!(" -f, --force Refresh skills and rules, merge meta hooks into settings"); println!(" -u, --update Update skills and rules only, preserve settings"); println!(); println!("EXAMPLES:"); println!(" meta init claude Install Claude integration"); println!(" meta init claude --update Update skills/rules, keep settings"); - println!(" meta init claude --force Overwrite everything"); + println!(" meta init claude --force Refresh skills/rules and merge settings"); } /// Install Claude Code skills and hook configuration @@ -189,7 +189,14 @@ fn install_claude_integration_to( println!(); } - let mut merged = false; + // Build and validate settings before writing any skills or rules. + let settings_path = claude_dir.join("settings.json"); + let settings_link = symlink_in(target_dir, Path::new(".claude/settings.json")); + let settings_plan = if update || settings_link.is_some() { + None + } else { + Some(prepare_settings(&settings_path)?) + }; // --force or --update: overwrite; default: skip existing let overwrite_content = force || update; @@ -227,19 +234,24 @@ fn install_claude_integration_to( .next() .is_some_and(|l| FLAT_SKILL_HEADINGS.contains(&l)) }); - if overwrite_content && is_file && !shipped { - println!( - "{} {} (not created by meta, left alone)", - "Skipped".yellow(), - escape_path(&flat_path) - ); - skipped += 1; - } else if overwrite_content && shipped { + if overwrite_content && shipped { fs::remove_file(&flat_path) .with_context(|| format!("Failed to remove {}", escape_path(&flat_path)))?; if verbose { println!("{} {}", "Removed".yellow(), escape_path(&flat_path)); } + } else if fs::symlink_metadata(&flat_path).is_ok() { + println!( + "{} {} ({})", + "Skipped".yellow(), + escape_path(&flat_path), + if shipped { + "an older meta's file; --force or --update removes it" + } else { + "not created by meta, left alone" + } + ); + skipped += 1; } } @@ -271,37 +283,28 @@ fn install_claude_integration_to( installed += 1; } - // Install/merge settings.json with hook configuration - // --update: skip entirely (preserve user settings) - // --force: overwrite completely - // default: merge meta hooks into existing settings - let settings_path = claude_dir.join("settings.json"); + // --update leaves settings untouched; --force uses the same merge as default. if update { - if verbose { - println!( - "{} settings.json (--update preserves settings)", - "Skipped".yellow() - ); - } + println!("Skipped .claude/settings.json (--update preserves settings)"); skipped += 1; - } else if let Some(link) = symlink_in(target_dir, Path::new(".claude/settings.json")) { + } else if let Some(link) = settings_link { println!( - "{} .claude/settings.json (reached through the symlink {}, not followed)", - "Skipped".yellow(), + "Skipped .claude/settings.json (reached through the symlink {}, not followed)", escape_path(&link) ); skipped += 1; - } else { - let result = install_settings(&settings_path, force, verbose)?; - match result { - SettingsResult::Created => installed += 1, - SettingsResult::Overwritten => installed += 1, - SettingsResult::Merged => { - merged = true; - installed += 1; - } + } else if let Some(plan) = settings_plan { + if let Some(content) = plan.content { + write_settings_atomic(&settings_path, &content)?; + installed += 1; } + println!("{} {}", plan.message, escape_path(&settings_path)); } + let present_hooks = fs::read_to_string(&settings_path) + .ok() + .and_then(|content| serde_json::from_str::(&content).ok()) + .map(|settings| installed_hooks(&settings)) + .unwrap_or_default(); // Print summary println!(); @@ -324,17 +327,11 @@ fn install_claude_integration_to( skills.copied ); } - if merged { - println!( - "{} Merged meta hooks into existing settings.json", - "✓".green() - ); - } if skipped > 0 { let hint = if update { "(--update preserves settings)" } else { - "(use --force to overwrite, --update to refresh content)" + "(use --force or --update to refresh skills and rules)" }; println!( "{} Skipped {} existing file(s) {}", @@ -344,7 +341,7 @@ fn install_claude_integration_to( ); } - if installed > 0 || merged { + if installed > 0 { println!(); println!("Claude Code is now configured for this meta repository:"); println!( @@ -353,12 +350,17 @@ fn install_claude_integration_to( skills.agent_dirs.join(", ") ); println!(" Rules: .claude/rules/ ({} rule files)", RULES.len()); - println!(" Hooks: .claude/settings.json (SessionStart, PreToolUse, PreCompact)"); + if !present_hooks.is_empty() { + println!( + " Hooks: .claude/settings.json ({})", + present_hooks.join(", ") + ); + } println!(" Note: PreToolUse hooks require the standalone agent CLI (`agent guard`)."); } #[cfg(not(test))] - if (installed > 0 || merged) && !agent_cli_available() { + if (installed > 0) && !agent_cli_available() { println!( "{}", "Warning: 'agent' CLI not found. PreToolUse hooks require the standalone agent tool." @@ -367,10 +369,10 @@ fn install_claude_integration_to( println!("Install from: https://github.com/gitkb/agent"); } - // Try to register GitKB marketplace if claude CLI is available - // Skip in tests to avoid external CLI calls that slow down test execution - #[cfg(not(test))] - register_marketplace(verbose); + println!(); + println!("For global Claude plugin access, run:"); + println!(" claude plugin marketplace add gitkb/claude-plugins"); + println!(" claude plugin install meta@gitkb"); Ok(()) } @@ -457,13 +459,11 @@ fn install_skills_with( } let path = root.join(&rel); if path.exists() && !overwrite { - if verbose { - println!( - "{} {} (already exists)", - "Skipped".yellow(), - escape_path(&path) - ); - } + println!( + "{} {} (already exists)", + "Skipped".yellow(), + escape_path(&path) + ); report.skipped += 1; continue; } @@ -503,16 +503,15 @@ fn install_skills_with( let legacy = agent.legacy.then_some(*content); match skill_entry(&link, &target, &marker, legacy) { SkillEntry::Missing => {} - SkillEntry::Linked => continue, - SkillEntry::Owned if overwrite => remove_owned(&link, &marker)?, - SkillEntry::Owned => { + SkillEntry::Linked => { if verbose { - println!( - "{} {} (already exists)", - "Skipped".yellow(), - escape_path(&link) - ); + println!("Skipped {} (already linked)", escape_path(&link)); } + continue; + } + SkillEntry::Owned if overwrite => remove_owned(&link, &marker)?, + SkillEntry::Owned => { + println!("Skipped {} (already exists)", escape_path(&link)); report.skipped += 1; continue; } @@ -642,56 +641,95 @@ fn copy_skill(source: &Path, dir: &Path, marker: &str) -> Result<()> { Ok(()) } -/// Result of settings installation -enum SettingsResult { - Created, - Overwritten, - Merged, +struct SettingsPlan { + content: Option, + message: String, } -/// Install or merge settings.json -fn install_settings(settings_path: &Path, force: bool, verbose: bool) -> Result { - let meta_hooks = build_meta_hooks(); - - if !settings_path.exists() { - // Fresh install: create new settings with meta hooks - let settings = json!({ "hooks": meta_hooks }); - let content = serde_json::to_string_pretty(&settings)?; - write_file(settings_path, &content, verbose)?; - return Ok(SettingsResult::Created); - } +fn prepare_settings(path: &Path) -> Result { + let existing = match fs::read_to_string(path) { + Ok(content) => Some( + serde_json::from_str::(&content) + .with_context(|| format!("Invalid JSON in {}", escape_path(path)))?, + ), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e).with_context(|| format!("Failed to read {}", escape_path(path))), + }; + let created = existing.is_none(); + let existing = existing.unwrap_or_else(|| json!({})); + let before = installed_hooks(&existing); + let merged = merge_hooks_into_settings(existing, build_meta_hooks(), path)?; + let added: Vec<_> = installed_hooks(&merged) + .into_iter() + .filter(|key| !before.contains(key)) + .collect(); + let message = if created { + "Created".to_string() + } else if added.is_empty() { + "Already has meta's hooks (no write):".to_string() + } else { + format!("Added {} hooks to", added.join(", ")) + }; + let content = if created || !added.is_empty() { + Some(serde_json::to_string_pretty(&merged)?) + } else { + None + }; + Ok(SettingsPlan { content, message }) +} - if force { - // Force: overwrite completely - let settings = json!({ "hooks": meta_hooks }); - let content = serde_json::to_string_pretty(&settings)?; - write_file(settings_path, &content, verbose)?; - return Ok(SettingsResult::Overwritten); +fn write_settings_atomic(path: &Path, content: &str) -> Result<()> { + use std::io::Write; + // A new file has nothing to lose, and gets the umask's mode + if !path.exists() { + return fs::write(path, content) + .with_context(|| format!("Failed to write {}", escape_path(path))); } + let parent = path.parent().context("Settings path has no parent")?; + let mut temp = tempfile::NamedTempFile::new_in(parent).with_context(|| { + format!( + "Failed to create temporary settings in {}", + escape_path(parent) + ) + })?; + temp.write_all(content.as_bytes())?; + // The temporary file is private; keep the mode settings.json had + temp.as_file() + .set_permissions(fs::metadata(path)?.permissions())?; + temp.persist(path) + .with_context(|| format!("Failed to write {}", escape_path(path)))?; + Ok(()) +} - // Merge: read existing, deep-merge hooks, write back - let existing_content = fs::read_to_string(settings_path) - .with_context(|| format!("Failed to read {}", escape_path(settings_path)))?; - - let existing: Value = serde_json::from_str(&existing_content) - .with_context(|| format!("Failed to parse {}", escape_path(settings_path)))?; - - let merged = merge_hooks_into_settings(existing, meta_hooks); - let content = serde_json::to_string_pretty(&merged)?; - fs::write(settings_path, &content) - .with_context(|| format!("Failed to write {}", escape_path(settings_path)))?; +fn installed_hooks(settings: &Value) -> Vec { + build_meta_hooks() + .into_iter() + .filter_map(|(key, groups)| { + let existing = settings.get("hooks")?.get(&key)?.as_array()?; + groups + .as_array()? + .iter() + .all(|group| existing.iter().any(|found| same_group(found, group))) + .then_some(key) + }) + .collect() +} - if verbose { - println!( - "{} {} (merged)", - "Wrote".green(), - escape_path(settings_path) - ); - } else { - println!(" {} settings.json (merged)", "✓".green()); +/// Whether two hook groups run the same hooks for the same tool calls: the +/// same matcher and the same hook types, commands and prompts. Other fields, +/// such as a timeout the user changed, don't make a group another one. +fn same_group(a: &Value, b: &Value) -> bool { + type Hook<'a> = (Option<&'a Value>, Option<&'a Value>, Option<&'a Value>); + fn hooks(group: &Value) -> Option>> { + let hooks = group.get("hooks")?.as_array()?; + Some( + hooks + .iter() + .map(|h| (h.get("type"), h.get("command"), h.get("prompt"))) + .collect(), + ) } - - Ok(SettingsResult::Merged) + a.get("matcher") == b.get("matcher") && hooks(a) == hooks(b) } /// Build the meta hooks configuration as a JSON object @@ -739,68 +777,45 @@ fn build_meta_hooks() -> Map { } /// Merge meta hooks into existing settings, preserving other settings -fn merge_hooks_into_settings(mut existing: Value, meta_hooks: Map) -> Value { - // Ensure existing has a hooks object - if !existing.is_object() { - return json!({ "hooks": meta_hooks }); - } - - let obj = existing.as_object_mut().unwrap(); - - // Get or create the hooks object +fn merge_hooks_into_settings( + mut existing: Value, + meta_hooks: Map, + path: &Path, +) -> Result { + let invalid = |key: &str, shape: &str| { + anyhow::anyhow!( + "Cannot merge {}: key '{}' must be {}", + escape_path(path), + key, + shape + ) + }; + let obj = existing.as_object_mut().ok_or_else(|| { + anyhow::anyhow!( + "Cannot merge {}: it must hold a JSON object", + escape_path(path) + ) + })?; let hooks = obj .entry("hooks") .or_insert_with(|| json!({})) - .as_object_mut(); - - if let Some(hooks) = hooks { - // For each lifecycle key in meta_hooks, append to existing array - for (lifecycle, meta_hook_array) in meta_hooks { - if let Some(existing_array) = hooks.get_mut(&lifecycle) { - // Existing array: append meta hooks - if let Some(arr) = existing_array.as_array_mut() { - if let Some(meta_arr) = meta_hook_array.as_array() { - for hook in meta_arr { - // Avoid duplicates by checking if hook already exists - if !arr.iter().any(|h| hooks_equal(h, hook)) { - arr.push(hook.clone()); - } - } - } + .as_object_mut() + .ok_or_else(|| invalid("hooks", "an object"))?; + for (key, groups) in meta_hooks { + let arr = hooks + .entry(&key) + .or_insert_with(|| json!([])) + .as_array_mut() + .ok_or_else(|| invalid(&format!("hooks.{key}"), "an array"))?; + if let Some(groups) = groups.as_array() { + for group in groups { + if !arr.iter().any(|found| same_group(found, group)) { + arr.push(group.clone()); } - } else { - // No existing array: add meta hooks - hooks.insert(lifecycle, meta_hook_array); } } - } else { - // hooks is not an object, replace it - obj.insert("hooks".to_string(), json!(meta_hooks)); - } - - existing -} - -/// Check if two hook entries are effectively equal (same type and command/prompt) -fn hooks_equal(a: &Value, b: &Value) -> bool { - // Compare the hooks array within each group - let a_hooks = a.get("hooks").and_then(|h| h.as_array()); - let b_hooks = b.get("hooks").and_then(|h| h.as_array()); - - match (a_hooks, b_hooks) { - (Some(a_arr), Some(b_arr)) => { - if a_arr.len() != b_arr.len() { - return false; - } - a_arr.iter().zip(b_arr.iter()).all(|(a_hook, b_hook)| { - let same_type = a_hook.get("type") == b_hook.get("type"); - let same_command = a_hook.get("command") == b_hook.get("command"); - let same_prompt = a_hook.get("prompt") == b_hook.get("prompt"); - same_type && same_command && same_prompt - }) - } - _ => false, } + Ok(existing) } #[cfg(not(test))] @@ -816,58 +831,6 @@ fn agent_cli_available() -> bool { .unwrap_or(false) } -/// Register the GitKB marketplace with Claude Code (if available). -/// This is best-effort — if `claude` is not on PATH, skip silently. -#[cfg(not(test))] -fn register_marketplace(verbose: bool) { - use std::process::Command; - - // Check if claude CLI is available - let claude_available = Command::new("claude") - .arg("--version") - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status() - .map(|s| s.success()) - .unwrap_or(false); - - if !claude_available { - if verbose { - println!( - "{} Claude CLI not found, skipping marketplace registration", - "•".yellow() - ); - } - return; - } - - // Register the marketplace (idempotent) - let result = Command::new("claude") - .args(["plugin", "marketplace", "add", "gitkb/claude-plugins"]) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status(); - - match result { - Ok(status) if status.success() => { - println!(); - println!("{} Registered GitKB plugin marketplace", "✓".green()); - println!( - " Run {} for global plugin access", - "claude plugin install meta@gitkb".cyan() - ); - } - _ => { - if verbose { - println!( - "{} Failed to register marketplace (non-fatal)", - "•".yellow() - ); - } - } - } -} - fn write_file(path: &Path, content: &str, verbose: bool) -> Result<()> { fs::write(path, content).with_context(|| format!("Failed to write {}", escape_path(path)))?; @@ -888,6 +851,96 @@ mod tests { use super::*; use tempfile::tempdir; + #[test] + fn invalid_settings_leave_every_file_unchanged_even_with_force() { + fn snapshot(root: &Path) -> Vec<(PathBuf, Option>)> { + let mut entries = Vec::new(); + for entry in fs::read_dir(root).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + entries.push((path.clone(), None)); + entries.extend(snapshot(&path)); + } else { + entries.push((path.clone(), Some(fs::read(&path).unwrap()))); + } + } + entries.sort(); + entries + } + for (content, key) in [ + (r#"[{"user":"data"}]"#, "must hold a JSON object"), + (r#"{"hooks":[],"theme":"dark"}"#, "key 'hooks'"), + (r#"{"hooks":{"PreToolUse":{}}}"#, "key 'hooks.PreToolUse'"), + ("{invalid json", "Invalid JSON"), + ] { + let dir = tempdir().unwrap(); + fs::create_dir_all(dir.path().join(".claude/rules")).unwrap(); + fs::write( + dir.path() + .join(".claude/rules/meta-workspace-discipline.md"), + "keep this rule", + ) + .unwrap(); + let settings = dir.path().join(".claude").join("settings.json"); + fs::write(&settings, content).unwrap(); + let before = snapshot(dir.path()); + for force in [false, true] { + let err = + install_claude_integration_to(dir.path(), force, false, false).unwrap_err(); + let message = format!("{err:#}"); + assert!(message.contains(&escape_path(&settings)), "{message}"); + assert!(message.contains(key), "{message}"); + assert_eq!(snapshot(dir.path()), before); + } + } + } + + #[test] + fn a_changed_hook_timeout_is_still_metas_hook() { + let dir = tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + let mut hooks = build_meta_hooks(); + hooks["SessionStart"][0]["hooks"][0]["timeout"] = json!(30); + fs::write(&settings, json!({ "hooks": hooks }).to_string()).unwrap(); + let plan = prepare_settings(&settings).unwrap(); + assert!(plan.content.is_none(), "{}", plan.message); + } + + #[cfg(unix)] + #[test] + fn merged_settings_keep_their_file_mode() { + use std::os::unix::fs::PermissionsExt; + let dir = tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + fs::write(&settings, r#"{"theme":"dark"}"#).unwrap(); + fs::set_permissions(&settings, fs::Permissions::from_mode(0o644)).unwrap(); + let plan = prepare_settings(&settings).unwrap(); + write_settings_atomic(&settings, &plan.content.unwrap()).unwrap(); + let mode = fs::metadata(&settings).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o644); + } + + #[test] + fn settings_plan_compares_matchers_and_reports_no_write() { + let dir = tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let mut settings = json!({"hooks": build_meta_hooks(), "theme": "dark"}); + settings["hooks"]["PreToolUse"][0]["matcher"] = json!("Read"); + fs::write(&path, serde_json::to_string(&settings).unwrap()).unwrap(); + let plan = prepare_settings(&path).unwrap(); + assert_eq!(plan.message, "Added PreToolUse hooks to"); + let content = plan.content.unwrap(); + let merged: Value = serde_json::from_str(&content).unwrap(); + assert_eq!(merged["theme"], "dark"); + assert_eq!(merged["hooks"]["PreToolUse"].as_array().unwrap().len(), 2); + assert_eq!(merged["hooks"]["PreToolUse"][1]["matcher"], "Bash"); + write_settings_atomic(&path, &content).unwrap(); + let plan = prepare_settings(&path).unwrap(); + assert_eq!(plan.message, "Already has meta's hooks (no write):"); + assert!(plan.content.is_none()); + assert_eq!(fs::read_to_string(path).unwrap(), content); + } + #[test] fn test_install_creates_skills_rules_and_settings() { let dir = tempdir().unwrap(); @@ -1002,12 +1055,12 @@ mod tests { let rule_content = fs::read_to_string(&existing_rule).unwrap(); assert!(rule_content.contains("Meta Workspace Discipline")); - // Settings should be overwritten (not merged) + // --force still merges settings. let settings_content = fs::read_to_string(&existing_settings).unwrap(); let settings: Value = serde_json::from_str(&settings_content).unwrap(); assert!( - settings.get("custom").is_none(), - "should not preserve custom key with --force" + settings.get("custom").is_some(), + "should preserve custom key with --force" ); assert!(settings.get("hooks").is_some(), "should have hooks"); } @@ -1466,7 +1519,8 @@ mod tests { }); let meta_hooks = build_meta_hooks(); - let merged = merge_hooks_into_settings(existing, meta_hooks); + let merged = + merge_hooks_into_settings(existing, meta_hooks, Path::new("settings.json")).unwrap(); // Should preserve existing Stop hook assert!(merged["hooks"]["Stop"].is_array()); @@ -1500,7 +1554,8 @@ mod tests { }); let meta_hooks = build_meta_hooks(); - let merged = merge_hooks_into_settings(existing, meta_hooks); + let merged = + merge_hooks_into_settings(existing, meta_hooks, Path::new("settings.json")).unwrap(); // Should NOT duplicate SessionStart hook let session_hooks = merged["hooks"]["SessionStart"].as_array().unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 7889f5a..23819db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod args; pub mod config; pub use meta_core::display; pub mod context; diff --git a/src/main.rs b/src/main.rs index 8b69175..4de3e53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -177,7 +177,7 @@ struct InitArgs { enum InitCommands { /// Install Claude Code skills, rules, and hooks for this meta repo Claude { - /// Overwrite all existing files including settings + /// Refresh skills and rules, merge meta hooks into settings #[arg(short, long)] force: bool, @@ -287,10 +287,15 @@ fn write_help_with_plugin_commands( commands.push((name, desc, Some(plugin))); } - // Plugin commands (e.g., "git", "project", "rust") + // Plugin namespaces must be claimed commands, not merely plugin names. // These are invoked as `meta ` // Mark them with plugin name and version suffix for (name, version, description) in plugins.list_plugins() { + if !plugins.available_commands().iter().any(|(command, owner)| { + *owner == name && command.split_whitespace().next() == Some(name) + }) { + continue; + } commands.push(( name.to_string(), description.to_string(), @@ -308,8 +313,13 @@ fn write_help_with_plugin_commands( None, )); - // Render commands section + // Render commands section; plugins name and describe their own commands, + // so each value stays on its line writeln!(w, "Commands:")?; + let commands: Vec<_> = commands + .iter() + .map(|(name, desc, plugin)| (escape(name), escape(desc), plugin.as_deref().map(escape))) + .collect(); let max_name_len = commands.iter().map(|c| c.0.len()).max().unwrap_or(10); for (name, desc, plugin_opt) in &commands { let suffix = plugin_opt @@ -456,9 +466,48 @@ fn print_plugin_update_help() { // === Main Entry Point === +/// Exit status for output cut off by a closed stdout, as a shell reports a +/// command SIGPIPE stopped (128 + 13): a failure it hid isn't success. +const CLOSED_STDOUT: u8 = 141; + +/// `println!` panics when stdout is a closed pipe (`meta … | head`). End +/// quietly instead, as a fallible write to stdout does; other panics are +/// reported as usual. +fn exit_quietly_on_closed_stdout() { + let report = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let payload = info.payload(); + let message = payload + .downcast_ref::() + .map(String::as_str) + .or_else(|| payload.downcast_ref::<&str>().copied()) + .unwrap_or(""); + if is_closed_stdout_panic(message) { + std::process::exit(CLOSED_STDOUT.into()); + } + report(info) + })); +} + +/// Whether `message` is std's panic for printing to a closed stdout: a +/// broken pipe, which Windows reports as os error 109 or 232. +fn is_closed_stdout_panic(message: &str) -> bool { + message.starts_with("failed printing to stdout") + && ["Broken pipe", "(os error 109)", "(os error 232)"] + .iter() + .any(|closed| message.contains(closed)) +} + fn main() -> std::process::ExitCode { + exit_quietly_on_closed_stdout(); match run_cli() { Ok(()) => std::process::ExitCode::SUCCESS, + Err(e) + if e.downcast_ref::() + .is_some_and(|e| e.0.kind() == std::io::ErrorKind::BrokenPipe) => + { + std::process::ExitCode::from(CLOSED_STDOUT) + } Err(e) => { // as Rust prints an error returned from main, but escaped: it can // carry paths and names from git and the filesystem @@ -486,7 +535,7 @@ fn run_cli() -> Result<()> { }) .init(); - let mut cli = Cli::parse(); + let mut cli: Cli = meta_cli::args::parse(); log::debug!("cli.json = {}", cli.json); @@ -596,7 +645,7 @@ fn run_cli() -> Result<()> { if is_root_help || (is_bare && !is_promoted) { if let Some(help_text) = subprocess_plugins.get_plugin_help(first) { - println!("{help_text}"); + subprocess_plugins::print_output(&format!("{help_text}\n"))?; return Ok(()); } } @@ -720,6 +769,16 @@ fn handle_command_dispatch( .into_iter() .map(|member| member.path) .collect(); + // Inside a set, a command never falls back to the workspace's + // own checkouts: they aren't the ones the caller is in. A plain + // clone that is merely under a `.worktrees` directory is no set. + if paths.is_empty() && worktree::holds_meta_checkout(&root) { + anyhow::bail!( + "No checkouts of worktree set '{}' found in {}. Run from a set meta made, or pass --primary to run in the workspace.", + escape(&name), + escape_path(&root) + ); + } (!paths.is_empty()).then_some((name, root, paths)) } else { None @@ -733,27 +792,42 @@ fn handle_command_dispatch( ); } - // Try to find .meta config for full feature support - if let Some((config_path, _format)) = find_meta_config(&task_dir, cli.config.as_ref()) { + if let Some((config_path, _format)) = + worktree::set_config(&task_dir, &wt_paths, cli.config.as_ref())? + { let (meta_projects, ignore_list) = parse_meta_config(&config_path)?; - // Build name→info lookup for tag filtering - let project_map: std::collections::HashMap<&str, &ProjectInfo> = - meta_projects.iter().map(|p| (p.name.as_str(), p)).collect(); + // A set lays its repos out as the workspace: a checkout's path + // in the set is its project's path, nested meta repos included. + // Only a filter reads the nested configs; the set's own copies + // win over the workspace's (see set_tree). + let filtered = cli.tag.is_some() || cli.include.is_some() || cli.exclude.is_some(); + let tree = if filtered { + worktree::set_tree(&task_dir, &wt_paths, &meta_projects)? + } else { + Vec::new() + }; + // Compared as directories: a project at a link in the set is + // the checkout where the link leads + let real = |path: &std::path::Path| { + path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) + }; + let project_map: std::collections::HashMap = + config::build_project_map(&tree, &task_dir, "") + .into_iter() + .map(|(place, (_, info))| (real(&task_dir.join(place)), info)) + .collect(); - // Derive aliases from worktree paths and filter by tags + // Filter the checkouts by their projects' tags let wt_directories: Vec = wt_paths .iter() .filter(|path| { if let Some(ref tag_filter) = cli.tag { - let alias = path - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_else(|| ".".to_string()); - if let Some(info) = project_map.get(alias.as_str()) { + if let Some(info) = project_map.get(&real(path)) { matches_tag_filter(&info.tags, tag_filter) } else { - true // Unknown projects pass through + // As in the workspace, only the root runs without a project + real(path) == real(&task_dir) } } else { true @@ -762,15 +836,16 @@ 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)?; + // Selected by project name or by its path in the set + let wt_directories = select_repos(cli, wt_directories, &task_dir, || { + repo_filter::repo_names(&task_dir, &meta_projects, &tree) + })?; if wt_directories.is_empty() { eprintln!( "{}: no projects match tag filter '{}' in worktree '{}'", "warning".yellow().bold(), - cli.tag.as_deref().unwrap_or(""), + escape(cli.tag.as_deref().unwrap_or("")), escape(&task_name) ); return Ok(()); @@ -835,6 +910,13 @@ fn handle_command_dispatch( } // No config found — degraded legacy path with warning + if let Some(tag) = &cli.tag { + anyhow::bail!( + "No meta config found for worktree '{}', so --tag '{}' cannot select its repos", + escape(&task_name), + escape(tag) + ); + } if cli.verbose { eprintln!( "{} No .meta config found for worktree '{}'. Tags, plugins, and dependency features unavailable.", @@ -868,14 +950,14 @@ fn handle_command_dispatch( } } - let absolute_path = match find_meta_config(¤t_dir, cli.config.as_ref()) { + let absolute_path = match find_meta_config(¤t_dir, cli.config.as_ref())? { Some((path, _format)) => path, None => { let config_name = cli .config .as_ref() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_else(|| ".meta / .meta.yaml / .meta.yml".to_string()); + .map(|p| escape_path(p)) + .unwrap_or_else(|| config::META_CONFIG_NAMES.join(" / ")); eprintln!("Error: Could not find meta config file '{config_name}'"); eprintln!("Searched from {} up to root", escape_path(¤t_dir)); std::process::exit(1); @@ -887,7 +969,7 @@ fn handle_command_dispatch( if cli.verbose { println!("{}", "Verbose mode enabled".green()); println!("Resolved config file path: {}", escape_path(&absolute_path)); - println!("Executing command: {command_str}"); + println!("Executing command: {}", escape(&command_str)); } let (meta_projects, ignore_list) = parse_meta_config(&absolute_path)?; @@ -1137,17 +1219,8 @@ fn handle_plugin_command( return Ok(()); } if local { - // For --local, use the registry-based listing for plugin management - let plugins = match PluginInstaller::new_local(verbose) { - Ok(installer) => installer.list_plugins_detailed()?, - Err(_) => { - if !json { - println!("Not in a meta workspace"); - } - return Ok(()); - } - }; - + let installer = PluginInstaller::new_local(verbose)?; + let plugins = installer.list_plugins_detailed()?; if json { println!("{}", serde_json::to_string_pretty(&plugins)?); } else if plugins.is_empty() { @@ -1163,9 +1236,7 @@ fn handle_plugin_command( .strip_prefix(PLUGIN_PREFIX) .unwrap_or(&plugin.name); let version = plugin.version.as_deref().unwrap_or("-"); - // For local plugins, show the path in the local plugins dir - let cwd = std::env::current_dir()?; - let path = cwd.join(".meta/plugins").join(&plugin.name); + let path = installer.plugins_dir().join(&plugin.name); println!( "{:<12} {:<12} {}", escape(name), @@ -1222,7 +1293,7 @@ fn handle_plugin_command( installer.uninstall(&name)?; if !json { - println!("Successfully uninstalled {name} from {location}"); + println!("Successfully uninstalled {} from {location}", escape(&name)); } } PluginCommands::Update { name, local, check } => { @@ -1416,8 +1487,9 @@ fn unrecognized_command_error( eprintln!( "{}: unrecognized command '{}'", "error".red().bold(), - first_cmd + escape(first_cmd) ); + let command_str = escape(command_str); eprintln!(); eprintln!("To run '{command_str}' across all repos:"); eprintln!(" meta exec -- {command_str}"); @@ -1441,7 +1513,7 @@ fn check_and_warn_orphan() { } // Find the nearest .meta config - let Some((config_path, _)) = find_meta_config(¤t_dir, None) else { + let Ok(Some((config_path, _))) = find_meta_config(¤t_dir, None) else { return; }; @@ -1451,6 +1523,10 @@ fn check_and_warn_orphan() { }; // Check if this meta repo is orphaned (not tracked by parent) + // A set's checkout is meta's own, not a repo its parent forgot to list + if config::set_source(&meta_dir).is_some() { + return; + } if let Some(warning) = config::check_orphan_status(&meta_dir) { eprintln!( "{}: This meta repo is not tracked by its parent.", @@ -1461,14 +1537,9 @@ fn check_and_warn_orphan() { eprintln!(); // Show format-appropriate syntax - let config_file = match warning.parent_format { - ConfigFormat::Json => ".meta", - ConfigFormat::Yaml => ".meta.yaml", - }; eprintln!( - " To include it, add to {}/{}:", - escape_path(&warning.parent), - config_file + " To include it, add to {}:", + escape_path(&warning.parent_config) ); match warning.parent_format { ConfigFormat::Json => { @@ -1524,6 +1595,21 @@ fn flatten_filtered_inner( #[cfg(test)] mod tests { use super::*; + + #[test] + fn closed_stdout_panics_are_recognised_on_every_platform() { + for message in [ + "failed printing to stdout: Broken pipe (os error 32)", + "failed printing to stdout: The pipe has been ended. (os error 109)", + "failed printing to stdout: The pipe is being closed. (os error 232)", + ] { + assert!(is_closed_stdout_panic(message), "{message}"); + } + assert!(!is_closed_stdout_panic( + "failed printing to stdout: No space left on device (os error 28)" + )); + assert!(!is_closed_stdout_panic("index out of bounds: Broken pipe")); + } use std::io::Write; use tempfile::NamedTempFile; @@ -1658,23 +1744,21 @@ ignore: let meta_path = dir.path().join(".meta"); std::fs::write(&meta_path, r#"{"projects": {}}"#).unwrap(); - let result = find_meta_config(dir.path(), None); + let result = find_meta_config(dir.path(), None).unwrap(); assert!(result.is_some()); let (path, _format) = result.unwrap(); assert_eq!(path, meta_path); } #[test] - fn test_find_meta_config_yaml_priority() { + fn test_find_meta_config_rejects_ambiguity() { let dir = tempfile::tempdir().unwrap(); - // Create .meta first (JSON), then .meta.yaml std::fs::write(dir.path().join(".meta"), r#"{"projects": {}}"#).unwrap(); - - // .meta should be found first (it's checked before .meta.yaml) - let result = find_meta_config(dir.path(), None); - assert!(result.is_some()); - let (path, _format) = result.unwrap(); - assert!(path.ends_with(".meta")); + std::fs::write(dir.path().join(".meta.yaml"), "projects: {}").unwrap(); + let err = find_meta_config(dir.path(), None).unwrap_err().to_string(); + assert!(err.contains("Multiple meta config files")); + assert!(err.contains(".meta.yaml")); + assert!(err.contains(&escape_path(&dir.path().join(".meta")))); } #[test] @@ -1917,7 +2001,7 @@ projects: std::fs::write(&meta_path, r#"{"projects": {}}"#).unwrap(); // Search from nested directory should find root .meta - let result = find_meta_config(&nested, None); + let result = find_meta_config(&nested, None).unwrap(); assert!(result.is_some()); let (found_path, _) = result.unwrap(); assert_eq!(found_path, meta_path); @@ -1931,7 +2015,7 @@ projects: let yaml_path = dir.path().join(".meta.yaml"); std::fs::write(&yaml_path, "projects:\n p1: git@test.git\n").unwrap(); - let result = find_meta_config(dir.path(), None); + let result = find_meta_config(dir.path(), None).unwrap(); assert!(result.is_some()); // Clean up and test .yml extension @@ -1939,7 +2023,7 @@ projects: let yml_path = dir.path().join(".meta.yml"); std::fs::write(&yml_path, "projects:\n p2: git@test.git\n").unwrap(); - let result = find_meta_config(dir.path(), None); + let result = find_meta_config(dir.path(), None).unwrap(); assert!(result.is_some()); } } diff --git a/src/query.rs b/src/query.rs index beba322..9b3d3de 100644 --- a/src/query.rs +++ b/src/query.rs @@ -15,6 +15,7 @@ //! - `branch:main AND modified_in:7d` use anyhow::{Context, Result}; +use meta_core::display::escape; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::Path; @@ -86,7 +87,10 @@ impl Query { fn parse_condition(s: &str) -> Result { let parts: Vec<&str> = s.splitn(2, ':').collect(); if parts.len() != 2 { - anyhow::bail!("Invalid condition format: '{s}'. Expected 'field:value'"); + anyhow::bail!( + "Invalid condition format: '{}'. Expected 'field:value'", + escape(s) + ); } let field = parts[0].trim().to_lowercase(); @@ -95,7 +99,7 @@ impl Query { match field.as_str() { "dirty" => { let is_dirty = value.parse::() - .with_context(|| format!("Invalid boolean value for dirty: '{value}'"))?; + .with_context(|| format!("Invalid boolean value for dirty: '{}'", escape(value)))?; Ok(QueryCondition::Dirty(is_dirty)) } "branch" => Ok(QueryCondition::Branch(value.to_string())), @@ -107,20 +111,20 @@ impl Query { "language" | "lang" => Ok(QueryCondition::Language(value.to_lowercase())), "has_unpushed" | "unpushed" => { let has_unpushed = value.parse::() - .with_context(|| format!("Invalid boolean value: '{value}'"))?; + .with_context(|| format!("Invalid boolean value: '{}'", escape(value)))?; Ok(QueryCondition::HasUnpushed(has_unpushed)) } "ahead" | "ahead_of_remote" => { let ahead = value.parse::() - .with_context(|| format!("Invalid boolean value: '{value}'"))?; + .with_context(|| format!("Invalid boolean value: '{}'", escape(value)))?; Ok(QueryCondition::AheadOfRemote(ahead)) } "behind" | "behind_remote" => { let behind = value.parse::() - .with_context(|| format!("Invalid boolean value: '{value}'"))?; + .with_context(|| format!("Invalid boolean value: '{}'", escape(value)))?; Ok(QueryCondition::BehindRemote(behind)) } - _ => anyhow::bail!("Unknown query field: '{field}'. Valid fields: dirty, branch, tag, modified_in, language, has_unpushed, ahead, behind"), + _ => anyhow::bail!("Unknown query field: '{}'. Valid fields: dirty, branch, tag, modified_in, language, has_unpushed, ahead, behind", escape(&field)), } } } @@ -132,25 +136,28 @@ fn parse_duration(s: &str) -> Result { if s.ends_with('h') { let hours: u64 = s[..s.len() - 1] .parse() - .with_context(|| format!("Invalid hours value: '{s}'"))?; + .with_context(|| format!("Invalid hours value: '{}'", escape(&s)))?; Ok(Duration::from_secs(hours * 3600)) } else if s.ends_with('d') { let days: u64 = s[..s.len() - 1] .parse() - .with_context(|| format!("Invalid days value: '{s}'"))?; + .with_context(|| format!("Invalid days value: '{}'", escape(&s)))?; Ok(Duration::from_secs(days * 86400)) } else if s.ends_with('m') { let minutes: u64 = s[..s.len() - 1] .parse() - .with_context(|| format!("Invalid minutes value: '{s}'"))?; + .with_context(|| format!("Invalid minutes value: '{}'", escape(&s)))?; Ok(Duration::from_secs(minutes * 60)) } else if s.ends_with('w') { let weeks: u64 = s[..s.len() - 1] .parse() - .with_context(|| format!("Invalid weeks value: '{s}'"))?; + .with_context(|| format!("Invalid weeks value: '{}'", escape(&s)))?; Ok(Duration::from_secs(weeks * 604800)) } else { - anyhow::bail!("Invalid duration format: '{s}'. Use format like '24h', '7d', '30m', '2w'") + anyhow::bail!( + "Invalid duration format: '{}'. Use format like '24h', '7d', '30m', '2w'", + escape(&s) + ) } } diff --git a/src/registry.rs b/src/registry.rs index d00b749..b416eae 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -6,7 +6,7 @@ use anyhow::{Context, Result}; use log::{debug, info}; -use meta_core::display::escape_path; +use meta_core::display::{escape, escape_path}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Read; @@ -327,7 +327,7 @@ impl RegistryClient { } } - anyhow::bail!("Plugin '{name}' not found in any registry") + anyhow::bail!("Plugin '{}' not found in any registry", escape(name)) } /// Fetch plugin metadata (complex registry format) @@ -347,7 +347,7 @@ impl RegistryClient { } } - anyhow::bail!("Plugin '{name}' not found in any registry") + anyhow::bail!("Plugin '{}' not found in any registry", escape(name)) } /// Search for plugins matching a query @@ -371,7 +371,7 @@ impl RegistryClient { fn fetch_json(&self, url: &str) -> Result { let response = ureq::get(url) .call() - .with_context(|| format!("Failed to fetch {url}"))?; + .with_context(|| format!("Failed to fetch {}", escape(url)))?; let body = response .into_string() @@ -391,7 +391,7 @@ impl RegistryClient { let parts: Vec<&str> = repo_path.split('/').collect(); if parts.len() != 2 { - anyhow::bail!("Invalid GitHub shorthand: {}", shorthand); + anyhow::bail!("Invalid GitHub shorthand: {}", escape(shorthand)); } let (user, repo) = (parts[0], parts[1]); @@ -405,7 +405,13 @@ impl RegistryClient { let response = ureq::get(&api_url) .set("User-Agent", "meta-cli") .call() - .with_context(|| format!("Failed to fetch latest release for {}/{}", user, repo))?; + .with_context(|| { + format!( + "Failed to fetch latest release for {}/{}", + escape(user), + escape(repo) + ) + })?; let body = response .into_string() @@ -499,6 +505,29 @@ impl ArchiveFormat { } } +/// No release of `shorthand` was found at any of `tried` URLs. Each value +/// comes from the user or the network, so each stays on its line. +fn release_not_found( + shorthand: &GitHubShorthand, + tried: usize, + last_error: Option, +) -> anyhow::Error { + anyhow::anyhow!( + "Could not find release for {}/{}{}\nTried {} URL(s). Last error: {}", + escape(&shorthand.user), + escape(&shorthand.repo), + shorthand + .version + .as_ref() + .map(|v| format!("@{}", escape(v))) + .unwrap_or_default(), + tried, + last_error + .map(|e| escape(&format!("{e:#}")).into_owned()) + .unwrap_or_default() + ) +} + /// Parsed GitHub shorthand: user/repo[@version] #[derive(Debug, Clone, PartialEq)] pub struct GitHubShorthand { @@ -625,46 +654,16 @@ impl PluginInstaller { &self.scope } - /// Find the workspace root directory by walking up from the current directory - /// - /// Searches for: - /// 1. `.meta/` directory (new format, preferred) - /// 2. `.meta.yaml`, `.meta.yml`, or `.meta` config file (legacy formats) - /// - /// Walks up the directory tree until one is found or filesystem root is reached. - /// - /// # Errors - /// Find the workspace root starting from the given directory. - /// Walks up the directory tree looking for .meta/ directory or legacy config files. + /// Find the nearest directory holding a config file (not a bare `.meta/`). fn find_workspace_root_from(start_dir: &Path) -> Result { - use crate::config::find_meta_config_in; - - // Walk up the directory tree once, checking both .meta/ and config files - let mut current = start_dir; - loop { - // Check for .meta/ directory (new format) - let meta_dir = current.join(".meta"); - if meta_dir.is_dir() { - return Ok(current.to_path_buf()); - } - - // Check for legacy config files in current directory - if let Some((_config_path, _)) = find_meta_config_in(current)? { - return Ok(current.to_path_buf()); - } - - // Move to parent directory - match current.parent() { - Some(parent) => current = parent, - None => break, - } - } + meta_core::config::nearest_meta_dir(start_dir)?.ok_or_else(|| anyhow::anyhow!( + "Not in a meta workspace.\nExpected to find a config file: {}.\nCreate one here (e.g. .meta.yaml), or cd into a workspace.", + meta_core::config::META_CONFIG_NAMES.join(", ") + )) + } - anyhow::bail!( - "Not in a meta workspace.\n\ - Expected to find .meta/ directory or .meta.yaml config file.\n\ - Run 'meta init' to create a new workspace, or cd to an existing workspace." - ) + pub fn plugins_dir(&self) -> &Path { + &self.plugins_dir } /// Get the default plugins directory (~/.meta/plugins/) @@ -675,7 +674,28 @@ impl PluginInstaller { /// Ensure the plugins directory exists fn ensure_plugins_dir(&self) -> Result<()> { // Made 0700, whatever the umask - meta_core::data_dir::create_private_dir(&self.plugins_dir) + meta_core::data_dir::create_private_dir(&self.plugins_dir)?; + if self.scope == InstallScope::Local { + let ignore_path = self.plugins_dir.join(".gitignore"); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&ignore_path) + { + Ok(mut file) => { + use std::io::Write; + file.write_all(b"*\n").with_context(|| { + format!("Failed to write {}", escape_path(&ignore_path)) + })?; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => { + return Err(e) + .with_context(|| format!("Failed to create {}", escape_path(&ignore_path))) + } + } + } + Ok(()) } /// Get the manifest file path @@ -721,7 +741,7 @@ impl PluginInstaller { fn download(&self, url: &str) -> Result> { let response = ureq::get(url) .call() - .with_context(|| format!("Failed to download {url}"))?; + .with_context(|| format!("Failed to download {}", escape(url)))?; let mut bytes = Vec::new(); response @@ -737,14 +757,16 @@ impl PluginInstaller { let platform = RegistryClient::current_platform(); // Get the download URL for the current platform and latest version - let releases = metadata - .releases - .get(&metadata.version) - .with_context(|| format!("No releases found for version {}", metadata.version))?; + let releases = metadata.releases.get(&metadata.version).with_context(|| { + format!( + "No releases found for version {}", + escape(&metadata.version) + ) + })?; let download_url = self .get_platform_url(releases, &platform) - .with_context(|| format!("No release available for platform {platform}"))?; + .with_context(|| format!("No release available for platform {}", escape(&platform)))?; info!( "Downloading {} v{} for {}", @@ -855,18 +877,7 @@ impl PluginInstaller { } // If we get here, none of the URLs worked - anyhow::bail!( - "Could not find release for {}/{}{}\nTried {} URL(s). Last error: {}", - shorthand.user, - shorthand.repo, - shorthand - .version - .as_ref() - .map(|v| format!("@{v}")) - .unwrap_or_default(), - urls.len(), - last_error.unwrap() - ) + Err(release_not_found(shorthand, urls.len(), last_error)) } /// Construct possible GitHub release URLs for a shorthand @@ -980,7 +991,7 @@ impl PluginInstaller { self.validate_plugin(&plugin_path).with_context(|| { // Remove invalid plugin on failure let _ = std::fs::remove_file(&plugin_path); - format!("Plugin validation failed for {plugin_name}") + format!("Plugin validation failed for {}", escape(plugin_name)) })?; } @@ -992,7 +1003,7 @@ impl PluginInstaller { // Try to detect format from URL first, then fall back to magic bytes let format = ArchiveFormat::from_url(url) .or_else(|| ArchiveFormat::from_bytes(bytes)) - .with_context(|| format!("Unsupported archive format: {url}"))?; + .with_context(|| format!("Unsupported archive format: {}", escape(url)))?; match format { ArchiveFormat::TarGz => self.extract_tar_gz(bytes), @@ -1042,7 +1053,8 @@ impl PluginInstaller { // Require one filename component on both Unix and Windows. anyhow::ensure!( !file_name.contains(['/', '\\']), - "ZIP plugin entry must be a top-level filename: {file_name}" + "ZIP plugin entry must be a top-level filename: {}", + escape(&file_name) ); entries.push((i, file_name)); } @@ -1113,9 +1125,19 @@ impl PluginInstaller { plugins.push(PluginInfo { name: name.to_string(), - version: manifest_entry.and_then(|e| e.version.clone()), + version: match crate::subprocess_plugins::probe_plugin_info(&path) { + Ok(info) => info.map(|info| info.version), + Err(e) => { + eprintln!("Warning: {e}"); + None + } + }, source: manifest_entry.map(|e| e.source.clone()), - location: PluginLocation::Installed, + location: if self.scope == InstallScope::Local { + PluginLocation::ProjectLocal + } else { + PluginLocation::Installed + }, installed: manifest_entry.map(|e| e.installed.clone()), }); } @@ -1144,7 +1166,7 @@ impl PluginInstaller { info!("Uninstalled {}", plugin_name); Ok(()) } else { - anyhow::bail!("Plugin {plugin_name} is not installed") + anyhow::bail!("Plugin {} is not installed", escape(&plugin_name)) } } @@ -1156,9 +1178,9 @@ impl PluginInstaller { let manifest = self.load_manifest()?; let plugin_name = ensure_plugin_prefix(plugin_name); - let entry = manifest - .get_plugin(&plugin_name) - .ok_or_else(|| anyhow::anyhow!("Plugin {} not found in manifest", plugin_name))?; + let entry = manifest.get_plugin(&plugin_name).ok_or_else(|| { + anyhow::anyhow!("Plugin {} not found in manifest", escape(&plugin_name)) + })?; // Check if source is a GitHub shorthand if !entry.source.contains('/') { @@ -1199,7 +1221,7 @@ impl PluginInstaller { let entry = manifest .get_plugin(&plugin_name) - .ok_or_else(|| anyhow::anyhow!("Plugin {} not installed", plugin_name))?; + .ok_or_else(|| anyhow::anyhow!("Plugin {} not installed", escape(&plugin_name)))?; // Parse source as GitHub shorthand let shorthand = GitHubShorthand::parse(&entry.source).ok_or_else(|| { @@ -1226,6 +1248,23 @@ impl PluginInstaller { mod tests { use super::*; + #[test] + fn a_missing_releases_error_keeps_each_value_on_its_line() { + let shorthand = GitHubShorthand { + user: "o\nFORGED".to_string(), + repo: "r\u{1b}[2J".to_string(), + version: Some("v1\nFORGED".to_string()), + }; + let message = + release_not_found(&shorthand, 2, Some(anyhow::anyhow!("e\nFORGED"))).to_string(); + assert_eq!(message.lines().count(), 2, "{message}"); + assert!(!message.contains('\u{1b}'), "{message}"); + assert!( + message.starts_with("Could not find release for o\\nFORGED/"), + "{message}" + ); + } + #[test] fn test_registry_config_default() { let config = RegistryConfig::default(); @@ -2019,8 +2058,9 @@ mod tests { assert!(plugins.is_empty()); } + #[cfg(unix)] #[test] - fn test_list_plugins_detailed_with_manifest() { + fn test_list_plugins_detailed_uses_binary_version_and_manifest_provenance() { let dir = tempfile::tempdir().unwrap(); let installer = PluginInstaller { plugins_dir: dir.path().to_path_buf(), @@ -2030,7 +2070,13 @@ mod tests { // Create plugin file std::fs::create_dir_all(dir.path()).unwrap(); - std::fs::write(dir.path().join("meta-test"), b"fake plugin").unwrap(); + let plugin_path = dir.path().join("meta-test"); + std::fs::write( + &plugin_path, + b"#!/bin/sh\necho '{\"name\":\"test\",\"version\":\"2.0.0\",\"commands\":[]}'\n", + ) + .unwrap(); + make_executable(&plugin_path).unwrap(); // Create manifest let mut manifest = PluginManifest::default(); @@ -2049,14 +2095,14 @@ mod tests { let plugins = installer.list_plugins_detailed().unwrap(); assert_eq!(plugins.len(), 1); assert_eq!(plugins[0].name, "meta-test"); - assert_eq!(plugins[0].version.as_deref(), Some("v1.0.0")); + assert_eq!(plugins[0].version.as_deref(), Some("2.0.0")); assert_eq!(plugins[0].source.as_deref(), Some("test-user/meta-test")); } // === M4: Project-local plugin installation tests === #[test] - fn test_find_workspace_root_with_meta_directory() { + fn test_find_workspace_root_rejects_bare_meta_directory() { let temp = tempfile::tempdir().unwrap(); let meta_dir = temp.path().join(".meta"); std::fs::create_dir(&meta_dir).unwrap(); @@ -2065,19 +2111,15 @@ mod tests { let subdir = temp.path().join("sub").join("dir"); std::fs::create_dir_all(&subdir).unwrap(); - // Test from subdirectory - should walk up and find .meta/ let result = PluginInstaller::find_workspace_root_from(&subdir); - - assert!(result.is_ok()); - // Canonicalize paths for comparison (handles /var vs /private/var on macOS) - assert_eq!( - result.unwrap().canonicalize().unwrap(), - temp.path().canonicalize().unwrap() - ); + assert!(result + .unwrap_err() + .to_string() + .contains("Not in a meta workspace")); } #[test] - fn test_find_workspace_root_with_legacy_yaml() { + fn test_find_workspace_root_with_yaml() { let temp = tempfile::tempdir().unwrap(); std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); @@ -2092,7 +2134,7 @@ mod tests { } #[test] - fn test_find_workspace_root_with_legacy_json() { + fn test_find_workspace_root_with_legacy_meta_file() { let temp = tempfile::tempdir().unwrap(); std::fs::write(temp.path().join(".meta"), r#"{"projects":{}}"#).unwrap(); @@ -2110,19 +2152,20 @@ mod tests { fn test_find_workspace_root_fails_outside_workspace() { let temp = tempfile::tempdir().unwrap(); - let result = PluginInstaller::find_workspace_root_from(temp.path()); + let result = + PluginInstaller::find_workspace_root_from(temp.path().ancestors().last().unwrap()); assert!(result.is_err()); let err_msg = result.unwrap_err().to_string(); assert!(err_msg.contains("Not in a meta workspace")); - assert!(err_msg.contains("meta init")); + assert!(err_msg.contains("Create one here")); } #[test] - fn test_find_workspace_root_prefers_meta_dir_over_legacy() { + fn test_find_workspace_root_with_config_and_meta_directory() { let temp = tempfile::tempdir().unwrap(); - // Create both .meta/ directory and legacy .meta.yaml + // A config file establishes a workspace alongside its .meta/ directory. let meta_dir = temp.path().join(".meta"); std::fs::create_dir(&meta_dir).unwrap(); std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); @@ -2144,6 +2187,8 @@ mod tests { let meta_dir = temp.path().join(".meta"); std::fs::create_dir(&meta_dir).unwrap(); + std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); + // Create plugins dir so we can canonicalize it let plugins_dir = temp.path().join(LOCAL_PLUGINS_DIR); std::fs::create_dir_all(&plugins_dir).unwrap(); @@ -2164,7 +2209,8 @@ mod tests { fn test_new_local_fails_outside_workspace() { let temp = tempfile::tempdir().unwrap(); - let result = PluginInstaller::new_local_from(temp.path(), false); + let result = + PluginInstaller::new_local_from(temp.path().ancestors().last().unwrap(), false); assert!(result.is_err()); assert!(result @@ -2173,6 +2219,19 @@ mod tests { .contains("Not in a meta workspace")); } + #[test] + fn local_plugins_gitignore_is_created_and_existing_file_is_kept() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join(".meta.yaml"), "projects: {}").unwrap(); + let installer = PluginInstaller::new_local_from(temp.path(), false).unwrap(); + installer.ensure_plugins_dir().unwrap(); + let path = installer.plugins_dir.join(".gitignore"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "*\n"); + std::fs::write(&path, "custom\n").unwrap(); + installer.ensure_plugins_dir().unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "custom\n"); + } + #[test] fn test_constants_defined() { // Verify constants are accessible and have expected values diff --git a/src/repo_filter.rs b/src/repo_filter.rs index 760efc2..bb54a22 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -55,29 +55,34 @@ pub fn select( id: std::fs::canonicalize(dir).unwrap_or_else(|_| PathBuf::from(dir)), }) .collect(); + // A path is the repo's, or leads there through a link + let names_dir = |path: &str, repo: &Repo| { + *path == repo.path || std::fs::canonicalize(root.join(path)).is_ok_and(|id| id == repo.id) + }; let named = |flag: &str, value: &str| -> Result> { let wanted = path_value(value); let by_path = distinct( repos .iter() - .filter(|r| wanted.as_deref() == Some(r.path.as_str())), + .filter(|r| wanted.as_deref().is_some_and(|path| names_dir(path, r))), ); let by_name = if value.starts_with("./") { vec![] } else { - distinct( - repos + distinct(repos.iter().filter(|r| { + names .iter() - .filter(|r| names.iter().any(|(name, p)| name == value && *p == r.path)), - ) + .any(|(name, p)| name == value && names_dir(p, r)) + })) }; let listed = |repos: &[&Repo]| -> String { repos .iter() - .map(|r| r.path.as_str()) + .map(|r| meta_core::display::escape(&r.path)) .collect::>() .join(", ") }; + let value = meta_core::display::escape(value); if by_name.len() > 1 { bail!( "{flag} '{value}' is the .meta name of the repos at {}; name one by its path, \ @@ -100,7 +105,7 @@ pub fn select( 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 \ + `meta project list` shows it; in a worktree set, the same, from the set's root. --tag and \ --recursive change which repos the command runs in." ); } diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 3472536..d4b703e 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -6,8 +6,10 @@ use anyhow::{Context, Result}; use meta_core::display::{escape, escape_path}; use std::collections::HashMap; +use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; #[allow(unused_imports)] pub use meta_plugin_protocol::{ @@ -15,6 +17,88 @@ pub use meta_plugin_protocol::{ PluginRequest, PluginRequestOptions, }; +/// Query metadata with one deadline for both process exit and stdout EOF. +pub(crate) fn probe_plugin_info(path: &Path) -> Result> { + let deadline = Instant::now() + Duration::from_secs(5); + let mut command = Command::new(path); + command + .arg("--meta-plugin-info") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.process_group(0); + } + let mut child = match command.spawn() { + Ok(child) => child, + Err(_) => return Ok(None), + }; + let Some(stdout) = child.stdout.take() else { + let _ = child.kill(); + let _ = child.wait(); + return Ok(None); + }; + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut bytes = Vec::new(); + // Plugin info is small; a plugin flooding stdout can't fill memory + let _ = sender.send(stdout.take(1 << 20).read_to_end(&mut bytes).map(|_| bytes)); + }); + // stdout ends once the plugin, and anything it started that holds it, is done + let remaining = deadline.saturating_duration_since(Instant::now()); + if let Ok(output) = receiver.recv_timeout(remaining) { + loop { + match child.try_wait() { + Ok(Some(status)) => { + return Ok(output + .ok() + .filter(|_| status.success()) + .and_then(|bytes| serde_json::from_slice(&bytes).ok())) + } + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(1)) + } + Ok(None) => break, + Err(e) => { + return Err(e).with_context(|| { + format!("Cannot wait for plugin {}; skipping", escape_path(path)) + }) + } + } + } + } + // A wrapper may already have exited while its descendants hold stdout open. + // Kill its process group even when the wrapper itself has exited. + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: the child was started as leader of its own process group. + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } + // Elsewhere only the plugin itself is killed: a process it started that + // still holds stdout outlives it, but meta doesn't wait for that reader + let _ = child.kill(); + let _ = child.wait(); + anyhow::bail!( + "Plugin {} did not answer --meta-plugin-info within 5 seconds; skipping", + escape_path(path) + ) +} + +/// Print a plugin's output. A closed stdout (`meta ... | head`) ends meta +/// quietly, as it does for command output. +pub(crate) fn print_output(text: &str) -> Result<()> { + use std::io::Write; + std::io::stdout() + .lock() + .write_all(text.as_bytes()) + .map_err(loop_lib::StdoutError)?; + Ok(()) +} + /// A discovered subprocess plugin #[derive(Debug, Clone)] pub struct SubprocessPlugin { @@ -45,24 +129,32 @@ impl SubprocessPluginManager { /// Discover and load all subprocess plugins /// /// Discovery order (first match wins): - /// 1. `.meta/plugins/` directories walking up from cwd (project-local) - /// 2. `~/.meta/plugins/` (global installed) + /// 1. `.meta/plugins/` of each of the workspace's meta directories, from + /// the nearest one up (`meta_core::config::workspace_meta_dirs`) + /// 2. `meta_core::meta_dir()/plugins/` (global installed) /// 3. PATH (bundled/system plugins) pub fn discover_plugins(&mut self, verbose: bool) -> Result<()> { self.verbose = verbose; let mut visited = std::collections::HashSet::new(); - // Search in .meta/plugins/ directories walking up from cwd (project-local) - let mut current_dir = std::env::current_dir()?; - loop { - let plugin_dir = current_dir.join(".meta").join("plugins"); - if plugin_dir.is_dir() && visited.insert(resolved(&plugin_dir)) { - self.scan_directory(&plugin_dir)?; - } - if let Some(parent) = current_dir.parent() { - current_dir = parent.to_path_buf(); - } else { - break; + // Project plugins: those of each meta directory from the nearest one + // up to its workspace's root, nearest first, independently of --config + let cwd = std::env::current_dir()?; + // A config meta can't use leaves no project plugins; the command + // itself reports it, and `--help` still prints + let nearest = meta_core::config::nearest_meta_dir(&cwd).unwrap_or_else(|e| { + eprintln!( + "Warning: {} Skipping project plugins.", + escape(&format!("{e:#}")) + ); + None + }); + if let Some(nearest) = nearest { + for dir in meta_core::config::workspace_meta_dirs(&nearest) { + let plugin_dir = dir.join(".meta/plugins"); + if visited.insert(resolved(&plugin_dir)) { + self.scan_directory(&plugin_dir)?; + } } } @@ -70,7 +162,7 @@ impl SubprocessPluginManager { // no global plugins. if let Ok(meta_dir) = meta_core::meta_dir() { let global_plugins = meta_dir.join("plugins"); - if global_plugins.is_dir() && visited.insert(resolved(&global_plugins)) { + if visited.insert(resolved(&global_plugins)) { self.scan_directory(&global_plugins)?; } } @@ -87,14 +179,44 @@ impl SubprocessPluginManager { Ok(()) } - /// Scan a .meta-plugins directory for plugin executables + /// Scan a `.meta/plugins` directory for plugin executables fn scan_directory(&mut self, dir: &Path) -> Result<()> { if self.verbose { println!("Scanning for subprocess plugins in: {}", escape_path(dir)); } - for entry in std::fs::read_dir(dir)? { - let entry = entry?; + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + // A legacy `.meta` config file in place of the `.meta/` folder means no plugins + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) => + { + return Ok(()) + } + Err(e) => { + eprintln!( + "Warning: Cannot read plugins directory {}: {}; skipping", + escape_path(dir), + escape(&e.to_string()) + ); + return Ok(()); + } + }; + for entry in entries { + let entry = match entry { + Ok(entry) => entry, + Err(e) => { + eprintln!( + "Warning: Cannot read plugins directory {}: {}; skipping entry", + escape_path(dir), + escape(&e.to_string()) + ); + continue; + } + }; let path = entry.path(); // Look for executables named meta-* @@ -133,46 +255,29 @@ impl SubprocessPluginManager { return Ok(()); } - // Query plugin info - let output = Command::new(path) - .arg("--meta-plugin-info") - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .output(); - - match output { - Ok(output) if output.status.success() => { - // Try to parse as plugin info - silently skip if invalid JSON - // (e.g., meta-mcp is an MCP server, not a meta plugin) - let info: PluginInfo = match serde_json::from_slice(&output.stdout) { - Ok(info) => info, - Err(_) => return Ok(()), // Not a valid plugin, skip silently - }; - - if self.verbose { - println!( - " Found plugin: {} v{} ({})", - escape(&info.name), - escape(&info.version), - escape_path(path) - ); - } - - // Don't override if already loaded (first one wins) - if !self.plugins.contains_key(&info.name) { - self.plugins.insert( - info.name.clone(), - SubprocessPlugin { - path: path.to_path_buf(), - info, - }, - ); - } - } - _ => { - // Not a valid plugin, ignore silently + let info = match probe_plugin_info(path) { + Ok(Some(info)) => info, + Ok(None) => return Ok(()), + Err(e) => { + eprintln!("Warning: {e}"); + return Ok(()); } + }; + if self.verbose { + println!( + " Found plugin: {} v{} ({})", + escape(&info.name), + escape(&info.version), + escape_path(path) + ); } + // Don't override if already loaded (first one wins). + self.plugins + .entry(info.name.clone()) + .or_insert_with(|| SubprocessPlugin { + path: path.to_path_buf(), + info, + }); Ok(()) } @@ -253,7 +358,8 @@ impl SubprocessPluginManager { if self.verbose { println!( "Executing plugin {} for command '{}'", - plugin.info.name, request.command + escape(&plugin.info.name), + escape(&request.command) ); } @@ -265,10 +371,19 @@ impl SubprocessPluginManager { .spawn() .with_context(|| format!("Failed to execute plugin {}", escape_path(&plugin.path)))?; - // Send request to plugin's stdin + // Send request to plugin's stdin. A plugin may answer without + // reading it; then its output and exit status decide, not the pipe. if let Some(mut stdin) = child.stdin.take() { use std::io::Write; - stdin.write_all(request_json.as_bytes())?; + match stdin.write_all(request_json.as_bytes()) { + Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {} + result => result.with_context(|| { + format!( + "Cannot send the request to plugin {}", + escape_path(&plugin.path) + ) + })?, + } } let output = child.wait_with_output()?; @@ -277,7 +392,7 @@ impl SubprocessPluginManager { // Plugin already printed its error to stderr. What it printed // before failing (say the worktrees it removed before a store // error) is shown too; then its exit code is propagated. - print!("{}", String::from_utf8_lossy(&output.stdout)); + let _ = std::io::Write::write_all(&mut std::io::stdout(), &output.stdout); std::process::exit(output.status.code().unwrap_or(1)); } @@ -291,7 +406,7 @@ impl SubprocessPluginManager { // If stdout doesn't look like JSON, print it (legacy plugin output) if !stdout_str.trim().starts_with('{') { - print!("{stdout_str}"); + print_output(&stdout_str)?; return Ok(true); } @@ -307,11 +422,11 @@ impl SubprocessPluginManager { 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() + escape_path(&plugin.path) ), Err(_) => { // Not a plan - print output as-is - print!("{stdout_str}"); + print_output(&stdout_str)?; Ok(true) } } @@ -580,9 +695,10 @@ impl SubprocessPluginManager { fn generate_fallback_help(&self, plugin: &SubprocessPlugin) -> String { let info = &plugin.info; let mut help = String::new(); - let name = &info.name; - let version = &info.version; - let description = info.description.as_deref().unwrap_or("Meta CLI plugin"); + // Every value comes from the plugin: each stays on its line + let name = escape(&info.name); + let version = escape(&info.version); + let description = escape(info.description.as_deref().unwrap_or("Meta CLI plugin")); // Header help.push_str(&format!("meta-{name} v{version} - {description}\n\n")); @@ -590,14 +706,15 @@ impl SubprocessPluginManager { // If plugin has structured help, use it if let Some(ref plugin_help) = info.help { help.push_str("USAGE:\n"); - let usage = &plugin_help.usage; + let usage = escape(&plugin_help.usage); help.push_str(&format!(" {usage}\n\n")); // Use command_sections if present, otherwise fall back to flat commands if !plugin_help.command_sections.is_empty() { for (section_title, commands) in &plugin_help.command_sections { - help.push_str(&format!("{section_title}:\n")); + help.push_str(&format!("{}:\n", escape(section_title))); for (cmd, desc) in commands { + let (cmd, desc) = (escape(cmd), escape(desc)); help.push_str(&format!(" {cmd:<16} {desc}\n")); } help.push('\n'); @@ -607,6 +724,7 @@ impl SubprocessPluginManager { let mut cmds: Vec<_> = plugin_help.commands.iter().collect(); cmds.sort_by(|a, b| a.0.cmp(b.0)); for (cmd, desc) in cmds { + let (cmd, desc) = (escape(cmd), escape(desc)); help.push_str(&format!(" {cmd:<16} {desc}\n")); } help.push('\n'); @@ -615,13 +733,13 @@ impl SubprocessPluginManager { if !plugin_help.examples.is_empty() { help.push_str("EXAMPLES:\n"); for example in &plugin_help.examples { - help.push_str(&format!(" {example}\n")); + help.push_str(&format!(" {}\n", escape(example))); } help.push('\n'); } if let Some(ref note) = plugin_help.note { - help.push_str(&format!("NOTE:\n {note}\n")); + help.push_str(&format!("NOTE:\n {}\n", escape(note))); } } else { // Basic fallback from command list @@ -630,10 +748,10 @@ impl SubprocessPluginManager { if !info.commands.is_empty() { help.push_str("COMMANDS:\n"); - let prefix = format!("{name} "); + let prefix = format!("{} ", info.name); for cmd in &info.commands { // Strip "git " prefix for display - let display_cmd = cmd.strip_prefix(&prefix).unwrap_or(cmd); + let display_cmd = escape(cmd.strip_prefix(&prefix).unwrap_or(cmd)); help.push_str(&format!(" {display_cmd}\n")); } help.push('\n'); diff --git a/src/worktree.rs b/src/worktree.rs index db6b3d6..617c8c2 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -6,7 +6,7 @@ //! for worktree management commands. use anyhow::{Context, Result}; -use meta_core::display::{escape_lines, escape_path}; +use meta_core::display::{escape, escape_lines, escape_path}; use serde::Serialize; use std::path::{Path, PathBuf}; @@ -67,6 +67,182 @@ pub fn detect_worktree_location(cwd: &Path) -> Option<(String, PathBuf)> { None } +/// The config that names the members of the set at `set_dir`: the set's own +/// (its root checkout's), else the config of the workspace meta recorded the +/// set was made from. Only a set without meta's records looks above itself. +pub fn set_config( + set_dir: &Path, + members: &[PathBuf], + config_name: Option<&PathBuf>, +) -> Result> { + use meta_core::config; + if let Some(found) = config::meta_config_at(set_dir, config_name)? { + return Ok(Some(found)); + } + match set_origin(set_dir, members)? { + Some(source) => config::meta_config_at(&source, config_name), + None => config::find_meta_config(set_dir, config_name), + } +} + +/// The workspace meta recorded the set at `set_dir` was made from, by the +/// members whose record names this set (another set's checkout moved in +/// doesn't count). Members that name different workspaces are an error. +fn set_origin(set_dir: &Path, members: &[PathBuf]) -> Result> { + use meta_core::config; + let set = set_dir + .canonicalize() + .unwrap_or_else(|_| set_dir.to_path_buf()); + let mut origin: Option = None; + for member in members { + if config::recorded_set(member).as_ref() != Some(&set) { + continue; + } + let Some(project) = config::recorded_project(member) else { + continue; + }; + match &origin { + Some(first) if *first != project => anyhow::bail!( + "The checkouts of worktree set {} name different workspaces ({} and {}); \ + meta can't tell which config describes them. Pass --primary to run in the workspace.", + escape_path(set_dir), + escape_path(first), + escape_path(&project) + ), + _ => origin = Some(project), + } + } + Ok(origin) +} + +/// The meta tree that describes the checkouts of the set at `set_dir`, whose +/// config lists `projects`: the nested configs of the workspace the set was +/// made from, for nested meta repos the set doesn't hold (one skipped, say), +/// then the set's own, so a map built from it in order lets the set's win. +/// The workspace's part is best effort: what neither tells about stays +/// unselected. +pub fn set_tree( + set_dir: &Path, + members: &[PathBuf], + projects: &[meta_core::config::ProjectInfo], +) -> Result> { + use meta_core::config; + let own = config::walk_projects(set_dir, projects, None)?; + let mut tree: Vec<_> = set_origin(set_dir, members)? + .map(|dir| { + let mut visited = std::collections::HashSet::new(); + not_held(readable_tree(&dir, projects, &mut visited), set_dir) + }) + .unwrap_or_default(); + tree.extend(own); + Ok(tree) +} + +/// The meta tree of `projects` in `dir`, passing over each nested config +/// that can't be read: one broken config loses only its own projects. +fn readable_tree( + dir: &Path, + projects: &[meta_core::config::ProjectInfo], + visited: &mut std::collections::HashSet, +) -> Vec { + use meta_core::config; + projects + .iter() + .map(|project| { + let path = dir.join(&project.path); + let nested = config::find_meta_config_in(&path).ok().flatten(); + // each meta repo once, as `walk_projects` does: links can loop + let children = nested + .as_ref() + .filter(|_| visited.insert(path.canonicalize().unwrap_or_else(|_| path.clone()))) + .and_then(|(config, _)| config::parse_meta_config(config).ok()) + .map(|(projects, _)| readable_tree(&path, &projects, visited)) + .unwrap_or_default(); + config::MetaTreeNode { + info: project.clone(), + is_meta: nested.is_some(), + children, + } + }) + .collect() +} + +/// `nodes` without the projects of the nested meta repos whose config the +/// set at `dir` holds: those the set's own tree describes. +fn not_held( + nodes: Vec, + dir: &Path, +) -> Vec { + nodes + .into_iter() + .map(|mut node| { + let place = dir.join(&node.info.path); + node.children = match meta_core::config::find_meta_config_in(&place) { + Ok(Some(_)) => Vec::new(), + _ => not_held(node.children, &place), + }; + node + }) + .collect() +} + +/// Whether a checkout meta made for a set (a linked worktree with meta's +/// record, readable or not, or one whose git directory can't be found) may +/// be under `dir`, as in a set moved by hand; a part of `dir` that can't be +/// read may hold one too. Other tools' worktrees +/// have no record; plain clones (a `.git` directory, or a link to one) are +/// not looked inside. +pub fn holds_meta_checkout(dir: &Path) -> bool { + let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()); + // Where discovery looks: not in `.git`, nor in the sets of a workspace + // that is itself under `.worktrees` (its own nested `.worktrees`) + let mut walk = walkdir::WalkDir::new(dir) + .follow_links(false) + .into_iter() + .filter_entry(|entry| entry.depth() == 0 || ScannedDirs::searched(entry.path())); + while let Some(entry) = walk.next() { + // What can't be read may hold one: can't tell is no plain clone + let Ok(entry) = entry else { return true }; + if !entry.file_type().is_dir() { + continue; + } + match std::fs::metadata(entry.path().join(".git")) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return true, + Ok(meta) if meta.is_dir() => walk.skip_current_dir(), + // a checkout of a set kept inside `dir` by a workspace inside + // `dir` (one there with sets of its own, wherever its + // worktrees_dir puts them) is no sign that `dir` is a set + Ok(_) + if meta_core::config::recorded_set(entry.path()) + .is_some_and(|set| set.starts_with(&canonical_dir) && set != canonical_dir) + && meta_core::config::recorded_project(entry.path()) + .and_then(|project| project.canonicalize().ok()) + .is_some_and(|project| project.starts_with(&canonical_dir)) => {} + // even one meta can no longer read: it was meta's. A checkout + // whose git directory can't be found (moved, with relative paths) + // may be meta's too: it is not taken for a plain clone + Ok(_) => { + let meta_made = + meta_core::config::gitfile_target(entry.path()).is_none_or(|admin| { + // only a record that is surely absent says "not meta's" + !admin.is_dir() + || !matches!( + admin + .join(meta_core::config::WORKTREE_RECORD_FILE) + .symlink_metadata(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound + ) + }); + if meta_made { + return true; + } + } + _ => {} + } + } + false +} + /// Discover repos within a worktree task directory by scanning for .git files. /// Results are sorted by alias for deterministic output. pub fn discover_worktree_repos(task_dir: &Path) -> Result> { @@ -110,7 +286,8 @@ pub fn discover_worktree_members(task_dir: &Path) -> Result Result, ) -> Result<()> { let entries = match std::fs::read_dir(dir) { @@ -151,9 +329,7 @@ fn discover_repos_recursive( continue; } - // Skip hidden directories - let name = entry.file_name(); - if name.to_string_lossy().starts_with('.') { + if !ScannedDirs::searched(&sub_path) { continue; } @@ -163,6 +339,9 @@ fn discover_repos_recursive( .map(|m| m.is_file()) .unwrap_or(false) { + if !scanned.member(root, &sub_path) { + continue; + } // This is a worktree repo — use relative path from root as alias let source = match source_repo_from_gitfile(&sub_git) { Ok(s) => s, @@ -187,7 +366,7 @@ fn discover_repos_recursive( }); } else { // Not a repo — recurse into intermediate directory - if let Err(e) = discover_repos_recursive(root, &sub_path, repos) { + if let Err(e) = discover_repos_recursive(root, &sub_path, scanned, repos) { log::debug!( "Skipping subtree {}: {}", escape_path(&sub_path), @@ -200,8 +379,10 @@ fn discover_repos_recursive( } /// Discover all realized worktrees, including repos nested beneath other repos. -/// Unlike legacy discovery, traversal errors are fatal. Hidden directories and -/// directory symlinks are excluded; traversal never follows links outside the set. +/// Unlike legacy discovery, traversal errors are fatal. Under a hidden +/// directory only checkouts meta recorded in this set count (see +/// `ScannedDirs`); directory symlinks are not followed, so traversal never +/// leaves the set. /// A finite entry budget prevents unbounded scans of generated directory trees. pub fn discover_worktree_repos_recursive(task_dir: &Path) -> Result> { Ok(discover_worktree_members_recursive(task_dir)? @@ -220,21 +401,61 @@ pub struct WorktreeMemberInfo { pub source_path: PathBuf, } +/// Which checkouts in a set are its members. `.git` and a nested +/// `.worktrees` hold none. Under another hidden directory, only a checkout +/// meta's record says it made for this set counts: a project may live at +/// `.deps/x`, but a tool's own worktrees (`.claude/worktrees/x`) are not the +/// set's. +struct ScannedDirs { + set: PathBuf, +} + +impl ScannedDirs { + fn of(task_dir: &Path) -> Self { + ScannedDirs { + set: task_dir + .canonicalize() + .unwrap_or_else(|_| task_dir.to_path_buf()), + } + } + + /// Whether to look for members inside `dir`. + fn searched(dir: &Path) -> bool { + dir.file_name() + .is_none_or(|name| name != ".git" && name != ".worktrees") + } + + /// Whether the checkout at `dir`, inside the set at `root`, is a member. + fn member(&self, root: &Path, dir: &Path) -> bool { + let hidden = dir.strip_prefix(root).is_ok_and(|place| { + place + .components() + .any(|c| c.as_os_str().to_string_lossy().starts_with('.')) + }); + !hidden || meta_core::config::recorded_set(dir).as_ref() == Some(&self.set) + } +} + pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result> { let mut repos = Vec::new(); + let scanned = ScannedDirs::of(task_dir); let entries = walkdir::WalkDir::new(task_dir) .follow_links(false) .into_iter() - .filter_entry(|entry| { - entry.depth() == 0 || !entry.file_name().to_string_lossy().starts_with('.') - }); + .filter_entry(|entry| entry.depth() == 0 || ScannedDirs::searched(entry.path())); for (count, entry) in entries.enumerate() { anyhow::ensure!( count < 2_000_000, "Recursive worktree discovery exceeded 2000000 entries" ); - let entry = - entry.with_context(|| format!("Cannot scan worktree {}", escape_path(task_dir)))?; + // walkdir's error names the path it failed on: kept on one line + let entry = entry.map_err(|e| { + anyhow::anyhow!( + "Cannot scan worktree {}: {}", + escape_path(task_dir), + escape(&e.to_string()) + ) + })?; if !entry.file_type().is_dir() { continue; } @@ -248,7 +469,7 @@ pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result Result { let dot_git_dir = gitdir_path .parent() // strip worktree name .and_then(|p| p.parent()) // strip "worktrees" - .ok_or_else(|| anyhow::anyhow!("Cannot derive source repo from gitdir: {gitdir}"))?; + .ok_or_else(|| { + anyhow::anyhow!("Cannot derive source repo from gitdir: {}", escape(gitdir)) + })?; // dot_git_dir is now the .git directory; parent is the repo root let repo_root = dot_git_dir.parent().ok_or_else(|| { @@ -348,6 +571,32 @@ fn source_repo_from_gitfile(git_file: &Path) -> Result { mod recursive_tests { use super::*; + #[test] + fn the_sets_own_nested_config_wins_over_the_workspaces() { + let tmp = tempfile::tempdir().unwrap(); + let (workspace, set) = (tmp.path().join("ws"), tmp.path().join("set")); + let config = |dir: &Path, projects: &str| { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write( + dir.join(".meta.json"), + format!(r#"{{"projects": {{{projects}}}}}"#), + ) + .unwrap(); + }; + config(&workspace, r#""parent": {"repo": "x", "meta": true}"#); + config(&workspace.join("parent"), r#""x": "x""#); + let (projects, _) = + meta_core::config::parse_meta_config(&workspace.join(".meta.json")).unwrap(); + let tree = meta_core::config::walk_projects(&workspace, &projects, None).unwrap(); + + // the set doesn't hold parent: the workspace's config tells about x + std::fs::create_dir_all(&set).unwrap(); + assert_eq!(not_held(tree.clone(), &set)[0].children.len(), 1); + // the set holds parent's config, which no longer lists x + config(&set.join("parent"), ""); + assert!(not_held(tree, &set)[0].children.is_empty()); + } + /// Create a real committed repository and linked worktree in the fixture. fn member(root: &Path, alias: &str) { let sources = if alias == "." { @@ -474,15 +723,27 @@ mod recursive_tests { #[cfg(unix)] #[test] - /// Hidden directories and symlink cycles are excluded from traversal. - fn recursive_skips_hidden_directories_and_symlink_cycles() { + /// Under a hidden directory, a checkout meta recorded for this set is a + /// member; others (an agent's own worktrees), a nested set and symlink + /// cycles are not. + fn recursive_finds_recorded_hidden_members_only() { let temp = tempfile::tempdir().unwrap(); - member(temp.path(), "visible"); - member(temp.path(), ".hidden/child"); - std::os::unix::fs::symlink(temp.path(), temp.path().join("visible/cycle")).unwrap(); + let root = temp.path().canonicalize().unwrap(); + member(&root, "visible"); + member(&root, ".deps/child"); + let gitfile = std::fs::read_to_string(root.join(".deps/child/.git")).unwrap(); + let admin = Path::new(gitfile.trim().strip_prefix("gitdir: ").unwrap()); + std::fs::write( + admin.join(meta_core::config::WORKTREE_RECORD_FILE), + serde_json::json!({ "project": "/p", "set": root }).to_string(), + ) + .unwrap(); + member(&root, ".claude/worktrees/agent"); + member(&root, ".worktrees/other"); + std::os::unix::fs::symlink(&root, root.join("visible/cycle")).unwrap(); assert_eq!( - aliases(discover_worktree_repos_recursive(temp.path()).unwrap()), - ["visible"] + aliases(discover_worktree_repos_recursive(&root).unwrap()), + [".deps/child", "visible"] ); } /// Relative Git links resolve against the checkout, independently of cwd. diff --git a/tests/plugin_discovery.rs b/tests/plugin_discovery.rs new file mode 100644 index 0000000..c6be992 --- /dev/null +++ b/tests/plugin_discovery.rs @@ -0,0 +1,563 @@ +//! Plugin scope and metadata probing must not break unrelated commands. +#![cfg(unix)] + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +struct Fixture { + _temp: tempfile::TempDir, + home: PathBuf, + cwd: PathBuf, + data: PathBuf, + bin: PathBuf, +} + +impl Fixture { + fn new(workspace: bool) -> Self { + let temp = tempfile::tempdir().unwrap(); + // meta reports resolved paths (macOS's temp dir is behind a link) + let base = temp.path().canonicalize().unwrap(); + let home = base.join("home"); + let cwd = home.join("workspace"); + let data = base.join("data"); + let bin = base.join("bin"); + for dir in [&cwd, &data, &bin] { + fs::create_dir_all(dir).unwrap(); + } + if workspace { + fs::write(cwd.join(".meta.yaml"), "projects: {}\n").unwrap(); + } + Self { + _temp: temp, + home, + cwd, + data, + bin, + } + } + + fn command(&self, args: &[&str]) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_meta")); + cmd.args(args) + .current_dir(&self.cwd) + .env("HOME", &self.home) + .env("XDG_CONFIG_HOME", self.home.join("xdg")) + .env("XDG_DATA_HOME", self.home.join("xdg/data")) + .env("GIT_CONFIG_GLOBAL", self.home.join("gitconfig")) + .env("META_DATA_DIR", &self.data) + .env("PATH", format!("{}:/usr/bin:/bin", self.bin.display())); + cmd + } + + fn run(&self, args: &[&str]) -> Output { + self.command(args).output().unwrap() + } +} + +fn script(path: &Path, body: &str) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, format!("#!/bin/sh\n{body}\n")).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); +} + +fn plugin(path: &Path, name: &str, version: &str) { + script( + path, + &format!( + "echo '{{\"name\":\"{name}\",\"version\":\"{version}\",\"commands\":[\"{name}\"]}}'" + ), + ); +} + +#[test] +fn bare_home_meta_directory_is_neither_workspace_nor_project_plugin_source() { + let f = Fixture::new(false); + plugin(&f.home.join(".meta/plugins/meta-fake"), "fake", "1.0"); + let help = f.run(&["--help"]); + assert!(help.status.success()); + assert!(!String::from_utf8_lossy(&help.stdout).contains("fake")); + for args in [ + vec!["plugin", "list", "--local"], + vec!["plugin", "list", "--local", "--json"], + vec!["plugin", "install", "--local", "missing/repo"], + vec!["plugin", "uninstall", "--local", "missing"], + vec!["plugin", "update", "--local", "missing"], + ] { + let output = f.run(&args); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(!output.status.success(), "{args:?}"); + assert!(text.contains("Not in a meta workspace"), "{args:?}: {text}"); + } +} + +#[test] +fn discovery_stops_at_nearest_workspace_and_uses_global_data_dir() { + let f = Fixture::new(true); + plugin(&f.home.join(".meta/plugins/meta-ancestor"), "ancestor", "1"); + plugin(&f.cwd.join(".meta/plugins/meta-local"), "local", "2"); + plugin(&f.data.join("plugins/meta-global"), "global", "3"); + plugin(&f.bin.join("meta-system"), "system", "4"); + // All three sources provide the same name: the local one wins. + plugin(&f.data.join("plugins/meta-local"), "local", "wrong-global"); + plugin(&f.bin.join("meta-local"), "local", "wrong-path"); + plugin(&f.bin.join("meta-global"), "global", "wrong-path"); + let output = f.run(&["plugin", "list", "--json"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8_lossy(&output.stdout); + assert!(!text.contains("ancestor"), "{text}"); + assert!(!text.contains("wrong-"), "{text}"); + for name in ["local", "global", "system"] { + assert!(text.contains(name), "{text}"); + } +} + +#[test] +fn nested_meta_dir_reads_its_workspace_plugins_but_not_an_unlisting_parent() { + let f = Fixture::new(true); + plugin(&f.home.join(".meta/plugins/meta-parent"), "parent", "1"); + let listed = |yaml: &str| { + fs::write(f.home.join(".meta.yaml"), yaml).unwrap(); + let output = f.run(&["plugin", "list", "--json"]); + assert!(output.status.success()); + String::from_utf8_lossy(&output.stdout).contains("parent") + }; + // The parent lists this meta dir: one workspace, its plugins load here + assert!(listed( + "projects:\n workspace:\n repo: x\n meta: true\n" + )); + // A parent that doesn't list it is another workspace + assert!(!listed("projects: {}\n")); +} + +#[test] +fn a_worktree_set_checkout_reads_its_own_and_its_origins_plugins() { + let f = Fixture::new(true); + // A set's root checkout, laid out as git and meta leave it + let set = f.cwd.join(".worktrees/s1"); + let admin = f.cwd.join(".git/worktrees/s1"); + fs::create_dir_all(&admin).unwrap(); + fs::write(admin.join("commondir"), "../..\n").unwrap(); + let record = format!( + "{{\"project\": {:?}, \"set\": {:?}}}", + f.cwd.display().to_string(), + set.display().to_string() + ); + fs::write(admin.join("meta-worktree.json"), record).unwrap(); + fs::create_dir_all(&set).unwrap(); + fs::write(set.join(".meta.yaml"), "projects: {}\n").unwrap(); + fs::write(set.join(".git"), format!("gitdir: {}\n", admin.display())).unwrap(); + plugin(&f.cwd.join(".meta/plugins/meta-main"), "main", "1"); + plugin(&set.join(".meta/plugins/meta-setlocal"), "setlocal", "1"); + let output = f + .command(&["plugin", "list", "--json"]) + .current_dir(&set) + .output() + .unwrap(); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + assert!( + text.contains("setlocal") && text.contains("\"main\""), + "{text}" + ); +} + +#[test] +fn explicit_config_does_not_redirect_plugin_scope() { + let f = Fixture::new(true); + let other = f.home.join("other"); + fs::create_dir(&other).unwrap(); + fs::write(other.join(".meta.yaml"), "projects: {}").unwrap(); + plugin(&other.join(".meta/plugins/meta-foreign"), "foreign", "1"); + plugin(&f.cwd.join(".meta/plugins/meta-local"), "local", "2"); + let output = f.run(&[ + "--config", + other.join(".meta.yaml").to_str().unwrap(), + "plugin", + "list", + "--json", + ]); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + assert!(text.contains("local")); + assert!(!text.contains("foreign")); +} + +#[test] +fn local_list_from_subdirectory_uses_real_path_and_binary_version() { + let mut f = Fixture::new(true); + let plugin_path = f.cwd.join(".meta/plugins/meta-real"); + plugin(&plugin_path, "real", "2.5.0"); + fs::write(f.cwd.join(".meta/plugins/.manifest.json"), r#"{"plugins":{"meta-real":{"source":"example/repo","version":"stale","installed":"2024-01-01","platform":"test"}}}"#).unwrap(); + f.cwd = f.cwd.join("nested/deep"); + fs::create_dir_all(&f.cwd).unwrap(); + let output = f.run(&["plugin", "list", "--local"]); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout); + assert!(text.contains(plugin_path.to_str().unwrap()), "{text}"); + assert!(text.contains("2.5.0"), "{text}"); + assert!(!text.contains("stale"), "{text}"); +} + +#[test] +fn ambiguous_configs_and_explicit_config_errors_are_escaped() { + let f = Fixture::new(true); + fs::write(f.cwd.join(".meta.json"), "{}").unwrap(); + // Help still prints, with a warning; a command that needs the config fails + for (args, works) in [ + (vec!["--help"], true), + (vec!["plugin", "list", "--local"], false), + ] { + let output = f.run(&args); + assert_eq!(output.status.success(), works, "{args:?}"); + let err = String::from_utf8_lossy(&output.stderr); + assert!(err.contains("Multiple meta config files"), "{err}"); + assert!( + err.contains(".meta.json") && err.contains(".meta.yaml"), + "{err}" + ); + } + fs::remove_file(f.cwd.join(".meta.json")).unwrap(); + let output = f.run(&["--config", "absent\u{1b}\nFORGED", "exec", "--", "true"]); + let err = String::from_utf8_lossy(&output.stderr); + assert!( + err.contains("Could not find meta config file 'absent\\u{1b}\\nFORGED'"), + "{err}" + ); + assert!(!err.contains('\u{1b}'), "{err}"); + fs::remove_file(f.cwd.join(".meta.yaml")).unwrap(); + let output = f.run(&["exec", "--", "true"]); + let err = String::from_utf8_lossy(&output.stderr); + assert!( + err.contains("'.meta / .meta.json / .meta.yaml / .meta.yml'"), + "{err}" + ); +} + +#[test] +fn local_install_gitignores_untracked_plugin_files() { + use std::io::{Read, Write}; + use std::net::TcpListener; + let f = Fixture::new(true); + let body = + b"#!/bin/sh\necho '{\"name\":\"installed\",\"version\":\"1.2.3\",\"commands\":[]}'\n"; + let mut archive = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::default(), + )); + let mut header = tar::Header::new_gnu(); + header.set_path("meta-installed").unwrap(); + header.set_size(body.len() as u64); + header.set_mode(0o755); + header.set_cksum(); + archive.append(&header, body.as_slice()).unwrap(); + let bytes = archive.into_inner().unwrap().finish().unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/plugin.tar.gz", listener.local_addr().unwrap()); + listener.set_nonblocking(true).unwrap(); + let server = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + match listener.accept() { + Ok((mut stream, _)) => { + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let mut request = [0; 4096]; + assert!(stream.read(&mut request).unwrap() > 0); + write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + bytes.len() + ) + .unwrap(); + stream.write_all(&bytes).unwrap(); + return; + } + Err(e) + if e.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => + { + std::thread::sleep(Duration::from_millis(10)); + } + Err(e) => panic!("download request did not arrive: {e}"), + } + } + }); + let output = f.run(&["plugin", "install", "--local", &url]); + server.join().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(f.cwd.join(".meta/plugins/meta-installed").is_file()); + assert_eq!( + fs::read_to_string(f.cwd.join(".meta/plugins/.gitignore")).unwrap(), + "*\n" + ); +} + +#[test] +fn orphan_hint_names_actual_parent_config() { + for name in [".meta.json", ".meta.yml"] { + let f = Fixture::new(true); + let parent_config = f.home.join(name); + fs::write( + &parent_config, + if name.ends_with("json") { + "{\"projects\":{}}" + } else { + "projects: {}" + }, + ) + .unwrap(); + let output = f.run(&["--help"]); + assert!(output.status.success()); + let err = String::from_utf8_lossy(&output.stderr); + // meta names the parent by its resolved path (/private/var on macOS) + let parent_config = f.home.canonicalize().unwrap().join(name); + assert!( + err.contains(&format!( + "To include it, add to {}:", + parent_config.display() + )), + "{err}" + ); + } +} + +#[test] +fn legacy_meta_config_file_means_no_project_plugins_without_a_warning() { + let f = Fixture::new(false); + fs::write(f.cwd.join(".meta"), "{\"projects\": {}}\n").unwrap(); + let out = f.run(&["exec", "--", "true"]); + assert!(out.status.success()); + assert_eq!(String::from_utf8_lossy(&out.stderr), ""); +} + +#[test] +fn unreadable_plugin_directory_warns_and_help_still_runs() { + // Root can read mode-000 directories, so this case cannot be exercised there. + if unsafe { libc::geteuid() } == 0 { + return; + } + let f = Fixture::new(true); + let global_data = f.home.join("global\nFORGED\u{1b}"); + let global_plugins = global_data.join("plugins"); + fs::create_dir_all(&global_plugins).unwrap(); + fs::set_permissions(&global_plugins, fs::Permissions::from_mode(0o000)).unwrap(); + let output = f + .command(&["--help"]) + .env("META_DATA_DIR", &global_data) + .output() + .unwrap(); + fs::set_permissions(&global_plugins, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(output.status.success()); + let err = String::from_utf8_lossy(&output.stderr); + assert!(err.contains("global\\nFORGED\\u{1b}/plugins"), "{err}"); + assert!(err.contains("Cannot read plugins directory"), "{err}"); + assert!(!err.contains('\u{1b}')); + // Also exercise the actual workspace plugins directory. + let path = f.cwd.join(".meta/plugins"); + fs::create_dir_all(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o000)).unwrap(); + let output_local = f.run(&["--help"]); + fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); + assert!(output.status.success()); + assert!(output_local.status.success()); + let err = String::from_utf8_lossy(&output_local.stderr); + assert!( + err.contains("Warning: Cannot read plugins directory"), + "{err}" + ); + assert!(err.contains(path.to_str().unwrap()), "{err}"); +} + +fn running(pid: i32) -> bool { + // On Linux an orphan may briefly be a zombie until init reaps it. + if let Ok(stat) = fs::read_to_string(format!("/proc/{pid}/stat")) { + return !stat.rsplit_once(") ").unwrap().1.starts_with('Z'); + } + unsafe { libc::kill(pid, 0) == 0 } +} + +fn timeout_case(background: bool) { + let f = Fixture::new(true); + let pidfile = f.cwd.join("pids"); + let path = f.cwd.join(".meta/plugins/meta-hung\nFORGED\u{1b}"); + let body = if background { + "echo $$ > pids\nsleep 60 &\necho $! >> pids\nexit 0" + } else { + "echo $$ > pids\nexec sleep 60" + }; + script(&path, body); + // Redirect to files so a regression cannot block this test on inherited pipes. + let stdout = fs::File::create(f.cwd.join("stdout")).unwrap(); + let stderr = fs::File::create(f.cwd.join("stderr")).unwrap(); + let started = Instant::now(); + let mut child = f + .command(&["--help"]) + .stdout(Stdio::from(stdout)) + .stderr(Stdio::from(stderr)) + .spawn() + .unwrap(); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break Some(status); + } + if started.elapsed() > Duration::from_secs(8) { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + std::thread::sleep(Duration::from_millis(20)); + }; + let pids: Vec = fs::read_to_string(&pidfile) + .unwrap() + .lines() + .map(|s| s.parse().unwrap()) + .collect(); + let mut survivors = Vec::new(); + for pid in pids { + for _ in 0..50 { + if !running(pid) { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + if running(pid) { + survivors.push(pid); + unsafe { + libc::kill(pid, libc::SIGKILL); + } + } + } + assert!( + status.is_some_and(|s| s.success()), + "command did not finish within deadline" + ); + assert!(started.elapsed() < Duration::from_secs(8)); + assert!( + survivors.is_empty(), + "plugin processes left running: {survivors:?}" + ); + let err = fs::read_to_string(f.cwd.join("stderr")).unwrap(); + assert!(err.contains("meta-hung\\nFORGED\\u{1b}"), "{err}"); + assert!( + err.contains("did not answer --meta-plugin-info within 5 seconds; skipping"), + "{err}" + ); + assert!(!err.contains('\u{1b}')); +} + +#[test] +fn sleeping_probe_times_out_and_reaps_plugin() { + timeout_case(false); +} + +#[test] +fn exited_wrapper_with_background_stdout_times_out_and_kills_descendant() { + timeout_case(true); +} + +#[test] +fn generated_help_keeps_a_plugins_values_on_their_lines() { + let f = Fixture::new(true); + script( + &f.data.join("plugins/meta-odd"), + r#"case "$1" in +--meta-plugin-info) printf '%s\n' '{"name":"odd","version":"1\u001b[2J","description":"d\nFORGED","commands":["odd x\u001b[2J\nFORGED"]}' ;; +*) exit 1 ;; +esac"#, + ); + for args in [&["--help"][..], &["odd", "--help"][..]] { + let out = f.run(args); + let text = String::from_utf8_lossy(&out.stdout).to_string() + + &String::from_utf8_lossy(&out.stderr); + assert!(!text.contains('\u{1b}'), "{args:?}: {text}"); + assert!( + !text.lines().any(|line| line.starts_with("FORGED")), + "{args:?}: {text}" + ); + assert!(text.contains("odd"), "{args:?}: {text}"); + } +} + +#[test] +fn verbose_dispatch_keeps_a_plugins_name_on_its_line() { + let f = Fixture::new(true); + script( + &f.data.join("plugins/meta-demo"), + r#"case "$1" in +--meta-plugin-info) printf '%s\n' '{"name":"bad\u001b[2J\nFORGED","version":"1","commands":["demo run"]}' ;; +*) cat >/dev/null ;; +esac"#, + ); + let out = f.run(&["--verbose", "demo", "run"]); + let text = + String::from_utf8_lossy(&out.stdout).to_string() + &String::from_utf8_lossy(&out.stderr); + assert!(text.contains("Executing plugin bad"), "{text}"); + assert!(!text.contains('\u{1b}'), "{text}"); + assert!( + !text.lines().any(|line| line.starts_with("FORGED")), + "{text}" + ); +} + +#[test] +fn an_unreadable_plan_names_the_plugin_on_one_line() { + let f = Fixture::new(false); + // a workspace whose path holds a newline: the plugin's path does too + let cwd = f.cwd.join("ws\nFORGED"); + fs::create_dir_all(&cwd).unwrap(); + fs::write(cwd.join(".meta.yaml"), "projects: {}\n").unwrap(); + script( + &cwd.join(".meta/plugins/meta-demo"), + r#"case "$1" in +--meta-plugin-info) printf '%s\n' '{"name":"demo","version":"1","commands":["demo run"]}' ;; +*) cat >/dev/null; printf '%s\n' '{"plan":{"commands":[{"cmd":"true"}]}}' ;; +esac"#, + ); + let out = f + .command(&["demo", "run"]) + .current_dir(&cwd) + .output() + .unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("ws\\nFORGED"), "{err}"); + assert!(!err.lines().any(|line| line.starts_with("FORGED")), "{err}"); +} + +#[test] +fn a_plugin_that_answers_without_reading_its_request_still_answers() { + let f = Fixture::new(true); + script( + &f.data.join("plugins/meta-quick"), + r#"case "$1" in +--meta-plugin-info) printf '%s\n' '{"name":"quick","version":"1","commands":["quick go"]}' ;; +*) echo answered ;; +esac"#, + ); + // the plugin may exit before meta has written its request + for _ in 0..20 { + let out = f.run(&["quick", "go"]); + let text = String::from_utf8_lossy(&out.stdout).to_string() + + &String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{text}"); + assert!(text.contains("answered"), "{text}"); + } +} diff --git a/tests/plugin_git.rs b/tests/plugin_git.rs index a2d2aef..4c7936b 100644 --- a/tests/plugin_git.rs +++ b/tests/plugin_git.rs @@ -352,6 +352,8 @@ fn malformed_worktree_membership_is_reported_before_dispatch() { .args(["exec", "--", "/usr/bin/touch", marker.to_str().unwrap()]) .current_dir(&worktree) .env("HOME", &root) + .env("XDG_CONFIG_HOME", root.join("xdg")) + .env("GIT_CONFIG_GLOBAL", root.join("gitconfig")) .env("META_DATA_DIR", root.join("data")) .env("PATH", "/usr/bin:/bin") .output() diff --git a/tests/plugin_routing.rs b/tests/plugin_routing.rs index 50ed27f..166f4dd 100644 --- a/tests/plugin_routing.rs +++ b/tests/plugin_routing.rs @@ -49,6 +49,8 @@ fn run_meta(root: &Path, args: &[&str]) -> std::process::Output { .args(args) .current_dir(root) .env("HOME", root) + .env("XDG_CONFIG_HOME", root.join("xdg")) + .env("GIT_CONFIG_GLOBAL", root.join("gitconfig")) .env("META_DATA_DIR", root.join("data")) .env( "PATH",