1use super::build::validate_spec;
2use super::*;
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
8pub struct CliSpec {
9 pub schema: String,
10 pub name: String,
11 pub version: String,
12 #[serde(skip_serializing_if = "Option::is_none")]
14 pub display_name: Option<String>,
15 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
28 pub shared_arguments: Vec<ArgSpec>,
29 pub lifecycle_output: OutputSpec,
30 #[serde(default, skip_serializing_if = "Vec::is_empty")]
36 pub exit_codes: Vec<ExitCodeSpec>,
37 pub commands: Vec<CommandSpec>,
38}
39
40#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
42pub struct ExitCodeSpec {
43 pub code: u8,
44 pub meaning: String,
46}
47
48impl CliSpec {
49 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 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 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 #[must_use]
124 pub fn shared_arg(mut self, argument: ArgSpec) -> Self {
125 self.shared_arguments.push(argument);
126 self
127 }
128
129 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 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 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 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#[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 #[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 #[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#[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#[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 Uuid,
285 KeyValue,
291}
292
293#[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 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#[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 #[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 #[serde(default, skip_serializing_if = "is_false")]
386 pub sensitive: bool,
387 #[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 #[must_use]
437 pub fn uuid(mut self) -> Self {
438 self.value_type = ArgValueType::Uuid;
439 self
440 }
441
442 #[must_use]
448 pub fn key_value(mut self) -> Self {
449 self.value_type = ArgValueType::KeyValue;
450 self
451 }
452
453 #[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 pub fn sensitive(mut self) -> Self {
559 self.sensitive = true;
560 self
561 }
562
563 #[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 #[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#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
709#[serde(rename_all = "snake_case")]
710pub enum OutputLifecycle {
711 Finite,
712 Stream,
713}
714
715#[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#[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 {}