gwtr 0.6.0

A simple Git worktree manager
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
pub mod audit;
pub use audit::run_audit;

use anyhow::{Context, Result, bail};
use colored::*;
use git2::Repository;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

#[derive(Serialize, Deserialize, Default)]
pub struct WorktreeNote {
    pub note: Option<String>,
    pub ref_: Option<String>,
}

fn gwtr_dir(repo: &Repository) -> Result<PathBuf> {
    let git_dir = repo.path();
    Ok(git_dir.join("gwtr"))
}

fn note_path(repo: &Repository, worktree_name: &str) -> Result<PathBuf> {
    Ok(gwtr_dir(repo)?.join(format!("{}.json", worktree_name)))
}

fn load_note(repo: &Repository, worktree_name: &str) -> Result<WorktreeNote> {
    let path = note_path(repo, worktree_name)?;
    if !path.exists() {
        return Ok(WorktreeNote::default());
    }
    let content = std::fs::read_to_string(&path)?;
    Ok(serde_json::from_str(&content)?)
}

fn save_note(repo: &Repository, worktree_name: &str, note: &WorktreeNote) -> Result<()> {
    let dir = gwtr_dir(repo)?;
    std::fs::create_dir_all(&dir)?;
    let path = note_path(repo, worktree_name)?;
    std::fs::write(path, serde_json::to_string_pretty(note)?)?;
    Ok(())
}

fn delete_note(repo: &Repository, worktree_name: &str) -> Result<()> {
    let path = note_path(repo, worktree_name)?;
    if path.exists() {
        std::fs::remove_file(path)?;
    }
    Ok(())
}

/// Check if the current directory is inside a git repository
pub fn ensure_git_repository(path: &Path) -> Result<Repository> {
    Repository::discover(path)
        .context("Not in a git repository. Please run this command inside a git repository.")
}

/// Get the repository name from the current git repository
pub fn get_repository_name(repo: &Repository) -> Result<String> {
    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;

    let repo_name = workdir
        .file_name()
        .context("Failed to get repository directory name")?
        .to_str()
        .context("Repository name contains invalid UTF-8")?;

    Ok(repo_name.to_string())
}

/// Create a new worktree with the specified name
pub fn create_worktree(repo: &Repository, worktree_name: &str) -> Result<PathBuf> {
    // Get repository name and parent directory
    let repo_name = get_repository_name(repo)?;
    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;
    let parent_dir = workdir
        .parent()
        .context("Failed to get parent directory of repository")?;

    // Construct worktree path: ../repo-name_worktree-name
    let worktree_path = parent_dir.join(format!("{}_{}", repo_name, worktree_name));

    // Check if worktree already exists
    if worktree_path.exists() {
        bail!(
            "Worktree '{}' already exists at {:?}",
            worktree_name,
            worktree_path
        );
    }

    // Use git command to create worktree
    // This is more reliable than using libgit2's worktree API
    use std::process::Command;

    let output = Command::new("git")
        .args([
            "worktree",
            "add",
            "-b",
            worktree_name,
            worktree_path.to_str().unwrap(),
        ])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);

        // Check if branch already exists and retry without -b flag
        if stderr.contains("already exists") {
            let output = Command::new("git")
                .args([
                    "worktree",
                    "add",
                    worktree_path.to_str().unwrap(),
                    worktree_name,
                ])
                .current_dir(workdir)
                .output()
                .context("Failed to execute git worktree command")?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                bail!("Failed to create worktree: {}", stderr);
            }
        } else {
            bail!("Failed to create worktree: {}", stderr);
        }
    }

    println!(
        "Created worktree '{}' at {:?}",
        worktree_name, worktree_path
    );
    println!("cd '{}'", worktree_path.display());

    Ok(worktree_path)
}

