gwtr 0.4.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
use anyhow::{Context, Result, bail};
use colored::*;
use git2::Repository;
use std::path::{Path, PathBuf};

/// 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);
        }
    }

    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() {
            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() {
                    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(())
}