gen-circleci-orb 0.0.46

Generate a CircleCI orb to provide the facilities offered by a CLI program
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
use anyhow::Result;
use clap::ValueEnum;
use std::path::{Path, PathBuf};

use crate::{help_parser, orb_config, orb_generator, output_writer};

pub const DEFAULT_BASE_IMAGE: &str = "debian:13-slim";

/// Base image used when the MCP feature is enabled. `build_mcp_server` compiles
/// the MCP server at runtime via `gen-orb-mcp generate --format binary`, so the
/// executor needs a Rust toolchain (cargo) present in the runtime stage.
pub const MCP_DEFAULT_BASE_IMAGE: &str = "rust:1-slim-trixie";

/// Apt packages the executor image needs to support `build_mcp_server`:
/// `libssl-dev`/`pkg-config` for the cargo compile, `gnupg` for the
/// `gen-orb-mcp save --sign` signed commit-back. Injected automatically when
/// the MCP feature is enabled. (No `openssh-client`: git uses HTTPS via
/// `set_https_remote`.)
pub const MCP_APT_PACKAGES: &[&str] = &["gnupg", "libssl-dev", "pkg-config"];

/// Whether the MCP feature is enabled in `[ci].mcp`.
pub(crate) fn mcp_enabled(config: &crate::orb_config::OrbConfig) -> bool {
    config.ci.as_ref().and_then(|c| c.mcp).unwrap_or(false)
}

#[derive(Debug, Clone, ValueEnum)]
pub enum InstallMethod {
    Binstall,
    Apt,
    /// Binary is pre-built and present in the Docker build context as `./{binary}`.
    /// Generates a single-stage Dockerfile with `COPY {binary}` — no crates.io download.
    /// Use when the release pipeline builds the binary before `docker build`.
    Local,
}

/// Generate orb source files from a CLI binary's --help output.
#[derive(Debug, clap::Args)]
pub struct Generate {
    /// Name of the binary to introspect (must be on PATH).
    /// Falls back to `binary` in the [orb] section of gen-circleci-orb.toml.
    #[arg(long)]
    pub binary: Option<String>,

    /// CircleCI orb namespace(s) to publish the orb under (repeatable).
    /// Falls back to `namespaces` in the [orb] section of gen-circleci-orb.toml.
    #[arg(long = "orb-namespace")]
    pub namespaces: Vec<String>,

    /// Project root directory (orb source is written to <output>/<orb-dir>/).
    #[arg(long, default_value = ".")]
    pub output: PathBuf,

    /// How the binary is installed in the generated Docker image.
    /// Falls back to `install_method` in the [orb] section of gen-circleci-orb.toml, then "binstall".
    #[arg(long, value_enum)]
    pub install_method: Option<InstallMethod>,

    /// Base Docker image for the generated executor.
    /// Falls back to `base_image` in the [orb] section of gen-circleci-orb.toml, then "debian:13-slim".
    #[arg(long)]
    pub base_image: Option<String>,

    /// Home URL for the orb registry display section.
    /// Falls back to `home_url` in the [orb] section of gen-circleci-orb.toml.
    #[arg(long)]
    pub home_url: Option<String>,

    /// Source URL for the orb registry display section.
    /// Falls back to `source_url` in the [orb] section of gen-circleci-orb.toml.
    #[arg(long)]
    pub source_url: Option<String>,

    /// Subdirectory within --output where orb source is written.
    /// Falls back to `orb_dir` in the [orb] section of gen-circleci-orb.toml, then "orb".
    #[arg(long)]
    pub orb_dir: Option<String>,

    /// Subcommand name(s) whose generated jobs should include a set_https_remote step
    /// (repeatable). Use for subcommands that push to git, e.g. --git-push-subcommand save.
    #[arg(long = "git-push-subcommand")]
    pub git_push_subcommands: Vec<String>,

