stakk 2.1.2

A CLI tool that bridges Jujutsu (jj) bookmarks to GitHub stacked pull requests
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
pub mod revset;
pub mod submit;

use std::path::PathBuf;

use clap::Args;
use clap::Command;
use clap::CommandFactory;
use clap::FromArgMatches;
use clap::Parser;
use clap::Subcommand;
use clap_complete::Shell;

use crate::cli::revset::RevsetArgs;
use crate::cli::submit::SubmitArgs;
use crate::config::Config;
// Generated by build.rs from the `docs/` directory, one variant per Markdown
// file. Re-exported because the topic is a CLI value like any other, even
// though the docs module is where it comes from.
pub use crate::docs::DocTopic;

/// stakk — bridge Jujutsu bookmarks to GitHub stacked pull requests.
#[derive(Debug, Parser)]
#[command(version, about, after_long_help = env!("CARGO_PKG_REPOSITORY"))]
pub struct Cli {
    /// Path to a config file (overrides automatic discovery).
    ///
    /// Loaded in place of the repo-level stakk.toml; user-level config is
    /// still merged unless inherit = false.
    // Implementation note: this arg exists for --help discoverability only.
    // Config is loaded *before* clap parsing (so config values can be injected
    // as clap defaults), which means clap's parsed value arrives too late.
    // The actual path is resolved by `config::pre_parse_config_path()` from
    // raw `std::env::args()` / `STAKK_CONFIG`.
    #[arg(long, global = true, env = "STAKK_CONFIG", verbatim_doc_comment)]
    pub config: Option<PathBuf>,

    /// Extra host to treat as GitHub, for GitHub Enterprise Server.
    ///
    /// github.com is always accepted. Naming a host here additionally accepts
    /// remotes on that host and talks to its API at https://<host>/api/v3.
    /// Falls back to GH_HOST when unset, so an existing GitHub CLI setup works
    /// without further configuration.
    #[arg(long, global = true, env = "STAKK_GITHUB_HOST", verbatim_doc_comment)]
    pub github_host: Option<String>,

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

/// The subcommands, each with its initial letter as a visible alias.
///
/// `completions` has none: it is typed once per shell setup, never
/// interactively, so the letter buys nothing and `c` is better left free.
/// Aliases are stable surface — see `docs/stability.md`.
#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Submit bookmarks as GitHub pull requests (default when no command
    /// given).
    // Boxed: SubmitArgs is by far the largest payload (clippy
    // large_enum_variant).
    #[command(visible_alias = "s")]
    Submit(Box<SubmitArgs>),
    /// Render the repository's bookmark stacks as a graph.
    // `show` is a supported alias, visible so `--help` answers for it. It is
    // deprecated and will be removed in a future major — see
    // docs/stability.md.
    #[command(visible_aliases = ["g", "show"])]
    Graph(GraphArgs),
    /// Generate shell completions for the given shell.
    Completions {
        /// The shell to generate completions for.
        shell: Shell,
    },
    /// Print stakk's bundled documentation, or list the available topics.
    #[command(visible_alias = "d")]
    Docs {
        /// Topic to print. Omit to list the available topics.
        #[arg(value_enum)]
        topic: Option<DocTopic>,
    },
}

/// Output format for the graph subcommand.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum GraphFormat {
    /// Human-readable jj-log-style graph of all bookmark stacks.
    #[default]
    Pretty,
    /// Machine-readable, schema-versioned JSON: a sparse projection with
    /// just enough to pinpoint a segment.
    Json,
    /// The same JSON document with every field, including commit
    /// descriptions, authors and touched files.
    JsonFull,
}

