use super::error::{
InvocationReadError, InvocationReadProblem, duplicate_error, invalid_value, missing_value,
};
use super::help::{HelpCatalog, combination_usage};
use super::*;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq)]
pub struct BuiltCliSpec {
pub(super) spec: CliSpec,
pub(super) hidden_help_defaults: BTreeMap<Vec<String>, BTreeSet<String>>,
}
impl BuiltCliSpec {
pub(crate) fn hide_help_defaults(&mut self, hide: impl Fn(&ArgSpec) -> bool) {
self.hidden_help_defaults = self
.spec
.commands
.iter()
.filter_map(|command| {
let hidden: BTreeSet<_> = command
.arguments
.iter()
.filter(|argument| argument.default.is_some() && hide(argument))
.map(|argument| argument.argument_id.clone())
.collect();
(!hidden.is_empty()).then(|| (command.command_path.clone(), hidden))
})
.collect();
}
pub fn spec(&self) -> &CliSpec {
&self.spec
}
pub fn resolve_from<I, S>(&self, args: I) -> Result<CliOutcome, CliError>
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
let raw: Vec<OsString> = args.into_iter().map(Into::into).collect();
self.resolve_os(&raw)
}
pub fn synthetic_invocations(&self) -> Vec<SyntheticInvocation> {
let mut fixtures = Vec::new();
for command in &self.spec.commands {
for combination in &command.combinations {
let mut variants = vec![vec![self.spec.name.clone()]];
for part in &command.command_path {
for argv in &mut variants {
argv.push(part.clone());
}
}
for argument in &command.arguments {
let values: Vec<String> =
if let Some(fixed) = combination.fixed.get(&argument.argument_id) {
fixed.values().to_vec()
} else if combination
.required
.iter()
.any(|id| id == &argument.argument_id)
{
vec![synthetic_value(argument)]
} else {
continue;
};
let mut expanded = Vec::new();
for argv in variants {
for value in &values {
let mut candidate = argv.clone();
append_synthetic_argument(&mut candidate, argument, value);
expanded.push(candidate);
}
}
variants = expanded;
}
fixtures.extend(variants.into_iter().map(|argv| SyntheticInvocation {
command_path: command.command_path.clone(),
combination_id: combination.combination_id.clone(),
argv,
}));
}
}
fixtures
}
pub fn help(&self, command_path: &[String]) -> Option<CliHelpV2> {
let command = self
.spec
.commands
.iter()
.find(|candidate| candidate.command_path == command_path)?;
Some(self.help_catalog(command, true).into_help_model())
}
pub fn bind_actions<R, I, S>(&self, handlers: I) -> Result<BoundCliSpec<R>, CliSpecError>
where
I: IntoIterator<Item = (S, fn(&ResolvedInvocation) -> R)>,
S: Into<String>,
{
let expected: BTreeSet<&str> = self
.spec
.commands
.iter()
.flat_map(|command| command.combinations.iter())
.map(|combination| combination.action_id.as_str())
.collect();
let mut actual = BTreeMap::new();
for (action_id, handler) in handlers {
let action_id = action_id.into();
if actual.insert(action_id.clone(), handler).is_some() {
return Err(CliSpecError::new(
"duplicate_action_handler",
format!("action `{action_id}` has more than one handler"),
));
}
}
let actual_ids: BTreeSet<&str> = actual.keys().map(String::as_str).collect();
if expected != actual_ids {
let missing: Vec<&str> = expected.difference(&actual_ids).copied().collect();
let extra: Vec<&str> = actual_ids.difference(&expected).copied().collect();
return Err(CliSpecError::new(
"action_handler_coverage",
format!("handler coverage mismatch; missing={missing:?}, extra={extra:?}"),
));
}
Ok(BoundCliSpec {
cli: self.clone(),
handlers: actual,
})
}
fn resolve_os(&self, raw: &[OsString]) -> Result<CliOutcome, CliError> {
let mut utf8 = Vec::with_capacity(raw.len());
for token in raw {
let Some(token) = token.to_str() else {
return Err(CliError::new(
CliErrorRule::InvalidUtf8,
self.spec.name.clone(),
"argv contains a token that is not valid UTF-8",
));
};
utf8.push(token.to_string());
}
let argv = if utf8.is_empty() { &[][..] } else { &utf8[1..] };
let (command, consumed) = self.select_command(argv)?;
let command_path = self.display_command_path(command);
let parsed = tokenize(
command,
&argv[consumed..],
&command_path,
&self.spec.commands,
)?;
if parsed.control_count() > 0 {
if parsed.control_count() != 1 || !parsed.application_values.is_empty() {
return Err(CliError::unregistered(command_path));
}
if parsed.docs {
if !command.command_path.is_empty() {
return Err(CliError::unregistered(command_path));
}
let contract = OutputSpec::raw()
.file_sinks(self.spec.lifecycle_output.file_sinks_ref().to_vec());
let output = resolve_output(&contract, &parsed.output, &command_path)?;
return Ok(CliOutcome::Docs(ResolvedDocs {
output,
registry: self.clone(),
}));
}
let output =
resolve_output(&self.spec.lifecycle_output, &parsed.output, &command_path)?;
if parsed.help {
return Ok(CliOutcome::Help(ResolvedHelp {
model: self.help_catalog(command, true).into_help_model(),
output,
}));
}
if parsed.version {
if !command.command_path.is_empty() {
return Err(CliError::unregistered(command_path));
}
return Ok(CliOutcome::Version(ResolvedVersion {
name: self.spec.name.clone(),
version: self.spec.version.clone(),
display_name: self.spec.display_name.clone(),
build: self.spec.build.clone(),
output,
}));
}
}
let matching: Vec<&Combination> = command
.combinations
.iter()
.filter(|combination| combination_matches(command, combination, &parsed))
.collect();
let Some(combination) = matching.first().copied() else {
return Err(CliError::unregistered(command_path));
};
if matching.len() != 1 {
return Err(CliError::new(
CliErrorRule::UnregisteredCombination,
command_path,
"arguments match more than one registered CLI combination",
));
}
let output = resolve_output(&combination.output, &parsed.output, &command_path)?;
let projected = project_values(command, combination, &parsed);
Ok(CliOutcome::Run(ResolvedInvocation {
command_path: command.command_path.clone(),
action_id: combination.action_id.clone(),
combination_id: combination.combination_id.clone(),
values: projected.values,
sources: projected.sources,
declared: projected.declared,
explicit_argument_ids: parsed.explicit_application_ids,
output,
strict_reads: false,
}))
}
fn select_command<'a>(&'a self, argv: &[String]) -> Result<(&'a CommandSpec, usize), CliError> {
let mut commands: Vec<&CommandSpec> = self.spec.commands.iter().collect();
commands.sort_by_key(|command| std::cmp::Reverse(command.command_path.len()));
if let Some(command) = commands.iter().copied().find(|command| {
command.command_path.len() <= argv.len()
&& command
.command_path
.iter()
.zip(argv)
.all(|(expected, actual)| expected == actual)
}) {
let remaining = &argv[command.command_path.len()..];
let has_children = self.spec.commands.iter().any(|candidate| {
candidate.command_path.len() > command.command_path.len()
&& candidate.command_path.starts_with(&command.command_path)
});
if remaining
.first()
.is_some_and(|token| !token.starts_with('-'))
&& has_children
{
return Err(CliError::new(
CliErrorRule::UnknownCommand,
self.display_command_path(command),
"unknown command",
));
}
return Ok((command, command.command_path.len()));
}
Err(CliError::new(
CliErrorRule::UnknownCommand,
self.spec.name.clone(),
"unknown command",
))
}
fn display_command_path(&self, command: &CommandSpec) -> String {
std::iter::once(self.spec.name.as_str())
.chain(command.command_path.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ")
}
fn child_help_commands(&self, command: &CommandSpec) -> Vec<String> {
let mut children: Vec<Vec<String>> = self
.spec
.commands
.iter()
.filter(|candidate| {
candidate.command_path.len() == command.command_path.len() + 1
&& candidate.command_path.starts_with(&command.command_path)
})
.map(|candidate| candidate.command_path.clone())
.collect();
children.sort();
children
.into_iter()
.map(|path| format!("{} {} --help", self.spec.name, path.join(" ")))
.collect()
}
pub(crate) fn help_catalog(
&self,
command: &CommandSpec,
include_output_usage: bool,
) -> HelpCatalog {
let command_path = self.display_command_path(command);
let mut shapes = Vec::new();
let mut notes = BTreeMap::new();
let mut shape_defaults = Vec::new();
let hidden_defaults = self.hidden_help_defaults.get(&command.command_path);
for combination in &command.combinations {
let (usage, shape_notes, defaults) = combination_usage(
command,
combination,
&command_path,
hidden_defaults,
include_output_usage,
);
shapes.push(CliShape {
id: combination.combination_id.clone(),
about: if command.combinations.len() == 1 {
None
} else {
combination.about.clone()
},
usage,
});
notes.extend(shape_notes);
shape_defaults.push(defaults);
}
let defaults: BTreeMap<_, _> = shape_defaults
.first()
.into_iter()
.flatten()
.filter(|(name, value)| {
shape_defaults
.iter()
.all(|defaults| defaults.get(*name) == Some(*value))
})
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
for specific in &mut shape_defaults {
specific.retain(|name, _| !defaults.contains_key(name));
}
let model = CliHelpV2 {
schema: "cli-help-v2".to_string(),
command_path,
about: command.about.clone().or_else(|| {
command
.command_path
.is_empty()
.then(|| self.spec.about.clone())
.flatten()
}),
shapes,
subcommands: self.child_help_commands(command),
notes,
defaults,
};
HelpCatalog {
model,
shape_defaults,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SyntheticInvocation {
pub command_path: Vec<String>,
pub combination_id: String,
pub argv: Vec<String>,
}
pub struct BoundCliSpec<R> {
cli: BuiltCliSpec,
handlers: BTreeMap<String, fn(&ResolvedInvocation) -> R>,
}
impl<R> BoundCliSpec<R> {
pub fn resolve_from<I, S>(&self, args: I) -> Result<BoundOutcome<R>, CliError>
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
Ok(match self.cli.resolve_from(args)? {
CliOutcome::Run(invocation) => BoundOutcome::Run(self.bind(invocation)),
CliOutcome::Help(help) => BoundOutcome::Help(help),
CliOutcome::Version(version) => BoundOutcome::Version(version),
CliOutcome::Docs(docs) => BoundOutcome::Docs(docs),
})
}
#[allow(clippy::panic)]
pub fn call_every_combination(&self) -> Vec<(String, R)> {
let mut results = Vec::new();
for fixture in self.cli.synthetic_invocations() {
let outcome = self.cli.resolve_from(fixture.argv.clone());
let Ok(CliOutcome::Run(mut invocation)) = outcome else {
panic!(
"combination `{}` generated argv {:?}, which does not resolve to a run",
fixture.combination_id, fixture.argv
);
};
invocation.strict_reads = true;
let combination = invocation.combination_id.clone();
results.push((combination, self.bind(invocation).run()));
}
assert!(
!results.is_empty(),
"no combination was called; a registry with no runnable combination cannot be verified"
);
results
}
fn bind(&self, invocation: ResolvedInvocation) -> BoundInvocation<R> {
#[allow(clippy::expect_used)]
let handler = *self
.handlers
.get(invocation.action_id())
.expect("bind_actions guarantees one handler per action id");
BoundInvocation {
invocation,
handler,
}
}
}
pub enum BoundOutcome<R> {
Run(BoundInvocation<R>),
Help(ResolvedHelp),
Version(ResolvedVersion),
Docs(ResolvedDocs),
}
impl<R> BoundOutcome<R> {
pub fn output_plan(&self) -> &OutputPlan {
match self {
Self::Run(invocation) => invocation.output_plan(),
Self::Docs(docs) => docs.output_plan(),
Self::Help(help) => help.output_plan(),
Self::Version(version) => version.output_plan(),
}
}
}
impl<R> std::fmt::Debug for BoundOutcome<R> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Run(invocation) => formatter.debug_tuple("Run").field(invocation).finish(),
Self::Help(help) => formatter.debug_tuple("Help").field(help).finish(),
Self::Version(version) => formatter.debug_tuple("Version").field(version).finish(),
Self::Docs(docs) => formatter.debug_tuple("Docs").field(docs).finish(),
}
}
}
pub struct BoundInvocation<R> {
invocation: ResolvedInvocation,
handler: fn(&ResolvedInvocation) -> R,
}
impl<R> BoundInvocation<R> {
pub fn output_plan(&self) -> &OutputPlan {
self.invocation.output_plan()
}
pub fn invocation(&self) -> &ResolvedInvocation {
&self.invocation
}
pub fn run(self) -> R {
(self.handler)(&self.invocation)
}
pub fn run_with_invocation(self) -> (R, ResolvedInvocation) {
let result = (self.handler)(&self.invocation);
(result, self.invocation)
}
}
impl<R> std::fmt::Debug for BoundInvocation<R> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("BoundInvocation")
.field("invocation", &self.invocation)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum CliOutcome {
Run(ResolvedInvocation),
Help(ResolvedHelp),
Version(ResolvedVersion),
Docs(ResolvedDocs),
}
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedInvocation {
pub(super) command_path: Vec<String>,
pub(super) action_id: String,
pub(super) combination_id: String,
pub(super) values: BTreeMap<String, InvocationValue>,
pub(super) sources: BTreeMap<String, Vec<ValueSource>>,
pub(super) declared: BTreeMap<String, DeclaredArgument>,
pub(super) explicit_argument_ids: BTreeSet<String>,
pub(super) output: OutputPlan,
pub(super) strict_reads: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct DeclaredArgument {
pub(super) value_type: ArgValueType,
pub(super) repeatable: bool,
pub(super) sourced: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub(super) enum InvocationValue {
Bool(bool),
String(String),
I64(i64),
FiniteF64(f64),
Json(String),
List(Vec<InvocationValue>),
}
impl InvocationValue {
fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(value) => Some(*value),
_ => None,
}
}
fn as_str(&self) -> Option<&str> {
match self {
Self::String(value) => Some(value),
_ => None,
}
}
fn as_i64(&self) -> Option<i64> {
match self {
Self::I64(value) => Some(*value),
_ => None,
}
}
fn as_f64(&self) -> Option<f64> {
match self {
Self::FiniteF64(value) => Some(*value),
_ => None,
}
}
fn as_json_str(&self) -> Option<&str> {
match self {
Self::Json(value) => Some(value),
_ => None,
}
}
fn as_list(&self) -> Option<&[InvocationValue]> {
match self {
Self::List(values) => Some(values),
_ => None,
}
}
}
impl From<CliValue> for InvocationValue {
fn from(value: CliValue) -> Self {
match value {
CliValue::Bool(value) => Self::Bool(value),
CliValue::String(value) => Self::String(value),
CliValue::I64(value) => Self::I64(value),
CliValue::FiniteF64(value) => Self::FiniteF64(value),
CliValue::Json(value) => Self::Json(value),
CliValue::List(items) => Self::List(items.into_iter().map(Self::from).collect()),
}
}
}
const TEXT_TYPES: &[ArgValueType] = &[ArgValueType::String, ArgValueType::Enum, ArgValueType::Uuid];
impl ResolvedInvocation {
pub fn command_path(&self) -> &[String] {
&self.command_path
}
pub fn action_id(&self) -> &str {
&self.action_id
}
pub fn combination_id(&self) -> &str {
&self.combination_id
}
pub fn output_plan(&self) -> &OutputPlan {
&self.output
}
pub fn was_explicit(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
self.declaration(argument_id, "explicit argument")?;
Ok(self.explicit_argument_ids.contains(argument_id))
}
pub fn declares(&self, argument_id: &str) -> bool {
self.declared.contains_key(argument_id)
}
pub fn text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
let value = self.single(argument_id, TEXT_TYPES, "text")?;
self.required_value(argument_id, value, "text")?
.as_str()
.ok_or_else(|| self.refuse(argument_id, "text", InvocationReadProblem::WrongType))
}
pub fn optional_text(&self, argument_id: &str) -> Result<Option<&str>, InvocationReadError> {
Ok(self
.single(argument_id, TEXT_TYPES, "optional text")?
.and_then(InvocationValue::as_str))
}
pub fn texts(&self, argument_id: &str) -> Result<Vec<&str>, InvocationReadError> {
Ok(self
.list(argument_id, TEXT_TYPES, "repeated text")?
.iter()
.filter_map(InvocationValue::as_str)
.collect())
}
pub fn flag(&self, argument_id: &str) -> Result<bool, InvocationReadError> {
let value = self.single(argument_id, &[ArgValueType::Flag], "flag")?;
Ok(value.and_then(InvocationValue::as_bool).unwrap_or(false))
}
pub fn json_text(&self, argument_id: &str) -> Result<&str, InvocationReadError> {
let value = self.single(argument_id, &[ArgValueType::Json], "json text")?;
self.required_value(argument_id, value, "json text")?
.as_json_str()
.ok_or_else(|| self.refuse(argument_id, "json text", InvocationReadProblem::WrongType))
}
pub fn optional_json_text(
&self,
argument_id: &str,
) -> Result<Option<&str>, InvocationReadError> {
Ok(self
.single(argument_id, &[ArgValueType::Json], "optional json text")?
.and_then(InvocationValue::as_json_str))
}
pub fn integer<T: TryFrom<i64>>(&self, argument_id: &str) -> Result<T, InvocationReadError> {
let expected = integer_read("integer", std::any::type_name::<T>());
let value = self.single(argument_id, &[ArgValueType::I64], &expected)?;
let number = self
.required_value(argument_id, value, &expected)?
.as_i64()
.ok_or_else(|| self.refuse(argument_id, &expected, InvocationReadProblem::WrongType))?;
T::try_from(number)
.map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
}
pub fn optional_integer<T: TryFrom<i64>>(
&self,
argument_id: &str,
) -> Result<Option<T>, InvocationReadError> {
let expected = integer_read("optional integer", std::any::type_name::<T>());
let Some(number) = self
.single(argument_id, &[ArgValueType::I64], &expected)?
.and_then(InvocationValue::as_i64)
else {
return Ok(None);
};
T::try_from(number)
.map(Some)
.map_err(|_| self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange))
}
pub fn integers<T: TryFrom<i64>>(
&self,
argument_id: &str,
) -> Result<Vec<T>, InvocationReadError> {
let expected = integer_read("repeated integers", std::any::type_name::<T>());
self.list(argument_id, &[ArgValueType::I64], &expected)?
.iter()
.filter_map(InvocationValue::as_i64)
.map(|number| {
T::try_from(number).map_err(|_| {
self.refuse(argument_id, &expected, InvocationReadProblem::OutOfRange)
})
})
.collect()
}
pub fn number(&self, argument_id: &str) -> Result<f64, InvocationReadError> {
let value = self.single(argument_id, &[ArgValueType::FiniteF64], "number")?;
self.required_value(argument_id, value, "number")?
.as_f64()
.ok_or_else(|| self.refuse(argument_id, "number", InvocationReadProblem::WrongType))
}
pub fn optional_number(&self, argument_id: &str) -> Result<Option<f64>, InvocationReadError> {
Ok(self
.single(argument_id, &[ArgValueType::FiniteF64], "optional number")?
.and_then(InvocationValue::as_f64))
}
pub fn key_value(&self, argument_id: &str) -> Result<(&str, &str), InvocationReadError> {
let value = self.single(argument_id, &[ArgValueType::KeyValue], "key-value pair")?;
self.required_value(argument_id, value, "key-value pair")?
.as_str()
.and_then(split_pair)
.ok_or_else(|| {
self.refuse(
argument_id,
"key-value pair",
InvocationReadProblem::WrongType,
)
})
}
pub fn optional_key_value(
&self,
argument_id: &str,
) -> Result<Option<(&str, &str)>, InvocationReadError> {
Ok(self
.single(
argument_id,
&[ArgValueType::KeyValue],
"optional key-value pair",
)?
.and_then(InvocationValue::as_str)
.and_then(split_pair))
}
pub fn key_values(&self, argument_id: &str) -> Result<Vec<(&str, &str)>, InvocationReadError> {
Ok(self
.list(
argument_id,
&[ArgValueType::KeyValue],
"repeated key-value pairs",
)?
.iter()
.filter_map(InvocationValue::as_str)
.filter_map(split_pair)
.collect())
}
pub fn source(&self, argument_id: &str) -> Result<&ValueSource, InvocationReadError> {
let sources = self.sourced(argument_id, false, "source")?;
sources
.first()
.ok_or_else(|| self.refuse(argument_id, "source", InvocationReadProblem::Absent))
}
pub fn optional_source(
&self,
argument_id: &str,
) -> Result<Option<&ValueSource>, InvocationReadError> {
Ok(self.sourced(argument_id, false, "optional source")?.first())
}
pub fn sources(&self, argument_id: &str) -> Result<&[ValueSource], InvocationReadError> {
self.sourced(argument_id, true, "repeated sources")
}
fn declaration(
&self,
argument_id: &str,
expected: &str,
) -> Result<&DeclaredArgument, InvocationReadError> {
self.declared
.get(argument_id)
.ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Undeclared))
}
fn single(
&self,
argument_id: &str,
types: &[ArgValueType],
expected: &str,
) -> Result<Option<&InvocationValue>, InvocationReadError> {
let declared = self.declaration(argument_id, expected)?;
if declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
}
Ok(self.values.get(argument_id))
}
fn list(
&self,
argument_id: &str,
types: &[ArgValueType],
expected: &str,
) -> Result<&[InvocationValue], InvocationReadError> {
let declared = self.declaration(argument_id, expected)?;
if !declared.repeatable || declared.sourced || !types.contains(&declared.value_type) {
return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
}
Ok(self
.values
.get(argument_id)
.and_then(InvocationValue::as_list)
.unwrap_or(&[]))
}
fn sourced(
&self,
argument_id: &str,
repeatable: bool,
expected: &str,
) -> Result<&[ValueSource], InvocationReadError> {
let declared = self.declaration(argument_id, expected)?;
if !declared.sourced || declared.repeatable != repeatable {
return Err(self.refuse(argument_id, expected, InvocationReadProblem::WrongType));
}
Ok(self.sources.get(argument_id).map_or(&[][..], Vec::as_slice))
}
fn required_value<'a>(
&self,
argument_id: &str,
value: Option<&'a InvocationValue>,
expected: &str,
) -> Result<&'a InvocationValue, InvocationReadError> {
value.ok_or_else(|| self.refuse(argument_id, expected, InvocationReadProblem::Absent))
}
#[allow(clippy::panic)]
fn refuse(
&self,
argument_id: &str,
expected: &str,
problem: InvocationReadProblem,
) -> InvocationReadError {
let error = InvocationReadError {
combination_id: self.combination_id.clone(),
argument_id: argument_id.to_string(),
expected: expected.to_string(),
problem,
};
if self.strict_reads {
panic!("{error}");
}
error
}
}
fn integer_read(read: &str, type_name: &str) -> String {
format!(
"{read} as {}",
type_name.rsplit("::").next().unwrap_or(type_name)
)
}
fn split_pair(text: &str) -> Option<(&str, &str)> {
text.split_once('=').filter(|(key, _)| !key.is_empty())
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OutputPlan {
Raw {
stdout_file: Option<PathBuf>,
stderr_file: Option<PathBuf>,
},
Protocol {
lifecycle: OutputLifecycle,
format: OutputFormat,
destination: OutputTo,
stdout_file: Option<PathBuf>,
stderr_file: Option<PathBuf>,
},
}
impl OutputPlan {
pub const fn output_format(&self) -> Option<OutputFormat> {
match self {
Self::Raw { .. } => None,
Self::Protocol { format, .. } => Some(*format),
}
}
pub const fn output_to(&self) -> Option<OutputTo> {
match self {
Self::Raw { .. } => None,
Self::Protocol { destination, .. } => Some(*destination),
}
}
pub fn stdout_file(&self) -> Option<&Path> {
match self {
Self::Raw { stdout_file, .. } | Self::Protocol { stdout_file, .. } => {
stdout_file.as_deref()
}
}
}
pub fn stderr_file(&self) -> Option<&Path> {
match self {
Self::Raw { stderr_file, .. } | Self::Protocol { stderr_file, .. } => {
stderr_file.as_deref()
}
}
}
}
#[derive(Default)]
struct ParsedArgs {
application_values: BTreeMap<String, Vec<InvocationValue>>,
application_sources: BTreeMap<String, Vec<ValueSource>>,
explicit_application_ids: BTreeSet<String>,
output: ParsedOutput,
help: bool,
version: bool,
docs: bool,
}
impl ParsedArgs {
fn control_count(&self) -> usize {
usize::from(self.help) + usize::from(self.version) + usize::from(self.docs)
}
}
#[derive(Default)]
struct ParsedOutput {
format: Option<String>,
destination: Option<String>,
stdout_file: Option<PathBuf>,
stderr_file: Option<PathBuf>,
}
fn tokenize(
command: &CommandSpec,
tokens: &[String],
command_path: &str,
all_commands: &[CommandSpec],
) -> Result<ParsedArgs, CliError> {
let longs: BTreeMap<&str, &ArgSpec> = command
.arguments
.iter()
.filter_map(|argument| match &argument.syntax {
ArgSyntax::Long { name } => Some((name.as_str(), argument)),
ArgSyntax::Positional { .. } => None,
})
.collect();
let mut positionals: Vec<&ArgSpec> = command
.arguments
.iter()
.filter(|argument| matches!(argument.syntax, ArgSyntax::Positional { .. }))
.collect();
positionals.sort_by_key(|argument| match argument.syntax {
ArgSyntax::Positional { index } => index,
ArgSyntax::Long { .. } => usize::MAX,
});
let mut parsed = ParsedArgs::default();
let mut index = 0;
let mut positional_index = 0;
let mut options_done = false;
while index < tokens.len() {
let token = &tokens[index];
if !options_done && token == "--" {
options_done = true;
index += 1;
continue;
}
if !options_done && token.starts_with("--") {
let (name, inline_value) = token
.split_once('=')
.map_or((token.as_str(), None), |(name, value)| (name, Some(value)));
if let Some(argument) = longs.get(name).copied() {
let display = name.to_string();
let raw_value = if argument.value_type == ArgValueType::Flag {
if inline_value.is_some() {
return Err(invalid_value(
command_path,
display,
"flags do not accept values",
));
}
None
} else {
Some(take_value(
tokens,
&mut index,
inline_value,
Some(argument),
&longs,
name,
command_path,
)?)
};
let value = match raw_value {
Some(value) => parse_value(argument, value).map_err(|message| {
invalid_value(command_path, display.clone(), &message)
})?,
None => InvocationValue::Bool(true),
};
insert_application(&mut parsed, argument, value, display, command_path)?;
index += 1;
continue;
}
match name {
"--help" => {
reject_inline_value(inline_value, name, command_path)?;
set_once(&mut parsed.help, name, command_path)?;
}
"--version" => {
reject_inline_value(inline_value, name, command_path)?;
set_once(&mut parsed.version, name, command_path)?;
}
"--docs" => {
reject_inline_value(inline_value, name, command_path)?;
set_once(&mut parsed.docs, name, command_path)?;
}
"--output" => {
parsed.output.format = Some(set_output_value(
parsed.output.format.as_ref(),
take_value(
tokens,
&mut index,
inline_value,
None,
&longs,
name,
command_path,
)?,
name,
command_path,
)?);
}
"--output-to" => {
parsed.output.destination = Some(set_output_value(
parsed.output.destination.as_ref(),
take_value(
tokens,
&mut index,
inline_value,
None,
&longs,
name,
command_path,
)?,
name,
command_path,
)?);
}
"--stdout-file" => {
parsed.output.stdout_file = Some(PathBuf::from(set_output_value(
parsed.output.stdout_file.as_ref(),
take_value(
tokens,
&mut index,
inline_value,
None,
&longs,
name,
command_path,
)?,
name,
command_path,
)?));
}
"--stderr-file" => {
parsed.output.stderr_file = Some(PathBuf::from(set_output_value(
parsed.output.stderr_file.as_ref(),
take_value(
tokens,
&mut index,
inline_value,
None,
&longs,
name,
command_path,
)?,
name,
command_path,
)?));
}
_ => {
let mut error = CliError::new(
CliErrorRule::UnknownArgument,
command_path.to_string(),
"unknown long argument",
);
error.hint = format!(
"run `{command_path} --help` for supported options, or pass `--` before a positional value that starts with `-`"
);
return Err(error);
}
}
index += 1;
continue;
}
if !options_done && token.starts_with('-') && token != "-" {
let positional_accepts_value = positionals
.get(positional_index)
.is_some_and(|argument| accepts_hyphen_prefixed_value(argument, token));
if !positional_accepts_value {
let mut error = CliError::new(
CliErrorRule::UnknownArgument,
command_path.to_string(),
"unknown short argument",
);
error.hint = format!(
"flags are long-only; pass `--` before a positional value that starts with `-`, or run `{command_path} --help`"
);
return Err(error);
}
}
let Some(argument) = positionals.get(positional_index).copied() else {
let message = if is_registered_command_segment(token, all_commands) {
"command name must come before its arguments"
} else {
"unexpected positional argument"
};
return Err(CliError::new(
CliErrorRule::UnexpectedPositional,
command_path.to_string(),
message,
));
};
let value = parse_value(argument, token).map_err(|message| {
invalid_value(command_path, argument.argument_id.clone(), &message)
})?;
insert_application(
&mut parsed,
argument,
value,
argument.argument_id.clone(),
command_path,
)?;
if !argument.repeatable {
positional_index += 1;
}
index += 1;
}
Ok(parsed)
}
fn take_value<'a>(
tokens: &'a [String],
index: &mut usize,
inline_value: Option<&'a str>,
argument: Option<&ArgSpec>,
longs: &BTreeMap<&str, &ArgSpec>,
name: &str,
command_path: &str,
) -> Result<&'a str, CliError> {
if let Some(value) = inline_value {
if value.is_empty() && argument.is_none() {
return Err(missing_value(command_path, name));
}
return Ok(value);
}
let Some(value) = tokens.get(*index + 1) else {
return Err(missing_value(command_path, name));
};
if value.starts_with('-')
&& value != "-"
&& !argument.is_some_and(|argument| accepts_hyphen_prefixed_value(argument, value))
{
let mut error = missing_value(command_path, name);
if !names_registered_flag(longs, value) {
error.hint = format!("write `{name}=VALUE` for a value that starts with `-`");
}
return Err(error);
}
*index += 1;
Ok(value)
}
fn names_registered_flag(longs: &BTreeMap<&str, &ArgSpec>, token: &str) -> bool {
let name = token.split_once('=').map_or(token, |(name, _)| name);
longs.contains_key(name)
|| matches!(
name,
"--help"
| "--version"
| "--docs"
| "--output"
| "--output-to"
| "--stdout-file"
| "--stderr-file"
)
}
fn accepts_hyphen_prefixed_value(argument: &ArgSpec, value: &str) -> bool {
match argument.value_type {
ArgValueType::I64 => value.parse::<i64>().is_ok(),
ArgValueType::FiniteF64 => value.parse::<f64>().is_ok_and(f64::is_finite),
ArgValueType::String => {
value.parse::<i64>().is_ok() || value.parse::<f64>().is_ok_and(f64::is_finite)
}
ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(value).is_ok(),
_ => false,
}
}
fn reject_inline_value(
inline_value: Option<&str>,
name: &str,
command_path: &str,
) -> Result<(), CliError> {
if inline_value.is_some() {
return Err(invalid_value(
command_path,
name.to_string(),
"control flags do not accept values",
));
}
Ok(())
}
fn set_once(value: &mut bool, name: &str, command_path: &str) -> Result<(), CliError> {
if *value {
return Err(duplicate_error(command_path, name));
}
*value = true;
Ok(())
}
fn set_output_value<T>(
existing: Option<&T>,
value: &str,
name: &str,
command_path: &str,
) -> Result<String, CliError> {
if existing.is_some() {
return Err(duplicate_error(command_path, name));
}
if value.is_empty() && matches!(name, "--stdout-file" | "--stderr-file") {
return Err(invalid_value(
command_path,
name.to_string(),
"expected a nonempty file path",
));
}
Ok(value.to_string())
}
fn insert_application(
parsed: &mut ParsedArgs,
argument: &ArgSpec,
value: InvocationValue,
display: String,
command_path: &str,
) -> Result<(), CliError> {
let values = parsed
.application_values
.entry(argument.argument_id.clone())
.or_default();
if !argument.repeatable && !values.is_empty() {
return Err(duplicate_error(command_path, &display));
}
if let (Some(sources), InvocationValue::String(raw)) = (&argument.sources, &value) {
let source = sources
.parse(raw)
.map_err(|error| invalid_value(command_path, display.clone(), error.message()))?;
parsed
.application_sources
.entry(argument.argument_id.clone())
.or_default()
.push(source);
}
values.push(value);
parsed
.explicit_application_ids
.insert(argument.argument_id.clone());
Ok(())
}
fn parse_value(argument: &ArgSpec, raw: &str) -> Result<InvocationValue, String> {
match argument.value_type {
ArgValueType::Flag => Ok(InvocationValue::Bool(true)),
ArgValueType::String | ArgValueType::Enum => {
if argument.value_type == ArgValueType::Enum
&& !argument.enum_values.iter().any(|value| value == raw)
{
return Err(format!(
"expected one of {}",
argument.enum_values.join(", ")
));
}
Ok(InvocationValue::String(raw.to_string()))
}
ArgValueType::KeyValue => match raw.split_once('=') {
Some((key, _)) if !key.is_empty() => Ok(InvocationValue::String(raw.to_string())),
Some(_) => Err("expected KEY=VALUE with a non-empty KEY".to_string()),
None => Err("expected KEY=VALUE".to_string()),
},
ArgValueType::I64 => {
let value = raw
.parse::<i64>()
.map_err(|_| "expected an i64 integer".to_string())?;
if let Some([minimum, maximum]) = argument.range
&& !(minimum..=maximum).contains(&value)
{
return Err(format!("expected an integer in {minimum}..={maximum}"));
}
Ok(InvocationValue::I64(value))
}
ArgValueType::Uuid => {
if is_canonical_uuid(raw) {
Ok(InvocationValue::String(raw.to_string()))
} else {
Err("expected a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
}
}
ArgValueType::FiniteF64 => raw
.parse::<f64>()
.ok()
.filter(|value| value.is_finite())
.map(InvocationValue::FiniteF64)
.ok_or_else(|| "expected a finite f64 number".to_string()),
ArgValueType::Json => serde_json::from_str::<serde::de::IgnoredAny>(raw)
.map(|_| InvocationValue::Json(raw.to_string()))
.map_err(|_| "expected one valid JSON value".to_string()),
}
}
pub(super) fn validate_value_type(argument: &ArgSpec, value: &CliValue) -> Result<(), String> {
match (&argument.value_type, value) {
(ArgValueType::Flag, CliValue::Bool(_))
| (ArgValueType::String, CliValue::String(_))
| (ArgValueType::Json, CliValue::Json(_)) => Ok(()),
(ArgValueType::I64, CliValue::I64(number)) => match argument.range {
Some([minimum, maximum]) if !(minimum..=maximum).contains(number) => Err(format!(
"value {number} is outside the argument's {minimum}..={maximum} range"
)),
_ => Ok(()),
},
(ArgValueType::Uuid, CliValue::String(text)) if is_canonical_uuid(text) => Ok(()),
(ArgValueType::Uuid, CliValue::String(_)) => {
Err("value is not a UUID (8-4-4-4-12 hexadecimal digits)".to_string())
}
(ArgValueType::FiniteF64, CliValue::FiniteF64(value)) if value.is_finite() => Ok(()),
(ArgValueType::KeyValue, CliValue::String(text))
if text.split_once('=').is_some_and(|(key, _)| !key.is_empty()) =>
{
Ok(())
}
(ArgValueType::KeyValue, CliValue::String(_)) => {
Err("value is not KEY=VALUE with a non-empty KEY".to_string())
}
(ArgValueType::Enum, CliValue::String(value)) if argument.enum_values.contains(value) => {
Ok(())
}
_ => Err("value type does not match the argument".to_string()),
}
}
fn combination_matches(
command: &CommandSpec,
combination: &Combination,
parsed: &ParsedArgs,
) -> bool {
let allowed: BTreeSet<&str> = combination
.fixed
.keys()
.map(String::as_str)
.chain(combination.required.iter().map(String::as_str))
.chain(combination.optional.iter().map(String::as_str))
.collect();
if parsed
.explicit_application_ids
.iter()
.any(|id| !allowed.contains(id.as_str()))
|| combination
.required
.iter()
.any(|id| !parsed.explicit_application_ids.contains(id))
{
return false;
}
combination.fixed.iter().all(|(id, fixed)| {
let argument = command
.arguments
.iter()
.find(|argument| argument.argument_id == *id);
let effective = parsed
.application_values
.get(id)
.and_then(|values| values.first())
.and_then(InvocationValue::as_str)
.or_else(|| {
argument
.and_then(|arg| arg.default.as_ref())
.and_then(CliValue::as_str)
});
effective.is_some_and(|value| fixed.values().iter().any(|fixed| fixed == value))
})
}
struct Projected {
values: BTreeMap<String, InvocationValue>,
sources: BTreeMap<String, Vec<ValueSource>>,
declared: BTreeMap<String, DeclaredArgument>,
}
fn project_values(
command: &CommandSpec,
combination: &Combination,
parsed: &ParsedArgs,
) -> Projected {
let allowed: BTreeSet<&str> = combination
.fixed
.keys()
.map(String::as_str)
.chain(combination.required.iter().map(String::as_str))
.chain(combination.optional.iter().map(String::as_str))
.collect();
let mut projected = Projected {
values: BTreeMap::new(),
sources: BTreeMap::new(),
declared: BTreeMap::new(),
};
for argument in command
.arguments
.iter()
.filter(|argument| allowed.contains(argument.argument_id.as_str()))
{
let id = argument.argument_id.clone();
projected.declared.insert(
id.clone(),
DeclaredArgument {
value_type: argument.value_type.clone(),
repeatable: argument.repeatable,
sourced: argument.sources.is_some(),
},
);
if argument.sources.is_some() {
if let Some(sources) = parsed.application_sources.get(&id) {
projected.sources.insert(id, sources.clone());
}
continue;
}
let value = parsed
.application_values
.get(&id)
.map(|values| {
if argument.repeatable {
InvocationValue::List(values.clone())
} else {
values[0].clone()
}
})
.or_else(|| {
argument
.default
.clone()
.map(InvocationValue::from)
.map(|default| {
if argument.repeatable {
InvocationValue::List(vec![default])
} else {
default
}
})
})
.or_else(|| {
(argument.value_type == ArgValueType::Flag).then_some(InvocationValue::Bool(false))
});
if let Some(value) = value {
projected.values.insert(id, value);
}
}
projected
}
fn resolve_output(
spec: &OutputSpec,
parsed: &ParsedOutput,
command_path: &str,
) -> Result<OutputPlan, CliError> {
match spec {
OutputSpec::Raw { file_sinks } => {
if parsed.format.is_some() || parsed.destination.is_some() {
return Err(CliError::unregistered(command_path.to_string()));
}
ensure_sinks(file_sinks, parsed, command_path)?;
Ok(OutputPlan::Raw {
stdout_file: parsed.stdout_file.clone(),
stderr_file: parsed.stderr_file.clone(),
})
}
OutputSpec::Protocol {
lifecycle,
formats,
destinations,
default_format,
default_destination,
file_sinks,
} => {
ensure_sinks(file_sinks, parsed, command_path)?;
let format = parsed.format.as_ref().unwrap_or(default_format);
if !formats.contains(format) {
return Err(invalid_value(
command_path,
"--output".to_string(),
&format!("expected one of {}", formats.join(", ")),
));
}
let destination = parsed.destination.as_ref().unwrap_or(default_destination);
if !destinations.contains(destination) {
return Err(invalid_value(
command_path,
"--output-to".to_string(),
&format!("expected one of {}", destinations.join(", ")),
));
}
let output_format = format.parse::<OutputFormat>().map_err(|_| {
invalid_value(
command_path,
"--output".to_string(),
"expected one of json, yaml, plain",
)
})?;
let output_to = destination.parse::<OutputTo>().map_err(|_| {
invalid_value(
command_path,
"--output-to".to_string(),
"expected one of split, stdout, stderr",
)
})?;
if !stdout_file_allowed(destination) && parsed.stdout_file.is_some() {
let mut error = CliError::new(
CliErrorRule::UnregisteredCombination,
command_path.to_string(),
"--stdout-file cannot be combined with --output-to stderr",
);
let alternatives: Vec<_> = destinations
.iter()
.filter(|destination| stdout_file_allowed(destination))
.map(String::as_str)
.collect();
error.hint = if alternatives.is_empty() {
"drop --stdout-file".into()
} else {
format!(
"drop --stdout-file or choose --output-to {}",
alternatives.join(" or ")
)
};
return Err(error);
}
Ok(OutputPlan::Protocol {
lifecycle: *lifecycle,
format: output_format,
destination: output_to,
stdout_file: parsed.stdout_file.clone(),
stderr_file: parsed.stderr_file.clone(),
})
}
}
}
fn ensure_sinks(
allowed: &[String],
parsed: &ParsedOutput,
command_path: &str,
) -> Result<(), CliError> {
if (parsed.stdout_file.is_some() && !allowed.iter().any(|sink| sink == "stdout"))
|| (parsed.stderr_file.is_some() && !allowed.iter().any(|sink| sink == "stderr"))
{
return Err(CliError::unregistered(command_path.to_string()));
}
Ok(())
}
fn is_registered_command_segment(token: &str, all_commands: &[CommandSpec]) -> bool {
all_commands
.iter()
.any(|command| command.command_path.iter().any(|segment| segment == token))
}
fn is_canonical_uuid(raw: &str) -> bool {
const GROUPS: [usize; 5] = [8, 4, 4, 4, 12];
let mut parts = raw.split('-');
for width in GROUPS {
let Some(part) = parts.next() else {
return false;
};
if part.len() != width || !part.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return false;
}
}
parts.next().is_none()
}
fn synthetic_value(argument: &ArgSpec) -> String {
match argument.value_type {
ArgValueType::Flag => String::new(),
ArgValueType::String => {
if argument.sensitive {
"synthetic-sensitive".to_string()
} else {
"value".to_string()
}
}
ArgValueType::I64 => argument
.range
.map_or_else(|| "1".to_string(), |[minimum, _]| minimum.to_string()),
ArgValueType::Uuid => "00000000-0000-0000-0000-000000000000".to_string(),
ArgValueType::FiniteF64 => "1.5".to_string(),
ArgValueType::Enum => argument.enum_values.first().cloned().unwrap_or_default(),
ArgValueType::Json => "{}".to_string(),
ArgValueType::KeyValue => "key=value".to_string(),
}
}
fn append_synthetic_argument(argv: &mut Vec<String>, argument: &ArgSpec, value: &str) {
match &argument.syntax {
ArgSyntax::Long { name } => {
argv.push(name.clone());
if argument.value_type != ArgValueType::Flag {
argv.push(value.to_string());
}
}
ArgSyntax::Positional { .. } => argv.push(value.to_string()),
}
}