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 nils_common::git::PrKind;
5use nils_common::shell::quote_posix_single;
6use serde::Serialize;
7use serde_json::json;
8use std::collections::HashMap;
9use std::env;
10use std::fs;
11use std::path::{Component, Path, PathBuf};
12
13const BINARY: &str = "git-cli";
14
15pub fn dispatch(cmd: &str, args: &[String]) -> Option<i32> {
16    match cmd {
17        "add" => Some(run_add(args)),
18        "list" => Some(run_list(args)),
19        "remove" => Some(run_remove(args)),
20        "prune" => Some(run_prune(args)),
21        "go" => Some(run_go(args)),
22        _ => None,
23    }
24}
25
26#[derive(Debug, Clone)]
27pub(crate) struct LinkedWorktree {
28    pub path: PathBuf,
29    pub head: Option<String>,
30    pub branch: Option<String>,
31    pub bare: bool,
32    pub detached: bool,
33    pub prunable: Option<String>,
34}
35
36#[derive(Debug)]
37struct WorktreeLayout {
38    agent_home: PathBuf,
39    worktree_root: PathBuf,
40    repo_root: PathBuf,
41    repo_key: String,
42}
43
44#[derive(Debug)]
45struct AddArgs {
46    slug: String,
47    from: Option<String>,
48    kind: PrKind,
49    format: OutputFormat,
50}
51
52#[derive(Debug)]
53struct ListArgs {
54    format: OutputFormat,
55}
56
57#[derive(Debug)]
58struct RemoveArgs {
59    target: String,
60    format: OutputFormat,
61}
62
63#[derive(Debug)]
64struct PruneArgs {
65    format: OutputFormat,
66}
67
68#[derive(Debug)]
69struct GoArgs {
70    target: String,
71    shell: bool,
72    format: OutputFormat,
73}
74
75#[derive(Debug, Clone)]
76struct CliError {
77    code: &'static str,
78    message: Box<str>,
79    hint: Option<Box<str>>,
80    exit_code: i32,
81    details: Option<Box<serde_json::Value>>,
82}
83
84#[derive(Debug, Serialize)]
85struct AddOutput {
86    agent_home: String,
87    worktree_root: String,
88    repo_root: String,
89    repo_key: String,
90    slug: String,
91    kind: String,
92    branch: String,
93    base_ref: String,
94    path: String,
95}
96
97#[derive(Debug, Serialize)]
98struct ListOutput {
99    agent_home: String,
100    worktree_root: String,
101    repo_root: String,
102    repo_key: String,
103    entries: Vec<WorktreeEntryOutput>,
104}
105
106#[derive(Debug, Serialize)]
107struct WorktreeEntryOutput {
108    path: String,
109    head: Option<String>,
110    branch: Option<String>,
111    bare: bool,
112    detached: bool,
113    prunable: Option<String>,
114    managed: bool,
115}
116
117#[derive(Debug, Serialize)]
118struct RemoveOutput {
119    removed_path: String,
120    pruned: bool,
121}
122
123#[derive(Debug, Serialize)]
124struct PruneOutput {
125    pruned: bool,
126}
127
128#[derive(Debug, Serialize)]
129struct GoOutput {
130    path: String,
131    slug: String,
132    branch: Option<String>,
133    managed: bool,
134    shell_command: String,
135}
136
137impl CliError {
138    fn usage(code: &'static str, message: impl Into<String>) -> Self {
139        Self {
140            code,
141            message: message.into().into_boxed_str(),
142            hint: None,
143            exit_code: exit::USAGE,
144            details: None,
145        }
146    }
147
148    fn runtime(code: &'static str, message: impl Into<String>) -> Self {
149        Self {
150            code,
151            message: message.into().into_boxed_str(),
152            hint: None,
153            exit_code: exit::RUNTIME,
154            details: None,
155        }
156    }
157
158    fn data(code: &'static str, message: impl Into<String>) -> Self {
159        Self {
160            code,
161            message: message.into().into_boxed_str(),
162            hint: None,
163            exit_code: exit::DATA,
164            details: None,
165        }
166    }
167
168    fn with_hint(mut self, hint: impl Into<String>) -> Self {
169        self.hint = Some(hint.into().into_boxed_str());
170        self
171    }
172
173    fn with_details(mut self, details: serde_json::Value) -> Self {
174        self.details = Some(Box::new(details));
175        self
176    }
177}
178
179fn run_add(args: &[String]) -> i32 {
180    let requested_format = detect_format(args);
181    let parsed = match parse_add_args(args) {
182        Ok(parsed) => parsed,
183        Err(err) => return emit_error("worktree.add", requested_format, err),
184    };
185
186    match add_worktree(&parsed) {
187        Ok(output) => emit_success("worktree.add", parsed.format, &output, || {
188            format!(
189                "Created worktree {}\nBranch: {}\nBase: {}",
190                output.path, output.branch, output.base_ref
191            )
192        }),
193        Err(err) => emit_error("worktree.add", parsed.format, err),
194    }
195}
196
197fn run_list(args: &[String]) -> i32 {
198    let requested_format = detect_format(args);
199    let parsed = match parse_list_args(args) {
200        Ok(parsed) => parsed,
201        Err(err) => return emit_error("worktree.list", requested_format, err),
202    };
203
204    match list_worktrees() {
205        Ok(output) => emit_success("worktree.list", parsed.format, &output, || {
206            render_list_text(&output)
207        }),
208        Err(err) => emit_error("worktree.list", parsed.format, err),
209    }
210}
211
212fn run_remove(args: &[String]) -> i32 {
213    let requested_format = detect_format(args);
214    let parsed = match parse_remove_args(args) {
215        Ok(parsed) => parsed,
216        Err(err) => return emit_error("worktree.remove", requested_format, err),
217    };
218
219    match remove_worktree(&parsed) {
220        Ok(output) => emit_success("worktree.remove", parsed.format, &output, || {
221            format!(
222                "Removed worktree {}\nPruned stale worktree metadata",
223                output.removed_path
224            )
225        }),
226        Err(err) => emit_error("worktree.remove", parsed.format, err),
227    }
228}
229
230fn run_prune(args: &[String]) -> i32 {
231    let requested_format = detect_format(args);
232    let parsed = match parse_prune_args(args) {
233        Ok(parsed) => parsed,
234        Err(err) => return emit_error("worktree.prune", requested_format, err),
235    };
236
237    match prune_worktrees() {
238        Ok(output) => emit_success("worktree.prune", parsed.format, &output, || {
239            "Pruned stale worktree metadata".to_string()
240        }),
241        Err(err) => emit_error("worktree.prune", parsed.format, err),
242    }
243}
244
245fn run_go(args: &[String]) -> i32 {
246    let requested_format = detect_format(args);
247    let parsed = match parse_go_args(args) {
248        Ok(parsed) => parsed,
249        Err(err) => return emit_error("worktree.go", requested_format, err),
250    };
251
252    match resolve_go(&parsed) {
253        Ok(output) => {
254            // Shell mode short-circuits the standard text rendering and prints a
255            // single evaluable `cd -- <path>` command (mirroring
256            // `git-cli utils root --shell`) so a shell wrapper can `eval` it.
257            // An explicit `--format json` still wins for machine consumers.
258            if parsed.shell && !matches!(parsed.format, OutputFormat::Json) {
259                println!("{}", output.shell_command);
260                return exit::SUCCESS;
261            }
262            emit_success("worktree.go", parsed.format, &output, || {
263                output.path.clone()
264            })
265        }
266        Err(err) => emit_error("worktree.go", parsed.format, err),
267    }
268}
269
270fn resolve_go(args: &GoArgs) -> Result<GoOutput, CliError> {
271    let layout = resolve_layout()?;
272    let entries = list_linked_worktrees()
273        .map_err(|err| CliError::runtime("git-worktree-list-failed", err.to_string()))?;
274    let entry = resolve_go_target(&args.target, &layout, &entries)?;
275
276    let path = canonical_or_raw(&entry.path);
277    let path_text = display_path(&path);
278    let slug = path
279        .file_name()
280        .and_then(|name| name.to_str())
281        .unwrap_or(args.target.as_str())
282        .to_string();
283    let shell_command = format!("cd -- {}", quote_posix_single(&path_text));
284    Ok(GoOutput {
285        path: path_text,
286        slug,
287        branch: entry.branch.clone(),
288        managed: is_managed_worktree(&entry.path, &layout),
289        shell_command,
290    })
291}
292
293/// Resolve a `worktree go` target to a single linked worktree. Accepts, in
294/// priority order: an exact branch name, an explicit worktree path, a managed
295/// slug, or any worktree directory's basename. Resolution is driven entirely by
296/// the live `git worktree list`, so it works identically from the primary
297/// checkout or from inside any linked worktree.
298fn resolve_go_target<'a>(
299    target: &str,
300    layout: &WorktreeLayout,
301    entries: &'a [LinkedWorktree],
302) -> Result<&'a LinkedWorktree, CliError> {
303    // 1. Exact branch name (e.g. `feat/topic`).
304    if let Some(entry) = entries
305        .iter()
306        .find(|entry| entry.branch.as_deref() == Some(target))
307    {
308        return Ok(entry);
309    }
310
311    // 2. Explicit path (absolute or multi-component) naming a known worktree.
312    let candidate = Path::new(target);
313    if candidate.is_absolute() || path_has_multiple_components(candidate) {
314        let target_key = path_key(candidate);
315        if let Some(entry) = entries
316            .iter()
317            .find(|entry| path_key(&entry.path) == target_key)
318        {
319            return Ok(entry);
320        }
321    }
322
323    // 3. Managed slug -> managed worktree path, then the slug as a basename.
324    if let Ok(slug) = normalize_slug(target) {
325        let managed_key = path_key(&layout.worktree_root.join(&layout.repo_key).join(&slug));
326        if let Some(entry) = entries
327            .iter()
328            .find(|entry| path_key(&entry.path) == managed_key)
329        {
330            return Ok(entry);
331        }
332        if let Some(entry) = entries
333            .iter()
334            .find(|entry| basename(&entry.path) == Some(slug.as_str()))
335        {
336            return Ok(entry);
337        }
338    }
339
340    // 4. Raw basename match (external worktrees whose dir name is not a slug).
341    if let Some(entry) = entries
342        .iter()
343        .find(|entry| basename(&entry.path) == Some(target))
344    {
345        return Ok(entry);
346    }
347
348    let mut err = CliError::data(
349        "worktree-not-found",
350        format!("no worktree found for {target}"),
351    )
352    .with_details(json!({ "target": target }));
353    if let Some(hint) = go_candidate_hint(entries) {
354        err = err.with_hint(hint);
355    }
356    Err(err)
357}
358
359fn basename(path: &Path) -> Option<&str> {
360    path.file_name().and_then(|name| name.to_str())
361}
362
363fn go_candidate_hint(entries: &[LinkedWorktree]) -> Option<String> {
364    let mut names: Vec<String> = entries
365        .iter()
366        .filter_map(|entry| basename(&entry.path).map(str::to_string))
367        .collect();
368    if names.is_empty() {
369        return None;
370    }
371    names.sort();
372    names.dedup();
373    Some(format!("available worktrees: {}", names.join(", ")))
374}
375
376fn add_worktree(args: &AddArgs) -> Result<AddOutput, CliError> {
377    let layout = resolve_layout()?;
378    let branch_slug = normalize_slug(&args.slug)?;
379    let branch = format!("{}/{branch_slug}", args.kind.branch_prefix());
380    let path = layout
381        .worktree_root
382        .join(&layout.repo_key)
383        .join(&branch_slug);
384    let base_ref = args.from.clone().unwrap_or_else(resolve_default_base_ref);
385
386    let branch_ref = format!("refs/heads/{branch}");
387    if git_status_success(&["show-ref", "--verify", "--quiet", &branch_ref]) {
388        return Err(
389            CliError::data("branch-exists", format!("branch {branch} already exists"))
390                .with_hint("use a different slug or remove the existing branch first"),
391        );
392    }
393
394    if path.exists() && !is_empty_dir(&path).unwrap_or(false) {
395        return Err(CliError::data(
396            "worktree-path-exists",
397            format!(
398                "managed worktree path already exists: {}",
399                display_path(&path)
400            ),
401        )
402        .with_details(json!({ "path": display_path(&path) })));
403    }
404
405    let parent = path.parent().ok_or_else(|| {
406        CliError::runtime(
407            "invalid-worktree-path",
408            format!("unable to resolve parent for {}", display_path(&path)),
409        )
410    })?;
411    fs::create_dir_all(parent).map_err(|err| {
412        CliError::runtime(
413            "create-worktree-parent-failed",
414            format!("failed to create {}: {err}", display_path(parent)),
415        )
416    })?;
417
418    let path_arg = display_path(&path);
419    git_output(&[
420        "worktree",
421        "add",
422        "-b",
423        branch.as_str(),
424        path_arg.as_str(),
425        base_ref.as_str(),
426    ])
427    .map_err(|err| {
428        CliError::runtime(
429            "git-worktree-add-failed",
430            summarize_git_error(&err.to_string()),
431        )
432    })?;
433
434    Ok(AddOutput {
435        agent_home: display_path(&layout.agent_home),
436        worktree_root: display_path(&layout.worktree_root),
437        repo_root: display_path(&layout.repo_root),
438        repo_key: layout.repo_key,
439        slug: branch_slug,
440        kind: args.kind.as_str().to_string(),
441        branch,
442        base_ref,
443        path: path_arg,
444    })
445}
446
447fn list_worktrees() -> Result<ListOutput, CliError> {
448    let layout = resolve_layout()?;
449    let entries = list_linked_worktrees()
450        .map_err(|err| CliError::runtime("git-worktree-list-failed", err.to_string()))?
451        .into_iter()
452        .map(|entry| {
453            let managed = is_managed_worktree(&entry.path, &layout);
454            WorktreeEntryOutput {
455                path: display_path(&entry.path),
456                head: entry.head,
457                branch: entry.branch,
458                bare: entry.bare,
459                detached: entry.detached,
460                prunable: entry.prunable,
461                managed,
462            }
463        })
464        .collect();
465
466    Ok(ListOutput {
467        agent_home: display_path(&layout.agent_home),
468        worktree_root: display_path(&layout.worktree_root),
469        repo_root: display_path(&layout.repo_root),
470        repo_key: layout.repo_key,
471        entries,
472    })
473}
474
475fn remove_worktree(args: &RemoveArgs) -> Result<RemoveOutput, CliError> {
476    let layout = resolve_layout()?;
477    let target = resolve_remove_target(&args.target, &layout)?;
478    let target_key = path_key(&target);
479    let repo_root_key = path_key(&layout.repo_root);
480
481    if target_key == repo_root_key {
482        return Err(CliError::data(
483            "refuse-primary-worktree",
484            "refusing to remove the primary repository worktree",
485        )
486        .with_details(json!({ "path": display_path(&target) })));
487    }
488
489    let cwd = env::current_dir().map_err(|err| {
490        CliError::runtime(
491            "current-dir-failed",
492            format!("failed to read current dir: {err}"),
493        )
494    })?;
495    let cwd_key = path_key(&cwd);
496    if cwd_key == target_key || cwd_key.starts_with(&(target_key.clone() + "/")) {
497        return Err(CliError::data(
498            "refuse-current-worktree",
499            format!(
500                "refusing to remove the current worktree {}",
501                display_path(&target)
502            ),
503        ));
504    }
505
506    let entries = list_linked_worktrees()
507        .map_err(|err| CliError::runtime("git-worktree-list-failed", err.to_string()))?;
508    let known = entries
509        .iter()
510        .any(|entry| path_key(&entry.path) == target_key);
511    if !known {
512        let mut err = CliError::data(
513            "worktree-not-found",
514            format!("no linked worktree found for {}", args.target),
515        )
516        .with_details(json!({ "target": args.target }));
517        if let Some(hint) = branch_name_hint(&args.target, &entries) {
518            err = err.with_hint(hint);
519        }
520        return Err(err);
521    }
522
523    let target_arg = display_path(&target);
524    git_output(&["worktree", "remove", "--force", target_arg.as_str()]).map_err(|err| {
525        CliError::runtime(
526            "git-worktree-remove-failed",
527            summarize_git_error(&err.to_string()),
528        )
529    })?;
530    run_git_worktree_prune()?;
531
532    Ok(RemoveOutput {
533        removed_path: target_arg,
534        pruned: true,
535    })
536}
537
538fn prune_worktrees() -> Result<PruneOutput, CliError> {
539    ensure_inside_git_repo()?;
540    run_git_worktree_prune()?;
541    Ok(PruneOutput { pruned: true })
542}
543
544/// When a `remove` target resolves to no managed path or slug but exactly
545/// matches a linked worktree's branch name, the caller most likely passed the
546/// branch (e.g. `docs/foo`) instead of the slug (`foo`) — and the leading
547/// `docs/` made the path heuristic treat it as a relative path. Point them at
548/// the slug (the managed path's final segment) and the full path so they can
549/// retry without guessing. Matching against live branch names keeps this free
550/// of any hard-coded prefix list.
551fn branch_name_hint(target: &str, entries: &[LinkedWorktree]) -> Option<String> {
552    let entry = entries
553        .iter()
554        .find(|entry| entry.branch.as_deref() == Some(target))?;
555    let slug = entry
556        .path
557        .file_name()
558        .and_then(|name| name.to_str())
559        .unwrap_or(target);
560    Some(format!(
561        "'{target}' is a branch name; remove by slug '{slug}' or path '{}'",
562        display_path(&entry.path)
563    ))
564}
565
566pub(crate) fn linked_worktrees_by_branch() -> anyhow::Result<HashMap<String, String>> {
567    let entries = list_linked_worktrees()?;
568    Ok(entries
569        .into_iter()
570        .filter_map(|entry| {
571            let branch = entry.branch?;
572            Some((branch, display_path(&entry.path)))
573        })
574        .collect())
575}
576
577/// Completion candidates for the `worktree go`/`worktree remove` target arg:
578/// managed worktree slugs (path basenames) plus their branch names, sorted and
579/// deduped. Fails soft to an empty list when `git worktree list` is unavailable
580/// (e.g. outside a repository) so completion never errors.
581pub(crate) fn go_target_candidates() -> Vec<String> {
582    let Ok(entries) = list_linked_worktrees() else {
583        return Vec::new();
584    };
585    worktree_candidates_from_entries(&entries)
586}
587
588fn worktree_candidates_from_entries(entries: &[LinkedWorktree]) -> Vec<String> {
589    let mut out = Vec::new();
590    for entry in entries {
591        if let Some(slug) = entry.path.file_name().and_then(|name| name.to_str()) {
592            out.push(slug.to_string());
593        }
594        if let Some(branch) = entry.branch.as_deref() {
595            out.push(branch.to_string());
596        }
597    }
598    out.sort();
599    out.dedup();
600    out
601}
602
603fn list_linked_worktrees() -> anyhow::Result<Vec<LinkedWorktree>> {
604    let output = git_output(&["worktree", "list", "--porcelain"])?;
605    let stdout = String::from_utf8(output.stdout).context("git worktree output was not UTF-8")?;
606    Ok(parse_worktree_porcelain(&stdout))
607}
608
609fn parse_worktree_porcelain(stdout: &str) -> Vec<LinkedWorktree> {
610    let mut entries = Vec::new();
611    let mut current: Option<LinkedWorktree> = None;
612
613    for line in stdout.lines() {
614        if let Some(path) = line.strip_prefix("worktree ") {
615            if let Some(previous) = current.take() {
616                entries.push(previous);
617            }
618            current = Some(LinkedWorktree {
619                path: PathBuf::from(path.trim()),
620                head: None,
621                branch: None,
622                bare: false,
623                detached: false,
624                prunable: None,
625            });
626            continue;
627        }
628
629        if line.trim().is_empty() {
630            if let Some(previous) = current.take() {
631                entries.push(previous);
632            }
633            continue;
634        }
635
636        let Some(entry) = current.as_mut() else {
637            continue;
638        };
639
640        if let Some(head) = line.strip_prefix("HEAD ") {
641            entry.head = Some(head.trim().to_string());
642        } else if let Some(branch) = line.strip_prefix("branch ") {
643            entry.branch = Some(branch.trim().trim_start_matches("refs/heads/").to_string());
644        } else if line.trim() == "bare" {
645            entry.bare = true;
646        } else if line.trim() == "detached" {
647            entry.detached = true;
648        } else if let Some(reason) = line.strip_prefix("prunable ") {
649            entry.prunable = Some(reason.trim().to_string());
650        }
651    }
652
653    if let Some(previous) = current {
654        entries.push(previous);
655    }
656
657    entries
658}
659
660fn parse_add_args(args: &[String]) -> Result<AddArgs, CliError> {
661    let mut args = args.to_vec();
662    let format = take_format(&mut args)?;
663    if take_help(&args) {
664        print_add_help();
665        return Err(CliError::usage("help", "help requested"));
666    }
667
668    let mut slug: Option<String> = None;
669    let mut from: Option<String> = None;
670    let mut kind_raw: Option<String> = None;
671    let mut i = 0usize;
672    while i < args.len() {
673        match args[i].as_str() {
674            "--from" => {
675                let Some(value) = args.get(i + 1) else {
676                    return Err(CliError::usage("missing-from", "--from requires a value"));
677                };
678                from = Some(value.to_string());
679                i += 2;
680            }
681            value if value.starts_with("--from=") => {
682                from = Some(value.trim_start_matches("--from=").to_string());
683                i += 1;
684            }
685            "--kind" => {
686                let Some(value) = args.get(i + 1) else {
687                    return Err(CliError::usage("missing-kind", "--kind requires a value"));
688                };
689                kind_raw = Some(value.to_string());
690                i += 2;
691            }
692            value if value.starts_with("--kind=") => {
693                kind_raw = Some(value.trim_start_matches("--kind=").to_string());
694                i += 1;
695            }
696            value if value.starts_with('-') => {
697                return Err(CliError::usage(
698                    "unknown-argument",
699                    format!("unknown argument: {value}"),
700                ));
701            }
702            value => {
703                if slug.is_some() {
704                    return Err(CliError::usage(
705                        "too-many-arguments",
706                        "worktree add accepts exactly one slug",
707                    ));
708                }
709                slug = Some(value.to_string());
710                i += 1;
711            }
712        }
713    }
714
715    let slug = slug.ok_or_else(|| CliError::usage("missing-slug", "missing worktree slug"))?;
716    // Default to `feature` (branch prefix `feat/`) so the prior behavior is
717    // unchanged; any other kind selects forge-cli's matching branch prefix.
718    let kind = match kind_raw {
719        Some(value) => PrKind::parse(&value).ok_or_else(|| {
720            CliError::usage(
721                "invalid-kind",
722                format!(
723                    "unknown --kind '{value}' (expected one of: feature, bug, chore, docs, ci, refactor)"
724                ),
725            )
726        })?,
727        None => PrKind::Feature,
728    };
729    Ok(AddArgs {
730        slug,
731        from,
732        kind,
733        format,
734    })
735}
736
737fn parse_list_args(args: &[String]) -> Result<ListArgs, CliError> {
738    let mut args = args.to_vec();
739    let format = take_format(&mut args)?;
740    if take_help(&args) {
741        print_list_help();
742        return Err(CliError::usage("help", "help requested"));
743    }
744    reject_extra_args("worktree list", &args)?;
745    Ok(ListArgs { format })
746}
747
748fn parse_remove_args(args: &[String]) -> Result<RemoveArgs, CliError> {
749    let mut args = args.to_vec();
750    let format = take_format(&mut args)?;
751    if take_help(&args) {
752        print_remove_help();
753        return Err(CliError::usage("help", "help requested"));
754    }
755
756    reject_unknown_flags(&args)?;
757    let positionals: Vec<_> = args.iter().filter(|arg| !arg.starts_with('-')).collect();
758    if positionals.len() != 1 {
759        return Err(CliError::usage(
760            "invalid-target-count",
761            "worktree remove accepts exactly one slug or path",
762        ));
763    }
764    Ok(RemoveArgs {
765        target: positionals[0].to_string(),
766        format,
767    })
768}
769
770fn parse_prune_args(args: &[String]) -> Result<PruneArgs, CliError> {
771    let mut args = args.to_vec();
772    let format = take_format(&mut args)?;
773    if take_help(&args) {
774        print_prune_help();
775        return Err(CliError::usage("help", "help requested"));
776    }
777    reject_extra_args("worktree prune", &args)?;
778    Ok(PruneArgs { format })
779}
780
781fn parse_go_args(args: &[String]) -> Result<GoArgs, CliError> {
782    let mut args = args.to_vec();
783    let format = take_format(&mut args)?;
784    if take_help(&args) {
785        print_go_help();
786        return Err(CliError::usage("help", "help requested"));
787    }
788
789    let mut shell = false;
790    let mut target: Option<String> = None;
791    let mut i = 0usize;
792    while i < args.len() {
793        match args[i].as_str() {
794            "--shell" => {
795                shell = true;
796                i += 1;
797            }
798            value if value.starts_with('-') => {
799                return Err(CliError::usage(
800                    "unknown-argument",
801                    format!("unknown argument: {value}"),
802                ));
803            }
804            value => {
805                if target.is_some() {
806                    return Err(CliError::usage(
807                        "too-many-arguments",
808                        "worktree go accepts exactly one slug, branch, or path",
809                    ));
810                }
811                target = Some(value.to_string());
812                i += 1;
813            }
814        }
815    }
816
817    let target = target.ok_or_else(|| {
818        CliError::usage("missing-target", "missing worktree slug, branch, or path")
819    })?;
820    Ok(GoArgs {
821        target,
822        shell,
823        format,
824    })
825}
826
827fn take_format(args: &mut Vec<String>) -> Result<OutputFormat, CliError> {
828    let mut format = OutputFormat::Text;
829    let mut i = 0usize;
830    while i < args.len() {
831        match args[i].as_str() {
832            "--format" => {
833                let Some(value) = args.get(i + 1) else {
834                    return Err(CliError::usage(
835                        "missing-format",
836                        "--format requires text or json",
837                    ));
838                };
839                format = parse_format_value(value)?;
840                args.drain(i..=i + 1);
841            }
842            value if value.starts_with("--format=") => {
843                let value = value.trim_start_matches("--format=");
844                format = parse_format_value(value)?;
845                args.remove(i);
846            }
847            _ => i += 1,
848        }
849    }
850    Ok(format)
851}
852
853fn parse_format_value(value: &str) -> Result<OutputFormat, CliError> {
854    match value {
855        "text" => Ok(OutputFormat::Text),
856        "json" => Ok(OutputFormat::Json),
857        other => Err(CliError::usage(
858            "invalid-format",
859            format!("unsupported output format: {other}"),
860        )),
861    }
862}
863
864fn detect_format(args: &[String]) -> OutputFormat {
865    let mut i = 0usize;
866    while i < args.len() {
867        match args[i].as_str() {
868            "--format" if args.get(i + 1).is_some_and(|value| value == "json") => {
869                return OutputFormat::Json;
870            }
871            "--format" => i += 2,
872            "--format=json" => return OutputFormat::Json,
873            _ => i += 1,
874        }
875    }
876    OutputFormat::Text
877}
878
879fn take_help(args: &[String]) -> bool {
880    args.iter()
881        .any(|arg| matches!(arg.as_str(), "-h" | "--help"))
882}
883
884fn reject_unknown_flags(args: &[String]) -> Result<(), CliError> {
885    if let Some(flag) = args.iter().find(|arg| arg.starts_with('-')) {
886        return Err(CliError::usage(
887            "unknown-argument",
888            format!("unknown argument: {flag}"),
889        ));
890    }
891    Ok(())
892}
893
894fn reject_extra_args(command: &str, args: &[String]) -> Result<(), CliError> {
895    reject_unknown_flags(args)?;
896    if !args.is_empty() {
897        return Err(CliError::usage(
898            "too-many-arguments",
899            format!("{command} does not accept positional arguments"),
900        ));
901    }
902    Ok(())
903}
904
905fn print_add_help() {
906    println!(
907        "Usage: git-cli worktree add <slug> [--from <ref>] [--kind <feature|bug|chore|docs|ci|refactor>] [--format text|json]"
908    );
909    println!(
910        "  --kind selects the branch prefix (feature->feat/, bug->fix/, chore->chore/, docs->docs/, ci->ci/, refactor->refactor/); default: feature"
911    );
912}
913
914fn print_list_help() {
915    println!("Usage: git-cli worktree list [--format text|json]");
916}
917
918fn print_remove_help() {
919    println!("Usage: git-cli worktree remove <slug-or-path> [--format text|json]");
920}
921
922fn print_prune_help() {
923    println!("Usage: git-cli worktree prune [--format text|json]");
924}
925
926fn print_go_help() {
927    println!("Usage: git-cli worktree go <slug-or-branch-or-path> [--shell] [--format text|json]");
928    println!("  Resolve a worktree and print its path (default), so you can `cd` into it.");
929    println!("  --shell  Print an evaluable `cd -- <path>` command instead of the bare path");
930}
931
932fn resolve_layout() -> Result<WorktreeLayout, CliError> {
933    let repo_root = require_repo_root()?;
934    let agent_home = resolve_agent_home()?;
935    let worktree_root = agent_home.join("worktrees");
936    let repo_key = repo_key_for_path(&repo_root);
937    Ok(WorktreeLayout {
938        agent_home,
939        worktree_root,
940        repo_root,
941        repo_key,
942    })
943}
944
945fn ensure_inside_git_repo() -> Result<(), CliError> {
946    if git_status_success(&["rev-parse", "--is-inside-work-tree"]) {
947        Ok(())
948    } else {
949        Err(CliError::runtime(
950            "not-git-repository",
951            "not in a git repository",
952        ))
953    }
954}
955
956fn require_repo_root() -> Result<PathBuf, CliError> {
957    ensure_inside_git_repo()?;
958    let root = primary_worktree_root()?;
959    absolute_existing_path(&root)
960}
961
962/// Resolve the repository's *primary* worktree, independent of the worktree the
963/// command is invoked from. `git rev-parse --show-toplevel` returns the current
964/// linked worktree, which would make the managed layout (`repo_key`, the
965/// managed/external classification, and slug-based add/remove paths) diverge
966/// when an agent runs from inside a linked worktree. `git worktree list` always
967/// emits the primary worktree first, so its first entry is the stable anchor
968/// for the managed layout from anywhere in the repository.
969fn primary_worktree_root() -> Result<PathBuf, CliError> {
970    let entries = list_linked_worktrees()
971        .map_err(|err| CliError::runtime("git-worktree-list-failed", err.to_string()))?;
972    let first = entries.into_iter().next().ok_or_else(|| {
973        CliError::runtime(
974            "repo-root-unavailable",
975            "unable to resolve git repository root",
976        )
977    })?;
978    Ok(first.path)
979}
980
981fn resolve_agent_home() -> Result<PathBuf, CliError> {
982    if let Some(value) = env_non_empty("AGENT_HOME") {
983        return absolute_or_existing_path(Path::new(&value));
984    }
985    if let Some(value) = env_non_empty("XDG_STATE_HOME") {
986        return absolute_or_existing_path(&Path::new(&value).join("agent-runtime-kit"));
987    }
988    if let Some(value) = env_non_empty("HOME") {
989        return absolute_or_existing_path(
990            &Path::new(&value).join(".local/state/agent-runtime-kit"),
991        );
992    }
993    Ok(env::temp_dir().join("agent-runtime-kit"))
994}
995
996fn env_non_empty(key: &str) -> Option<String> {
997    env::var_os(key)
998        .filter(|value| !value.is_empty())
999        .map(|value| value.to_string_lossy().to_string())
1000}
1001
1002fn absolute_path(path: &Path) -> Result<PathBuf, CliError> {
1003    if path.is_absolute() {
1004        return Ok(path.to_path_buf());
1005    }
1006    let cwd = env::current_dir().map_err(|err| {
1007        CliError::runtime(
1008            "current-dir-failed",
1009            format!("failed to read current dir: {err}"),
1010        )
1011    })?;
1012    Ok(cwd.join(path))
1013}
1014
1015fn absolute_or_existing_path(path: &Path) -> Result<PathBuf, CliError> {
1016    if path.exists() {
1017        return absolute_existing_path(path);
1018    }
1019    absolute_path(path)
1020}
1021
1022fn absolute_existing_path(path: &Path) -> Result<PathBuf, CliError> {
1023    fs::canonicalize(path).map_err(|err| {
1024        CliError::runtime(
1025            "canonicalize-path-failed",
1026            format!("failed to canonicalize {}: {err}", display_path(path)),
1027        )
1028    })
1029}
1030
1031fn repo_key_for_path(repo_root: &Path) -> String {
1032    let basename = repo_root
1033        .file_name()
1034        .and_then(|value| value.to_str())
1035        .unwrap_or("repo");
1036    let slug = sanitize_segment(basename, "repo");
1037    let hash = stable_short_hash(&display_path(repo_root));
1038    format!("{slug}-{hash}")
1039}
1040
1041fn normalize_slug(value: &str) -> Result<String, CliError> {
1042    let slug = sanitize_segment(value, "");
1043    if slug.is_empty() {
1044        return Err(CliError::usage(
1045            "invalid-slug",
1046            "slug must contain at least one ASCII letter or digit",
1047        ));
1048    }
1049    Ok(slug)
1050}
1051
1052fn sanitize_segment(value: &str, fallback: &str) -> String {
1053    let mut out = String::new();
1054    let mut last_dash = false;
1055    for ch in value.chars() {
1056        if ch.is_ascii_alphanumeric() {
1057            out.push(ch.to_ascii_lowercase());
1058            last_dash = false;
1059        } else if matches!(ch, '-' | '_' | '.') {
1060            out.push(ch);
1061            last_dash = false;
1062        } else if !last_dash {
1063            out.push('-');
1064            last_dash = true;
1065        }
1066    }
1067
1068    let trimmed = out.trim_matches(['-', '_', '.']);
1069    let mut sanitized: String = trimmed.chars().take(80).collect();
1070    sanitized = sanitized.trim_matches(['-', '_', '.']).to_string();
1071
1072    if sanitized.is_empty() {
1073        fallback.to_string()
1074    } else {
1075        sanitized
1076    }
1077}
1078
1079fn stable_short_hash(value: &str) -> String {
1080    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
1081    for byte in value.as_bytes() {
1082        hash ^= u64::from(*byte);
1083        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
1084    }
1085    format!("{:08x}", hash as u32)
1086}
1087
1088fn resolve_default_base_ref() -> String {
1089    if let Some(origin_head) = git_stdout_trimmed_optional(&[
1090        "symbolic-ref",
1091        "--quiet",
1092        "--short",
1093        "refs/remotes/origin/HEAD",
1094    ]) {
1095        return origin_head;
1096    }
1097    if git_status_success(&["show-ref", "--verify", "--quiet", "refs/heads/main"]) {
1098        return "main".to_string();
1099    }
1100    if git_status_success(&["show-ref", "--verify", "--quiet", "refs/heads/master"]) {
1101        return "master".to_string();
1102    }
1103    "HEAD".to_string()
1104}
1105
1106fn resolve_remove_target(target: &str, layout: &WorktreeLayout) -> Result<PathBuf, CliError> {
1107    let candidate = Path::new(target);
1108    if candidate.is_absolute() || path_has_multiple_components(candidate) {
1109        return absolute_path(candidate);
1110    }
1111
1112    let slug = normalize_slug(target)?;
1113    Ok(layout.worktree_root.join(&layout.repo_key).join(slug))
1114}
1115
1116fn path_has_multiple_components(path: &Path) -> bool {
1117    path.components()
1118        .filter(|component| !matches!(component, Component::CurDir))
1119        .count()
1120        > 1
1121}
1122
1123fn path_key(path: &Path) -> String {
1124    let normalized = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
1125    display_path(&normalized)
1126}
1127
1128fn is_managed_worktree(path: &Path, layout: &WorktreeLayout) -> bool {
1129    let managed_root = canonical_or_raw(&layout.worktree_root.join(&layout.repo_key));
1130    canonical_or_raw(path).starts_with(managed_root)
1131}
1132
1133fn canonical_or_raw(path: &Path) -> PathBuf {
1134    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
1135}
1136
1137fn is_empty_dir(path: &Path) -> std::io::Result<bool> {
1138    Ok(path.is_dir() && fs::read_dir(path)?.next().is_none())
1139}
1140
1141fn run_git_worktree_prune() -> Result<(), CliError> {
1142    git_output(&["worktree", "prune"]).map_err(|err| {
1143        CliError::runtime(
1144            "git-worktree-prune-failed",
1145            summarize_git_error(&err.to_string()),
1146        )
1147    })?;
1148    Ok(())
1149}
1150
1151fn emit_success<T: Serialize, F: FnOnce() -> String>(
1152    command: &str,
1153    format: OutputFormat,
1154    payload: &T,
1155    text: F,
1156) -> i32 {
1157    match format {
1158        OutputFormat::Json => {
1159            let envelope = Envelope::success(schema_version_for(BINARY, command, 1), payload);
1160            match serde_json::to_string(&envelope) {
1161                Ok(serialized) => {
1162                    println!("{serialized}");
1163                    exit::SUCCESS
1164                }
1165                Err(err) => {
1166                    eprintln!("failed to serialize JSON output: {err}");
1167                    exit::RUNTIME
1168                }
1169            }
1170        }
1171        OutputFormat::Text => {
1172            println!("{}", text());
1173            exit::SUCCESS
1174        }
1175    }
1176}
1177
1178fn emit_error(command: &str, format: OutputFormat, err: CliError) -> i32 {
1179    if err.code == "help" {
1180        return exit::SUCCESS;
1181    }
1182
1183    match format {
1184        OutputFormat::Json => {
1185            let mut envelope_error = EnvelopeError::new(err.code, err.message.as_ref());
1186            if let Some(hint) = &err.hint {
1187                envelope_error = envelope_error.with_hint(hint.as_ref());
1188            }
1189            if let Some(details) = err.details {
1190                envelope_error = envelope_error.with_details(*details);
1191            }
1192            let envelope: Envelope<()> =
1193                Envelope::failure(schema_version_for(BINARY, command, 1), envelope_error);
1194            match serde_json::to_string(&envelope) {
1195                Ok(serialized) => println!("{serialized}"),
1196                Err(serialize_err) => eprintln!("failed to serialize JSON error: {serialize_err}"),
1197            }
1198        }
1199        OutputFormat::Text => {
1200            eprintln!("{}", err.message);
1201            if let Some(hint) = &err.hint {
1202                eprintln!("hint: {hint}");
1203            }
1204        }
1205    }
1206    err.exit_code
1207}
1208
1209fn render_list_text(output: &ListOutput) -> String {
1210    if output.entries.is_empty() {
1211        return "No linked git worktrees found.".to_string();
1212    }
1213
1214    let mut lines = vec!["Worktrees:".to_string()];
1215    for entry in &output.entries {
1216        let branch = entry.branch.as_deref().unwrap_or("(detached)");
1217        let marker = if entry.managed { "managed" } else { "external" };
1218        lines.push(format!("  - {branch}: {} [{marker}]", entry.path));
1219    }
1220    lines.join("\n")
1221}
1222
1223fn summarize_git_error(message: &str) -> String {
1224    let trimmed = message.trim();
1225    let summary = trimmed
1226        .rsplit_once(" failed: ")
1227        .map(|(_, suffix)| suffix.trim())
1228        .unwrap_or(trimmed);
1229    summary.replace('\n', " ")
1230}
1231
1232fn display_path(path: &Path) -> String {
1233    path.to_string_lossy().to_string()
1234}
1235
1236#[cfg(test)]
1237mod tests {
1238    use super::{
1239        LinkedWorktree, branch_name_hint, normalize_slug, parse_worktree_porcelain,
1240        repo_key_for_path, resolve_go_target, resolve_remove_target,
1241    };
1242    use pretty_assertions::{assert_eq, assert_ne};
1243    use std::path::{Path, PathBuf};
1244
1245    fn managed_entry(path: &str, branch: Option<&str>) -> LinkedWorktree {
1246        LinkedWorktree {
1247            path: PathBuf::from(path),
1248            head: Some("0123456789abcdef".to_string()),
1249            branch: branch.map(str::to_string),
1250            bare: false,
1251            detached: branch.is_none(),
1252            prunable: None,
1253        }
1254    }
1255
1256    #[test]
1257    fn repo_key_includes_basename_and_stable_hash() {
1258        let first = repo_key_for_path(Path::new("/tmp/a/repo"));
1259        let second = repo_key_for_path(Path::new("/tmp/b/repo"));
1260        assert!(first.starts_with("repo-"));
1261        assert!(second.starts_with("repo-"));
1262        assert_ne!(first, second);
1263        assert_eq!(first, repo_key_for_path(Path::new("/tmp/a/repo")));
1264    }
1265
1266    #[test]
1267    fn normalize_slug_keeps_branch_safe_path_segment() {
1268        assert_eq!(normalize_slug("Topic One").expect("slug"), "topic-one");
1269        assert_eq!(normalize_slug("fix/foo_bar").expect("slug"), "fix-foo_bar");
1270        assert!(normalize_slug("!!!").is_err());
1271    }
1272
1273    #[test]
1274    fn parse_worktree_porcelain_captures_branch_and_detached_entries() {
1275        let entries = parse_worktree_porcelain(
1276            "worktree /repo\nHEAD 111\nbranch refs/heads/main\n\nworktree /repo/wt\nHEAD 222\ndetached\n",
1277        );
1278        assert_eq!(entries.len(), 2);
1279        assert_eq!(entries[0].path, Path::new("/repo"));
1280        assert_eq!(entries[0].branch.as_deref(), Some("main"));
1281        assert_eq!(entries[1].path, Path::new("/repo/wt"));
1282        assert!(entries[1].detached);
1283    }
1284
1285    #[test]
1286    fn worktree_candidates_include_slugs_and_branches() {
1287        let entries = parse_worktree_porcelain(
1288            "worktree /repo/main\nHEAD 111\nbranch refs/heads/main\n\nworktree /repo/.worktrees/feat-x\nHEAD 222\nbranch refs/heads/feat/x\n\nworktree /repo/.worktrees/detached-wt\nHEAD 333\ndetached\n",
1289        );
1290        let candidates = super::worktree_candidates_from_entries(&entries);
1291        // Slugs are path basenames; branch names are stripped of `refs/heads/`.
1292        assert!(candidates.contains(&"main".to_string()));
1293        assert!(candidates.contains(&"feat-x".to_string()));
1294        assert!(candidates.contains(&"feat/x".to_string()));
1295        // Detached worktrees still contribute their slug (no branch).
1296        assert!(candidates.contains(&"detached-wt".to_string()));
1297        // Sorted + deduped: `main` is both a slug basename and a branch name but
1298        // appears once.
1299        assert_eq!(
1300            candidates.iter().filter(|c| c.as_str() == "main").count(),
1301            1
1302        );
1303    }
1304
1305    #[test]
1306    fn resolve_remove_target_uses_managed_path_for_slug() {
1307        let layout = super::WorktreeLayout {
1308            agent_home: Path::new("/agent").to_path_buf(),
1309            worktree_root: Path::new("/agent/worktrees").to_path_buf(),
1310            repo_root: Path::new("/repo").to_path_buf(),
1311            repo_key: "repo-12345678".to_string(),
1312        };
1313        let target = resolve_remove_target("Topic One", &layout).expect("target");
1314        assert_eq!(
1315            target,
1316            Path::new("/agent/worktrees/repo-12345678/topic-one")
1317        );
1318    }
1319
1320    #[test]
1321    fn branch_name_hint_points_to_slug_when_target_is_branch() {
1322        let entries = vec![managed_entry(
1323            "/agent/worktrees/repo-12345678/closeout-records-delivery",
1324            Some("docs/closeout-records-delivery"),
1325        )];
1326        let hint = branch_name_hint("docs/closeout-records-delivery", &entries).expect("hint");
1327        assert!(hint.contains("branch name"), "hint was: {hint}");
1328        assert!(
1329            hint.contains("closeout-records-delivery"),
1330            "hint was: {hint}"
1331        );
1332        assert!(
1333            hint.contains("/agent/worktrees/repo-12345678/closeout-records-delivery"),
1334            "hint was: {hint}"
1335        );
1336    }
1337
1338    #[test]
1339    fn branch_name_hint_absent_when_target_matches_no_branch() {
1340        let entries = vec![managed_entry(
1341            "/agent/worktrees/repo-12345678/closeout-records-delivery",
1342            Some("docs/closeout-records-delivery"),
1343        )];
1344        assert!(branch_name_hint("docs/typo", &entries).is_none());
1345        assert!(branch_name_hint("closeout-records-delivery", &entries).is_none());
1346    }
1347
1348    #[test]
1349    fn resolve_go_target_matches_branch_path_slug_and_basename() {
1350        let layout = super::WorktreeLayout {
1351            agent_home: Path::new("/agent").to_path_buf(),
1352            worktree_root: Path::new("/agent/worktrees").to_path_buf(),
1353            repo_root: Path::new("/repo").to_path_buf(),
1354            repo_key: "repo-12345678".to_string(),
1355        };
1356        let entries = vec![
1357            managed_entry("/repo", Some("main")),
1358            managed_entry(
1359                "/agent/worktrees/repo-12345678/topic-one",
1360                Some("feat/topic-one"),
1361            ),
1362        ];
1363
1364        let by_branch =
1365            resolve_go_target("feat/topic-one", &layout, &entries).expect("branch match");
1366        assert_eq!(
1367            by_branch.path,
1368            Path::new("/agent/worktrees/repo-12345678/topic-one")
1369        );
1370
1371        let by_slug = resolve_go_target("topic-one", &layout, &entries).expect("slug match");
1372        assert_eq!(
1373            by_slug.path,
1374            Path::new("/agent/worktrees/repo-12345678/topic-one")
1375        );
1376
1377        let by_path = resolve_go_target("/repo", &layout, &entries).expect("path match");
1378        assert_eq!(by_path.path, Path::new("/repo"));
1379
1380        let unknown = resolve_go_target("does-not-exist", &layout, &entries);
1381        assert!(unknown.is_err(), "unknown target should not resolve");
1382    }
1383
1384    #[test]
1385    fn branch_name_hint_skips_detached_entries() {
1386        let entries = vec![managed_entry(
1387            "/agent/worktrees/repo-12345678/detached",
1388            None,
1389        )];
1390        assert!(branch_name_hint("anything", &entries).is_none());
1391    }
1392}