gitgrip 0.19.0

Multi-repo workflow tool - manage multiple git repositories as one
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
//! Tree command implementation
//!
//! Manages griptrees (worktree-based parallel workspaces).

use crate::cli::commands::link::run_link;
use crate::cli::output::Output;
use crate::core::griptree::{GriptreeConfig, GriptreePointer, GriptreeRepoInfo};
use crate::core::manifest::Manifest;
use crate::core::manifest_paths;
use crate::core::repo::{filter_repos, get_manifest_repo_info, RepoInfo};
use crate::git::branch::{
    branch_exists, checkout_branch, delete_local_branch, remote_branch_exists,
};
use crate::git::remote::{delete_remote_branch, get_upstream_branch, set_branch_upstream_ref};
use crate::git::status::get_cached_status;
use crate::git::{get_current_branch, open_repo, path_exists};
use crate::util::log_cmd;
use chrono::Utc;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;

/// Griptrees list file structure
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct GriptreesList {
    griptrees: HashMap<String, GriptreeEntry>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct GriptreeEntry {
    path: String,
    branch: String,
    locked: bool,
    lock_reason: Option<String>,
}

/// Context for tracking griptree creation progress (for rollback on failure)
struct GriptreeCreationContext {
    /// List of (main_repo_path, worktree_name) for created worktrees
    created_worktrees: Vec<(PathBuf, String)>,
    /// The griptree directory being created
    tree_path: PathBuf,
}

impl GriptreeCreationContext {
    fn new(tree_path: PathBuf) -> Self {
        Self {
            created_worktrees: Vec::new(),
            tree_path,
        }
    }

    fn record_worktree(&mut self, main_repo_path: PathBuf, worktree_name: String) {
        self.created_worktrees.push((main_repo_path, worktree_name));
    }

    fn rollback(&self) {
        // Remove worktrees in reverse order
        for (repo_path, wt_name) in self.created_worktrees.iter().rev() {
            if let Ok(repo) = open_repo(repo_path) {
                if let Ok(wt) = repo.find_worktree(wt_name) {
                    let mut opts = git2::WorktreePruneOptions::new();
                    opts.valid(true);
                    let _ = wt.prune(Some(&mut opts));
                }
            }
        }
        // Remove griptree directory
        let _ = std::fs::remove_dir_all(&self.tree_path);
    }
}

/// Run tree add command
pub fn run_tree_add(
    workspace_root: &Path,
    manifest: &Manifest,
    branch: &str,
) -> anyhow::Result<()> {
    Output::header(&format!("Creating griptree for branch '{}'", branch));
    println!();

    // Load or create griptrees list
    let config_path = workspace_root.join(".gitgrip").join("griptrees.json");
    let mut griptrees: GriptreesList = if config_path.exists() {
        let content = std::fs::read_to_string(&config_path)?;
        serde_json::from_str(&content)?
    } else {
        GriptreesList::default()
    };

    // Clean up stale griptree.json if this workspace is acting as a root (#402).
    // A root workspace has griptrees.json — it should not also have griptree.json
    // (which marks it as a linked child). Mixed markers cause ambiguity.
    let stale_child_marker = workspace_root.join(".gitgrip").join("griptree.json");
    if stale_child_marker.exists() {
        eprintln!(
            "Cleaning up stale .gitgrip/griptree.json (this workspace is a root, not a child)"
        );
        let _ = std::fs::remove_file(&stale_child_marker);
    }

    // Check if griptree already exists
    if griptrees.griptrees.contains_key(branch) {
        anyhow::bail!("Griptree for '{}' already exists", branch);
    }

    // Calculate griptree path (sibling to workspace)
    let tree_name = branch.replace('/', "-");
    let tree_path = workspace_root
        .parent()
        .ok_or_else(|| anyhow::anyhow!("Cannot determine parent directory"))?
        .join(&tree_name);

    if tree_path.exists() {
        anyhow::bail!("Directory already exists: {:?}", tree_path);
    }

    // Create griptree directory
    std::fs::create_dir_all(&tree_path)?;

    // Initialize rollback context
    let mut ctx = GriptreeCreationContext::new(tree_path.clone());

    // Get all repos
    let repos: Vec<RepoInfo> = manifest
        .repos
        .iter()
        .filter_map(|(name, config)| {
            RepoInfo::from_config(
                name,
                config,
                workspace_root,
                &manifest.settings,
                manifest.remotes.as_ref(),
            )
        })
        .collect();

    let mut success_count = 0;
    let mut error_count = 0;

    // Track original branches for each repo
    let mut repo_branches: Vec<GriptreeRepoInfo> = Vec::new();

    for repo in &repos {
        if !path_exists(&repo.absolute_path) {
            if repo.name == "opencode" {
                Output::error(&format!(
                    "{}: not cloned, skipping - this repo is required",
                    repo.name
                ));
            } else {
                Output::warning(&format!("{}: not cloned, skipping", repo.name));
            }
            continue;
        }

        // Get current branch from main workspace
        let git_repo = match open_repo(&repo.absolute_path) {
            Ok(r) => r,
            Err(e) => {
                Output::warning(&format!("{}: failed to open - {}", repo.name, e));
                continue;
            }
        };

        let current_branch = match get_current_branch(&git_repo) {
            Ok(b) => b,
            Err(e) => {
                Output::warning(&format!("{}: failed to get branch - {}", repo.name, e));
                continue;
            }
        };

        let worktree_path = tree_path.join(&repo.path);
        let spinner = Output::spinner(&format!("{}...", repo.name));

        // For reference repos: try to sync with upstream before creating worktree
        // Sync failure is not fatal - we'll create the worktree with current state
        let sync_warning = if repo.reference {
            match sync_repo_with_upstream(&repo.absolute_path, &repo.revision) {
                Ok(_) => None,
                Err(e) => Some(format!("sync skipped: {}", e)),
            }
        } else {
            None
        };

        // Create worktree on the griptree branch (creates branch if needed)
        // Base the new branch off the repo's default branch, not current HEAD
        match create_worktree(
            &repo.absolute_path,
            &worktree_path,
            branch,
            Some(&repo.revision),
        ) {
            Ok(_) => {
                let expected_upstream = format!("origin/{}", repo.revision);
                let upstream_warning = match open_repo(&worktree_path) {
                    Ok(repo_handle) => {
                        match set_branch_upstream_ref(&repo_handle, branch, &expected_upstream) {
                            Ok(()) => None,
                            Err(e) => Some(format!("upstream not set ({})", e)),
                        }
                    }
                    Err(e) => Some(format!("upstream not set ({})", e)),
                };

                // Record for rollback (use sanitized name matching create_worktree)
                let worktree_name = branch.replace('/', "-");
                ctx.record_worktree(repo.absolute_path.clone(), worktree_name.clone());

                // Track original branch for this repo (for merging back later)
                repo_branches.push(GriptreeRepoInfo {
                    name: repo.name.clone(),
                    original_branch: current_branch.clone(),
                    is_reference: repo.reference,
                    worktree_name: Some(worktree_name),
                    worktree_path: Some(worktree_path.to_string_lossy().to_string()),
                    main_repo_path: Some(repo.absolute_path.to_string_lossy().to_string()),
                });

                let mut status_msg = if repo.reference {
                    if let Some(ref warning) = sync_warning {
                        format!("{}: created on {} ({})", repo.name, branch, warning)
                    } else {
                        format!("{}: synced & created on {}", repo.name, branch)
                    }
                } else {
                    format!(
                        "{}: created on {} (from {})",
                        repo.name, branch, repo.revision
                    )
                };
                if let Some(warning) = upstream_warning {
                    status_msg.push_str(&format!(" ({})", warning));
                }
                spinner.finish_with_message(status_msg);
                success_count += 1;
            }
            Err(e) => {
                spinner.finish_with_message(format!("{}: failed - {}", repo.name, e));
                error_count += 1;
            }
        }
    }

    // Create .griptree structure in griptree
    let tree_gitgrip = tree_path.join(".gitgrip");
    std::fs::create_dir_all(&tree_gitgrip)?;

    // Initialize state.json for this griptree
    let state_path = tree_gitgrip.join("state.json");
    std::fs::write(&state_path, "{}")?;

    // Create manifest worktree if main workspace has a manifest repo
    let main_manifests_dir = manifest_paths::resolve_manifest_repo_dir(workspace_root);
    let (manifest_branch_option, manifest_worktree_name): (Option<String>, Option<String>) =
        if let Some(main_manifests_dir) = main_manifests_dir {
            let main_manifest_git_dir = main_manifests_dir.join(".git");
            if main_manifest_git_dir.exists() {
                // Main workspace has a manifest git repo - create worktree in griptree
                let tree_manifests_dir = tree_gitgrip.join("spaces").join("main");
                let manifest_spinner = Output::spinner("manifest");

                match create_manifest_worktree(&main_manifests_dir, &tree_manifests_dir, branch) {
                    Ok(manifest_branch) => {
                        manifest_spinner.finish_with_message(format!(
                            "manifest: created on {}",
                            manifest_branch
                        ));
                        success_count += 1;
                        (Some(manifest_branch.clone()), Some(manifest_branch))
                    }
                    Err(e) => {
                        manifest_spinner.finish_with_message(format!("manifest: failed - {}", e));
                        error_count += 1;
                        (None, None)
                    }
                }
            } else {
                (None, None)
            }
        } else {
            (None, None)
        };

    // Save griptree config in the griptree directory (include upstream mapping)
    let mut repo_upstreams: HashMap<String, String> = HashMap::new();
    for repo in &repos {
        let worktree_path = tree_path.join(&repo.path);
        if !worktree_path.exists() {
            continue;
        }

        let upstream = match open_repo(&worktree_path) {
            Ok(repo_handle) => match get_upstream_branch(&repo_handle, Some(branch)) {
                Ok(Some(name)) => name,
                _ => format!("origin/{}", repo.revision),
            },
            Err(_) => format!("origin/{}", repo.revision),
        };

        repo_upstreams.insert(repo.name.clone(), upstream);
    }

    let mut griptree_config = GriptreeConfig::new(branch, &tree_path.to_string_lossy());
    griptree_config.repo_upstreams = repo_upstreams;
    let griptree_config_path = tree_gitgrip.join("griptree.json");
    griptree_config.save(&griptree_config_path)?;

    // Create .griptree pointer file at root of griptree
    // This allows `gr status` to detect when running from within a griptree
    let pointer = GriptreePointer {
        main_workspace: workspace_root.to_string_lossy().to_string(),
        branch: branch.to_string(),
        locked: false,
        created_at: Some(Utc::now()),
        repos: repo_branches,
        manifest_branch: manifest_branch_option,
        manifest_worktree_name,
    };
    let pointer_path = tree_path.join(".griptree");
    let pointer_json = serde_json::to_string_pretty(&pointer)?;
    std::fs::write(&pointer_path, pointer_json)?;

    // Add to griptrees list
    // Check if we should rollback due to too many failures BEFORE saving config
    if success_count == 0 && error_count > 0 {
        Output::error("Griptree creation failed - no worktrees were created successfully");
        ctx.rollback();
        anyhow::bail!("Griptree creation failed, rolled back");
    }

    griptrees.griptrees.insert(
        branch.to_string(),
        GriptreeEntry {
            path: tree_path.to_string_lossy().to_string(),
            branch: branch.to_string(),
            locked: false,
            lock_reason: None,
        },
    );

    // Save griptrees list
    let config_json = serde_json::to_string_pretty(&griptrees)?;
    std::fs::write(&config_path, config_json)?;

    println!();
    if error_count == 0 {
        Output::success(&format!(
            "Griptree created at {:?} with {} repo(s)",
            tree_path, success_count
        ));
    } else {
        Output::warning(&format!(
            "Griptree created with {} success, {} errors",
            success_count, error_count
        ));
    }

    // Apply links in the new griptree
    if let Some(tree_manifest_path) = manifest_paths::resolve_gripspace_manifest_path(&tree_path) {
        println!();
        if let Ok(tree_manifest) = Manifest::load(&tree_manifest_path) {
            if let Err(e) = run_link(&tree_path, &tree_manifest, false, true, false) {
                Output::warning(&format!("Failed to apply links: {}", e));
            }
        }
    }

    println!();
    println!("To use the griptree:");
    println!("  cd {:?}", tree_path);

    Ok(())
}

/// Run tree list command
pub fn run_tree_list(workspace_root: &Path) -> anyhow::Result<()> {
    Output::header("Griptrees");
    println!();

    let griptrees_root = resolve_griptrees_workspace_root(workspace_root);
    let config_path = griptrees_root.join(".gitgrip").join("griptrees.json");
    let griptrees: GriptreesList = if config_path.exists() {
        let content = std::fs::read_to_string(&config_path)?;
        serde_json::from_str(&content)?
    } else {
        GriptreesList::default()
    };

    // Auto-repair stale child marker in root workspace (#402)
    let stale_child_marker = griptrees_root.join(".gitgrip").join("griptree.json");
    if config_path.exists() && stale_child_marker.exists() {
        eprintln!("Repaired: removed stale .gitgrip/griptree.json from root workspace");
        let _ = std::fs::remove_file(&stale_child_marker);
    }

    // Detect if we're currently inside a griptree
    let current_branch = std::env::current_dir().ok().and_then(|cwd| {
        crate::core::griptree::GriptreePointer::find_in_ancestors(&cwd)
            .map(|(_, pointer)| pointer.branch)
    });

    if griptrees.griptrees.is_empty() {
        println!("No griptrees configured.");
    } else {
        for (branch, entry) in &griptrees.griptrees {
            let exists = PathBuf::from(&entry.path).exists();
            let is_current = current_branch.as_deref() == Some(branch.as_str());
            let mut markers = Vec::new();
            if is_current {
                markers.push("current");
            }
            if !exists {
                markers.push("missing");
            }
            if entry.locked {
                markers.push("locked");
            }
            let suffix = if markers.is_empty() {
                String::new()
            } else {
                format!(" ({})", markers.join(", "))
            };

            let prefix = if is_current { "* " } else { "  " };
            println!("{}{} -> {}{}", prefix, branch, entry.path, suffix);
            if let Some(ref reason) = entry.lock_reason {
                println!("    Lock reason: {}", reason);
            }
        }
    }

    // Discover unregistered griptrees
    let discovered = discover_legacy_griptrees(&griptrees_root, &griptrees)?;
    if !discovered.is_empty() {
        println!();
        Output::warning("Found unregistered griptrees:");
        for (path, branch) in &discovered {
            let is_current = current_branch.as_deref() == Some(branch.as_str());
            let prefix = if is_current { "* " } else { "  " };
            let suffix = if is_current {
                " (current, unregistered)"
            } else {
                " (unregistered)"
            };
            println!("{}{} -> {}{}", prefix, branch, path.display(), suffix);
        }
        println!();
        println!("These griptrees point to this workspace but are not in griptrees.json.");
        println!("You can manually add them to griptrees.json if needed.");
    }

    Ok(())
}

/// Options for the tree return command.
pub struct TreeReturnOptions<'a> {
    pub base_override: Option<&'a str>,
    pub no_sync: bool,
    pub autostash: bool,
    pub prune_branch: Option<&'a str>,
    pub prune_current: bool,
    pub prune_remote: bool,
    pub force: bool,
}

