Skip to main content

git_cli/
worktree.rs

1use crate::commit_shared::{git_output, git_status_success, git_stdout_trimmed_optional};
2use anyhow::Context;
3use nils_common::cli_contract::{Envelope, EnvelopeError, OutputFormat, exit, schema_version_for};
4use serde::Serialize;
5use serde_json::json;
6use std::collections::HashMap;
7use std::env;
8use std::fs;
9use std::path::{Component, Path, PathBuf};
10
11const BINARY: &str = "git-cli";
12
13pub fn dispatch(cmd: &str, args: &[String]) -> Option<i32> {
14    match cmd {
15        "add" => Some(run_add(args)),
16        "list" => Some(run_list(args)),
17        "remove" => Some(run_remove(args)),
18        "prune" => Some(run_prune(args)),
19        _ => None,
20    }
21}
22
23#[derive(Debug, Clone)]
24pub(crate) struct LinkedWorktree {
25    pub path: PathBuf,
26    pub head: Option<String>,
27    pub branch: Option<String>,
28    pub bare: bool,
29    pub detached: bool,
30    pub prunable: Option<String>,
31}
32
33#[derive(Debug)]
34struct WorktreeLayout {
35    agent_home: PathBuf,
36    worktree_root: PathBuf,
37    repo_root: PathBuf,
38    repo_key: String,
39}
40
41#[derive(Debug)]
42struct AddArgs {
43    slug: String,
44    from: Option<String>,
45    format: OutputFormat,
46}
47
48#[derive(Debug)]
49struct ListArgs {
50    format: OutputFormat,
51}
52
53#[derive(Debug)]
54struct RemoveArgs {
55    target: String,
56    format: OutputFormat,
57}
58
59#[derive(Debug)]
60struct PruneArgs {
61    format: OutputFormat,
62}
63
64#[derive(Debug, Clone)]
65struct CliError {
66    code: &'static str,
67    message: Box<str>,
68    hint: Option<Box<str>>,
69    exit_code: i32,
70    details: Option<Box<serde_json::Value>>,
71}
72
73#[derive(Debug, Serialize)]
74struct AddOutput {
75    agent_home: String,
76    worktree_root: String,
77    repo_root: String,
78    repo_key: String,
79    slug: String,
80    branch: String,
81    base_ref: String,
82    path: String,
83}
84
85#[derive(Debug, Serialize)]
86struct ListOutput {
87    agent_home: String,
88    worktree_root: String,
89    repo_root: String,
90    repo_key: String,
91    entries: Vec<WorktreeEntryOutput>,
92}
93
94#[derive(Debug, Serialize)]
95struct WorktreeEntryOutput {
96    path: String,
97    head: Option<String>,
98    branch: Option<String>,
99    bare: bool,
100    detached: bool,
101    prunable: Option<String>,
102    managed: bool,
103}
104
105#[derive(Debug, Serialize)]
106struct RemoveOutput {
107    removed_path: String,
108    pruned: bool,
109}
110
111#[derive(Debug, Serialize)]
112struct PruneOutput {
113    pruned: bool,
114}
115
116impl CliError {
117    fn usage(code: &'static str, message: impl Into<String>) -> Self {
118        Self {
119            code,
120            message: message.into().into_boxed_str(),
121            hint: None,
122            exit_code: exit::USAGE,
123            details: None,
124        }
125    }
126
127    fn runtime(code: &'static str, message: impl Into<String>) -> Self {
128        Self {
129            code,
130            message: message.into().into_boxed_str(),
131            hint: None,
132            exit_code: exit::RUNTIME,
133            details: None,
134        }
135    }
136
137    fn data(code: &'static str, message: impl Into<String>) -> Self {
138        Self {
139            code,
140            message: message.into().into_boxed_str(),
141            hint: None,
142            exit_code: exit::DATA,
143            details: None,
144        }
145    }
146
147    fn with_hint(mut self, hint: impl Into<String>) -> Self {
148        self.hint = Some(hint.into().into_boxed_str());
149        self
150    }
151
152    fn with_details(mut self, details: serde_json::Value) -> Self {
153        self.details = Some(Box::new(details));
154        self
155    }
156}
157
158fn run_add(args: &[String]) -> i32 {
159    let requested_format = detect_format(args);
160    let parsed = match parse_add_args(args) {
161        Ok(parsed) => parsed,
162        Err(err) => return emit_error("worktree.add", requested_format, err),
163    };
164
165    match add_worktree(&parsed) {
166        Ok(output) => emit_success("worktree.add", parsed.format, &output, || {
167            format!(
168                "Created worktree {}\nBranch: {}\nBase: {}",
169                output.path, output.branch, output.base_ref
170            )
171        }),
172        Err(err) => emit_error("worktree.add", parsed.format, err),
173    }
174}
175
176fn run_list(args: &[String]) -> i32 {
177    let requested_format = detect_format(args);
178    let parsed = match parse_list_args(args) {
179        Ok(parsed) => parsed,
180        Err(err) => return emit_error("worktree.list", requested_format, err),
181    };
182
183    match list_worktrees() {
184        Ok(output) => emit_success("worktree.list", parsed.format, &output, || {
185            render_list_text(&output)
186        }),
187        Err(err) => emit_error("worktree.list", parsed.format, err),
188    }
189}
190
191fn run_remove(args: &[String]) -> i32 {
192    let requested_format = detect_format(args);
193    let parsed = match parse_remove_args(args) {
194        Ok(parsed) => parsed,
195        Err(err) => return emit_error("worktree.remove", requested_format, err),
196    };
197
198    match remove_worktree(&parsed) {
199        Ok(output) => emit_success("worktree.remove", parsed.format, &output, || {
200            format!(
201                "Removed worktree {}\nPruned stale worktree metadata",
202                output.removed_path
203            )
204        }),
205        Err(err) => emit_error("worktree.remove", parsed.format, err),
206    }
207}
208
209fn run_prune(args: &[String]) -> i32 {
210    let requested_format = detect_format(args);
211    let parsed = match parse_prune_args(args) {
212        Ok(parsed) => parsed,
213        Err(err) => return emit_error("worktree.prune", requested_format, err),
214    };
215
216    match prune_worktrees() {
217        Ok(output) => emit_success("worktree.prune", parsed.format, &output, || {
218            "Pruned stale worktree metadata".to_string()
219        }),
220        Err(err) => emit_error("worktree.prune", parsed.format, err),
221    }
222}
223
224fn add_worktree(args: &AddArgs) -> Result<AddOutput, CliError> {
225    let layout = resolve_layout()?;
226    let branch_slug = normalize_slug(&args.slug)?;
227    let branch = format!("feat/{branch_slug}");
228    let path = layout
229        .worktree_root
230        .join(&layout.repo_key)
231        .join(&branch_slug);
232    let base_ref = args.from.clone().unwrap_or_else(resolve_default_base_ref);
233
234    let branch_ref = format!("refs/heads/{branch}");
235    if git_status_success(&["show-ref", "--verify", "--quiet", &branch_ref]) {
236        return Err(
237            CliError::data("branch-exists", format!("branch {branch} already exists"))
238                .with_hint("use a different slug or remove the existing branch first"),
239        );
240    }
241
242    if path.exists() && !is_empty_dir(&path).unwrap_or(false) {
243        return Err(CliError::data(
244            "worktree-path-exists",
245            format!(
246                "managed worktree path already exists: {}",
247                display_path(&path)
248            ),
249        )
250        .with_details(json!({ "path": display_path(&path) })));
251    }
252
253    let parent = path.parent().ok_or_else(|| {
254        CliError::runtime(
255            "invalid-worktree-path",
256            format!("unable to resolve parent for {}", display_path(&path)),
257        )
258    })?;
259    fs::create_dir_all(parent).map_err(|err| {
260        CliError::runtime(
261            "create-worktree-parent-failed",
262            format!("failed to create {}: {err}", display_path(parent)),
263        )
264    })?;
265
266    let path_arg = display_path(&path);
267    git_output(&[
268        "worktree",
269        "add",
270        "-b",
271        branch.as_str(),
272        path_arg.as_str(),
273        base_ref.as_str(),
274    ])
275    .map_err(|err| {
276        CliError::runtime(
277            "git-worktree-add-failed",
278            summarize_git_error(&err.to_string()),
279        )
280    })?;
281
282    Ok(AddOutput {
283        agent_home: display_path(&layout.agent_home),
284        worktree_root: display_path(&layout.worktree_root),
285        repo_root: display_path(&layout.repo_root),
286        repo_key: layout.repo_key,
287        slug: branch_slug,
288        branch,
289        base_ref,
290        path: path_arg,
291    })
292}
293
294fn list_worktrees() -> Result<ListOutput, CliError> {
295    let layout = resolve_layout()?;
296    let entries = list_linked_worktrees()
297        .map_err(|err| CliError::runtime("git-worktree-list-failed", err.to_string()))?
298        .into_iter()
299        .map(|entry| {
300            let managed = is_managed_worktree(&entry.path, &layout);
301            WorktreeEntryOutput {
302                path: display_path(&entry.path),
303                head: entry.head,
304                branch: entry.branch,
305                bare: entry.bare,
306                detached: entry.detached,
307                prunable: entry.prunable,
308                managed,
309            }
310        })
311        .collect();
312
313    Ok(ListOutput {
314        agent_home: display_path(&layout.agent_home),
315        worktree_root: display_path(&layout.worktree_root),
316        repo_root: display_path(&layout.repo_root),
317        repo_key: layout.repo_key,
318        entries,
319    })
320}
321
322fn remove_worktree(args: &RemoveArgs) -> Result<RemoveOutput, CliError> {
323    let layout = resolve_layout()?;
324    let target = resolve_remove_target(&args.target, &layout)?;
325    let target_key = path_key(&target);
326    let repo_root_key = path_key(&layout.repo_root);
327
328    if target_key == repo_root_key {
329        return Err(CliError::data(
330            "refuse-primary-worktree",
331            "refusing to remove the primary repository worktree",
332        )
333        .with_details(json!({ "path": display_path(&target) })));
334    }
335
336    let cwd = env::current_dir().map_err(|err| {
337        CliError::runtime(
338            "current-dir-failed",
339            format!("failed to read current dir: {err}"),
340        )
341    })?;
342    let cwd_key = path_key(&cwd);
343    if cwd_key == target_key || cwd_key.starts_with(&(target_key.clone() + "/")) {
344        return Err(CliError::data(
345            "refuse-current-worktree",
346            format!(
347                "refusing to remove the current worktree {}",
348                display_path(&target)
349            ),
350        ));
351    }
352
353    let entries = list_linked_worktrees()
354        .map_err(|err| CliError::runtime("git-worktree-list-failed", err.to_string()))?;
355    let known = entries
356        .iter()
357        .any(|entry| path_key(&entry.path) == target_key);
358    if !known {
359        return Err(CliError::data(
360            "worktree-not-found",
361            format!("no linked worktree found for {}", args.target),
362        )
363        .with_details(json!({ "target": args.target })));
364    }
365
366    let target_arg = display_path(&target);
367    git_output(&["worktree", "remove", "--force", target_arg.as_str()]).map_err(|err| {
368        CliError::runtime(
369            "git-worktree-remove-failed",
370            summarize_git_error(&err.to_string()),
371        )
372    })?;
373    run_git_worktree_prune()?;
374
375    Ok(RemoveOutput {
376        removed_path: target_arg,
377        pruned: true,
378    })
379}
380
381fn prune_worktrees() -> Result<PruneOutput, CliError> {
382    ensure_inside_git_repo()?;
383    run_git_worktree_prune()?;
384    Ok(PruneOutput { pruned: true })
385}
386
387pub(crate) fn linked_worktrees_by_branch() -> anyhow::Result<HashMap<String, String>> {
388    let entries = list_linked_worktrees()?;
389    Ok(entries
390        .into_iter()
391        .filter_map(|entry| {
392            let branch = entry.branch?;
393            Some((branch, display_path(&entry.path)))
394        })
395        .collect())
396}
397
398fn list_linked_worktrees() -> anyhow::Result<Vec<LinkedWorktree>> {
399    let output = git_output(&["worktree", "list", "--porcelain"])?;
400    let stdout = String::from_utf8(output.stdout).context("git worktree output was not UTF-8")?;
401    Ok(parse_worktree_porcelain(&stdout))
402}
403
404fn parse_worktree_porcelain(stdout: &str) -> Vec<LinkedWorktree> {
405    let mut entries = Vec::new();
406    let mut current: Option<LinkedWorktree> = None;
407
408    for line in stdout.lines() {
409        if let Some(path) = line.strip_prefix("worktree ") {
410            if let Some(previous) = current.take() {
411                entries.push(previous);
412            }
413            current = Some(LinkedWorktree {
414                path: PathBuf::from(path.trim()),
415                head: None,
416                branch: None,
417                bare: false,
418                detached: false,
419                prunable: None,
420            });
421            continue;
422        }
423
424        if line.trim().is_empty() {
425            if let Some(previous) = current.take() {
426                entries.push(previous);
427            }
428            continue;
429        }
430
431        let Some(entry) = current.as_mut() else {
432            continue;
433        };
434
435        if let Some(head) = line.strip_prefix("HEAD ") {
436            entry.head = Some(head.trim().to_string());
437        } else if let Some(branch) = line.strip_prefix("branch ") {
438            entry.branch = Some(branch.trim().trim_start_matches("refs/heads/").to_string());
439        } else if line.trim() == "bare" {
440            entry.bare = true;
441        } else if line.trim() == "detached" {
442            entry.detached = true;
443        } else if let Some(reason) = line.strip_prefix("prunable ") {
444            entry.prunable = Some(reason.trim().to_string());
445        }
446    }
447
448    if let Some(previous) = current {
449        entries.push(previous);
450    }
451
452    entries
453}
454
455fn parse_add_args(args: &[String]) -> Result<AddArgs, CliError> {
456    let mut args = args.to_vec();
457    let format = take_format(&mut args)?;
458    if take_help(&args) {
459        print_add_help();
460        return Err(CliError::usage("help", "help requested"));
461    }
462
463    let mut slug: Option<String> = None;
464    let mut from: Option<String> = None;
465    let mut i = 0usize;
466    while i < args.len() {
467        match args[i].as_str() {
468            "--from" => {
469                let Some(value) = args.get(i + 1) else {
470                    return Err(CliError::usage("missing-from", "--from requires a value"));
471                };
472                from = Some(value.to_string());
473                i += 2;
474            }
475            value if value.starts_with("--from=") => {
476                from = Some(value.trim_start_matches("--from=").to_string());
477                i += 1;
478            }
479            value if value.starts_with('-') => {
480                return Err(CliError::usage(
481                    "unknown-argument",
482                    format!("unknown argument: {value}"),
483                ));
484            }
485            value => {
486                if slug.is_some() {
487                    return Err(CliError::usage(
488                        "too-many-arguments",
489                        "worktree add accepts exactly one slug",
490                    ));
491                }
492                slug = Some(value.to_string());
493                i += 1;
494            }
495        }
496    }
497
498    let slug = slug.ok_or_else(|| CliError::usage("missing-slug", "missing worktree slug"))?;
499    Ok(AddArgs { slug, from, format })
500}
501
502fn parse_list_args(args: &[String]) -> Result<ListArgs, CliError> {
503    let mut args = args.to_vec();
504    let format = take_format(&mut args)?;
505    if take_help(&args) {
506        print_list_help();
507        return Err(CliError::usage("help", "help requested"));
508    }
509    reject_extra_args("worktree list", &args)?;
510    Ok(ListArgs { format })
511}
512
513fn parse_remove_args(args: &[String]) -> Result<RemoveArgs, CliError> {
514    let mut args = args.to_vec();
515    let format = take_format(&mut args)?;
516    if take_help(&args) {
517        print_remove_help();
518        return Err(CliError::usage("help", "help requested"));
519    }
520
521    reject_unknown_flags(&args)?;
522    let positionals: Vec<_> = args.iter().filter(|arg| !arg.starts_with('-')).collect();
523    if positionals.len() != 1 {
524        return Err(CliError::usage(
525            "invalid-target-count",
526            "worktree remove accepts exactly one slug or path",
527        ));
528    }
529    Ok(RemoveArgs {
530        target: positionals[0].to_string(),
531        format,
532    })
533}
534
535fn parse_prune_args(args: &[String]) -> Result<PruneArgs, CliError> {
536    let mut args = args.to_vec();
537    let format = take_format(&mut args)?;
538    if take_help(&args) {
539        print_prune_help();
540        return Err(CliError::usage("help", "help requested"));
541    }
542    reject_extra_args("worktree prune", &args)?;
543    Ok(PruneArgs { format })
544}
545
546fn take_format(args: &mut Vec<String>) -> Result<OutputFormat, CliError> {
547    let mut format = OutputFormat::Text;
548    let mut i = 0usize;
549    while i < args.len() {
550        match args[i].as_str() {
551            "--format" => {
552                let Some(value) = args.get(i + 1) else {
553                    return Err(CliError::usage(
554                        "missing-format",
555                        "--format requires text or json",
556                    ));
557                };
558                format = parse_format_value(value)?;
559                args.drain(i..=i + 1);
560            }
561            value if value.starts_with("--format=") => {
562                let value = value.trim_start_matches("--format=");
563                format = parse_format_value(value)?;
564                args.remove(i);
565            }
566            _ => i += 1,
567        }
568    }
569    Ok(format)
570}
571
572fn parse_format_value(value: &str) -> Result<OutputFormat, CliError> {
573    match value {
574        "text" => Ok(OutputFormat::Text),
575        "json" => Ok(OutputFormat::Json),
576        other => Err(CliError::usage(
577            "invalid-format",
578            format!("unsupported output format: {other}"),
579        )),
580    }
581}
582
583fn detect_format(args: &[String]) -> OutputFormat {
584    let mut i = 0usize;
585    while i < args.len() {
586        match args[i].as_str() {
587            "--format" if args.get(i + 1).is_some_and(|value| value == "json") => {
588                return OutputFormat::Json;
589            }
590            "--format" => i += 2,
591            "--format=json" => return OutputFormat::Json,
592            _ => i += 1,
593        }
594    }
595    OutputFormat::Text
596}
597
598fn take_help(args: &[String]) -> bool {
599    args.iter()
600        .any(|arg| matches!(arg.as_str(), "-h" | "--help"))
601}
602
603fn reject_unknown_flags(args: &[String]) -> Result<(), CliError> {
604    if let Some(flag) = args.iter().find(|arg| arg.starts_with('-')) {
605        return Err(CliError::usage(
606            "unknown-argument",
607            format!("unknown argument: {flag}"),
608        ));
609    }
610    Ok(())
611}
612
613fn reject_extra_args(command: &str, args: &[String]) -> Result<(), CliError> {
614    reject_unknown_flags(args)?;
615    if !args.is_empty() {
616        return Err(CliError::usage(
617            "too-many-arguments",
618            format!("{command} does not accept positional arguments"),
619        ));
620    }
621    Ok(())
622}
623
624fn print_add_help() {
625    println!("Usage: git-cli worktree add <slug> [--from <ref>] [--format text|json]");
626}
627
628fn print_list_help() {
629    println!("Usage: git-cli worktree list [--format text|json]");
630}
631
632fn print_remove_help() {
633    println!("Usage: git-cli worktree remove <slug-or-path> [--format text|json]");
634}
635
636fn print_prune_help() {
637    println!("Usage: git-cli worktree prune [--format text|json]");
638}
639
640fn resolve_layout() -> Result<WorktreeLayout, CliError> {
641    let repo_root = require_repo_root()?;
642    let agent_home = resolve_agent_home()?;
643    let worktree_root = agent_home.join("worktrees");
644    let repo_key = repo_key_for_path(&repo_root);
645    Ok(WorktreeLayout {
646        agent_home,
647        worktree_root,
648        repo_root,
649        repo_key,
650    })
651}
652
653fn ensure_inside_git_repo() -> Result<(), CliError> {
654    if git_status_success(&["rev-parse", "--is-inside-work-tree"]) {
655        Ok(())
656    } else {
657        Err(CliError::runtime(
658            "not-git-repository",
659            "not in a git repository",
660        ))
661    }
662}
663
664fn require_repo_root() -> Result<PathBuf, CliError> {
665    ensure_inside_git_repo()?;
666    let root = git_stdout_trimmed_optional(&["rev-parse", "--show-toplevel"]).ok_or_else(|| {
667        CliError::runtime(
668            "repo-root-unavailable",
669            "unable to resolve git repository root",
670        )
671    })?;
672    absolute_existing_path(Path::new(&root))
673}
674
675fn resolve_agent_home() -> Result<PathBuf, CliError> {
676    if let Some(value) = env_non_empty("AGENT_HOME") {
677        return absolute_or_existing_path(Path::new(&value));
678    }
679    if let Some(value) = env_non_empty("XDG_STATE_HOME") {
680        return absolute_or_existing_path(&Path::new(&value).join("agent-runtime-kit"));
681    }
682    if let Some(value) = env_non_empty("HOME") {
683        return absolute_or_existing_path(
684            &Path::new(&value).join(".local/state/agent-runtime-kit"),
685        );
686    }
687    Ok(env::temp_dir().join("agent-runtime-kit"))
688}
689
690fn env_non_empty(key: &str) -> Option<String> {
691    env::var_os(key)
692        .filter(|value| !value.is_empty())
693        .map(|value| value.to_string_lossy().to_string())
694}
695
696fn absolute_path(path: &Path) -> Result<PathBuf, CliError> {
697    if path.is_absolute() {
698        return Ok(path.to_path_buf());
699    }
700    let cwd = env::current_dir().map_err(|err| {
701        CliError::runtime(
702            "current-dir-failed",
703            format!("failed to read current dir: {err}"),
704        )
705    })?;
706    Ok(cwd.join(path))
707}
708
709fn absolute_or_existing_path(path: &Path) -> Result<PathBuf, CliError> {
710    if path.exists() {
711        return absolute_existing_path(path);
712    }
713    absolute_path(path)
714}
715
716fn absolute_existing_path(path: &Path) -> Result<PathBuf, CliError> {
717    fs::canonicalize(path).map_err(|err| {
718        CliError::runtime(
719            "canonicalize-path-failed",
720            format!("failed to canonicalize {}: {err}", display_path(path)),
721        )
722    })
723}
724
725fn repo_key_for_path(repo_root: &Path) -> String {
726    let basename = repo_root
727        .file_name()
728        .and_then(|value| value.to_str())
729        .unwrap_or("repo");
730    let slug = sanitize_segment(basename, "repo");
731    let hash = stable_short_hash(&display_path(repo_root));
732    format!("{slug}-{hash}")
733}
734
735fn normalize_slug(value: &str) -> Result<String, CliError> {
736    let slug = sanitize_segment(value, "");
737    if slug.is_empty() {
738        return Err(CliError::usage(
739            "invalid-slug",
740            "slug must contain at least one ASCII letter or digit",
741        ));
742    }
743    Ok(slug)
744}
745
746fn sanitize_segment(value: &str, fallback: &str) -> String {
747    let mut out = String::new();
748    let mut last_dash = false;
749    for ch in value.chars() {
750        if ch.is_ascii_alphanumeric() {
751            out.push(ch.to_ascii_lowercase());
752            last_dash = false;
753        } else if matches!(ch, '-' | '_' | '.') {
754            out.push(ch);
755            last_dash = false;
756        } else if !last_dash {
757            out.push('-');
758            last_dash = true;
759        }
760    }
761
762    let trimmed = out.trim_matches(['-', '_', '.']);
763    let mut sanitized: String = trimmed.chars().take(80).collect();
764    sanitized = sanitized.trim_matches(['-', '_', '.']).to_string();
765
766    if sanitized.is_empty() {
767        fallback.to_string()
768    } else {
769        sanitized
770    }
771}
772
773fn stable_short_hash(value: &str) -> String {
774    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
775    for byte in value.as_bytes() {
776        hash ^= u64::from(*byte);
777        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
778    }
779    format!("{:08x}", hash as u32)
780}
781
782fn resolve_default_base_ref() -> String {
783    if let Some(origin_head) = git_stdout_trimmed_optional(&[
784        "symbolic-ref",
785        "--quiet",
786        "--short",
787        "refs/remotes/origin/HEAD",
788    ]) {
789        return origin_head;
790    }
791    if git_status_success(&["show-ref", "--verify", "--quiet", "refs/heads/main"]) {
792        return "main".to_string();
793    }
794    if git_status_success(&["show-ref", "--verify", "--quiet", "refs/heads/master"]) {
795        return "master".to_string();
796    }
797    "HEAD".to_string()
798}
799
800fn resolve_remove_target(target: &str, layout: &WorktreeLayout) -> Result<PathBuf, CliError> {
801    let candidate = Path::new(target);
802    if candidate.is_absolute() || path_has_multiple_components(candidate) {
803        return absolute_path(candidate);
804    }
805
806    let slug = normalize_slug(target)?;
807    Ok(layout.worktree_root.join(&layout.repo_key).join(slug))
808}
809
810fn path_has_multiple_components(path: &Path) -> bool {
811    path.components()
812        .filter(|component| !matches!(component, Component::CurDir))
813        .count()
814        > 1
815}
816
817fn path_key(path: &Path) -> String {
818    let normalized = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
819    display_path(&normalized)
820}
821
822fn is_managed_worktree(path: &Path, layout: &WorktreeLayout) -> bool {
823    let managed_root = canonical_or_raw(&layout.worktree_root.join(&layout.repo_key));
824    canonical_or_raw(path).starts_with(managed_root)
825}
826
827fn canonical_or_raw(path: &Path) -> PathBuf {
828    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
829}
830
831fn is_empty_dir(path: &Path) -> std::io::Result<bool> {
832    Ok(path.is_dir() && fs::read_dir(path)?.next().is_none())
833}
834
835fn run_git_worktree_prune() -> Result<(), CliError> {
836    git_output(&["worktree", "prune"]).map_err(|err| {
837        CliError::runtime(
838            "git-worktree-prune-failed",
839            summarize_git_error(&err.to_string()),
840        )
841    })?;
842    Ok(())
843}
844
845fn emit_success<T: Serialize, F: FnOnce() -> String>(
846    command: &str,
847    format: OutputFormat,
848    payload: &T,
849    text: F,
850) -> i32 {
851    match format {
852        OutputFormat::Json => {
853            let envelope = Envelope::success(schema_version_for(BINARY, command, 1), payload);
854            match serde_json::to_string(&envelope) {
855                Ok(serialized) => {
856                    println!("{serialized}");
857                    exit::SUCCESS
858                }
859                Err(err) => {
860                    eprintln!("failed to serialize JSON output: {err}");
861                    exit::RUNTIME
862                }
863            }
864        }
865        OutputFormat::Text => {
866            println!("{}", text());
867            exit::SUCCESS
868        }
869    }
870}
871
872fn emit_error(command: &str, format: OutputFormat, err: CliError) -> i32 {
873    if err.code == "help" {
874        return exit::SUCCESS;
875    }
876
877    match format {
878        OutputFormat::Json => {
879            let mut envelope_error = EnvelopeError::new(err.code, err.message.as_ref());
880            if let Some(hint) = &err.hint {
881                envelope_error = envelope_error.with_hint(hint.as_ref());
882            }
883            if let Some(details) = err.details {
884                envelope_error = envelope_error.with_details(*details);
885            }
886            let envelope: Envelope<()> =
887                Envelope::failure(schema_version_for(BINARY, command, 1), envelope_error);
888            match serde_json::to_string(&envelope) {
889                Ok(serialized) => println!("{serialized}"),
890                Err(serialize_err) => eprintln!("failed to serialize JSON error: {serialize_err}"),
891            }
892        }
893        OutputFormat::Text => eprintln!("{}", err.message),
894    }
895    err.exit_code
896}
897
898fn render_list_text(output: &ListOutput) -> String {
899    if output.entries.is_empty() {
900        return "No linked git worktrees found.".to_string();
901    }
902
903    let mut lines = vec!["Worktrees:".to_string()];
904    for entry in &output.entries {
905        let branch = entry.branch.as_deref().unwrap_or("(detached)");
906        let marker = if entry.managed { "managed" } else { "external" };
907        lines.push(format!("  - {branch}: {} [{marker}]", entry.path));
908    }
909    lines.join("\n")
910}
911
912fn summarize_git_error(message: &str) -> String {
913    let trimmed = message.trim();
914    let summary = trimmed
915        .rsplit_once(" failed: ")
916        .map(|(_, suffix)| suffix.trim())
917        .unwrap_or(trimmed);
918    summary.replace('\n', " ")
919}
920
921fn display_path(path: &Path) -> String {
922    path.to_string_lossy().to_string()
923}
924
925#[cfg(test)]
926mod tests {
927    use super::{
928        normalize_slug, parse_worktree_porcelain, repo_key_for_path, resolve_remove_target,
929    };
930    use pretty_assertions::{assert_eq, assert_ne};
931    use std::path::Path;
932
933    #[test]
934    fn repo_key_includes_basename_and_stable_hash() {
935        let first = repo_key_for_path(Path::new("/tmp/a/repo"));
936        let second = repo_key_for_path(Path::new("/tmp/b/repo"));
937        assert!(first.starts_with("repo-"));
938        assert!(second.starts_with("repo-"));
939        assert_ne!(first, second);
940        assert_eq!(first, repo_key_for_path(Path::new("/tmp/a/repo")));
941    }
942
943    #[test]
944    fn normalize_slug_keeps_branch_safe_path_segment() {
945        assert_eq!(normalize_slug("Topic One").expect("slug"), "topic-one");
946        assert_eq!(normalize_slug("fix/foo_bar").expect("slug"), "fix-foo_bar");
947        assert!(normalize_slug("!!!").is_err());
948    }
949
950    #[test]
951    fn parse_worktree_porcelain_captures_branch_and_detached_entries() {
952        let entries = parse_worktree_porcelain(
953            "worktree /repo\nHEAD 111\nbranch refs/heads/main\n\nworktree /repo/wt\nHEAD 222\ndetached\n",
954        );
955        assert_eq!(entries.len(), 2);
956        assert_eq!(entries[0].path, Path::new("/repo"));
957        assert_eq!(entries[0].branch.as_deref(), Some("main"));
958        assert_eq!(entries[1].path, Path::new("/repo/wt"));
959        assert!(entries[1].detached);
960    }
961
962    #[test]
963    fn resolve_remove_target_uses_managed_path_for_slug() {
964        let layout = super::WorktreeLayout {
965            agent_home: Path::new("/agent").to_path_buf(),
966            worktree_root: Path::new("/agent/worktrees").to_path_buf(),
967            repo_root: Path::new("/repo").to_path_buf(),
968            repo_key: "repo-12345678".to_string(),
969        };
970        let target = resolve_remove_target("Topic One", &layout).expect("target");
971        assert_eq!(
972            target,
973            Path::new("/agent/worktrees/repo-12345678/topic-one")
974        );
975    }
976}