    /// circleci-cli version to install in the generated Docker image executor.
    /// When set, adds a cli-installer builder stage that downloads the release
    /// tarball, verifies its SHA-256 checksum, and copies the binary into the
    /// final image.  Required when the wrapped binary calls `circleci` commands
    /// at runtime (e.g. when generating gen-circleci-orb's own orb).
    #[arg(long)]
    pub circleci_cli_version: Option<String>,

    /// Extra apt package(s) to install in the final Docker image stage (repeatable).
    /// Combined with the baseline packages (ca-certificates, git) and sorted
    /// alphanumerically. Example: --apt-packages libssl-dev --apt-packages pkg-config
    #[arg(long = "apt-packages")]
    pub apt_packages: Vec<String>,

    /// Show planned output without writing any files.
    #[arg(long)]
    pub dry_run: bool,

    /// Path to gen-circleci-orb.toml config file.
    /// Defaults to <output>/gen-circleci-orb.toml when not specified.
    #[arg(long)]
    pub config: Option<PathBuf>,
}

/// Convert any git remote URL to a plain HTTPS URL, stripping the `.git` suffix.
///
/// Handles:
/// - `git@github.com:org/repo.git` → `https://github.com/org/repo`
/// - `https://github.com/org/repo.git` → `https://github.com/org/repo`
/// - `https://github.com/org/repo` → unchanged
pub(crate) fn normalize_git_remote_url(url: &str) -> String {
    let url = if let Some(rest) = url.strip_prefix("git@") {
        // git@host:org/repo.git → https://host/org/repo
        let normalized = rest.replacen(':', "/", 1);
        format!("https://{normalized}")
    } else {
        url.to_string()
    };
    url.strip_suffix(".git").unwrap_or(&url).to_string()
}

/// Attempt to detect the repository source URL from the git remote named `origin`.
/// Returns `None` if git is unavailable or no `origin` remote is configured.
pub(crate) fn detect_source_url() -> Option<String> {
    let output = std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let raw = String::from_utf8(output.stdout).ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(normalize_git_remote_url(trimmed))
}

/// Guard: refuse to write into a directory that exists but looks like unrelated source code.
///
/// A directory is considered safe if it is absent, empty, or already contains `src/@orb.yml`.
pub(crate) fn check_orb_dir(orb_root: &Path) -> Result<()> {
    if !orb_root.exists() {
        return Ok(());
    }
    if orb_root.join("src/@orb.yml").exists() {
        return Ok(());
    }
    let has_content = std::fs::read_dir(orb_root)?.next().is_some();
    if has_content {
        anyhow::bail!(
            "Directory '{}' already exists but does not appear to contain a CircleCI orb \
             (no src/@orb.yml found). Refusing to write into it to avoid mixing orb source \
             with unrelated code. Use --orb-dir to specify a different subdirectory.",
            orb_root.display()
        );
    }
    Ok(())
}

/// Resolve the binary name: CLI flag takes precedence, then `[orb].binary` in config.
/// Returns an error with a helpful message when neither is provided.
pub(crate) fn resolve_binary(
    cli: Option<&str>,
    config: &crate::orb_config::OrbConfig,
) -> Result<String> {
    if let Some(b) = cli.filter(|s| !s.is_empty()) {
        return Ok(b.to_string());
    }
    config
        .orb
        .as_ref()
        .and_then(|o| o.binary.clone())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "binary name is required — pass --binary <NAME> or add `binary = \"<name>\"` \
                 to the [orb] section of gen-circleci-orb.toml"
            )
        })
}

/// Resolve namespaces: CLI flags take precedence, then `[orb].namespaces` in config.
/// Returns an error with a helpful message when neither is provided.
pub(crate) fn resolve_namespaces(
    cli: &[String],
    config: &crate::orb_config::OrbConfig,
) -> Result<Vec<String>> {
    if !cli.is_empty() {
        return Ok(cli.to_vec());
    }
    config
        .orb
        .as_ref()
        .and_then(|o| o.namespaces.clone())
        .filter(|ns| !ns.is_empty())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "at least one namespace is required — pass --orb-namespace <NS> or add \
                 `namespaces = [\"<ns>\"]` to the [orb] section of gen-circleci-orb.toml"
            )
        })
}

