1use crate::cli_spec::{
10 ArgValueType, BuiltCliSpec, CliError, CliSpec, CliSpecError, ResolvedHelp, ResolvedVersion,
11};
12use crate::protocol::{Event, json_error, json_result};
13
14pub fn build_afdata_cli(mut spec: CliSpec) -> Result<BuiltCliSpec, CliSpecError> {
24 for command in &mut spec.commands {
25 for argument in &mut command.arguments {
26 let suffixed = argument.argument_id.ends_with("_secret");
27 let is_flag = matches!(argument.value_type, ArgValueType::Flag);
28 if argument.sensitive && !suffixed {
29 return Err(CliSpecError {
30 rule: "sensitive_without_secret_suffix",
31 message: format!(
32 "argument `{}` is marked sensitive; rename it to `{}_secret` so AFDATA \
33 redaction covers it too",
34 argument.argument_id, argument.argument_id
35 ),
36 });
37 }
38 if argument.sensitive && is_flag {
39 return Err(CliSpecError {
40 rule: "sensitive_flag",
41 message: format!(
42 "flag `{}` is marked sensitive, but a flag carries no value to redact",
43 argument.argument_id
44 ),
45 });
46 }
47 argument.sensitive = suffixed && !is_flag;
53 }
54 }
55 spec.build()
56}
57
58pub fn cli_help_event(help: &ResolvedHelp) -> Event {
60 json_result(serde_json::json!({
61 "code": "help",
62 "help": help.model(),
63 }))
64 .build()
65}
66
67pub fn cli_version_event(version: &ResolvedVersion) -> Event {
74 crate::cli::build_cli_version(
75 version.name(),
76 version.display_name(),
77 version.version(),
78 version.build(),
79 )
80}
81
82pub fn render_cli_reference(cli: &BuiltCliSpec) -> String {
99 let spec = cli.spec();
100 let name = spec.name.as_str();
101 let mut commands: Vec<&crate::cli_spec::CommandSpec> = spec
102 .commands
103 .iter()
104 .filter(|command| !command.combinations.is_empty())
105 .collect();
106 commands.sort_by(|left, right| left.command_path.cmp(&right.command_path));
107
108 let path_of = |command: &crate::cli_spec::CommandSpec| {
109 if command.command_path.is_empty() {
110 name.to_string()
111 } else {
112 format!("{name} {}", command.command_path.join(" "))
113 }
114 };
115
116 let mut out = String::new();
117 out.push_str(&format!("# {name} CLI reference\n\n"));
118 out.push_str(&format!(
119 "<!-- Generated by `{name} --docs`. Do not edit by hand. -->\n\n"
120 ));
121 if let Some(about) = &spec.about {
122 out.push_str(&format!("{about}\n\n"));
123 }
124 out.push_str(&format!(
125 "`{name}` is compiled from a closed `cli-spec-v1` registry: one source for argv parsing, \
126 typed invocation values, which parameter combinations are legal, output contracts, and \
127 help. An invocation runs only when it matches exactly one registered combination.\n\n"
128 ));
129
130 let baseline = baseline_output(&commands);
135 out.push_str("## Global arguments\n\n");
136 out.push_str(
137 "AFDATA registers these; no command declares them, and the syntax in \
138 [Commands](#commands) leaves them out.\n\n",
139 );
140 out.push_str("| Argument | Where | What it does |\n|---|---|---|\n");
141 out.push_str(
142 "| `--help` | every command | Every legal shape of that command, complete, plus its \
143 subcommands. JSON by default; `--output plain` for a terminal. |\n",
144 );
145 out.push_str(&format!(
146 "| `--version` | {name} only | Name, version, and build identity as one protocol result. \
147 |\n"
148 ));
149 out.push_str(&format!(
150 "| `--docs` | {name} only | This document, rendered from the registry. |\n"
151 ));
152 if let Some(crate::cli_spec::OutputSpec::Protocol {
153 formats,
154 destinations,
155 default_format,
156 default_destination,
157 ..
158 }) = &baseline
159 {
160 out.push_str(&format!(
161 "| `--output <FORMAT>` | per output contract | Render as {} (default \
162 `{default_format}`). |\n",
163 formats.join(", ")
164 ));
165 out.push_str(&format!(
166 "| `--output-to <DESTINATION>` | per output contract | Route results and diagnostics \
167 to {} (default `{default_destination}`). |\n",
168 destinations.join(", ")
169 ));
170 }
171 out.push_str(
172 "| `--stdout-file <PATH>`, `--stderr-file <PATH>` | per output contract | Append that \
173 stream to a file instead. |\n\n",
174 );
175 let baseline_line = baseline.as_ref().map(describe_output);
176 if baseline.is_some() {
179 out.push_str(
180 "Success output is protocol events, on those terms, unless a command's own \
181 **Output** line says otherwise.\n\n",
182 );
183 }
184 out.push_str(
185 "A **shape** is one legal set of arguments that may appear together, under a stable id. \
186 Where a command has more than one, each id is a heading below. `--help` returns them \
187 all at once, so discovering a command costs one call; there is no recursive mode across \
188 commands, and this document is that view.\n\n",
189 );
190
191 out.push_str("## Commands\n\n");
192 for command in &commands {
193 let path = path_of(command);
194 let anchor = path.replace(' ', "-");
195 let about = command.about.as_deref().unwrap_or("");
196 out.push_str(&format!("- [`{path}`](#{anchor}) — {about}\n"));
197 }
198 out.push('\n');
199
200 for command in &commands {
201 let path = path_of(command);
202 out.push_str(&format!("### `{path}`\n\n"));
203 if let Some(about) = &command.about {
204 out.push_str(&format!("{about}\n\n"));
205 }
206
207 let Some(model) = cli.help(&command.command_path) else {
208 continue;
209 };
210 for shape in &model.shapes {
211 if model.shapes.len() > 1 {
212 let differs = shape.about.as_deref().unwrap_or_default();
213 out.push_str(&format!("#### `{}` — {differs}\n\n", shape.id));
214 }
215 out.push_str(&format!(
216 "```\n{}\n```\n\n",
217 trim_output_arguments(&shape.usage)
218 ));
219 }
220
221 let combinations: Vec<&crate::cli_spec::Combination> =
222 command.combinations.iter().collect();
223 let contracts = output_contracts(&combinations);
224 let is_baseline =
225 matches!((contracts.as_slice(), &baseline_line), ([only], Some(line)) if only == line);
226 if !is_baseline {
227 out.push_str(&render_output(&contracts));
228 }
229
230 let documented: Vec<&crate::cli_spec::ArgSpec> = command
231 .arguments
232 .iter()
233 .filter(|argument| argument.about.is_some())
234 .collect();
235 if !documented.is_empty() {
236 if model.shapes.len() > 1 {
237 out.push_str("Arguments across every shape above:\n\n");
241 }
242 out.push_str("| Argument | Meaning |\n|---|---|\n");
243 for argument in documented {
244 let about = argument.about.as_deref().unwrap_or_default();
245 out.push_str(&format!(
248 "| `{}` | {about} |\n",
249 crate::cli_spec::argument_key(argument)
250 ));
251 }
252 out.push('\n');
253 }
254 }
255
256 out.push_str("## Exit codes\n\n");
257 out.push_str(
258 "| Code | Meaning |\n|---|---|\n\
259 | 0 | The command ran and succeeded. |\n\
260 | 1 | The command ran and failed. The event carries a domain `error.code`. |\n\
261 | 2 | The invocation was rejected before anything ran. `error.code` is one of the \
262 `cli_*` codes below. |\n\n\
263 The split is the useful one for a caller: exit 2 means the call was never made, so \
264 retrying it unchanged cannot help, while exit 1 means it was.\n\n",
265 );
266
267 out.push_str("## CLI errors\n\n");
268 out.push_str(
269 "Every structural failure emits one strict JSON `kind:\"error\"` event on stderr, leaves \
270 stdout empty, and exits 2. The `code` names the failure — `cli_unknown_argument` for an \
271 unknown spelling, `cli_unregistered_combination` for registered arguments in a mixture \
272 that is not, and one each for `cli_unknown_command`, `cli_missing_argument_value`, \
273 `cli_invalid_argument_value`, `cli_duplicate_argument`, `cli_unexpected_positional`, and \
274 `cli_invalid_utf8`. `message` names the offending argument and `hint` gives the command \
275 to run next; neither ever quotes a raw value, including secrets. These are decided \
276 before any config, secret source, filesystem, network, or domain I/O.\n\n\
277 Domain failures (exit 1) carry their own stable `error.code` instead, drawn from \
278 whatever this tool defines rather than from the `cli_*` set. No error message quotes a \
279 raw value it was given — an error event is routinely logged, and the input may hold \
280 secrets.\n",
281 );
282 out
283}
284
285fn describe_output(output: &crate::cli_spec::OutputSpec) -> String {
288 use crate::cli_spec::OutputSpec;
289 match output {
290 OutputSpec::Raw { file_sinks } => format!(
291 "raw bytes on success; rejects `--output` and `--output-to`{}. Failures are still \
292 strict JSON on stderr",
293 render_file_sinks(file_sinks)
294 ),
295 OutputSpec::Protocol {
296 formats,
297 destinations,
298 default_format,
299 default_destination,
300 file_sinks,
301 ..
302 } => format!(
303 "protocol events; `--output` {} (default `{default_format}`), `--output-to` {} \
304 (default `{default_destination}`){}",
305 formats.join("/"),
306 destinations.join("/"),
307 render_file_sinks(file_sinks),
308 ),
309 }
310}
311
312fn output_contracts(combinations: &[&crate::cli_spec::Combination]) -> Vec<String> {
314 let mut lines: Vec<String> = Vec::new();
315 for combination in combinations {
316 let line = describe_output(&combination.output);
317 if !lines.contains(&line) {
318 lines.push(line);
319 }
320 }
321 lines
322}
323
324fn baseline_output(
329 commands: &[&crate::cli_spec::CommandSpec],
330) -> Option<crate::cli_spec::OutputSpec> {
331 let mut counts: std::collections::BTreeMap<String, (usize, crate::cli_spec::OutputSpec)> =
332 std::collections::BTreeMap::new();
333 for command in commands {
334 let mut contracts: Vec<&crate::cli_spec::OutputSpec> = Vec::new();
335 for combination in &command.combinations {
336 if !contracts.contains(&&combination.output) {
337 contracts.push(&combination.output);
338 }
339 }
340 if let [only] = contracts.as_slice() {
341 let entry = counts
342 .entry(describe_output(only))
343 .or_insert((0, (*only).clone()));
344 entry.0 += 1;
345 }
346 }
347 counts
348 .into_iter()
349 .max_by(|left, right| left.1.0.cmp(&right.1.0).then_with(|| right.0.cmp(&left.0)))
350 .filter(|(_, (count, _))| *count > 1)
351 .map(|(_, (_, spec))| spec)
352}
353
354fn render_output(contracts: &[String]) -> String {
355 match contracts {
356 [] => String::new(),
357 [only] => format!("Output: {only}.\n\n"),
358 many => {
359 let mut out = String::from("Output differs by combination:\n\n");
360 for line in many {
361 out.push_str(&format!("- {line}\n"));
362 }
363 out.push('\n');
364 out
365 }
366 }
367}
368
369fn trim_output_arguments(usage: &str) -> &str {
376 let cut = ["[--output ", "[--stdout-file ", "[--stderr-file "]
377 .iter()
378 .filter_map(|marker| usage.find(marker))
379 .min();
380 match cut {
381 Some(index) => usage[..index].trim_end(),
382 None => usage,
383 }
384}
385
386fn render_file_sinks(file_sinks: &[String]) -> String {
387 let mut names: Vec<&str> = Vec::new();
388 if file_sinks.iter().any(|sink| sink == "stdout") {
389 names.push("`--stdout-file`");
390 }
391 if file_sinks.iter().any(|sink| sink == "stderr") {
392 names.push("`--stderr-file`");
393 }
394 if names.is_empty() {
395 String::new()
396 } else {
397 format!("; redirect with {}", names.join(" or "))
398 }
399}
400
401pub fn cli_error_event(error: &CliError) -> Event {
411 let builder = json_error(error.rule.code(), &error.message).hint(&error.hint);
412 match builder.build() {
413 Ok(event) => event,
414 Err(_) => json_error("cli_error", "failed to build CLI error")
415 .build()
416 .unwrap_or_else(|_| {
417 json_result(serde_json::json!({"code":"internal_cli_error"})).build()
420 }),
421 }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427 use crate::cli_spec::{ArgSpec, CliOutcome, Combination, CommandSpec, OutputSpec};
428
429 fn output() -> OutputSpec {
430 OutputSpec::protocol_finite(["json"], ["split"], "json", "split")
431 }
432
433 fn spec_with(argument: ArgSpec) -> CliSpec {
434 let id = argument.argument_id.clone();
435 CliSpec::new("demo", "1").command(
436 CommandSpec::root().arg(argument).combination(
437 Combination::new("only")
438 .action("only")
439 .required([id])
440 .output(output()),
441 ),
442 )
443 }
444
445 #[test]
446 fn secret_suffix_drives_the_sensitive_bit() {
447 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
448 let argument = &built.spec().commands[0].arguments[0];
449 assert!(argument.sensitive);
450 }
451
452 #[test]
453 fn sensitive_without_the_suffix_fails_the_build() {
454 let error = build_afdata_cli(spec_with(ArgSpec::option("--token", "TOKEN").sensitive()))
455 .unwrap_err();
456 assert_eq!(error.rule, "sensitive_without_secret_suffix");
457 }
458
459 #[test]
460 fn a_plain_argument_stays_insensitive() {
461 let built = build_afdata_cli(spec_with(ArgSpec::option("--host", "HOST"))).unwrap();
462 assert!(!built.spec().commands[0].arguments[0].sensitive);
463 }
464
465 #[test]
469 fn version_events_carry_the_full_documented_payload() {
470 let built = CliSpec::new("demo", "1.2.3")
471 .display_name("Demo Tool")
472 .build_id("abc1234")
473 .command(CommandSpec::root())
474 .build()
475 .unwrap();
476 let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
477 else {
478 panic!("expected a version outcome");
479 };
480 assert_eq!(
481 cli_version_event(&version).as_value(),
482 &serde_json::json!({
483 "kind": "result",
484 "result": {
485 "code": "version",
486 "name": "demo",
487 "display_name": "Demo Tool",
488 "version": "1.2.3",
489 "build": "abc1234",
490 },
491 "trace": {},
492 })
493 );
494 }
495
496 #[test]
497 fn version_events_omit_absent_metadata() {
498 let built = CliSpec::new("demo", "1.2.3")
499 .command(CommandSpec::root())
500 .build()
501 .unwrap();
502 let CliOutcome::Version(version) = built.resolve_from(["demo", "--version"]).unwrap()
503 else {
504 panic!("expected a version outcome");
505 };
506 let payload = serde_json::to_string(cli_version_event(&version).as_value()).unwrap();
507 assert!(!payload.contains("display_name"), "{payload}");
508 assert!(!payload.contains("build"), "{payload}");
509 }
510
511 #[test]
512 fn cli_error_events_never_carry_a_secret_value() {
513 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
514 let error = built
515 .resolve_from([
516 "demo",
517 "--dsn-secret",
518 "postgres://user:password@example.test/db",
519 "--unknown",
520 ])
521 .unwrap_err();
522 let serialized = serde_json::to_string(cli_error_event(&error).as_value()).unwrap();
523 assert!(!serialized.contains("password"));
524 assert!(serialized.contains("\"code\":\"cli_unknown_argument\""));
526 assert!(serialized.contains("run `demo --help`"));
529 }
530
531 #[test]
532 fn a_secret_named_flag_is_not_marked_sensitive() {
533 let built = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret"))).unwrap();
537 let argument = built
538 .spec()
539 .commands
540 .iter()
541 .flat_map(|command| &command.arguments)
542 .find(|argument| argument.argument_id == "reveal_secret")
543 .expect("the flag is registered");
544 assert!(!argument.sensitive, "a flag has no value to redact");
545 }
546
547 #[test]
548 fn marking_a_flag_sensitive_is_a_contradiction() {
549 let error = build_afdata_cli(spec_with(ArgSpec::flag("--reveal-secret").sensitive()))
550 .expect_err("a sensitive flag must not build");
551 assert_eq!(error.rule, "sensitive_flag");
552 }
553
554 #[test]
555 fn a_value_carrying_secret_argument_is_still_marked() {
556 let built = build_afdata_cli(spec_with(ArgSpec::option("--dsn-secret", "DSN"))).unwrap();
557 let argument = built
558 .spec()
559 .commands
560 .iter()
561 .flat_map(|command| &command.arguments)
562 .find(|argument| argument.argument_id == "dsn_secret")
563 .expect("the option is registered");
564 assert!(argument.sensitive, "an option with a value still counts");
565 }
566}