1use std::path::PathBuf;
4
5use clap::{Parser, Subcommand, ValueEnum};
6
7#[derive(Debug, Clone, Parser)]
8#[command(
9 name = "docsrs-cli",
10 version,
11 about = "One-shot CLI for crates.io and docs.rs documentation",
12 long_about = "One-shot BORN→EXECUTE→DIE CLI for crates.io and docs.rs.
13\
14Stdout is the data contract (JSON or markdown). Stderr is diagnostics only.
15\
16JSON is automatic when stdout is not a TTY; force human with --format markdown|text.
17\
18First Ctrl-C / SIGINT cancels cooperatively (exit 130). Second Ctrl-C within 5s force-exits 130.
19\
20SIGTERM and SIGHUP cancel as terminate (exit 143). On Windows, Ctrl+Break and console close also terminate (143).
21\
22Broken pipe on stdout is exit 141 (pipeline-safe; no stack trace).",
23 after_help = "Examples:
24 \
25docsrs-cli search-crates serde --json
26 \
27docsrs-cli readme tokio --json
28 \
29docsrs-cli get-item clap trait clap::Parser --json
30 \
31docsrs-cli search-in-crate reqwest Client --json
32 \
33docsrs-cli doctor --json
34 \
35docsrs-cli config path --json
36 \
37docsrs-cli config show --json
38 \
39docsrs-cli config init --json
40 \
41docsrs-cli commands --json
42 \
43docsrs-cli completions bash
44 \
45docsrs-cli --dry-run readme serde
46 \
47# Agents: JSON is auto when stdout is not a TTY; force markdown with --format markdown",
48 disable_help_subcommand = false
49)]
50pub struct Cli {
52 #[arg(long, global = true)]
54 pub json: bool,
55
56 #[arg(long, global = true, value_enum)]
58 pub format: Option<OutputFormat>,
59
60 #[arg(long, global = true)]
62 pub timeout: Option<u64>,
63
64 #[arg(long, global = true)]
66 pub connect_timeout: Option<u64>,
67
68 #[arg(long, global = true)]
70 pub user_agent: Option<String>,
71
72 #[arg(long, global = true)]
74 pub lang: Option<String>,
75
76 #[arg(long, global = true)]
78 pub config_dir: Option<PathBuf>,
79
80 #[arg(long, global = true)]
82 pub cache_dir: Option<PathBuf>,
83
84 #[arg(long, global = true)]
86 pub no_cache: bool,
87
88 #[arg(long, global = true)]
90 pub cache_ttl_secs: Option<u64>,
91
92 #[arg(long, global = true)]
94 pub max_cache_bytes: Option<u64>,
95
96 #[arg(long, global = true)]
98 pub dry_run: bool,
99
100 #[arg(long, global = true)]
102 pub max_body_bytes: Option<u64>,
103
104 #[arg(long, global = true)]
106 pub max_output_bytes: Option<u64>,
107
108 #[arg(long, global = true)]
110 pub rate_limit_delay_ms: Option<u64>,
111
112 #[arg(long, global = true)]
114 pub max_concurrency: Option<u32>,
115
116 #[arg(long, global = true)]
118 pub max_retries: Option<u32>,
119
120 #[arg(long, global = true)]
122 pub retry_base_ms: Option<u64>,
123
124 #[arg(long, global = true)]
126 pub retry_max_delay_ms: Option<u64>,
127
128 #[arg(long, global = true)]
130 pub disable_retry: bool,
131
132 #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
134 pub verbose: u8,
135
136 #[arg(short = 'q', long, global = true)]
138 pub quiet: bool,
139
140 #[arg(long, global = true)]
142 pub no_color: bool,
143
144 #[command(subcommand)]
145 pub command: Commands,
147}
148
149#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
151pub enum OutputFormat {
152 Markdown,
154 Json,
156 Text,
158}
159
160#[derive(Debug, Clone, Subcommand)]
162pub enum Commands {
163 SearchCrates {
165 #[arg(default_value = "")]
167 query: String,
168 #[arg(long, default_value_t = 10)]
170 per_page: u32,
171 #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
173 sort: SortKind,
174 #[arg(long, default_value_t = 1, conflicts_with = "page_token")]
176 page: u32,
177 #[arg(long, conflicts_with = "page")]
179 page_token: Option<String>,
180 },
181 Readme {
183 crate_name: String,
185 #[arg(long)]
187 crate_version: Option<String>,
188 },
189 GetItem {
191 crate_name: String,
193 item_type: String,
195 item_path: String,
197 #[arg(long)]
199 crate_version: Option<String>,
200 #[arg(long)]
202 suggest: bool,
203 },
204 SearchInCrate {
206 crate_name: String,
208 #[arg(default_value = "")]
210 query: String,
211 #[arg(long)]
213 crate_version: Option<String>,
214 #[arg(long)]
216 item_type: Option<String>,
217 #[arg(long, default_value_t = 100)]
219 limit: u32,
220 #[arg(long, default_value = "prefix")]
222 r#match: String,
223 },
224 Version,
226 Doctor {
228 #[arg(long)]
230 online: bool,
231 },
232 Commands,
234 Schema {
236 #[arg(long)]
238 cmd: String,
239 },
240 Completions {
242 #[arg(value_enum)]
244 shell: Shell,
245 },
246 Cache {
248 #[command(subcommand)]
250 action: CacheAction,
251 },
252 Config {
254 #[command(subcommand)]
256 action: ConfigAction,
257 },
258}
259
260#[derive(Debug, Clone, Subcommand)]
262pub enum CacheAction {
263 Clear,
265 Stats,
267}
268
269#[derive(Debug, Clone, Subcommand)]
271pub enum ConfigAction {
272 Path,
274 Show,
276 Init {
278 #[arg(long)]
280 force: bool,
281 },
282}
283
284#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
286pub enum SortKind {
287 Relevance,
289 Downloads,
291 #[value(name = "recent-downloads")]
293 RecentDownloads,
294 #[value(name = "recent-updates")]
296 RecentUpdates,
297 New,
299 Alphabetical,
301}
302
303impl SortKind {
304 pub fn as_api_str(self) -> &'static str {
306 match self {
307 Self::Relevance => "relevance",
308 Self::Downloads => "downloads",
309 Self::RecentDownloads => "recent-downloads",
310 Self::RecentUpdates => "recent-updates",
311 Self::New => "new",
312 Self::Alphabetical => "alphabetical",
313 }
314 }
315}
316
317#[derive(Debug, Clone, Copy, ValueEnum)]
319pub enum Shell {
320 Bash,
322 Zsh,
324 Fish,
326 Elvish,
328 #[value(name = "power-shell", alias = "powershell")]
330 PowerShell,
331}
332
333impl Shell {
334 pub fn as_str(self) -> &'static str {
336 match self {
337 Self::Bash => "bash",
338 Self::Zsh => "zsh",
339 Self::Fish => "fish",
340 Self::Elvish => "elvish",
341 Self::PowerShell => "power-shell",
342 }
343 }
344
345 pub fn to_clap_shell(self) -> clap_complete::Shell {
347 match self {
348 Self::Bash => clap_complete::Shell::Bash,
349 Self::Zsh => clap_complete::Shell::Zsh,
350 Self::Fish => clap_complete::Shell::Fish,
351 Self::Elvish => clap_complete::Shell::Elvish,
352 Self::PowerShell => clap_complete::Shell::PowerShell,
353 }
354 }
355}
356
357impl Cli {
358 pub fn wants_json(&self, stdout_is_terminal: bool) -> bool {
365 if self.json || matches!(self.format, Some(OutputFormat::Json)) {
366 return true;
367 }
368 if matches!(
369 self.format,
370 Some(OutputFormat::Markdown | OutputFormat::Text)
371 ) {
372 return false;
373 }
374 !stdout_is_terminal
375 }
376
377 pub fn validate_format_conflict(&self) -> Result<(), crate::error::AppError> {
384 use crate::error::{AppError, ErrorKind};
385 if self.json
386 && matches!(
387 self.format,
388 Some(OutputFormat::Text | OutputFormat::Markdown)
389 )
390 {
391 return Err(AppError::new(
392 ErrorKind::Usage,
393 "cannot combine --json with --format text or --format markdown",
394 ));
395 }
396 Ok(())
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403 use clap::Parser;
404
405 #[test]
406 fn sort_api_strings() {
407 assert_eq!(SortKind::Relevance.as_api_str(), "relevance");
408 assert_eq!(SortKind::Downloads.as_api_str(), "downloads");
409 assert_eq!(SortKind::RecentDownloads.as_api_str(), "recent-downloads");
410 assert_eq!(SortKind::RecentUpdates.as_api_str(), "recent-updates");
411 assert_eq!(SortKind::New.as_api_str(), "new");
412 assert_eq!(SortKind::Alphabetical.as_api_str(), "alphabetical");
413 }
414
415 #[test]
416 fn wants_json_from_flag_or_format() {
417 let a = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
418 assert!(a.wants_json(true));
419 assert!(a.wants_json(false));
420 let b = Cli::try_parse_from(["docsrs-cli", "version", "--format", "json"]).unwrap();
421 assert!(b.wants_json(true));
422 let c = Cli::try_parse_from(["docsrs-cli", "version"]).unwrap();
423 assert!(!c.wants_json(true), "TTY defaults to human markdown");
424 assert!(c.wants_json(false), "non-TTY auto-JSON for agents");
425 let d = Cli::try_parse_from(["docsrs-cli", "version", "--format", "markdown"]).unwrap();
426 assert!(!d.wants_json(false), "explicit format overrides auto-JSON");
427 let e = Cli::try_parse_from(["docsrs-cli", "version", "--format", "text"]).unwrap();
428 assert!(!e.wants_json(false));
429 }
430
431 #[test]
432 fn parse_commands_subcommand() {
433 let cli = Cli::try_parse_from(["docsrs-cli", "commands"]).unwrap();
434 assert!(matches!(cli.command, Commands::Commands));
435 }
436
437 #[test]
438 fn format_conflict_detected() {
439 let cli =
440 Cli::try_parse_from(["docsrs-cli", "version", "--json", "--format", "text"]).unwrap();
441 assert!(cli.validate_format_conflict().is_err());
442 let ok = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
443 assert!(ok.validate_format_conflict().is_ok());
444 }
445
446 #[test]
447 fn shell_mapping() {
448 assert!(matches!(
449 Shell::Bash.to_clap_shell(),
450 clap_complete::Shell::Bash
451 ));
452 assert!(matches!(
453 Shell::Zsh.to_clap_shell(),
454 clap_complete::Shell::Zsh
455 ));
456 assert!(matches!(
457 Shell::Fish.to_clap_shell(),
458 clap_complete::Shell::Fish
459 ));
460 assert!(matches!(
461 Shell::Elvish.to_clap_shell(),
462 clap_complete::Shell::Elvish
463 ));
464 assert!(matches!(
465 Shell::PowerShell.to_clap_shell(),
466 clap_complete::Shell::PowerShell
467 ));
468 }
469
470 #[test]
471 fn powershell_alias_and_canonical_parse() {
472 let a = Cli::try_parse_from(["docsrs-cli", "completions", "powershell"]).unwrap();
473 let b = Cli::try_parse_from(["docsrs-cli", "completions", "power-shell"]).unwrap();
474 match (a.command, b.command) {
475 (Commands::Completions { shell: sa }, Commands::Completions { shell: sb }) => {
476 assert!(matches!(sa, Shell::PowerShell));
477 assert!(matches!(sb, Shell::PowerShell));
478 }
479 _ => panic!("expected completions commands"),
480 }
481 }
482
483 #[test]
484 fn parse_search_crates_defaults() {
485 let cli = Cli::try_parse_from(["docsrs-cli", "search-crates", "serde"]).unwrap();
486 match cli.command {
487 Commands::SearchCrates {
488 query,
489 per_page,
490 sort,
491 page,
492 page_token,
493 } => {
494 assert_eq!(query, "serde");
495 assert_eq!(per_page, 10);
496 assert_eq!(sort, SortKind::Relevance);
497 assert_eq!(page, 1);
498 assert!(page_token.is_none());
499 }
500 _ => panic!("wrong command"),
501 }
502 }
503}