use crate::cli_spec::SourceScheme;
use crate::cli_spec::{
ArgValueType, BoundCliSpec, BoundOutcome, BuiltCliSpec, CliError, CliErrorRule, CliSpec,
CliSpecError, InvocationReadError, OutputPlan, ResolvedHelp, ResolvedInvocation,
ResolvedVersion,
};
use crate::protocol::{Event, json_error, json_result};
pub fn cli_output_setup_failed_event(detail: &str) -> Event {
json_error(
"output_setup_failed",
if detail.is_empty() {
"an output sink could not be established"
} else {
detail
},
)
.build()
.unwrap_or_else(|_| cli_invocation_invalid_event("could not construct output setup diagnostic"))
}
pub fn cli_output_write_failed_event() -> Event {
json_error("output_write_failed", "could not write command output")
.build()
.unwrap_or_else(|_| {
cli_invocation_invalid_event("could not construct output write diagnostic")
})
}
#[derive(Debug)]
pub struct CliStop {
event: Event,
exit_code: u8,
}
impl CliStop {
pub fn new(event: Event, exit_code: u8) -> Self {
Self { event, exit_code }
}
pub fn invalid_argument(message: &str, hint: &str) -> Self {
let event = json_error(CliErrorRule::InvalidArgumentValue.code(), message)
.hint(hint)
.build()
.unwrap_or_else(|_| cli_invocation_invalid_event("could not construct usage error"));
Self::new(event, 2)
}
pub fn event(&self) -> &Event {
&self.event
}
pub const fn exit_code(&self) -> u8 {
self.exit_code
}
pub fn into_parts(self) -> (Event, u8) {
(self.event, self.exit_code)
}
}
impl From<CliError> for CliStop {
fn from(error: CliError) -> Self {
Self::new(cli_error_event(&error), error.exit_code())
}
}
impl From<InvocationReadError> for CliStop {
fn from(error: InvocationReadError) -> Self {
Self::new(cli_invocation_invalid_event(&error.to_string()), 1)
}
}
pub type CliHandler<C> = fn(&ResolvedInvocation) -> Result<C, CliStop>;
pub type ProcessEmitter = crate::cli::CliEmitter<Box<dyn std::io::Write>>;
type VersionHook<'a> = Box<dyn FnOnce(&ResolvedVersion) -> Event + 'a>;
type CheckHook<'a, C> =
Box<dyn FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a>;
pub struct CliMain<'a, C> {
bound: Result<BoundCliSpec<Result<C, CliStop>>, CliStop>,
check: Option<CheckHook<'a, C>>,
version: Option<VersionHook<'a>>,
}
pub struct PreparedCli<C> {
pub command: C,
pub invocation: ResolvedInvocation,
_sinks: InstalledSinks,
}
impl<C> PreparedCli<C> {
pub fn output_plan(&self) -> &OutputPlan {
self.invocation.output_plan()
}
pub fn emitter(&self) -> ProcessEmitter {
crate::cli::CliEmitter::from_plan(self.output_plan())
}
pub fn execute(
self,
execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
) -> std::process::ExitCode {
let PreparedCli {
command,
invocation,
_sinks,
} = self;
let mut emitter = crate::cli::CliEmitter::from_plan(invocation.output_plan());
let result = execute(command, &invocation, &mut emitter);
settle_output(&mut emitter, result)
}
}
impl<'a, C> CliMain<'a, C> {
pub fn new<I, S>(
cli: Result<BuiltCliSpec, CliSpecError>,
actions: impl FnOnce(&BuiltCliSpec) -> I,
) -> Self
where
I: IntoIterator<Item = (S, CliHandler<C>)>,
S: Into<String>,
{
let bound = match cli {
Err(error) => Err(startup_stop(
"cli_spec_invalid",
&error.to_string(),
"fix the program's cli-spec-v1 registry",
)),
Ok(cli) => cli.bind_actions(actions(&cli)).map_err(|error| {
startup_stop(
"cli_actions_invalid",
&error.to_string(),
"make the action handlers match the registry's actions exactly",
)
}),
};
Self {
bound,
check: None,
version: None,
}
}
#[must_use]
pub fn check(
mut self,
hook: impl FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a,
) -> Self {
self.check = Some(Box::new(hook));
self
}
#[must_use]
pub fn version(mut self, event: impl FnOnce(&ResolvedVersion) -> Event + 'a) -> Self {
self.version = Some(Box::new(event));
self
}
pub fn run<A, T>(
self,
argv: A,
execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
) -> std::process::ExitCode
where
A: IntoIterator<Item = T>,
T: Into<std::ffi::OsString>,
{
match self.prepare(argv) {
Ok(prepared) => prepared.execute(execute),
Err(exit) => exit,
}
}
pub fn prepare<A, T>(self, argv: A) -> Result<PreparedCli<C>, std::process::ExitCode>
where
A: IntoIterator<Item = T>,
T: Into<std::ffi::OsString>,
{
let outcome = self
.bound
.and_then(|bound| bound.resolve_from(argv).map_err(CliStop::from));
let outcome = match outcome {
Ok(outcome) => outcome,
Err(stop) => return Err(stop_before_output(stop)),
};
if let Some(check) = self.check
&& let Err(stop) = check(&outcome)
{
return Err(stop_before_output(stop));
}
match outcome {
BoundOutcome::Run(invocation) => {
let (projected, invocation) = invocation.run_with_invocation();
let command = match projected {
Ok(command) => command,
Err(stop) => return Err(stop_before_output(stop)),
};
let sinks = prepare_sinks(invocation.output_plan())?;
Ok(PreparedCli {
command,
invocation,
_sinks: sinks,
})
}
BoundOutcome::Docs(docs) => Err(run_with_plan(docs.output_plan(), |emitter| {
Ok(emitter.finish_raw(render_cli_reference(docs.registry()).as_bytes()))
})),
BoundOutcome::Help(help) => Err(run_with_plan(help.output_plan(), |emitter| {
if help.output_plan().output_format() == Some(crate::OutputFormat::Plain) {
Ok(emitter.finish_raw(help.plain().as_bytes()))
} else {
Ok(emitter.finish(cli_help_event(&help), 0))
}
})),
BoundOutcome::Version(version) => {
Err(run_with_plan(version.output_plan(), |emitter| {
let event = match self.version {
Some(event) => event(&version),
None => cli_version_event(&version),
};
Ok(emitter.finish(event, 0))
}))
}
}
}
}
pub fn run_with_plan(
plan: &OutputPlan,
execute: impl FnOnce(&mut ProcessEmitter) -> Result<u8, CliStop>,
) -> std::process::ExitCode {
let _sinks = match prepare_sinks(plan) {
Ok(sinks) => sinks,
Err(exit) => return exit,
};
let mut emitter = crate::cli::CliEmitter::from_plan(plan);
let result = execute(&mut emitter);
settle_output(&mut emitter, result)
}
fn settle_output(
emitter: &mut ProcessEmitter,
result: Result<u8, CliStop>,
) -> std::process::ExitCode {
let code = match result {
Ok(code) => emitter.exit_code(code),
Err(stop) => {
let (event, code) = stop.into_parts();
emitter.finish(event, code)
}
};
std::process::ExitCode::from(code)
}
#[cfg(feature = "stream-redirect")]
type InstalledSinks = Option<crate::stream_redirect::InstalledStreamRedirect>;
#[cfg(not(feature = "stream-redirect"))]
type InstalledSinks = ();
fn prepare_sinks(plan: &OutputPlan) -> Result<InstalledSinks, std::process::ExitCode> {
install_sinks(plan).map_err(|detail| {
stop_before_output(CliStop::new(cli_output_setup_failed_event(&detail), 1))
})
}
#[cfg(feature = "stream-redirect")]
fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
crate::stream_redirect::install_from_plan(plan).map_err(|error| error.to_string())
}
#[cfg(not(feature = "stream-redirect"))]
fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
if plan.stdout_file().is_some() || plan.stderr_file().is_some() {
return Err(
"this build has no stream-redirect support, so file sinks are unavailable".to_string(),
);
}
Ok(())
}
fn startup_stop(code: &str, message: &str, hint: &str) -> CliStop {
let event = json_error(code, message)
.hint(hint)
.build()
.unwrap_or_else(|_| cli_invocation_invalid_event("could not construct startup error"));
CliStop::new(event, 1)
}
fn stop_before_output(stop: CliStop) -> std::process::ExitCode {
let (event, code) = stop.into_parts();
let mut emitter =
crate::cli::CliEmitter::from_output_to(crate::OutputTo::Stderr, crate::OutputFormat::Json)
.with_strict_protocol();
std::process::ExitCode::from(emitter.finish(event, code))
}
pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
for command in &mut spec.commands {
for argument in &mut command.arguments {
let suffixed = argument.argument_id.ends_with("_secret");
let is_flag = matches!(argument.value_type, ArgValueType::Flag);
if argument.sensitive && !suffixed {
return Err(CliSpecError {
rule: "sensitive_without_secret_suffix",
message: format!(
"argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
redaction covers it too",
argument.argument_id, argument.argument_id
),
});
}
if argument.sensitive && is_flag {
return Err(CliSpecError {
rule: "sensitive_flag",
message: format!(
"flag `{}` is marked sensitive, but a flag carries no value to redact",
argument.argument_id
),
});
}
argument.sensitive = suffixed && !is_flag;
if let Some(sources) = &argument.sources
&& sources.accepts(SourceScheme::Prompt)
&& !argument.sensitive
{
return Err(CliSpecError {
rule: "prompt_source_without_secret",
message: format!(
"argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
drop the source — prompting blocks on a terminal for a value that is not \
a credential",
argument.argument_id, argument.argument_id
),
});
}
}
}
spec.build()
}
pub fn cli_help_event(help: &ResolvedHelp) -> Event {
json_result(serde_json::json!({
"code": "help",
"help": help.model(),
}))
.build()
}
pub fn cli_version_event(version: &ResolvedVersion) -> Event {
crate::cli::build_cli_version(
version.name(),
version.display_name(),
version.version(),
version.build(),
)
}
const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");
pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
let spec = cli.spec();
let name = spec.name.as_str();
let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
.commands
.iter()
.filter(|command| !command.combinations.is_empty())
.collect();
commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
let path_of = |command: &crate::cli_spec::CommandSpec| {
if command.command_path.is_empty() {
name.to_string()
} else {
format!("{name} {}", command.command_path.join(" "))
}
};
let mut out = String::new();
out.push_str(&format!("# {name} CLI reference\n\n"));
out.push_str(&format!(
"<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
));
if let Some(about) = &spec.about {
out.push_str(&format!("{about}\n\n"));
}
out.push_str(&format!(
"`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
typed invocation values, which parameter combinations are legal, output contracts, and \
help. An invocation runs only when it matches exactly one registered combination.\n\n"
));
let baseline = baseline_output(&commands);
out.push_str("## Global arguments\n\n");
out.push_str(
"AFDATA registers these itself, so the syntax in [Commands](#commands) \
leaves them out.\n\n",
);
out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
out.push_str(
"| `--help` | every command | Every legal shape of that command, complete, plus its \
subcommands. JSON by default; `--output plain` for a terminal. |\n",
);
out.push_str(&format!(
"| `--version` | {name} only | Name, version, and build identity as one protocol result. \
|\n"
));
out.push_str(&format!(
"| `--docs` | {name} only | This document, rendered from the registry. |\n"
));
if let Some(crate::cli_spec::OutputSpec::Protocol {
formats,
destinations,
default_format,
default_destination,
..
}) = &baseline
{
out.push_str(&format!(
"| `--output <FORMAT>` | per output contract | Render as {} (default \
`{default_format}`). |\n",
formats.join(", ")
));
out.push_str(&format!(
"| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
to {} (default `{default_destination}`). |\n",
destinations.join(", ")
));
}
out.push_str(
"| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
stream to a file instead. |\n\n",
);
let baseline_line = baseline.as_ref().map(describe_output);
if baseline.is_some() {
out.push_str(
"Success output is protocol events, on those terms, unless a command's own \
**Output** line says otherwise.\n\n",
);
}
out.push_str(SHAPES_PROSE);
out.push('\n');
out.push_str("## Commands\n\n");
for command in &commands {
let path = path_of(command);
let anchor = path.replace(' ', "-");
let about = command.about.as_deref().unwrap_or("");
out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
}
out.push('\n');
for command in &commands {
let path = path_of(command);
out.push_str(&format!("### `{path}`\n\n"));
if let Some(about) = &command.about {
out.push_str(&format!("{about}\n\n"));
}
let Some(model) = cli.help(&command.command_path) else {
continue;
};
for shape in &model.shapes {
if model.shapes.len() > 1 {
let differs = shape.about.as_deref().unwrap_or_default();
out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
}
out.push_str(&format!(
"```\n{}\n```\n\n",
trim_output_arguments(&shape.usage)
));
}
let combinations: Vec<&crate::cli_spec::Combination> =
command.combinations.iter().collect();
let contracts = output_contracts(&combinations);
let is_baseline =
matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
if !is_baseline {
out.push_str(&render_output(&contracts));
}
let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
.arguments
.iter()
.filter_map(|argument| Some((argument, argument.rendered_about()?)))
.collect();
if !documented.is_empty() {
if model.shapes.len() > 1 {
out.push_str("Arguments across every shape above:\n\n");
}
out.push_str("| Argument | Meaning |\n|---|---|\n");
for (argument, about) in documented {
out.push_str(&format!(
"| `{}` | {about} |\n",
crate::cli_spec::argument_key(argument)
));
}
out.push('\n');
}
if let Some(note) = &command.reference_note {
out.push_str(note.trim_end());
out.push_str("\n\n");
}
}
out.push_str("## Exit codes\n\n");
out.push_str(
"| Code | Meaning |\n|---|---|\n\
| 0 | The command ran and succeeded. |\n\
| 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
| 2 | The invocation was rejected before anything ran. `error.code` is one of the \
`cli_*` codes below. |\n",
);
let mut declared_exit_codes: Vec<(u8, &str)> = spec
.exit_codes
.iter()
.map(|exit| (exit.code, exit.meaning.as_str()))
.collect();
declared_exit_codes.push((
4,
"Output could not be written (`output_write_failed`); a closed reader is success.",
));
declared_exit_codes.sort_by_key(|(code, _)| *code);
for (code, meaning) in declared_exit_codes {
out.push_str(&format!("| {code} | {meaning} |\n"));
}
out.push_str(
"\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
retrying it unchanged cannot help, while exit 1 means it was.\n\n",
);
out.push_str("## CLI errors\n\n");
out.push_str(CLI_ERRORS_PROSE);
out
}
fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
use crate::cli_spec::OutputSpec;
match output {
OutputSpec::Raw { file_sinks } => format!(
"raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
strict JSON on stderr",
render_file_sinks(file_sinks)
),
OutputSpec::Protocol {
formats,
destinations,
default_format,
default_destination,
file_sinks,
..
} => format!(
"protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
(default `{default_destination}`){}",
formats.join("/"),
destinations.join("/"),
render_file_sinks(file_sinks),
),
}
}
fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for combination in combinations {
let line = describe_output(&combination.output);
if !lines.contains(&line) {
lines.push(line);
}
}
lines
}
fn baseline_output(
commands: &[&crate::cli_spec::CommandSpec],
) -> Option<crate::cli_spec::OutputSpec> {
let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
std::collections::BTreeMap::new();
for command in commands {
let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
for combination in &command.combinations {
if !contracts.contains(&&combination.output) {
contracts.push(&combination.output);
}
}
if let [only] = contracts.as_slice() {
let entry = counts
.entry(describe_output(only))
.or_insert((0, (*only).clone()));
entry.0 += 1;
}
}
counts
.into_iter()
.max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
.filter(|(_, (count, _))| *count > 1)
.map(|(_, (_, spec))| spec)
}
fn render_output(contracts: &[String]) -> String {
match contracts {
[] => String::new(),
[only] => format!("Output: {only}.\n\n"),
many => {
let mut out = String::from("Output differs by combination:\n\n");
for line in many {
out.push_str(&format!("- {line}\n"));
}
out.push('\n');
out
}
}
}
fn trim_output_arguments(usage: &str) -> &str {
let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
.iter()
.filter_map(|marker| usage.find(marker))
.min();
match cut {
Some(index) => usage[..index].trim_end(),
None => usage,
}
}
fn render_file_sinks(file_sinks: &[String]) -> String {
let mut names: Vec<&str> = Vec::new();
if file_sinks.iter().any(|sink| sink == "stdout") {
names.push("`--stdout-file`");
}
if file_sinks.iter().any(|sink| sink == "stderr") {
names.push("`--stderr-file`");
}
if names.is_empty() {
String::new()
} else {
format!("; redirect with {}", names.join(" or "))
}
}
pub fn cli_error_event(error: &CliError) -> Event {
let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
match builder.build() {
Ok(event) => event,
Err(_) => json_error("cli_error", "failed to build CLI error")
.build()
.unwrap_or_else(|_| {
json_result(serde_json::json!({"code":"internal_cli_error"})).build()
}),
}
}
pub fn cli_invocation_invalid_event(detail: &str) -> Event {
let builder = json_error("cli_invocation_invalid", detail)
.hint("this is a defect in the program, not in the command; report it");
match builder.build() {
Ok(event) => event,
Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
.build()
.unwrap_or_else(|_| {
json_result(serde_json::json!({"code":"internal_cli_error"})).build()
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli_spec::SourceSet;
use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
fn output() -> OutputSpec {
OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
}
fn spec_with(argument: ArgSpec) -> CliSpec {
let id = argument.argument_id.clone();
CliSpec::new("demo", "1").command(
CommandSpec::root().arg(argument).combination(
Combination::new("only")
.action("only")
.required([id])
.output(output()),
),
)
}
#[test]
fn a_cli_declares_exit_codes_beyond_afdatas_own() {
let spec = CliSpec::new("demo", "1.0.0")
.lifecycle_output(output())
.exit_code(5, "An application-specific failure.")
.exit_code(3, "The command ran and partly succeeded.")
.command(CommandSpec::root())
.build()
.unwrap();
let reference = render_cli_reference(&spec);
let table = reference
.split("## Exit codes")
.nth(1)
.expect("the reference documents exit codes");
let partial = table.find("| 3 | The command ran and partly succeeded. |");
let write_failed = table.find("| 5 | An application-specific failure. |");
assert!(partial.is_some() && write_failed.is_some(), "{table}");
assert!(partial < write_failed, "{table}");
}
#[test]
fn a_declared_source_set_renders_itself_into_help_and_docs() {
let built = build_afdata_cli(spec_with(
ArgSpec::option("--token-secret", "SOURCE")
.about("Token this host requires")
.sources(SourceSet::config().host_scheme("container", "container:NAME")),
))
.expect("registry builds");
let reference = render_cli_reference(&built);
assert!(
reference.contains(
"Token this host requires (the value, or where to read it: env:NAME, \
file[+FORMAT]:PATH[#DOT_PATH], container:NAME, literal:VALUE)"
),
"{reference}"
);
let CliOutcome::Help(help) = built
.resolve_from(vec!["demo", "--help"])
.expect("help resolves")
else {
panic!("--help must resolve to help");
};
let model = serde_json::to_value(help.model()).expect("help serializes");
let note = model["notes"]["--token-secret"]
.as_str()
.unwrap_or_default()
.to_string();
assert!(note.contains("file[+FORMAT]:PATH[#DOT_PATH]"), "{model}");
}
#[test]
fn an_unaccepted_scheme_is_an_argv_rejection() {
let built = build_afdata_cli(spec_with(
ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
))
.expect("registry builds");
let error = built
.resolve_from(vec!["demo", "--token-secret", "prompt"])
.expect_err("prompt is not in config()");
assert_eq!(
error.rule,
crate::cli_spec::CliErrorRule::InvalidArgumentValue
);
assert!(error.message.contains("env:NAME"), "{}", error.message);
let outcome = built
.resolve_from(vec!["demo", "--token-secret", "env:NAME"])
.expect("env is accepted");
let CliOutcome::Run(invocation) = outcome else {
panic!("must resolve to a run");
};
assert_eq!(
invocation.source("token_secret").unwrap(),
&crate::cli_spec::ValueSource::Env("NAME".to_string())
);
}
#[test]
fn the_prompt_source_is_refused_on_a_non_secret_argument() {
let error = build_afdata_cli(spec_with(
ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
))
.expect_err("prompt on a non-secret argument");
assert_eq!(error.rule, "prompt_source_without_secret");
assert!(
build_afdata_cli(spec_with(
ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
))
.is_ok()
);
}
#[test]
fn secret_suffix_drives_the_sensitive_bit() {
let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
let argument = &built.spec().commands[0].arguments[0];
assert!(argument.sensitive);
}
#[test]
fn sensitive_without_the_suffix_fails_the_build() {
let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
.unwrap_err();
assert_eq!(error.rule, "sensitive_without_secret_suffix");
}
#[test]
fn a_plain_argument_stays_insensitive() {
let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
assert!(!built.spec().commands[0].arguments[0].sensitive);
}
#[test]
fn version_events_carry_the_full_documented_payload() {
let built = CliSpec::new("demo", "1.2.3")
.display_name("Demo Tool")
.build_id("abc1234")
.command(CommandSpec::root())
.build()
.unwrap();
let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
else {
panic!("expected a version outcome");
};
assert_eq!(
cli_version_event(&version).as_value(),
&serde_json::json!({
"kind": "result",
"result": {
"code": "version",
"name": "demo",
"display_name": "Demo Tool",
"version": "1.2.3",
"build": "abc1234",
},
"trace": {},
})
);
}
#[test]
fn version_events_omit_absent_metadata() {
let built = CliSpec::new("demo", "1.2.3")
.command(CommandSpec::root())
.build()
.unwrap();
let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
else {
panic!("expected a version outcome");
};
let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
assert!(!payload.contains("display_name"), "{payload}");
assert!(!payload.contains("build"), "{payload}");
}
#[test]
fn cli_error_events_never_carry_a_secret_value() {
let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
let error = built
.resolve_from([
"demo",
"--dsn-secret",
"postgres://user:password@example.test/db",
"--unknown",
])
.unwrap_err();
let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
assert!(!serialized.contains("password"));
assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
assert!(serialized.contains("run `demo --help`"));
}
#[test]
fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
let event = cli_invocation_invalid_event("no handler for this registry's invocation");
let serialized = serde_json::to_string(event.as_value()).unwrap();
assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
assert!(serialized.contains("no handler for this registry's invocation"));
assert!(serialized.contains("defect in the program"));
assert!(
crate::validate_protocol_event(event.as_value(), true).is_ok(),
"the helper must emit a strict event: {serialized}"
);
}
#[test]
fn a_secret_named_flag_is_not_marked_sensitive() {
let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
let argument = built
.spec()
.commands
.iter()
.flat_map(|command| &command.arguments)
.find(|argument| argument.argument_id == "reveal_secret")
.expect("the flag is registered");
assert!(!argument.sensitive, "a flag has no value to redact");
}
#[test]
fn marking_a_flag_sensitive_is_a_contradiction() {
let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
.expect_err("a sensitive flag must not build");
assert_eq!(error.rule, "sensitive_flag");
}
#[test]
fn a_value_carrying_secret_argument_is_still_marked() {
let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
let argument = built
.spec()
.commands
.iter()
.flat_map(|command| &command.arguments)
.find(|argument| argument.argument_id == "dsn_secret")
.expect("the option is registered");
assert!(argument.sensitive, "an option with a value still counts");
}
#[test]
fn an_invalid_argument_stop_is_a_usage_error() {
let stop = CliStop::invalid_argument("expected one character", "pass a single character");
assert_eq!(stop.exit_code(), 2);
let value = stop.event().as_value();
assert_eq!(value["kind"], "error");
assert_eq!(value["error"]["code"], "cli_invalid_argument_value");
assert_eq!(value["error"]["hint"], "pass a single character");
let (event, code) = stop.into_parts();
assert_eq!(code, 2);
assert_eq!(
event.as_value()["error"]["message"],
"expected one character"
);
}
#[test]
fn a_failed_read_stops_as_a_program_defect() {
let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
let CliOutcome::Run(invocation) = built
.resolve_from(["demo", "--label", "a"])
.expect("resolves")
else {
panic!("must resolve to a run");
};
let error = invocation.text("lable").unwrap_err();
let stop = CliStop::from(error);
assert_eq!(stop.exit_code(), 1);
assert_eq!(
stop.event().as_value()["error"]["code"],
"cli_invocation_invalid"
);
assert!(
stop.event().as_value()["error"]["message"]
.as_str()
.is_some_and(|message| message.contains("lable") && message.contains("only")),
"{:?}",
stop.event()
);
}
#[test]
fn an_argv_rejection_stops_with_its_rule_code_and_exit_two() {
let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
let error = built
.resolve_from(["demo", "--nope"])
.expect_err("unknown argument");
let stop = CliStop::from(error);
assert_eq!(stop.exit_code(), 2);
assert_eq!(
stop.event().as_value()["error"]["code"],
"cli_unknown_argument"
);
}
}