worktrunk 0.35.2

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
use insta::assert_snapshot;
use std::path::PathBuf;
use worktrunk::git::{FailedCommand, GitError, HookType, WorktrunkError, add_hook_skip_hint};

// ============================================================================
// Worktree errors
// ============================================================================

#[test]
fn display_worktree_removal_failed() {
    let err = GitError::WorktreeRemovalFailed {
        branch: "feature-x".into(),
        path: PathBuf::from("/tmp/repo.feature-x"),
        error: "fatal: worktree is dirty\nerror: could not remove worktree".into(),
        remaining_entries: None,
    };

    assert_snapshot!("worktree_removal_failed", err.to_string());
}

#[test]
fn display_worktree_removal_failed_directory_not_empty() {
    let err = GitError::WorktreeRemovalFailed {
        branch: "feature-x".into(),
        path: PathBuf::from("/tmp/repo.feature-x"),
        error: "error: failed to delete '/tmp/repo.feature-x': Directory not empty".into(),
        remaining_entries: Some(vec![
            ".vite/".into(),
            "node_modules/".into(),
            "target/".into(),
        ]),
    };

    assert_snapshot!(
        "worktree_removal_failed_directory_not_empty",
        err.to_string()
    );
}

#[test]
fn display_worktree_removal_failed_with_remaining_entries() {
    let err = GitError::WorktreeRemovalFailed {
        branch: "feature-x".into(),
        path: PathBuf::from("/tmp/repo.feature-x"),
        error: "error: failed to remove '/tmp/repo.feature-x/target': Permission denied".into(),
        remaining_entries: Some(vec!["target/".into()]),
    };

    assert_snapshot!(
        "worktree_removal_failed_with_remaining_entries",
        err.to_string()
    );
}

#[test]
fn display_worktree_removal_failed_many_remaining_entries() {
    let err = GitError::WorktreeRemovalFailed {
        branch: "feature-x".into(),
        path: PathBuf::from("/tmp/repo.feature-x"),
        error: "error: failed to delete '/tmp/repo.feature-x': Directory not empty".into(),
        remaining_entries: Some((0..15).map(|i| format!("dir-{i:02}/")).collect()),
    };

    assert_snapshot!(
        "worktree_removal_failed_many_remaining_entries",
        err.to_string()
    );
}

#[test]
fn display_worktree_creation_failed() {
    let err = GitError::WorktreeCreationFailed {
        branch: "feature-y".into(),
        base_branch: Some("main".into()),
        error: "fatal: '/tmp/repo.feature-y' already exists".into(),
        command: None,
    };

    assert_snapshot!("worktree_creation_failed", err.to_string());
}

#[test]
fn display_worktree_creation_failed_with_command() {
    let err = GitError::WorktreeCreationFailed {
        branch: "fix".into(),
        base_branch: Some("main".into()),
        error: "Preparing worktree (new branch 'fix')\nfatal: cannot lock ref 'refs/heads/fix'"
            .into(),
        command: Some(FailedCommand {
            command: "git worktree add /tmp/repo.fix -b fix main".into(),
            exit_info: "exit code 128".into(),
        }),
    };

    assert_snapshot!("worktree_creation_failed_with_command", err.to_string());
}

#[test]
fn display_worktree_missing() {
    let err = GitError::WorktreeMissing {
        branch: "stale-branch".into(),
    };

    assert_snapshot!("worktree_missing", err.to_string());
}

#[test]
fn branch_not_found() {
    let err = GitError::BranchNotFound {
        branch: "nonexistent".into(),
        show_create_hint: true,
        last_fetch_ago: None,
    };

    assert_snapshot!("branch_not_found", err.to_string());
}

#[test]
fn branch_not_found_with_fetch_time() {
    let err = GitError::BranchNotFound {
        branch: "nonexistent".into(),
        show_create_hint: true,
        last_fetch_ago: Some("last fetched 3h ago".into()),
    };

    assert_snapshot!("branch_not_found_with_fetch_time", err.to_string());
}

#[test]
fn branch_not_found_no_create_hint() {
    let err = GitError::BranchNotFound {
        branch: "nonexistent".into(),
        show_create_hint: false,
        last_fetch_ago: None,
    };

    assert_snapshot!("branch_not_found_no_create_hint", err.to_string());
}

#[test]
fn display_worktree_path_occupied() {
    let err = GitError::WorktreePathOccupied {
        branch: "feature-z".into(),
        path: PathBuf::from("/tmp/repo.feature-z"),
        occupant: Some("other-branch".into()),
    };

    assert_snapshot!("worktree_path_occupied", err.to_string());
}

#[test]
fn display_worktree_path_exists() {
    let err = GitError::WorktreePathExists {
        branch: "feature".to_string(),
        path: PathBuf::from("/tmp/repo.feature"),
        create: false,
    };

    assert_snapshot!("worktree_path_exists", err.to_string());
}

