cascade-cli 0.1.152

Stacked diffs CLI for Bitbucket Server
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
pub mod commands;
pub mod output;

use crate::errors::Result;
use clap::{Parser, Subcommand};
use clap_complete::Shell;
use commands::entry::EntryAction;
use commands::stack::StackAction;
use commands::{MergeStrategyArg, RebaseStrategyArg};

#[derive(Debug, Subcommand)]
pub enum SyncAction {
    /// Continue after resolving conflicts
    Continue,
    /// Abort in-progress sync
    Abort,
}

#[derive(Debug, Subcommand)]
pub enum RebaseAction {
    /// Continue after resolving conflicts
    Continue,
    /// Abort in-progress rebase
    Abort,
}

#[derive(Parser)]
#[command(name = "ca")]
#[command(about = "Cascade CLI - Stacked Diffs for Bitbucket")]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    /// Enable verbose logging
    #[arg(long, short, global = true)]
    pub verbose: bool,

    /// Disable colored output
    #[arg(long, global = true)]
    pub no_color: bool,
}

/// Commands available in the CLI
#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Initialize repository for Cascade
    Init {
        /// Bitbucket Server URL
        #[arg(long)]
        bitbucket_url: Option<String>,

        /// Force initialization even if already initialized
        #[arg(long)]
        force: bool,
    },

    /// Configuration management
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Stack management
    Stacks {
        #[command(subcommand)]
        action: StackAction,
    },

    /// Entry management and editing
    Entry {
        #[command(subcommand)]
        action: EntryAction,
    },

    /// Show repository overview and all stacks
    Repo,

    /// Show version information  
    Version,

    /// Check repository health and configuration
    Doctor,

    /// Diagnose git2 TLS/SSH support issues
    Diagnose,

    /// Generate shell completions
    Completions {
        #[command(subcommand)]
        action: CompletionsAction,
    },

    /// Interactive setup wizard
    Setup {
        /// Force reconfiguration if already initialized
        #[arg(long)]
        force: bool,
    },

    /// Launch interactive TUI for stack management
    Tui,

    /// Git hooks management
    Hooks {
        #[command(subcommand)]
        action: HooksAction,
    },

    /// Visualize stacks and dependencies
    Viz {
        #[command(subcommand)]
        action: VizAction,
    },

    /// Clean up orphaned temporary branches
    Cleanup {
        /// Actually delete branches (default is dry-run)
        #[arg(long)]
        execute: bool,

        /// Force deletion even if branches have unmerged commits
        #[arg(long)]
        force: bool,
    },

    // Stack command shortcuts for commonly used operations
    /// Show current stack details
    Stack {
        /// Show detailed pull request information
        #[arg(short, long)]
        verbose: bool,
        /// Show mergability status for all PRs
        #[arg(short, long)]
        mergeable: bool,
    },

    /// Push current commit to the top of the stack (shortcut for 'stack push')
    Push {
        /// Branch name for this commit
        #[arg(long, short)]
        branch: Option<String>,
        /// Commit message (if creating a new commit)
        #[arg(long, short)]
        message: Option<String>,
        /// Use specific commit hash instead of HEAD
        #[arg(long)]
        commit: Option<String>,
        /// Push commits since this reference (e.g., HEAD~3)
        #[arg(long)]
        since: Option<String>,
        /// Push multiple specific commits (comma-separated)
        #[arg(long)]
        commits: Option<String>,
        /// Squash last N commits into one before pushing
        #[arg(long)]
        squash: Option<usize>,
        /// Squash all commits since this reference (e.g., HEAD~5)
        #[arg(long)]
        squash_since: Option<String>,
        /// Auto-create feature branch when pushing from base branch
        #[arg(long)]
        auto_branch: bool,
        /// Allow pushing commits from base branch (not recommended)
        #[arg(long)]
        allow_base_branch: bool,
        /// Show what would be pushed without actually pushing
        #[arg(long)]
        dry_run: bool,
        /// Skip confirmation prompts
        #[arg(long, short = 'y')]
        yes: bool,
    },

    /// Pop the top commit from the stack (shortcut for 'stack pop')
    Pop {
        /// Keep the branch (don't delete it)
        #[arg(long)]
        keep_branch: bool,
    },

    /// Drop (remove) stack entries by position (shortcut for 'stacks drop')
    Drop {
        /// Entry position or range (e.g., "3", "1-5", "1,3,5")
        entry: String,
        /// Keep the branch (don't delete it)
        #[arg(long)]
        keep_branch: bool,
        /// Keep the PR open on Bitbucket (don't decline it)
        #[arg(long)]
        keep_pr: bool,
        /// Skip all confirmation prompts
        #[arg(long, short)]
        force: bool,
        /// Skip confirmation prompts
        #[arg(long, short = 'y')]
        yes: bool,
    },

    /// Land (merge) approved stack entries (shortcut for 'stack land')
    Land {
        /// Stack entry number to land (1-based index, optional)
        entry: Option<usize>,
        /// Force land even with blocking issues (dangerous)
        #[arg(short, long)]
        force: bool,
        /// Dry run - show what would be landed without doing it
        #[arg(short, long)]
        dry_run: bool,
        /// Use server-side validation (safer, checks approvals/builds)
        #[arg(long)]
        auto: bool,
        /// Wait for builds to complete before merging
        #[arg(long)]
        wait_for_builds: bool,
        /// Merge strategy to use
        #[arg(long, value_enum, default_value = "squash")]
        strategy: Option<MergeStrategyArg>,
        /// Maximum time to wait for builds (seconds)
        #[arg(long, default_value = "1800")]
        build_timeout: u64,
    },

    /// Auto-land all ready PRs (shortcut for 'stack autoland')
    Autoland {
        /// Force land even with blocking issues (dangerous)
        #[arg(short, long)]
        force: bool,
        /// Dry run - show what would be landed without doing it
        #[arg(short, long)]
        dry_run: bool,
        /// Wait for builds to complete before merging
        #[arg(long)]
        wait_for_builds: bool,
        /// Merge strategy to use
        #[arg(long, value_enum, default_value = "squash")]
        strategy: Option<MergeStrategyArg>,
        /// Maximum time to wait for builds (seconds)
        #[arg(long, default_value = "1800")]
        build_timeout: u64,
    },

    /// Sync operations (shortcut for 'stack sync')
    Sync {
        #[command(subcommand)]
        action: Option<SyncAction>,

        /// Force sync even if there are conflicts
        #[arg(long, global = true)]
        force: bool,
        /// Also cleanup merged branches after sync
        #[arg(long, global = true)]
        cleanup: bool,
        /// Interactive mode for conflict resolution
        #[arg(long, short, global = true)]
        interactive: bool,
    },

    /// Rebase operations (shortcut for 'stack rebase')
    Rebase {
        #[command(subcommand)]
        action: Option<RebaseAction>,

        /// Interactive rebase
        #[arg(long, short, global = true)]
        interactive: bool,
        /// Target base branch (defaults to stack's base branch)
        #[arg(long, global = true)]
        onto: Option<String>,
        /// Rebase strategy to use
        #[arg(long, value_enum, global = true)]
        strategy: Option<RebaseStrategyArg>,
    },

    /// Switch to a different stack (shortcut for 'stacks switch')
    Switch {
        /// Name of the stack to switch to
        #[arg(value_hint = clap::ValueHint::Other)]
        name: String,
    },

    /// Analyze conflicts in the repository
    Conflicts {
        /// Show detailed information about each conflict
        #[arg(long)]
        detailed: bool,

        /// Only show conflicts that can be auto-resolved
        #[arg(long)]
        auto_only: bool,

        /// Only show conflicts that require manual resolution
        #[arg(long)]
        manual_only: bool,

        /// Analyze specific files (if not provided, analyzes all conflicted files)
        #[arg(value_name = "FILE")]
        files: Vec<String>,
    },

    /// Deactivate the current stack - turn off stack mode (shortcut for 'stacks deactivate')
    Deactivate {
        /// Force deactivation without confirmation
        #[arg(long)]
        force: bool,
    },

    /// Submit a stack entry for review (shortcut for 'stacks submit')
    Submit {
        /// Stack entry number (1-based, defaults to all unsubmitted)
        entry: Option<usize>,
        /// Pull request title
        #[arg(long, short)]
        title: Option<String>,
        /// Pull request description
        #[arg(long, short)]
        description: Option<String>,
        /// Submit range of entries (e.g., "1-3" or "2,4,6")
        #[arg(long)]
        range: Option<String>,
        /// Create draft pull requests (default: true, use --no-draft to create ready PRs)
        #[arg(long, default_value_t = true)]
        draft: bool,
        /// Open the PR(s) in your default browser after submission (default: true, use --no-open to disable)
        #[arg(long, default_value_t = true)]
        open: bool,
    },

    /// Validate stack integrity and handle branch modifications (shortcut for 'stacks validate')
    Validate {
        /// Name of the stack (defaults to active stack)
        name: Option<String>,
        /// Auto-fix mode: incorporate, split, or reset
        #[arg(long)]
        fix: Option<String>,
    },

    /// Internal command for shell completion (hidden)
    #[command(hide = true)]
    CompletionHelper {
        #[command(subcommand)]
        action: CompletionHelperAction,
    },
}

