faucet-cli 1.9.0

Config-driven CLI runner for faucet-stream pipelines (YAML / JSON, Meltano-style)
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
//! `faucet template` — the CLI half of the pipeline template registry (#444).
//!
//! Register a parameterized config once into a store (`sqlite:` / `postgres://` /
//! `memory`), then list / inspect / delete versions, or materialize one with
//! `--param` values and run it locally. Pointing `faucet serve --history` at the
//! same URL makes the very same templates triggerable over HTTP — the CLI and
//! the control plane share one registry, not two.

use crate::cli::{
    TemplateArgs, TemplateCommand, TemplateDeleteArgs, TemplateDeprecateArgs, TemplateLaunchArgs,
    TemplateListArgs, TemplatePromoteArgs, TemplateRegisterArgs, TemplateRollbackArgs,
    TemplateRunArgs, TemplateShowArgs, TemplateStoreArgs,
};
use crate::error::{CliError, CliResult};
use crate::serve::history::templates::{
    TemplateRecord, TemplateSummary, VersionChannel, VersionSelector,
};
use crate::serve::load::ConfigFormat;
use crate::templates::{RegisterRequest, TemplateStore};

/// Execute the `template` subcommand.
pub async fn run(args: TemplateArgs) -> CliResult<()> {
    match args.command {
        TemplateCommand::Register(a) => register(a).await,
        TemplateCommand::List(a) => list(a).await,
        TemplateCommand::Show(a) => show(a).await,
        TemplateCommand::Launch(a) => launch(a).await,
        TemplateCommand::Rollback(a) => rollback(a).await,
        TemplateCommand::Deprecate(a) => deprecate(a).await,
        TemplateCommand::Promote(a) => promote(a).await,
        TemplateCommand::Delete(a) => delete(a).await,
        TemplateCommand::Run(a) => run_template(a).await,
    }
}

/// Load `.env` (so a `${env:…}` in a materialized template resolves) and connect
/// the registry store.
async fn connect(common: &TemplateStoreArgs) -> CliResult<TemplateStore> {
    let cwd = std::env::current_dir()?;
    let env_path =
        crate::env_loader::resolve_env_file(common.env_file.as_deref(), common.no_env_file, &cwd)?;
    crate::env_loader::load_env_file_if_present(env_path.as_deref())?;
    crate::templates::resolve_store_url(&common.store).await
}

fn to_pretty<T: serde::Serialize>(value: &T) -> CliResult<String> {
    serde_json::to_string_pretty(value)
        .map_err(|e| CliError::Internal(format!("rendering template JSON: {e}")))
}

/// Pick the wire format from a config path's extension.
fn format_of(path: &std::path::Path) -> CliResult<ConfigFormat> {
    match path
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("yaml" | "yml") => Ok(ConfigFormat::Yaml),
        Some("json") => Ok(ConfigFormat::Json),
        _ => Err(CliError::UnknownExtension {
            path: path.to_path_buf(),
        }),
    }
}