#[test]
fn display_cannot_remove_main_worktree() {
    let err = GitError::CannotRemoveMainWorktree;

    assert_snapshot!("cannot_remove_main_worktree", err.to_string());
}

// ============================================================================
// Git state errors
// ============================================================================

#[test]
fn display_detached_head() {
    let err = GitError::DetachedHead {
        action: Some("merge".into()),
    };

    assert_snapshot!("detached_head", err.to_string());
}

#[test]
fn display_detached_head_no_action() {
    let err = GitError::DetachedHead { action: None };

    assert_snapshot!("detached_head_no_action", err.to_string());
}

#[test]
fn display_uncommitted_changes() {
    let err = GitError::UncommittedChanges {
        action: Some("remove worktree".into()),
        branch: None,
        force_hint: false,
    };

    assert_snapshot!("uncommitted_changes", err.to_string());
}

#[test]
fn display_uncommitted_changes_with_branch() {
    let err = GitError::UncommittedChanges {
        action: Some("remove worktree".into()),
        branch: Some("feature-branch".into()),
        force_hint: false,
    };

    assert_snapshot!("uncommitted_changes_with_branch", err.to_string());
}

#[test]
fn display_uncommitted_changes_with_force_hint() {
    let err = GitError::UncommittedChanges {
        action: Some("remove worktree".into()),
        branch: Some("feature-branch".into()),
        force_hint: true,
    };

    assert_snapshot!("uncommitted_changes_with_force_hint", err.to_string());
}

#[test]
fn display_branch_already_exists() {
    let err = GitError::BranchAlreadyExists {
        branch: "feature".into(),
    };

    assert_snapshot!("branch_already_exists", err.to_string());
}

// ============================================================================
// Merge/push errors
// ============================================================================

#[test]
fn display_push_failed() {
    let err = GitError::PushFailed {
        target_branch: "main".into(),
        error: "To /Users/user/workspace/repo/.git\n ! [remote rejected] HEAD -> main (Up-to-date check failed)\nerror: failed to push some refs to '/Users/user/workspace/repo/.git'".into(),
    };

    assert_snapshot!("push_failed", err.to_string());
}

#[test]
fn display_conflicting_changes() {
    let err = GitError::ConflictingChanges {
        target_branch: "main".into(),
        files: vec!["src/main.rs".into(), "src/lib.rs".into()],
        worktree_path: PathBuf::from("/tmp/repo.main"),
    };

    assert_snapshot!("conflicting_changes", err.to_string());
}

#[test]
fn display_not_fast_forward() {
    let err = GitError::NotFastForward {
        target_branch: "main".into(),
        commits_formatted: "abc1234 Fix bug\ndef5678 Add feature".into(),
        in_merge_context: false,
    };

    assert_snapshot!("not_fast_forward", err.to_string());
}

#[test]
fn display_not_fast_forward_merge_context() {
    let err = GitError::NotFastForward {
        target_branch: "main".into(),
        commits_formatted: "abc1234 New commit on main".into(),
        in_merge_context: true,
    };

    assert_snapshot!("not_fast_forward_merge_context", err.to_string());
}

#[test]
fn display_rebase_conflict() {
    let err = GitError::RebaseConflict {
        target_branch: "main".into(),
        git_output: "CONFLICT (content): Merge conflict in src/main.rs".into(),
    };

    assert_snapshot!("rebase_conflict", err.to_string());
}

// ============================================================================
// Validation/other errors
// ============================================================================

#[test]
fn display_not_interactive() {
    let err = GitError::NotInteractive;

    assert_snapshot!("not_interactive", err.to_string());
}

#[test]
fn display_llm_command_failed() {
    let err = GitError::LlmCommandFailed {
        command: "llm --model claude".into(),
        error: "Error: API key not found".into(),
        reproduction_command: None,
    };

    assert_snapshot!("llm_command_failed", err.to_string());
}

#[test]
fn display_llm_command_failed_with_reproduction() {
    let err = GitError::LlmCommandFailed {
        command: "llm --model claude".into(),
        error: "Error: API key not found".into(),
        reproduction_command: Some("wt step commit --show-prompt | llm --model claude".into()),
    };

    assert_snapshot!("llm_command_failed_with_reproduction", err.to_string());
}

#[test]
fn display_project_config_not_found() {
    let err = GitError::ProjectConfigNotFound {
        config_path: PathBuf::from("/tmp/repo/.config/wt.toml"),
    };

    assert_snapshot!("project_config_not_found", err.to_string());
}

#[test]
fn display_parse_error() {
    let err = GitError::ParseError {
        message: "Invalid branch name format".into(),
    };

    assert_snapshot!("parse_error", err.to_string());
}