/// Git hooks actions
#[derive(Debug, Subcommand)]
pub enum HooksAction {
    /// Install Cascade Git hooks
    Install {
        /// Install all hooks including post-commit (default: essential hooks only)
        #[arg(long)]
        all: bool,

        /// Skip prerequisite checks (repository type, configuration validation)
        #[arg(long)]
        skip_checks: bool,

        /// Allow installation on main/master branches (not recommended)
        #[arg(long)]
        allow_main_branch: bool,

        /// Skip confirmation prompt
        #[arg(long, short)]
        yes: bool,

        /// Force installation even if checks fail (not recommended)
        #[arg(long)]
        force: bool,
    },

    /// Uninstall all Cascade Git hooks
    Uninstall,

    /// Show Git hooks status
    Status,

    /// Install a specific hook
    Add {
        /// Hook name (post-commit, pre-push, commit-msg, prepare-commit-msg)
        hook: String,

        /// Skip prerequisite checks
        #[arg(long)]
        skip_checks: bool,

        /// Force installation even if checks fail
        #[arg(long)]
        force: bool,
    },

    /// Remove a specific hook
    Remove {
        /// Hook name (post-commit, pre-push, commit-msg, prepare-commit-msg)
        hook: String,
    },
}

/// Visualization actions
#[derive(Debug, Subcommand)]
pub enum VizAction {
    /// Show stack diagram
    Stack {
        /// Stack name (defaults to active stack)
        name: Option<String>,
        /// Output format (ascii, mermaid, dot, plantuml)
        #[arg(long, short)]
        format: Option<String>,
        /// Output file path
        #[arg(long, short)]
        output: Option<String>,
        /// Compact mode (less details)
        #[arg(long)]
        compact: bool,
        /// Disable colors
        #[arg(long)]
        no_colors: bool,
    },

