1use crate::parsers::api::{ApiItem, ApiKind, DocComment};
10use crate::pulse::extract::surface::{Surface, SurfaceItem};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct CliCommand {
15 pub path: Vec<String>,
17 pub about: Option<String>,
18 pub doc: Option<DocComment>,
19 pub args: Vec<CliArg>,
20 pub subcommands: Vec<CliCommand>,
21 pub hidden: bool,
22 pub file: String,
23 pub line: u32,
24}
25
26#[derive(Debug, Clone, PartialEq)]
27pub struct CliArg {
28 pub field: String,
29 pub long: Option<String>,
30 pub short: Option<char>,
31 pub positional: bool,
32 pub value_name: Option<String>,
33 pub ty: String,
35 pub default: Option<String>,
36 pub flag: bool,
37 pub multiple: bool,
38 pub required: bool,
39 pub hidden: bool,
40 pub doc: Option<DocComment>,
41}
42
43impl CliArg {
44 pub fn usage(&self) -> String {
46 let value = self
47 .value_name
48 .clone()
49 .unwrap_or_else(|| self.field.to_ascii_uppercase());
50 if self.positional {
51 let v = format!("<{value}>");
52 return if self.multiple { format!("{v}...") } else { v };
53 }
54 let mut parts = Vec::new();
55 if let Some(s) = self.short {
56 parts.push(format!("-{s}"));
57 }
58 if let Some(l) = &self.long {
59 parts.push(format!("--{l}"));
60 }
61 let mut u = parts.join(", ");
62 if !self.flag {
63 u.push_str(&format!(" <{value}>"));
64 }
65 u
66 }
67}
68
69impl CliCommand {
70 pub fn name(&self) -> &str {
71 self.path.last().map(String::as_str).unwrap_or("")
72 }
73
74 pub fn usage(&self) -> String {
76 let mut u = self.path.join(" ");
77 if self.args.iter().any(|a| !a.positional && !a.hidden) {
78 u.push_str(" [OPTIONS]");
79 }
80 for a in self.args.iter().filter(|a| a.positional && !a.hidden) {
81 let s = a.usage();
82 if a.required {
83 u.push_str(&format!(" {s}"));
84 } else {
85 u.push_str(&format!(" [{s}]"));
86 }
87 }
88 if self.subcommands.iter().any(|c| !c.hidden) {
89 u.push_str(" <COMMAND>");
90 }
91 u
92 }
93
94 pub fn walk(&self) -> Vec<&CliCommand> {
96 let mut out = vec![self];
97 for c in &self.subcommands {
98 out.extend(c.walk());
99 }
100 out
101 }
102}
103
104pub fn kebab(s: &str) -> String {
106 let mut out = String::new();
107 for (i, c) in s.chars().enumerate() {
108 if c.is_ascii_uppercase() {
109 if i > 0 {
110 out.push('-');
111 }
112 out.push(c.to_ascii_lowercase());
113 } else if c == '_' {
114 out.push('-');
115 } else {
116 out.push(c);
117 }
118 }
119 out
120}
121
122fn attr_args(attr: &str, name: &str) -> Option<Vec<(String, Option<String>)>> {
124 let inner = attr
125 .strip_prefix(name)?
126 .trim()
127 .strip_prefix('(')?
128 .strip_suffix(')')?;
129 let mut out = Vec::new();
130 let (mut depth, mut in_str, mut cur) = (0i32, false, String::new());
131 for c in inner.chars() {
132 match c {
133 '"' => {
134 in_str = !in_str;
135 cur.push(c);
136 }
137 '(' | '[' | '{' if !in_str => {
138 depth += 1;
139 cur.push(c);
140 }
141 ')' | ']' | '}' if !in_str => {
142 depth -= 1;
143 cur.push(c);
144 }
145 ',' if !in_str && depth == 0 => {
146 out.push(std::mem::take(&mut cur));
147 }
148 _ => cur.push(c),
149 }
150 }
151 out.push(cur);
152 Some(
153 out.into_iter()
154 .map(|p| p.trim().to_string())
155 .filter(|p| !p.is_empty())
156 .map(|p| match p.split_once('=') {
157 Some((k, v)) => (
158 k.trim().to_string(),
159 Some(v.trim().trim_matches('"').to_string()),
160 ),
161 None => (p, None),
162 })
163 .collect(),
164 )
165}
166
167fn attr_kv(attrs: &[String], name: &str) -> HashMap<String, Option<String>> {
168 attrs
169 .iter()
170 .filter_map(|a| attr_args(a, name))
171 .flatten()
172 .collect()
173}
174
175fn has_derive(item: &ApiItem, what: &str) -> bool {
176 item.attrs.iter().any(|a| {
177 a.starts_with("derive(")
178 && a.trim_start_matches("derive(")
179 .trim_end_matches(')')
180 .split(',')
181 .any(|d| d.trim().rsplit("::").next() == Some(what))
182 })
183}
184
185fn inner_type(ty: &str) -> &str {
187 let mut t = ty.trim();
188 for wrapper in ["Option<", "Box<", "Vec<"] {
189 if let Some(rest) = t.strip_prefix(wrapper) {
190 t = rest.strip_suffix('>').unwrap_or(rest);
191 }
192 }
193 let t = t.split('<').next().unwrap_or(t);
194 t.rsplit("::").next().unwrap_or(t).trim()
195}
196
197fn field_type(field: &ApiItem) -> String {
198 field
199 .signature
200 .split_once(':')
201 .map(|(_, t)| t.trim().to_string())
202 .unwrap_or_default()
203}
204
205struct Types<'a> {
206 by_name: HashMap<&'a str, &'a SurfaceItem>,
207}
208
209pub fn find_commands(api: &Surface) -> Vec<CliCommand> {
211 let mut all: Vec<&SurfaceItem> = Vec::new();
212 for k in &api.packages {
213 for m in &k.modules {
214 all.extend(m.items.iter());
215 }
216 }
217 let types = Types {
218 by_name: all
219 .iter()
220 .filter(|i| i.item.kind.is_type())
221 .map(|i| (i.item.name.as_str(), *i))
222 .collect(),
223 };
224 let mut roots: Vec<CliCommand> = Vec::new();
225 for it in all
226 .iter()
227 .filter(|i| i.item.kind == ApiKind::Struct && has_derive(&i.item, "Parser"))
228 {
229 let cmd = attr_kv(&it.item.attrs, "command");
230 let bin = api
231 .packages
232 .iter()
233 .find(|k| !k.is_lib)
234 .map(|k| k.name.replace('_', "-"));
235 let name = cmd
236 .get("name")
237 .cloned()
238 .flatten()
239 .or(bin)
240 .unwrap_or_else(|| kebab(&it.item.name));
241 if roots.iter().any(|r| r.path[0] == name) {
242 continue;
243 }
244 let mut root = CliCommand {
245 path: vec![name],
246 about: cmd.get("about").cloned().flatten(),
247 doc: it.item.doc.clone(),
248 args: Vec::new(),
249 subcommands: Vec::new(),
250 hidden: false,
251 file: it.file.clone(),
252 line: it.item.start_line,
253 };
254 if let Some(Some(long)) = cmd.get("long_about") {
255 root.doc = Some(DocComment {
256 markdown: long
257 .replace("\\\n", "")
258 .split_whitespace()
259 .collect::<Vec<_>>()
260 .join(" "),
261 summary: root.about.clone().unwrap_or_default(),
262 ..DocComment::default()
263 });
264 }
265 fill_from_fields(&mut root, &it.item.members, &types, 0);
266 roots.push(root);
267 }
268 roots
269}
270
271fn fill_from_fields(cmd: &mut CliCommand, fields: &[ApiItem], types: &Types, depth: usize) {
272 if depth > 16 {
273 return;
274 }
275 for f in fields.iter().filter(|f| f.kind == ApiKind::Field) {
276 let command = attr_kv(&f.attrs, "command");
277 let ty = field_type(f);
278 if command.contains_key("subcommand") {
279 if let Some(e) = types.by_name.get(inner_type(&ty)) {
280 cmd.subcommands
281 .extend(subcommands(&cmd.path, e, types, depth + 1));
282 }
283 continue;
284 }
285 if command.contains_key("flatten") {
286 if let Some(s) = types.by_name.get(inner_type(&ty)) {
287 fill_from_fields(cmd, &s.item.members, types, depth + 1);
288 }
289 continue;
290 }
291 cmd.args.push(arg(f, &ty));
292 }
293}
294
295fn arg(f: &ApiItem, ty: &str) -> CliArg {
296 let a = attr_kv(&f.attrs, "arg");
297 let a2 = attr_kv(&f.attrs, "clap");
298 let get = |k: &str| a.get(k).or_else(|| a2.get(k));
299 let long = get("long").map(|v| v.clone().unwrap_or_else(|| kebab(&f.name)));
300 let short = get("short").map(|v| {
301 v.as_deref()
302 .and_then(|s| s.trim_matches('\'').chars().next())
303 .unwrap_or_else(|| f.name.chars().next().unwrap_or('?'))
304 });
305 let is_bool = ty == "bool";
306 let action = get("action").cloned().flatten().unwrap_or_default();
307 let flag = is_bool || action.ends_with("Count") || action.ends_with("SetTrue");
308 let optional = ty.starts_with("Option<");
309 let multiple = ty.starts_with("Vec<");
310 let default = get("default_value")
311 .or_else(|| get("default_value_t"))
312 .cloned()
313 .flatten();
314 let positional = long.is_none() && short.is_none();
315 CliArg {
316 field: f.name.clone(),
317 long,
318 short,
319 positional,
320 value_name: get("value_name").cloned().flatten(),
321 ty: ty.to_string(),
322 default: default.clone(),
323 flag,
324 multiple,
325 required: get("required").is_some_and(|v| v.as_deref() != Some("false"))
326 || (positional && !optional && !multiple && default.is_none() && !is_bool),
327 hidden: get("hide").is_some_and(|v| v.as_deref() != Some("false")),
328 doc: f.doc.clone(),
329 }
330}
331
332fn subcommands(parent: &[String], e: &SurfaceItem, types: &Types, depth: usize) -> Vec<CliCommand> {
333 if e.item.kind != ApiKind::Enum {
334 return Vec::new();
335 }
336 let mut out = Vec::new();
337 for v in e.item.members.iter().filter(|m| m.kind == ApiKind::Variant) {
338 let cmd = attr_kv(&v.attrs, "command");
339 let name = cmd
340 .get("name")
341 .cloned()
342 .flatten()
343 .unwrap_or_else(|| kebab(&v.name));
344 let mut path = parent.to_vec();
345 path.push(name);
346 let mut c = CliCommand {
347 path,
348 about: cmd.get("about").cloned().flatten(),
349 doc: v.doc.clone(),
350 args: Vec::new(),
351 subcommands: Vec::new(),
352 hidden: cmd
353 .get("hide")
354 .is_some_and(|h| h.as_deref() != Some("false")),
355 file: e.file.clone(),
356 line: v.start_line,
357 };
358 if !v.members.is_empty() {
359 fill_from_fields(&mut c, &v.members, types, depth + 1);
360 } else if let Some(inner) = v
361 .signature
362 .split_once('(')
363 .map(|(_, r)| r.trim_end_matches(')'))
364 && let Some(t) = types.by_name.get(inner_type(inner))
365 {
366 match t.item.kind {
368 ApiKind::Enum => c.subcommands = subcommands(&c.path, t, types, depth + 1),
369 _ => fill_from_fields(&mut c, &t.item.members, types, depth + 1),
370 }
371 }
372 out.push(c);
373 }
374 out
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::pulse::extract::surface::{Package, SurfaceModule};
381 use std::collections::BTreeMap;
382
383 fn api(src: &str) -> Surface {
384 let file = crate::parsers::api::rust::extract(src).unwrap();
385 let items = file
386 .items
387 .into_iter()
388 .map(|item| SurfaceItem {
389 path: format!("app::{}", item.name),
390 item,
391 file: "src/cli.rs".into(),
392 public: false,
393 defined_at: None,
394 impl_files: BTreeMap::new(),
395 })
396 .collect();
397 Surface {
398 packages: vec![Package {
399 name: "app".into(),
400 lang: crate::models::Language::Rust,
401 sep: "::",
402 package: "app".into(),
403 manifest: "Cargo.toml".into(),
404 is_lib: false,
405 root_file: "src/main.rs".into(),
406 modules: vec![SurfaceModule {
407 path: "app".into(),
408 name: "app".into(),
409 file: "src/cli.rs".into(),
410 public: false,
411 doc: None,
412 items,
413 children: vec![],
414 parent: None,
415 }],
416 }],
417 }
418 }
419
420 const SRC: &str = r#"
421/// The app.
422#[derive(Parser, Debug)]
423#[command(name = "app", about = "Does things")]
424pub struct Cli {
425 /// Be loud
426 #[arg(short, long, action = clap::ArgAction::Count)]
427 verbose: u8,
428 #[command(subcommand)]
429 command: Option<Command>,
430}
431
432#[derive(Subcommand)]
433enum Command {
434 /// Build the index
435 ///
436 /// Longer text.
437 Index {
438 /// Where
439 #[arg(value_name = "PATH", default_value = ".")]
440 path: PathBuf,
441 /// Rebuild
442 #[arg(short, long)]
443 force: bool,
444 #[command(flatten)]
445 common: Common,
446 },
447 /// Nested
448 Pulse {
449 #[command(subcommand)]
450 command: PulseCmd,
451 },
452 #[command(hide = true)]
453 Internal,
454}
455
456#[derive(Args)]
457struct Common {
458 /// Output file
459 #[arg(short = 'o', long = "out-file", default_value = "a,b")]
460 output: Option<String>,
461 /// Names
462 names: Vec<String>,
463}
464
465#[derive(Subcommand)]
466enum PulseCmd {
467 /// Generate it
468 GenerateSite,
469}
470"#;
471
472 #[test]
473 fn command_tree() {
474 let roots = find_commands(&api(SRC));
475 assert_eq!(roots.len(), 1);
476 let root = &roots[0];
477 assert_eq!(root.path, vec!["app"]);
478 assert_eq!(root.about.as_deref(), Some("Does things"));
479 assert_eq!(root.args[0].usage(), "-v, --verbose");
480 assert!(root.args[0].flag);
481 assert_eq!(root.usage(), "app [OPTIONS] <COMMAND>");
482
483 let names: Vec<String> = root.walk().iter().map(|c| c.path.join(" ")).collect();
484 assert_eq!(
485 names,
486 vec![
487 "app",
488 "app index",
489 "app pulse",
490 "app pulse generate-site",
491 "app internal"
492 ]
493 );
494 assert!(root.subcommands[2].hidden);
495
496 let index = &root.subcommands[0];
497 assert_eq!(index.doc.as_ref().unwrap().summary, "Build the index");
498 let usages: Vec<String> = index.args.iter().map(|a| a.usage()).collect();
499 assert_eq!(
500 usages,
501 vec![
502 "<PATH>",
503 "-f, --force",
504 "-o, --out-file <OUTPUT>",
505 "<NAMES>..."
506 ]
507 );
508 assert!(!index.args[0].required, "has a default");
509 assert_eq!(index.args[0].default.as_deref(), Some("."));
510 assert_eq!(index.args[2].default.as_deref(), Some("a,b"));
511 assert_eq!(index.usage(), "app index [OPTIONS] [<PATH>] [<NAMES>...]");
512 }
513
514 #[test]
515 fn helpers() {
516 assert_eq!(kebab("GenerateSite"), "generate-site");
517 assert_eq!(kebab("no_llm"), "no-llm");
518 assert_eq!(inner_type("Option<crate::x::Foo>"), "Foo");
519 let kv = attr_args(
520 r#"arg(long, default_value = "a,b", num_args = 0..=1)"#,
521 "arg",
522 )
523 .unwrap();
524 assert_eq!(kv.len(), 3);
525 assert_eq!(kv[1], ("default_value".into(), Some("a,b".into())));
526 }
527}