#[test]
fn display_remote_only_branch() {
    let err = GitError::RemoteOnlyBranch {
        branch: "feature".into(),
        remote: "origin".into(),
    };

    assert_snapshot!("remote_only_branch", err.to_string());
}

#[test]
fn display_other() {
    let err = GitError::Other {
        message: "Unexpected git error".into(),
    };

    assert_snapshot!("other", err.to_string());
}

// ============================================================================
// WorktrunkError display tests
// ============================================================================

#[test]
fn display_hook_command_failed_with_name() {
    let err = WorktrunkError::HookCommandFailed {
        hook_type: HookType::PreMerge,
        command_name: Some("test".into()),
        error: "exit code 1".into(),
        exit_code: Some(1),
    };

    assert_snapshot!("hook_command_failed_with_name", err.to_string());
}

#[test]
fn display_hook_command_failed_without_name() {
    let err = WorktrunkError::HookCommandFailed {
        hook_type: HookType::PreStart,
        command_name: None,
        error: "command not found".into(),
        exit_code: Some(127),
    };

    assert_snapshot!("hook_command_failed_without_name", err.to_string());
}

/// Shows the complete error with hint, as users would see it.
#[test]
fn display_hook_command_failed_with_skip_hint() {
    let err: anyhow::Error = WorktrunkError::HookCommandFailed {
        hook_type: HookType::PreMerge,
        command_name: Some("test".into()),
        error: "exit code 1".into(),
        exit_code: Some(1),
    }
    .into();

    // Wrap with hint (as done by commands supporting --no-hooks)
    let err_with_hint = add_hook_skip_hint(err);

    assert_snapshot!(
        "hook_command_failed_with_skip_hint",
        err_with_hint.to_string()
    );
}

// ============================================================================
// Multiline error formatting (tests the pattern used in main.rs catchall)
// ============================================================================

/// Test that multiline errors without context are formatted with header + gutter.
/// This is the pattern used in main.rs for untyped anyhow errors.
#[test]
fn multiline_error_formatting() {
    use worktrunk::styling::{error_message, format_with_gutter};

    // Simulate what main.rs does for multiline errors without context:
    // 1. Show "Command failed" header
    // 2. Show the error content in a gutter

    let multiline_error =
        "fatal: Unable to read current working directory\nerror: Could not determine cwd";

    let header = error_message("Command failed").to_string();
    let gutter = format_with_gutter(multiline_error, None);

    // Verify header has error symbol
    assert!(
        header.contains("Command failed"),
        "Header should contain 'Command failed'"
    );

    // Verify gutter contains both lines
    assert!(
        gutter.contains("fatal: Unable to read"),
        "Gutter should contain first line"
    );
    assert!(
        gutter.contains("Could not determine cwd"),
        "Gutter should contain second line"
    );

    // Snapshot the combined output
    assert_snapshot!(
        "multiline_error_formatting",
        format!("{}\n{}", header, gutter)
    );
}

/// Test that CRLF and CR line endings are normalized before formatting.
/// main.rs normalizes: msg.replace("\r\n", "\n").replace('\r', "\n")
#[test]
fn multiline_error_crlf_normalization() {
    use worktrunk::styling::format_with_gutter;

    // Test CRLF (Windows line endings)
    let crlf_error = "line1\r\nline2\r\nline3";
    let normalized = crlf_error.replace("\r\n", "\n").replace('\r', "\n");
    let gutter = format_with_gutter(&normalized, None);

    // All three lines should appear
    assert!(gutter.contains("line1"), "Should contain line1");
    assert!(gutter.contains("line2"), "Should contain line2");
    assert!(gutter.contains("line3"), "Should contain line3");

    // Test CR only (old Mac line endings)
    let cr_error = "line1\rline2\rline3";
    let normalized = cr_error.replace("\r\n", "\n").replace('\r', "\n");
    let gutter = format_with_gutter(&normalized, None);

    assert!(gutter.contains("line1"), "CR: Should contain line1");
    assert!(gutter.contains("line2"), "CR: Should contain line2");
    assert!(gutter.contains("line3"), "CR: Should contain line3");
}

// ============================================================================
// Integration test: verify error message includes command when git unavailable
// ============================================================================

/// This is an integration test because it requires running the actual binary.
#[test]
#[cfg(unix)]
fn git_unavailable_error_includes_command() {
    use crate::common::wt_bin;
    use std::process::Command;

    let mut cmd = Command::new(wt_bin());
    cmd.arg("list")
        // Set PATH to empty so git isn't found
        .env("PATH", "/nonexistent")
        // Prevent any fallback mechanisms
        .env_remove("GIT_EXEC_PATH");

    let output = cmd.output().expect("Failed to run wt");
    let stderr = String::from_utf8_lossy(&output.stderr);

    // The error should include the git command that failed
    assert!(
        stderr.contains("Failed to execute: git"),
        "Error should include 'Failed to execute: git', got: {}",
        stderr
    );
}