/// Return to the griptree base branch, sync upstreams, and optionally prune a branch.
pub async fn run_tree_return(
    workspace_root: &Path,
    manifest: &Manifest,
    opts: &TreeReturnOptions<'_>,
) -> anyhow::Result<()> {
    let griptree_config = GriptreeConfig::load_from_workspace(workspace_root)?;
    let base_branch = match (opts.base_override, griptree_config.as_ref()) {
        (Some(base), _) => base.to_string(),
        (None, Some(cfg)) => cfg.branch.clone(),
        (None, None) => {
            anyhow::bail!(
                "No griptree config found. Use --base <branch> to specify the base branch."
            );
        }
    };

    let mut repos: Vec<RepoInfo> = filter_repos(
        manifest,
        workspace_root,
        None,
        None,
        false, /* include_reference */
    );
    if let Some(manifest_repo) = get_manifest_repo_info(manifest, workspace_root) {
        repos.push(manifest_repo);
    }

    Output::header(&format!(
        "Returning to {} and syncing upstreams...",
        Output::branch_name(&base_branch)
    ));
    println!();

    let mut dirty_repos: Vec<String> = Vec::new();
    let mut current_branches: HashMap<String, String> = HashMap::new();

    for repo in &repos {
        if !repo.exists() {
            continue;
        }
        let status = get_cached_status(&repo.absolute_path)?;
        current_branches.insert(repo.name.clone(), status.current_branch.clone());
        if !status.is_clean {
            dirty_repos.push(repo.name.clone());
        }
    }

    if !dirty_repos.is_empty() && !opts.autostash {
        anyhow::bail!(
            "Uncommitted changes in: {}. Use --autostash to proceed.",
            dirty_repos.join(", ")
        );
    }

    let mut stashed_repos: Vec<PathBuf> = Vec::new();
    if opts.autostash {
        for repo in &repos {
            if !dirty_repos.contains(&repo.name) || !repo.exists() {
                continue;
            }
            match stash_repo(&repo.absolute_path, "gr tree return") {
                Ok(true) => stashed_repos.push(repo.absolute_path.clone()),
                Ok(false) => {}
                Err(e) => Output::error(&format!("{}: stash failed - {}", repo.name, e)),
            }
        }
    }

    let mut checkout_failures = 0;
    for repo in &repos {
        if !repo.exists() {
            Output::warning(&format!("{}: not cloned, skipping", repo.name));
            continue;
        }
        let git_repo = open_repo(&repo.absolute_path)?;
        if let Ok(current) = get_current_branch(&git_repo) {
            if current == base_branch {
                Output::success(&format!("{}: already on {}", repo.name, base_branch));
                continue;
            }
        }
        if !branch_exists(&git_repo, &base_branch) {
            Output::warning(&format!(
                "{}: branch '{}' does not exist, skipping",
                repo.name, base_branch
            ));
            checkout_failures += 1;
            continue;
        }
        match checkout_branch(&git_repo, &base_branch) {
            Ok(()) => Output::success(&format!("{}: checked out {}", repo.name, base_branch)),
            Err(e) => {
                Output::error(&format!("{}: {}", repo.name, e));
                checkout_failures += 1;
            }
        }
    }

    if !opts.no_sync {
        println!();
        let _ = crate::cli::commands::sync::run_sync(
            workspace_root,
            manifest,
            false,
            false,
            None,
            None,
            false,
            false,
            false,
            false,
        )
        .await;
    }

    if opts.prune_branch.is_some() || opts.prune_current {
        println!();
        let prune_target = opts.prune_branch.map(|b| b.to_string());
        for repo in &repos {
            if !repo.exists() {
                continue;
            }
            let git_repo = open_repo(&repo.absolute_path)?;
            let target_branch = match &prune_target {
                Some(branch) => branch.clone(),
                None => current_branches
                    .get(&repo.name)
                    .cloned()
                    .unwrap_or_default(),
            };
            if target_branch.is_empty() || target_branch == base_branch {
                continue;
            }
            if !branch_exists(&git_repo, &target_branch) {
                Output::info(&format!(
                    "{}: branch '{}' not found, skipping",
                    repo.name, target_branch
                ));
                continue;
            }
            if let Err(e) = delete_local_branch(&git_repo, &target_branch, opts.force) {
                Output::warning(&format!(
                    "{}: failed to delete '{}' - {}",
                    repo.name, target_branch, e
                ));
                continue;
            }
            Output::success(&format!(
                "{}: deleted local branch '{}'",
                repo.name, target_branch
            ));

            if opts.prune_remote {
                let remote = "origin";
                if remote_branch_exists(&git_repo, &target_branch, remote) {
                    match delete_remote_branch(&git_repo, &target_branch, remote) {
                        Ok(()) => Output::success(&format!(
                            "{}: deleted remote branch '{}/{}'",
                            repo.name, remote, target_branch
                        )),
                        Err(e) => Output::warning(&format!(
                            "{}: failed to delete remote '{}/{}' - {}",
                            repo.name, remote, target_branch, e
                        )),
                    }
                } else {
                    Output::info(&format!(
                        "{}: remote branch '{}/{}' not found, skipping",
                        repo.name, remote, target_branch
                    ));
                }
            }
        }
    }

    if opts.autostash && !stashed_repos.is_empty() {
        println!();
        for repo_path in &stashed_repos {
            if let Err(e) = stash_pop_repo(repo_path) {
                Output::warning(&format!(
                    "{}: stash pop failed - {}",
                    repo_path.display(),
                    e
                ));
            }
        }
    }

    if checkout_failures > 0 {
        Output::warning(&format!(
            "Return completed with {} checkout error(s)",
            checkout_failures
        ));
    } else {
        Output::success("Return completed");
    }

    Ok(())
}

