gitgrip 0.10.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
//! gitgrip CLI entry point

use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::{generate, Shell};

#[derive(Parser)]
#[command(name = "gr")]
#[command(author, version, about = "Multi-repo workflow tool", long_about = None)]
struct Cli {
    /// Suppress output for repos with no relevant changes (saves tokens for AI tools)
    #[arg(short, long, global = true)]
    quiet: bool,

    /// Show verbose output including external commands being executed
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a new workspace
    Init {
        /// Manifest URL
        url: Option<String>,
        /// Target directory
        #[arg(short, long)]
        path: Option<String>,
        /// Create workspace from existing local directories
        #[arg(long, conflicts_with_all = ["url", "from_repo"])]
        from_dirs: bool,
        /// Specific directories to scan (requires --from-dirs)
        #[arg(long, requires = "from_dirs")]
        dirs: Vec<String>,
        /// Interactive mode - preview and confirm before writing
        #[arg(short, long)]
        interactive: bool,
        /// Create manifest repository on detected platform (requires --from-dirs)
        #[arg(long, requires = "from_dirs")]
        create_manifest: bool,
        /// Name for manifest repository (default: workspace-manifest)
        #[arg(long, requires = "create_manifest")]
        manifest_name: Option<String>,
        /// Make manifest repository private (default: false)
        #[arg(long, requires = "create_manifest")]
        private: bool,
        /// Initialize from existing .repo/ directory (git-repo coexistence)
        #[arg(long, conflicts_with_all = ["from_dirs", "url"])]
        from_repo: bool,
    },
    /// Sync all repositories
    Sync {
        /// Force sync even with local changes
        #[arg(short, long)]
        force: bool,
        /// Only sync repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
        /// Sync repos sequentially (default: parallel)
        #[arg(long)]
        sequential: bool,
    },
    /// Show status of all repositories
    Status {
        /// Show detailed status
        #[arg(short, long)]
        verbose: bool,
        /// Only show repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
        /// Output JSON (machine-readable)
        #[arg(long)]
        json: bool,
    },
    /// Create or switch branches across repos
    Branch {
        /// Branch name
        name: Option<String>,
        /// Delete branch
        #[arg(short, long)]
        delete: bool,
        /// Move recent commits to new branch (resets current branch to remote)
        #[arg(short, long)]
        r#move: bool,
        /// Only operate on specific repos
        #[arg(long, value_delimiter = ',')]
        repo: Option<Vec<String>>,
        /// Include manifest repo
        #[arg(long)]
        include_manifest: bool,
        /// Only operate on repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
        /// Output JSON (machine-readable, list mode only)
        #[arg(long)]
        json: bool,
    },
    /// Checkout a branch across repos
    Checkout {
        /// Branch name
        name: Option<String>,
        /// Create branch if it doesn't exist
        #[arg(short = 'b', long)]
        create: bool,
        /// Checkout the griptree base branch for this worktree
        #[arg(long, conflicts_with = "create")]
        base: bool,
    },
    /// Stage changes across repos
    Add {
        /// Files to add (. for all)
        #[arg(default_value = ".")]
        files: Vec<String>,
    },
    /// Show diff across repos
    Diff {
        /// Show staged changes
        #[arg(long)]
        staged: bool,
        /// Output JSON (machine-readable)
        #[arg(long)]
        json: bool,
    },
    /// Commit changes across repos
    Commit {
        /// Commit message
        #[arg(short, long)]
        message: Option<String>,
        /// Amend previous commit
        #[arg(long)]
        amend: bool,
    },
    /// Push changes across repos
    Push {
        /// Set upstream
        #[arg(short = 'u', long)]
        set_upstream: bool,
        /// Force push
        #[arg(short, long)]
        force: bool,
    },
    /// Clean up merged branches across repos
    Prune {
        /// Actually delete branches (default: dry-run)
        #[arg(long)]
        execute: bool,
        /// Also prune remote tracking refs
        #[arg(long)]
        remote: bool,
        /// Only prune repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
    },
    /// Pull request operations
    Pr {
        #[command(subcommand)]
        action: PrCommands,
    },
    /// Griptree (worktree) operations
    Tree {
        #[command(subcommand)]
        action: TreeCommands,
    },
    /// Search across all repos using git grep
    Grep {
        /// Search pattern
        pattern: String,
        /// Case insensitive
        #[arg(short = 'i', long)]
        ignore_case: bool,
        /// Run in parallel
        #[arg(short, long)]
        parallel: bool,
        /// File pattern (after --)
        #[arg(last = true)]
        pathspec: Vec<String>,
        /// Only search repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
    },
    /// Run command in each repo
    Forall {
        /// Command to run
        #[arg(short, long)]
        command: String,
        /// Run in parallel
        #[arg(short, long)]
        parallel: bool,
        /// Run in ALL repos (default: only repos with changes)
        #[arg(short, long)]
        all: bool,
        /// Disable git command interception (use CLI for all commands)
        #[arg(long)]
        no_intercept: bool,
        /// Only run in repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
    },
    /// Rebase branches across repos
    Rebase {
        /// Target branch
        onto: Option<String>,
        /// Use upstream tracking branch when no target is provided
        #[arg(long)]
        upstream: bool,
        /// Abort rebase in progress
        #[arg(long)]
        abort: bool,
        /// Continue rebase after resolving conflicts
        #[arg(long, name = "continue")]
        continue_rebase: bool,
    },
    /// Pull latest changes across repos
    Pull {
        /// Rebase instead of merge
        #[arg(long)]
        rebase: bool,
        /// Only pull repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
        /// Sync repos sequentially (default: parallel)
        #[arg(long)]
        sequential: bool,
    },
    /// Manage file links
    Link {
        /// Show link status
        #[arg(long)]
        status: bool,
        /// Apply/fix links
        #[arg(long)]
        apply: bool,
    },
    /// Run workspace scripts
    Run {
        /// Script name
        name: Option<String>,
        /// List available scripts
        #[arg(long)]
        list: bool,
    },
    /// Show environment variables
    Env,
    /// Run benchmarks
    Bench(gitgrip::cli::commands::bench::BenchArgs),
    /// Repository operations
    Repo {
        #[command(subcommand)]
        action: RepoCommands,
    },
    /// Repository group operations
    Group {
        #[command(subcommand)]
        action: GroupCommands,
    },
    /// Run garbage collection across repos
    Gc {
        /// More thorough gc (slower)
        #[arg(long)]
        aggressive: bool,
        /// Only report .git sizes, don't gc
        #[arg(long)]
        dry_run: bool,
        /// Only operate on specific repos
        #[arg(long, value_delimiter = ',')]
        repo: Option<Vec<String>>,
        /// Only gc repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
    },
    /// Cherry-pick commits across repos
    CherryPick {
        /// Commit SHA to cherry-pick
        #[arg(conflicts_with_all = ["abort", "continue"])]
        commit: Option<String>,
        /// Abort in-progress cherry-pick
        #[arg(long, conflicts_with = "continue")]
        abort: bool,
        /// Continue after conflict resolution
        #[arg(long, name = "continue", conflicts_with = "abort")]
        continue_pick: bool,
        /// Only operate on specific repos
        #[arg(long, value_delimiter = ',')]
        repo: Option<Vec<String>>,
        /// Only operate on repos in these groups
        #[arg(long, value_delimiter = ',')]
        group: Option<Vec<String>>,
    },
    /// CI/CD pipeline operations
    Ci {
        #[command(subcommand)]
        action: CiCommands,
    },
    /// Manifest operations (import, sync)
    Manifest {
        #[command(subcommand)]
        action: ManifestCommands,
    },
    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
}