async fn register(args: TemplateRegisterArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let format = format_of(&args.config)?;
    let body = std::fs::read_to_string(&args.config).map_err(|e| {
        CliError::Config(format!(
            "reading template config '{}': {e}",
            args.config.display()
        ))
    })?;
    let tags = args
        .tag
        .iter()
        .map(|t| VersionChannel::parse(t))
        .collect::<CliResult<Vec<_>>>()?;
    let record = crate::templates::register(
        &store,
        RegisterRequest {
            id: args.id.clone(),
            body,
            format,
            description: args.description.clone(),
            tags: tags.clone(),
            launch: args.launch,
            created_by: None,
        },
    )
    .await?;

    if args.common.json {
        println!("{}", to_pretty(&record.summary())?);
        return Ok(());
    }
    println!(
        "registered template '{}' version {}{}",
        record.id,
        record.version,
        if tags.is_empty() {
            String::new()
        } else {
            format!(
                "  (channels: {})",
                tags.iter()
                    .map(|c| c.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    );
    print_params(&record.summary());
    println!(
        "\ntrigger it with:\n  faucet template run {} --store {}{}",
        record.id,
        args.common.store,
        required_param_hint(&record.summary())
    );
    Ok(())
}

/// `--param name=<…>` hints for every required param, for the register / show
/// "how do I run this" line.
fn required_param_hint(summary: &TemplateSummary) -> String {
    summary
        .params
        .iter()
        .filter(|(_, p)| p.required)
        .map(|(name, p)| format!(" --param {name}=<{}>", p.kind.as_str()))
        .collect()
}

fn print_params(summary: &TemplateSummary) {
    if summary.params.is_empty() {
        println!("params: (none — this template takes no overrides)");
        return;
    }
    println!("\nparams:");
    for (name, p) in &summary.params {
        let requirement = if p.required {
            "required".to_string()
        } else {
            match &p.default {
                Some(d) => format!("default {d}"),
                None => "optional".to_string(),
            }
        };
        println!(
            "  {:<20} {:<7} {}{}{}",
            name,
            p.kind.as_str(),
            requirement,
            if p.secret { "  [secret]" } else { "" },
            match &p.description {
                Some(d) => format!("{d}"),
                None => String::new(),
            }
        );
    }
}

async fn list(args: TemplateListArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let templates = crate::templates::list_with_state(&store).await?;
    if args.common.json {
        println!(
            "{}",
            to_pretty(&serde_json::json!({ "templates": templates }))?
        );
        return Ok(());
    }
    if templates.is_empty() {
        println!("no templates registered in this store — add one with `faucet template register`");
        return Ok(());
    }
    // LIVE is what an unpinned run gets; NEWEST is the build tip. Showing both
    // side by side is the whole point of the model — a nightly can sit at v7 while
    // production still rides v4.
    println!(
        "{:<26}  {:<11}  {:<6}  {:<7}  {:>6}  DESCRIPTION",
        "ID", "STATUS", "LIVE", "NEWEST", "PARAMS"
    );
    for t in &templates {
        let (status, live, newest) = match &t.state {
            Some(st) => (
                st.status.to_string(),
                st.stable.map(|v| format!("v{v}")).unwrap_or("".into()),
                st.newest.map(|v| format!("v{v}")).unwrap_or("".into()),
            ),
            None => ("?".into(), "?".into(), format!("v{}", t.version)),
        };
        println!(
            "{:<26}  {:<11}  {:<6}  {:<7}  {:>6}  {}",
            t.id,
            status,
            live,
            newest,
            t.params.len(),
            t.description.as_deref().unwrap_or("")
        );
    }
    Ok(())
}

/// Fetch one template, mapping "not found" to a typed error naming the id.
async fn fetch(store: &TemplateStore, id: &str, version: Option<u32>) -> CliResult<TemplateRecord> {
    store
        .template_get(id, version)
        .await
        .map_err(|e| CliError::Internal(format!("template registry read: {e}")))?
        .ok_or_else(|| CliError::UnknownPipelineTemplate {
            id: id.to_string(),
            version,
        })
}

async fn show(args: TemplateShowArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let selector = VersionSelector::parse(&args.version)?;
    let want = crate::templates::resolve_version(&store, &args.id, selector).await?;
    let record = fetch(&store, &args.id, Some(want)).await?;
    let state = crate::templates::template_state(&store, &args.id).await?;
    let launches = store
        .template_launches(&args.id)
        .await
        .map_err(|e| CliError::Internal(format!("template launch read: {e}")))?;

    if args.common.json {
        println!(
            "{}",
            to_pretty(&serde_json::json!({
                "template": record,
                "state": state,
                "is_stable": state.stable == Some(record.version),
                "launches": launches,
            }))?
        );
        return Ok(());
    }
    println!("template  {}   [{}]", record.id, state.status);
    if let Some(name) = &record.name {
        println!("name      {name}");
    }
    if let Some(d) = &record.description {
        println!("about     {d}");
    }
    println!(
        "created   {}{}",
        record.created_at.format("%Y-%m-%dT%H:%M:%SZ"),
        match &record.created_by {
            Some(p) => format!(" by {p}"),
            None => String::new(),
        }
    );
    println!(
        "showing   v{}{}",
        record.version,
        if state.stable == Some(record.version) {
            "  (live)"
        } else {
            ""
        }
    );
    // One row per version with its channels — the version-first view, which is
    // how you actually think about "what is v3 tagged as?".
    println!("\nversions:");
    for v in &state.versions {
        let mut marks: Vec<String> = Vec::new();
        if state.stable == Some(*v) {
            marks.push("live".into());
        }
        if state.previous == Some(*v) {
            marks.push("previous".into());
        }
        if state.newest == Some(*v) {
            marks.push("newest".into());
        }
        marks.extend(
            state
                .tags
                .iter()
                .filter(|(_, pointed)| *pointed == v)
                .map(|(t, _)| t.clone()),
        );
        println!(
            "  v{:<4} {}",
            v,
            if marks.is_empty() {
                String::from("")
            } else {
                marks.join(", ")
            }
        );
    }
    if let Some(d) = &state.deprecation {
        println!(
            "\ndeprecated {}{}",
            d.deprecated_at.format("%Y-%m-%dT%H:%M:%SZ"),
            match &d.reason {
                Some(r) => format!("{r}"),
                None => String::new(),
            }
        );
    }
    if !launches.is_empty() {
        println!("\nlaunch history (newest first):");
        for l in launches.iter().take(10) {
            println!(
                "  v{:<4} {}{}",
                l.version,
                l.launched_at.format("%Y-%m-%dT%H:%M:%SZ"),
                match &l.launched_by {
                    Some(by) => format!("  by {by}"),
                    None => String::new(),
                }
            );
        }
    }
    print_params(&record.summary());
    println!("\nconfig ({:?}, stored verbatim):", record.format);
    for line in record.body.lines() {
        println!("  {line}");
    }
    Ok(())
}

async fn delete(args: TemplateDeleteArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    // No `--version` deletes the whole template; a selector deletes one version.
    let pinned = match args.version.as_deref() {
        None => None,
        // A selector always resolves to a concrete version, so `--version stable`
        // removes just the launched one rather than the whole template.
        Some(raw) => Some(
            crate::templates::resolve_version(&store, &args.id, VersionSelector::parse(raw)?)
                .await?,
        ),
    };
    let removed = store
        .template_delete(&args.id, pinned)
        .await
        .map_err(|e| CliError::Internal(format!("template registry write: {e}")))?;
    if removed == 0 {
        return Err(CliError::UnknownPipelineTemplate {
            id: args.id.clone(),
            version: pinned,
        });
    }
    if args.common.json {
        println!(
            "{}",
            to_pretty(&serde_json::json!({ "id": args.id, "deleted_versions": removed }))?
        );
        return Ok(());
    }
    println!("deleted {removed} version(s) of template '{}'", args.id);
    Ok(())
}

/// Render a launch/rollback outcome.
fn report_launch(
    id: &str,
    outcome: &crate::templates::LaunchOutcome,
    json: bool,
    verb: &str,
) -> CliResult<()> {
    if json {
        println!(
            "{}",
            to_pretty(&serde_json::json!({
                "id": id,
                "version": outcome.version,
                "replaced": outcome.replaced,
                "already_launched": outcome.already_launched,
                "first_launch": outcome.first_launch,
            }))?
        );
        return Ok(());
    }
    if outcome.already_launched {
        println!(
            "template '{id}': v{} was already live — nothing changed",
            outcome.version
        );
        return Ok(());
    }
    println!(
        "template '{id}': {verb} v{}{}",
        outcome.version,
        match outcome.replaced {
            Some(prev) => format!(" (was v{prev}; previous → v{prev})"),
            None => String::from(" — first launch, template is now `launched`"),
        }
    );
    Ok(())
}

async fn launch(args: TemplateLaunchArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let target = VersionSelector::parse(&args.version)?;
    let outcome = crate::templates::launch(&store, &args.id, target, None).await?;
    report_launch(&args.id, &outcome, args.common.json, "launched")
}

async fn rollback(args: TemplateRollbackArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let outcome = crate::templates::rollback(&store, &args.id, None).await?;
    report_launch(&args.id, &outcome, args.common.json, "rolled back to")
}

async fn deprecate(args: TemplateDeprecateArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let status =
        crate::templates::set_deprecated(&store, &args.id, args.reason.clone(), None, !args.undo)
            .await?;
    if args.common.json {
        println!(
            "{}",
            to_pretty(&serde_json::json!({ "id": args.id, "status": status.as_str() }))?
        );
        return Ok(());
    }
    println!("template '{}' is now {status}", args.id);
    if !args.undo {
        println!(
            "  existing callers keep working (pinned runs and `stable` still resolve) but every \
             trigger warns — use `faucet template delete` for a hard stop"
        );
    }
    Ok(())
}

async fn promote(args: TemplatePromoteArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let tag = VersionChannel::parse(&args.tag)?;
    let target = VersionSelector::parse(&args.version)?;
    let version = crate::templates::promote(&store, &args.id, tag, target).await?;
    if args.common.json {
        println!(
            "{}",
            to_pretty(&serde_json::json!({
                "id": args.id, "tag": tag.as_str(), "version": version,
            }))?
        );
        return Ok(());
    }
    println!("template '{}': {tag} → v{version}", args.id);
    Ok(())
}

async fn run_template(args: TemplateRunArgs) -> CliResult<()> {
    let store = connect(&args.common).await?;
    let supplied = crate::params::collect_cli_params(&args.param)?;
    let env = crate::params::collect_env_overrides(&args.param_env)?;
    let selector = VersionSelector::parse(&args.version)?;
    let want = crate::templates::resolve_version(&store, &args.id, selector).await?;
    let materialized = crate::templates::materialize(
        &store,
        &args.id,
        want,
        &supplied,
        &env,
        // `faucet template run` executes locally; nothing is persisted.
        crate::templates::Materialize::Local,
    )
    .await?;

    tracing::info!(
        template = %materialized.template_id,
        version = materialized.version,
        "materialized pipeline template"
    );

    // The materialized body is JSON with every `${param.*}` bound; `${env:…}`
    // for overridden variables is bound too. Remaining directives (secrets,
    // un-overridden env) resolve on the normal load path below.
    let doc: serde_json::Value = serde_json::from_str(&materialized.body)
        .map_err(|e| CliError::Internal(format!("re-parsing materialized template: {e}")))?;
    let mut cfg = crate::config::PipelineConfig::from_value(doc)?;
    crate::secrets::resolve_secrets(&mut cfg).await?;

    if args.dry_run && args.common.json {
        println!("{}", to_pretty(&cfg)?);
        return Ok(());
    }

    // Run through the identical path as `faucet run`, so observability,
    // lineage, notifications, the catalog, SLA evaluation, and row selection all
    // behave the same as they would for the same config on disk.
    let run_args = crate::cli::RunArgs {
        dry_run: args.dry_run,
        limit: args.limit,
        no_env_file: true,
        ..Default::default()
    };
    crate::commands::run::execute(cfg, run_args, None).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::TemplateStoreArgs;

    fn common(store: &str, json: bool) -> TemplateStoreArgs {
        TemplateStoreArgs {
            store: store.to_string(),
            env_file: None,
            no_env_file: true,
            json,
        }
    }

    const BODY: &str = "\
version: 1
name: cli-tpl
params:
  tag: { required: true, description: Output tag }
  page: { type: int, default: 5 }
pipeline:
  source:
    type: csv
    config:
      path: IN_PATH
  sink:
    type: jsonl
    config:
      path: OUT_PATH
";

    /// A registered template needs a *persistent* store to be visible to a
    /// second command, so the CLI round-trip test uses a temp SQLite file.
    /// Without the SQL backend feature the whole test is skipped.
    #[cfg(feature = "serve-history-sqlite")]
    #[tokio::test]
    async fn register_launch_promote_run_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let input = dir.path().join("in.csv");
        std::fs::write(&input, "id,name\n1,alice\n2,bob\n").unwrap();
        let output = dir.path().join("out.jsonl");
        let cfg_path = dir.path().join("tpl.yaml");
        std::fs::write(
            &cfg_path,
            BODY.replace("IN_PATH", &input.display().to_string())
                .replace("OUT_PATH", &output.display().to_string()),
        )
        .unwrap();
        let store = format!("sqlite:{}", dir.path().join("registry.db").display());
        let reg = |launch: bool, tag: Vec<String>| TemplateRegisterArgs {
            config: cfg_path.clone(),
            id: None,
            description: Some("round trip".into()),
            tag,
            launch,
            common: common(&store, false),
        };

        // A plain register is inert: the template is a draft.
        register(reg(false, vec!["dev".into()]))
            .await
            .expect("register v1");
        list(TemplateListArgs {
            common: common(&store, true),
        })
        .await
        .expect("list");

        // An unpinned run refuses, naming the launch command.
        let err = run_template(TemplateRunArgs {
            id: "cli-tpl".into(),
            version: "stable".into(),
            param: vec!["tag=alpha".into()],
            param_env: vec![],
            dry_run: true,
            limit: None,
            common: common(&store, false),
        })
        .await
        .unwrap_err()
        .to_string();
        assert!(err.contains("no launched version"), "{err}");

        // Launching makes it live; then an unpinned run works.
        launch(TemplateLaunchArgs {
            id: "cli-tpl".into(),
            version: "newest".into(),
            common: common(&store, false),
        })
        .await
        .expect("launch");
        run_template(TemplateRunArgs {
            id: "cli-tpl".into(),
            version: "stable".into(),
            param: vec!["tag=alpha".into()],
            param_env: vec![],
            dry_run: false,
            limit: None,
            common: common(&store, false),
        })
        .await
        .expect("run");
        assert_eq!(
            std::fs::read_to_string(&output).unwrap().lines().count(),
            2,
            "the launched version's pipeline wrote both records"
        );

        // Register v2 (a build) — the live version must not move.
        register(reg(false, vec![])).await.expect("register v2");
        show(TemplateShowArgs {
            id: "cli-tpl".into(),
            version: "stable".into(),
            common: common(&store, false),
        })
        .await
        .expect("show");
        promote(TemplatePromoteArgs {
            id: "cli-tpl".into(),
            tag: "pre-prod".into(),
            version: "newest".into(),
            common: common(&store, false),
        })
        .await
        .expect("promote");
        // Launch from the channel, then roll back.
        launch(TemplateLaunchArgs {
            id: "cli-tpl".into(),
            version: "pre-prod".into(),
            common: common(&store, true),
        })
        .await
        .expect("launch from channel");
        rollback(TemplateRollbackArgs {
            id: "cli-tpl".into(),
            common: common(&store, false),
        })
        .await
        .expect("rollback");

        // Derived channels and invented names are refused on promote.
        for tag in ["stable", "previous", "newest", "prd", "latest"] {
            assert!(
                promote(TemplatePromoteArgs {
                    id: "cli-tpl".into(),
                    tag: tag.into(),
                    version: "1".into(),
                    common: common(&store, false),
                })
                .await
                .is_err(),
                "`{tag}` must not be promotable"
            );
        }

        // Deprecate → revive.
        deprecate(TemplateDeprecateArgs {
            id: "cli-tpl".into(),
            reason: Some("superseded".into()),
            undo: false,
            common: common(&store, false),
        })
        .await
        .expect("deprecate");
        deprecate(TemplateDeprecateArgs {
            id: "cli-tpl".into(),
            reason: None,
            undo: true,
            common: common(&store, true),
        })
        .await
        .expect("undeprecate");

        // Delete a single version, then the whole template.
        delete(TemplateDeleteArgs {
            id: "cli-tpl".into(),
            version: Some("newest".into()),
            common: common(&store, false),
        })
        .await
        .expect("delete newest");
        delete(TemplateDeleteArgs {
            id: "cli-tpl".into(),
            version: None,
            common: common(&store, true),
        })
        .await
        .expect("delete all");
        let err = delete(TemplateDeleteArgs {
            id: "cli-tpl".into(),
            version: None,
            common: common(&store, false),
        })
        .await
        .unwrap_err();
        assert!(
            matches!(err, CliError::UnknownPipelineTemplate { .. }),
            "{err:?}"
        );
    }

    #[tokio::test]
    async fn show_and_run_report_an_unknown_template() {
        let c = common("memory", false);
        let store = connect(&c).await.unwrap();
        let err = fetch(&store, "nope", None).await.unwrap_err();
        assert!(
            matches!(err, CliError::UnknownPipelineTemplate { ref id, .. } if id == "nope"),
            "{err:?}"
        );
        // Promoting a channel on a template that does not exist is the same
        // typed error, not a silently-created pointer.
        let err = promote(TemplatePromoteArgs {
            id: "nope".into(),
            tag: "prod".into(),
            version: "newest".into(),
            common: common("memory", false),
        })
        .await
        .unwrap_err();
        assert!(
            matches!(err, CliError::UnknownPipelineTemplate { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn format_is_taken_from_the_extension() {
        assert_eq!(
            format_of(std::path::Path::new("a.yaml")).unwrap(),
            ConfigFormat::Yaml
        );
        assert_eq!(
            format_of(std::path::Path::new("a.YML")).unwrap(),
            ConfigFormat::Yaml
        );
        assert_eq!(
            format_of(std::path::Path::new("a.json")).unwrap(),
            ConfigFormat::Json
        );
        assert!(format_of(std::path::Path::new("a.toml")).is_err());
        assert!(format_of(std::path::Path::new("a")).is_err());
    }

    #[test]
    fn required_param_hint_lists_only_required_params() {
        let mut params = crate::params::ParamsSpec::new();
        params.insert(
            "tag".into(),
            crate::params::ParamSpec {
                kind: crate::params::ParamType::String,
                required: true,
                default: None,
                secret: false,
                description: None,
            },
        );
        params.insert(
            "page".into(),
            crate::params::ParamSpec {
                kind: crate::params::ParamType::Int,
                required: false,
                default: Some(serde_json::json!(5)),
                secret: false,
                description: None,
            },
        );
        let summary = TemplateSummary {
            state: None,
            id: "t".into(),
            version: 1,
            name: None,
            description: None,
            params,
            created_at: chrono::Utc::now(),
            created_by: None,
        };
        let hint = required_param_hint(&summary);
        assert_eq!(hint, " --param tag=<string>");
        // `print_params` renders both without panicking.
        print_params(&summary);
    }

    #[tokio::test]
    async fn register_rejects_a_bad_extension_and_a_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let bad = dir.path().join("cfg.toml");
        std::fs::write(&bad, "x = 1").unwrap();
        let err = register(TemplateRegisterArgs {
            config: bad,
            id: None,
            description: None,
            tag: vec![],
            launch: false,
            common: common("memory", false),
        })
        .await
        .unwrap_err();
        assert!(matches!(err, CliError::UnknownExtension { .. }), "{err:?}");

        let err = register(TemplateRegisterArgs {
            config: dir.path().join("nope.yaml"),
            id: None,
            description: None,
            tag: vec![],
            launch: false,
            common: common("memory", false),
        })
        .await
        .unwrap_err()
        .to_string();
        assert!(err.contains("reading template config"), "{err}");
    }

    #[tokio::test]
    async fn list_reports_an_empty_store() {
        list(TemplateListArgs {
            common: common("memory", false),
        })
        .await
        .expect("empty list is not an error");
    }
}