Skip to main content

agent_first_data/cli_spec/
spec.rs

1use super::build::validate_spec;
2use super::*;
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6/// Serializable version-one closed-world CLI registry.
7#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
8pub struct CliSpec {
9    pub schema: String,
10    pub name: String,
11    pub version: String,
12    /// Human-facing product name, distinct from the binary identity in `name`.
13    #[serde(skip_serializing_if = "Option::is_none")]
14    pub display_name: Option<String>,
15    /// Opaque build identifier (a git SHA, for example). The core only carries
16    /// it; what it means is the host's business.
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub build: Option<String>,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub about: Option<String>,
21    /// Arguments every command accepts, declared once.
22    ///
23    /// Spliced into each command at build time and added to every combination's
24    /// optional set, so nothing downstream — resolution, help, `--docs` — needs
25    /// to know they were shared. Serialized as their own list so a consumer in
26    /// another language reads the same declaration rather than N copies.
27    #[serde(default, skip_serializing_if = "Vec::is_empty")]
28    pub shared_arguments: Vec<ArgSpec>,
29    pub lifecycle_output: OutputSpec,
30    /// Exit codes this CLI returns beyond the 0/1/2/4 AFDATA defines, rendered
31    /// into the reference's exit-code table. Without this the published
32    /// reference documents only AFDATA's standard codes, so a tool that also returns,
33    /// say, a partial-success code ships a document that contradicts its own
34    /// binary — on exactly the code a caller needs to branch on.
35    #[serde(default, skip_serializing_if = "Vec::is_empty")]
36    pub exit_codes: Vec<ExitCodeSpec>,
37    pub commands: Vec<CommandSpec>,
38}
39
40/// One exit code a CLI defines for itself, beyond AFDATA's 0/1/2/4.
41#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
42pub struct ExitCodeSpec {
43    pub code: u8,
44    /// What the code means to a caller, as one table cell.
45    pub meaning: String,
46}
47
48impl CliSpec {
49    /// Start a `cli-spec-v1` registry.
50    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
51        Self {
52            schema: "cli-spec-v1".to_string(),
53            name: name.into(),
54            version: version.into(),
55            display_name: None,
56            build: None,
57            about: None,
58            shared_arguments: Vec::new(),
59            lifecycle_output: OutputSpec::protocol_finite(
60                ["json", "yaml", "plain"],
61                ["split", "stdout", "stderr"],
62                "json",
63                "split",
64            ),
65            exit_codes: Vec::new(),
66            commands: Vec::new(),
67        }
68    }
69
70    pub fn about(mut self, about: impl Into<String>) -> Self {
71        self.about = nonempty(about.into());
72        self
73    }
74
75    pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
76        self.display_name = nonempty(display_name.into());
77        self
78    }
79
80    /// Record an opaque build identifier. Named `build_id` because `build()`
81    /// already compiles the registry.
82    pub fn build_id(mut self, build: impl Into<String>) -> Self {
83        self.build = nonempty(build.into());
84        self
85    }
86
87    pub fn lifecycle_output(mut self, output: OutputSpec) -> Self {
88        self.lifecycle_output = output;
89        self
90    }
91
92    /// Declare an exit code this CLI returns beyond AFDATA's 0/1/2/4, so the
93    /// rendered reference documents what the binary actually does.
94    pub fn exit_code(mut self, code: u8, meaning: impl Into<String>) -> Self {
95        self.exit_codes.push(ExitCodeSpec {
96            code,
97            meaning: meaning.into(),
98        });
99        self
100    }
101
102    pub fn command(mut self, command: CommandSpec) -> Self {
103        self.commands.push(command);
104        self
105    }
106
107    /// Declare an argument every command accepts, once.
108    ///
109    /// AFDATA already parses `--output`, `--stdout-file` and friends at every
110    /// command; this is the same capability for an argument the application
111    /// owns, so a `--config` needed by six commands is written once instead of
112    /// six times and cannot drift between them.
113    ///
114    /// It does **not** change where the argument may appear. The command path
115    /// is still matched against the leading tokens of argv, so `tool --config x
116    /// sub` remains an error and `tool sub --config x` is the accepted form.
117    /// This is only about declaration, not position — a caller migrating from a
118    /// parser with interleaved global flags has to move them after the path.
119    ///
120    /// A command with no combinations is skipped: it exists to carry help for
121    /// its children, accepts nothing itself, and would otherwise fail the
122    /// build for declaring an argument no combination covers.
123    #[must_use]
124    pub fn shared_arg(mut self, argument: ArgSpec) -> Self {
125        self.shared_arguments.push(argument);
126        self
127    }
128
129    /// Validate and compile the registry.
130    pub fn build(mut self) -> Result<BuiltCliSpec, CliSpecError> {
131        self.splice_shared_arguments()?;
132        validate_spec(&self)?;
133        Ok(BuiltCliSpec { spec: self })
134    }
135
136    /// Copy the shared arguments into every command, and into every
137    /// combination's optional set.
138    ///
139    /// Done before validation so a shared argument is held to exactly the same
140    /// rules as a declared one — reserved names, canonical spelling, and the
141    /// id/flag agreement all report against it normally.
142    fn splice_shared_arguments(&mut self) -> Result<(), CliSpecError> {
143        if self.shared_arguments.is_empty() {
144            return Ok(());
145        }
146        for shared in &self.shared_arguments {
147            for command in &self.commands {
148                if command
149                    .arguments
150                    .iter()
151                    .any(|argument| argument.argument_id == shared.argument_id)
152                {
153                    return Err(CliSpecError::new(
154                        "shared_argument_redeclared",
155                        format!(
156                            "argument `{}` is shared by every command, so `{}` must not declare \
157                             it again",
158                            shared.argument_id,
159                            if command.command_path.is_empty() {
160                                "the root command".to_string()
161                            } else {
162                                command.command_path.join(" ")
163                            }
164                        ),
165                    ));
166                }
167            }
168        }
169        let shared = self.shared_arguments.clone();
170        for command in &mut self.commands {
171            // A combination-less command is a help-only path node (`tool
172            // analysis --help` listing its children). It accepts no arguments
173            // of its own, so splicing one in would leave an argument no
174            // combination covers and fail validation.
175            if command.combinations.is_empty() {
176                continue;
177            }
178            for argument in &shared {
179                command.arguments.push(argument.clone());
180                for combination in &mut command.combinations {
181                    // Shared arguments are never required and never fixed: a
182                    // combination that needs one must declare its own.
183                    if !combination.optional.contains(&argument.argument_id) {
184                        combination.optional.push(argument.argument_id.clone());
185                    }
186                }
187            }
188        }
189        Ok(())
190    }
191}
192
193/// One exact command path in a CLI registry.
194#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
195pub struct CommandSpec {
196    pub command_path: Vec<String>,
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub about: Option<String>,
199    /// Prose for the generated reference, after this command's argument table.
200    ///
201    /// An argument's `about` is one table cell and has to stay one — but some
202    /// commands need a paragraph that belongs to no single argument: where a
203    /// default is read from, what two options mean together, what the result
204    /// reports back. Without somewhere to put it, that paragraph ends up
205    /// hand-written into a file whose own header says "generated, do not edit
206    /// by hand", where the next regeneration silently deletes it.
207    ///
208    /// Reference only. `--help` stays the machine-readable shape of a command;
209    /// this is for the document a person reads.
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub reference_note: Option<String>,
212    pub arguments: Vec<ArgSpec>,
213    pub combinations: Vec<Combination>,
214}
215
216impl CommandSpec {
217    pub fn root() -> Self {
218        Self::new(std::iter::empty::<String>())
219    }
220
221    pub fn new<I, S>(command_path: I) -> Self
222    where
223        I: IntoIterator<Item = S>,
224        S: Into<String>,
225    {
226        Self {
227            command_path: command_path.into_iter().map(Into::into).collect(),
228            about: None,
229            reference_note: None,
230            arguments: Vec::new(),
231            combinations: Vec::new(),
232        }
233    }
234
235    pub fn about(mut self, about: impl Into<String>) -> Self {
236        self.about = nonempty(about.into());
237        self
238    }
239
240    /// Prose for the generated reference, after this command's argument table.
241    #[must_use]
242    pub fn reference_note(mut self, note: impl Into<String>) -> Self {
243        self.reference_note = nonempty(note.into());
244        self
245    }
246
247    pub fn arg(mut self, argument: ArgSpec) -> Self {
248        self.arguments.push(argument);
249        self
250    }
251
252    pub fn combination(mut self, combination: Combination) -> Self {
253        self.combinations.push(combination);
254        self
255    }
256}
257
258/// An argument's exact command-local spelling.
259#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
260#[serde(tag = "kind", rename_all = "snake_case")]
261pub enum ArgSyntax {
262    Long { name: String },
263    Positional { index: usize },
264}
265
266/// Closed portable value type used by CLI specs and resolved invocations.
267#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
268#[serde(rename_all = "snake_case")]
269pub enum ArgValueType {
270    Flag,
271    String,
272    I64,
273    FiniteF64,
274    Enum,
275    Json,
276    /// A canonical RFC 4122 UUID, kept as its string form.
277    ///
278    /// Declarative on purpose: the registry serializes to `cli-spec-v1`, so a
279    /// value type has to be something another language can implement from the
280    /// spec alone. A host-supplied parser could not survive that trip; this
281    /// can. The value stays a `String` so the core takes no UUID dependency —
282    /// what it buys is that a malformed one is a *usage* error, rejected before
283    /// the command runs, instead of a domain failure the handler has to invent.
284    Uuid,
285    /// A `KEY=VALUE` pair, split at the first `=`; the key must not be empty.
286    ///
287    /// The value may itself contain `=` and may be empty. Kept as its source
288    /// text and split when read, so the pair has one spelling everywhere a
289    /// value is serialized.
290    KeyValue,
291}
292
293/// A typed value produced by a built CLI registry.
294///
295/// `Json` deliberately holds the argument's raw source text rather than a
296/// parsed `serde_json::Value`. AFDATA turns on `serde_json/arbitrary_precision`
297/// and that feature unifies across a whole binary, so a parsed value's number
298/// semantics would depend on which other crates happen to be linked in. The
299/// text is validated as one JSON value at parse time; deciding what its numbers
300/// mean is the caller's choice.
301#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
302#[serde(untagged)]
303pub enum CliValue {
304    Bool(bool),
305    String(String),
306    I64(i64),
307    FiniteF64(f64),
308    Json(String),
309    List(Vec<CliValue>),
310}
311
312impl CliValue {
313    pub fn as_bool(&self) -> Option<bool> {
314        match self {
315            Self::Bool(value) => Some(*value),
316            _ => None,
317        }
318    }
319
320    pub fn as_str(&self) -> Option<&str> {
321        match self {
322            Self::String(value) => Some(value),
323            _ => None,
324        }
325    }
326
327    pub fn as_i64(&self) -> Option<i64> {
328        match self {
329            Self::I64(value) => Some(*value),
330            _ => None,
331        }
332    }
333
334    pub fn as_f64(&self) -> Option<f64> {
335        match self {
336            Self::FiniteF64(value) => Some(*value),
337            _ => None,
338        }
339    }
340
341    /// The raw, still-unparsed JSON source text of a `json` argument.
342    pub fn as_json_str(&self) -> Option<&str> {
343        match self {
344            Self::Json(value) => Some(value),
345            _ => None,
346        }
347    }
348
349    pub fn as_list(&self) -> Option<&[CliValue]> {
350        match self {
351            Self::List(values) => Some(values),
352            _ => None,
353        }
354    }
355}
356
357/// One command-local application argument.
358#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
359pub struct ArgSpec {
360    pub argument_id: String,
361    pub syntax: ArgSyntax,
362    pub value_type: ArgValueType,
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub value_name: Option<String>,
365    #[serde(default, skip_serializing_if = "Vec::is_empty")]
366    pub enum_values: Vec<String>,
367    /// Inclusive bounds for an `I64` argument.
368    ///
369    /// Lets a registry say `1..=1000` without a host-supplied parser, so a
370    /// count that must fit an `i32`, a `usize`, or a `NonZero` is rejected at
371    /// exit 2 with the other usage errors rather than checked again inside the
372    /// handler — where the only honest report left is a domain failure.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub range: Option<[i64; 2]>,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    pub default: Option<CliValue>,
377    #[serde(default, skip_serializing_if = "is_false")]
378    pub repeatable: bool,
379    /// This argument's value must never be echoed back.
380    ///
381    /// The core only consumes the bit: it suppresses help defaults, keeps the
382    /// value out of rendered templates, and rejects a serializable default.
383    /// Which arguments deserve it is a host convention — `crate::cli_afdata`
384    /// derives it from AFDATA's `_secret` suffix.
385    #[serde(default, skip_serializing_if = "is_false")]
386    pub sensitive: bool,
387    /// The sources this argument accepts beside a literal value.
388    ///
389    /// Declared rather than assumed: a source turns an argument into a reader
390    /// of files and environment variables, which is right for a credential and
391    /// wrong for most everything else. The core validates that a value names
392    /// only a scheme in this set, and renders the syntax into help so no host
393    /// repeats it in an `about` string. Reading happens in the host, when it
394    /// chooses — see [`crate::value_source`].
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub sources: Option<SourceSet>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub about: Option<String>,
399}
400
401impl ArgSpec {
402    pub fn flag(long: impl Into<String>) -> Self {
403        Self::long(long, ArgValueType::Flag, None::<String>)
404    }
405
406    pub fn option(long: impl Into<String>, value_name: impl Into<String>) -> Self {
407        Self::long(long, ArgValueType::String, Some(value_name.into()))
408    }
409
410    pub fn option_i64(long: impl Into<String>, value_name: impl Into<String>) -> Self {
411        Self::long(long, ArgValueType::I64, Some(value_name.into()))
412    }
413
414    pub fn option_f64(long: impl Into<String>, value_name: impl Into<String>) -> Self {
415        Self::long(long, ArgValueType::FiniteF64, Some(value_name.into()))
416    }
417
418    pub fn option_json(long: impl Into<String>, value_name: impl Into<String>) -> Self {
419        Self::long(long, ArgValueType::Json, Some(value_name.into()))
420    }
421
422    pub fn option_enum<I, S>(long: impl Into<String>, values: I) -> Self
423    where
424        I: IntoIterator<Item = S>,
425        S: Into<String>,
426    {
427        let mut spec = Self::long(long, ArgValueType::Enum, Some("VALUE".to_string()));
428        spec.enum_values = values.into_iter().map(Into::into).collect();
429        spec
430    }
431
432    /// Read this argument as a canonical RFC 4122 UUID.
433    ///
434    /// The resolved value is still a `CliValue::String`; what changes is that a
435    /// malformed one is rejected as a usage error before the command runs.
436    #[must_use]
437    pub fn uuid(mut self) -> Self {
438        self.value_type = ArgValueType::Uuid;
439        self
440    }
441
442    /// Read this argument as a `KEY=VALUE` pair, split at the first `=`.
443    ///
444    /// An empty key or a missing `=` is a usage error, rejected before the
445    /// command runs. Read it with
446    /// [`ResolvedInvocation::key_value`](crate::cli_spec::ResolvedInvocation::key_value).
447    #[must_use]
448    pub fn key_value(mut self) -> Self {
449        self.value_type = ArgValueType::KeyValue;
450        self
451    }
452
453    /// Constrain an `I64` argument to an inclusive range.
454    ///
455    /// Use it for a count that must fit a narrower integer than `i64` — the
456    /// check then reports as a usage error, beside the other argument
457    /// failures, rather than as a domain failure from inside the handler.
458    #[must_use]
459    pub fn range(mut self, minimum: i64, maximum: i64) -> Self {
460        self.value_type = ArgValueType::I64;
461        self.range = Some([minimum, maximum]);
462        self
463    }
464
465    pub fn positional(
466        argument_id: impl Into<String>,
467        index: usize,
468        value_name: impl Into<String>,
469    ) -> Self {
470        Self {
471            argument_id: argument_id.into(),
472            syntax: ArgSyntax::Positional { index },
473            value_type: ArgValueType::String,
474            value_name: nonempty(value_name.into()),
475            enum_values: Vec::new(),
476            range: None,
477            default: None,
478            repeatable: false,
479            sensitive: false,
480            sources: None,
481            about: None,
482        }
483    }
484
485    pub fn positional_json(
486        argument_id: impl Into<String>,
487        index: usize,
488        value_name: impl Into<String>,
489    ) -> Self {
490        Self {
491            value_type: ArgValueType::Json,
492            ..Self::positional(argument_id, index, value_name)
493        }
494    }
495
496    pub fn positional_enum<I, S>(
497        argument_id: impl Into<String>,
498        index: usize,
499        value_name: impl Into<String>,
500        values: I,
501    ) -> Self
502    where
503        I: IntoIterator<Item = S>,
504        S: Into<String>,
505    {
506        let mut spec = Self {
507            value_type: ArgValueType::Enum,
508            ..Self::positional(argument_id, index, value_name)
509        };
510        spec.enum_values = values.into_iter().map(Into::into).collect();
511        spec
512    }
513
514    fn long(long: impl Into<String>, value_type: ArgValueType, value_name: Option<String>) -> Self {
515        let long = long.into();
516        let argument_id = long.trim_prefix("--").replace('-', "_");
517        Self {
518            argument_id,
519            syntax: ArgSyntax::Long { name: long },
520            value_type,
521            value_name: value_name.and_then(nonempty),
522            enum_values: Vec::new(),
523            range: None,
524            default: None,
525            repeatable: false,
526            sensitive: false,
527            sources: None,
528            about: None,
529        }
530    }
531
532    pub fn value_name(mut self, value_name: impl Into<String>) -> Self {
533        self.value_name = nonempty(value_name.into());
534        self
535    }
536
537    pub fn default(mut self, value: impl Into<String>) -> Self {
538        self.default = Some(CliValue::String(value.into()));
539        self
540    }
541
542    pub fn default_i64(mut self, value: i64) -> Self {
543        self.default = Some(CliValue::I64(value));
544        self
545    }
546
547    pub fn default_f64(mut self, value: f64) -> Self {
548        self.default = Some(CliValue::FiniteF64(value));
549        self
550    }
551
552    pub fn repeatable(mut self) -> Self {
553        self.repeatable = true;
554        self
555    }
556
557    /// Mark this argument's value as one that must never be echoed back.
558    pub fn sensitive(mut self) -> Self {
559        self.sensitive = true;
560        self
561    }
562
563    /// Accept the value indirectly, from any source in `sources`.
564    ///
565    /// The help text follows from the set, so `about` should say what the value
566    /// *is* and leave the syntax to this. Reading is the host's, at the moment
567    /// it chooses: [`crate::cli_spec::SourceSet::parse`] on the resolved
568    /// string, then `read` or `read_secret`.
569    #[must_use]
570    pub fn sources(mut self, sources: SourceSet) -> Self {
571        self.sources = Some(sources);
572        self
573    }
574
575    pub fn about(mut self, about: impl Into<String>) -> Self {
576        self.about = nonempty(about.into());
577        self
578    }
579
580    /// What a reader is told about this argument: what the value means, plus
581    /// how it may be sourced.
582    ///
583    /// Hosts declare those separately — `about` says what the value *is*, the
584    /// source set says where it may come from — and every rendering path joins
585    /// them here. That is the whole reason the set is declared rather than
586    /// written into prose: a single flag's syntax is otherwise repeated across
587    /// every row of a generated reference that mentions it — dozens, for a
588    /// widely-used one — each a place to forget when a source is added.
589    #[must_use]
590    pub fn rendered_about(&self) -> Option<String> {
591        match (&self.about, &self.sources) {
592            (Some(about), Some(sources)) => Some(format!("{about} ({})", sources.syntax_summary())),
593            (Some(about), None) => Some(about.clone()),
594            (None, Some(sources)) => Some(sources.syntax_summary()),
595            (None, None) => None,
596        }
597    }
598}
599
600/// A finite fixed enum constraint.
601#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
602#[serde(untagged)]
603pub enum FixedValue {
604    Value(String),
605    OneOf { one_of: Vec<String> },
606}
607
608impl FixedValue {
609    pub(super) fn values(&self) -> &[String] {
610        match self {
611            Self::Value(value) => std::slice::from_ref(value),
612            Self::OneOf { one_of } => one_of,
613        }
614    }
615}
616
617/// One named legal application invocation shape.
618#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
619pub struct Combination {
620    pub combination_id: String,
621    pub action_id: String,
622    #[serde(skip_serializing_if = "Option::is_none")]
623    pub about: Option<String>,
624    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
625    pub fixed: BTreeMap<String, FixedValue>,
626    #[serde(default, skip_serializing_if = "Vec::is_empty")]
627    pub required: Vec<String>,
628    #[serde(default, skip_serializing_if = "Vec::is_empty")]
629    pub optional: Vec<String>,
630    pub output: OutputSpec,
631}
632
633impl Combination {
634    pub fn new(combination_id: impl Into<String>) -> Self {
635        Self {
636            combination_id: combination_id.into(),
637            action_id: String::new(),
638            about: None,
639            fixed: BTreeMap::new(),
640            required: Vec::new(),
641            optional: Vec::new(),
642            output: OutputSpec::protocol_finite(
643                ["json", "yaml", "plain"],
644                ["split", "stdout", "stderr"],
645                "json",
646                "split",
647            ),
648        }
649    }
650
651    pub fn action(mut self, action_id: impl Into<String>) -> Self {
652        self.action_id = action_id.into();
653        self
654    }
655
656    pub fn about(mut self, about: impl Into<String>) -> Self {
657        self.about = nonempty(about.into());
658        self
659    }
660
661    pub fn fixed(mut self, argument_id: impl Into<String>, value: impl Into<String>) -> Self {
662        self.fixed
663            .insert(argument_id.into(), FixedValue::Value(value.into()));
664        self
665    }
666
667    pub fn fixed_one_of<I, S>(mut self, argument_id: impl Into<String>, values: I) -> Self
668    where
669        I: IntoIterator<Item = S>,
670        S: Into<String>,
671    {
672        self.fixed.insert(
673            argument_id.into(),
674            FixedValue::OneOf {
675                one_of: values.into_iter().map(Into::into).collect(),
676            },
677        );
678        self
679    }
680
681    pub fn required<I, S>(mut self, argument_ids: I) -> Self
682    where
683        I: IntoIterator<Item = S>,
684        S: Into<String>,
685    {
686        self.required
687            .extend(argument_ids.into_iter().map(Into::into));
688        self
689    }
690
691    pub fn optional<I, S>(mut self, argument_ids: I) -> Self
692    where
693        I: IntoIterator<Item = S>,
694        S: Into<String>,
695    {
696        self.optional
697            .extend(argument_ids.into_iter().map(Into::into));
698        self
699    }
700
701    pub fn output(mut self, output: OutputSpec) -> Self {
702        self.output = output;
703        self
704    }
705}
706
707/// Protocol output lifecycle.
708#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
709#[serde(rename_all = "snake_case")]
710pub enum OutputLifecycle {
711    Finite,
712    Stream,
713}
714
715/// Closed output contract for one combination.
716#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
717#[serde(tag = "kind", rename_all = "snake_case")]
718pub enum OutputSpec {
719    Raw {
720        #[serde(default)]
721        file_sinks: Vec<String>,
722    },
723    Protocol {
724        lifecycle: OutputLifecycle,
725        formats: Vec<String>,
726        destinations: Vec<String>,
727        default_format: String,
728        default_destination: String,
729        #[serde(default)]
730        file_sinks: Vec<String>,
731    },
732}
733
734impl OutputSpec {
735    pub fn raw() -> Self {
736        Self::Raw {
737            file_sinks: Vec::new(),
738        }
739    }
740
741    pub fn protocol_finite<FI, FS, DI, DS>(
742        formats: FI,
743        destinations: DI,
744        default_format: impl Into<String>,
745        default_destination: impl Into<String>,
746    ) -> Self
747    where
748        FI: IntoIterator<Item = FS>,
749        FS: Into<String>,
750        DI: IntoIterator<Item = DS>,
751        DS: Into<String>,
752    {
753        Self::Protocol {
754            lifecycle: OutputLifecycle::Finite,
755            formats: formats.into_iter().map(Into::into).collect(),
756            destinations: destinations.into_iter().map(Into::into).collect(),
757            default_format: default_format.into(),
758            default_destination: default_destination.into(),
759            file_sinks: Vec::new(),
760        }
761    }
762
763    pub fn protocol_stream<FI, FS, DI, DS>(
764        formats: FI,
765        destinations: DI,
766        default_format: impl Into<String>,
767        default_destination: impl Into<String>,
768    ) -> Self
769    where
770        FI: IntoIterator<Item = FS>,
771        FS: Into<String>,
772        DI: IntoIterator<Item = DS>,
773        DS: Into<String>,
774    {
775        Self::Protocol {
776            lifecycle: OutputLifecycle::Stream,
777            formats: formats.into_iter().map(Into::into).collect(),
778            destinations: destinations.into_iter().map(Into::into).collect(),
779            default_format: default_format.into(),
780            default_destination: default_destination.into(),
781            file_sinks: Vec::new(),
782        }
783    }
784
785    pub fn file_sinks<I, S>(mut self, sinks: I) -> Self
786    where
787        I: IntoIterator<Item = S>,
788        S: Into<String>,
789    {
790        let values = sinks.into_iter().map(Into::into).collect();
791        match &mut self {
792            Self::Raw { file_sinks } | Self::Protocol { file_sinks, .. } => {
793                *file_sinks = values;
794            }
795        }
796        self
797    }
798
799    pub(super) fn file_sinks_ref(&self) -> &[String] {
800        match self {
801            Self::Raw { file_sinks } | Self::Protocol { file_sinks, .. } => file_sinks,
802        }
803    }
804}
805
806/// Stable build-time registry error.
807#[derive(Clone, Debug, PartialEq, Eq)]
808pub struct CliSpecError {
809    pub rule: &'static str,
810    pub message: String,
811}
812
813impl CliSpecError {
814    pub(super) fn new(rule: &'static str, message: impl Into<String>) -> Self {
815        Self {
816            rule,
817            message: message.into(),
818        }
819    }
820}
821
822impl std::fmt::Display for CliSpecError {
823    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
824        write!(f, "{}: {}", self.rule, self.message)
825    }
826}
827
828impl std::error::Error for CliSpecError {}