/// Discover legacy/unregistered griptrees that point to this workspace
fn discover_legacy_griptrees(
    workspace_root: &Path,
    registered: &GriptreesList,
) -> anyhow::Result<Vec<(PathBuf, String)>> {
    let mut discovered = Vec::new();

    let parent = match workspace_root.parent() {
        Some(p) => p,
        None => return Ok(discovered),
    };

    // Build set of registered paths for quick lookup
    let registered_paths: HashSet<String> = registered
        .griptrees
        .values()
        .map(|e| e.path.clone())
        .collect();

    // Scan sibling directories
    let entries = match std::fs::read_dir(parent) {
        Ok(e) => e,
        Err(_) => return Ok(discovered),
    };

    for entry in entries.flatten() {
        let path = entry.path();

        if !path.is_dir() {
            continue;
        }
        if path == workspace_root {
            continue;
        }
        if registered_paths.contains(&path.to_string_lossy().to_string()) {
            continue;
        }

        // Check for .griptree pointer file
        let pointer_path = path.join(".griptree");
        if pointer_path.exists() {
            if let Ok(pointer) = GriptreePointer::load(&pointer_path) {
                // Check if it points to this workspace
                if pointer.main_workspace == workspace_root.to_string_lossy() {
                    discovered.push((path, pointer.branch));
                }
            }
        }
    }

    Ok(discovered)
}

