worktrunk 0.48.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//! Worktree resolution and path computation.
//!
//! Functions for resolving worktree arguments and computing expected paths.

use std::io::IsTerminal;
use std::path::{Path, PathBuf};

use anyhow::Context;
use color_print::cformat;
use normalize_path::NormalizePath;
use worktrunk::config::UserConfig;
use worktrunk::git::{GitError, Repository, ResolvedWorktree};
use worktrunk::path::{format_path_for_display, paths_match};
use worktrunk::styling::{
    eprintln, format_toml, hint_message, info_message, success_message, warning_message,
};

use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};

use super::types::OperationMode;

/// Resolve a worktree argument using branch-first lookup.
///
/// Resolution order:
/// 1. Special symbols ("@", "-", "^") are handled specially
/// 2. Resolve argument as branch name
/// 3. If branch has a worktree, return it
/// 4. For `Remove`: fall back to path-based lookup (supports detached worktrees)
/// 5. Otherwise, return branch-only (no worktree)
///
/// For `CreateOrSwitch` context: If the branch has no worktree but expected
/// path is occupied by another branch's worktree, an error is raised.
///
/// For `Remove` context: If branch lookup fails to find a worktree, the
/// argument is tried as a filesystem path (absolute or relative to CWD).
/// This supports removing detached HEAD worktrees which have no branch name.
pub fn resolve_worktree_arg(
    repo: &Repository,
    name: &str,
    config: &UserConfig,
    context: OperationMode,
) -> anyhow::Result<ResolvedWorktree> {
    // Special symbols - delegate to Repository for consistent error handling
    match name {
        "@" | "-" | "^" => {
            return repo.resolve_worktree(name);
        }
        _ => {}
    }

    // Resolve as branch name
    let branch = repo.resolve_worktree_name(name)?;

    // Branch-first: check if branch has worktree anywhere
    if let Some(path) = repo.worktree_for_branch(&branch)? {
        return Ok(ResolvedWorktree::Worktree {
            path,
            branch: Some(branch),
        });
    }

    // No worktree for branch - check if expected path is occupied (only for create/switch)
    if context == OperationMode::CreateOrSwitch {
        let expected_path = compute_worktree_path(repo, name, config)?;
        if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {
            // Path is occupied by a different branch's worktree
            return Err(GitError::WorktreePathOccupied {
                branch,
                path: expected_path,
                occupant: occupant_branch,
            }
            .into());
        }
    }

    // For Remove: fall back to path-based lookup (supports detached worktrees)
    if context == OperationMode::Remove {
        let candidate = Path::new(name);
        // Try as absolute path, or resolve relative to CWD
        let abs_path = if candidate.is_absolute() {
            candidate.to_path_buf()
        } else {
            std::env::current_dir()
                .context("Failed to determine current directory")?
                .join(candidate)
        };
        if let Some((path, wt_branch)) = repo.worktree_at_path(&abs_path)? {
            return Ok(ResolvedWorktree::Worktree {
                path,
                branch: wt_branch,
            });
        }
    }

    // No worktree for branch (and path not occupied, or we don't care about path)
    Ok(ResolvedWorktree::BranchOnly { branch })
}

/// Compute the expected worktree path for a branch name.
///
/// For the default branch, returns the repo root (main worktree location).
/// For other branches, applies the `worktree-path` template from config.
///
/// Uses cached values from Repository for `default_branch` and `is_bare`.
pub fn compute_worktree_path(
    repo: &Repository,
    branch: &str,
    config: &UserConfig,
) -> anyhow::Result<PathBuf> {
    let repo_root = repo.repo_path()?;
    let default_branch = repo.default_branch().unwrap_or_default();
    let is_bare = repo.is_bare()?;

    // Default branch lives at repo root (main worktree), not a templated path.
    // Exception: bare repos have no main worktree, so all branches use templated paths.
    if !is_bare && branch == default_branch {
        return Ok(repo_root.to_path_buf());
    }

    let repo_name = repo_root
        .file_name()
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Repository path has no filename: {}",
                format_path_for_display(repo_root)
            )
        })?
        .to_str()
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Repository path contains invalid UTF-8: {}",
                format_path_for_display(repo_root)
            )
        })?;

    let project = repo.project_identifier().ok();
    let expanded_path = config.format_path(repo_name, branch, repo, project.as_deref())?;

    Ok(repo_root.join(expanded_path).normalize())
}