/// List all worktrees for the current repository
pub fn list_worktrees(repo: &Repository) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;

    // Use git worktree list command
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree list command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to list worktrees: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().collect();

    if lines.is_empty() {
        println!("No worktrees found");
        return Ok(());
    }

    // Parse the porcelain output
    let mut worktrees = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        if lines[i].starts_with("worktree ") {
            let path = lines[i].strip_prefix("worktree ").unwrap_or("");
            let mut branch = "detached";
            let mut is_bare = false;

            // Look for additional info
            if i + 1 < lines.len() && lines[i + 1].starts_with("HEAD ") {
                i += 1;
            }
            if i + 1 < lines.len() && lines[i + 1].starts_with("branch ") {
                branch = lines[i + 1]
                    .strip_prefix("branch refs/heads/")
                    .unwrap_or("unknown");
                i += 1;
            }
            if i + 1 < lines.len() && lines[i + 1] == "bare" {
                is_bare = true;
                i += 1;
            }

            worktrees.push((path.to_string(), branch.to_string(), is_bare));
        }
        i += 1;
    }

    // Display worktrees
    println!("{}", "Worktrees:".bold());
    let main_path = workdir.to_string_lossy().trim_end_matches('/').to_string();

    for (path, branch, is_bare) in worktrees {
        let normalized_path = path.trim_end_matches('/');
        let is_main = normalized_path == main_path;

        let display_path = if is_main {
            format!("{} (main)", path).green()
        } else {
            path.yellow()
        };

        if is_bare {
            println!("  {} [bare]", display_path);
        } else {
            println!("  {} [{}]", display_path, branch.cyan());
        }
    }

    Ok(())
}

/// Remove a worktree
pub fn remove_worktree(repo: &Repository, worktree_name: &str) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;
    let repo_name = get_repository_name(repo)?;
    let parent_dir = workdir
        .parent()
        .context("Failed to get parent directory of repository")?;

    // Construct expected worktree path
    let worktree_path = parent_dir.join(format!("{}_{}", repo_name, worktree_name));

    // Check if worktree exists
    if !worktree_path.exists() {
        bail!(
            "Worktree '{}' not found at {:?}",
            worktree_name,
            worktree_path
        );
    }

    // Use git worktree remove command
    let output = Command::new("git")
        .args(["worktree", "remove", worktree_path.to_str().unwrap()])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree remove command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);

        // Try with --force if it contains uncommitted changes
        if stderr.contains("contains modified or untracked files") {
            println!("Worktree contains uncommitted changes, removing with --force");

            let output = Command::new("git")
                .args([
                    "worktree",
                    "remove",
                    "--force",
                    worktree_path.to_str().unwrap(),
                ])
                .current_dir(workdir)
                .output()
                .context("Failed to execute git worktree remove command")?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                bail!("Failed to remove worktree: {}", stderr);
            }
        } else {
            bail!("Failed to remove worktree: {}", stderr);
        }
    }

    delete_note(repo, worktree_name)?;
    println!(
        "Removed worktree '{}' at {:?}",
        worktree_name, worktree_path
    );

    Ok(())
}

/// Show status of all worktrees
pub fn show_worktrees_status(repo: &Repository) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;

    // Get list of worktrees
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree list command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to list worktrees: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().collect();

    // Parse worktrees
    let mut worktrees = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        if lines[i].starts_with("worktree ") {
            let path = lines[i].strip_prefix("worktree ").unwrap_or("");
            let mut branch = "detached";

            // Look for branch info
            if i + 1 < lines.len() && lines[i + 1].starts_with("HEAD ") {
                i += 1;
            }
            if i + 1 < lines.len() && lines[i + 1].starts_with("branch ") {
                branch = lines[i + 1]
                    .strip_prefix("branch refs/heads/")
                    .unwrap_or("unknown");
                i += 1;
            }

            worktrees.push((path.to_string(), branch.to_string()));
        }
        i += 1;
    }

    // Display worktrees with status
    println!("{}", "Worktrees:".bold());
    let main_path = workdir.to_string_lossy().trim_end_matches('/').to_string();

    for (path, branch) in worktrees {
        let normalized_path = path.trim_end_matches('/');
        let is_main = normalized_path == main_path;

        // Check for uncommitted changes
        let status_output = Command::new("git")
            .args(["status", "--porcelain"])
            .current_dir(&path)
            .output();

        let status_msg = if let Ok(output) = status_output {
            if output.status.success() {
                let status_str = String::from_utf8_lossy(&output.stdout);
                if status_str.trim().is_empty() {
                    "clean".green().to_string()
                } else {
                    let change_count = status_str.lines().count();
                    format!("{} uncommitted changes", change_count)
                        .yellow()
                        .to_string()
                }
            } else {
                "unknown".red().to_string()
            }
        } else {
            "error".red().to_string()
        };

        let display_path = if is_main {
            format!("{} (main)", path).green()
        } else {
            path.yellow()
        };

        println!("  {} [{}] - {}", display_path, branch.cyan(), status_msg);
    }

    Ok(())
}