    /// Show dependency graph of all stacks
    Deps {
        /// Output format (ascii, mermaid, dot, plantuml)
        #[arg(long, short)]
        format: Option<String>,
        /// Output file path
        #[arg(long, short)]
        output: Option<String>,
        /// Compact mode (less details)
        #[arg(long)]
        compact: bool,
        /// Disable colors
        #[arg(long)]
        no_colors: bool,
    },
}

/// Shell completion actions
#[derive(Debug, Subcommand)]
pub enum CompletionsAction {
    /// Generate completions for a shell
    Generate {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },

    /// Install completions for available shells
    Install {
        /// Specific shell to install for
        #[arg(long, value_enum)]
        shell: Option<Shell>,
    },

    /// Show completion installation status
    Status,
}

/// Hidden completion helper actions
#[derive(Debug, Subcommand)]
pub enum CompletionHelperAction {
    /// List available stack names
    StackNames,
}

#[derive(Debug, Subcommand)]
pub enum ConfigAction {
    /// Set a configuration value
    Set {
        /// Configuration key (e.g., bitbucket.url)
        key: String,
        /// Configuration value
        value: String,
    },

    /// Get a configuration value
    Get {
        /// Configuration key
        key: String,
    },

    /// List all configuration values
    List,

    /// Remove a configuration value
    Unset {
        /// Configuration key
        key: String,
    },
}

