diff --git a/src/context.rs b/src/context.rs index 8a55d0a..12d82a8 100644 --- a/src/context.rs +++ b/src/context.rs @@ -14,6 +14,7 @@ use std::time::{Duration, SystemTime}; use crate::dependency_graph::DependencyGraph; use crate::git_utils; use meta_core::config::{self, ProjectInfo}; +use meta_core::display::{escape, escape_path}; // ── Cache ─────────────────────────────────────────────── @@ -26,33 +27,26 @@ struct CachedContext { workspace_root: PathBuf, } -fn cache_path() -> PathBuf { +fn cache_path() -> anyhow::Result { meta_core::data_dir::data_file("context_cache") } fn load_cache() -> Option { - let path = cache_path(); - let content = std::fs::read(&path).ok()?; - serde_json::from_slice(&content).ok() + // checked like any store: it is rendered into what agents read + meta_core::store::read::>(&cache_path().ok()?) + .ok() + .flatten() } fn save_cache(cached: &CachedContext, verbose: bool) { - let path = cache_path(); - match serde_json::to_vec(cached) { - Ok(json) => { - if let Err(e) = std::fs::write(&path, json) { - if verbose { - eprintln!("Failed to write context cache: {e}"); - } - } else if verbose { - eprintln!("Saved context cache to {}", path.display()); - } - } - Err(e) => { - if verbose { - eprintln!("Failed to serialize context cache: {e}"); - } - } + let Ok(path) = cache_path() else { + return; + }; + match meta_core::store::write_atomic(&path, cached) { + Ok(()) if verbose => eprintln!("Saved context cache to {}", escape_path(&path)), + Ok(()) => {} + Err(e) if verbose => eprintln!("Failed to write context cache: {e:#}"), + Err(_) => {} } } @@ -147,7 +141,7 @@ pub fn handle_context(json: bool, no_status: bool, no_cache: bool, verbose: bool eprintln!( "Found {} projects in {}", projects.len(), - config_path.display() + escape_path(&config_path) ); } @@ -315,15 +309,27 @@ fn build_dependency_map(projects: &[ProjectInfo]) -> Option String { + escape(s).replace('\\', "\\\\").replace('|', "\\|") +} + +fn md_list(items: &[String]) -> String { + items.iter().map(|s| md(s)).collect::>().join(", ") +} + pub fn format_markdown(ctx: &WorkspaceContext) -> String { let mut out = String::new(); // Header out.push_str(&format!( "# Meta Workspace: {} ({} repos)\n\n", - ctx.name, ctx.repo_count + md(&ctx.name), + ctx.repo_count )); - out.push_str(&ctx.description); + out.push_str(&md(&ctx.description)); out.push_str("\n\n"); // Repo table @@ -337,10 +343,10 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { for r in &ctx.repos { out.push_str(&format!( "| {} | {} | {} | {} |\n", - r.name, - r.branch.as_deref().unwrap_or("-"), + md(&r.name), + md(r.branch.as_deref().unwrap_or("-")), format_status(r), - r.tags.join(", "), + md_list(&r.tags), )); } } else if has_status { @@ -350,8 +356,8 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { for r in &ctx.repos { out.push_str(&format!( "| {} | {} | {} |\n", - r.name, - r.branch.as_deref().unwrap_or("-"), + md(&r.name), + md(r.branch.as_deref().unwrap_or("-")), format_status(r), )); } @@ -361,11 +367,11 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { out.push_str("| Repo | Tags |\n"); out.push_str("|------|------|\n"); for r in &ctx.repos { - out.push_str(&format!("| {} | {} |\n", r.name, r.tags.join(", "))); + out.push_str(&format!("| {} | {} |\n", md(&r.name), md_list(&r.tags))); } } else { for r in &ctx.repos { - out.push_str(&format!("- {}\n", r.name)); + out.push_str(&format!("- {}\n", md(&r.name))); } } } @@ -373,7 +379,11 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { // Key commands out.push_str("\n## Key Commands\n"); for cmd in &ctx.commands { - out.push_str(&format!("- `{}` — {}\n", cmd.command, cmd.description)); + out.push_str(&format!( + "- `{}` — {}\n", + md(&cmd.command), + md(&cmd.description) + )); } // Dependencies @@ -383,7 +393,7 @@ pub fn format_markdown(ctx: &WorkspaceContext) -> String { sorted_keys.sort(); for key in sorted_keys { let targets = &deps[key]; - out.push_str(&format!("{} → {}\n", key, targets.join(", "))); + out.push_str(&format!("{} → {}\n", md(key), md_list(targets))); } } @@ -447,6 +457,39 @@ mod tests { } } + #[test] + fn markdown_escapes_untrusted_values() { + // Values from git, the filesystem or an old context cache can carry + // terminal escapes or break the table that agents read. + let mut ctx = make_ctx( + vec![make_repo( + "z\u{1b}[2J", + Some("evil|branch\\|x\u{1b}]52;c;cm0K\u{7}"), + Some(false), + Some(0), + vec!["n\nfake"], + )], + Some(HashMap::from([( + "a\u{1b}[1A".to_string(), + vec!["b\nc".to_string()], + )])), + ); + ctx.name = "ws\u{1b}]0;TITLE\u{7}".to_string(); + let md = format_markdown(&ctx); + assert!(!md.contains('\u{1b}') && !md.contains('\u{7}'), "{md}"); + assert!( + md.contains( + "| z\\\\u{1b}[2J | evil\\|branch\\\\\\|x\\\\u{1b}]52;c;cm0K\\\\u{7} | clean | n\\\\nfake |" + ), + "{md}" + ); + assert!( + md.contains("# Meta Workspace: ws\\\\u{1b}]0;TITLE\\\\u{7} (1 repos)"), + "{md}" + ); + assert!(md.contains("a\\\\u{1b}[1A → b\\\\nc"), "{md}"); + } + // ── format_status ────────────────────────────────── #[test] diff --git a/src/init.rs b/src/init.rs index 74621f8..e2d66cf 100644 --- a/src/init.rs +++ b/src/init.rs @@ -7,6 +7,7 @@ use crate::config; use anyhow::{Context, Result}; use colored::*; +use meta_core::display::escape_path; use serde_json::{json, Map, Value}; use std::fs; use std::path::{Path, PathBuf}; @@ -178,7 +179,8 @@ fn install_claude_integration_to( let skills_dir = claude_dir.join("skills"); let rules_dir = claude_dir.join("rules"); - if config::find_meta_config_in(target_dir).is_none() { + // A config that can't be read is an error, not "no config" + if config::find_meta_config_in(target_dir)?.is_none() { println!( "{}", "Warning: No .meta config found in current directory.".yellow() @@ -206,7 +208,7 @@ fn install_claude_integration_to( let rules_link = symlink_in(target_dir, Path::new(".claude/rules")); if rules_link.is_none() { fs::create_dir_all(&rules_dir) - .with_context(|| format!("Failed to create {}", rules_dir.display()))?; + .with_context(|| format!("Failed to create {}", escape_path(&rules_dir)))?; } // Older releases wrote flat `.md` files, which Claude Code does not load. @@ -229,14 +231,14 @@ fn install_claude_integration_to( println!( "{} {} (not created by meta, left alone)", "Skipped".yellow(), - flat_path.display() + escape_path(&flat_path) ); skipped += 1; } else if overwrite_content && shipped { fs::remove_file(&flat_path) - .with_context(|| format!("Failed to remove {}", flat_path.display()))?; + .with_context(|| format!("Failed to remove {}", escape_path(&flat_path)))?; if verbose { - println!("{} {}", "Removed".yellow(), flat_path.display()); + println!("{} {}", "Removed".yellow(), escape_path(&flat_path)); } } } @@ -250,8 +252,8 @@ fn install_claude_integration_to( println!( "{} {} (reached through the symlink {}, not followed)", "Skipped".yellow(), - rel.display(), - link.display() + escape_path(&rel), + escape_path(&link) ); skipped += 1; continue; @@ -286,7 +288,7 @@ fn install_claude_integration_to( println!( "{} .claude/settings.json (reached through the symlink {}, not followed)", "Skipped".yellow(), - link.display() + escape_path(&link) ); skipped += 1; } else { @@ -448,19 +450,26 @@ fn install_skills_with( for (name, content) in skills { let rel = tool_dir.join(name).join("SKILL.md"); if let Some(link) = symlink_in(root, &rel) { - anyhow::bail!("Refusing to write through the symlink {}", link.display()); + anyhow::bail!( + "Refusing to write through the symlink {}", + escape_path(&link) + ); } let path = root.join(&rel); if path.exists() && !overwrite { if verbose { - println!("{} {} (already exists)", "Skipped".yellow(), path.display()); + println!( + "{} {} (already exists)", + "Skipped".yellow(), + escape_path(&path) + ); } report.skipped += 1; continue; } let skill_dir = root.join(tool_dir.join(name)); fs::create_dir_all(&skill_dir) - .with_context(|| format!("Failed to create {}", skill_dir.display()))?; + .with_context(|| format!("Failed to create {}", escape_path(&skill_dir)))?; write_file(&path, content, verbose)?; report.written += 1; } @@ -475,15 +484,15 @@ fn install_skills_with( println!( "{} {} (reached through the symlink {}, not followed)", "Skipped".yellow(), - agent_dir.display(), - link.display() + escape_path(agent_dir), + escape_path(&link) ); report.skipped += 1; continue; } let skills_dir = root.join(agent_dir); fs::create_dir_all(&skills_dir) - .with_context(|| format!("Failed to create {}", skills_dir.display()))?; + .with_context(|| format!("Failed to create {}", escape_path(&skills_dir)))?; report.agent_dirs.push(agent_dir.display().to_string()); // One `..` per folder in `agent_dir` @@ -498,7 +507,11 @@ fn install_skills_with( SkillEntry::Owned if overwrite => remove_owned(&link, &marker)?, SkillEntry::Owned => { if verbose { - println!("{} {} (already exists)", "Skipped".yellow(), link.display()); + println!( + "{} {} (already exists)", + "Skipped".yellow(), + escape_path(&link) + ); } report.skipped += 1; continue; @@ -507,7 +520,7 @@ fn install_skills_with( println!( "{} {} (not created by {tool}, left alone)", "Skipped".yellow(), - link.display() + escape_path(&link) ); report.skipped += 1; continue; @@ -519,8 +532,8 @@ fn install_skills_with( println!( "{} {} -> {}", "Linked".green(), - link.display(), - target.display() + escape_path(&link), + escape_path(&target) ); } } @@ -532,7 +545,7 @@ fn install_skills_with( println!( "{} {} (symlink failed: {err})", "Copied".yellow(), - link.display() + escape_path(&link) ); report.copied += 1; } @@ -602,30 +615,30 @@ fn skill_entry(link: &Path, target: &Path, marker: &str, legacy: Option<&str>) - fn remove_owned(link: &Path, marker: &str) -> Result<()> { if fs::symlink_metadata(link).is_ok_and(|m| m.is_file()) { return fs::remove_file(link) - .with_context(|| format!("Failed to remove {}", link.display())); + .with_context(|| format!("Failed to remove {}", escape_path(link))); } for file in ["SKILL.md", marker] { let path = link.join(file); if path.exists() { fs::remove_file(&path) - .with_context(|| format!("Failed to remove {}", path.display()))?; + .with_context(|| format!("Failed to remove {}", escape_path(&path)))?; } } - fs::remove_dir(link).with_context(|| format!("Failed to remove {}", link.display())) + fs::remove_dir(link).with_context(|| format!("Failed to remove {}", escape_path(link))) } /// Copy the skill folder of `source` (a `SKILL.md`) to `dir` where it can't be linked, /// marking the copy as the tool's own. fn copy_skill(source: &Path, dir: &Path, marker: &str) -> Result<()> { - fs::create_dir(dir).with_context(|| format!("Failed to create {}", dir.display()))?; + fs::create_dir(dir).with_context(|| format!("Failed to create {}", escape_path(dir)))?; fs::copy(source, dir.join("SKILL.md")) - .with_context(|| format!("Failed to copy {}", source.display()))?; + .with_context(|| format!("Failed to copy {}", escape_path(source)))?; fs::write( dir.join(marker), "Copied by `meta init claude` because a symlink could not be created here.\n\ `meta init claude --update` refreshes it.\n", ) - .with_context(|| format!("Failed to write {}", dir.display()))?; + .with_context(|| format!("Failed to write {}", escape_path(dir)))?; Ok(()) } @@ -658,18 +671,22 @@ fn install_settings(settings_path: &Path, force: bool, verbose: bool) -> Result< // Merge: read existing, deep-merge hooks, write back let existing_content = fs::read_to_string(settings_path) - .with_context(|| format!("Failed to read {}", settings_path.display()))?; + .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 {}", settings_path.display()))?; + .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 {}", settings_path.display()))?; + .with_context(|| format!("Failed to write {}", escape_path(settings_path)))?; if verbose { - println!("{} {} (merged)", "Wrote".green(), settings_path.display()); + println!( + "{} {} (merged)", + "Wrote".green(), + escape_path(settings_path) + ); } else { println!(" {} settings.json (merged)", "✓".green()); } @@ -852,15 +869,15 @@ fn register_marketplace(verbose: bool) { } fn write_file(path: &Path, content: &str, verbose: bool) -> Result<()> { - fs::write(path, content).with_context(|| format!("Failed to write {}", path.display()))?; + fs::write(path, content).with_context(|| format!("Failed to write {}", escape_path(path)))?; if verbose { - println!("{} {}", "Wrote".green(), path.display()); + println!("{} {}", "Wrote".green(), escape_path(path)); } else { // Show the parent too: every skill file is named SKILL.md. let name = |p: &Path| p.file_name().unwrap_or_default().to_owned(); let shown = Path::new(&path.parent().map(name).unwrap_or_default()).join(name(path)); - println!(" {} {}", "✓".green(), shown.display()); + println!(" {} {}", "✓".green(), escape_path(&shown)); } Ok(()) diff --git a/src/lib.rs b/src/lib.rs index 17dbba7..7889f5a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod config; +pub use meta_core::display; pub mod context; pub mod dependency_graph; pub mod git_utils; diff --git a/src/main.rs b/src/main.rs index 1ae0557..8b69175 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use loop_lib::run; use meta_core::config::{ self, find_meta_config, parse_meta_config, ConfigFormat, MetaTreeNode, ProjectInfo, }; +use meta_core::display::{escape, escape_lines, escape_path}; use std::io::Write; use std::path::PathBuf; @@ -455,8 +456,35 @@ fn print_plugin_update_help() { // === Main Entry Point === -fn main() -> Result<()> { - env_logger::init(); +fn main() -> std::process::ExitCode { + match run_cli() { + Ok(()) => std::process::ExitCode::SUCCESS, + Err(e) => { + // as Rust prints an error returned from main, but escaped: it can + // carry paths and names from git and the filesystem + eprintln!("Error: {}", escape_lines(&format!("{e:?}"))); + std::process::ExitCode::FAILURE + } + } +} + +fn run_cli() -> Result<()> { + // Log records carry names, versions, paths and URLs from config, the + // filesystem and plugin registries: escape them like other output + env_logger::Builder::from_default_env() + .format(|buf, record| { + use std::io::Write; + writeln!( + buf, + "[{} {} {}] {}", + buf.timestamp(), + record.level(), + record.target(), + // Newlines too: one from data could forge a log line + escape(&record.args().to_string()) + ) + }) + .init(); let mut cli = Cli::parse(); @@ -641,7 +669,7 @@ fn handle_command_dispatch( log::debug!( "parallel={} (from config defaults, cwd={})", defaults.parallel, - cwd.display() + escape_path(&cwd) ); defaults.parallel }; @@ -700,7 +728,7 @@ fn handle_command_dispatch( if cli.verbose { eprintln!( "Detected worktree context: '{}' ({} repos)", - task_name, + escape(&task_name), wt_paths.len() ); } @@ -743,7 +771,7 @@ fn handle_command_dispatch( "{}: no projects match tag filter '{}' in worktree '{}'", "warning".yellow().bold(), cli.tag.as_deref().unwrap_or(""), - task_name + escape(&task_name) ); return Ok(()); } @@ -753,7 +781,7 @@ fn handle_command_dispatch( if cli.verbose && !config_in_worktree { eprintln!( "Using config from primary checkout: {}", - config_path.display() + escape_path(&config_path) ); } @@ -811,7 +839,7 @@ fn handle_command_dispatch( eprintln!( "{} No .meta config found for worktree '{}'. Tags, plugins, and dependency features unavailable.", "warning:".yellow().bold(), - task_name + escape(&task_name) ); } @@ -849,7 +877,7 @@ fn handle_command_dispatch( .map(|p| p.to_string_lossy().to_string()) .unwrap_or_else(|| ".meta / .meta.yaml / .meta.yml".to_string()); eprintln!("Error: Could not find meta config file '{config_name}'"); - eprintln!("Searched from {} up to root", current_dir.display()); + eprintln!("Searched from {} up to root", escape_path(¤t_dir)); std::process::exit(1); } }; @@ -858,7 +886,7 @@ fn handle_command_dispatch( if cli.verbose { println!("{}", "Verbose mode enabled".green()); - println!("Resolved config file path: {}", absolute_path.display()); + println!("Resolved config file path: {}", escape_path(&absolute_path)); println!("Executing command: {command_str}"); } @@ -898,7 +926,7 @@ fn handle_command_dispatch( // The walk reads the default config file; with --config, start from // the chosen one and walk only the nested meta repos tree = match cli.config { - Some(_) => walk_from(meta_dir, &meta_projects, depth), + Some(_) => config::walk_projects(meta_dir, &meta_projects, depth)?, None => config::walk_meta_tree(meta_dir, depth)?, }; project_paths = vec![meta_dir_str.clone()]; @@ -1020,15 +1048,17 @@ fn handle_plugin_command( if json { println!("{}", serde_json::to_string_pretty(&results)?); } else if results.is_empty() { - println!("No plugins found matching '{query}'"); + println!("No plugins found matching '{}'", escape(&query)); } else { println!("Found {} plugin(s):", results.len()); for plugin in results { println!( " {} v{} - {}", - plugin.name, plugin.version, plugin.description + escape(&plugin.name), + escape(&plugin.version), + escape(&plugin.description) ); - println!(" by {}", plugin.author); + println!(" by {}", escape(&plugin.author)); } } } @@ -1049,13 +1079,19 @@ fn handle_plugin_command( // Direct URL install let plugin_name = installer.install_from_url(&name)?; if !json { - println!("Successfully installed {plugin_name} to {location}"); + println!( + "Successfully installed {} to {location}", + escape(&plugin_name) + ); } } else if let Some(shorthand) = GitHubShorthand::parse(&name) { // GitHub shorthand install (user/repo[@version]) let plugin_name = installer.install_from_github(&shorthand)?; if !json { - println!("Successfully installed {plugin_name} to {location}"); + println!( + "Successfully installed {} to {location}", + escape(&plugin_name) + ); } } else { // Registry-based install @@ -1069,11 +1105,13 @@ fn handle_plugin_command( let plugin_name = installer.install_from_github(&shorthand)?; if !json { println!( - "Successfully installed {plugin_name} from {source} to {location}" + "Successfully installed {} from {} to {location}", + escape(&plugin_name), + escape(&source) ); } } else { - anyhow::bail!("Invalid plugin source in registry: {}", source); + anyhow::bail!("Invalid plugin source in registry: {}", escape(&source)); } } Err(_) => { @@ -1084,9 +1122,9 @@ fn handle_plugin_command( if !json { println!( "Successfully installed {} v{} ({}) to {location}", - metadata.name, - metadata.version, - installed.join(", ") + escape(&metadata.name), + escape(&metadata.version), + escape(&installed.join(", ")) ); } } @@ -1128,7 +1166,12 @@ fn handle_plugin_command( // 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); - println!("{:<12} {:<12} {}", name, version, path.display()); + println!( + "{:<12} {:<12} {}", + escape(name), + escape(version), + escape_path(&path) + ); } } } else { @@ -1156,7 +1199,12 @@ fn handle_plugin_command( println!("{:<12} {:<12} PATH", "NAME", "VERSION"); println!("{}", "-".repeat(70)); for (name, version, _, path) in &plugins { - println!("{:<12} {:<12} {}", name, version, path.display()); + println!( + "{:<12} {:<12} {}", + escape(name), + escape(version), + escape_path(path) + ); } } } @@ -1193,7 +1241,9 @@ fn handle_plugin_command( if !json { println!( "Update available for {}: {} → {}", - plugin_name, current, latest + escape(&plugin_name), + escape(¤t), + escape(&latest) ); } } else { @@ -1201,14 +1251,17 @@ fn handle_plugin_command( if !json { println!( "Successfully updated {} from {} to {} in {}", - updated, current, latest, location + escape(&updated), + escape(¤t), + escape(&latest), + escape(location) ); } } } None => { if !json { - println!("{} is already up to date", plugin_name); + println!("{} is already up to date", escape(&plugin_name)); } } } @@ -1236,7 +1289,12 @@ fn handle_plugin_command( if !json { println!("Updates available:"); for (name, current, latest) in &updates_available { - println!(" {} {} → {}", name, current, latest); + println!( + " {} {} → {}", + escape(name), + escape(current), + escape(latest) + ); } } } else { @@ -1244,19 +1302,32 @@ fn handle_plugin_command( match installer.update_plugin(name) { Ok(_) => { if !json { - println!("Updated {} from {} to {}", name, current, latest); + println!( + "Updated {} from {} to {}", + escape(name), + escape(current), + escape(latest) + ); } updated_count += 1; } Err(e) => { if !json { - eprintln!("Failed to update {}: {}", name, e); + eprintln!( + "Failed to update {}: {}", + escape(name), + escape_lines(&format!("{e:#}")) + ); } } } } if !json { - println!("\nUpdated {} plugin(s) in {}", updated_count, location); + println!( + "\nUpdated {} plugin(s) in {}", + updated_count, + escape(location) + ); } } } @@ -1385,8 +1456,8 @@ fn check_and_warn_orphan() { "{}: This meta repo is not tracked by its parent.", "warning".yellow().bold() ); - eprintln!(" Current: {}", warning.current.display()); - eprintln!(" Parent: {}", warning.parent.display()); + eprintln!(" Current: {}", escape_path(&warning.current)); + eprintln!(" Parent: {}", escape_path(&warning.parent)); eprintln!(); // Show format-appropriate syntax @@ -1396,18 +1467,18 @@ fn check_and_warn_orphan() { }; eprintln!( " To include it, add to {}/{}:", - warning.parent.display(), + escape_path(&warning.parent), config_file ); match warning.parent_format { ConfigFormat::Json => { eprintln!( " \"{}\": {{ \"repo\": \"\", \"meta\": true }}", - warning.suggested_key + escape(&warning.suggested_key) ); } ConfigFormat::Yaml => { - eprintln!(" {}:", warning.suggested_key); + eprintln!(" {}:", escape(&warning.suggested_key)); eprintln!(" repo: "); eprintln!(" meta: true"); } @@ -1416,53 +1487,6 @@ fn check_and_warn_orphan() { } } -/// The meta tree whose top level is `projects` (from the config the user -/// chose), walked the way `walk_meta_tree` walks the default config: nested -/// meta repos `depth` levels down, each directory expanded at most once. -fn walk_from( - meta_dir: &std::path::Path, - projects: &[ProjectInfo], - depth: Option, -) -> Vec { - fn walk( - dir: &std::path::Path, - projects: &[ProjectInfo], - depth: Option, - visited: &mut std::collections::HashSet, - ) -> Vec { - let mut nodes: Vec = projects - .iter() - .map(|project| { - let project_dir = dir.join(&project.path); - let config = find_meta_config(&project_dir, None).filter(|(path, _)| { - project_dir.is_dir() && path.parent() == Some(&project_dir) - }); - let canonical = project_dir.canonicalize().unwrap_or(project_dir.clone()); - let children = match &config { - Some((path, _)) if depth != Some(0) && visited.insert(canonical) => { - parse_meta_config(path) - .map(|(nested, _)| { - let depth = depth.map(|d| d.saturating_sub(1)); - walk(&project_dir, &nested, depth, visited) - }) - .unwrap_or_default() - } - _ => vec![], - }; - MetaTreeNode { - info: project.clone(), - is_meta: config.is_some(), - children, - } - }) - .collect(); - nodes.sort_by(|a, b| a.info.name.cmp(&b.info.name)); - nodes - } - let root = meta_dir.canonicalize().unwrap_or(meta_dir.to_path_buf()); - walk(meta_dir, projects, depth, &mut [root].into_iter().collect()) -} - /// Flatten a meta tree into path strings, optionally filtering by tag. /// If tag_filter is Some, only includes nodes whose tags match (and recurses into them). fn flatten_with_tag_filter(nodes: &[MetaTreeNode], tag_filter: &Option) -> Vec { @@ -1559,7 +1583,7 @@ mod tests { let api = &projects[0]; assert_eq!(api.name, "api"); - assert_eq!(api.path, "./services/api"); + assert_eq!(api.path, "services/api"); // normalized assert_eq!(api.repo.as_ref().unwrap(), "git@github.com:org/api.git"); assert_eq!(api.tags, vec!["backend", "rust"]); } @@ -1622,7 +1646,7 @@ ignore: ); let api = projects.iter().find(|p| p.name == "api").unwrap(); - assert_eq!(api.path, "./backend/api"); + assert_eq!(api.path, "backend/api"); // normalized assert_eq!(api.tags, vec!["backend", "python"]); assert_eq!(ignore, vec!["node_modules", "__pycache__"]); diff --git a/src/registry.rs b/src/registry.rs index adfaea6..347a8b5 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -6,6 +6,7 @@ use anyhow::{Context, Result}; use log::{debug, info}; +use meta_core::display::escape_path; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::Read; @@ -114,15 +115,36 @@ pub enum InstallScope { // Future: Custom(PathBuf) for --path flag in M5 } +/// Whether `e` means the path does not exist: not found, or a part of it +/// that is a file (`.meta/plugins` where `.meta` is the config file). +fn missing(e: &std::io::Error) -> bool { + matches!( + e.kind(), + std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory + ) +} + impl PluginManifest { /// Load manifest from file, or return empty manifest if not found pub fn load(manifest_path: &Path) -> Result { - if !manifest_path.exists() { - return Ok(Self::default()); + match std::fs::symlink_metadata(manifest_path) { + Err(e) if missing(&e) => return Ok(Self::default()), + Err(e) => { + return Err(e).with_context(|| { + format!("Cannot read manifest {}", escape_path(manifest_path)) + }) + } + // It names where each plugin is updated from, so another user + // must not be able to change it + Ok(_) => meta_core::data_dir::check_trusted_file(manifest_path)?, } - let content = std::fs::read_to_string(manifest_path) - .with_context(|| format!("Failed to read manifest from {}", manifest_path.display()))?; + let content = std::fs::read_to_string(manifest_path).with_context(|| { + format!( + "Failed to read manifest from {}", + escape_path(manifest_path) + ) + })?; let manifest: Self = serde_json::from_str(&content).with_context(|| "Failed to parse plugin manifest")?; @@ -132,13 +154,10 @@ impl PluginManifest { /// Save manifest to file pub fn save(&self, manifest_path: &Path) -> Result<()> { - let json = - serde_json::to_string_pretty(self).with_context(|| "Failed to serialize manifest")?; - - std::fs::write(manifest_path, json) - .with_context(|| format!("Failed to write manifest to {}", manifest_path.display()))?; - - Ok(()) + // Private (0600), like meta's other stores: load refuses a manifest + // others could change, so one written under umask 002 would refuse itself + meta_core::store::write_atomic(manifest_path, self) + .with_context(|| format!("Failed to write manifest to {}", escape_path(manifest_path))) } /// Add or update a plugin entry @@ -212,9 +231,31 @@ impl RegistryConfig { /// Load registry config from ~/.meta/config.yaml pub fn load() -> Result { let config_path = Self::config_path()?; - if config_path.exists() { - let content = std::fs::read_to_string(&config_path) - .with_context(|| format!("Failed to read {}", config_path.display()))?; + // Only a missing file means "use the default registry": one that + // can't be examined may list a private registry + let present = match std::fs::symlink_metadata(&config_path) { + Ok(_) => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(e) => { + return Err(e).with_context(|| { + format!( + "Cannot read {}", + meta_core::display::escape_path(&config_path) + ) + }) + } + }; + if present { + // It names where plugins are downloaded from. (A symlink, as + // dotfile managers make, is fine if nothing on the way is + // another user's.) + meta_core::data_dir::check_trusted_file(&config_path)?; + let content = std::fs::read_to_string(&config_path).with_context(|| { + format!( + "Failed to read {}", + meta_core::display::escape_path(&config_path) + ) + })?; let config: RegistryConfig = serde_yaml::from_str(&content) .with_context(|| "Failed to parse registry config")?; Ok(config) @@ -225,7 +266,7 @@ impl RegistryConfig { /// Get the config file path fn config_path() -> Result { - Ok(meta_core::meta_dir().join("config.yaml")) + Ok(meta_core::data_dir::private_meta_dir()?.join("config.yaml")) } /// Get list of registries (defaults to the public registry) @@ -248,7 +289,9 @@ pub struct RegistryClient { impl RegistryClient { /// Create a new registry client pub fn new(verbose: bool) -> Result { - let config = RegistryConfig::load().unwrap_or_default(); + // A config that is refused must not fall back to the default + // registry: it may list a private one with the same plugin names + let config = RegistryConfig::load()?; Ok(Self { registries: config.get_registries(), verbose, @@ -638,7 +681,7 @@ impl PluginInstaller { } // Check for legacy config files in current directory - if let Some((_config_path, _)) = find_meta_config_in(current) { + if let Some((_config_path, _)) = find_meta_config_in(current)? { return Ok(current.to_path_buf()); } @@ -663,12 +706,20 @@ impl PluginInstaller { /// Ensure the plugins directory exists fn ensure_plugins_dir(&self) -> Result<()> { - std::fs::create_dir_all(&self.plugins_dir).with_context(|| { - format!( - "Failed to create plugins directory: {}", - self.plugins_dir.display() - ) - }) + // Made 0700 (whatever the umask), then held to the private-dir rules + meta_core::data_dir::create_private_dir(&self.plugins_dir) + } + + /// Plugins are run from this directory and its manifest says where they + /// are updated from: like plugin discovery, refuse it when another user + /// owns it or can change it (or a directory on the way to it). + fn check_plugins_dir(&self) -> Result<()> { + match std::fs::symlink_metadata(&self.plugins_dir) { + // None there (in a workspace whose .meta is the config file, + // .meta/plugins is "not a directory"): no plugins + Err(e) if missing(&e) => Ok(()), + _ => meta_core::data_dir::check_private_dir(&self.plugins_dir), + } } /// Get the manifest file path @@ -678,6 +729,7 @@ impl PluginInstaller { /// Load the plugin manifest fn load_manifest(&self) -> Result { + self.check_plugins_dir()?; PluginManifest::load(&self.manifest_path()) } @@ -1057,10 +1109,12 @@ impl PluginInstaller { fn validate_plugin(&self, plugin_path: &Path) -> Result<()> { use std::process::Command; + // It is run: the same check as for any plugin meta runs + meta_core::data_dir::check_trusted_file(plugin_path)?; let output = Command::new(plugin_path) .arg("--meta-plugin-info") .output() - .with_context(|| format!("Failed to execute {}", plugin_path.display()))?; + .with_context(|| format!("Failed to execute {}", escape_path(plugin_path)))?; if !output.status.success() { anyhow::bail!( @@ -1123,13 +1177,16 @@ impl PluginInstaller { pub fn uninstall(&self, name: &str) -> Result<()> { let plugin_name = ensure_plugin_prefix(name); + // Refuse an untrusted dir before deleting anything in it + self.check_plugins_dir()?; let plugin_path = self.plugins_dir.join(&plugin_name); if plugin_path.exists() { + // The manifest is checked before anything is deleted + let mut manifest = self.load_manifest()?; std::fs::remove_file(&plugin_path) - .with_context(|| format!("Failed to remove {}", plugin_path.display()))?; + .with_context(|| format!("Failed to remove {}", escape_path(&plugin_path)))?; // Remove from manifest - let mut manifest = self.load_manifest()?; manifest.remove_plugin(&plugin_name); self.save_manifest(&manifest)?; @@ -1309,6 +1366,25 @@ mod tests { assert_eq!(registries[1], "https://another.registry.com"); } + #[cfg(unix)] + #[test] + fn test_plugins_dir_and_manifest_are_private_whatever_the_umask() { + // Load refuses a manifest or dir others could change, so meta must + // not create them group- or world-writable (umask 002) itself + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let installer = PluginInstaller { + plugins_dir: dir.path().join("plugins"), + verbose: false, + scope: InstallScope::Local, + }; + installer.save_manifest(&PluginManifest::default()).unwrap(); + let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&installer.plugins_dir), 0o700); + assert_eq!(mode(&installer.manifest_path()), 0o600); + assert!(installer.load_manifest().is_ok()); + } + #[test] fn test_plugin_installer_uninstall() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/repo_filter.rs b/src/repo_filter.rs index a245d17..760efc2 100644 --- a/src/repo_filter.rs +++ b/src/repo_filter.rs @@ -33,7 +33,7 @@ pub fn repo_names( /// [`repo_names`]) or by its whole path from `root` (`.` for the root; a /// trailing `/` is ignored), never by a part of either. A value starting with /// `./` is a path only. Repos are compared as directories, so excluding one -/// excludes every spelling of it (`api` and `libs/../api`). A value that names +/// excludes every spelling of it (`api`, `./api` and `api/`). A value that names /// none of `dirs` is an error, so a typo never runs a command in a repo it was /// meant to leave out; so is a value that names several repos, and a selection /// that leaves no repo. diff --git a/src/subprocess_plugins.rs b/src/subprocess_plugins.rs index 85c4eab..17754b3 100644 --- a/src/subprocess_plugins.rs +++ b/src/subprocess_plugins.rs @@ -4,6 +4,7 @@ //! This approach provides better isolation, language flexibility, and simpler debugging. use anyhow::{Context, Result}; +use meta_core::display::{escape, escape_lines, escape_path}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; @@ -45,18 +46,60 @@ impl SubprocessPluginManager { /// /// Discovery order (first match wins): /// 1. `.meta/plugins/` directories walking up from cwd (project-local) + /// + /// A plugin directory that another user owns or could write to is + /// skipped with a warning (see `meta_core::data_dir::check_private_dir`). /// 2. `~/.meta/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(); + // Plugin dirs refused below, resolved: a PATH entry may lead into one + let mut refused = std::collections::HashSet::new(); + + // ~/.meta/plugins/, when it exists, is refused if another user could + // write to it. The walk up from cwd passes through it from anywhere + // under $HOME, so a refused one is marked visited to keep that walk + // from running what it holds. No home, or no plugins dir, just means + // no global plugins. + let global_plugins = meta_core::meta_dir() + .ok() + .map(|dir| dir.join("plugins")) + .filter(|dir| dir.is_dir()) + .filter(|dir| match meta_core::data_dir::check_private_dir(dir) { + Ok(()) => true, + Err(e) => { + eprintln!( + "warning: skipping global plugins: {}", + escape_lines(&format!("{e:#}")) + ); + let resolved = dir.canonicalize().unwrap_or(dir.clone()); + visited.insert(resolved.clone()); + refused.insert(resolved); + false + } + }); // 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.exists() && plugin_dir.is_dir() && visited.insert(plugin_dir.clone()) { - self.scan_directory(&plugin_dir)?; + if plugin_dir.is_dir() + && visited.insert(plugin_dir.canonicalize().unwrap_or(plugin_dir.clone())) + { + // Plugins are run, so one that another user could have put + // there is skipped + match meta_core::data_dir::check_private_dir(&plugin_dir) { + Ok(()) => self.scan_directory(&plugin_dir, &mut refused)?, + Err(e) => { + eprintln!( + "warning: skipping plugins in {}: {}", + escape_path(&plugin_dir), + escape_lines(&format!("{e:#}")) + ); + refused.insert(plugin_dir.canonicalize().unwrap_or(plugin_dir.clone())); + } + } } if let Some(parent) = current_dir.parent() { current_dir = parent.to_path_buf(); @@ -66,17 +109,25 @@ impl SubprocessPluginManager { } // Search in ~/.meta/plugins/ (global installed) - if let Ok(global_plugins) = meta_core::data_dir::data_subdir("plugins") { - if global_plugins.exists() && visited.insert(global_plugins.clone()) { - self.scan_directory(&global_plugins)?; + if let Some(global_plugins) = global_plugins { + if visited.insert( + global_plugins + .canonicalize() + .unwrap_or(global_plugins.clone()), + ) { + self.scan_directory(&global_plugins, &mut refused)?; } } // Search in PATH for meta-* executables (bundled/system) if let Ok(path_var) = std::env::var("PATH") { for path_dir in std::env::split_paths(&path_var) { - if path_dir.exists() && visited.insert(path_dir.clone()) { - self.scan_path_directory(&path_dir)?; + // Compared resolved, like the plugin dirs above: a PATH entry + // that links to a refused plugin dir must not bring it back + if path_dir.exists() + && visited.insert(path_dir.canonicalize().unwrap_or(path_dir.clone())) + { + self.scan_path_directory(&path_dir, &refused)?; } } } @@ -85,9 +136,13 @@ impl SubprocessPluginManager { } /// Scan a .meta-plugins directory for plugin executables - fn scan_directory(&mut self, dir: &Path) -> Result<()> { + fn scan_directory( + &mut self, + dir: &Path, + refused: &mut std::collections::HashSet, + ) -> Result<()> { if self.verbose { - println!("Scanning for subprocess plugins in: {}", dir.display()); + println!("Scanning for subprocess plugins in: {}", escape_path(dir)); } for entry in std::fs::read_dir(dir)? { @@ -100,22 +155,48 @@ impl SubprocessPluginManager { && !name.ends_with(".dylib") && !name.ends_with(".so") && !name.ends_with(".dll") + && is_executable(&path) { - self.try_load_plugin(&path)?; + // It is run: skip it if another user could have changed it + match meta_core::data_dir::check_trusted_file(&path) { + Ok(()) => self.try_load_plugin(&path)?, + Err(e) => { + eprintln!( + "warning: skipping plugin {}: {}", + escape_path(&path), + escape_lines(&format!("{e:#}")) + ); + refused.insert(path.canonicalize().unwrap_or(path.clone())); + } + } } } } Ok(()) } - /// Scan a PATH directory for meta-* executables - fn scan_path_directory(&mut self, dir: &Path) -> Result<()> { + /// Scan a PATH directory for meta-* executables. PATH is the user's own + /// choice (it is where meta and git come from too), so only a program + /// that leads into a plugin dir or file refused above, through any of + /// its links, is skipped. + fn scan_path_directory( + &mut self, + dir: &Path, + refused: &std::collections::HashSet, + ) -> Result<()> { if let Ok(entries) = std::fs::read_dir(dir) { for entry in entries.flatten() { let path = entry.path(); if let Some(name) = path.file_name().and_then(|n| n.to_str()) { if name.starts_with("meta-") && is_executable(&path) { - self.try_load_plugin(&path)?; + if leads_into_refused(&path, refused) { + eprintln!( + "warning: skipping plugin {}: it links into a refused plugin directory", + escape_path(&path) + ); + } else { + self.try_load_plugin(&path)?; + } } } } @@ -148,9 +229,9 @@ impl SubprocessPluginManager { if self.verbose { println!( " Found plugin: {} v{} ({})", - info.name, - info.version, - path.display() + escape(&info.name), + escape(&info.version), + escape_path(path) ); } @@ -259,7 +340,7 @@ impl SubprocessPluginManager { .stdout(Stdio::piped()) // Capture stdout to parse response .stderr(Stdio::inherit()) // Let stderr pass through for error messages .spawn() - .with_context(|| format!("Failed to execute plugin {}", plugin.path.display()))?; + .with_context(|| format!("Failed to execute plugin {}", escape_path(&plugin.path)))?; // Send request to plugin's stdin if let Some(mut stdin) = child.stdin.take() { @@ -270,7 +351,10 @@ impl SubprocessPluginManager { let output = child.wait_with_output()?; if !output.status.success() { - // Plugin already printed its error to stderr, just propagate the exit code + // 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)); std::process::exit(output.status.code().unwrap_or(1)); } @@ -642,6 +726,72 @@ impl SubprocessPluginManager { } /// Check if a file is executable +/// Whether running `path` would pass through a refused plugin dir or file. +/// The path is resolved one component at a time, following each symlink +/// where it is met (a directory link as well as the program's own), and +/// every location on the way is checked: one at or below a refused dir, or +/// a refused file, counts. More than 40 links count as well. +fn leads_into_refused(path: &Path, refused: &std::collections::HashSet) -> bool { + use std::path::Component; + // A location as canonicalize writes it (refused entries are written so), + // without resolving a link at its last component + let located = |at: &Path| match (at.parent(), at.file_name()) { + (Some(dir), Some(name)) => dir.canonicalize().ok().map(|dir| dir.join(name)), + _ => at.canonicalize().ok(), + }; + let held = |at: &Path| located(at).is_some_and(|at| refused.iter().any(|r| at.starts_with(r))); + // From the absolute path, so a relative PATH entry's `..` is resolved + // against where it really leads + let absolute = match std::env::current_dir() { + Ok(cwd) => cwd.join(path), + Err(_) => return true, + }; + let mut pending: std::collections::VecDeque = absolute + .components() + .map(|c| PathBuf::from(c.as_os_str())) + .collect(); + let mut current = PathBuf::new(); + let mut links = 0; + while let Some(part) = pending.pop_front() { + match part.components().next() { + Some(Component::Prefix(_)) | Some(Component::RootDir) => current.push(&part), + Some(Component::CurDir) | None => {} + Some(Component::ParentDir) => { + current.pop(); + } + Some(Component::Normal(name)) => { + let next = current.join(name); + if held(&next) { + return true; + } + match std::fs::symlink_metadata(&next) { + Ok(meta) if meta.file_type().is_symlink() => { + links += 1; + let Ok(target) = std::fs::read_link(&next) else { + return true; + }; + if links > 40 { + return true; + } + // The target's parts go first; an absolute one + // starts again from its root + if target.has_root() { + current = PathBuf::new(); + } + for (k, c) in target.components().enumerate() { + pending.insert(k, PathBuf::from(c.as_os_str())); + } + } + Ok(_) => current = next, + // Not there: nothing to run through it + Err(_) => return false, + } + } + } + } + false +} + #[cfg(unix)] fn is_executable(path: &Path) -> bool { use std::os::unix::fs::PermissionsExt; diff --git a/src/worktree.rs b/src/worktree.rs index cd81704..db6b3d6 100644 --- a/src/worktree.rs +++ b/src/worktree.rs @@ -6,6 +6,7 @@ //! for worktree management commands. use anyhow::{Context, Result}; +use meta_core::display::{escape_lines, escape_path}; use serde::Serialize; use std::path::{Path, PathBuf}; @@ -132,7 +133,11 @@ fn discover_repos_recursive( let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, Err(e) => { - log::debug!("Skipping unreadable directory {}: {e}", dir.display()); + log::debug!( + "Skipping unreadable directory {}: {}", + escape_path(dir), + escape_lines(&format!("{e:#}")) + ); return Ok(()); } }; @@ -162,7 +167,11 @@ fn discover_repos_recursive( let source = match source_repo_from_gitfile(&sub_git) { Ok(s) => s, Err(e) => { - log::debug!("Skipping {}: {e}", sub_path.display()); + log::debug!( + "Skipping {}: {}", + escape_path(&sub_path), + escape_lines(&format!("{e:#}")) + ); continue; } }; @@ -179,7 +188,11 @@ fn discover_repos_recursive( } else { // Not a repo — recurse into intermediate directory if let Err(e) = discover_repos_recursive(root, &sub_path, repos) { - log::debug!("Skipping subtree {}: {e}", sub_path.display()); + log::debug!( + "Skipping subtree {}: {}", + escape_path(&sub_path), + escape_lines(&format!("{e:#}")) + ); } } } @@ -221,7 +234,7 @@ pub fn discover_worktree_members_recursive(task_dir: &Path) -> Result Result metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, Err(error) => { - return Err(error).with_context(|| format!("Cannot inspect {}", git_file.display())) + return Err(error) + .with_context(|| format!("Cannot inspect {}", escape_path(&git_file))) } }; if !metadata.is_file() { @@ -261,30 +275,30 @@ fn validate_worktree_gitfile(git_file: &Path) -> Result<()> { let target = content .trim() .strip_prefix("gitdir: ") - .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", git_file.display()))?; + .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", escape_path(git_file)))?; let admin = git_file .parent() .unwrap_or(Path::new(".")) .join(target) .canonicalize() - .with_context(|| format!("Missing worktree metadata for {}", git_file.display()))?; + .with_context(|| format!("Missing worktree metadata for {}", escape_path(git_file)))?; anyhow::ensure!( admin.join("HEAD").is_file(), "Missing worktree HEAD at {}", - admin.display() + escape_path(&admin) ); let common = std::fs::read_to_string(admin.join("commondir"))?; let common = admin.join(common.trim()).canonicalize()?; anyhow::ensure!( common.join("HEAD").is_file() && common.join("objects").is_dir(), "Incomplete common Git metadata at {}", - common.display() + escape_path(&common) ); let backlink = std::fs::read_to_string(admin.join("gitdir"))?; anyhow::ensure!( admin.join(backlink.trim()).canonicalize()? == git_file.canonicalize()?, "Worktree metadata backlink does not match {}", - git_file.display() + escape_path(git_file) ); Ok(()) } @@ -293,12 +307,12 @@ fn validate_worktree_gitfile(git_file: &Path) -> Result<()> { /// .git file contains: "gitdir: /path/to/primary/.git/worktrees/" fn source_repo_from_gitfile(git_file: &Path) -> Result { let content = std::fs::read_to_string(git_file) - .with_context(|| format!("Failed to read .git file at {}", git_file.display()))?; + .with_context(|| format!("Failed to read .git file at {}", escape_path(git_file)))?; let gitdir = content .trim() .strip_prefix("gitdir: ") - .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", git_file.display()))?; + .ok_or_else(|| anyhow::anyhow!("Invalid .git file format at {}", escape_path(git_file)))?; // gitdir points to: /path/to/primary/.git/worktrees/ // We need: /path/to/primary/ @@ -311,7 +325,7 @@ fn source_repo_from_gitfile(git_file: &Path) -> Result { .unwrap_or(Path::new(".")) .join(gitdir_path) .canonicalize() - .with_context(|| format!("Cannot resolve gitdir from {}", git_file.display()))? + .with_context(|| format!("Cannot resolve gitdir from {}", escape_path(git_file)))? }; // Walk up: worktrees/ -> .git -> repo root let dot_git_dir = gitdir_path @@ -323,7 +337,7 @@ fn source_repo_from_gitfile(git_file: &Path) -> Result { let repo_root = dot_git_dir.parent().ok_or_else(|| { anyhow::anyhow!( "Cannot find repo root from .git dir: {}", - dot_git_dir.display() + escape_path(dot_git_dir) ) })?;