/// Pull changes in all worktrees
pub fn pull_all_worktrees(repo: &Repository) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;

    println!("Pulling all worktrees from origin/main...");

    // Get list of worktrees
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree list command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to list worktrees: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().collect();

    // Parse worktree paths
    let mut worktree_paths = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        if lines[i].starts_with("worktree ") {
            let path = lines[i].strip_prefix("worktree ").unwrap_or("");
            let mut branch = "detached";

            // Look for branch info
            if i + 1 < lines.len() && lines[i + 1].starts_with("HEAD ") {
                i += 1;
            }
            if i + 1 < lines.len() && lines[i + 1].starts_with("branch ") {
                branch = lines[i + 1]
                    .strip_prefix("branch refs/heads/")
                    .unwrap_or("unknown");
                i += 1;
            }

            worktree_paths.push((path.to_string(), branch.to_string()));
        }
        i += 1;
    }

    // Pull origin/main in each worktree
    let main_path = workdir.to_string_lossy().trim_end_matches('/').to_string();

    for (path, branch) in worktree_paths {
        let normalized_path = path.trim_end_matches('/');
        let is_main = normalized_path == main_path;

        let worktree_name = if is_main {
            "main".to_string()
        } else {
            // Extract worktree name from path
            std::path::Path::new(&path)
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(&branch)
                .to_string()
        };

        print!("  {} [{}]: ", worktree_name.yellow(), branch.cyan());

        // Pull from origin/main
        let pull_output = Command::new("git")
            .args(["pull", "origin", "main"])
            .current_dir(&path)
            .output();

        match pull_output {
            Ok(output) => {
                if output.status.success() {
                    let stdout = String::from_utf8_lossy(&output.stdout);
                    if stdout.contains("Already up to date")
                        || stdout.contains("Already up-to-date")
                    {
                        println!("{}", "Already up to date".green());
                    } else {
                        println!("{}", "Updated".green());
                    }
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    if stderr.contains("Could not find remote")
                        || stderr.contains("fatal: 'origin' does not appear to be a git repository")
                    {
                        println!("{}: No remote configured", "Skipped".yellow());
                    } else {
                        println!("{}: {}", "Failed".red(), stderr.trim());
                    }
                }
            }
            Err(e) => {
                println!("{}: {}", "Error".red(), e);
            }
        }
    }

    Ok(())
}