/// Resolve orb_dir: CLI value takes precedence, then `[orb].orb_dir` in config, then "orb".
pub(crate) fn resolve_orb_dir(cli: Option<&str>, config: &crate::orb_config::OrbConfig) -> String {
    cli.filter(|s| !s.is_empty())
        .map(str::to_string)
        .or_else(|| config.orb.as_ref().and_then(|o| o.orb_dir.clone()))
        .unwrap_or_else(|| "orb".to_string())
}

/// CLI flag takes precedence; falls back to `[orb] git_push_subcommands` in the config.
pub(crate) fn resolve_git_push_subcommands(
    cli: &[String],
    config: &crate::orb_config::OrbConfig,
) -> Vec<String> {
    if !cli.is_empty() {
        return cli.to_vec();
    }
    config
        .orb
        .as_ref()
        .and_then(|o| o.git_push_subcommands.clone())
        .unwrap_or_default()
}

/// CLI flag takes precedence; falls back to `[orb].install_method` in config, then Binstall.
pub(crate) fn resolve_install_method(
    cli: Option<&InstallMethod>,
    config: &crate::orb_config::OrbConfig,
) -> InstallMethod {
    if let Some(m) = cli {
        return m.clone();
    }
    config
        .orb
        .as_ref()
        .and_then(|o| o.install_method.as_deref())
        .and_then(|s| match s {
            "apt" => Some(InstallMethod::Apt),
            "binstall" => Some(InstallMethod::Binstall),
            "local" => Some(InstallMethod::Local),
            _ => None,
        })
        .unwrap_or(InstallMethod::Binstall)
}

/// CLI flag takes precedence, then `[orb].base_image`. When neither is set the
/// default depends on the MCP feature: MCP needs a Rust runtime (cargo) for the
/// `--format binary` compile, so it defaults to `MCP_DEFAULT_BASE_IMAGE`;
/// otherwise `DEFAULT_BASE_IMAGE`.
pub(crate) fn resolve_base_image(
    cli: Option<&str>,
    config: &crate::orb_config::OrbConfig,
) -> String {
    cli.filter(|s| !s.is_empty())
        .map(str::to_string)
        .or_else(|| config.orb.as_ref().and_then(|o| o.base_image.clone()))
        .unwrap_or_else(|| {
            if mcp_enabled(config) {
                MCP_DEFAULT_BASE_IMAGE.to_string()
            } else {
                DEFAULT_BASE_IMAGE.to_string()
            }
        })
}

/// CLI flags take precedence over `[orb].apt_packages`. When the MCP feature is
/// enabled, the build dependencies it requires (`MCP_APT_PACKAGES`) are unioned
/// in regardless, since `build_mcp_server` cannot run without them.
pub(crate) fn resolve_apt_packages(
    cli: &[String],
    config: &crate::orb_config::OrbConfig,
) -> Vec<String> {
    let mut pkgs = if !cli.is_empty() {
        cli.to_vec()
    } else {
        config
            .orb
            .as_ref()
            .and_then(|o| o.apt_packages.clone())
            .unwrap_or_default()
    };
    if mcp_enabled(config) {
        for pkg in MCP_APT_PACKAGES {
            if !pkgs.iter().any(|p| p == pkg) {
                pkgs.push((*pkg).to_string());
            }
        }
    }
    pkgs
}

pub(crate) fn resolve_config_path(explicit: Option<&PathBuf>, output: &Path) -> PathBuf {
    explicit
        .cloned()
        .unwrap_or_else(|| output.join("gen-circleci-orb.toml"))
}