/// Check if a worktree is at its expected path based on config template.
///
/// Returns true if the worktree's actual path matches what `compute_worktree_path`
/// would generate for its branch. Detached HEAD always returns false (no expected path).
///
/// Uses canonicalization to handle symlinks and relative paths correctly.
/// Uses cached values from Repository for `default_branch` and `is_bare`.
pub fn is_worktree_at_expected_path(
    wt: &worktrunk::git::WorktreeInfo,
    repo: &Repository,
    config: &UserConfig,
) -> bool {
    match &wt.branch {
        Some(branch) => compute_worktree_path(repo, branch, config)
            .map(|expected| paths_match(&wt.path, &expected))
            .unwrap_or(false),
        None => false,
    }
}

/// Returns the expected path if `actual_path` differs from the template-computed path.
///
/// Returns `Some(expected_path)` when there's a mismatch, `None` when paths match.
/// Used to show path mismatch warnings in switch, picker, remove, and merge.
pub fn path_mismatch(
    repo: &Repository,
    branch: &str,
    actual_path: &std::path::Path,
    config: &UserConfig,
) -> Option<PathBuf> {
    compute_worktree_path(repo, branch, config)
        .ok()
        .filter(|expected| !paths_match(actual_path, expected))
}

/// Compute a user-facing display name for a worktree.
///
/// Returns styled content with branch names bolded:
/// - If branch is consistent with worktree location: just the branch name (bolded)
/// - If branch differs from expected location: `dir_name (on **branch**)` (both bolded)
/// - If detached HEAD: `dir_name (detached)` (dir_name bolded)
///
/// "Consistent" means the worktree path matches `compute_worktree_path(branch)`,
/// which returns repo root for default branch and templated path for others.
pub fn worktree_display_name(
    wt: &worktrunk::git::WorktreeInfo,
    repo: &Repository,
    config: &UserConfig,
) -> String {
    let dir_name = wt.dir_name();

    match &wt.branch {
        Some(branch) => {
            if is_worktree_at_expected_path(wt, repo, config) {
                cformat!("<bold>{branch}</>")
            } else {
                cformat!("<bold>{dir_name}</> (on <bold>{branch}</>)")
            }
        }
        None => cformat!("<bold>{dir_name}</> (detached)"),
    }
}

/// Generate a backup path for the given path with a timestamp suffix.
///
/// For paths with extensions: `file.txt` → `file.txt.bak.TIMESTAMP`
/// For paths without extensions: `foo` → `foo.bak.TIMESTAMP`
///
/// Returns an error for unusual paths without a file name (e.g., `/` or `..`).
pub(super) fn generate_backup_path(
    path: &std::path::Path,
    suffix: &str,
) -> anyhow::Result<PathBuf> {
    let file_name = path.file_name().ok_or_else(|| {
        anyhow::anyhow!(
            "Cannot generate backup path for {}",
            format_path_for_display(path)
        )
    })?;

    if path.extension().is_none() {
        // Path has no extension (e.g., /repo/feature)
        Ok(path.with_file_name(format!("{}.bak.{suffix}", file_name.to_string_lossy())))
    } else {
        // Path has an extension (e.g., /repo.feature or /file.txt)
        Ok(path.with_extension(format!(
            "{}.bak.{suffix}",
            path.extension()
                .map(|e| e.to_string_lossy().to_string())
                .unwrap_or_default()
        )))
    }
}

/// Compute the backup path for clobber operations.
///
/// Returns `Ok(None)` if path doesn't exist.
/// Returns `Ok(Some(backup_path))` if clobber is true and path exists.
/// Returns `Err(GitError::WorktreePathExists)` if clobber is false and path exists.
pub(super) fn compute_clobber_backup(
    path: &Path,
    branch: &str,
    clobber: bool,
    create: bool,
) -> anyhow::Result<Option<PathBuf>> {
    if !path.exists() {
        return Ok(None);
    }

    if clobber {
        let timestamp = worktrunk::utils::epoch_now() as i64;
        let datetime =
            chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);
        let suffix = datetime.format("%Y%m%d-%H%M%S").to_string();
        let backup_path = generate_backup_path(path, &suffix)?;

        if backup_path.exists() {
            anyhow::bail!(
                "Backup path already exists: {}",
                worktrunk::path::format_path_for_display(&backup_path)
            );
        }
        Ok(Some(backup_path))
    } else {
        Err(GitError::WorktreePathExists {
            branch: branch.to_string(),
            path: path.to_path_buf(),
            create,
        }
        .into())
    }
}