#[derive(Subcommand)]
enum PrCommands {
    /// Create a pull request
    Create {
        /// PR title
        #[arg(short, long)]
        title: Option<String>,
        /// PR body/description
        #[arg(short, long)]
        body: Option<String>,
        /// Push before creating
        #[arg(long)]
        push: bool,
        /// Create as draft
        #[arg(long)]
        draft: bool,
        /// Preview without creating PR
        #[arg(long)]
        dry_run: bool,
    },
    /// Show PR status
    Status {
        /// Output JSON
        #[arg(long)]
        json: bool,
    },
    /// Merge pull requests
    Merge {
        /// Merge method (merge, squash, rebase)
        #[arg(short, long)]
        method: Option<String>,
        /// Force merge without readiness checks
        #[arg(short, long)]
        force: bool,
        /// Update branch from base if behind before merging
        #[arg(short = 'u', long)]
        update: bool,
        /// Enable auto-merge (merges when all checks pass)
        #[arg(long)]
        auto: bool,
    },
    /// Check CI status
    Checks {
        /// Output JSON
        #[arg(long)]
        json: bool,
    },
    /// Show PR diff
    Diff {
        /// Show stat summary only
        #[arg(long)]
        stat: bool,
    },
}

#[derive(Subcommand)]
enum TreeCommands {
    /// Add a new griptree
    Add {
        /// Branch name
        branch: String,
    },
    /// List griptrees
    List,
    /// Remove a griptree
    Remove {
        /// Branch name
        branch: String,
        /// Force removal
        #[arg(short, long)]
        force: bool,
    },
    /// Lock a griptree
    Lock {
        /// Branch name
        branch: String,
        /// Lock reason
        #[arg(short, long)]
        reason: Option<String>,
    },
    /// Unlock a griptree
    Unlock {
        /// Branch name
        branch: String,
    },
}