impl Cli {
    pub async fn run(self) -> Result<()> {
        // Set up logging based on verbosity
        self.setup_logging();

        // Initialize git2 to use system certificates by default
        // This ensures we work out-of-the-box in corporate environments
        // just like git CLI and other modern dev tools (Graphite, Sapling, Phabricator)
        self.init_git2_ssl()?;

        match self.command {
            Commands::Init {
                bitbucket_url,
                force,
            } => commands::init::run(bitbucket_url, force).await,
            Commands::Config { action } => commands::config::run(action).await,
            Commands::Stacks { action } => commands::stack::run(action).await,
            Commands::Entry { action } => commands::entry::run(action).await,
            Commands::Repo => commands::status::run().await,
            Commands::Version => commands::version::run().await,
            Commands::Doctor => commands::doctor::run().await,
            Commands::Diagnose => commands::diagnose::run().await,

            Commands::Completions { action } => match action {
                CompletionsAction::Generate { shell } => {
                    commands::completions::generate_completions(shell)
                }
                CompletionsAction::Install { shell } => {
                    commands::completions::install_completions(shell)
                }
                CompletionsAction::Status => commands::completions::show_completions_status(),
            },

            Commands::Setup { force } => commands::setup::run(force).await,

            Commands::Tui => commands::tui::run().await,

            Commands::Cleanup { execute, force } => commands::cleanup::run(execute, force).await,

            Commands::Hooks { action } => match action {
                HooksAction::Install {
                    all,
                    skip_checks,
                    allow_main_branch,
                    yes,
                    force,
                } => {
                    if all {
                        // Install all hooks including post-commit
                        commands::hooks::install_with_options(
                            skip_checks,
                            allow_main_branch,
                            yes,
                            force,
                        )
                        .await
                    } else {
                        // Install essential hooks by default (excludes post-commit)
                        // Users can install post-commit separately with 'ca hooks add post-commit'
                        commands::hooks::install_essential().await
                    }
                }
                HooksAction::Uninstall => commands::hooks::uninstall().await,
                HooksAction::Status => commands::hooks::status().await,
                HooksAction::Add {
                    hook,
                    skip_checks,
                    force,
                } => commands::hooks::install_hook_with_options(&hook, skip_checks, force).await,
                HooksAction::Remove { hook } => commands::hooks::uninstall_hook(&hook).await,
            },

            Commands::Viz { action } => match action {
                VizAction::Stack {
                    name,
                    format,
                    output,
                    compact,
                    no_colors,
                } => {
                    commands::viz::show_stack(
                        name.clone(),
                        format.clone(),
                        output.clone(),
                        compact,
                        no_colors,
                    )
                    .await
                }
                VizAction::Deps {
                    format,
                    output,
                    compact,
                    no_colors,
                } => {
                    commands::viz::show_dependencies(
                        format.clone(),
                        output.clone(),
                        compact,
                        no_colors,
                    )
                    .await
                }
            },

            Commands::Stack { verbose, mergeable } => {
                commands::stack::show(verbose, mergeable).await
            }

            Commands::Push {
                branch,
                message,
                commit,
                since,
                commits,
                squash,
                squash_since,
                auto_branch,
                allow_base_branch,
                dry_run,
                yes,
            } => {
                commands::stack::push(
                    branch,
                    message,
                    commit,
                    since,
                    commits,
                    squash,
                    squash_since,
                    auto_branch,
                    allow_base_branch,
                    dry_run,
                    yes,
                )
                .await
            }

            Commands::Pop { keep_branch } => commands::stack::pop(keep_branch).await,

            Commands::Drop {
                entry,
                keep_branch,
                keep_pr,
                force,
                yes,
            } => commands::stack::drop(entry, keep_branch, keep_pr, force, yes).await,

            Commands::Land {
                entry,
                force,
                dry_run,
                auto,
                wait_for_builds,
                strategy,
                build_timeout,
            } => {
                commands::stack::land(
                    entry,
                    force,
                    dry_run,
                    auto,
                    wait_for_builds,
                    strategy,
                    build_timeout,
                )
                .await
            }

            Commands::Autoland {
                force,
                dry_run,
                wait_for_builds,
                strategy,
                build_timeout,
            } => {
                commands::stack::autoland(force, dry_run, wait_for_builds, strategy, build_timeout)
                    .await
            }

            Commands::Sync {
                action,
                force,
                cleanup,
                interactive,
            } => match action {
                Some(SyncAction::Continue) => commands::stack::continue_sync().await,
                Some(SyncAction::Abort) => commands::stack::abort_sync().await,
                None => commands::stack::sync(force, cleanup, interactive).await,
            },

            Commands::Rebase {
                action,
                interactive,
                onto,
                strategy,
            } => match action {
                Some(RebaseAction::Continue) => commands::stack::continue_rebase().await,
                Some(RebaseAction::Abort) => commands::stack::abort_rebase().await,
                None => commands::stack::rebase(interactive, onto, strategy).await,
            },

            Commands::Switch { name } => commands::stack::switch(name).await,

            Commands::Conflicts {
                detailed,
                auto_only,
                manual_only,
                files,
            } => {
                commands::conflicts::run(commands::conflicts::ConflictsArgs {
                    detailed,
                    auto_only,
                    manual_only,
                    files,
                })
                .await
            }

            Commands::Deactivate { force } => commands::stack::deactivate(force).await,

            Commands::Submit {
                entry,
                title,
                description,
                range,
                draft,
                open,
            } => {
                // Delegate to the stacks submit functionality
                let submit_action = StackAction::Submit {
                    entry,
                    title,
                    description,
                    range,
                    draft,
                    open,
                };
                commands::stack::run(submit_action).await
            }

            Commands::Validate { name, fix } => {
                // Delegate to the stacks validate functionality
                let validate_action = StackAction::Validate { name, fix };
                commands::stack::run(validate_action).await
            }

            Commands::CompletionHelper { action } => handle_completion_helper(action).await,
        }
    }

