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