impl Generate {
    pub fn run(&self) -> Result<()> {
        let config_path = resolve_config_path(self.config.as_ref(), &self.output);
        let orb_config = orb_config::load_config(&config_path)?;

        // Resolve fields that may come from config when not provided on CLI.
        let binary = resolve_binary(self.binary.as_deref(), &orb_config)?;
        let namespaces = resolve_namespaces(&self.namespaces, &orb_config)?;
        let orb_dir = resolve_orb_dir(self.orb_dir.as_deref(), &orb_config);

        let orb_root = self.output.join(&orb_dir);
        check_orb_dir(&orb_root)?;

        tracing::info!("Parsing {} --help", binary);
        let cli_def = help_parser::parse_binary(&binary)?;

        tracing::info!("Discovered {} subcommand(s)", cli_def.subcommands.len());

        let config_url = orb_config.orb.as_ref();
        let detected_url = self.source_url.is_none().then(detect_source_url).flatten();
        let source_url = self
            .source_url
            .clone()
            .or_else(|| config_url.and_then(|o| o.source_url.clone()))
            .or_else(|| detected_url.clone());
        let home_url = self
            .home_url
            .clone()
            .or_else(|| config_url.and_then(|o| o.home_url.clone()))
            .or_else(|| detected_url.clone());

        let opts = orb_generator::GenerateOpts {
            namespaces,
            install_method: resolve_install_method(self.install_method.as_ref(), &orb_config),
            base_image: resolve_base_image(self.base_image.as_deref(), &orb_config),
            home_url,
            source_url,
            binary_name: cli_def.binary_name.clone(),
            git_push_subcommands: resolve_git_push_subcommands(
                &self.git_push_subcommands,
                &orb_config,
            ),
            circleci_cli_version: self.circleci_cli_version.clone(),
            apt_packages: resolve_apt_packages(&self.apt_packages, &orb_config),
        };

        let files = orb_generator::generate(&cli_def, &opts, Some(&orb_config));

        tracing::info!("Generated {} file(s)", files.len());

        let report = output_writer::write_tree(&orb_root, &files, self.dry_run)?;

        println!(
            "Done: {} created, {} updated, {} unchanged",
            report.created, report.updated, report.unchanged
        );
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // ── normalize_git_remote_url ────────────────────────────────────────────

    #[test]
    fn normalize_ssh_remote_to_https() {
        assert_eq!(
            normalize_git_remote_url("git@github.com:jerus-org/gen-circleci-orb.git"),
            "https://github.com/jerus-org/gen-circleci-orb"
        );
    }

    #[test]
    fn normalize_https_with_git_suffix() {
        assert_eq!(
            normalize_git_remote_url("https://github.com/jerus-org/gen-circleci-orb.git"),
            "https://github.com/jerus-org/gen-circleci-orb"
        );
    }

    #[test]
    fn normalize_https_without_git_suffix_unchanged() {
        assert_eq!(
            normalize_git_remote_url("https://github.com/jerus-org/gen-circleci-orb"),
            "https://github.com/jerus-org/gen-circleci-orb"
        );
    }

    #[test]
    fn normalize_ssh_non_github_host() {
        assert_eq!(
            normalize_git_remote_url("git@gitlab.com:myorg/myrepo.git"),
            "https://gitlab.com/myorg/myrepo"
        );
    }

    #[test]
    fn check_orb_dir_absent_is_ok() {
        let tmp = TempDir::new().unwrap();
        let orb_root = tmp.path().join("orb");
        assert!(check_orb_dir(&orb_root).is_ok());
    }

    #[test]
    fn check_orb_dir_with_orb_yml_is_ok() {
        let tmp = TempDir::new().unwrap();
        let orb_root = tmp.path().join("orb");
        fs::create_dir_all(orb_root.join("src")).unwrap();
        fs::write(orb_root.join("src/@orb.yml"), "version: 2.1").unwrap();
        assert!(check_orb_dir(&orb_root).is_ok());
    }

    #[test]
    fn check_orb_dir_empty_is_ok() {
        let tmp = TempDir::new().unwrap();
        let orb_root = tmp.path().join("orb");
        fs::create_dir_all(&orb_root).unwrap();
        assert!(check_orb_dir(&orb_root).is_ok());
    }

    #[test]
    fn check_orb_dir_with_unrelated_content_errors() {
        let tmp = TempDir::new().unwrap();
        let orb_root = tmp.path().join("src");
        fs::create_dir_all(&orb_root).unwrap();
        fs::write(orb_root.join("main.rs"), "fn main() {}").unwrap();
        let result = check_orb_dir(&orb_root);
        assert!(
            result.is_err(),
            "should error when unrelated content present"
        );
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("does not appear to contain a CircleCI orb"),
            "unexpected error message: {msg}"
        );
    }