/// Suggested worktree-path template for bare repos with hidden directory names.
///
/// Places worktrees as siblings of the bare repo directory inside the parent,
/// e.g., `myproject/.git` + branch `feature` → `myproject/feature`.
/// Uses an absolute path (`repo_path`/../) to avoid ambiguity with relative resolution.
const BARE_REPO_WORKTREE_PATH: &str = "{{ repo_path }}/../{{ branch | sanitize }}";

/// Check whether a template string references `{{ repo }}` or `{{ main_worktree }}`.
fn template_references_repo_name(template: &str) -> bool {
    worktrunk::config::template_references_var(template, "repo")
        || worktrunk::config::template_references_var(template, "main_worktree")
}

/// Offer to set a project-level `worktree-path` for bare repos with hidden directory names.
///
/// When a bare repo lives at a hidden path like `.git` or `.bare`, the `{{ repo }}`
/// template variable resolves to that directory name, producing broken worktree paths.
/// This function detects the situation and offers to set a project-level override.
///
/// Returns `true` if config was modified (caller should use the updated config).
pub fn offer_bare_repo_worktree_path_fix(
    repo: &Repository,
    config: &mut UserConfig,
) -> anyhow::Result<bool> {
    if !repo.is_bare()? {
        return Ok(false);
    }

    let repo_path = repo.repo_path()?;
    let repo_name = repo_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    if !repo_name.starts_with('.') {
        return Ok(false);
    }

    if repo
        .config_value("worktrunk.skip-bare-repo-prompt")
        .unwrap_or(None)
        .is_some()
    {
        return Ok(false);
    }

    let project_id = repo.project_identifier()?;
    let template = config.worktree_path_for_project(&project_id);
    if !template_references_repo_name(&template) {
        return Ok(false);
    }

    // Display names for messages
    let display_path = repo_path
        .parent()
        .map(|p| format_path_for_display(p).to_string())
        .unwrap_or_else(|| format_path_for_display(repo_path).to_string());
    let parent_name = repo_path
        .parent()
        .and_then(|p| p.file_name())
        .and_then(|n| n.to_str())
        .unwrap_or("project");

    // Example paths to show the user what changes
    let example_bad = format!("{parent_name}/{repo_name}.feature-auth");
    let example_good = format!("{parent_name}/feature-auth");

    let config_path_display = worktrunk::config::config_path()
        .map(|p| format_path_for_display(&p).to_string())
        .unwrap_or_else(|| "~/.config/worktrunk/config.toml".to_string());

    // Non-interactive: warn and show the config to add.
    if !std::io::stdin().is_terminal() {
        eprintln!(
            "{}",
            warning_message(cformat!(
                "Bare repo at <bold>{parent_name}/{repo_name}</> — worktrees will be at <bold>{example_bad}</>"
            ))
        );
        eprintln!(
            "{}",
            hint_message(cformat!(
                "To place worktrees at <underline>{example_good}</>, add to <underline>{config_path_display}</>:"
            ))
        );
        let config_snippet =
            format!("[projects.\"{project_id}\"]\nworktree-path = \"{BARE_REPO_WORKTREE_PATH}\"");
        eprintln!("{}", format_toml(&config_snippet));
        return Ok(false);
    }

    // Interactive: show diagnosis, then prompt
    eprintln!(
        "{}",
        warning_message(cformat!(
            "Bare repo at <bold>{parent_name}/{repo_name}</> — worktrees will be at <bold>{example_bad}</>"
        ))
    );

    let config_path_for_preview = config_path_display.clone();
    let project_id_for_preview = project_id.clone();
    match prompt_yes_no_preview(
        &cformat!("Configure worktree-path to place worktrees at <bold>{example_good}</>?"),
        move || {
            eprintln!(
                "{}",
                info_message(cformat!("Would add to <bold>{config_path_for_preview}</>:"))
            );
            let preview = format!(
                "[projects.\"{project_id_for_preview}\"]\nworktree-path = \"{BARE_REPO_WORKTREE_PATH}\""
            );
            eprintln!("{}", format_toml(&preview));
            eprintln!();
        },
    )? {
        PromptResponse::Accepted => {
            config.set_project_worktree_path(
                &project_id,
                BARE_REPO_WORKTREE_PATH.to_string(),
                None,
            )?;
            print_accepted_message(&display_path, &config_path_display);
            Ok(true)
        }
        PromptResponse::Declined => {
            if let Err(e) = repo.set_config("worktrunk.skip-bare-repo-prompt", "true") {
                log::warn!("Failed to save skip-bare-repo-prompt to git config: {e}");
            }
            Ok(false)
        }
    }
}

