1use crate::cli_spec::SourceScheme;
10use crate::cli_spec::{
11 ArgValueType, BuiltCliSpec, CliError, CliSpec, CliSpecError, ResolvedHelp, ResolvedVersion,
12};
13use crate::protocol::{Event, json_error, json_result};
14
15pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
25 for command in &mut spec.commands {
26 for argument in &mut command.arguments {
27 let suffixed = argument.argument_id.ends_with("_secret");
28 let is_flag = matches!(argument.value_type, ArgValueType::Flag);
29 if argument.sensitive && !suffixed {
30 return Err(CliSpecError {
31 rule: "sensitive_without_secret_suffix",
32 message: format!(
33 "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
34 redaction covers it too",
35 argument.argument_id, argument.argument_id
36 ),
37 });
38 }
39 if argument.sensitive && is_flag {
40 return Err(CliSpecError {
41 rule: "sensitive_flag",
42 message: format!(
43 "flag `{}` is marked sensitive, but a flag carries no value to redact",
44 argument.argument_id
45 ),
46 });
47 }
48 argument.sensitive = suffixed && !is_flag;
54
55 if let Some(sources) = &argument.sources
60 && sources.accepts(SourceScheme::Prompt)
61 && !argument.sensitive
62 {
63 return Err(CliSpecError {
64 rule: "prompt_source_without_secret",
65 message: format!(
66 "argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
67 drop the source — prompting blocks on a terminal for a value that is not \
68 a credential",
69 argument.argument_id, argument.argument_id
70 ),
71 });
72 }
73 }
74 }
75 spec.build()
76}
77
78pub fn cli_help_event(help: &ResolvedHelp) -> Event {
80 json_result(serde_json::json!({
81 "code": "help",
82 "help": help.model(),
83 }))
84 .build()
85}
86
87pub fn cli_version_event(version: &ResolvedVersion) -> Event {
94 crate::cli::build_cli_version(
95 version.name(),
96 version.display_name(),
97 version.version(),
98 version.build(),
99 )
100}
101
102const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
114const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");
115
116pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
133 let spec = cli.spec();
134 let name = spec.name.as_str();
135 let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
136 .commands
137 .iter()
138 .filter(|command| !command.combinations.is_empty())
139 .collect();
140 commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
141
142 let path_of = |command: &crate::cli_spec::CommandSpec| {
143 if command.command_path.is_empty() {
144 name.to_string()
145 } else {
146 format!("{name} {}", command.command_path.join(" "))
147 }
148 };
149
150 let mut out = String::new();
151 out.push_str(&format!("# {name} CLI reference\n\n"));
152 out.push_str(&format!(
153 "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
154 ));
155 if let Some(about) = &spec.about {
156 out.push_str(&format!("{about}\n\n"));
157 }
158 out.push_str(&format!(
159 "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
160 typed invocation values, which parameter combinations are legal, output contracts, and \
161 help. An invocation runs only when it matches exactly one registered combination.\n\n"
162 ));
163
164 let baseline = baseline_output(&commands);
169 out.push_str("## Global arguments\n\n");
170 out.push_str(
174 "AFDATA registers these itself, so the syntax in [Commands](#commands) \
175 leaves them out.\n\n",
176 );
177 out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
178 out.push_str(
179 "| `--help` | every command | Every legal shape of that command, complete, plus its \
180 subcommands. JSON by default; `--output plain` for a terminal. |\n",
181 );
182 out.push_str(&format!(
183 "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
184 |\n"
185 ));
186 out.push_str(&format!(
187 "| `--docs` | {name} only | This document, rendered from the registry. |\n"
188 ));
189 if let Some(crate::cli_spec::OutputSpec::Protocol {
190 formats,
191 destinations,
192 default_format,
193 default_destination,
194 ..
195 }) = &baseline
196 {
197 out.push_str(&format!(
198 "| `--output <FORMAT>` | per output contract | Render as {} (default \
199 `{default_format}`). |\n",
200 formats.join(", ")
201 ));
202 out.push_str(&format!(
203 "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
204 to {} (default `{default_destination}`). |\n",
205 destinations.join(", ")
206 ));
207 }
208 out.push_str(
209 "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
210 stream to a file instead. |\n\n",
211 );
212 let baseline_line = baseline.as_ref().map(describe_output);
213 if baseline.is_some() {
216 out.push_str(
217 "Success output is protocol events, on those terms, unless a command's own \
218 **Output** line says otherwise.\n\n",
219 );
220 }
221 out.push_str(SHAPES_PROSE);
222 out.push('\n');
223
224 out.push_str("## Commands\n\n");
225 for command in &commands {
226 let path = path_of(command);
227 let anchor = path.replace(' ', "-");
228 let about = command.about.as_deref().unwrap_or("");
229 out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
230 }
231 out.push('\n');
232
233 for command in &commands {
234 let path = path_of(command);
235 out.push_str(&format!("### `{path}`\n\n"));
236 if let Some(about) = &command.about {
237 out.push_str(&format!("{about}\n\n"));
238 }
239
240 let Some(model) = cli.help(&command.command_path) else {
241 continue;
242 };
243 for shape in &model.shapes {
244 if model.shapes.len() > 1 {
245 let differs = shape.about.as_deref().unwrap_or_default();
246 out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
247 }
248 out.push_str(&format!(
249 "```\n{}\n```\n\n",
250 trim_output_arguments(&shape.usage)
251 ));
252 }
253
254 let combinations: Vec<&crate::cli_spec::Combination> =
255 command.combinations.iter().collect();
256 let contracts = output_contracts(&combinations);
257 let is_baseline =
258 matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
259 if !is_baseline {
260 out.push_str(&render_output(&contracts));
261 }
262
263 let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
264 .arguments
265 .iter()
266 .filter_map(|argument| Some((argument, argument.rendered_about()?)))
267 .collect();
268 if !documented.is_empty() {
269 if model.shapes.len() > 1 {
270 out.push_str("Arguments across every shape above:\n\n");
274 }
275 out.push_str("| Argument | Meaning |\n|---|---|\n");
276 for (argument, about) in documented {
277 out.push_str(&format!(
280 "| `{}` | {about} |\n",
281 crate::cli_spec::argument_key(argument)
282 ));
283 }
284 out.push('\n');
285 }
286 }
287
288 out.push_str("## Exit codes\n\n");
289 out.push_str(
290 "| Code | Meaning |\n|---|---|\n\
291 | 0 | The command ran and succeeded. |\n\
292 | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
293 | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
294 `cli_*` codes below. |\n",
295 );
296 let mut declared_exit_codes: Vec<&crate::cli_spec::ExitCodeSpec> =
299 spec.exit_codes.iter().collect();
300 declared_exit_codes.sort_by_key(|exit| exit.code);
301 for exit in declared_exit_codes {
302 out.push_str(&format!("| {} | {} |\n", exit.code, exit.meaning));
303 }
304 out.push_str(
305 "\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
306 retrying it unchanged cannot help, while exit 1 means it was.\n\n",
307 );
308
309 out.push_str("## CLI errors\n\n");
310 out.push_str(CLI_ERRORS_PROSE);
311 out
312}
313
314fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
317 use crate::cli_spec::OutputSpec;
318 match output {
319 OutputSpec::Raw { file_sinks } => format!(
320 "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
321 strict JSON on stderr",
322 render_file_sinks(file_sinks)
323 ),
324 OutputSpec::Protocol {
325 formats,
326 destinations,
327 default_format,
328 default_destination,
329 file_sinks,
330 ..
331 } => format!(
332 "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
333 (default `{default_destination}`){}",
334 formats.join("/"),
335 destinations.join("/"),
336 render_file_sinks(file_sinks),
337 ),
338 }
339}
340
341fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
343 let mut lines: Vec<String> = Vec::new();
344 for combination in combinations {
345 let line = describe_output(&combination.output);
346 if !lines.contains(&line) {
347 lines.push(line);
348 }
349 }
350 lines
351}
352
353fn baseline_output(
358 commands: &[&crate::cli_spec::CommandSpec],
359) -> Option<crate::cli_spec::OutputSpec> {
360 let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
361 std::collections::BTreeMap::new();
362 for command in commands {
363 let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
364 for combination in &command.combinations {
365 if !contracts.contains(&&combination.output) {
366 contracts.push(&combination.output);
367 }
368 }
369 if let [only] = contracts.as_slice() {
370 let entry = counts
371 .entry(describe_output(only))
372 .or_insert((0, (*only).clone()));
373 entry.0 += 1;
374 }
375 }
376 counts
377 .into_iter()
378 .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
379 .filter(|(_, (count, _))| *count > 1)
380 .map(|(_, (_, spec))| spec)
381}
382
383fn render_output(contracts: &[String]) -> String {
384 match contracts {
385 [] => String::new(),
386 [only] => format!("Output: {only}.\n\n"),
387 many => {
388 let mut out = String::from("Output differs by combination:\n\n");
389 for line in many {
390 out.push_str(&format!("- {line}\n"));
391 }
392 out.push('\n');
393 out
394 }
395 }
396}
397
398fn trim_output_arguments(usage: &str) -> &str {
405 let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
406 .iter()
407 .filter_map(|marker| usage.find(marker))
408 .min();
409 match cut {
410 Some(index) => usage[..index].trim_end(),
411 None => usage,
412 }
413}
414
415fn render_file_sinks(file_sinks: &[String]) -> String {
416 let mut names: Vec<&str> = Vec::new();
417 if file_sinks.iter().any(|sink| sink == "stdout") {
418 names.push("`--stdout-file`");
419 }
420 if file_sinks.iter().any(|sink| sink == "stderr") {
421 names.push("`--stderr-file`");
422 }
423 if names.is_empty() {
424 String::new()
425 } else {
426 format!("; redirect with {}", names.join(" or "))
427 }
428}
429
430pub fn cli_error_event(error: &CliError) -> Event {
440 let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
441 match builder.build() {
442 Ok(event) => event,
443 Err(_) => json_error("cli_error", "failed to build CLI error")
444 .build()
445 .unwrap_or_else(|_| {
446 json_result(serde_json::json!({"code":"internal_cli_error"})).build()
449 }),
450 }
451}
452
453pub fn cli_invocation_invalid_event(detail: &str) -> Event {
471 let builder = json_error("cli_invocation_invalid", detail)
472 .hint("this is a defect in the program, not in the command; report it");
473 match builder.build() {
474 Ok(event) => event,
475 Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
476 .build()
477 .unwrap_or_else(|_| {
478 json_result(serde_json::json!({"code":"internal_cli_error"})).build()
481 }),
482 }
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488 use crate::cli_spec::SourceSet;
489 use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
490
491 fn output() -> OutputSpec {
492 OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
493 }
494
495 fn spec_with(argument: ArgSpec) -> CliSpec {
496 let id = argument.argument_id.clone();
497 CliSpec::new("demo", "1").command(
498 CommandSpec::root().arg(argument).combination(
499 Combination::new("only")
500 .action("only")
501 .required([id])
502 .output(output()),
503 ),
504 )
505 }
506
507 #[test]
508 fn a_cli_declares_exit_codes_beyond_afdatas_own() {
509 let spec = CliSpec::new("demo", "1.0.0")
510 .lifecycle_output(output())
511 .exit_code(4, "The output could not be written.")
512 .exit_code(3, "The command ran and partly succeeded.")
513 .command(CommandSpec::root())
514 .build()
515 .unwrap();
516 let reference = render_cli_reference(&spec);
517 let table = reference
518 .split("## Exit codes")
519 .nth(1)
520 .expect("the reference documents exit codes");
521 let partial = table.find("| 3 | The command ran and partly succeeded. |");
523 let write_failed = table.find("| 4 | The output could not be written. |");
524 assert!(partial.is_some() && write_failed.is_some(), "{table}");
525 assert!(partial < write_failed, "{table}");
526 }
527
528 #[test]
532 fn a_declared_source_set_renders_itself_into_help_and_docs() {
533 let built = build_afdata_cli(spec_with(
534 ArgSpec::option("--token-secret", "SOURCE")
535 .about("Token this host requires")
536 .sources(SourceSet::config().host_scheme("container", "container:NAME")),
537 ))
538 .expect("registry builds");
539
540 let reference = render_cli_reference(&built);
541 assert!(
542 reference.contains(
543 "Token this host requires (the value, or where to read it: env:NAME, \
544 file[+FORMAT]:PATH#DOT_PATH, container:NAME, literal:VALUE)"
545 ),
546 "{reference}"
547 );
548
549 let CliOutcome::Help(help) = built
550 .resolve_from(vec!["demo", "--help"])
551 .expect("help resolves")
552 else {
553 panic!("--help must resolve to help");
554 };
555 let model = serde_json::to_value(help.model()).expect("help serializes");
556 let note = model["notes"]["--token-secret"]
557 .as_str()
558 .unwrap_or_default()
559 .to_string();
560 assert!(note.contains("file[+FORMAT]:PATH#DOT_PATH"), "{model}");
561 }
562
563 #[test]
566 fn an_unaccepted_scheme_is_an_argv_rejection() {
567 let built = build_afdata_cli(spec_with(
568 ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
569 ))
570 .expect("registry builds");
571 let error = built
572 .resolve_from(vec!["demo", "--token-secret", "prompt"])
573 .expect_err("prompt is not in config()");
574 assert_eq!(
575 error.rule,
576 crate::cli_spec::CliErrorRule::InvalidArgumentValue
577 );
578 assert!(error.message.contains("env:NAME"), "{}", error.message);
579
580 let outcome = built
582 .resolve_from(vec!["demo", "--token-secret", "env:NAME"])
583 .expect("env is accepted");
584 let CliOutcome::Run(invocation) = outcome else {
585 panic!("must resolve to a run");
586 };
587 assert_eq!(
588 invocation.required("token_secret").as_str(),
589 Some("env:NAME")
590 );
591 }
592
593 #[test]
596 fn the_prompt_source_is_refused_on_a_non_secret_argument() {
597 let error = build_afdata_cli(spec_with(
598 ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
599 ))
600 .expect_err("prompt on a non-secret argument");
601 assert_eq!(error.rule, "prompt_source_without_secret");
602 assert!(
604 build_afdata_cli(spec_with(
605 ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
606 ))
607 .is_ok()
608 );
609 }
610
611 #[test]
612 fn secret_suffix_drives_the_sensitive_bit() {
613 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
614 let argument = &built.spec().commands[0].arguments[0];
615 assert!(argument.sensitive);
616 }
617
618 #[test]
619 fn sensitive_without_the_suffix_fails_the_build() {
620 let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
621 .unwrap_err();
622 assert_eq!(error.rule, "sensitive_without_secret_suffix");
623 }
624
625 #[test]
626 fn a_plain_argument_stays_insensitive() {
627 let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
628 assert!(!built.spec().commands[0].arguments[0].sensitive);
629 }
630
631 #[test]
635 fn version_events_carry_the_full_documented_payload() {
636 let built = CliSpec::new("demo", "1.2.3")
637 .display_name("Demo Tool")
638 .build_id("abc1234")
639 .command(CommandSpec::root())
640 .build()
641 .unwrap();
642 let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
643 else {
644 panic!("expected a version outcome");
645 };
646 assert_eq!(
647 cli_version_event(&version).as_value(),
648 &serde_json::json!({
649 "kind": "result",
650 "result": {
651 "code": "version",
652 "name": "demo",
653 "display_name": "Demo Tool",
654 "version": "1.2.3",
655 "build": "abc1234",
656 },
657 "trace": {},
658 })
659 );
660 }
661
662 #[test]
663 fn version_events_omit_absent_metadata() {
664 let built = CliSpec::new("demo", "1.2.3")
665 .command(CommandSpec::root())
666 .build()
667 .unwrap();
668 let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
669 else {
670 panic!("expected a version outcome");
671 };
672 let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
673 assert!(!payload.contains("display_name"), "{payload}");
674 assert!(!payload.contains("build"), "{payload}");
675 }
676
677 #[test]
678 fn cli_error_events_never_carry_a_secret_value() {
679 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
680 let error = built
681 .resolve_from([
682 "demo",
683 "--dsn-secret",
684 "postgres://user:password@example.test/db",
685 "--unknown",
686 ])
687 .unwrap_err();
688 let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
689 assert!(!serialized.contains("password"));
690 assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
692 assert!(serialized.contains("run `demo --help`"));
695 }
696
697 #[test]
702 fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
703 let event = cli_invocation_invalid_event("no handler for this registry's invocation");
704 let serialized = serde_json::to_string(event.as_value()).unwrap();
705
706 assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
707 assert!(serialized.contains("no handler for this registry's invocation"));
708 assert!(serialized.contains("defect in the program"));
711 assert!(
712 crate::validate_protocol_event(event.as_value(), true).is_ok(),
713 "the helper must emit a strict event: {serialized}"
714 );
715 }
716
717 #[test]
718 fn a_secret_named_flag_is_not_marked_sensitive() {
719 let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
723 let argument = built
724 .spec()
725 .commands
726 .iter()
727 .flat_map(|command| &command.arguments)
728 .find(|argument| argument.argument_id == "reveal_secret")
729 .expect("the flag is registered");
730 assert!(!argument.sensitive, "a flag has no value to redact");
731 }
732
733 #[test]
734 fn marking_a_flag_sensitive_is_a_contradiction() {
735 let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
736 .expect_err("a sensitive flag must not build");
737 assert_eq!(error.rule, "sensitive_flag");
738 }
739
740 #[test]
741 fn a_value_carrying_secret_argument_is_still_marked() {
742 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
743 let argument = built
744 .spec()
745 .commands
746 .iter()
747 .flat_map(|command| &command.arguments)
748 .find(|argument| argument.argument_id == "dsn_secret")
749 .expect("the option is registered");
750 assert!(argument.sensitive, "an option with a value still counts");
751 }
752}