    // ── Phase 5: config path resolution ────────────────────────────────────

    #[test]
    fn config_path_defaults_to_output_dir() {
        let tmp = TempDir::new().unwrap();
        let output = tmp.path();
        let resolved = resolve_config_path(None, output);
        assert_eq!(resolved, output.join("gen-circleci-orb.toml"));
    }

    #[test]
    fn config_path_uses_explicit_when_provided() {
        let tmp = TempDir::new().unwrap();
        let output = tmp.path();
        let explicit = PathBuf::from("/custom/path/config.toml");
        let resolved = resolve_config_path(Some(&explicit), output);
        assert_eq!(resolved, explicit);
    }

    // ── resolve_orb_opts: config fallbacks for required fields ─────────────

    #[test]
    fn resolve_binary_uses_cli_when_provided() {
        use crate::orb_config::OrbConfig;
        let config = OrbConfig::default();
        let binary = resolve_binary(Some("mytool"), &config).unwrap();
        assert_eq!(binary, "mytool");
    }

    #[test]
    fn resolve_binary_falls_back_to_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                binary: Some("config-tool".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let binary = resolve_binary(None, &config).unwrap();
        assert_eq!(binary, "config-tool");
    }

    #[test]
    fn resolve_binary_errors_when_neither_provided() {
        use crate::orb_config::OrbConfig;
        let result = resolve_binary(None, &OrbConfig::default());
        assert!(
            result.is_err(),
            "must error when no binary in CLI or config"
        );
        assert!(result.unwrap_err().to_string().contains("binary"));
    }

    #[test]
    fn resolve_namespaces_uses_cli_when_provided() {
        use crate::orb_config::OrbConfig;
        let ns = resolve_namespaces(&["my-org".to_string()], &OrbConfig::default()).unwrap();
        assert_eq!(ns, vec!["my-org".to_string()]);
    }