/// Arguments for the graph subcommand.
#[derive(Debug, Args)]
pub struct GraphArgs {
    /// Output format.
    ///
    /// pretty renders a fully expanded jj-log-style commit graph: short
    /// change id, bookmarks and description summary per commit.
    ///
    /// json describes every stack, segment and commit for scripts and
    /// agents. Its identifiers (short_change_id, bookmark names) can be
    /// passed directly to `stakk submit`. It is a sparse projection:
    /// per commit it carries change_id, short_change_id, title,
    /// committer_timestamp, is_immutable, local_bookmark_names,
    /// is_boundary and is_leaf.
    ///
    /// json-full is the same document with commit_id, description,
    /// author and files added back. Every json field is present in
    /// json-full with the same name, type and value.
    #[arg(long, default_value = "pretty", value_enum, verbatim_doc_comment)]
    pub format: GraphFormat,

    #[command(flatten)]
    pub revset: RevsetArgs,
}

/// Apply config-file defaults to clap's `Command` before parsing.
///
/// This mutates argument default values so they appear in `--help` and
/// take effect when the user does not pass the corresponding flag.
#[expect(
    clippy::needless_pass_by_value,
    reason = "Config is moved into closures captured by mut_subcommand which requires 'static"
)]
pub fn apply_config_defaults(config: Config, cmd: Command) -> Command {
    // Global args live on the root; every other arg has exactly one home on
    // its own subcommand.
    let cmd = apply_global_defaults(&config, cmd);
    // Clone for the closures that mut_subcommand requires ('static).
    let config2 = config.clone();
    let cmd = cmd.mut_subcommand("submit", |sub| {
        let sub = apply_submit_defaults(&config, sub);
        apply_revset_defaults(&config, sub)
    });
    cmd.mut_subcommand("graph", |sub| apply_revset_defaults(&config2, sub))
}

/// Parse the `SubmitArgs` that a bare `stakk` runs with.
///
/// The args come from a real clap parse of the synthetic argv `stakk submit`
/// against a `Command` this function config-applies itself, so clap defaults,
/// `STAKK_*` environment variables and config-injected defaults all apply,
/// exactly as they would for a typed `stakk submit`. Building `SubmitArgs` by
/// hand would bypass all three — which is why `SubmitArgs` has no `Default`
/// impl. Taking the `Config` rather than a prepared `Command` keeps the
/// config application inside this function, where a caller cannot skip it.
pub fn default_submit_args(config: Config) -> Result<SubmitArgs, clap::Error> {
    let cmd = apply_config_defaults(config, Cli::command());
    let matches = cmd.try_get_matches_from(["stakk", "submit"])?;
    let submit = matches
        .subcommand_matches("submit")
        .expect("the synthetic argv always names the submit subcommand");
    SubmitArgs::from_arg_matches(submit)
}

fn set_default(cmd: Command, arg_id: &str, value: &str) -> Command {
    // Leak the value so clap can store it as a `'static` default. This is
    // acceptable because the CLI runs once and exits — the leaked count is
    // bounded by the number of config fields.
    let leaked: &'static str = Box::leak(value.to_string().into_boxed_str());
    cmd.mut_arg(arg_id, |a| a.default_value(leaked))
}

/// Defaults for `global = true` args on the root command.
///
/// Global args are defined once on the root and propagated to subcommands by
/// clap, so `mut_arg` must run on the root — calling it on a subcommand would
/// panic with "Argument is undefined".
fn apply_global_defaults(config: &Config, mut cmd: Command) -> Command {
    if let Some(ref host) = config.github_host {
        cmd = set_default(cmd, "github_host", host);
    }
    cmd
}

fn apply_submit_defaults(config: &Config, mut cmd: Command) -> Command {
    if let Some(ref remote) = config.remote {
        cmd = set_default(cmd, "remote", remote);
    }
    if let Some(pr_mode) = config.pr_mode {
        cmd = set_default(cmd, "pr_mode", &pr_mode.to_string());
    }
    if let Some(ref template_path) = config.template_path {
        cmd = set_default(cmd, "template_path", template_path);
    }
    if let Some(sp) = config.stack_placement {
        cmd = set_default(cmd, "stack_placement", &sp.to_string());
    }
    if let Some(spc) = config.sync_pr_content {
        cmd = set_default(cmd, "sync_pr_content", &spc.to_string());
    }
    if let Some(tr) = config.trailers {
        cmd = set_default(cmd, "trailers", &tr.to_string());
    }
    if let Some(ref ap) = config.auto_prefix {
        cmd = set_default(cmd, "auto_prefix", ap);
    }
    if let Some(ref bc) = config.bookmark_command {
        cmd = set_default(cmd, "bookmark_command", bc);
    }
    cmd
}