fn print_accepted_message(display_path: &str, config_path: &str) {
    eprintln!(
        "{}",
        success_message(cformat!(
            "Set <bold>worktree-path</> for <bold>{display_path}</>:"
        ))
    );
    let global_config = format!("worktree-path = \"{BARE_REPO_WORKTREE_PATH}\"");
    eprintln!("{}", format_toml(&global_config));
    eprintln!(
        "{}",
        hint_message(cformat!(
            "To set globally, add to <underline>{config_path}</>"
        ))
    );

    // Blank line separates this setup phase from the main operation that follows
    eprintln!();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_backup_path_with_extension() {
        // Paths with extensions: file.txt -> file.txt.bak.TIMESTAMP
        let path = PathBuf::from("/tmp/repo.feature");
        let backup = generate_backup_path(&path, "20250101-000000").unwrap();
        assert_eq!(
            backup,
            PathBuf::from("/tmp/repo.feature.bak.20250101-000000")
        );

        let path = PathBuf::from("/tmp/file.txt");
        let backup = generate_backup_path(&path, "20250101-000000").unwrap();
        assert_eq!(backup, PathBuf::from("/tmp/file.txt.bak.20250101-000000"));
    }

    #[test]
    fn test_generate_backup_path_without_extension() {
        // Paths without extensions: foo -> foo.bak.TIMESTAMP
        let path = PathBuf::from("/tmp/repo/feature");
        let backup = generate_backup_path(&path, "20250101-000000").unwrap();
        assert_eq!(
            backup,
            PathBuf::from("/tmp/repo/feature.bak.20250101-000000")
        );

        let path = PathBuf::from("/tmp/mydir");
        let backup = generate_backup_path(&path, "20250101-000000").unwrap();
        assert_eq!(backup, PathBuf::from("/tmp/mydir.bak.20250101-000000"));
    }

    #[test]
    fn test_generate_backup_path_unusual_paths() {
        // Root path has no file name
        let path = PathBuf::from("/");
        assert!(generate_backup_path(&path, "20250101-000000").is_err());

        // Parent reference has no file name
        let path = PathBuf::from("..");
        assert!(generate_backup_path(&path, "20250101-000000").is_err());
    }

    #[test]
    fn test_template_references_repo_name_default() {
        // Default template uses {{ repo }}
        assert!(template_references_repo_name(
            "{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
        ));
    }

    #[test]
    fn test_template_references_repo_name_with_filter() {
        assert!(template_references_repo_name("{{ repo | sanitize }}"));
    }

    #[test]
    fn test_template_references_repo_name_deprecated_alias() {
        assert!(template_references_repo_name(
            "{{ main_worktree }}.{{ branch }}"
        ));
    }

    #[test]
    fn test_template_references_repo_name_not_repo_path() {
        // {{ repo_path }} should NOT match
        assert!(!template_references_repo_name(
            "{{ repo_path }}/../{{ branch | sanitize }}"
        ));
    }

    #[test]
    fn test_template_references_repo_name_no_repo() {
        assert!(!template_references_repo_name("../{{ branch | sanitize }}"));
    }

    #[test]
    fn test_template_references_repo_name_no_spaces() {
        assert!(template_references_repo_name("{{repo}}.{{branch}}"));
    }

    #[test]
    fn test_template_references_repo_name_no_braces() {
        // "repo" outside template expressions should not match
        assert!(!template_references_repo_name("my-repo-path/{{ branch }}"));
    }

    #[test]
    fn test_template_references_repo_name_substring_prefix() {
        // "myrepo" should NOT match — "repo" is a suffix of a longer identifier
        assert!(!template_references_repo_name("{{ myrepo }}"));
        assert!(!template_references_repo_name("{{ norepo }}"));
    }
}