fn resolve_griptrees_workspace_root(workspace_root: &Path) -> PathBuf {
    let local_registry = workspace_root.join(".gitgrip").join("griptrees.json");
    if local_registry.exists() {
        return workspace_root.to_path_buf();
    }

    let pointer_path = workspace_root.join(".griptree");
    if pointer_path.exists() {
        if let Ok(pointer) = GriptreePointer::load(&pointer_path) {
            let main_workspace = PathBuf::from(pointer.main_workspace);
            let main_registry = main_workspace.join(".gitgrip").join("griptrees.json");
            if main_registry.exists() {
                return main_workspace;
            }
        }
    }

    workspace_root.to_path_buf()
}

/// Run tree remove command
pub fn run_tree_remove(workspace_root: &Path, branch: &str, force: bool) -> anyhow::Result<()> {
    Output::header(&format!("Removing griptree for '{}'", branch));
    println!();

    let griptrees_root = resolve_griptrees_workspace_root(workspace_root);
    let config_path = griptrees_root.join(".gitgrip").join("griptrees.json");
    if !config_path.exists() {
        anyhow::bail!("No griptrees configured");
    }

    let content = std::fs::read_to_string(&config_path)?;
    let mut griptrees: GriptreesList = serde_json::from_str(&content)?;

    let entry = griptrees
        .griptrees
        .get(branch)
        .ok_or_else(|| anyhow::anyhow!("Griptree '{}' not found", branch))?;

    if entry.locked && !force {
        anyhow::bail!(
            "Griptree '{}' is locked{}. Use --force to remove anyway.",
            branch,
            entry
                .lock_reason
                .as_ref()
                .map(|r| format!(": {}", r))
                .unwrap_or_default()
        );
    }

    let tree_path = PathBuf::from(&entry.path);

    // Load griptree pointer to get worktree info for cleanup
    let pointer_path = tree_path.join(".griptree");
    let pointer = if pointer_path.exists() {
        GriptreePointer::load(&pointer_path).ok()
    } else {
        None
    };

    // Prune each repo's worktree properly before removing directory
    if let Some(ref ptr) = pointer {
        let cleanup_spinner = Output::spinner("Cleaning up worktrees...");

        for repo_info in &ptr.repos {
            // Use stored main_repo_path if available, otherwise fall back to workspace/name
            let main_repo_path = repo_info
                .main_repo_path
                .as_ref()
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from(&ptr.main_workspace).join(&repo_info.name));

            if let Ok(repo) = open_repo(&main_repo_path) {
                // Use stored worktree name if available, otherwise fall back to original branch
                let wt_name = repo_info
                    .worktree_name
                    .as_deref()
                    .unwrap_or(&repo_info.original_branch);
                prune_worktree(&repo, wt_name);
            }
        }

        // Remove manifest worktree
        if let Some(ref manifest_wt_name) = ptr.manifest_worktree_name {
            let main_workspace = PathBuf::from(&ptr.main_workspace);
            if let Some(main_manifest_path) =
                manifest_paths::resolve_manifest_repo_dir(&main_workspace)
            {
                if let Ok(repo) = open_repo(&main_manifest_path) {
                    prune_worktree(&repo, manifest_wt_name);
                }
            }
        }

        cleanup_spinner.finish_with_message("Worktrees cleaned up");
    }

    // Remove directory
    if tree_path.exists() {
        let spinner = Output::spinner("Removing griptree directory...");
        std::fs::remove_dir_all(&tree_path)?;
        spinner.finish_with_message("Directory removed");
    }

    // Update griptrees list
    griptrees.griptrees.remove(branch);
    let config_json = serde_json::to_string_pretty(&griptrees)?;
    std::fs::write(&config_path, config_json)?;

    Output::success(&format!("Griptree '{}' removed", branch));
    Ok(())
}