    /// Initialize git2 to use system certificates by default
    /// This makes Cascade work like git CLI in corporate environments
    fn init_git2_ssl(&self) -> Result<()> {
        // Only import SSL functions on platforms that use them
        #[cfg(any(target_os = "macos", target_os = "linux"))]
        use git2::opts::{set_ssl_cert_dir, set_ssl_cert_file};

        // Configure git2 to use system certificate store
        // This matches behavior of git CLI and tools like Graphite/Sapling
        tracing::debug!("Initializing git2 SSL configuration with system certificates");

        // Try to use system certificate locations
        // On macOS: /etc/ssl/cert.pem, /usr/local/etc/ssl/cert.pem
        // On Linux: /etc/ssl/certs/ca-certificates.crt, /etc/ssl/certs/ca-bundle.crt
        // On Windows: Uses Windows certificate store automatically

        #[cfg(target_os = "macos")]
        {
            // macOS certificate locations (certificate files)
            let cert_files = [
                "/etc/ssl/cert.pem",
                "/usr/local/etc/ssl/cert.pem",
                "/opt/homebrew/etc/ca-certificates/cert.pem",
            ];

            for cert_path in &cert_files {
                if std::path::Path::new(cert_path).exists() {
                    tracing::debug!("Using macOS system certificates from: {}", cert_path);
                    if let Err(e) = unsafe { set_ssl_cert_file(cert_path) } {
                        tracing::trace!(
                            "SSL cert file {} not supported by TLS backend: {}",
                            cert_path,
                            e
                        );
                    } else {
                        return Ok(());
                    }
                }
            }

            // Fallback to certificate directories
            let cert_dirs = ["/etc/ssl/certs", "/usr/local/etc/ssl/certs"];

            for cert_dir in &cert_dirs {
                if std::path::Path::new(cert_dir).exists() {
                    tracing::debug!("Using macOS system certificate directory: {}", cert_dir);
                    if let Err(e) = unsafe { set_ssl_cert_dir(cert_dir) } {
                        tracing::trace!(
                            "SSL cert directory {} not supported by TLS backend: {}",
                            cert_dir,
                            e
                        );
                    } else {
                        return Ok(());
                    }
                }
            }
        }

        #[cfg(target_os = "linux")]
        {
            // Linux certificate files
            let cert_files = [
                "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
                "/etc/ssl/certs/ca-bundle.crt",       // RHEL/CentOS
                "/etc/pki/tls/certs/ca-bundle.crt",   // Fedora/RHEL
                "/etc/ssl/ca-bundle.pem",             // OpenSUSE
            ];

            for cert_path in &cert_files {
                if std::path::Path::new(cert_path).exists() {
                    tracing::debug!("Using Linux system certificates from: {}", cert_path);
                    if let Err(e) = unsafe { set_ssl_cert_file(cert_path) } {
                        tracing::trace!(
                            "SSL cert file {} not supported by TLS backend: {}",
                            cert_path,
                            e
                        );
                    } else {
                        return Ok(());
                    }
                }
            }

            // Fallback to certificate directories
            let cert_dirs = ["/etc/ssl/certs", "/etc/pki/tls/certs"];

            for cert_dir in &cert_dirs {
                if std::path::Path::new(cert_dir).exists() {
                    tracing::debug!("Using Linux system certificate directory: {}", cert_dir);
                    if let Err(e) = unsafe { set_ssl_cert_dir(cert_dir) } {
                        tracing::trace!(
                            "SSL cert directory {} not supported by TLS backend: {}",
                            cert_dir,
                            e
                        );
                    } else {
                        return Ok(());
                    }
                }
            }
        }

        #[cfg(target_os = "windows")]
        {
            // Windows uses system certificate store automatically via git2's default configuration
            tracing::debug!("Using Windows system certificate store (automatic)");
        }

        tracing::debug!("System SSL certificate configuration complete");
        tracing::debug!(
            "Note: SSL warnings from libgit2 are normal - git CLI fallback will be used if needed"
        );
        Ok(())
    }

    fn setup_logging(&self) {
        let level = if self.verbose {
            tracing::Level::DEBUG
        } else {
            tracing::Level::INFO
        };

        let subscriber = tracing_subscriber::fmt()
            .with_max_level(level)
            .with_target(false)
            .without_time();

        if self.no_color {
            subscriber.with_ansi(false).init();
        } else {
            subscriber.init();
        }
    }
}

/// Handle completion helper commands
async fn handle_completion_helper(action: CompletionHelperAction) -> Result<()> {
    match action {
        CompletionHelperAction::StackNames => {
            use crate::git::find_repository_root;
            use crate::stack::StackManager;
            use std::env;

            // Try to get stack names, but silently fail if not in a repository
            if let Ok(current_dir) = env::current_dir() {
                if let Ok(repo_root) = find_repository_root(&current_dir) {
                    if let Ok(manager) = StackManager::new(&repo_root) {
                        for (_, name, _, _, _) in manager.list_stacks() {
                            println!("{name}");
                        }
                    }
                }
            }
            Ok(())
        }
    }
}