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 {
134 spec: self,
135 hidden_help_defaults: Default::default(),
136 })
137 }
138
139 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 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 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#[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 #[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 #[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#[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#[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 Uuid,
288 KeyValue,
294}
295
296#[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 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#[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 #[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 #[serde(default, skip_serializing_if = "is_false")]
389 pub sensitive: bool,
390 #[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 #[must_use]
440 pub fn uuid(mut self) -> Self {
441 self.value_type = ArgValueType::Uuid;
442 self
443 }
444
445 #[must_use]
451 pub fn key_value(mut self) -> Self {
452 self.value_type = ArgValueType::KeyValue;
453 self
454 }
455
456 #[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 pub fn sensitive(mut self) -> Self {
562 self.sensitive = true;
563 self
564 }
565
566 #[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 #[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#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
712#[serde(rename_all = "snake_case")]
713pub enum OutputLifecycle {
714 Finite,
715 Stream,
716}
717
718#[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#[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 {}