/// Prune a worktree from a repository
fn prune_worktree(repo: &git2::Repository, worktree_name: &str) {
    if let Ok(wt) = repo.find_worktree(worktree_name) {
        let mut opts = git2::WorktreePruneOptions::new();
        opts.valid(true); // Prune even if valid
        let _ = wt.prune(Some(&mut opts));
    }
}

/// Run tree lock command
pub fn run_tree_lock(
    workspace_root: &Path,
    branch: &str,
    reason: Option<&str>,
) -> anyhow::Result<()> {
    let griptrees_root = resolve_griptrees_workspace_root(workspace_root);
    let config_path = griptrees_root.join(".gitgrip").join("griptrees.json");
    if !config_path.exists() {
        anyhow::bail!("No griptrees configured");
    }

    let content = std::fs::read_to_string(&config_path)?;
    let mut griptrees: GriptreesList = serde_json::from_str(&content)?;

    let entry = griptrees
        .griptrees
        .get_mut(branch)
        .ok_or_else(|| anyhow::anyhow!("Griptree '{}' not found", branch))?;

    entry.locked = true;
    entry.lock_reason = reason.map(|s| s.to_string());
    let entry_path = entry.path.clone();

    let config_json = serde_json::to_string_pretty(&griptrees)?;
    std::fs::write(&config_path, config_json)?;

    // Update .griptree pointer file if it exists
    let pointer_path = PathBuf::from(&entry_path).join(".griptree");
    if pointer_path.exists() {
        if let Ok(mut pointer) = GriptreePointer::load(&pointer_path) {
            pointer.locked = true;
            let pointer_json = serde_json::to_string_pretty(&pointer)?;
            std::fs::write(&pointer_path, pointer_json)?;
        }
    }

    Output::success(&format!("Griptree '{}' locked", branch));
    Ok(())
}