/// Pull changes in a specific worktree
pub fn pull_worktree(repo: &Repository, worktree_name: &str) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;
    let repo_name = get_repository_name(repo)?;
    let parent_dir = workdir
        .parent()
        .context("Failed to get parent directory of repository")?;

    // Check if pulling main worktree
    let worktree_path = if worktree_name == "main" {
        workdir.to_path_buf()
    } else {
        // Construct expected worktree path
        let path = parent_dir.join(format!("{}_{}", repo_name, worktree_name));

        // Check if worktree exists
        if !path.exists() {
            bail!("Worktree '{}' not found", worktree_name);
        }
        path
    };

    println!("Pulling worktree '{}' from origin/main...", worktree_name);

    // Execute git pull from origin/main
    let output = Command::new("git")
        .args(["pull", "origin", "main"])
        .current_dir(&worktree_path)
        .output()
        .context("Failed to execute git pull command")?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout.contains("Already up to date") || stdout.contains("Already up-to-date") {
            println!(
                "{}: {}",
                worktree_name.yellow(),
                "Already up to date".green()
            );
        } else {
            println!("{}: {}", worktree_name.yellow(), "Updated".green());
        }
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("Could not find remote")
            || stderr.contains("fatal: 'origin' does not appear to be a git repository")
        {
            bail!("No remote 'origin' configured");
        } else {
            bail!("Failed to pull worktree '{}': {}", worktree_name, stderr);
        }
    }

    Ok(())
}

/// Pull changes in the current worktree
pub fn pull_current_worktree(repo: &Repository) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;

    println!("Pulling current worktree from origin/main...");

    // Execute git pull from origin/main
    let output = Command::new("git")
        .args(["pull", "origin", "main"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git pull command")?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stdout.contains("Already up to date") || stdout.contains("Already up-to-date") {
            println!("{}", "Already up to date".green());
        } else {
            println!("{}", "Updated".green());
        }
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("Could not find remote")
            || stderr.contains("fatal: 'origin' does not appear to be a git repository")
        {
            bail!("No remote 'origin' configured");
        } else {
            bail!("Failed to pull: {}", stderr);
        }
    }

    Ok(())
}

/// Prune merged worktrees
pub fn prune_merged_worktrees(repo: &Repository, dry_run: bool, force: bool) -> Result<()> {
    use std::io::{self, Write};
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;
    let repo_name = get_repository_name(repo)?;

    // Get list of worktrees
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree list command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to list worktrees: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().collect();

    // Parse worktrees and check which branches are merged
    let main_path = workdir.to_string_lossy().trim_end_matches('/').to_string();
    let mut merged_worktrees = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        if lines[i].starts_with("worktree ") {
            let path = lines[i].strip_prefix("worktree ").unwrap_or("");
            let normalized_path = path.trim_end_matches('/');

            // Skip main worktree
            if normalized_path == main_path {
                i += 1;
                continue;
            }

            // Look for branch info
            if i + 1 < lines.len() && lines[i + 1].starts_with("HEAD ") {
                i += 1;
            }
            if i + 1 < lines.len() && lines[i + 1].starts_with("branch ") {
                let branch = lines[i + 1]
                    .strip_prefix("branch refs/heads/")
                    .unwrap_or("unknown");
                i += 1;

                // Check if branch is merged to main
                let merged_output = Command::new("git")
                    .args(["branch", "--merged", "main"])
                    .current_dir(workdir)
                    .output();

                if let Ok(output) = merged_output
                    && output.status.success()
                {
                    let merged_branches = String::from_utf8_lossy(&output.stdout);
                    if merged_branches
                        .lines()
                        .any(|line| line.trim() == branch || line.trim() == format!("* {}", branch))
                    {
                        // Extract worktree name from path
                        let worktree_name = std::path::Path::new(path)
                            .file_name()
                            .and_then(|n| n.to_str())
                            .unwrap_or(branch)
                            .to_string();

                        // Remove repo name prefix if present
                        let worktree_name = if worktree_name.starts_with(&format!("{}_", repo_name))
                        {
                            worktree_name
                                .strip_prefix(&format!("{}_", repo_name))
                                .unwrap_or(&worktree_name)
                                .to_string()
                        } else {
                            worktree_name
                        };

                        merged_worktrees.push((
                            path.to_string(),
                            branch.to_string(),
                            worktree_name,
                        ));
                    }
                }
            }
        }
        i += 1;
    }

    if merged_worktrees.is_empty() {
        println!("No worktrees to prune");
        return Ok(());
    }

    if dry_run {
        println!(
            "Would prune {} merged worktree{}:",
            merged_worktrees.len(),
            if merged_worktrees.len() == 1 { "" } else { "s" }
        );
        for (path, branch, name) in &merged_worktrees {
            println!("  {} [{}] at {}", name.yellow(), branch.cyan(), path);
        }
        return Ok(());
    }

    // Show worktrees to be pruned
    println!(
        "Found {} merged worktree{} to prune:",
        merged_worktrees.len(),
        if merged_worktrees.len() == 1 { "" } else { "s" }
    );
    for (path, branch, name) in &merged_worktrees {
        println!("  {} [{}] at {}", name.yellow(), branch.cyan(), path);
    }

    // Ask for confirmation unless --force is used
    if !force {
        print!("\nPrune these worktrees? [y/N] ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;

        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Cancelled");
            return Ok(());
        }
    }

    // Prune each worktree
    let pruned_count = merged_worktrees.len();
    for (path, _, name) in merged_worktrees {
        print!("Pruning {}... ", name.yellow());

        let output = Command::new("git")
            .args(["worktree", "remove", &path])
            .current_dir(workdir)
            .output()
            .context("Failed to execute git worktree remove command")?;

        if output.status.success() {
            delete_note(repo, &name)?;
            println!("{}", "done".green());
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);

            // Try with --force if it contains uncommitted changes
            if stderr.contains("contains modified or untracked files") {
                print!("has uncommitted changes, removing with --force... ");

                let output = Command::new("git")
                    .args(["worktree", "remove", "--force", &path])
                    .current_dir(workdir)
                    .output()
                    .context("Failed to execute git worktree remove command")?;

                if output.status.success() {
                    delete_note(repo, &name)?;
                    println!("{}", "done".green());
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    println!("{}", "failed".red());
                    eprintln!("  Error: {}", stderr.trim());
                }
            } else {
                println!("{}", "failed".red());
                eprintln!("  Error: {}", stderr.trim());
            }
        }
    }

    println!(
        "\nPruned {} worktree{}",
        pruned_count,
        if pruned_count == 1 { "" } else { "s" }
    );

    Ok(())
}