#[derive(Subcommand)]
enum GroupCommands {
    /// List all groups and their repos
    List,
    /// Add repo(s) to a group
    Add {
        /// Group name
        group: String,
        /// Repository names
        #[arg(required = true)]
        repos: Vec<String>,
    },
    /// Remove repo(s) from a group
    Remove {
        /// Group name
        group: String,
        /// Repository names
        #[arg(required = true)]
        repos: Vec<String>,
    },
    /// Create a new empty group (for documentation purposes)
    Create {
        /// Group name
        name: String,
    },
}

#[derive(Subcommand)]
enum CiCommands {
    /// Run a CI pipeline
    Run {
        /// Pipeline name
        name: String,
        /// Output JSON
        #[arg(long)]
        json: bool,
    },
    /// List available pipelines
    List {
        /// Output JSON
        #[arg(long)]
        json: bool,
    },
    /// Show status of last CI runs
    Status {
        /// Output JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum ManifestCommands {
    /// Convert git-repo XML manifest to gitgrip YAML
    Import {
        /// Path to XML manifest (e.g., .repo/manifests/default.xml)
        path: String,
        /// Output path for YAML manifest
        #[arg(short, long)]
        output: Option<String>,
    },
    /// Re-sync gitgrip YAML from .repo/ manifest after repo sync
    Sync,
    /// Show manifest schema specification
    Schema {
        /// Output format (yaml, json, markdown)
        #[arg(long, default_value = "yaml")]
        format: String,
    },
}

#[derive(Subcommand)]
enum RepoCommands {
    /// List repositories
    List,
    /// Add a repository
    Add {
        /// Repository URL
        url: String,
        /// Local path
        #[arg(short, long)]
        path: Option<String>,
        /// Default branch
        #[arg(short, long)]
        branch: Option<String>,
    },
    /// Remove a repository
    Remove {
        /// Repository name
        name: String,
        /// Delete files from disk
        #[arg(long)]
        delete: bool,
    },
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    // Initialize tracing — `--verbose` enables debug logging for gitgrip
    if cli.verbose {
        tracing_subscriber::fmt()
            .with_env_filter("gitgrip=debug")
            .with_target(false)
            .init();
    } else {
        tracing_subscriber::fmt()
            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
            .init();
    }