/// Run tree unlock command
pub fn run_tree_unlock(workspace_root: &Path, branch: &str) -> anyhow::Result<()> {
    let griptrees_root = resolve_griptrees_workspace_root(workspace_root);
    let config_path = griptrees_root.join(".gitgrip").join("griptrees.json");
    if !config_path.exists() {
        anyhow::bail!("No griptrees configured");
    }

    let content = std::fs::read_to_string(&config_path)?;
    let mut griptrees: GriptreesList = serde_json::from_str(&content)?;

    let entry = griptrees
        .griptrees
        .get_mut(branch)
        .ok_or_else(|| anyhow::anyhow!("Griptree '{}' not found", branch))?;

    entry.locked = false;
    entry.lock_reason = None;
    let entry_path = entry.path.clone();

    let config_json = serde_json::to_string_pretty(&griptrees)?;
    std::fs::write(&config_path, config_json)?;

    // Update .griptree pointer file if it exists
    let pointer_path = PathBuf::from(&entry_path).join(".griptree");
    if pointer_path.exists() {
        if let Ok(mut pointer) = GriptreePointer::load(&pointer_path) {
            pointer.locked = false;
            let pointer_json = serde_json::to_string_pretty(&pointer)?;
            std::fs::write(&pointer_path, pointer_json)?;
        }
    }

    Output::success(&format!("Griptree '{}' unlocked", branch));
    Ok(())
}

