diff --git a/src/worktree/git_ops.rs b/src/worktree/git_ops.rs index aec863b..aa8a5e6 100644 --- a/src/worktree/git_ops.rs +++ b/src/worktree/git_ops.rs @@ -68,7 +68,7 @@ fn ensure_checkout_config_is_not_bare(repo_path: &Path) -> Result<()> { anyhow::bail!( "Failed to inspect core.bare for '{}': {}", escape_path(repo_path), - stderr.trim() + escape(stderr.trim()) ); } @@ -106,9 +106,9 @@ pub fn git_worktree_add( anyhow::bail!( "git worktree add failed for '{}' (branch: {}, ref: {}): {}", escape_path(repo_path), - branch, - ref_name, - stderr.trim() + escape(branch), + escape(ref_name), + escape(stderr.trim()) ); } return Ok(Some(start)); // Always creates a new branch from ref @@ -155,8 +155,8 @@ pub fn git_worktree_add( anyhow::bail!( "git worktree add failed for '{}' (branch: {}): {}", escape_path(repo_path), - branch, - stderr.trim() + escape(branch), + escape(stderr.trim()) ); } @@ -177,7 +177,7 @@ pub fn git_worktree_remove(repo_path: &Path, worktree_path: &Path, force: bool) if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); - anyhow::bail!("git worktree remove failed: {}", stderr.trim()); + anyhow::bail!("git worktree remove failed: {}", escape(stderr.trim())); } Ok(()) } @@ -194,7 +194,7 @@ pub fn git_status_summary(repo_path: &Path) -> Result { anyhow::bail!( "git status failed for '{}': {}", escape_path(repo_path), - stderr.trim() + escape(stderr.trim()) ); } @@ -337,9 +337,10 @@ pub fn git_rev_parse(repo_path: &Path, rev: &str) -> Result> { return Ok(None); } anyhow::bail!( - "git rev-parse {rev} failed in {}: {}", + "git rev-parse {} failed in {}: {}", + escape(rev), escape_path(repo_path), - stderr.trim() + escape(stderr.trim()) ) } @@ -352,7 +353,7 @@ pub fn git_rev_parse(repo_path: &Path, rev: &str) -> Result> { /// can't read is an error, not "free". pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { let full = format!("refs/heads/{branch}"); - let in_use = |by: &str| anyhow::anyhow!("'{branch}' is {by}"); + let in_use = |by: &str| anyhow::anyhow!("'{}' is {by}", escape(branch)); // A symbolic branch would carry a ref transaction to the branch it points // at, which this check never looked at. @@ -363,8 +364,9 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { Some(1) => {} Some(0) => return Err(in_use("a symbolic ref; meta only moves plain branches")), _ => anyhow::bail!( - "Cannot inspect '{branch}': {}", - String::from_utf8_lossy(&symbolic.stderr).trim() + "Cannot inspect '{}': {}", + escape(branch), + escape(String::from_utf8_lossy(&symbolic.stderr).trim()) ), } @@ -375,7 +377,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { list.status.success(), "Cannot list the worktrees of {}: {}", escape_path(repo_path), - String::from_utf8_lossy(&list.stderr).trim() + escape(String::from_utf8_lossy(&list.stderr).trim()) ); let wanted = format!("branch {full}"); if String::from_utf8_lossy(&list.stdout) @@ -392,7 +394,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { output.status.success(), "Cannot find the git directory of {}: {}", escape_path(repo_path), - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); // Relative output is relative to the repository, where git ran. let common = @@ -453,7 +455,7 @@ pub fn git_branch_is_free(repo_path: &Path, branch: &str) -> Result<()> { /// through git's ref transaction. pub fn git_delete_branch_at(repo_path: &Path, branch: &str, expected: &str) -> Result<()> { git_branch_is_free(repo_path, branch) - .map_err(|e| anyhow::anyhow!("Branch '{branch}' is in use; kept ({e})"))?; + .map_err(|e| anyhow::anyhow!("Branch '{}' is in use; kept ({e})", escape(branch)))?; let output = git_command(repo_path) .args([ "update-ref", @@ -466,8 +468,9 @@ pub fn git_delete_branch_at(repo_path: &Path, branch: &str, expected: &str) -> R if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!( - "Branch '{branch}' no longer points where it was created; kept ({})", - stderr.trim() + "Branch '{}' no longer points where it was created; kept ({})", + escape(branch), + escape(stderr.trim()) ); } // Upstream settings of a deleted branch; there may be none. @@ -486,7 +489,11 @@ pub fn git_fetch_branch(repo_path: &Path, branch: &str) -> Result<()> { if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); - anyhow::bail!("Failed to fetch branch '{}': {}", branch, stderr.trim()); + anyhow::bail!( + "Failed to fetch branch '{}': {}", + escape(branch), + escape(stderr.trim()) + ); } Ok(()) } @@ -496,6 +503,21 @@ mod tests { use super::*; use std::collections::BTreeSet; + #[test] + fn a_failed_fetch_is_reported_on_one_line() { + let tmp = init_git_repo(); + git_command(tmp.path()) + .args(["remote", "add", "origin", "/nonexistent/r\u{1b}[2J\nFORGED"]) + .status() + .unwrap(); + let err = git_fetch_branch(tmp.path(), "b\u{1b}[2J\nFORGED").unwrap_err(); + let message = format!("{err:#}"); + assert!( + !message.contains('\n') && !message.contains('\u{1b}'), + "{message}" + ); + } + /// Create a minimal git repo in a tempdir and return the tempdir handle. fn init_git_repo() -> tempfile::TempDir { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/worktree/helpers.rs b/src/worktree/helpers.rs index 2b40b3f..a67321b 100644 --- a/src/worktree/helpers.rs +++ b/src/worktree/helpers.rs @@ -1,7 +1,8 @@ //! Utility functions for worktree management. use anyhow::{Context, Result}; -use meta_core::display::escape_path; +use meta_core::config::ConfigFormat; +use meta_core::display::{escape, escape_path}; use std::path::{Path, PathBuf}; use super::types::WorktreeContext; @@ -10,17 +11,18 @@ pub fn validate_worktree_name(name: &str) -> Result<()> { if name.is_empty() { anyhow::bail!("Worktree name cannot be empty"); } + let shown = escape(name); if name.starts_with('.') { - anyhow::bail!("Invalid worktree name '{name}': cannot start with '.'"); + anyhow::bail!("Invalid worktree name '{shown}': cannot start with '.'"); } if name.contains('/') || name.contains('\\') { - anyhow::bail!("Invalid worktree name '{name}': cannot contain path separators"); + anyhow::bail!("Invalid worktree name '{shown}': cannot contain path separators"); } if !name .chars() .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { - anyhow::bail!("Invalid worktree name '{name}': only ASCII alphanumeric characters, hyphens, and underscores allowed"); + anyhow::bail!("Invalid worktree name '{shown}': only ASCII alphanumeric characters, hyphens, and underscores allowed"); } Ok(()) } @@ -30,15 +32,17 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { if let Ok(env_path) = std::env::var("META_WORKTREES") { return Ok(PathBuf::from(env_path)); } - // 2. Check worktrees_dir in .meta config - if let Some(dir) = meta_dir { + // 2. Check worktrees_dir in .meta config. In a worktree set, of the + // checkout it stands for: its sets live where that one's do + if let Some(dir) = meta_dir.map(owner_dir) { + let dir = dir.as_path(); // The config's rules for the worktree directory (inside the // workspace, not inside a project, not into .git) hold here too, // whoever ran this plugin if let Some((config, _)) = meta_core::config::find_meta_config_in(dir)? { meta_core::config::parse_meta_config(&config)?; } - if let Some(configured) = read_worktrees_dir_from_config(dir) { + if let Some(configured) = read_worktrees_dir_from_config(dir)? { // Worktrees are created and removed there, so a committed config // may not point it outside the workspace let relative = meta_core::config::relative_dir(dir, &configured).map_err(|why| { @@ -67,49 +71,41 @@ pub fn resolve_worktree_root(meta_dir: Option<&Path>) -> Result { Ok(cwd.join(".worktrees")) } -/// Read and parse the .meta config as a JSON Value. -/// Tries .meta, .meta.json, .meta.yaml, .meta.yml in order, parsing JSON or YAML as appropriate. -pub fn read_meta_config_value(meta_dir: &Path) -> Option { - for name in &[".meta", ".meta.json", ".meta.yaml", ".meta.yml"] { - let path = meta_dir.join(name); - if !path.exists() || !path.is_file() { - continue; - } - let content = match std::fs::read_to_string(&path) { - Ok(c) => c, - Err(_) => continue, - }; - // Try JSON first - if let Ok(v) = serde_json::from_str::(&content) { - return Some(v); - } - // Try YAML - if let Ok(v) = serde_yaml_ng::from_str::(&content) { - // Convert YAML Value to JSON Value for uniform access - if let Ok(json_val) = serde_json::to_value(v) { - return Some(json_val); - } - } - } - None +/// The config file in `meta_dir` (see +/// [`meta_core::config::find_meta_config_in`]) as a JSON value, if there is +/// one. One that can't be read or parsed is an error. +pub fn read_meta_config_value(meta_dir: &Path) -> Result> { + let Some((path, format)) = meta_core::config::find_meta_config_in(meta_dir)? else { + return Ok(None); + }; + let content = std::fs::read_to_string(&path) + .with_context(|| format!("Cannot read {}", escape_path(&path)))?; + let value = match format { + ConfigFormat::Json => serde_json::from_str(&content).map_err(anyhow::Error::from), + ConfigFormat::Yaml => serde_yaml_ng::from_str::(&content) + .map_err(anyhow::Error::from) + .and_then(|v| serde_json::to_value(v).map_err(anyhow::Error::from)), + }; + value + .map(Some) + .with_context(|| format!("Cannot parse {}", escape_path(&path))) } -pub fn read_worktrees_dir_from_config(meta_dir: &Path) -> Option { - read_meta_config_value(meta_dir)? - .get("worktrees_dir") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()) +pub fn read_worktrees_dir_from_config(meta_dir: &Path) -> Result> { + Ok(read_meta_config_value(meta_dir)? + .and_then(|config| config.get("worktrees_dir")?.as_str().map(str::to_string))) } pub fn find_meta_dir() -> Option { let cwd = std::env::current_dir().ok()?; - meta_core::config::find_meta_config(&cwd, None) - .map(|(path, _)| path.parent().unwrap_or(Path::new(".")).to_path_buf()) + meta_core::config::nearest_meta_dir(&cwd).ok().flatten() } /// Like `find_meta_dir()` but returns an error if not found. pub fn require_meta_dir() -> Result { - find_meta_dir().ok_or_else(|| anyhow::anyhow!("Not inside a meta project (no .meta found)")) + let cwd = std::env::current_dir()?; + meta_core::config::nearest_meta_dir(&cwd)? + .ok_or_else(|| anyhow::anyhow!("Not inside a meta project (no .meta found)")) } /// The directory of the worktree set `name` under `worktree_root`. A symlink @@ -155,6 +151,7 @@ pub fn resolve_worktree_context(name: &str) -> Result { /// Resolve worktree context and verify the worktree exists. pub fn resolve_existing_worktree(name: &str) -> Result { + validate_worktree_name(name)?; let ctx = resolve_worktree_context(name)?; if !ctx.wt_dir.exists() { anyhow::bail!( @@ -175,14 +172,14 @@ pub fn discover_and_validate_worktree( let ctx = resolve_existing_worktree(name)?; let repos = meta_cli::worktree::discover_worktree_repos(&ctx.wt_dir)?; if repos.is_empty() { - anyhow::bail!("No repos found in worktree '{name}'"); + anyhow::bail!("No repos found in worktree '{}'", escape(name)); } Ok(repos) } /// Load and parse the .meta config, returning the project list. pub fn load_projects(meta_dir: &Path) -> Result> { - let (config_path, _) = meta_core::config::find_meta_config(meta_dir, None) + let (config_path, _) = meta_core::config::find_meta_config(meta_dir, None)? .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", escape_path(meta_dir)))?; let (projects, _) = meta_core::config::parse_meta_config(&config_path)?; Ok(projects) @@ -232,12 +229,62 @@ pub fn lookup_project<'a>( let valid: Vec<&str> = projects.iter().map(|p| p.name.as_str()).collect(); anyhow::anyhow!( "Unknown repo alias: '{}'. Valid aliases: {}", - alias, - valid.join(", ") + escape(alias), + escape(&valid.join(", ")) ) }) } +/// The meta directory whose sets and settings (such as hooks) `meta_dir`'s +/// are: inside a set, the checkout the set stands for, which outlives it. +pub fn owner_dir(meta_dir: &Path) -> PathBuf { + meta_core::config::set_source(meta_dir) + .filter(|source| source.is_dir()) + .unwrap_or_else(|| meta_dir.to_path_buf()) +} + +/// Where the repo at `source`, found from `meta_dir` under `alias`, goes in +/// a worktree set: its path from the meta dir, so a set lays its repos out +/// as the workspace does (its copied config stays right, and relative +/// references between repos, such as Cargo workspace members, hold). The +/// alias stands in for a source outside the meta dir. +pub fn place_in_set(meta_dir: &Path, alias: &str, source: &Path) -> String { + // The configured path, as written (a link inside the workspace stays the + // link); resolved only when the two are spelled differently + let resolve = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); + source + .strip_prefix(meta_dir) + .map(Path::to_path_buf) + .or_else(|_| { + resolve(source) + .strip_prefix(resolve(meta_dir)) + .map(Path::to_path_buf) + }) + .ok() + .filter(|place| !place.as_os_str().is_empty()) + .map(|place| { + place + .components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/") + }) + .unwrap_or_else(|| alias.to_string()) +} + +/// Where the repo placed at `place` is checked out in the set at `wt_dir`: +/// there, or where a link a checkout already put there leads, as in the +/// workspace. Refused when a link leads outside the set. +pub fn dest_in_set(wt_dir: &Path, place: &str) -> Result { + let resolved = meta_core::config::resolve_inside(wt_dir, place)?; + let plain = wt_dir.canonicalize().map(|dir| dir.join(place)).ok(); + Ok(if plain.as_ref() == Some(&resolved) { + wt_dir.join(place) + } else { + resolved + }) +} + /// Look up a project by alias, supporting nested paths like "vendor/tree-sitter-markdown". /// /// For simple aliases (no `/`), uses flat lookup from the current .meta. @@ -260,13 +307,13 @@ pub fn lookup_nested_project( let mut valid_paths: Vec<_> = project_map.keys().collect(); valid_paths.sort(); anyhow::anyhow!( - "Unknown nested repo: '{}'. Valid nested paths:\n {}", - alias, + "Unknown nested repo: '{}'. Valid nested paths: {}", + escape(alias), valid_paths .into_iter() - .cloned() + .map(|path| escape(path)) .collect::>() - .join("\n ") + .join(", ") ) }) } else { @@ -310,18 +357,22 @@ pub fn parse_duration(s: &str) -> Result { "d" => 86400, "w" => 604800, _ => anyhow::bail!( - "Invalid duration suffix '{suffix}'. Use s (seconds), m (minutes), h (hours), d (days), or w (weeks)" + "Invalid duration suffix '{}'. Use s (seconds), m (minutes), h (hours), d (days), or w (weeks)", + escape(suffix) ), }; (num_str, multiplier) }; - let num: u64 = num_str - .parse() - .with_context(|| format!("Invalid duration number: '{num_str}'"))?; + let num: u64 = num_str.parse().with_context(|| { + format!( + "Invalid duration '{}': use a number with an optional s, m, h, d or w suffix", + escape(s) + ) + })?; num.checked_mul(multiplier) .filter(|secs| i64::try_from(*secs).is_ok()) - .ok_or_else(|| anyhow::anyhow!("Duration '{s}' is too large")) + .ok_or_else(|| anyhow::anyhow!("Duration '{}' is too large", escape(s))) } /// Format seconds into a human-friendly duration string. @@ -354,17 +405,23 @@ pub fn resolve_from_pr(from_pr: &str) -> Result<(String, u32, String)> { // Parse format: owner/repo#N let hash_pos = from_pr.rfind('#').ok_or_else(|| { - anyhow::anyhow!("Invalid --from-pr format: '{from_pr}'. Expected: owner/repo#N") + anyhow::anyhow!( + "Invalid --from-pr format: '{}'. Expected: owner/repo#N", + escape(from_pr) + ) })?; let repo_spec = &from_pr[..hash_pos]; // Validate repo spec format: must be owner/repo if !repo_spec.contains('/') || repo_spec.starts_with('/') || repo_spec.ends_with('/') { - anyhow::bail!("Invalid repo spec '{repo_spec}' in --from-pr. Expected: owner/repo#N"); + anyhow::bail!( + "Invalid repo spec '{}' in --from-pr. Expected: owner/repo#N", + escape(repo_spec) + ); } let pr_num: u32 = from_pr[hash_pos + 1..] .parse() - .with_context(|| format!("Invalid PR number in '{from_pr}'"))?; + .with_context(|| format!("Invalid PR number in '{}'", escape(from_pr)))?; // Resolve head branch via gh CLI let output = Command::new("gh") @@ -387,14 +444,17 @@ pub fn resolve_from_pr(from_pr: &str) -> Result<(String, u32, String)> { anyhow::bail!( "Failed to resolve PR #{} in {}: {}", pr_num, - repo_spec, - stderr.trim() + escape(repo_spec), + escape(stderr.trim()) ); } let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); if branch.is_empty() { - anyhow::bail!("Empty head branch for PR #{pr_num} in {repo_spec}"); + anyhow::bail!( + "Empty head branch for PR #{pr_num} in {}", + escape(repo_spec) + ); } Ok((repo_spec.to_string(), pr_num, branch)) @@ -513,6 +573,59 @@ mod tests { assert!(err.to_string().contains("only ASCII alphanumeric")); } + /// A user-given name in an error is shown escaped, so the error stays + /// one line with no control characters. + fn assert_escaped(err: anyhow::Error) { + let err = err.to_string(); + assert!(!err.contains('\n') && !err.contains('\x1b'), "{err:?}"); + } + + #[test] + fn from_pr_errors_escape_the_spec() { + for spec in ["o/r#1\u{1b}[2J\nFORGED", "bad\u{1b}[2J\nFORGED"] { + let message = format!("{:#}", resolve_from_pr(spec).unwrap_err()); + assert!( + !message.contains('\n') && !message.contains('\u{1b}'), + "{message}" + ); + } + } + + #[test] + fn errors_escape_the_names_they_show() { + for name in [ + "bad\nFORGED", + ".bad\nFORGED", + "a/\x1b]0;x\x07", + "bad\x1b[2J", + ] { + assert_escaped(validate_worktree_name(name).unwrap_err()); + } + + let projects = [meta_core::config::ProjectInfo { + name: "odd\x1b[2J".to_string(), + path: "odd".to_string(), + repo: None, + tags: vec![], + provides: vec![], + depends_on: vec![], + meta: false, + }]; + let err = lookup_project(&projects, "a\nFORGED").unwrap_err(); + assert!(err.to_string().contains("'a\\nFORGED'"), "{err}"); + assert_escaped(err); + + let tmp = tempfile::tempdir().unwrap(); + std::fs::write( + tmp.path().join(".meta"), + r#"{"projects": {"vendor": {"repo": "git@github.com:org/vendor.git", "meta": true}}}"#, + ) + .unwrap(); + for alias in ["a\nFORGED", "vendor/\nFORGED", "vendor/\x1b[2J"] { + assert_escaped(lookup_nested_project(tmp.path(), alias).unwrap_err()); + } + } + // ── parse_duration ────────────────────────────────────── #[test] diff --git a/src/worktree/hooks.rs b/src/worktree/hooks.rs index 23b6cf8..da1465f 100644 --- a/src/worktree/hooks.rs +++ b/src/worktree/hooks.rs @@ -21,8 +21,15 @@ pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir }; let config = match read_meta_config_value(dir) { - Some(c) => c, - None => return, + Ok(Some(c)) => c, + Ok(None) => return, + Err(e) => { + log::warn!( + "Hook '{hook_name}' not run: {}", + meta_core::display::escape_lines(&format!("{e:#}")) + ); + return; + } }; let hook_cmd = config @@ -41,8 +48,11 @@ pub fn fire_worktree_hook(hook_name: &str, payload: &serde_json::Value, meta_dir Err(_) => return, }; + // From the directory whose config names the hook: a set removed from + // inside it takes the caller's directory with it let result = Command::new("sh") .args(["-c", cmd_str]) + .current_dir(dir) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::inherit()) diff --git a/src/worktree/mod.rs b/src/worktree/mod.rs index ec02b17..93afceb 100644 --- a/src/worktree/mod.rs +++ b/src/worktree/mod.rs @@ -9,6 +9,7 @@ pub mod hooks; pub mod record; pub mod safety; pub mod types; +pub mod workspace; // Re-export commonly-used types pub use types::RepoSpec; diff --git a/src/worktree/record.rs b/src/worktree/record.rs index 738e710..3c83e7d 100644 --- a/src/worktree/record.rs +++ b/src/worktree/record.rs @@ -14,7 +14,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; /// The record's file name inside a worktree's admin directory. -pub const RECORD_FILE: &str = "meta-worktree.json"; +pub const RECORD_FILE: &str = meta_core::config::WORKTREE_RECORD_FILE; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SetRecord { diff --git a/src/worktree/safety.rs b/src/worktree/safety.rs index 876f44c..bfac413 100644 --- a/src/worktree/safety.rs +++ b/src/worktree/safety.rs @@ -37,6 +37,12 @@ pub struct RemovalCheck { /// as a proof of ownership; a create rolling back the set it just /// claimed needs no such proof. pub unusable_records: Vec, + /// Worktrees without a record in a set whose other worktrees have one + /// (part of `blockers`): meta didn't make them, so it doesn't delete + /// them. A create rolling back may not have recorded every worktree yet. + pub missing_records: Vec, + /// The members whose record can't be used. + unusable_members: Vec, /// Each checkout's complete git status, stranded commit ids, and the size /// and modification time of every file `unsaved` lists, so a re-check /// sees changes the abbreviated lines would hide, rewrites included. @@ -64,8 +70,9 @@ impl RemovalCheck { /// as unsaved: uncommitted or untracked changes, commits that no branch, tag /// or remote ref holds, and files that no repository holds. Ignored files count as disposable, as /// they do for `git worktree remove`. Blocks on a worktree whose record -/// (see [`record`]) names another set, such as a set nested in this one, or -/// whose record can't be read. +/// (see [`record`]) names another set, such as a set nested in this one, +/// whose record can't be read, or that has no record while another worktree +/// of the set has one. pub fn check_worktree_removal(wt_dir: &Path) -> Result { let mut check = RemovalCheck::default(); if wt_dir.symlink_metadata().is_ok_and(|m| m.is_symlink()) { @@ -95,7 +102,6 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { scan(&set, wt_dir, root_owned, &mut loose, &mut check)?; // A stable order, so two checks of an unchanged set compare equal. check.members.sort_by(|a, b| a.path.cmp(&b.path)); - check.blockers.sort(); loose.sort(); // Another set's records are blockers already @@ -110,7 +116,22 @@ pub fn check_worktree_removal(wt_dir: &Path) -> Result { escape_path(wt_dir) )); } + let missing: Vec = check + .members + .iter() + .filter(|m| m.record.is_none() && !check.unusable_members.contains(&m.path)) + .map(|m| { + format!( + "{}: meta has no record of creating it (made by hand, or its record was \ + deleted); run 'git worktree remove' on it first", + relative_label(wt_dir, &m.path) + ) + }) + .collect(); + check.blockers.extend(missing.iter().cloned()); + check.missing_records = missing; } + check.blockers.sort(); let paths: Vec = check.members.iter().map(|m| m.path.clone()).collect(); for member in &paths { @@ -246,6 +267,7 @@ fn add_member( ); check.unusable_records.push(why.clone()); check.blockers.push(why); + check.unusable_members.push(path.to_path_buf()); None } }; @@ -446,7 +468,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String anyhow::ensure!( output.status.success(), "git status failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); // Exact, for the re-check: raw bytes, not a lossy decoding. let text = format!("{:?}", output.stdout); @@ -510,7 +532,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String anyhow::ensure!( output.status.success(), "git rev-list failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); let commits = String::from_utf8_lossy(&output.stdout).into_owned(); let stranded = commits.lines().count(); @@ -528,7 +550,7 @@ fn unsaved_work(repo: &Path, members: &[PathBuf]) -> Result<(Vec, String anyhow::ensure!( staged.status.success(), "git diff --cached failed: {}", - String::from_utf8_lossy(&staged.stderr).trim() + escape(String::from_utf8_lossy(&staged.stderr).trim()) ); let staged = String::from_utf8_lossy(&staged.stdout).into_owned(); let files: Vec = modified @@ -559,7 +581,7 @@ fn hidden_files(repo: &Path) -> Result> { anyhow::ensure!( output.status.success(), "git ls-files failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); // Entries are " "; a lowercase tag means assume-unchanged, // "S" skip-worktree. @@ -607,7 +629,7 @@ fn operation_in_progress(repo: &Path) -> Result> { anyhow::ensure!( output.status.success(), "git rev-parse --git-dir failed: {}", - String::from_utf8_lossy(&output.stderr).trim() + escape(String::from_utf8_lossy(&output.stderr).trim()) ); let git_dir = repo.join(String::from_utf8_lossy(&output.stdout).trim_end_matches(['\n', '\r'])); let markers = [ @@ -625,7 +647,7 @@ fn operation_in_progress(repo: &Path) -> Result> { .map(|(_, name)| name)) } -fn relative_label(root: &Path, path: &Path) -> String { +pub(super) fn relative_label(root: &Path, path: &Path) -> String { match path.strip_prefix(root) { Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(), Ok(rel) => escape_path(rel).to_string(), @@ -738,6 +760,12 @@ mod tests { let record = set_record(&set); mark(&set, &record); + // In a set meta made, a worktree without a record is not meta's + let check = check_worktree_removal(&set).unwrap(); + assert_eq!(check.missing_records.len(), 1, "{check:?}"); + assert!(check.missing_records[0].starts_with("leaf: meta has no record")); + assert_eq!(check.blockers, check.missing_records); + mark(&set.join("leaf"), &record); let check = check_worktree_removal(&set).unwrap(); assert!(check.is_clear(), "{check:?}"); assert_eq!(check.record(), Some(&record)); diff --git a/src/worktree/workspace.rs b/src/worktree/workspace.rs new file mode 100644 index 0000000..422509a --- /dev/null +++ b/src/worktree/workspace.rs @@ -0,0 +1,166 @@ +//! The workspace a command runs in, and the repositories that make it up. +//! +//! Commands that delete worktree sets keep to this workspace's sets: those +//! whose every worktree belongs to one of its repositories. Where the sets +//! are kept (`META_WORKTREES` may be shared, or point into another +//! workspace) doesn't change that. + +use anyhow::{Context, Result}; +use meta_core::display::escape_path; +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use super::safety::{relative_label, RemovalCheck}; + +/// A workspace's root meta directory and its repositories. +pub struct Workspace { + pub root: PathBuf, + /// The git directory of each repository (the root's own, then every one + /// in its `.meta` tree, nested ones included): where the records of the + /// worktrees made from it are. + pub repos: Vec, + /// What couldn't be read (the project tree, a repository), with why: + /// worktrees from there count as another workspace's. + pub unreadable: Vec<(PathBuf, anyhow::Error)>, + git_dirs: HashSet, + /// `root`, resolved, to compare other workspaces' roots with. + canonical_root: PathBuf, +} + +impl Workspace { + /// The workspace `meta_dir` belongs to (see [`meta_core::config::workspace_root`]). + pub fn of(meta_dir: &Path) -> Workspace { + let root = meta_core::config::workspace_root(meta_dir); + let mut paths = vec![root.clone()]; + let mut unreadable = Vec::new(); + match meta_core::config::walk_meta_tree(&root, None) { + Ok(tree) => paths.extend( + meta_core::config::build_project_map(&tree, &root, "") + .into_values() + .map(|(path, _)| path), + ), + Err(e) => unreadable.push((root.clone(), e)), + } + let mut repos = Vec::new(); + for path in paths { + match repo_git_dir(&path) { + Ok(Some(git_dir)) => repos.push(git_dir), + Ok(None) => {} + Err(e) => unreadable.push((path, e)), + } + } + let git_dirs = repos + .iter() + .filter_map(|git_dir| git_dir.canonicalize().ok()) + .collect(); + Workspace { + canonical_root: root.canonicalize().unwrap_or_else(|_| root.clone()), + root, + repos, + unreadable, + git_dirs, + } + } + + /// Whether `git_dir` is the git directory of one of this workspace's + /// repositories. + pub fn holds(&self, git_dir: &Path) -> bool { + git_dir + .canonicalize() + .is_ok_and(|git_dir| self.git_dirs.contains(&git_dir)) + } + + /// Whether `project`, the meta directory a record names, is in this + /// workspace. Two workspaces can share a repository (one checked out + /// with `git worktree add` from the other), so the repository alone + /// doesn't say whose a set is. A project that is gone (or moved) leaves + /// its sets of unknown ownership: not this workspace's. + pub fn made_here(&self, project: &Path) -> bool { + let root = meta_core::config::workspace_root(project); + project.exists() && root.canonicalize().unwrap_or(root) == self.canonical_root + } + + /// The worktrees of the set at `wt_dir` (checked as `check`) that come + /// from repositories outside this workspace, or that another workspace + /// made, each with the workspace its record names. A set with any is + /// another workspace's. + pub fn foreign_members(&self, wt_dir: &Path, check: &RemovalCheck) -> Vec { + check + .members + .iter() + .filter(|m| { + !self.holds(&m.repo_git_dir) + || m.record + .as_ref() + .is_some_and(|r| !self.made_here(&r.project)) + }) + .map(|m| { + let label = relative_label(wt_dir, &m.path); + let repo = m.repo_git_dir.canonicalize(); + let repo = escape_path(repo.as_deref().unwrap_or(&m.repo_git_dir)); + match &m.record { + Some(record) if !record.project.exists() => format!( + "{label}: the workspace at {} made it, and it is gone or was moved; \ + remove this worktree with 'git worktree remove'", + escape_path(&record.project) + ), + Some(record) if self.holds(&m.repo_git_dir) => format!( + "{label}: the workspace at {} made it", + escape_path(&record.project) + ), + Some(record) => format!( + "{label}: its repository {repo} is not one of this workspace's; its \ + record names the workspace at {}", + escape_path(&record.project) + ), + None => { + format!("{label}: its repository {repo} is not one of this workspace's") + } + } + }) + .collect() + } +} + +/// The git directory holding the worktrees of the repository at `repo`: +/// `None` if there is no repository there (not cloned). +pub fn repo_git_dir(repo: &Path) -> Result> { + let dot_git = repo.join(".git"); + // Links are followed: a `.git` linked to the real git directory is one + let meta = match std::fs::metadata(&dot_git) { + Ok(meta) => meta, + // A bare repository is its own git directory + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let bare = repo.join("HEAD").is_file() + && repo.join("objects").is_dir() + && repo.join("refs").is_dir(); + return Ok(bare.then(|| repo.to_path_buf())); + } + Err(e) => { + return Err( + anyhow::Error::from(e).context(format!("Cannot inspect {}", escape_path(&dot_git))) + ) + } + }; + if meta.is_dir() { + return Ok(Some(dot_git)); + } + // A `.git` file: a linked worktree's (its admin directory names the + // repository's git directory in `commondir`) or a `--separate-git-dir` + // checkout's (it names the git directory itself, with no `commondir`) + let content = std::fs::read_to_string(&dot_git) + .with_context(|| format!("Cannot read {}", escape_path(&dot_git)))?; + let target = content + .trim() + .strip_prefix("gitdir:") + .map(|target| repo.join(target.trim())) + .with_context(|| format!("{} has no gitdir line", escape_path(&dot_git)))?; + let commondir = target.join("commondir"); + match std::fs::read_to_string(&commondir) { + Ok(common) => Ok(Some(target.join(common.trim()))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Some(target)), + Err(e) => { + Err(anyhow::Error::from(e).context(format!("Cannot read {}", escape_path(&commondir)))) + } + } +}