/// Add or show a note for a worktree
pub fn manage_note(
    repo: &Repository,
    worktree_name: &str,
    text: Option<&str>,
    ref_: Option<&str>,
) -> Result<()> {
    let mut note = load_note(repo, worktree_name)?;

    if text.is_none() && ref_.is_none() {
        // Show current note
        println!("{}", format!("Note for '{}':", worktree_name).bold());
        match &note.note {
            Some(n) => println!("  Note: {}", n),
            None => println!("  Note: {}", "(none)".dimmed()),
        }
        match &note.ref_ {
            Some(r) => println!("  Ref:  {}", r.cyan()),
            None => println!("  Ref:  {}", "(none)".dimmed()),
        }
        return Ok(());
    }

    if let Some(t) = text {
        note.note = Some(t.to_string());
    }
    if let Some(r) = ref_ {
        note.ref_ = Some(r.to_string());
    }

    save_note(repo, worktree_name, &note)?;
    println!("Saved note for '{}'", worktree_name.yellow());
    Ok(())
}

/// Show context of worktrees for AI
pub fn show_context(repo: &Repository, worktree_name: Option<&str>, save: bool) -> Result<()> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;
    let repo_name = get_repository_name(repo)?;
    let parent_dir = workdir
        .parent()
        .context("Failed to get parent directory")?;

    let mut output_lines: Vec<String> = Vec::new();

    let worktrees = collect_worktrees(repo)?;

    let targets: Vec<(String, String)> = if let Some(name) = worktree_name {
        let path = parent_dir.join(format!("{}_{}", repo_name, name));
        if !path.exists() {
            bail!("Worktree '{}' not found", name);
        }
        vec![(name.to_string(), path.to_string_lossy().to_string())]
    } else {
        worktrees
            .iter()
            .filter(|(_, path)| {
                path.trim_end_matches('/') != workdir.to_string_lossy().trim_end_matches('/')
            })
            .map(|(branch, path)| {
                let name = std::path::Path::new(path)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .and_then(|n| n.strip_prefix(&format!("{}_", repo_name)))
                    .unwrap_or(branch)
                    .to_string();
                (name, path.clone())
            })
            .collect()
    };

    let detailed = worktree_name.is_some();

    for (name, path) in &targets {
        let note = load_note(repo, name)?;
        output_lines.push(format!("## {}", name));

        if let Some(n) = &note.note {
            output_lines.push(format!("Note: {}", n));
        }
        if let Some(r) = &note.ref_ {
            output_lines.push(format!("Ref: {}", r));
        }

        // Branch
        let branch_out = Command::new("git")
            .args(["branch", "--show-current"])
            .current_dir(path)
            .output();
        if let Ok(o) = branch_out {
            let branch = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if !branch.is_empty() {
                output_lines.push(format!("Branch: {}", branch));
            }
        }

        // Changed files stat
        let diff_out = Command::new("git")
            .args(["diff", "main", "--stat"])
            .current_dir(path)
            .output();
        if let Ok(o) = diff_out {
            let stat = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if !stat.is_empty() {
                output_lines.push(String::new());
                output_lines.push("### Changed files (vs main)".to_string());
                for line in stat.lines() {
                    output_lines.push(format!("  {}", line));
                }
            }
        }

        // Recent commits
        let log_args = if detailed {
            vec!["log", "main..HEAD", "--oneline", "--no-decorate"]
        } else {
            vec!["log", "main..HEAD", "--oneline", "--no-decorate", "-5"]
        };
        let log_out = Command::new("git")
            .args(&log_args)
            .current_dir(path)
            .output();
        if let Ok(o) = log_out {
            let log = String::from_utf8_lossy(&o.stdout).trim().to_string();
            if !log.is_empty() {
                output_lines.push(String::new());
                output_lines.push("### Commits (vs main)".to_string());
                for line in log.lines() {
                    output_lines.push(format!("  {}", line));
                }
            }
        }

        // Uncommitted changes
        let status_out = Command::new("git")
            .args(["status", "--porcelain"])
            .current_dir(path)
            .output();
        if let Ok(o) = status_out {
            let status = String::from_utf8_lossy(&o.stdout).trim().to_string();
            output_lines.push(String::new());
            if status.is_empty() {
                output_lines.push("### Uncommitted changes: none".to_string());
            } else {
                output_lines.push("### Uncommitted changes".to_string());
                for line in status.lines() {
                    output_lines.push(format!("  {}", line));
                }
            }
        }

        output_lines.push(String::new());
    }

    let content = output_lines.join("\n");

    if save {
        let save_path = workdir.join(".gwtr-context.md");
        std::fs::write(&save_path, &content)?;
        println!("{}", format!("Saved to {:?}", save_path).green());
    } else {
        println!("{}", content);
    }

    Ok(())
}

fn collect_worktrees(repo: &Repository) -> Result<Vec<(String, String)>> {
    use std::process::Command;

    let workdir = repo
        .workdir()
        .context("Failed to get repository working directory")?;

    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git worktree list command")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("Failed to list worktrees: {}", stderr);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let lines: Vec<&str> = stdout.lines().collect();
    let mut result = Vec::new();
    let mut i = 0;

    while i < lines.len() {
        if lines[i].starts_with("worktree ") {
            let path = lines[i].strip_prefix("worktree ").unwrap_or("").to_string();
            let mut branch = String::from("detached");

            if i + 1 < lines.len() && lines[i + 1].starts_with("HEAD ") {
                i += 1;
            }
            if i + 1 < lines.len() && lines[i + 1].starts_with("branch ") {
                branch = lines[i + 1]
                    .strip_prefix("branch refs/heads/")
                    .unwrap_or("unknown")
                    .to_string();
                i += 1;
            }

            result.push((branch, path));
        }
        i += 1;
    }

    Ok(result)
}