/// Create manifest worktree for a griptree
fn create_manifest_worktree(
    main_manifests_dir: &Path,
    tree_manifests_dir: &Path,
    branch: &str,
) -> anyhow::Result<String> {
    let repo = open_repo(main_manifests_dir)?;

    // Get current branch from main manifests (unused but kept for context)
    let _current_branch = get_current_branch(&repo)?;

    // Create worktree at griptree's .gitgrip/spaces/main/
    // Use the griptree branch name for the manifest worktree
    // Manifest worktrees create from HEAD since there's no "default branch" concept
    let worktree_name = format!("griptree-{}", branch.replace('/', "-"));
    create_worktree(main_manifests_dir, tree_manifests_dir, &worktree_name, None)?;

    // Ensure a supported workspace manifest file exists in the new worktree.
    if manifest_paths::resolve_manifest_file_in_dir(tree_manifests_dir).is_none() {
        if let Some(main_manifest) =
            manifest_paths::resolve_manifest_file_in_dir(main_manifests_dir)
        {
            let target_manifest = tree_manifests_dir.join(manifest_paths::PRIMARY_FILE_NAME);
            std::fs::copy(main_manifest, target_manifest)?;
        }
    }

    Ok(worktree_name)
}
/// Create a git worktree using git2
///
/// When creating a new branch, bases it off `base_branch` (e.g., "main") instead of HEAD.
/// This ensures griptrees start from the default branch, not whatever branch the workspace is on.
fn create_worktree(
    repo_path: &Path,
    worktree_path: &Path,
    branch: &str,
    base_branch: Option<&str>,
) -> anyhow::Result<()> {
    let repo = open_repo(repo_path)?;

    // Create parent directory if needed
    if let Some(parent) = worktree_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    // Sanitize worktree name: git2 uses this as a directory name under
    // .git/worktrees/<name>, so slashes would create nested directories
    // that don't exist. Replace them with dashes.
    let worktree_name = branch.replace('/', "-");

    // Check if branch exists, create if not
    let branch_exists = repo.find_branch(branch, git2::BranchType::Local).is_ok();

    if branch_exists {
        // Add worktree with existing branch
        repo.worktree(
            &worktree_name,
            worktree_path,
            Some(
                git2::WorktreeAddOptions::new().reference(Some(
                    &repo
                        .find_branch(branch, git2::BranchType::Local)?
                        .into_reference(),
                )),
            ),
        )?;
    } else {
        // Create branch from base_branch (default branch) rather than HEAD
        // This ensures griptrees start from a clean state, not from a feature branch
        let base_commit = if let Some(base) = base_branch {
            // Try local branch first, then remote tracking branch
            if let Ok(local_branch) = repo.find_branch(base, git2::BranchType::Local) {
                local_branch.get().peel_to_commit()?
            } else {
                // Try origin/<base>
                let remote_ref = format!("refs/remotes/origin/{}", base);
                repo.revparse_single(&remote_ref)?.peel_to_commit()?
            }
        } else {
            // Fall back to HEAD if no base branch specified
            repo.head()?.peel_to_commit()?
        };

        repo.branch(branch, &base_commit, false)?;

        repo.worktree(
            &worktree_name,
            worktree_path,
            Some(
                git2::WorktreeAddOptions::new().reference(Some(
                    &repo
                        .find_branch(branch, git2::BranchType::Local)?
                        .into_reference(),
                )),
            ),
        )?;
    }

    Ok(())
}

