1use crate::cli_spec::SourceScheme;
10use crate::cli_spec::{
11 ArgValueType, BoundCliSpec, BoundOutcome, BuiltCliSpec, CliError, CliErrorRule, CliSpec,
12 CliSpecError, InvocationReadError, OutputPlan, ResolvedHelp, ResolvedInvocation,
13 ResolvedVersion,
14};
15use crate::protocol::{Event, json_error, json_result};
16
17pub fn cli_output_setup_failed_event(detail: &str) -> Event {
19 json_error(
20 "output_setup_failed",
21 if detail.is_empty() {
22 "an output sink could not be established"
23 } else {
24 detail
25 },
26 )
27 .build()
28 .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct output setup diagnostic"))
29}
30
31pub fn cli_output_write_failed_event() -> Event {
33 json_error("output_write_failed", "could not write command output")
34 .build()
35 .unwrap_or_else(|_| {
36 cli_invocation_invalid_event("could not construct output write diagnostic")
37 })
38}
39
40#[derive(Debug)]
49pub struct CliStop {
50 event: Event,
51 exit_code: u8,
52}
53
54impl CliStop {
55 pub fn new(event: Event, exit_code: u8) -> Self {
56 Self { event, exit_code }
57 }
58
59 pub fn invalid_argument(message: &str, hint: &str) -> Self {
63 let event = json_error(CliErrorRule::InvalidArgumentValue.code(), message)
64 .hint(hint)
65 .build()
66 .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct usage error"));
67 Self::new(event, 2)
68 }
69
70 pub fn event(&self) -> &Event {
71 &self.event
72 }
73
74 pub const fn exit_code(&self) -> u8 {
75 self.exit_code
76 }
77
78 pub fn into_parts(self) -> (Event, u8) {
79 (self.event, self.exit_code)
80 }
81}
82
83impl From<CliError> for CliStop {
84 fn from(error: CliError) -> Self {
85 Self::new(cli_error_event(&error), error.exit_code())
86 }
87}
88
89impl From<InvocationReadError> for CliStop {
90 fn from(error: InvocationReadError) -> Self {
91 Self::new(cli_invocation_invalid_event(&error.to_string()), 1)
92 }
93}
94
95pub type CliHandler<C> = fn(&ResolvedInvocation) -> Result<C, CliStop>;
99
100pub type ProcessEmitter = crate::cli::CliEmitter<Box<dyn std::io::Write>>;
103
104type VersionHook<'a> = Box<dyn FnOnce(&ResolvedVersion) -> Event + 'a>;
105
106type CheckHook<'a, C> =
107 Box<dyn FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a>;
108
109pub struct CliMain<'a, C> {
130 bound: Result<BoundCliSpec<Result<C, CliStop>>, CliStop>,
131 check: Option<CheckHook<'a, C>>,
132 version: Option<VersionHook<'a>>,
133}
134
135pub struct PreparedCli<C> {
137 pub command: C,
139 pub invocation: ResolvedInvocation,
141 _sinks: InstalledSinks,
142}
143
144impl<C> PreparedCli<C> {
145 pub fn output_plan(&self) -> &OutputPlan {
147 self.invocation.output_plan()
148 }
149
150 pub fn emitter(&self) -> ProcessEmitter {
152 crate::cli::CliEmitter::from_plan(self.output_plan())
153 }
154
155 pub fn execute(
157 self,
158 execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
159 ) -> std::process::ExitCode {
160 let PreparedCli {
161 command,
162 invocation,
163 _sinks,
164 } = self;
165 let mut emitter = crate::cli::CliEmitter::from_plan(invocation.output_plan());
166 let result = execute(command, &invocation, &mut emitter);
167 settle_output(&mut emitter, result)
168 }
169}
170
171impl<'a, C> CliMain<'a, C> {
172 pub fn new<I, S>(
175 cli: Result<BuiltCliSpec, CliSpecError>,
176 actions: impl FnOnce(&BuiltCliSpec) -> I,
177 ) -> Self
178 where
179 I: IntoIterator<Item = (S, CliHandler<C>)>,
180 S: Into<String>,
181 {
182 let bound = match cli {
183 Err(error) => Err(startup_stop(
184 "cli_spec_invalid",
185 &error.to_string(),
186 "fix the program's cli-spec-v1 registry",
187 )),
188 Ok(cli) => cli.bind_actions(actions(&cli)).map_err(|error| {
189 startup_stop(
190 "cli_actions_invalid",
191 &error.to_string(),
192 "make the action handlers match the registry's actions exactly",
193 )
194 }),
195 };
196 Self {
197 bound,
198 check: None,
199 version: None,
200 }
201 }
202
203 #[must_use]
208 pub fn check(
209 mut self,
210 hook: impl FnOnce(&BoundOutcome<Result<C, CliStop>>) -> Result<(), CliStop> + 'a,
211 ) -> Self {
212 self.check = Some(Box::new(hook));
213 self
214 }
215
216 #[must_use]
221 pub fn version(mut self, event: impl FnOnce(&ResolvedVersion) -> Event + 'a) -> Self {
222 self.version = Some(Box::new(event));
223 self
224 }
225
226 pub fn run<A, T>(
228 self,
229 argv: A,
230 execute: impl FnOnce(C, &ResolvedInvocation, &mut ProcessEmitter) -> Result<u8, CliStop>,
231 ) -> std::process::ExitCode
232 where
233 A: IntoIterator<Item = T>,
234 T: Into<std::ffi::OsString>,
235 {
236 match self.prepare(argv) {
237 Ok(prepared) => prepared.execute(execute),
238 Err(exit) => exit,
239 }
240 }
241
242 pub fn prepare<A, T>(self, argv: A) -> Result<PreparedCli<C>, std::process::ExitCode>
247 where
248 A: IntoIterator<Item = T>,
249 T: Into<std::ffi::OsString>,
250 {
251 let outcome = self
252 .bound
253 .and_then(|bound| bound.resolve_from(argv).map_err(CliStop::from));
254 let outcome = match outcome {
255 Ok(outcome) => outcome,
256 Err(stop) => return Err(stop_before_output(stop)),
257 };
258 if let Some(check) = self.check
259 && let Err(stop) = check(&outcome)
260 {
261 return Err(stop_before_output(stop));
262 }
263 match outcome {
264 BoundOutcome::Run(invocation) => {
265 let (projected, invocation) = invocation.run_with_invocation();
266 let command = match projected {
267 Ok(command) => command,
268 Err(stop) => return Err(stop_before_output(stop)),
269 };
270 let sinks = prepare_sinks(invocation.output_plan())?;
271 Ok(PreparedCli {
272 command,
273 invocation,
274 _sinks: sinks,
275 })
276 }
277 BoundOutcome::Docs(docs) => Err(run_with_plan(docs.output_plan(), |emitter| {
278 Ok(emitter.finish_raw(render_cli_reference(docs.registry()).as_bytes()))
279 })),
280 BoundOutcome::Help(help) => Err(run_with_plan(help.output_plan(), |emitter| {
281 if help.output_plan().output_format() == Some(crate::OutputFormat::Plain) {
282 Ok(emitter.finish_raw(help.plain().as_bytes()))
283 } else {
284 Ok(emitter.finish(cli_help_event(&help), 0))
285 }
286 })),
287 BoundOutcome::Version(version) => {
288 Err(run_with_plan(version.output_plan(), |emitter| {
289 let event = match self.version {
290 Some(event) => event(&version),
291 None => cli_version_event(&version),
292 };
293 Ok(emitter.finish(event, 0))
294 }))
295 }
296 }
297 }
298}
299
300pub fn run_with_plan(
307 plan: &OutputPlan,
308 execute: impl FnOnce(&mut ProcessEmitter) -> Result<u8, CliStop>,
309) -> std::process::ExitCode {
310 let _sinks = match prepare_sinks(plan) {
311 Ok(sinks) => sinks,
312 Err(exit) => return exit,
313 };
314 let mut emitter = crate::cli::CliEmitter::from_plan(plan);
315 let result = execute(&mut emitter);
316 settle_output(&mut emitter, result)
317}
318
319fn settle_output(
320 emitter: &mut ProcessEmitter,
321 result: Result<u8, CliStop>,
322) -> std::process::ExitCode {
323 let code = match result {
324 Ok(code) => emitter.exit_code(code),
325 Err(stop) => {
326 let (event, code) = stop.into_parts();
327 emitter.finish(event, code)
328 }
329 };
330 std::process::ExitCode::from(code)
331}
332
333#[cfg(feature = "stream-redirect")]
334type InstalledSinks = Option<crate::stream_redirect::InstalledStreamRedirect>;
335#[cfg(not(feature = "stream-redirect"))]
336type InstalledSinks = ();
337
338fn prepare_sinks(plan: &OutputPlan) -> Result<InstalledSinks, std::process::ExitCode> {
339 install_sinks(plan).map_err(|detail| {
340 stop_before_output(CliStop::new(cli_output_setup_failed_event(&detail), 1))
341 })
342}
343
344#[cfg(feature = "stream-redirect")]
345fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
346 crate::stream_redirect::install_from_plan(plan).map_err(|error| error.to_string())
347}
348
349#[cfg(not(feature = "stream-redirect"))]
350fn install_sinks(plan: &OutputPlan) -> Result<InstalledSinks, String> {
351 if plan.stdout_file().is_some() || plan.stderr_file().is_some() {
352 return Err(
353 "this build has no stream-redirect support, so file sinks are unavailable".to_string(),
354 );
355 }
356 Ok(())
357}
358
359fn startup_stop(code: &str, message: &str, hint: &str) -> CliStop {
360 let event = json_error(code, message)
361 .hint(hint)
362 .build()
363 .unwrap_or_else(|_| cli_invocation_invalid_event("could not construct startup error"));
364 CliStop::new(event, 1)
365}
366
367fn stop_before_output(stop: CliStop) -> std::process::ExitCode {
370 let (event, code) = stop.into_parts();
371 let mut emitter =
372 crate::cli::CliEmitter::from_output_to(crate::OutputTo::Stderr, crate::OutputFormat::Json)
373 .with_strict_protocol();
374 std::process::ExitCode::from(emitter.finish(event, code))
375}
376
377pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
387 for command in &mut spec.commands {
388 for argument in &mut command.arguments {
389 let suffixed = argument.argument_id.ends_with("_secret");
390 let is_flag = matches!(argument.value_type, ArgValueType::Flag);
391 if argument.sensitive && !suffixed {
392 return Err(CliSpecError {
393 rule: "sensitive_without_secret_suffix",
394 message: format!(
395 "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
396 redaction covers it too",
397 argument.argument_id, argument.argument_id
398 ),
399 });
400 }
401 if argument.sensitive && is_flag {
402 return Err(CliSpecError {
403 rule: "sensitive_flag",
404 message: format!(
405 "flag `{}` is marked sensitive, but a flag carries no value to redact",
406 argument.argument_id
407 ),
408 });
409 }
410 argument.sensitive = suffixed && !is_flag;
416
417 if let Some(sources) = &argument.sources
422 && sources.accepts(SourceScheme::Prompt)
423 && !argument.sensitive
424 {
425 return Err(CliSpecError {
426 rule: "prompt_source_without_secret",
427 message: format!(
428 "argument `{}` accepts the `prompt` source; rename it to `{}_secret`, or \
429 drop the source — prompting blocks on a terminal for a value that is not \
430 a credential",
431 argument.argument_id, argument.argument_id
432 ),
433 });
434 }
435 }
436 }
437 spec.build()
438}
439
440pub fn cli_help_event(help: &ResolvedHelp) -> Event {
442 json_result(serde_json::json!({
443 "code": "help",
444 "help": help.model(),
445 }))
446 .build()
447}
448
449pub fn cli_version_event(version: &ResolvedVersion) -> Event {
456 crate::cli::build_cli_version(
457 version.name(),
458 version.display_name(),
459 version.version(),
460 version.build(),
461 )
462}
463
464const SHAPES_PROSE: &str = include_str!("cli_reference/shapes.md");
476const CLI_ERRORS_PROSE: &str = include_str!("cli_reference/cli-errors.md");
477
478pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
495 let spec = cli.spec();
496 let name = spec.name.as_str();
497 let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
498 .commands
499 .iter()
500 .filter(|command| !command.combinations.is_empty())
501 .collect();
502 commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
503
504 let path_of = |command: &crate::cli_spec::CommandSpec| {
505 if command.command_path.is_empty() {
506 name.to_string()
507 } else {
508 format!("{name} {}", command.command_path.join(" "))
509 }
510 };
511
512 let mut out = String::new();
513 out.push_str(&format!("# {name} CLI reference\n\n"));
514 out.push_str(&format!(
515 "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
516 ));
517 if let Some(about) = &spec.about {
518 out.push_str(&format!("{about}\n\n"));
519 }
520 out.push_str(&format!(
521 "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
522 typed invocation values, which parameter combinations are legal, output contracts, and \
523 help. An invocation runs only when it matches exactly one registered combination.\n\n"
524 ));
525
526 let baseline = baseline_output(&commands);
531 out.push_str("## Global arguments\n\n");
532 out.push_str(
536 "AFDATA registers these itself, so the syntax in [Commands](#commands) \
537 leaves them out.\n\n",
538 );
539 out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
540 out.push_str(
541 "| `--help` | every command | Every legal shape of that command, complete, plus its \
542 subcommands. JSON by default; `--output plain` for a terminal. |\n",
543 );
544 out.push_str(&format!(
545 "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
546 |\n"
547 ));
548 out.push_str(&format!(
549 "| `--docs` | {name} only | This document, rendered from the registry. |\n"
550 ));
551 if let Some(crate::cli_spec::OutputSpec::Protocol {
552 formats,
553 destinations,
554 default_format,
555 default_destination,
556 ..
557 }) = &baseline
558 {
559 out.push_str(&format!(
560 "| `--output <FORMAT>` | per output contract | Render as {} (default \
561 `{default_format}`). |\n",
562 formats.join(", ")
563 ));
564 out.push_str(&format!(
565 "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
566 to {} (default `{default_destination}`). |\n",
567 destinations.join(", ")
568 ));
569 }
570 out.push_str(
571 "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
572 stream to a file instead. |\n\n",
573 );
574 let baseline_line = baseline.as_ref().map(describe_output);
575 if baseline.is_some() {
578 out.push_str(
579 "Success output is protocol events, on those terms, unless a command's own \
580 **Output** line says otherwise.\n\n",
581 );
582 }
583 out.push_str(SHAPES_PROSE);
584 out.push('\n');
585
586 out.push_str("## Commands\n\n");
587 for command in &commands {
588 let path = path_of(command);
589 let anchor = path.replace(' ', "-");
590 let about = command.about.as_deref().unwrap_or("");
591 out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
592 }
593 out.push('\n');
594
595 for command in &commands {
596 let path = path_of(command);
597 out.push_str(&format!("### `{path}`\n\n"));
598 if let Some(about) = &command.about {
599 out.push_str(&format!("{about}\n\n"));
600 }
601
602 let Some(model) = cli.help(&command.command_path) else {
603 continue;
604 };
605 for shape in &model.shapes {
606 if model.shapes.len() > 1 {
607 let differs = shape.about.as_deref().unwrap_or_default();
608 out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
609 }
610 out.push_str(&format!(
611 "```\n{}\n```\n\n",
612 trim_output_arguments(&shape.usage)
613 ));
614 }
615
616 let combinations: Vec<&crate::cli_spec::Combination> =
617 command.combinations.iter().collect();
618 let contracts = output_contracts(&combinations);
619 let is_baseline =
620 matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
621 if !is_baseline {
622 out.push_str(&render_output(&contracts));
623 }
624
625 let documented: Vec<(&crate::cli_spec::ArgSpec, String)> = command
626 .arguments
627 .iter()
628 .filter_map(|argument| Some((argument, argument.rendered_about()?)))
629 .collect();
630 if !documented.is_empty() {
631 if model.shapes.len() > 1 {
632 out.push_str("Arguments across every shape above:\n\n");
636 }
637 out.push_str("| Argument | Meaning |\n|---|---|\n");
638 for (argument, about) in documented {
639 out.push_str(&format!(
642 "| `{}` | {about} |\n",
643 crate::cli_spec::argument_key(argument)
644 ));
645 }
646 out.push('\n');
647 }
648
649 if let Some(note) = &command.reference_note {
651 out.push_str(note.trim_end());
652 out.push_str("\n\n");
653 }
654 }
655
656 out.push_str("## Exit codes\n\n");
657 out.push_str(
658 "| Code | Meaning |\n|---|---|\n\
659 | 0 | The command ran and succeeded. |\n\
660 | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
661 | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
662 `cli_*` codes below. |\n",
663 );
664 let mut declared_exit_codes: Vec<(u8, &str)> = spec
667 .exit_codes
668 .iter()
669 .map(|exit| (exit.code, exit.meaning.as_str()))
670 .collect();
671 declared_exit_codes.push((
672 4,
673 "Output could not be written (`output_write_failed`); a closed reader is success.",
674 ));
675 declared_exit_codes.sort_by_key(|(code, _)| *code);
676 for (code, meaning) in declared_exit_codes {
677 out.push_str(&format!("| {code} | {meaning} |\n"));
678 }
679 out.push_str(
680 "\nThe split is the useful one for a caller: exit 2 means the call was never made, so \
681 retrying it unchanged cannot help, while exit 1 means it was.\n\n",
682 );
683
684 out.push_str("## CLI errors\n\n");
685 out.push_str(CLI_ERRORS_PROSE);
686 out
687}
688
689fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
692 use crate::cli_spec::OutputSpec;
693 match output {
694 OutputSpec::Raw { file_sinks } => format!(
695 "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
696 strict JSON on stderr",
697 render_file_sinks(file_sinks)
698 ),
699 OutputSpec::Protocol {
700 formats,
701 destinations,
702 default_format,
703 default_destination,
704 file_sinks,
705 ..
706 } => format!(
707 "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
708 (default `{default_destination}`){}",
709 formats.join("/"),
710 destinations.join("/"),
711 render_file_sinks(file_sinks),
712 ),
713 }
714}
715
716fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
718 let mut lines: Vec<String> = Vec::new();
719 for combination in combinations {
720 let line = describe_output(&combination.output);
721 if !lines.contains(&line) {
722 lines.push(line);
723 }
724 }
725 lines
726}
727
728fn baseline_output(
733 commands: &[&crate::cli_spec::CommandSpec],
734) -> Option<crate::cli_spec::OutputSpec> {
735 let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
736 std::collections::BTreeMap::new();
737 for command in commands {
738 let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
739 for combination in &command.combinations {
740 if !contracts.contains(&&combination.output) {
741 contracts.push(&combination.output);
742 }
743 }
744 if let [only] = contracts.as_slice() {
745 let entry = counts
746 .entry(describe_output(only))
747 .or_insert((0, (*only).clone()));
748 entry.0 += 1;
749 }
750 }
751 counts
752 .into_iter()
753 .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
754 .filter(|(_, (count, _))| *count > 1)
755 .map(|(_, (_, spec))| spec)
756}
757
758fn render_output(contracts: &[String]) -> String {
759 match contracts {
760 [] => String::new(),
761 [only] => format!("Output: {only}.\n\n"),
762 many => {
763 let mut out = String::from("Output differs by combination:\n\n");
764 for line in many {
765 out.push_str(&format!("- {line}\n"));
766 }
767 out.push('\n');
768 out
769 }
770 }
771}
772
773fn trim_output_arguments(usage: &str) -> &str {
780 let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
781 .iter()
782 .filter_map(|marker| usage.find(marker))
783 .min();
784 match cut {
785 Some(index) => usage[..index].trim_end(),
786 None => usage,
787 }
788}
789
790fn render_file_sinks(file_sinks: &[String]) -> String {
791 let mut names: Vec<&str> = Vec::new();
792 if file_sinks.iter().any(|sink| sink == "stdout") {
793 names.push("`--stdout-file`");
794 }
795 if file_sinks.iter().any(|sink| sink == "stderr") {
796 names.push("`--stderr-file`");
797 }
798 if names.is_empty() {
799 String::new()
800 } else {
801 format!("; redirect with {}", names.join(" or "))
802 }
803}
804
805pub fn cli_error_event(error: &CliError) -> Event {
815 let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
816 match builder.build() {
817 Ok(event) => event,
818 Err(_) => json_error("cli_error", "failed to build CLI error")
819 .build()
820 .unwrap_or_else(|_| {
821 json_result(serde_json::json!({"code":"internal_cli_error"})).build()
824 }),
825 }
826}
827
828pub fn cli_invocation_invalid_event(detail: &str) -> Event {
846 let builder = json_error("cli_invocation_invalid", detail)
847 .hint("this is a defect in the program, not in the command; report it");
848 match builder.build() {
849 Ok(event) => event,
850 Err(_) => json_error("cli_invocation_invalid", "invocation cannot be dispatched")
851 .build()
852 .unwrap_or_else(|_| {
853 json_result(serde_json::json!({"code":"internal_cli_error"})).build()
856 }),
857 }
858}
859
860#[cfg(test)]
861mod tests {
862 use super::*;
863 use crate::cli_spec::SourceSet;
864 use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
865
866 fn output() -> OutputSpec {
867 OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
868 }
869
870 fn spec_with(argument: ArgSpec) -> CliSpec {
871 let id = argument.argument_id.clone();
872 CliSpec::new("demo", "1").command(
873 CommandSpec::root().arg(argument).combination(
874 Combination::new("only")
875 .action("only")
876 .required([id])
877 .output(output()),
878 ),
879 )
880 }
881
882 #[test]
883 fn a_cli_declares_exit_codes_beyond_afdatas_own() {
884 let spec = CliSpec::new("demo", "1.0.0")
885 .lifecycle_output(output())
886 .exit_code(5, "An application-specific failure.")
887 .exit_code(3, "The command ran and partly succeeded.")
888 .command(CommandSpec::root())
889 .build()
890 .unwrap();
891 let reference = render_cli_reference(&spec);
892 let table = reference
893 .split("## Exit codes")
894 .nth(1)
895 .expect("the reference documents exit codes");
896 let partial = table.find("| 3 | The command ran and partly succeeded. |");
898 let write_failed = table.find("| 5 | An application-specific failure. |");
899 assert!(partial.is_some() && write_failed.is_some(), "{table}");
900 assert!(partial < write_failed, "{table}");
901 }
902
903 #[test]
907 fn a_declared_source_set_renders_itself_into_help_and_docs() {
908 let built = build_afdata_cli(spec_with(
909 ArgSpec::option("--token-secret", "SOURCE")
910 .about("Token this host requires")
911 .sources(SourceSet::config().host_scheme("container", "container:NAME")),
912 ))
913 .expect("registry builds");
914
915 let reference = render_cli_reference(&built);
916 assert!(
917 reference.contains(
918 "Token this host requires (the value, or where to read it: env:NAME, \
919 file[+FORMAT]:PATH[#DOT_PATH], container:NAME, literal:VALUE)"
920 ),
921 "{reference}"
922 );
923
924 let CliOutcome::Help(help) = built
925 .resolve_from(vec!["demo", "--help"])
926 .expect("help resolves")
927 else {
928 panic!("--help must resolve to help");
929 };
930 let model = serde_json::to_value(help.model()).expect("help serializes");
931 let note = model["notes"]["--token-secret"]
932 .as_str()
933 .unwrap_or_default()
934 .to_string();
935 assert!(note.contains("file[+FORMAT]:PATH[#DOT_PATH]"), "{model}");
936 }
937
938 #[test]
941 fn an_unaccepted_scheme_is_an_argv_rejection() {
942 let built = build_afdata_cli(spec_with(
943 ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::config()),
944 ))
945 .expect("registry builds");
946 let error = built
947 .resolve_from(vec!["demo", "--token-secret", "prompt"])
948 .expect_err("prompt is not in config()");
949 assert_eq!(
950 error.rule,
951 crate::cli_spec::CliErrorRule::InvalidArgumentValue
952 );
953 assert!(error.message.contains("env:NAME"), "{}", error.message);
954
955 let outcome = built
957 .resolve_from(vec!["demo", "--token-secret", "env:NAME"])
958 .expect("env is accepted");
959 let CliOutcome::Run(invocation) = outcome else {
960 panic!("must resolve to a run");
961 };
962 assert_eq!(
963 invocation.source("token_secret").unwrap(),
964 &crate::cli_spec::ValueSource::Env("NAME".to_string())
965 );
966 }
967
968 #[test]
971 fn the_prompt_source_is_refused_on_a_non_secret_argument() {
972 let error = build_afdata_cli(spec_with(
973 ArgSpec::option("--label", "LABEL").sources(SourceSet::stream()),
974 ))
975 .expect_err("prompt on a non-secret argument");
976 assert_eq!(error.rule, "prompt_source_without_secret");
977 assert!(
979 build_afdata_cli(spec_with(
980 ArgSpec::option("--token-secret", "SOURCE").sources(SourceSet::stream())
981 ))
982 .is_ok()
983 );
984 }
985
986 #[test]
987 fn secret_suffix_drives_the_sensitive_bit() {
988 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
989 let argument = &built.spec().commands[0].arguments[0];
990 assert!(argument.sensitive);
991 }
992
993 #[test]
994 fn sensitive_without_the_suffix_fails_the_build() {
995 let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
996 .unwrap_err();
997 assert_eq!(error.rule, "sensitive_without_secret_suffix");
998 }
999
1000 #[test]
1001 fn a_plain_argument_stays_insensitive() {
1002 let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
1003 assert!(!built.spec().commands[0].arguments[0].sensitive);
1004 }
1005
1006 #[test]
1010 fn version_events_carry_the_full_documented_payload() {
1011 let built = CliSpec::new("demo", "1.2.3")
1012 .display_name("Demo Tool")
1013 .build_id("abc1234")
1014 .command(CommandSpec::root())
1015 .build()
1016 .unwrap();
1017 let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
1018 else {
1019 panic!("expected a version outcome");
1020 };
1021 assert_eq!(
1022 cli_version_event(&version).as_value(),
1023 &serde_json::json!({
1024 "kind": "result",
1025 "result": {
1026 "code": "version",
1027 "name": "demo",
1028 "display_name": "Demo Tool",
1029 "version": "1.2.3",
1030 "build": "abc1234",
1031 },
1032 "trace": {},
1033 })
1034 );
1035 }
1036
1037 #[test]
1038 fn version_events_omit_absent_metadata() {
1039 let built = CliSpec::new("demo", "1.2.3")
1040 .command(CommandSpec::root())
1041 .build()
1042 .unwrap();
1043 let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
1044 else {
1045 panic!("expected a version outcome");
1046 };
1047 let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
1048 assert!(!payload.contains("display_name"), "{payload}");
1049 assert!(!payload.contains("build"), "{payload}");
1050 }
1051
1052 #[test]
1053 fn cli_error_events_never_carry_a_secret_value() {
1054 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1055 let error = built
1056 .resolve_from([
1057 "demo",
1058 "--dsn-secret",
1059 "postgres://user:password@example.test/db",
1060 "--unknown",
1061 ])
1062 .unwrap_err();
1063 let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
1064 assert!(!serialized.contains("password"));
1065 assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
1067 assert!(serialized.contains("run `demo --help`"));
1070 }
1071
1072 #[test]
1077 fn invocation_invalid_event_is_a_program_defect_not_a_usage_error() {
1078 let event = cli_invocation_invalid_event("no handler for this registry's invocation");
1079 let serialized = serde_json::to_string(event.as_value()).unwrap();
1080
1081 assert!(serialized.contains("\"code\":\"cli_invocation_invalid\""));
1082 assert!(serialized.contains("no handler for this registry's invocation"));
1083 assert!(serialized.contains("defect in the program"));
1086 assert!(
1087 crate::validate_protocol_event(event.as_value(), true).is_ok(),
1088 "the helper must emit a strict event: {serialized}"
1089 );
1090 }
1091
1092 #[test]
1093 fn a_secret_named_flag_is_not_marked_sensitive() {
1094 let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
1098 let argument = built
1099 .spec()
1100 .commands
1101 .iter()
1102 .flat_map(|command| &command.arguments)
1103 .find(|argument| argument.argument_id == "reveal_secret")
1104 .expect("the flag is registered");
1105 assert!(!argument.sensitive, "a flag has no value to redact");
1106 }
1107
1108 #[test]
1109 fn marking_a_flag_sensitive_is_a_contradiction() {
1110 let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
1111 .expect_err("a sensitive flag must not build");
1112 assert_eq!(error.rule, "sensitive_flag");
1113 }
1114
1115 #[test]
1116 fn a_value_carrying_secret_argument_is_still_marked() {
1117 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
1118 let argument = built
1119 .spec()
1120 .commands
1121 .iter()
1122 .flat_map(|command| &command.arguments)
1123 .find(|argument| argument.argument_id == "dsn_secret")
1124 .expect("the option is registered");
1125 assert!(argument.sensitive, "an option with a value still counts");
1126 }
1127
1128 #[test]
1129 fn an_invalid_argument_stop_is_a_usage_error() {
1130 let stop = CliStop::invalid_argument("expected one character", "pass a single character");
1131 assert_eq!(stop.exit_code(), 2);
1132 let value = stop.event().as_value();
1133 assert_eq!(value["kind"], "error");
1134 assert_eq!(value["error"]["code"], "cli_invalid_argument_value");
1135 assert_eq!(value["error"]["hint"], "pass a single character");
1136 let (event, code) = stop.into_parts();
1137 assert_eq!(code, 2);
1138 assert_eq!(
1139 event.as_value()["error"]["message"],
1140 "expected one character"
1141 );
1142 }
1143
1144 #[test]
1145 fn a_failed_read_stops_as_a_program_defect() {
1146 let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
1147 let CliOutcome::Run(invocation) = built
1148 .resolve_from(["demo", "--label", "a"])
1149 .expect("resolves")
1150 else {
1151 panic!("must resolve to a run");
1152 };
1153 let error = invocation.text("lable").unwrap_err();
1154 let stop = CliStop::from(error);
1155 assert_eq!(stop.exit_code(), 1);
1156 assert_eq!(
1157 stop.event().as_value()["error"]["code"],
1158 "cli_invocation_invalid"
1159 );
1160 assert!(
1161 stop.event().as_value()["error"]["message"]
1162 .as_str()
1163 .is_some_and(|message| message.contains("lable") && message.contains("only")),
1164 "{:?}",
1165 stop.event()
1166 );
1167 }
1168
1169 #[test]
1170 fn an_argv_rejection_stops_with_its_rule_code_and_exit_two() {
1171 let built = build_afdata_cli(spec_with(ArgSpec::option("--label", "LABEL"))).unwrap();
1172 let error = built
1173 .resolve_from(["demo", "--nope"])
1174 .expect_err("unknown argument");
1175 let stop = CliStop::from(error);
1176 assert_eq!(stop.exit_code(), 2);
1177 assert_eq!(
1178 stop.event().as_value()["error"]["code"],
1179 "cli_unknown_argument"
1180 );
1181 }
1182}