1use super::error::{
2 InvocationReadError, InvocationReadProblem, duplicate_error, invalid_value, missing_value,
3};
4use super::help::combination_usage;
5use super::*;
6use std::collections::{BTreeMap, BTreeSet};
7use std::ffi::OsString;
8use std::path::{Path, PathBuf};
9
10#[derive(Clone, Debug, PartialEq)]
12pub struct BuiltCliSpec {
13 pub(super) spec: CliSpec,
14}
15
16impl BuiltCliSpec {
17 pub fn spec(&self) -> &CliSpec {
18 &self.spec
19 }
20
21 pub fn resolve_from<I, S>(&self, args: I) -> Result<CliOutcome, CliError>
22 where
23 I: IntoIterator<Item = S>,
24 S: Into<OsString>,
25 {
26 let raw: Vec<OsString> = args.into_iter().map(Into::into).collect();
27 self.resolve_os(&raw)
28 }
29
30 pub fn synthetic_invocations(&self) -> Vec<SyntheticInvocation> {
34 let mut fixtures = Vec::new();
35 for command in &self.spec.commands {
36 for combination in &command.combinations {
37 let mut variants = vec![vec![self.spec.name.clone()]];
38 for part in &command.command_path {
39 for argv in &mut variants {
40 argv.push(part.clone());
41 }
42 }
43 for argument in &command.arguments {
44 let values: Vec<String> =
45 if let Some(fixed) = combination.fixed.get(&argument.argument_id) {
46 fixed.values().to_vec()
47 } else if combination
48 .required
49 .iter()
50 .any(|id| id == &argument.argument_id)
51 {
52 vec![synthetic_value(argument)]
53 } else {
54 continue;
55 };
56 let mut expanded = Vec::new();
57 for argv in variants {
58 for value in &values {
59 let mut candidate = argv.clone();
60 append_synthetic_argument(&mut candidate, argument, value);
61 expanded.push(candidate);
62 }
63 }
64 variants = expanded;
65 }
66 fixtures.extend(variants.into_iter().map(|argv| SyntheticInvocation {
67 command_path: command.command_path.clone(),
68 combination_id: combination.combination_id.clone(),
69 argv,
70 }));
71 }
72 }
73 fixtures
74 }
75
76 pub fn help(&self, command_path: &[String]) -> Option<CliHelpV2> {
83 let command = self
84 .spec
85 .commands
86 .iter()
87 .find(|candidate| candidate.command_path == command_path)?;
88 Some(self.help_model(command))
89 }
90
91 pub fn bind_actions<R, I, S>(&self, handlers: I) -> Result<BoundCliSpec<R>, CliSpecError>
93 where
94 I: IntoIterator<Item = (S, fn(&ResolvedInvocation) -> R)>,
95 S: Into<String>,
96 {
97 let expected: BTreeSet<&str> = self
98 .spec
99 .commands
100 .iter()
101 .flat_map(|command| command.combinations.iter())
102 .map(|combination| combination.action_id.as_str())
103 .collect();
104 let mut actual = BTreeMap::new();
105 for (action_id, handler) in handlers {
106 let action_id = action_id.into();
107 if actual.insert(action_id.clone(), handler).is_some() {
108 return Err(CliSpecError::new(
109 "duplicate_action_handler",
110 format!("action `{action_id}` has more than one handler"),
111 ));
112 }
113 }
114 let actual_ids: BTreeSet<&str> = actual.keys().map(String::as_str).collect();
115 if expected != actual_ids {
116 let missing: Vec<&str> = expected.difference(&actual_ids).copied().collect();
117 let extra: Vec<&str> = actual_ids.difference(&expected).copied().collect();
118 return Err(CliSpecError::new(
119 "action_handler_coverage",
120 format!("handler coverage mismatch; missing={missing:?}, extra={extra:?}"),
121 ));
122 }
123 Ok(BoundCliSpec {
124 cli: self.clone(),
125 handlers: actual,
126 })
127 }
128
129 fn resolve_os(&self, raw: &[OsString]) -> Result<CliOutcome, CliError> {
130 let mut utf8 = Vec::with_capacity(raw.len());
131 for token in raw {
132 let Some(token) = token.to_str() else {
133 return Err(CliError::new(
134 CliErrorRule::InvalidUtf8,
135 self.spec.name.clone(),
136 "argv contains a token that is not valid UTF-8",
137 ));
138 };
139 utf8.push(token.to_string());
140 }
141 let argv = if utf8.is_empty() { &[][..] } else { &utf8[1..] };
142 let (command, consumed) = self.select_command(argv)?;
143 let command_path = self.display_command_path(command);
144 let parsed = tokenize(
145 command,
146 &argv[consumed..],
147 &command_path,
148 &self.spec.commands,
149 )?;
150
151 if parsed.control_count() > 0 {
152 if parsed.control_count() != 1 || !parsed.application_values.is_empty() {
153 return Err(CliError::unregistered(command_path));
154 }
155 if parsed.docs {
160 if !command.command_path.is_empty() {
165 return Err(CliError::unregistered(command_path));
166 }
167 let contract = OutputSpec::raw()
168 .file_sinks(self.spec.lifecycle_output.file_sinks_ref().to_vec());
169 let output = resolve_output(&contract, &parsed.output, &command_path)?;
170 return Ok(CliOutcome::Docs(ResolvedDocs {
171 output,
172 registry: self.clone(),
173 }));
174 }
175 let output =
176 resolve_output(&self.spec.lifecycle_output, &parsed.output, &command_path)?;
177 if parsed.help {
178 return Ok(CliOutcome::Help(ResolvedHelp {
179 model: self.help_model(command),
180 output,
181 }));
182 }
183 if parsed.version {
184 if !command.command_path.is_empty() {
185 return Err(CliError::unregistered(command_path));
186 }
187 return Ok(CliOutcome::Version(ResolvedVersion {
188 name: self.spec.name.clone(),
189 version: self.spec.version.clone(),
190 display_name: self.spec.display_name.clone(),
191 build: self.spec.build.clone(),
192 output,
193 }));
194 }
195 }
196
197 let matching: Vec<&Combination> = command
198 .combinations
199 .iter()
200 .filter(|combination| combination_matches(command, combination, &parsed))
201 .collect();
202 let Some(combination) = matching.first().copied() else {
203 return Err(CliError::unregistered(command_path));
204 };
205 if matching.len() != 1 {
206 return Err(CliError::new(
207 CliErrorRule::UnregisteredCombination,
208 command_path,
209 "arguments match more than one registered CLI combination",
210 ));
211 }
212 let output = resolve_output(&combination.output, &parsed.output, &command_path)?;
213 let projected = project_values(command, combination, &parsed);
214 Ok(CliOutcome::Run(ResolvedInvocation {
215 command_path: command.command_path.clone(),
216 action_id: combination.action_id.clone(),
217 combination_id: combination.combination_id.clone(),
218 values: projected.values,
219 sources: projected.sources,
220 declared: projected.declared,
221 explicit_argument_ids: parsed.explicit_application_ids,
222 output,
223 strict_reads: false,
224 }))
225 }
226
227 fn select_command<'a>(&'a self, argv: &[String]) -> Result<(&'a CommandSpec, usize), CliError> {
228 let mut commands: Vec<&CommandSpec> = self.spec.commands.iter().collect();
229 commands.sort_by_key(|command| std::cmp::Reverse(command.command_path.len()));
230 if let Some(command) = commands.iter().copied().find(|command| {
231 command.command_path.len() <= argv.len()
232 && command
233 .command_path
234 .iter()
235 .zip(argv)
236 .all(|(expected, actual)| expected == actual)
237 }) {
238 let remaining = &argv[command.command_path.len()..];
239 let has_children = self.spec.commands.iter().any(|candidate| {
240 candidate.command_path.len() > command.command_path.len()
241 && candidate.command_path.starts_with(&command.command_path)
242 });
243 if remaining
244 .first()
245 .is_some_and(|token| !token.starts_with('-'))
246 && has_children
247 {
248 return Err(CliError::new(
249 CliErrorRule::UnknownCommand,
250 self.display_command_path(command),
251 "unknown command",
252 ));
253 }
254 return Ok((command, command.command_path.len()));
255 }
256 Err(CliError::new(
257 CliErrorRule::UnknownCommand,
258 self.spec.name.clone(),
259 "unknown command",
260 ))
261 }
262
263 fn display_command_path(&self, command: &CommandSpec) -> String {
264 std::iter::once(self.spec.name.as_str())
265 .chain(command.command_path.iter().map(String::as_str))
266 .collect::<Vec<_>>()
267 .join(" ")
268 }
269
270 fn child_help_commands(&self, command: &CommandSpec) -> Vec<String> {
271 let mut children: Vec<Vec<String>> = self
272 .spec
273 .commands
274 .iter()
275 .filter(|candidate| {
276 candidate.command_path.len() == command.command_path.len() + 1
277 && candidate.command_path.starts_with(&command.command_path)
278 })
279 .map(|candidate| candidate.command_path.clone())
280 .collect();
281 children.sort();
282 children
283 .into_iter()
284 .map(|path| format!("{} {} --help", self.spec.name, path.join(" ")))
285 .collect()
286 }
287
288 fn help_model(&self, command: &CommandSpec) -> CliHelpV2 {
289 let command_path = self.display_command_path(command);
290 let mut shapes = Vec::new();
291 let mut notes = BTreeMap::new();
292 let mut defaults = BTreeMap::new();
293 for combination in &command.combinations {
294 let (usage, shape_notes, shape_defaults) =
295 combination_usage(command, combination, &command_path, true);
296 shapes.push(CliShape {
297 id: combination.combination_id.clone(),
298 about: if command.combinations.len() == 1 {
301 None
302 } else {
303 combination.about.clone()
304 },
305 usage,
306 });
307 notes.extend(shape_notes);
311 defaults.extend(shape_defaults);
312 }
313 CliHelpV2 {
314 schema: "cli-help-v2".to_string(),
315 command_path,
316 about: command.about.clone().or_else(|| {
320 command
321 .command_path
322 .is_empty()
323 .then(|| self.spec.about.clone())
324 .flatten()
325 }),
326 shapes,
327 subcommands: self.child_help_commands(command),
328 notes,
329 defaults,
330 }
331 }
332}
333
334#[derive(Clone, Debug, PartialEq, Eq)]
336pub struct SyntheticInvocation {
337 pub command_path: Vec<String>,
338 pub combination_id: String,
339 pub argv: Vec<String>,
340}
341
342pub struct BoundCliSpec<R> {
344 cli: BuiltCliSpec,
345 handlers: BTreeMap<String, fn(&ResolvedInvocation) -> R>,
346}
347
348impl<R> BoundCliSpec<R> {
349 pub fn resolve_from<I, S>(&self, args: I) -> Result<BoundOutcome<R>, CliError>
359 where
360 I: IntoIterator<Item = S>,
361 S: Into<OsString>,
362 {
363 Ok(match self.cli.resolve_from(args)? {
364 CliOutcome::Run(invocation) => BoundOutcome::Run(self.bind(invocation)),
365 CliOutcome::Help(help) => BoundOutcome::Help(help),
366 CliOutcome::Version(version) => BoundOutcome::Version(version),
367 CliOutcome::Docs(docs) => BoundOutcome::Docs(docs),
368 })
369 }
370
371 #[allow(clippy::panic)]
406 pub fn call_every_combination(&self) -> Vec<(String, R)> {
407 let mut results = Vec::new();
408 for fixture in self.cli.synthetic_invocations() {
409 let outcome = self.cli.resolve_from(fixture.argv.clone());
413 let Ok(CliOutcome::Run(mut invocation)) = outcome else {
414 panic!(
415 "combination `{}` generated argv {:?}, which does not resolve to a run",
416 fixture.combination_id, fixture.argv
417 );
418 };
419 invocation.strict_reads = true;
420 let combination = invocation.combination_id.clone();
421 results.push((combination, self.bind(invocation).run()));
422 }
423 assert!(
424 !results.is_empty(),
425 "no combination was called; a registry with no runnable combination cannot be verified"
426 );
427 results
428 }
429
430 fn bind(&self, invocation: ResolvedInvocation) -> BoundInvocation<R> {
431 #[allow(clippy::expect_used)]
436 let handler = *self
437 .handlers
438 .get(invocation.action_id())
439 .expect("bind_actions guarantees one handler per action id");
440 BoundInvocation {
441 invocation,
442 handler,
443 }
444 }
445}
446
447pub enum BoundOutcome<R> {
449 Run(BoundInvocation<R>),
450 Help(ResolvedHelp),
451 Version(ResolvedVersion),
452 Docs(ResolvedDocs),
453}
454
455impl<R> BoundOutcome<R> {
456 pub fn output_plan(&self) -> &OutputPlan {
458 match self {
459 Self::Run(invocation) => invocation.output_plan(),
460 Self::Docs(docs) => docs.output_plan(),
461 Self::Help(help) => help.output_plan(),
462 Self::Version(version) => version.output_plan(),
463 }
464 }
465}
466
467impl<R> std::fmt::Debug for BoundOutcome<R> {
468 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
472 match self {
473 Self::Run(invocation) => formatter.debug_tuple("Run").field(invocation).finish(),
474 Self::Help(help) => formatter.debug_tuple("Help").field(help).finish(),
475 Self::Version(version) => formatter.debug_tuple("Version").field(version).finish(),
476 Self::Docs(docs) => formatter.debug_tuple("Docs").field(docs).finish(),
477 }
478 }
479}
480
481pub struct BoundInvocation<R> {
486 invocation: ResolvedInvocation,
487 handler: fn(&ResolvedInvocation) -> R,
488}
489
490impl<R> BoundInvocation<R> {
491 pub fn output_plan(&self) -> &OutputPlan {
494 self.invocation.output_plan()
495 }
496
497 pub fn invocation(&self) -> &ResolvedInvocation {
499 &self.invocation
500 }
501
502 pub fn run(self) -> R {
504 (self.handler)(&self.invocation)
505 }
506
507 pub fn run_with_invocation(self) -> (R, ResolvedInvocation) {
514 let result = (self.handler)(&self.invocation);
515 (result, self.invocation)
516 }
517}
518
519impl<R> std::fmt::Debug for BoundInvocation<R> {
520 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521 formatter
522 .debug_struct("BoundInvocation")
523 .field("invocation", &self.invocation)
524 .finish_non_exhaustive()
525 }
526}
527
528#[derive(Clone, Debug, PartialEq)]
530pub enum CliOutcome {
531 Run(ResolvedInvocation),
532 Help(ResolvedHelp),
533 Version(ResolvedVersion),
534 Docs(ResolvedDocs),
535}
536
537#[derive(Clone, Debug, PartialEq)]
547pub struct ResolvedInvocation {
548 pub(super) command_path: Vec<String>,
549 pub(super) action_id: String,
550 pub(super) combination_id: String,
551 pub(super) values: BTreeMap<String, InvocationValue>,
552 pub(super) sources: BTreeMap<String, Vec<ValueSource>>,
553 pub(super) declared: BTreeMap<String, DeclaredArgument>,
554 pub(super) explicit_argument_ids: BTreeSet<String>,
555 pub(super) output: OutputPlan,
556 pub(super) strict_reads: bool,
560}
561
562#[derive(Clone, Debug, PartialEq, Eq)]
564pub(super) struct DeclaredArgument {
565 pub(super) value_type: ArgValueType,
566 pub(super) repeatable: bool,
567 pub(super) sourced: bool,
568}
569
570#[derive(Clone, Debug, PartialEq)]
572pub(super) enum InvocationValue {
573 Bool(bool),
574 String(String),
575 I64(i64),
576 FiniteF64(f64),
577 Json(String),
578 List(Vec<InvocationValue>),
579}
580
581impl InvocationValue {
582 fn as_bool(&self) -> Option<bool> {
583 match self {
584 Self::Bool(value) => Some(*value),
585 _ => None,
586 }
587 }
588
589 fn as_str(&self) -> Option<&str> {
590 match self {
591 Self::String(value) => Some(value),
592 _ => None,
593 }
594 }
595
596 fn as_i64(&self) -> Option<i64> {
597 match self {
598 Self::I64(value) => Some(*value),
599 _ => None,
600 }
601 }
602
603 fn as_f64(&self) -> Option<f64> {
604 match self {
605 Self::FiniteF64(value) => Some(*value),
606 _ => None,
607 }
608 }
609
610 fn as_json_str(&self) -> Option<&str> {
612 match self {
613 Self::Json(value) => Some(value),
614 _ => None,
615 }
616 }
617
618 fn as_list(&self) -> Option<&[InvocationValue]> {
619 match self {
620 Self::List(values) => Some(values),
621 _ => None,
622 }
623 }
624}
625
626impl From<CliValue> for InvocationValue {
627 fn from(value: CliValue) -> Self {
628 match value {
629 CliValue::Bool(value) => Self::Bool(value),
630 CliValue::String(value) => Self::String(value),
631 CliValue::I64(value) => Self::I64(value),
632 CliValue::FiniteF64(value) => Self::FiniteF64(value),
633 CliValue::Json(value) => Self::Json(value),
634 CliValue::List(items) => Self::List(items.into_iter().map(Self::from).collect()),
635 }
636 }
637}
638
639const TEXT_TYPES: &[ArgValueType] = &[ArgValueType::String, ArgValueType::Enum, ArgValueType::Uuid];
641
642impl ResolvedInvocation {
643 pub fn command_path(&self) -> &[String] {
644 &self.command_path
645 }
646
647 pub fn action_id(&self) -> &str {
648 &self.action_id
649 }
650
651 pub fn combination_id(&self) -> &str {
652 &self.combination_id
653 }
654
655 pub fn output_plan(&self) -> &OutputPlan {
656 &self.output
657 }
658
659 pub fn was_explicit(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
662 self.declaration(argument_id, "explicit argument")?;
663 Ok(self.explicit_argument_ids.contains(argument_id))
664 }
665
666 pub fn declares(&self, argument_id: &str) -> bool {
672 self.declared.contains_key(argument_id)
673 }
674
675 pub fn text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
678 let value = self.single(argument_id, TEXT_TYPES, "text")?;
679 self.required_value(argument_id, value, "text")?
680 .as_str()
681 .ok_or_else(|| self.refuse(argument_id, "text", InvocationReadProblem::WrongType))
682 }
683
684 pub fn optional_text(&self, argument_id: &str) -> Result<Option<&str>, InvocationReadError> {
686 Ok(self
687 .single(argument_id, TEXT_TYPES, "optional text")?
688 .and_then(InvocationValue::as_str))
689 }
690
691 pub fn texts(&self, argument_id: &str) -> Result<Vec<&str>, InvocationReadError> {
693 Ok(self
694 .list(argument_id, TEXT_TYPES, "repeated text")?
695 .iter()
696 .filter_map(InvocationValue::as_str)
697 .collect())
698 }
699
700 pub fn flag(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
703 let value = self.single(argument_id, &[ArgValueType::Flag], "flag")?;
704 Ok(value.and_then(InvocationValue::as_bool).unwrap_or(false))
705 }
706
707 pub fn json_text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
709 let value = self.single(argument_id, &[ArgValueType::Json], "json text")?;
710 self.required_value(argument_id, value, "json text")?
711 .as_json_str()
712 .ok_or_else(|| self.refuse(argument_id, "json text", InvocationReadProblem::WrongType))
713 }
714
715 pub fn optional_json_text(
717 &self,
718 argument_id: &str,
719 ) -> Result<Option<&str>, InvocationReadError> {
720 Ok(self
721 .single(argument_id, &[ArgValueType::Json], "optional json text")?
722 .and_then(InvocationValue::as_json_str))
723 }
724
725 pub fn integer<T: TryFrom<i64>>(&self, argument_id: &str) -> Result<T, InvocationReadError> {
731 let expected = integer_read("integer", std::any::type_name::<T>());
732 let value = self.single(argument_id, &[ArgValueType::I64], &expected)?;
733 let number = self
734 .required_value(argument_id, value, &expected)?
735 .as_i64()
736 .ok_or_else(|| self.refuse(argument_id, &expected, InvocationReadProblem::WrongType))?;
737 T::try_from(number)
738 .map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
739 }
740
741 pub fn optional_integer<T: TryFrom<i64>>(
743 &self,
744 argument_id: &str,
745 ) -> Result<Option<T>, InvocationReadError> {
746 let expected = integer_read("optional integer", std::any::type_name::<T>());
747 let Some(number) = self
748 .single(argument_id, &[ArgValueType::I64], &expected)?
749 .and_then(InvocationValue::as_i64)
750 else {
751 return Ok(None);
752 };
753 T::try_from(number)
754 .map(Some)
755 .map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
756 }
757
758 pub fn integers<T: TryFrom<i64>>(
761 &self,
762 argument_id: &str,
763 ) -> Result<Vec<T>, InvocationReadError> {
764 let expected = integer_read("repeated integers", std::any::type_name::<T>());
765 self.list(argument_id, &[ArgValueType::I64], &expected)?
766 .iter()
767 .filter_map(InvocationValue::as_i64)
768 .map(|number| {
769 T::try_from(number).map_err(|_| {
770 self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange)
771 })
772 })
773 .collect()
774 }
775
776 pub fn number(&self, argument_id: &str) -> Result<f64, InvocationReadError> {
778 let value = self.single(argument_id, &[ArgValueType::FiniteF64], "number")?;
779 self.required_value(argument_id, value, "number")?
780 .as_f64()
781 .ok_or_else(|| self.refuse(argument_id, "number", InvocationReadProblem::WrongType))
782 }
783
784 pub fn optional_number(&self, argument_id: &str) -> Result<Option<f64>, InvocationReadError> {
786 Ok(self
787 .single(argument_id, &[ArgValueType::FiniteF64], "optional number")?
788 .and_then(InvocationValue::as_f64))
789 }
790
791 pub fn key_value(&self, argument_id: &str) -> Result<(&str, &str), InvocationReadError> {
794 let value = self.single(argument_id, &[ArgValueType::KeyValue], "key-value pair")?;
795 self.required_value(argument_id, value, "key-value pair")?
796 .as_str()
797 .and_then(split_pair)
798 .ok_or_else(|| {
799 self.refuse(
800 argument_id,
801 "key-value pair",
802 InvocationReadProblem::WrongType,
803 )
804 })
805 }
806
807 pub fn optional_key_value(
809 &self,
810 argument_id: &str,
811 ) -> Result<Option<(&str, &str)>, InvocationReadError> {
812 Ok(self
813 .single(
814 argument_id,
815 &[ArgValueType::KeyValue],
816 "optional key-value pair",
817 )?
818 .and_then(InvocationValue::as_str)
819 .and_then(split_pair))
820 }
821
822 pub fn key_values(&self, argument_id: &str) -> Result<Vec<(&str, &str)>, InvocationReadError> {
824 Ok(self
825 .list(
826 argument_id,
827 &[ArgValueType::KeyValue],
828 "repeated key-value pairs",
829 )?
830 .iter()
831 .filter_map(InvocationValue::as_str)
832 .filter_map(split_pair)
833 .collect())
834 }
835
836 pub fn source(&self, argument_id: &str) -> Result<&ValueSource, InvocationReadError> {
843 let sources = self.sourced(argument_id, false, "source")?;
844 sources
845 .first()
846 .ok_or_else(|| self.refuse(argument_id, "source", InvocationReadProblem::Absent))
847 }
848
849 pub fn optional_source(
851 &self,
852 argument_id: &str,
853 ) -> Result<Option<&ValueSource>, InvocationReadError> {
854 Ok(self.sourced(argument_id, false, "optional source")?.first())
855 }
856
857 pub fn sources(&self, argument_id: &str) -> Result<&[ValueSource], InvocationReadError> {
859 self.sourced(argument_id, true, "repeated sources")
860 }
861
862 fn declaration(
863 &self,
864 argument_id: &str,
865 expected: &str,
866 ) -> Result<&DeclaredArgument, InvocationReadError> {
867 self.declared
868 .get(argument_id)
869 .ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Undeclared))
870 }
871
872 fn single(
874 &self,
875 argument_id: &str,
876 types: &[ArgValueType],
877 expected: &str,
878 ) -> Result<Option<&InvocationValue>, InvocationReadError> {
879 let declared = self.declaration(argument_id, expected)?;
880 if declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
881 return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
882 }
883 Ok(self.values.get(argument_id))
884 }
885
886 fn list(
888 &self,
889 argument_id: &str,
890 types: &[ArgValueType],
891 expected: &str,
892 ) -> Result<&[InvocationValue], InvocationReadError> {
893 let declared = self.declaration(argument_id, expected)?;
894 if !declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
895 return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
896 }
897 Ok(self
898 .values
899 .get(argument_id)
900 .and_then(InvocationValue::as_list)
901 .unwrap_or(&[]))
902 }
903
904 fn sourced(
905 &self,
906 argument_id: &str,
907 repeatable: bool,
908 expected: &str,
909 ) -> Result<&[ValueSource], InvocationReadError> {
910 let declared = self.declaration(argument_id, expected)?;
911 if !declared.sourced || declared.repeatable != repeatable {
912 return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
913 }
914 Ok(self.sources.get(argument_id).map_or(&[][..], Vec::as_slice))
915 }
916
917 fn required_value<'a>(
918 &self,
919 argument_id: &str,
920 value: Option<&'a InvocationValue>,
921 expected: &str,
922 ) -> Result<&'a InvocationValue, InvocationReadError> {
923 value.ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Absent))
924 }
925
926 #[allow(clippy::panic)]
929 fn refuse(
930 &self,
931 argument_id: &str,
932 expected: &str,
933 problem: InvocationReadProblem,
934 ) -> InvocationReadError {
935 let error = InvocationReadError {
936 combination_id: self.combination_id.clone(),
937 argument_id: argument_id.to_string(),
938 expected: expected.to_string(),
939 problem,
940 };
941 if self.strict_reads {
942 panic!("{error}");
943 }
944 error
945 }
946}
947
948fn integer_read(read: &str, type_name: &str) -> String {
949 format!(
950 "{read} as {}",
951 type_name.rsplit("::").next().unwrap_or(type_name)
952 )
953}
954
955fn split_pair(text: &str) -> Option<(&str, &str)> {
956 text.split_once('=').filter(|(key, _)| !key.is_empty())
957}
958
959#[derive(Clone, Debug, PartialEq, Eq)]
961pub enum OutputPlan {
962 Raw {
963 stdout_file: Option<PathBuf>,
964 stderr_file: Option<PathBuf>,
965 },
966 Protocol {
967 lifecycle: OutputLifecycle,
968 format: OutputFormat,
969 destination: OutputTo,
970 stdout_file: Option<PathBuf>,
971 stderr_file: Option<PathBuf>,
972 },
973}
974
975impl OutputPlan {
976 pub const fn output_format(&self) -> Option<OutputFormat> {
978 match self {
979 Self::Raw { .. } => None,
980 Self::Protocol { format, .. } => Some(*format),
981 }
982 }
983
984 pub const fn output_to(&self) -> Option<OutputTo> {
986 match self {
987 Self::Raw { .. } => None,
988 Self::Protocol { destination, .. } => Some(*destination),
989 }
990 }
991
992 pub fn stdout_file(&self) -> Option<&Path> {
993 match self {
994 Self::Raw { stdout_file, .. } | Self::Protocol { stdout_file, .. } => {
995 stdout_file.as_deref()
996 }
997 }
998 }
999
1000 pub fn stderr_file(&self) -> Option<&Path> {
1001 match self {
1002 Self::Raw { stderr_file, .. } | Self::Protocol { stderr_file, .. } => {
1003 stderr_file.as_deref()
1004 }
1005 }
1006 }
1007}
1008
1009#[derive(Default)]
1010struct ParsedArgs {
1011 application_values: BTreeMap<String, Vec<InvocationValue>>,
1012 application_sources: BTreeMap<String, Vec<ValueSource>>,
1015 explicit_application_ids: BTreeSet<String>,
1016 output: ParsedOutput,
1017 help: bool,
1018 version: bool,
1019 docs: bool,
1020}
1021
1022impl ParsedArgs {
1023 fn control_count(&self) -> usize {
1024 usize::from(self.help) + usize::from(self.version) + usize::from(self.docs)
1025 }
1026}
1027
1028#[derive(Default)]
1029struct ParsedOutput {
1030 format: Option<String>,
1031 destination: Option<String>,
1032 stdout_file: Option<PathBuf>,
1033 stderr_file: Option<PathBuf>,
1034}
1035
1036fn tokenize(
1037 command: &CommandSpec,
1038 tokens: &[String],
1039 command_path: &str,
1040 all_commands: &[CommandSpec],
1041) -> Result<ParsedArgs, CliError> {
1042 let longs: BTreeMap<&str, &ArgSpec> = command
1043 .arguments
1044 .iter()
1045 .filter_map(|argument| match &argument.syntax {
1046 ArgSyntax::Long { name } => Some((name.as_str(), argument)),
1047 ArgSyntax::Positional { .. } => None,
1048 })
1049 .collect();
1050 let mut positionals: Vec<&ArgSpec> = command
1051 .arguments
1052 .iter()
1053 .filter(|argument| matches!(argument.syntax, ArgSyntax::Positional { .. }))
1054 .collect();
1055 positionals.sort_by_key(|argument| match argument.syntax {
1056 ArgSyntax::Positional { index } => index,
1057 ArgSyntax::Long { .. } => usize::MAX,
1058 });
1059
1060 let mut parsed = ParsedArgs::default();
1061 let mut index = 0;
1062 let mut positional_index = 0;
1063 let mut options_done = false;
1064 while index < tokens.len() {
1065 let token = &tokens[index];
1066 if !options_done && token == "--" {
1067 options_done = true;
1068 index += 1;
1069 continue;
1070 }
1071 if !options_done && token.starts_with("--") {
1072 let (name, inline_value) = token
1073 .split_once('=')
1074 .map_or((token.as_str(), None), |(name, value)| (name, Some(value)));
1075 if let Some(argument) = longs.get(name).copied() {
1076 let display = name.to_string();
1077 let raw_value = if argument.value_type == ArgValueType::Flag {
1078 if inline_value.is_some() {
1079 return Err(invalid_value(
1080 command_path,
1081 display,
1082 "flags do not accept values",
1083 ));
1084 }
1085 None
1086 } else {
1087 Some(take_value(
1088 tokens,
1089 &mut index,
1090 inline_value,
1091 Some(argument),
1092 &longs,
1093 name,
1094 command_path,
1095 )?)
1096 };
1097 let value = match raw_value {
1098 Some(value) => parse_value(argument, value).map_err(|message| {
1099 invalid_value(command_path, display.clone(), &message)
1100 })?,
1101 None => InvocationValue::Bool(true),
1102 };
1103 insert_application(&mut parsed, argument, value, display, command_path)?;
1104 index += 1;
1105 continue;
1106 }
1107 match name {
1108 "--help" => {
1109 reject_inline_value(inline_value, name, command_path)?;
1110 set_once(&mut parsed.help, name, command_path)?;
1111 }
1112 "--version" => {
1113 reject_inline_value(inline_value, name, command_path)?;
1114 set_once(&mut parsed.version, name, command_path)?;
1115 }
1116 "--docs" => {
1117 reject_inline_value(inline_value, name, command_path)?;
1118 set_once(&mut parsed.docs, name, command_path)?;
1119 }
1120 "--output" => {
1121 parsed.output.format = Some(set_output_value(
1122 parsed.output.format.as_ref(),
1123 take_value(
1124 tokens,
1125 &mut index,
1126 inline_value,
1127 None,
1128 &longs,
1129 name,
1130 command_path,
1131 )?,
1132 name,
1133 command_path,
1134 )?);
1135 }
1136 "--output-to" => {
1137 parsed.output.destination = Some(set_output_value(
1138 parsed.output.destination.as_ref(),
1139 take_value(
1140 tokens,
1141 &mut index,
1142 inline_value,
1143 None,
1144 &longs,
1145 name,
1146 command_path,
1147 )?,
1148 name,
1149 command_path,
1150 )?);
1151 }
1152 "--stdout-file" => {
1153 parsed.output.stdout_file = Some(PathBuf::from(set_output_value(
1154 parsed.output.stdout_file.as_ref(),
1155 take_value(
1156 tokens,
1157 &mut index,
1158 inline_value,
1159 None,
1160 &longs,
1161 name,
1162 command_path,
1163 )?,
1164 name,
1165 command_path,
1166 )?));
1167 }
1168 "--stderr-file" => {
1169 parsed.output.stderr_file = Some(PathBuf::from(set_output_value(
1170 parsed.output.stderr_file.as_ref(),
1171 take_value(
1172 tokens,
1173 &mut index,
1174 inline_value,
1175 None,
1176 &longs,
1177 name,
1178 command_path,
1179 )?,
1180 name,
1181 command_path,
1182 )?));
1183 }
1184 _ => {
1185 return Err(CliError::new(
1186 CliErrorRule::UnknownArgument,
1187 command_path.to_string(),
1188 format!("unknown argument `{name}`"),
1189 ));
1190 }
1191 }
1192 index += 1;
1193 continue;
1194 }
1195 if !options_done && token.starts_with('-') && token != "-" {
1196 let positional_accepts_value = positionals
1197 .get(positional_index)
1198 .is_some_and(|argument| accepts_hyphen_prefixed_value(argument, token));
1199 if !positional_accepts_value {
1200 let mut error = CliError::new(
1201 CliErrorRule::UnknownArgument,
1202 command_path.to_string(),
1203 "unknown short argument",
1204 );
1205 error.hint = format!(
1206 "flags are long-only; pass `--` before a positional value that starts with `-`, or run `{command_path} --help`"
1207 );
1208 return Err(error);
1209 }
1210 }
1211 let Some(argument) = positionals.get(positional_index).copied() else {
1212 let message = if is_registered_command_segment(token, all_commands) {
1217 "command name must come before its arguments"
1218 } else {
1219 "unexpected positional argument"
1220 };
1221 return Err(CliError::new(
1222 CliErrorRule::UnexpectedPositional,
1223 command_path.to_string(),
1224 message,
1225 ));
1226 };
1227 let value = parse_value(argument, token).map_err(|message| {
1228 invalid_value(command_path, argument.argument_id.clone(), &message)
1229 })?;
1230 insert_application(
1231 &mut parsed,
1232 argument,
1233 value,
1234 argument.argument_id.clone(),
1235 command_path,
1236 )?;
1237 if !argument.repeatable {
1238 positional_index += 1;
1239 }
1240 index += 1;
1241 }
1242 Ok(parsed)
1243}
1244
1245fn take_value<'a>(
1246 tokens: &'a [String],
1247 index: &mut usize,
1248 inline_value: Option<&'a str>,
1249 argument: Option<&ArgSpec>,
1250 longs: &BTreeMap<&str, &ArgSpec>,
1251 name: &str,
1252 command_path: &str,
1253) -> Result<&'a str, CliError> {
1254 if let Some(value) = inline_value {
1255 if value.is_empty() && argument.is_none() {
1256 return Err(missing_value(command_path, name));
1257 }
1258 return Ok(value);
1259 }
1260 let Some(value) = tokens.get(*index + 1) else {
1261 return Err(missing_value(command_path, name));
1262 };
1263 if value.starts_with('-')
1264 && value != "-"
1265 && !argument.is_some_and(|argument| accepts_hyphen_prefixed_value(argument, value))
1266 {
1267 let mut error = missing_value(command_path, name);
1268 if !names_registered_flag(longs, value) {
1272 error.hint = format!("write `{name}=VALUE` for a value that starts with `-`");
1273 }
1274 return Err(error);
1275 }
1276 *index += 1;
1277 Ok(value)
1278}
1279
1280fn names_registered_flag(longs: &BTreeMap<&str, &ArgSpec>, token: &str) -> bool {
1283 let name = token.split_once('=').map_or(token, |(name, _)| name);
1284 longs.contains_key(name)
1285 || matches!(
1286 name,
1287 "--help"
1288 | "--version"
1289 | "--docs"
1290 | "--output"
1291 | "--output-to"
1292 | "--stdout-file"
1293 | "--stderr-file"
1294 )
1295}
1296
1297fn accepts_hyphen_prefixed_value(argument: &ArgSpec, value: &str) -> bool {
1309 match argument.value_type {
1310 ArgValueType::I64 => value.parse::<i64>().is_ok(),
1311 ArgValueType::FiniteF64 => value.parse::<f64>().is_ok_and(f64::is_finite),
1312 ArgValueType::String => {
1313 value.parse::<i64>().is_ok() || value.parse::<f64>().is_ok_and(f64::is_finite)
1314 }
1315 ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(value).is_ok(),
1316 _ => false,
1317 }
1318}
1319
1320fn reject_inline_value(
1321 inline_value: Option<&str>,
1322 name: &str,
1323 command_path: &str,
1324) -> Result<(), CliError> {
1325 if inline_value.is_some() {
1326 return Err(invalid_value(
1327 command_path,
1328 name.to_string(),
1329 "control flags do not accept values",
1330 ));
1331 }
1332 Ok(())
1333}
1334
1335fn set_once(value: &mut bool, name: &str, command_path: &str) -> Result<(), CliError> {
1336 if *value {
1337 return Err(duplicate_error(command_path, name));
1338 }
1339 *value = true;
1340 Ok(())
1341}
1342
1343fn set_output_value<T>(
1344 existing: Option<&T>,
1345 value: &str,
1346 name: &str,
1347 command_path: &str,
1348) -> Result<String, CliError> {
1349 if existing.is_some() {
1350 return Err(duplicate_error(command_path, name));
1351 }
1352 Ok(value.to_string())
1353}
1354
1355fn insert_application(
1356 parsed: &mut ParsedArgs,
1357 argument: &ArgSpec,
1358 value: InvocationValue,
1359 display: String,
1360 command_path: &str,
1361) -> Result<(), CliError> {
1362 let values = parsed
1363 .application_values
1364 .entry(argument.argument_id.clone())
1365 .or_default();
1366 if !argument.repeatable && !values.is_empty() {
1367 return Err(duplicate_error(command_path, &display));
1368 }
1369 if let (Some(sources), InvocationValue::String(raw)) = (&argument.sources, &value) {
1370 let source = sources
1372 .parse(raw)
1373 .map_err(|error| invalid_value(command_path, display.clone(), error.message()))?;
1374 parsed
1375 .application_sources
1376 .entry(argument.argument_id.clone())
1377 .or_default()
1378 .push(source);
1379 }
1380 values.push(value);
1381 parsed
1382 .explicit_application_ids
1383 .insert(argument.argument_id.clone());
1384 Ok(())
1385}
1386
1387fn parse_value(argument: &ArgSpec, raw: &str) -> Result<InvocationValue, String> {
1388 match argument.value_type {
1389 ArgValueType::Flag => Ok(InvocationValue::Bool(true)),
1390 ArgValueType::String | ArgValueType::Enum => {
1391 if argument.value_type == ArgValueType::Enum
1392 && !argument.enum_values.iter().any(|value| value == raw)
1393 {
1394 return Err(format!(
1395 "expected one of {}",
1396 argument.enum_values.join(", ")
1397 ));
1398 }
1399 Ok(InvocationValue::String(raw.to_string()))
1400 }
1401 ArgValueType::KeyValue => match raw.split_once('=') {
1402 Some((key, _)) if !key.is_empty() => Ok(InvocationValue::String(raw.to_string())),
1403 Some(_) => Err("expected KEY=VALUE with a non-empty KEY".to_string()),
1404 None => Err("expected KEY=VALUE".to_string()),
1405 },
1406 ArgValueType::I64 => {
1407 let value = raw
1408 .parse::<i64>()
1409 .map_err(|_| "expected an i64 integer".to_string())?;
1410 if let Some([minimum, maximum]) = argument.range
1411 && !(minimum..=maximum).contains(&value)
1412 {
1413 return Err(format!("expected an integer in {minimum}..={maximum}"));
1414 }
1415 Ok(InvocationValue::I64(value))
1416 }
1417 ArgValueType::Uuid => {
1418 if is_canonical_uuid(raw) {
1419 Ok(InvocationValue::String(raw.to_string()))
1420 } else {
1421 Err("expected a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
1422 }
1423 }
1424 ArgValueType::FiniteF64 => raw
1425 .parse::<f64>()
1426 .ok()
1427 .filter(|value| value.is_finite())
1428 .map(InvocationValue::FiniteF64)
1429 .ok_or_else(|| "expected a finite f64 number".to_string()),
1430 ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(raw)
1435 .map(|_| InvocationValue::Json(raw.to_string()))
1436 .map_err(|_| "expected one valid JSON value".to_string()),
1437 }
1438}
1439
1440pub(super) fn validate_value_type(argument: &ArgSpec, value: &CliValue) -> Result<(), String> {
1441 match (&argument.value_type, value) {
1442 (ArgValueType::Flag, CliValue::Bool(_))
1443 | (ArgValueType::String, CliValue::String(_))
1444 | (ArgValueType::Json, CliValue::Json(_)) => Ok(()),
1445 (ArgValueType::I64, CliValue::I64(number)) => match argument.range {
1450 Some([minimum, maximum]) if !(minimum..=maximum).contains(number) => Err(format!(
1451 "value {number} is outside the argument's {minimum}..={maximum} range"
1452 )),
1453 _ => Ok(()),
1454 },
1455 (ArgValueType::Uuid, CliValue::String(text)) if is_canonical_uuid(text) => Ok(()),
1456 (ArgValueType::Uuid, CliValue::String(_)) => {
1457 Err("value is not a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
1458 }
1459 (ArgValueType::FiniteF64, CliValue::FiniteF64(value)) if value.is_finite() => Ok(()),
1460 (ArgValueType::KeyValue, CliValue::String(text))
1461 if text.split_once('=').is_some_and(|(key, _)| !key.is_empty()) =>
1462 {
1463 Ok(())
1464 }
1465 (ArgValueType::KeyValue, CliValue::String(_)) => {
1466 Err("value is not KEY=VALUE with a non-empty KEY".to_string())
1467 }
1468 (ArgValueType::Enum, CliValue::String(value)) if argument.enum_values.contains(value) => {
1469 Ok(())
1470 }
1471 _ => Err("value type does not match the argument".to_string()),
1472 }
1473}
1474
1475fn combination_matches(
1476 command: &CommandSpec,
1477 combination: &Combination,
1478 parsed: &ParsedArgs,
1479) -> bool {
1480 let allowed: BTreeSet<&str> = combination
1481 .fixed
1482 .keys()
1483 .map(String::as_str)
1484 .chain(combination.required.iter().map(String::as_str))
1485 .chain(combination.optional.iter().map(String::as_str))
1486 .collect();
1487 if parsed
1488 .explicit_application_ids
1489 .iter()
1490 .any(|id| !allowed.contains(id.as_str()))
1491 || combination
1492 .required
1493 .iter()
1494 .any(|id| !parsed.explicit_application_ids.contains(id))
1495 {
1496 return false;
1497 }
1498 combination.fixed.iter().all(|(id, fixed)| {
1499 let argument = command
1500 .arguments
1501 .iter()
1502 .find(|argument| argument.argument_id == *id);
1503 let effective = parsed
1504 .application_values
1505 .get(id)
1506 .and_then(|values| values.first())
1507 .and_then(InvocationValue::as_str)
1508 .or_else(|| {
1509 argument
1510 .and_then(|arg| arg.default.as_ref())
1511 .and_then(CliValue::as_str)
1512 });
1513 effective.is_some_and(|value| fixed.values().iter().any(|fixed| fixed == value))
1514 })
1515}
1516
1517struct Projected {
1519 values: BTreeMap<String, InvocationValue>,
1520 sources: BTreeMap<String, Vec<ValueSource>>,
1521 declared: BTreeMap<String, DeclaredArgument>,
1522}
1523
1524fn project_values(
1525 command: &CommandSpec,
1526 combination: &Combination,
1527 parsed: &ParsedArgs,
1528) -> Projected {
1529 let allowed: BTreeSet<&str> = combination
1530 .fixed
1531 .keys()
1532 .map(String::as_str)
1533 .chain(combination.required.iter().map(String::as_str))
1534 .chain(combination.optional.iter().map(String::as_str))
1535 .collect();
1536 let mut projected = Projected {
1537 values: BTreeMap::new(),
1538 sources: BTreeMap::new(),
1539 declared: BTreeMap::new(),
1540 };
1541 for argument in command
1542 .arguments
1543 .iter()
1544 .filter(|argument| allowed.contains(argument.argument_id.as_str()))
1545 {
1546 let id = argument.argument_id.clone();
1547 projected.declared.insert(
1548 id.clone(),
1549 DeclaredArgument {
1550 value_type: argument.value_type.clone(),
1551 repeatable: argument.repeatable,
1552 sourced: argument.sources.is_some(),
1553 },
1554 );
1555 if argument.sources.is_some() {
1559 if let Some(sources) = parsed.application_sources.get(&id) {
1560 projected.sources.insert(id, sources.clone());
1561 }
1562 continue;
1563 }
1564 let value = parsed
1565 .application_values
1566 .get(&id)
1567 .map(|values| {
1568 if argument.repeatable {
1569 InvocationValue::List(values.clone())
1570 } else {
1571 values[0].clone()
1572 }
1573 })
1574 .or_else(|| {
1575 argument
1576 .default
1577 .clone()
1578 .map(InvocationValue::from)
1579 .map(|default| {
1580 if argument.repeatable {
1581 InvocationValue::List(vec![default])
1582 } else {
1583 default
1584 }
1585 })
1586 })
1587 .or_else(|| {
1588 (argument.value_type == ArgValueType::Flag).then_some(InvocationValue::Bool(false))
1589 });
1590 if let Some(value) = value {
1591 projected.values.insert(id, value);
1592 }
1593 }
1594 projected
1595}
1596
1597fn resolve_output(
1598 spec: &OutputSpec,
1599 parsed: &ParsedOutput,
1600 command_path: &str,
1601) -> Result<OutputPlan, CliError> {
1602 match spec {
1603 OutputSpec::Raw { file_sinks } => {
1604 if parsed.format.is_some() || parsed.destination.is_some() {
1605 return Err(CliError::unregistered(command_path.to_string()));
1606 }
1607 ensure_sinks(file_sinks, parsed, command_path)?;
1608 Ok(OutputPlan::Raw {
1609 stdout_file: parsed.stdout_file.clone(),
1610 stderr_file: parsed.stderr_file.clone(),
1611 })
1612 }
1613 OutputSpec::Protocol {
1614 lifecycle,
1615 formats,
1616 destinations,
1617 default_format,
1618 default_destination,
1619 file_sinks,
1620 } => {
1621 ensure_sinks(file_sinks, parsed, command_path)?;
1622 let format = parsed.format.as_ref().unwrap_or(default_format);
1623 if !formats.contains(format) {
1624 return Err(invalid_value(
1625 command_path,
1626 "--output".to_string(),
1627 &format!("expected one of {}", formats.join(", ")),
1628 ));
1629 }
1630 let destination = parsed.destination.as_ref().unwrap_or(default_destination);
1631 if !destinations.contains(destination) {
1632 return Err(invalid_value(
1633 command_path,
1634 "--output-to".to_string(),
1635 &format!("expected one of {}", destinations.join(", ")),
1636 ));
1637 }
1638 let output_format = format.parse::<OutputFormat>().map_err(|_| {
1639 invalid_value(
1640 command_path,
1641 "--output".to_string(),
1642 "expected one of json, yaml, plain",
1643 )
1644 })?;
1645 let output_to = destination.parse::<OutputTo>().map_err(|_| {
1646 invalid_value(
1647 command_path,
1648 "--output-to".to_string(),
1649 "expected one of split, stdout, stderr",
1650 )
1651 })?;
1652 Ok(OutputPlan::Protocol {
1653 lifecycle: *lifecycle,
1654 format: output_format,
1655 destination: output_to,
1656 stdout_file: parsed.stdout_file.clone(),
1657 stderr_file: parsed.stderr_file.clone(),
1658 })
1659 }
1660 }
1661}
1662
1663fn ensure_sinks(
1664 allowed: &[String],
1665 parsed: &ParsedOutput,
1666 command_path: &str,
1667) -> Result<(), CliError> {
1668 if (parsed.stdout_file.is_some() && !allowed.iter().any(|sink| sink == "stdout"))
1669 || (parsed.stderr_file.is_some() && !allowed.iter().any(|sink| sink == "stderr"))
1670 {
1671 return Err(CliError::unregistered(command_path.to_string()));
1672 }
1673 Ok(())
1674}
1675
1676fn is_registered_command_segment(token: &str, all_commands: &[CommandSpec]) -> bool {
1682 all_commands
1683 .iter()
1684 .any(|command| command.command_path.iter().any(|segment| segment == token))
1685}
1686
1687fn is_canonical_uuid(raw: &str) -> bool {
1693 const GROUPS: [usize; 5] = [8, 4, 4, 4, 12];
1694 let mut parts = raw.split('-');
1695 for width in GROUPS {
1696 let Some(part) = parts.next() else {
1697 return false;
1698 };
1699 if part.len() != width || !part.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1700 return false;
1701 }
1702 }
1703 parts.next().is_none()
1704}
1705
1706fn synthetic_value(argument: &ArgSpec) -> String {
1707 match argument.value_type {
1708 ArgValueType::Flag => String::new(),
1709 ArgValueType::String => {
1710 if argument.sensitive {
1711 "synthetic-sensitive".to_string()
1712 } else {
1713 "value".to_string()
1714 }
1715 }
1716 ArgValueType::I64 => argument
1717 .range
1718 .map_or_else(|| "1".to_string(), |[minimum, _]| minimum.to_string()),
1719 ArgValueType::Uuid => "00000000-0000-0000-0000-000000000000".to_string(),
1720 ArgValueType::FiniteF64 => "1.5".to_string(),
1721 ArgValueType::Enum => argument.enum_values.first().cloned().unwrap_or_default(),
1722 ArgValueType::Json => "{}".to_string(),
1723 ArgValueType::KeyValue => "key=value".to_string(),
1724 }
1725}
1726
1727fn append_synthetic_argument(argv: &mut Vec<String>, argument: &ArgSpec, value: &str) {
1728 match &argument.syntax {
1729 ArgSyntax::Long { name } => {
1730 argv.push(name.clone());
1731 if argument.value_type != ArgValueType::Flag {
1732 argv.push(value.to_string());
1733 }
1734 }
1735 ArgSyntax::Positional { .. } => argv.push(value.to_string()),
1736 }
1737}