/// Sync reference repo with upstream revision
fn sync_repo_with_upstream(repo_path: &Path, revision: &str) -> anyhow::Result<()> {
    let repo = open_repo(repo_path)?;

    // Fetch from origin to ensure up-to-date
    let mut remote = repo.find_remote("origin")?;
    remote.fetch(&[revision], None, None)?;

    // Reset main worktree HEAD to upstream revision
    let upstream_ref = format!("refs/remotes/origin/{}", revision);
    let upstream_commit = repo.revparse_single(&upstream_ref)?.peel_to_commit()?;
    repo.reset(upstream_commit.as_object(), git2::ResetType::Hard, None)?;

    Ok(())
}

fn stash_repo(repo_path: &Path, message: &str) -> anyhow::Result<bool> {
    let mut cmd = Command::new("git");
    cmd.args(["stash", "push", "-u", "-m", message])
        .current_dir(repo_path);
    log_cmd(&cmd);
    let output = cmd.output()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    if !output.status.success() {
        return Err(anyhow::anyhow!("git stash failed: {}", stderr.trim()));
    }

    let combined = format!("{}{}", stdout, stderr);
    if combined.contains("No local changes to save") {
        return Ok(false);
    }

    Ok(true)
}

fn stash_pop_repo(repo_path: &Path) -> anyhow::Result<()> {
    let mut cmd = Command::new("git");
    cmd.args(["stash", "pop"]).current_dir(repo_path);
    log_cmd(&cmd);
    let output = cmd.output()?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow::anyhow!("git stash pop failed: {}", stderr.trim()));
    }
    Ok(())
}

#[cfg(test)]
mod tests {

    use tempfile::TempDir;

    #[test]
    fn test_stale_child_marker_cleaned_on_tree_list() {
        // Create a workspace with both markers (mixed state)
        let tmp = TempDir::new().unwrap();
        let gitgrip_dir = tmp.path().join(".gitgrip");
        std::fs::create_dir_all(&gitgrip_dir).unwrap();

        // Write griptrees.json (root marker)
        let griptrees_path = gitgrip_dir.join("griptrees.json");
        std::fs::write(&griptrees_path, r#"{"griptrees":{}}"#).unwrap();

        // Write stale griptree.json (child marker)
        let griptree_path = gitgrip_dir.join("griptree.json");
        std::fs::write(&griptree_path, r#"{"branch":"old","path":"."}"#).unwrap();

        assert!(
            griptree_path.exists(),
            "child marker should exist before repair"
        );

        // run_tree_list would clean this up, but requires full workspace setup.
        // Test the repair logic directly:
        if griptrees_path.exists() && griptree_path.exists() {
            let _ = std::fs::remove_file(&griptree_path);
        }

        assert!(!griptree_path.exists(), "child marker should be removed");
        assert!(griptrees_path.exists(), "root marker should be preserved");
    }
}