    #[test]
    fn resolve_namespaces_falls_back_to_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                namespaces: Some(vec!["cfg-org".to_string()]),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let ns = resolve_namespaces(&[], &config).unwrap();
        assert_eq!(ns, vec!["cfg-org".to_string()]);
    }

    #[test]
    fn resolve_namespaces_errors_when_neither_provided() {
        use crate::orb_config::OrbConfig;
        let result = resolve_namespaces(&[], &OrbConfig::default());
        assert!(
            result.is_err(),
            "must error when no namespaces in CLI or config"
        );
        assert!(result.unwrap_err().to_string().contains("namespace"));
    }

    #[test]
    fn resolve_orb_dir_uses_cli_when_provided() {
        use crate::orb_config::OrbConfig;
        let dir = resolve_orb_dir(Some("custom-orb"), &OrbConfig::default());
        assert_eq!(dir, "custom-orb");
    }

    #[test]
    fn resolve_orb_dir_falls_back_to_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                orb_dir: Some("src/orb".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let dir = resolve_orb_dir(None, &config);
        assert_eq!(dir, "src/orb");
    }

    #[test]
    fn resolve_orb_dir_defaults_to_orb_when_nothing_provided() {
        use crate::orb_config::OrbConfig;
        let dir = resolve_orb_dir(None, &OrbConfig::default());
        assert_eq!(dir, "orb");
    }

    // ── resolve_install_method ─────────────────────────────────────────────

    #[test]
    fn resolve_install_method_uses_cli_when_provided() {
        use crate::orb_config::OrbConfig;
        let result = resolve_install_method(Some(&InstallMethod::Apt), &OrbConfig::default());
        assert!(matches!(result, InstallMethod::Apt));
    }

    #[test]
    fn resolve_install_method_falls_back_to_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                install_method: Some("apt".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_install_method(None, &config);
        assert!(
            matches!(result, InstallMethod::Apt),
            "expected Apt from config, got {result:?}"
        );
    }

    #[test]
    fn resolve_install_method_cli_overrides_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                install_method: Some("apt".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_install_method(Some(&InstallMethod::Binstall), &config);
        assert!(matches!(result, InstallMethod::Binstall));
    }

    #[test]
    fn resolve_install_method_local_from_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                install_method: Some("local".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_install_method(None, &config);
        assert!(matches!(result, InstallMethod::Local));
    }

    #[test]
    fn resolve_install_method_defaults_to_binstall() {
        use crate::orb_config::OrbConfig;
        let result = resolve_install_method(None, &OrbConfig::default());
        assert!(matches!(result, InstallMethod::Binstall));
    }

    // ── resolve_base_image ─────────────────────────────────────────────────

    #[test]
    fn resolve_base_image_uses_cli_when_provided() {
        use crate::orb_config::OrbConfig;
        let result = resolve_base_image(Some("ubuntu:22.04"), &OrbConfig::default());
        assert_eq!(result, "ubuntu:22.04");
    }

    #[test]
    fn resolve_base_image_falls_back_to_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                base_image: Some("ubuntu:22.04".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_base_image(None, &config);
        assert_eq!(result, "ubuntu:22.04");
    }

    #[test]
    fn resolve_base_image_cli_overrides_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                base_image: Some("ubuntu:22.04".to_string()),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_base_image(Some("alpine:3.19"), &config);
        assert_eq!(result, "alpine:3.19");
    }

    #[test]
    fn resolve_base_image_defaults_to_debian() {
        use crate::orb_config::OrbConfig;
        let result = resolve_base_image(None, &OrbConfig::default());
        assert_eq!(result, DEFAULT_BASE_IMAGE);
    }

    // ── resolve_apt_packages ───────────────────────────────────────────────

    #[test]
    fn resolve_apt_packages_uses_cli_when_provided() {
        use crate::orb_config::OrbConfig;
        let cli = vec!["libssl-dev".to_string(), "pkg-config".to_string()];
        let result = resolve_apt_packages(&cli, &OrbConfig::default());
        assert_eq!(result, vec!["libssl-dev", "pkg-config"]);
    }

    #[test]
    fn resolve_apt_packages_falls_back_to_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                apt_packages: Some(vec!["libssl-dev".to_string(), "pkg-config".to_string()]),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_apt_packages(&[], &config);
        assert_eq!(result, vec!["libssl-dev", "pkg-config"]);
    }

    #[test]
    fn resolve_apt_packages_cli_overrides_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                apt_packages: Some(vec!["libssl-dev".to_string()]),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_apt_packages(&["cmake".to_string()], &config);
        assert_eq!(result, vec!["cmake"]);
    }

    #[test]
    fn resolve_apt_packages_defaults_to_empty() {
        use crate::orb_config::OrbConfig;
        let result = resolve_apt_packages(&[], &OrbConfig::default());
        assert!(result.is_empty());
    }

    // ── MCP feature auto-provisions the executor image ─────────────────────

    fn mcp_config() -> crate::orb_config::OrbConfig {
        use crate::orb_config::{CiSection, OrbConfig};
        OrbConfig {
            ci: Some(CiSection {
                mcp: Some(true),
                ..CiSection::default()
            }),
            ..OrbConfig::default()
        }
    }

    #[test]
    fn mcp_enabled_reads_ci_section() {
        use crate::orb_config::OrbConfig;
        assert!(mcp_enabled(&mcp_config()));
        assert!(!mcp_enabled(&OrbConfig::default()));
    }

    #[test]
    fn resolve_base_image_defaults_to_rust_when_mcp_enabled() {
        let result = resolve_base_image(None, &mcp_config());
        assert_eq!(result, MCP_DEFAULT_BASE_IMAGE);
    }

    #[test]
    fn resolve_base_image_explicit_config_overrides_mcp_default() {
        use crate::orb_config::{CiSection, OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                base_image: Some("rust:1.85-slim".to_string()),
                ..OrbSection::default()
            }),
            ci: Some(CiSection {
                mcp: Some(true),
                ..CiSection::default()
            }),
            ..OrbConfig::default()
        };
        assert_eq!(resolve_base_image(None, &config), "rust:1.85-slim");
    }

    #[test]
    fn resolve_apt_packages_injects_mcp_deps_when_enabled() {
        let result = resolve_apt_packages(&[], &mcp_config());
        for pkg in MCP_APT_PACKAGES {
            assert!(
                result.iter().any(|p| p == pkg),
                "mcp must inject {pkg}; got {result:?}"
            );
        }
    }

    #[test]
    fn resolve_apt_packages_mcp_deps_union_with_user_packages() {
        use crate::orb_config::{CiSection, OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                apt_packages: Some(vec!["cmake".to_string()]),
                ..OrbSection::default()
            }),
            ci: Some(CiSection {
                mcp: Some(true),
                ..CiSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_apt_packages(&[], &config);
        assert!(
            result.iter().any(|p| p == "cmake"),
            "keep user pkg: {result:?}"
        );
        assert!(
            result.iter().any(|p| p == "gnupg"),
            "inject gnupg: {result:?}"
        );
    }

    #[test]
    fn resolve_apt_packages_no_mcp_deps_when_disabled() {
        use crate::orb_config::OrbConfig;
        let result = resolve_apt_packages(&[], &OrbConfig::default());
        assert!(
            !result.iter().any(|p| p == "gnupg"),
            "no mcp deps when mcp disabled: {result:?}"
        );
    }

    #[test]
    fn resolve_apt_packages_mcp_deps_not_duplicated() {
        use crate::orb_config::{CiSection, OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                apt_packages: Some(vec!["gnupg".to_string()]),
                ..OrbSection::default()
            }),
            ci: Some(CiSection {
                mcp: Some(true),
                ..CiSection::default()
            }),
            ..OrbConfig::default()
        };
        let result = resolve_apt_packages(&[], &config);
        assert_eq!(
            result.iter().filter(|p| *p == "gnupg").count(),
            1,
            "gnupg must not be duplicated: {result:?}"
        );
    }

    // ── git_push_subcommands: config fallback ───────────────────────────────

    #[test]
    fn git_push_subcommands_falls_back_to_config_when_cli_empty() {
        // When --git-push-subcommand is not passed on the CLI but the config
        // has [orb] git_push_subcommands = ["save"], generate must use the config value
        // so that set_https_remote is generated without requiring the flag every time.
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                git_push_subcommands: Some(vec!["save".to_string()]),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let resolved = resolve_git_push_subcommands(&[], &config);
        assert_eq!(resolved, vec!["save".to_string()]);
    }

    #[test]
    fn git_push_subcommands_cli_takes_precedence_over_config() {
        use crate::orb_config::{OrbConfig, OrbSection};
        let config = OrbConfig {
            orb: Some(OrbSection {
                git_push_subcommands: Some(vec!["save".to_string()]),
                ..OrbSection::default()
            }),
            ..OrbConfig::default()
        };
        let resolved = resolve_git_push_subcommands(&["commit".to_string()], &config);
        assert_eq!(resolved, vec!["commit".to_string()]);
    }
}