fn apply_revset_defaults(config: &Config, mut cmd: Command) -> Command {
    if let Some(ref br) = config.bookmarks_revset {
        cmd = set_default(cmd, "bookmarks_revset", br);
    }
    if let Some(ref hr) = config.heads_revset {
        cmd = set_default(cmd, "heads_revset", hr);
    }
    cmd
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::forge::comment::StackPlacement;

    /// Parse CLI args with the given config applied, returning the `Cli`.
    fn parse_with_config(config: Config, args: &[&str]) -> Cli {
        let cmd = apply_config_defaults(config, Cli::command());
        let matches = cmd.get_matches_from(args);
        Cli::from_arg_matches(&matches).unwrap()
    }

    /// Extract `SubmitArgs` from a parsed `stakk submit` invocation.
    fn submit_args(cli: &Cli) -> &SubmitArgs {
        match &cli.command {
            Some(Commands::Submit(args)) => args,
            other => panic!("expected Submit, got {other:?}"),
        }
    }

    // -- pr_mode tests --

    use crate::cli::submit::PrMode;

    #[test]
    fn pr_mode_default_no_config() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).pr_mode, PrMode::Regular);
    }

    #[test]
    fn pr_mode_config_draft_no_flag() {
        let config = Config {
            pr_mode: Some(PrMode::Draft),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).pr_mode, PrMode::Draft);
    }

    #[test]
    fn pr_mode_config_regular_no_flag() {
        let config = Config {
            pr_mode: Some(PrMode::Regular),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).pr_mode, PrMode::Regular);
    }

    #[test]
    fn pr_mode_cli_draft() {
        // Config says regular, so this pins CLI-beats-config in the draft
        // direction; pr_mode_config_draft_cli_regular covers the reverse.
        let config = Config {
            pr_mode: Some(PrMode::Regular),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--pr-mode", "draft"]);
        assert_eq!(submit_args(&cli).pr_mode, PrMode::Draft);
    }

    #[test]
    fn pr_mode_cli_overrides_config() {
        let config = Config {
            pr_mode: Some(PrMode::Draft),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--pr-mode", "regular"]);
        assert_eq!(submit_args(&cli).pr_mode, PrMode::Regular);
    }

    // -- the bare `stakk` form --

    #[test]
    fn bare_stakk_parses_to_no_subcommand() {
        let cli = parse_with_config(Config::default(), &["stakk"]);
        assert!(cli.command.is_none());
    }

    /// Regression guard for 90718ef5cf97 ("fix: respect env vars when running
    /// without subcommand").
    ///
    /// The bare `stakk` form must take its `SubmitArgs` from a clap parse of
    /// the config-applied `Command` — the mechanism `default_submit_args`
    /// implements and `main.rs`'s `None` arm calls. A hand-built value would
    /// silently ignore both `STAKK_*` environment variables and the config
    /// defaults passed here. Env vars ride the same parse, so pinning the
    /// config path pins both; clap's own env handling is not ours to test.
    #[test]
    fn bare_stakk_submit_args_come_from_a_config_applied_clap_parse() {
        let config = Config {
            pr_mode: Some(PrMode::Draft),
            ..Default::default()
        };
        let args = default_submit_args(config).unwrap();
        assert_eq!(args.pr_mode, PrMode::Draft);
    }

    #[test]
    fn bare_stakk_rejects_submit_flags() {
        use clap::error::ErrorKind;

        let cmd = apply_config_defaults(Config::default(), Cli::command());
        let err = cmd
            .try_get_matches_from(["stakk", "--dry-run"])
            .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::UnknownArgument);
    }

    // -- remote tests --

    #[test]
    fn remote_default_no_config() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).remote, "origin");
    }

    #[test]
    fn remote_config_override() {
        let config = Config {
            remote: Some("upstream".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).remote, "upstream");
    }

    #[test]
    fn remote_cli_overrides_config() {
        let config = Config {
            remote: Some("upstream".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--remote", "other"]);
        assert_eq!(submit_args(&cli).remote, "other");
    }

    // -- github_host tests --
    //
    // github_host is a `global = true` arg on the root command, so its config
    // default is injected there rather than per subcommand. These cover that it
    // still reaches every subcommand.

    #[test]
    fn github_host_default_none() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(cli.github_host, None);
    }

    #[test]
    fn github_host_from_config() {
        let config = Config {
            github_host: Some("github.example.com".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(cli.github_host.as_deref(), Some("github.example.com"));
    }

    #[test]
    fn github_host_cli_overrides_config() {
        let config = Config {
            github_host: Some("github.example.com".into()),
            ..Default::default()
        };
        let cli = parse_with_config(
            config,
            &["stakk", "submit", "--github-host", "ghe.other.com"],
        );
        assert_eq!(cli.github_host.as_deref(), Some("ghe.other.com"));
    }

    #[test]
    fn github_host_is_global_and_parses_before_the_subcommand() {
        // `global = true` makes it insertable anywhere; the submit flags are
        // accepted only after `submit`.
        let cli = parse_with_config(
            Config::default(),
            &["stakk", "--github-host", "ghe.example.com", "submit"],
        );
        assert_eq!(cli.github_host.as_deref(), Some("ghe.example.com"));
    }

    #[test]
    fn github_host_from_config_reaches_graph() {
        let config = Config {
            github_host: Some("github.example.com".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "graph"]);
        assert_eq!(cli.github_host.as_deref(), Some("github.example.com"));
    }

    /// The bare form has no subcommand to carry the global arg, and `main.rs`
    /// reads `github_host` off this parse — not off the synthetic `submit`
    /// parse, which yields a `SubmitArgs` with no host field.
    #[test]
    fn github_host_from_config_reaches_bare_stakk() {
        let config = Config {
            github_host: Some("github.example.com".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk"]);
        assert_eq!(cli.github_host.as_deref(), Some("github.example.com"));
    }

    // -- template_path tests --

    #[test]
    fn template_path_default_none() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).template_path, None);
    }

    #[test]
    fn template_path_config_override() {
        let config = Config {
            template_path: Some("/from/config.jinja".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(
            submit_args(&cli).template_path.as_deref(),
            Some("/from/config.jinja"),
        );
    }

    #[test]
    fn template_path_cli_overrides_config() {
        let config = Config {
            template_path: Some("/from/config.jinja".into()),
            ..Default::default()
        };
        let cli = parse_with_config(
            config,
            &["stakk", "submit", "--template-path", "/from/cli.jinja"],
        );
        assert_eq!(
            submit_args(&cli).template_path.as_deref(),
            Some("/from/cli.jinja"),
        );
    }

    // -- stack_placement tests --

    #[test]
    fn stack_placement_default_no_config() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).stack_placement, StackPlacement::Comment);
    }

    #[test]
    fn stack_placement_config_body() {
        let config = Config {
            stack_placement: Some(StackPlacement::Body),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).stack_placement, StackPlacement::Body);
    }

    #[test]
    fn stack_placement_cli_overrides_config() {
        let config = Config {
            stack_placement: Some(StackPlacement::Body),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--stack-placement", "comment"]);
        assert_eq!(submit_args(&cli).stack_placement, StackPlacement::Comment);
    }

    #[test]
    fn stack_placement_config_none() {
        let config = Config {
            stack_placement: Some(StackPlacement::None),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).stack_placement, StackPlacement::None);
    }

    #[test]
    fn stack_placement_cli_none_overrides_config() {
        let config = Config {
            stack_placement: Some(StackPlacement::Body),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--stack-placement", "none"]);
        assert_eq!(submit_args(&cli).stack_placement, StackPlacement::None);
    }

    // -- sync_pr_content tests --

    #[test]
    fn sync_pr_content_default_none() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(
            submit_args(&cli).sync_pr_content,
            crate::cli::submit::SyncPrContent::None,
        );
    }

    #[test]
    fn sync_pr_content_config_all() {
        let config = Config {
            sync_pr_content: Some(crate::cli::submit::SyncPrContent::All),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(
            submit_args(&cli).sync_pr_content,
            crate::cli::submit::SyncPrContent::All,
        );
    }

    #[test]
    fn sync_pr_content_cli_overrides_config() {
        let config = Config {
            sync_pr_content: Some(crate::cli::submit::SyncPrContent::All),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--sync-pr-content=title"]);
        assert_eq!(
            submit_args(&cli).sync_pr_content,
            crate::cli::submit::SyncPrContent::Title,
        );
    }

    // -- trailers tests --

    #[test]
    fn trailers_default_keep() {
        let cli = parse_with_config(Config::default(), &["stakk", "submit"]);
        assert_eq!(
            submit_args(&cli).trailers,
            crate::cli::submit::TrailerHandling::Keep,
        );
    }

    #[test]
    fn trailers_config_strip() {
        let config = Config {
            trailers: Some(crate::cli::submit::TrailerHandling::Strip),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(
            submit_args(&cli).trailers,
            crate::cli::submit::TrailerHandling::Strip,
        );
    }

    #[test]
    fn trailers_cli_overrides_config() {
        let config = Config {
            trailers: Some(crate::cli::submit::TrailerHandling::Strip),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--trailers=keep"]);
        assert_eq!(
            submit_args(&cli).trailers,
            crate::cli::submit::TrailerHandling::Keep,
        );
    }

    // -- auto_prefix tests --

    #[test]
    fn auto_prefix_config_override() {
        let config = Config {
            auto_prefix: Some("gb-".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).auto_prefix.as_deref(), Some("gb-"));
    }

    #[test]
    fn auto_prefix_cli_overrides_config() {
        let config = Config {
            auto_prefix: Some("gb-".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--auto-prefix", "xx-"]);
        assert_eq!(submit_args(&cli).auto_prefix.as_deref(), Some("xx-"));
    }

    // -- revset tests --

    #[test]
    fn bookmarks_revset_config_override() {
        let config = Config {
            bookmarks_revset: Some("all()".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).revset.bookmarks_revset, "all()");
    }

    #[test]
    fn heads_revset_config_override() {
        let config = Config {
            heads_revset: Some("heads(all())".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit"]);
        assert_eq!(submit_args(&cli).revset.heads_revset, "heads(all())");
    }

    #[test]
    fn revset_cli_overrides_config() {
        let config = Config {
            bookmarks_revset: Some("all()".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "submit", "--bookmarks-revset", "mine()"]);
        assert_eq!(submit_args(&cli).revset.bookmarks_revset, "mine()");
    }

    // -- graph subcommand gets revset defaults --

    #[test]
    fn graph_inherits_revset_defaults() {
        let config = Config {
            bookmarks_revset: Some("custom()".into()),
            heads_revset: Some("heads(custom())".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "graph"]);
        match &cli.command {
            Some(Commands::Graph(args)) => {
                assert_eq!(args.revset.bookmarks_revset, "custom()");
                assert_eq!(args.revset.heads_revset, "heads(custom())");
            }
            other => panic!("expected Graph, got {other:?}"),
        }
    }

    /// `apply_config_defaults` reaches the subcommand by its canonical name,
    /// so the alias must resolve to the same config-applied command rather
    /// than to an unconfigured one.
    #[test]
    fn show_alias_is_graph_and_still_gets_revset_defaults() {
        let config = Config {
            bookmarks_revset: Some("custom()".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config, &["stakk", "show"]);
        match &cli.command {
            Some(Commands::Graph(args)) => {
                assert_eq!(args.revset.bookmarks_revset, "custom()");
            }
            other => panic!("expected Graph, got {other:?}"),
        }
    }

    // -- one-letter aliases --

    /// `completions` deliberately has none.
    #[test]
    fn one_letter_aliases_reach_their_subcommands() {
        let cli = parse_with_config(Config::default(), &["stakk", "s"]);
        assert!(matches!(cli.command, Some(Commands::Submit(_))));

        let cli = parse_with_config(Config::default(), &["stakk", "g"]);
        assert!(matches!(cli.command, Some(Commands::Graph(_))));

        let cli = parse_with_config(Config::default(), &["stakk", "d", "config"]);
        match &cli.command {
            Some(Commands::Docs { topic }) => assert_eq!(*topic, Some(DocTopic::Config)),
            other => panic!("expected Docs, got {other:?}"),
        }
    }

    /// The letter goes through the same config-applied `Command` as the name it
    /// stands for, which `mut_subcommand` only ever sees by its canonical
    /// spelling.
    #[test]
    fn one_letter_aliases_still_get_config_defaults() {
        let config = Config {
            bookmarks_revset: Some("custom()".into()),
            ..Default::default()
        };
        let cli = parse_with_config(config.clone(), &["stakk", "s"]);
        assert_eq!(submit_args(&cli).revset.bookmarks_revset, "custom()");

        let cli = parse_with_config(config, &["stakk", "g"]);
        match &cli.command {
            Some(Commands::Graph(args)) => {
                assert_eq!(args.revset.bookmarks_revset, "custom()");
            }
            other => panic!("expected Graph, got {other:?}"),
        }
    }

    #[test]
    fn completions_has_no_one_letter_alias() {
        let cmd = apply_config_defaults(Config::default(), Cli::command());
        assert!(cmd.try_get_matches_from(["stakk", "c", "zsh"]).is_err());
    }

    // -- docs subcommand --

    #[test]
    fn docs_without_topic_is_none() {
        // `None` means "print the index", not "print a default topic".
        let cli = parse_with_config(Config::default(), &["stakk", "docs"]);
        match &cli.command {
            Some(Commands::Docs { topic }) => assert_eq!(*topic, None),
            other => panic!("expected Docs, got {other:?}"),
        }
    }

    /// Driven by the generated variants rather than a written-out list, which
    /// would otherwise have to be extended by hand every time a document is
    /// added to `docs/` — the edit this whole arrangement exists to avoid.
    #[test]
    fn docs_parses_each_topic() {
        use clap::ValueEnum as _;

        for expected in DocTopic::value_variants() {
            let arg = expected
                .to_possible_value()
                .expect("every DocTopic variant has a possible value")
                .get_name()
                .to_string();
            let cli = parse_with_config(Config::default(), &["stakk", "docs", &arg]);
            match &cli.command {
                Some(Commands::Docs { topic }) => assert_eq!(*topic, Some(*expected)),
                other => panic!("expected Docs, got {other:?}"),
            }
        }
    }

    #[test]
    fn docs_rejects_an_unknown_topic() {
        use clap::error::ErrorKind;

        let cmd = apply_config_defaults(Config::default(), Cli::command());
        let err = cmd
            .try_get_matches_from(["stakk", "docs", "nonsense"])
            .unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidValue);
    }

    // -- explicit selection flags --

    #[test]
    fn selection_flags_parse_and_accumulate() {
        let cli = parse_with_config(
            Config::default(),
            &[
                "stakk",
                "submit",
                "--keep",
                "a",
                "--keep",
                "b",
                "--new",
                "r1=name1",
                "--new",
                "r2",
                "--new-auto",
                "r3",
                "--new-command",
                "r4",
            ],
        );
        let args = submit_args(&cli);
        assert_eq!(args.keep, vec!["a", "b"]);
        assert_eq!(args.new, vec!["r1=name1", "r2"]);
        assert_eq!(args.new_auto, vec!["r3"]);
        assert_eq!(args.new_command, vec!["r4"]);
    }

    // -- env var interaction --

    #[test]
    fn env_var_overrides_config() {
        // env vars are set per-process, so this test just verifies the
        // precedence: CLI > env > config > hardcoded default.
        // We can't easily test env vars in unit tests without side effects,
        // so this test documents the expected clap precedence.
        let config = Config {
            remote: Some("from-config".into()),
            ..Default::default()
        };
        // CLI flag should override config.
        let cli = parse_with_config(config, &["stakk", "submit", "--remote", "from-cli"]);
        assert_eq!(submit_args(&cli).remote, "from-cli");
    }

    // -- TOML parsing --

    #[test]
    fn toml_deserialize_full() {
        let toml_str = r#"
remote = "upstream"
github_host = "github.example.com"
pr_mode = "draft"
template_path = "/path/to/template.jinja"
stack_placement = "body"
sync_pr_content = "all"
trailers = "strip"
auto_prefix = "gb-"
bookmark_command = "my-command"
bookmarks_revset = "all()"
heads_revset = "heads(all())"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.remote.as_deref(), Some("upstream"));
        assert_eq!(config.github_host.as_deref(), Some("github.example.com"));
        assert_eq!(config.pr_mode, Some(PrMode::Draft));
        assert_eq!(
            config.template_path.as_deref(),
            Some("/path/to/template.jinja"),
        );
        assert_eq!(config.stack_placement, Some(StackPlacement::Body));
        assert_eq!(
            config.sync_pr_content,
            Some(crate::cli::submit::SyncPrContent::All),
        );
        assert_eq!(
            config.trailers,
            Some(crate::cli::submit::TrailerHandling::Strip),
        );
        assert_eq!(config.auto_prefix.as_deref(), Some("gb-"));
        assert_eq!(config.bookmark_command.as_deref(), Some("my-command"));
        assert_eq!(config.bookmarks_revset.as_deref(), Some("all()"));
        assert_eq!(config.heads_revset.as_deref(), Some("heads(all())"));
    }

    #[test]
    fn toml_deserialize_empty() {
        let config: Config = toml::from_str("").unwrap();
        assert!(config.remote.is_none());
        assert!(config.pr_mode.is_none());
    }

    #[test]
    fn toml_deserialize_partial() {
        let config: Config = toml::from_str(r#"pr_mode = "regular""#).unwrap();
        assert_eq!(config.pr_mode, Some(PrMode::Regular));
        assert!(config.remote.is_none());
    }

    #[test]
    fn toml_rejects_unknown_field() {
        let result: Result<Config, _> = toml::from_str("bogus = 42");
        assert!(result.is_err());
    }

    #[test]
    fn toml_stack_placement_kebab_case() {
        let config: Config = toml::from_str(r#"stack_placement = "comment""#).unwrap();
        assert_eq!(config.stack_placement, Some(StackPlacement::Comment));
    }

    #[test]
    fn toml_stack_placement_none() {
        let config: Config = toml::from_str(r#"stack_placement = "none""#).unwrap();
        assert_eq!(config.stack_placement, Some(StackPlacement::None));
    }

    #[test]
    fn toml_stack_placement_ignore() {
        let config: Config = toml::from_str(r#"stack_placement = "ignore""#).unwrap();
        assert_eq!(config.stack_placement, Some(StackPlacement::Ignore));
    }

    #[test]
    fn toml_stack_placement_invalid() {
        let result: Result<Config, _> = toml::from_str(r#"stack_placement = "invalid""#);
        assert!(result.is_err());
    }
}