    match cli.command {
        Some(Commands::Status {
            verbose,
            group,
            json,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::status::run_status(
                &workspace_root,
                &manifest,
                verbose,
                cli.quiet,
                group.as_deref(),
                json,
            )?;
        }
        Some(Commands::Sync {
            force,
            group,
            sequential,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::sync::run_sync(
                &workspace_root,
                &manifest,
                force,
                cli.quiet,
                group.as_deref(),
                sequential,
            )
            .await?;
        }
        Some(Commands::Branch {
            name,
            delete,
            r#move,
            repo,
            include_manifest: _,
            group,
            json,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::branch::run_branch(
                gitgrip::cli::commands::branch::BranchOptions {
                    workspace_root: &workspace_root,
                    manifest: &manifest,
                    name: name.as_deref(),
                    delete,
                    move_commits: r#move,
                    repos_filter: repo.as_deref(),
                    group_filter: group.as_deref(),
                    json,
                },
            )?;
        }
        Some(Commands::Checkout { name, create, base }) => {
            let (workspace_root, manifest) = load_workspace()?;
            let branch = if base {
                let config =
                    gitgrip::core::griptree::GriptreeConfig::load_from_workspace(&workspace_root)?
                        .ok_or_else(|| anyhow::anyhow!("Not in a griptree workspace"))?;
                config.branch
            } else {
                name.ok_or_else(|| anyhow::anyhow!("Branch name is required"))?
            };

            gitgrip::cli::commands::checkout::run_checkout(
                &workspace_root,
                &manifest,
                &branch,
                create,
            )?;
        }
        Some(Commands::Add { files }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::add::run_add(&workspace_root, &manifest, &files)?;
        }
        Some(Commands::Diff { staged, json }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::diff::run_diff(&workspace_root, &manifest, staged, json)?;
        }
        Some(Commands::Commit { message, amend }) => {
            let (workspace_root, manifest) = load_workspace()?;
            let msg = message.unwrap_or_else(|| {
                eprintln!("Error: commit message required (-m)");
                std::process::exit(1);
            });
            gitgrip::cli::commands::commit::run_commit(&workspace_root, &manifest, &msg, amend)?;
        }
        Some(Commands::Push {
            set_upstream,
            force,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::push::run_push(
                &workspace_root,
                &manifest,
                set_upstream,
                force,
                cli.quiet,
            )?;
        }
        Some(Commands::Prune {
            execute,
            remote,
            group,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::prune::run_prune(
                &workspace_root,
                &manifest,
                execute,
                remote,
                group.as_deref(),
            )?;
        }
        Some(Commands::Pr { action }) => {
            let (workspace_root, manifest) = load_workspace()?;
            match action {
                PrCommands::Create {
                    title,
                    body,
                    push,
                    draft,
                    dry_run,
                } => {
                    gitgrip::cli::commands::pr::run_pr_create(
                        &workspace_root,
                        &manifest,
                        title.as_deref(),
                        body.as_deref(),
                        draft,
                        push,
                        dry_run,
                    )
                    .await?;
                }
                PrCommands::Status { json } => {
                    gitgrip::cli::commands::pr::run_pr_status(&workspace_root, &manifest, json)
                        .await?;
                }
                PrCommands::Merge {
                    method,
                    force,
                    update,
                    auto,
                } => {
                    gitgrip::cli::commands::pr::run_pr_merge(
                        &workspace_root,
                        &manifest,
                        method.as_deref(),
                        force,
                        update,
                        auto,
                    )
                    .await?;
                }
                PrCommands::Checks { json } => {
                    gitgrip::cli::commands::pr::run_pr_checks(&workspace_root, &manifest, json)
                        .await?;
                }
                PrCommands::Diff { stat } => {
                    gitgrip::cli::commands::pr::run_pr_diff(&workspace_root, &manifest, stat)
                        .await?;
                }
            }
        }
        Some(Commands::Init {
            url,
            path,
            from_dirs,
            dirs,
            interactive,
            create_manifest,
            manifest_name,
            private,
            from_repo,
        }) => {
            gitgrip::cli::commands::init::run_init(gitgrip::cli::commands::init::InitOptions {
                url: url.as_deref(),
                path: path.as_deref(),
                from_dirs,
                dirs: &dirs,
                interactive,
                create_manifest,
                manifest_name: manifest_name.as_deref(),
                private,
                from_repo,
            })
            .await?;
        }
        Some(Commands::Tree { action }) => {
            let (workspace_root, manifest) = load_workspace()?;
            match action {
                TreeCommands::Add { branch } => {
                    gitgrip::cli::commands::tree::run_tree_add(
                        &workspace_root,
                        &manifest,
                        &branch,
                    )?;
                }
                TreeCommands::List => {
                    gitgrip::cli::commands::tree::run_tree_list(&workspace_root)?;
                }
                TreeCommands::Remove { branch, force } => {
                    gitgrip::cli::commands::tree::run_tree_remove(&workspace_root, &branch, force)?;
                }
                TreeCommands::Lock { branch, reason } => {
                    gitgrip::cli::commands::tree::run_tree_lock(
                        &workspace_root,
                        &branch,
                        reason.as_deref(),
                    )?;
                }
                TreeCommands::Unlock { branch } => {
                    gitgrip::cli::commands::tree::run_tree_unlock(&workspace_root, &branch)?;
                }
            }
        }
        Some(Commands::Grep {
            pattern,
            ignore_case,
            parallel,
            pathspec,
            group,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::grep::run_grep(
                &workspace_root,
                &manifest,
                &pattern,
                ignore_case,
                parallel,
                &pathspec,
                group.as_deref(),
            )?;
        }
        Some(Commands::Forall {
            command,
            parallel,
            all,
            no_intercept,
            group,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::forall::run_forall(
                &workspace_root,
                &manifest,
                &command,
                parallel,
                !all, // Default: only repos with changes (changed_only=true unless --all)
                no_intercept,
                group.as_deref(),
            )?;
        }
        Some(Commands::Rebase {
            onto,
            upstream,
            abort,
            continue_rebase,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::rebase::run_rebase(
                &workspace_root,
                &manifest,
                onto.as_deref(),
                upstream,
                abort,
                continue_rebase,
            )?;
        }
        Some(Commands::Pull {
            rebase,
            group,
            sequential,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::pull::run_pull(
                &workspace_root,
                &manifest,
                rebase,
                group.as_deref(),
                sequential,
                cli.quiet,
            )
            .await?;
        }
        Some(Commands::Link { status, apply }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::link::run_link(&workspace_root, &manifest, status, apply)?;
        }
        Some(Commands::Run { name, list }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::run::run_run(
                &workspace_root,
                &manifest,
                name.as_deref(),
                list,
            )?;
        }
        Some(Commands::Env) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::env::run_env(&workspace_root, &manifest)?;
        }
        Some(Commands::Repo { action }) => {
            let (workspace_root, manifest) = load_workspace()?;
            match action {
                RepoCommands::List => {
                    gitgrip::cli::commands::repo::run_repo_list(&workspace_root, &manifest)?;
                }
                RepoCommands::Add { url, path, branch } => {
                    gitgrip::cli::commands::repo::run_repo_add(
                        &workspace_root,
                        &url,
                        path.as_deref(),
                        branch.as_deref(),
                    )?;
                }
                RepoCommands::Remove { name, delete } => {
                    gitgrip::cli::commands::repo::run_repo_remove(&workspace_root, &name, delete)?;
                }
            }
        }
        Some(Commands::Group { action }) => {
            let (workspace_root, manifest) = load_workspace()?;
            match action {
                GroupCommands::List => {
                    gitgrip::cli::commands::group::run_group_list(&workspace_root, &manifest)?;
                }
                GroupCommands::Add { group, repos } => {
                    gitgrip::cli::commands::group::run_group_add(&workspace_root, &group, &repos)?;
                }
                GroupCommands::Remove { group, repos } => {
                    gitgrip::cli::commands::group::run_group_remove(
                        &workspace_root,
                        &group,
                        &repos,
                    )?;
                }
                GroupCommands::Create { name } => {
                    gitgrip::cli::commands::group::run_group_create(&workspace_root, &name)?;
                }
            }
        }
        Some(Commands::Gc {
            aggressive,
            dry_run,
            repo,
            group,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::gc::run_gc(
                &workspace_root,
                &manifest,
                aggressive,
                dry_run,
                repo.as_deref(),
                group.as_deref(),
            )?;
        }
        Some(Commands::CherryPick {
            commit,
            abort,
            continue_pick,
            repo,
            group,
        }) => {
            let (workspace_root, manifest) = load_workspace()?;
            gitgrip::cli::commands::cherry_pick::run_cherry_pick(
                &workspace_root,
                &manifest,
                commit.as_deref(),
                abort,
                continue_pick,
                repo.as_deref(),
                group.as_deref(),
            )?;
        }
        Some(Commands::Ci { action }) => {
            let (workspace_root, manifest) = load_workspace()?;
            match action {
                CiCommands::Run { name, json } => {
                    gitgrip::cli::commands::ci::run_ci_run(
                        &workspace_root,
                        &manifest,
                        &name,
                        json,
                    )?;
                }
                CiCommands::List { json } => {
                    gitgrip::cli::commands::ci::run_ci_list(&manifest, json)?;
                }
                CiCommands::Status { json } => {
                    gitgrip::cli::commands::ci::run_ci_status(&workspace_root, json)?;
                }
            }
        }
        Some(Commands::Manifest { action }) => match action {
            ManifestCommands::Import { path, output } => {
                gitgrip::cli::commands::manifest::run_manifest_import(&path, output.as_deref())?;
            }
            ManifestCommands::Sync => {
                let (workspace_root, _manifest) = load_workspace()?;
                gitgrip::cli::commands::manifest::run_manifest_sync(&workspace_root)?;
            }
            ManifestCommands::Schema { format } => {
                gitgrip::cli::commands::manifest::run_manifest_schema(&format)?;
            }
        },
        Some(Commands::Bench(args)) => {
            gitgrip::cli::commands::bench::run(args).await?;
        }
        Some(Commands::Completions { shell }) => {
            let mut cmd = Cli::command();
            generate(shell, &mut cmd, "gr", &mut std::io::stdout());
        }
        None => {
            println!("gitgrip - Multi-repo workflow tool");
            println!("Run 'gr --help' for usage");
        }
    }

    Ok(())
}

/// Load the workspace manifest
fn load_workspace() -> anyhow::Result<(std::path::PathBuf, gitgrip::core::manifest::Manifest)> {
    let current = std::env::current_dir()?;

    // First, check if we're in a griptree (has .griptree pointer file)
    if let Some((griptree_path, pointer)) =
        gitgrip::core::griptree::GriptreePointer::find_in_ancestors(&current)
    {
        // We're in a griptree - prioritize loading manifest from griptree's own manifests directory
        // Fall back to main workspace if griptree doesn't have its own manifest
        let griptree_manifest_path = griptree_path
            .join(".gitgrip")
            .join("manifests")
            .join("manifest.yaml");

        let content = if griptree_manifest_path.exists() {
            std::fs::read_to_string(&griptree_manifest_path)?
        } else {
            // Fall back to main workspace's manifest
            let main_workspace = std::path::PathBuf::from(&pointer.main_workspace);
            let main_manifest_path = main_workspace
                .join(".gitgrip")
                .join("manifests")
                .join("manifest.yaml");

            if !main_manifest_path.exists() {
                anyhow::bail!(
                    "Griptree points to main workspace '{}' but manifest not found at '{}' or '{}'",
                    pointer.main_workspace,
                    griptree_manifest_path.display(),
                    main_manifest_path.display()
                );
            }
            std::fs::read_to_string(&main_manifest_path)?
        };

        let manifest = gitgrip::core::manifest::Manifest::parse(&content)?;
        // Return griptree path as workspace root - repos are located here, not in main workspace
        return Ok((griptree_path, manifest));
    }

    // Not in a griptree - find workspace root by looking for .gitgrip or .repo directory
    let mut search_path = current;
    loop {
        // Check for .gitgrip/manifests/manifest.yaml (standard gitgrip)
        let gitgrip_dir = search_path.join(".gitgrip");
        if gitgrip_dir.exists() {
            let manifest_path = gitgrip_dir.join("manifests").join("manifest.yaml");
            if manifest_path.exists() {
                let content = std::fs::read_to_string(&manifest_path)?;
                let manifest = gitgrip::core::manifest::Manifest::parse(&content)?;
                return Ok((search_path, manifest));
            }
        }

        // Check for .repo/manifests/manifest.yaml (gitgrip YAML inside repo manifests dir)
        let repo_manifests_dir = search_path.join(".repo").join("manifests");
        let repo_yaml = repo_manifests_dir.join("manifest.yaml");
        if repo_yaml.exists() {
            let content = std::fs::read_to_string(&repo_yaml)?;
            let manifest = gitgrip::core::manifest::Manifest::parse(&content)?;
            return Ok((search_path, manifest));
        }

        // Fallback: parse .repo/manifest.xml directly (zero-config — just works)
        let repo_xml = search_path.join(".repo").join("manifest.xml");
        if repo_xml.exists() {
            let xml_manifest = gitgrip::core::repo_manifest::XmlManifest::parse_file(&repo_xml)?;
            let result = xml_manifest.to_manifest()?;
            return Ok((search_path, result.manifest));
        }

        match search_path.parent() {
            Some(parent) => search_path = parent.to_path_buf(),
            None => {
                anyhow::bail!("Not in a gitgrip workspace (no .gitgrip or .repo directory found)");
            }
        }
    }
}