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