agent_first_data/cli_spec/
help.rs1use super::*;
2use serde::Serialize;
3use std::collections::{BTreeMap, BTreeSet};
4
5#[derive(Clone, Debug, PartialEq, Serialize)]
10pub struct CliHelpV2 {
11 pub schema: String,
12 pub command_path: String,
13 #[serde(skip_serializing_if = "Option::is_none")]
14 pub about: Option<String>,
15 #[serde(default, skip_serializing_if = "Vec::is_empty")]
22 pub shapes: Vec<CliShape>,
23 #[serde(default, skip_serializing_if = "Vec::is_empty")]
24 pub subcommands: Vec<String>,
25 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
28 pub notes: BTreeMap<String, String>,
29 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
31 pub defaults: BTreeMap<String, CliValue>,
32}
33
34#[derive(Clone, Debug, PartialEq, Serialize)]
36pub struct CliShape {
37 pub id: String,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub about: Option<String>,
40 pub usage: String,
41}
42
43#[derive(Clone, Debug, PartialEq)]
45pub struct ResolvedHelp {
46 pub(super) model: CliHelpV2,
47 pub(super) output: OutputPlan,
48}
49
50impl ResolvedHelp {
51 pub fn model(&self) -> &CliHelpV2 {
52 &self.model
53 }
54
55 pub fn output_plan(&self) -> &OutputPlan {
56 &self.output
57 }
58
59 pub fn plain(&self) -> String {
60 let mut output = String::new();
61 if let Some(about) = &self.model.about {
62 output.push_str(about);
63 output.push_str("\n\n");
64 }
65 for shape in &self.model.shapes {
66 if self.model.shapes.len() > 1 {
67 let about = shape.about.as_deref().unwrap_or_default();
68 output.push_str(&format!("{} {about}\n", shape.id));
69 }
70 output.push_str(&shape.usage);
71 output.push('\n');
72 }
73 if !self.model.notes.is_empty() {
78 output.push('\n');
79 let width = self
80 .model
81 .notes
82 .keys()
83 .map(String::len)
84 .max()
85 .unwrap_or_default();
86 for (name, note) in &self.model.notes {
87 output.push_str(&format!(" {name:<width$} {note}\n"));
88 }
89 }
90 if !self.model.defaults.is_empty() {
91 output.push_str("\ndefaults:");
92 output.push(' ');
93 output.push_str(&describe_defaults(&self.model.defaults, " "));
94 output.push('\n');
95 }
96 for (index, subcommand) in self.model.subcommands.iter().enumerate() {
97 output.push_str(if index == 0 {
98 "\nmore: "
99 } else {
100 " "
101 });
102 output.push_str(subcommand);
103 output.push('\n');
104 }
105 output
106 }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq)]
111pub struct ResolvedVersion {
112 pub(super) name: String,
113 pub(super) version: String,
114 pub(super) display_name: Option<String>,
115 pub(super) build: Option<String>,
116 pub(super) output: OutputPlan,
117}
118
119impl ResolvedVersion {
120 pub fn output_plan(&self) -> &OutputPlan {
121 &self.output
122 }
123
124 pub fn name(&self) -> &str {
125 &self.name
126 }
127
128 pub fn version(&self) -> &str {
129 &self.version
130 }
131
132 pub fn display_name(&self) -> Option<&str> {
133 self.display_name.as_deref()
134 }
135
136 pub fn build(&self) -> Option<&str> {
137 self.build.as_deref()
138 }
139}
140
141#[derive(Clone, Debug, PartialEq)]
147pub struct ResolvedDocs {
148 pub(super) output: OutputPlan,
149 pub(super) registry: BuiltCliSpec,
150}
151
152impl ResolvedDocs {
153 pub fn registry(&self) -> &BuiltCliSpec {
154 &self.registry
155 }
156 pub fn output_plan(&self) -> &OutputPlan {
157 &self.output
158 }
159}
160
161pub(super) fn combination_usage(
162 command: &CommandSpec,
163 combination: &Combination,
164 command_path: &str,
165 hidden_defaults: Option<&BTreeSet<String>>,
166 include_output_usage: bool,
167) -> (String, BTreeMap<String, String>, BTreeMap<String, CliValue>) {
168 let mut parts = vec![command_path.to_string()];
169 let mut notes = BTreeMap::new();
170 let mut defaults = BTreeMap::new();
171 for argument in &command.arguments {
172 let id = argument.argument_id.as_str();
173 let fixed = combination.fixed.get(id);
174 let required = combination.required.iter().any(|candidate| candidate == id);
175 let optional = combination.optional.iter().any(|candidate| candidate == id);
176 if fixed.is_none() && !required && !optional {
177 continue;
178 }
179 let default_satisfies_fixed = fixed.is_some_and(|fixed| {
184 argument
185 .default
186 .as_ref()
187 .and_then(CliValue::as_str)
188 .is_some_and(|value| fixed.values().iter().any(|fixed| fixed == value))
189 });
190 let omittable = optional || default_satisfies_fixed;
191 let visible = !argument.sensitive && !hidden_defaults.is_some_and(|ids| ids.contains(id));
192 let token = render_argument(argument, fixed, omittable, visible);
193 parts.push(token);
194 let key = argument_key(argument);
195 if let Some(about) = argument.rendered_about() {
196 notes.insert(key.clone(), about);
197 }
198 if omittable
202 && visible
203 && let Some(default) = &argument.default
204 {
205 defaults.insert(key, default.clone());
206 }
207 }
208 match &combination.output {
209 OutputSpec::Raw { file_sinks } => {
210 if include_output_usage {
211 render_file_sinks(&mut parts, file_sinks);
212 }
213 }
214 OutputSpec::Protocol {
215 formats,
216 destinations,
217 default_format,
218 default_destination,
219 file_sinks,
220 ..
221 } => {
222 if include_output_usage {
223 parts.push(format!("[--output <{}>]", formats.join("|")));
224 parts.push(format!("[--output-to <{}>]", destinations.join("|")));
225 render_file_sinks(&mut parts, file_sinks);
226 }
227 if file_sinks.iter().any(|sink| sink == "stdout")
228 && let Some(destination) = destinations
229 .iter()
230 .find(|destination| !stdout_file_allowed(destination))
231 {
232 notes.insert(
233 "--stdout-file".into(),
234 format!("Cannot be combined with --output-to {destination}."),
235 );
236 }
237 defaults.insert(
238 "--output".to_string(),
239 CliValue::String(default_format.clone()),
240 );
241 defaults.insert(
242 "--output-to".to_string(),
243 CliValue::String(default_destination.clone()),
244 );
245 }
246 }
247 (parts.join(" "), notes, defaults)
248}
249
250pub(crate) struct HelpCatalog {
253 pub(crate) model: CliHelpV2,
255 pub(crate) shape_defaults: Vec<BTreeMap<String, CliValue>>,
256}
257
258impl HelpCatalog {
259 pub(super) fn into_help_model(self) -> CliHelpV2 {
260 let mut model = self.model;
261 let mut conflicting = BTreeSet::new();
262
263 for (shape, defaults) in model.shapes.iter_mut().zip(self.shape_defaults) {
264 if defaults.is_empty() {
265 continue;
266 }
267
268 let about = shape.about.get_or_insert_with(String::new);
272 about.push_str(&format!(
273 " (defaults {} when omitted)",
274 describe_defaults(&defaults, ", ")
275 ));
276 for (name, value) in defaults {
277 if let Some(previous) = model.defaults.get(&name) {
278 if previous != &value {
279 conflicting.insert(name);
280 }
281 } else {
282 model.defaults.insert(name, value);
283 }
284 }
285 }
286 model.defaults.retain(|name, _| !conflicting.contains(name));
287 model
288 }
289}
290
291fn describe_defaults(defaults: &BTreeMap<String, CliValue>, separator: &str) -> String {
292 defaults
293 .iter()
294 .map(|(name, value)| format!("{name}={}", display_help_default(value)))
295 .collect::<Vec<_>>()
296 .join(separator)
297}
298
299pub(crate) fn display_help_default(value: &CliValue) -> String {
301 match value {
302 CliValue::Bool(value) => value.to_string(),
303 CliValue::String(value) => display_help_string(value),
304 CliValue::Json(value) => value.clone(),
305 CliValue::I64(value) => value.to_string(),
306 CliValue::FiniteF64(value) => value.to_string(),
307 CliValue::List(values) => values
308 .iter()
309 .map(display_help_default)
310 .collect::<Vec<_>>()
311 .join(","),
312 }
313}
314
315fn display_help_string(value: &str) -> String {
316 if value.is_empty()
317 || value.contains(|ch: char| {
318 ch.is_whitespace() || ch.is_control() || matches!(ch, ',' | '"' | '\\')
319 })
320 {
321 format!("{value:?}")
322 } else {
323 value.to_owned()
324 }
325}
326
327pub(crate) fn argument_key(argument: &ArgSpec) -> String {
335 match &argument.syntax {
336 ArgSyntax::Long { name } => name.clone(),
337 ArgSyntax::Positional { .. } => argument
338 .value_name
339 .clone()
340 .unwrap_or_else(|| argument.argument_id.clone()),
341 }
342}
343
344fn render_argument(
345 argument: &ArgSpec,
346 fixed: Option<&FixedValue>,
347 optional: bool,
348 show_values: bool,
349) -> String {
350 let value = if argument.value_type == ArgValueType::Flag {
351 String::new()
352 } else if let Some(fixed) = fixed.filter(|_| show_values) {
353 match fixed {
354 FixedValue::Value(value) => display_usage_choice(value),
355 FixedValue::OneOf { one_of } => render_usage_choices(one_of),
356 }
357 } else if show_values && !argument.enum_values.is_empty() {
358 render_usage_choices(&argument.enum_values)
362 } else {
363 format!(
364 "<{}>",
365 argument
366 .value_name
367 .as_deref()
368 .unwrap_or(argument.argument_id.as_str())
369 )
370 };
371 let mut token = match &argument.syntax {
372 ArgSyntax::Long { name } => {
373 if value.is_empty() {
374 name.clone()
375 } else {
376 format!("{name} {value}")
377 }
378 }
379 ArgSyntax::Positional { .. } => value,
380 };
381 if argument.repeatable {
382 token.push_str("...");
383 }
384 if optional {
385 token = format!("[{token}]");
386 }
387 token
388}
389
390fn render_usage_choices(values: &[String]) -> String {
391 let choices = values
392 .iter()
393 .map(|value| display_usage_choice(value))
394 .collect::<Vec<_>>();
395 format!("<{}>", choices.join("|"))
396}
397
398fn display_usage_choice(value: &str) -> String {
399 if value.contains(['<', '>', '[', ']', '|']) {
400 format!("{value:?}")
401 } else {
402 display_help_string(value)
403 }
404}
405
406fn render_file_sinks(parts: &mut Vec<String>, file_sinks: &[String]) {
407 if file_sinks.iter().any(|sink| sink == "stdout") {
408 parts.push("[--stdout-file <PATH>]".to_string());
409 }
410 if file_sinks.iter().any(|sink| sink == "stderr") {
411 parts.push("[--stderr-file <PATH>]".to_string());
412 }
413}