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 retry_max_elapsed_ms: Option<u64>,
131
132 #[arg(long, global = true)]
134 pub disable_retry: bool,
135
136 #[arg(long, global = true)]
140 pub allow_loopback: bool,
141
142 #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
144 pub verbose: u8,
145
146 #[arg(short = 'q', long, global = true)]
148 pub quiet: bool,
149
150 #[arg(long, global = true)]
152 pub no_color: bool,
153
154 #[command(subcommand)]
155 pub command: Commands,
157}
158
159#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
161pub enum OutputFormat {
162 Markdown,
164 Json,
166 Text,
168}
169
170#[derive(Debug, Clone, Subcommand)]
172pub enum Commands {
173 SearchCrates {
175 #[arg(default_value = "")]
177 query: String,
178 #[arg(long, default_value_t = 10)]
180 per_page: u32,
181 #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
183 sort: SortKind,
184 #[arg(long, default_value_t = 1, conflicts_with = "page_token")]
186 page: u32,
187 #[arg(long, conflicts_with = "page")]
189 page_token: Option<String>,
190 },
191 Readme {
193 crate_name: String,
195 #[arg(long)]
197 crate_version: Option<String>,
198 },
199 GetItem {
201 crate_name: String,
203 item_type: String,
205 item_path: String,
207 #[arg(long)]
209 crate_version: Option<String>,
210 #[arg(long)]
212 suggest: bool,
213 },
214 SearchInCrate {
216 crate_name: String,
218 #[arg(default_value = "")]
220 query: String,
221 #[arg(long)]
223 crate_version: Option<String>,
224 #[arg(long)]
226 item_type: Option<String>,
227 #[arg(long, default_value_t = 100)]
229 limit: u32,
230 #[arg(long, default_value = "prefix")]
232 r#match: String,
233 },
234 Version,
236 Doctor {
238 #[arg(long)]
240 online: bool,
241 },
242 Commands,
244 Schema {
246 #[arg(long)]
248 cmd: String,
249 },
250 Completions {
252 #[arg(value_enum)]
254 shell: Shell,
255 },
256 Cache {
258 #[command(subcommand)]
260 action: CacheAction,
261 },
262 Config {
264 #[command(subcommand)]
266 action: ConfigAction,
267 },
268}
269
270#[derive(Debug, Clone, Subcommand)]
272pub enum CacheAction {
273 Path,
275 Clear,
277 Stats,
279}
280
281#[derive(Debug, Clone, Subcommand)]
283pub enum ConfigAction {
284 Path,
286 Show,
288 Init {
290 #[arg(long)]
292 force: bool,
293 },
294}
295
296#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
298pub enum SortKind {
299 Relevance,
301 Downloads,
303 #[value(name = "recent-downloads")]
305 RecentDownloads,
306 #[value(name = "recent-updates")]
308 RecentUpdates,
309 New,
311 Alphabetical,
313}
314
315impl SortKind {
316 pub fn as_api_str(self) -> &'static str {
318 match self {
319 Self::Relevance => "relevance",
320 Self::Downloads => "downloads",
321 Self::RecentDownloads => "recent-downloads",
322 Self::RecentUpdates => "recent-updates",
323 Self::New => "new",
324 Self::Alphabetical => "alphabetical",
325 }
326 }
327}
328
329#[derive(Debug, Clone, Copy, ValueEnum)]
331pub enum Shell {
332 Bash,
334 Zsh,
336 Fish,
338 Elvish,
340 #[value(name = "power-shell", alias = "powershell")]
342 PowerShell,
343}
344
345impl Shell {
346 pub fn as_str(self) -> &'static str {
348 match self {
349 Self::Bash => "bash",
350 Self::Zsh => "zsh",
351 Self::Fish => "fish",
352 Self::Elvish => "elvish",
353 Self::PowerShell => "power-shell",
354 }
355 }
356
357 pub fn to_clap_shell(self) -> clap_complete::Shell {
359 match self {
360 Self::Bash => clap_complete::Shell::Bash,
361 Self::Zsh => clap_complete::Shell::Zsh,
362 Self::Fish => clap_complete::Shell::Fish,
363 Self::Elvish => clap_complete::Shell::Elvish,
364 Self::PowerShell => clap_complete::Shell::PowerShell,
365 }
366 }
367}
368
369impl Commands {
370 pub fn wire_name(&self) -> &'static str {
375 match self {
376 Self::SearchCrates { .. } => "search-crates",
377 Self::Readme { .. } => "readme",
378 Self::GetItem { .. } => "get-item",
379 Self::SearchInCrate { .. } => "search-in-crate",
380 Self::Version => "version",
381 Self::Doctor { .. } => "doctor",
382 Self::Commands => "commands",
383 Self::Schema { .. } => "schema",
384 Self::Completions { .. } => "completions",
385 Self::Cache { action } => match action {
386 CacheAction::Path => "cache-path",
387 CacheAction::Clear => "cache-clear",
388 CacheAction::Stats => "cache-stats",
389 },
390 Self::Config { action } => match action {
391 ConfigAction::Path => "config-path",
392 ConfigAction::Show => "config-show",
393 ConfigAction::Init { .. } => "config-init",
394 },
395 }
396 }
397}
398
399impl Cli {
400 pub fn wire_command(&self) -> &'static str {
402 self.command.wire_name()
403 }
404
405 pub fn wants_json(&self, stdout_is_terminal: bool) -> bool {
412 if self.json || matches!(self.format, Some(OutputFormat::Json)) {
413 return true;
414 }
415 if matches!(
416 self.format,
417 Some(OutputFormat::Markdown | OutputFormat::Text)
418 ) {
419 return false;
420 }
421 !stdout_is_terminal
422 }
423
424 pub fn validate_format_conflict(&self) -> Result<(), crate::error::AppError> {
431 use crate::error::{AppError, ErrorKind};
432 if self.json
433 && matches!(
434 self.format,
435 Some(OutputFormat::Text | OutputFormat::Markdown)
436 )
437 {
438 return Err(AppError::new(
439 ErrorKind::Usage,
440 "cannot combine --json with --format text or --format markdown",
441 ));
442 }
443 Ok(())
444 }
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450 use clap::Parser;
451
452 #[test]
453 fn sort_api_strings() {
454 assert_eq!(SortKind::Relevance.as_api_str(), "relevance");
455 assert_eq!(SortKind::Downloads.as_api_str(), "downloads");
456 assert_eq!(SortKind::RecentDownloads.as_api_str(), "recent-downloads");
457 assert_eq!(SortKind::RecentUpdates.as_api_str(), "recent-updates");
458 assert_eq!(SortKind::New.as_api_str(), "new");
459 assert_eq!(SortKind::Alphabetical.as_api_str(), "alphabetical");
460 }
461
462 #[test]
463 fn wants_json_from_flag_or_format() {
464 let a = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
465 assert!(a.wants_json(true));
466 assert!(a.wants_json(false));
467 let b = Cli::try_parse_from(["docsrs-cli", "version", "--format", "json"]).unwrap();
468 assert!(b.wants_json(true));
469 let c = Cli::try_parse_from(["docsrs-cli", "version"]).unwrap();
470 assert!(!c.wants_json(true), "TTY defaults to human markdown");
471 assert!(c.wants_json(false), "non-TTY auto-JSON for agents");
472 let d = Cli::try_parse_from(["docsrs-cli", "version", "--format", "markdown"]).unwrap();
473 assert!(!d.wants_json(false), "explicit format overrides auto-JSON");
474 let e = Cli::try_parse_from(["docsrs-cli", "version", "--format", "text"]).unwrap();
475 assert!(!e.wants_json(false));
476 }
477
478 #[test]
479 fn parse_commands_subcommand() {
480 let cli = Cli::try_parse_from(["docsrs-cli", "commands"]).unwrap();
481 assert!(matches!(cli.command, Commands::Commands));
482 }
483
484 #[test]
485 fn format_conflict_detected() {
486 let cli =
487 Cli::try_parse_from(["docsrs-cli", "version", "--json", "--format", "text"]).unwrap();
488 assert!(cli.validate_format_conflict().is_err());
489 let ok = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
490 assert!(ok.validate_format_conflict().is_ok());
491 }
492
493 #[test]
494 fn shell_mapping() {
495 assert!(matches!(
496 Shell::Bash.to_clap_shell(),
497 clap_complete::Shell::Bash
498 ));
499 assert!(matches!(
500 Shell::Zsh.to_clap_shell(),
501 clap_complete::Shell::Zsh
502 ));
503 assert!(matches!(
504 Shell::Fish.to_clap_shell(),
505 clap_complete::Shell::Fish
506 ));
507 assert!(matches!(
508 Shell::Elvish.to_clap_shell(),
509 clap_complete::Shell::Elvish
510 ));
511 assert!(matches!(
512 Shell::PowerShell.to_clap_shell(),
513 clap_complete::Shell::PowerShell
514 ));
515 }
516
517 #[test]
518 fn powershell_alias_and_canonical_parse() {
519 let a = Cli::try_parse_from(["docsrs-cli", "completions", "powershell"]).unwrap();
520 let b = Cli::try_parse_from(["docsrs-cli", "completions", "power-shell"]).unwrap();
521 match (a.command, b.command) {
522 (Commands::Completions { shell: sa }, Commands::Completions { shell: sb }) => {
523 assert!(matches!(sa, Shell::PowerShell));
524 assert!(matches!(sb, Shell::PowerShell));
525 }
526 _ => panic!("expected completions commands"),
527 }
528 }
529
530 #[test]
531 fn parse_search_crates_defaults() {
532 let cli = Cli::try_parse_from(["docsrs-cli", "search-crates", "serde"]).unwrap();
533 match cli.command {
534 Commands::SearchCrates {
535 query,
536 per_page,
537 sort,
538 page,
539 page_token,
540 } => {
541 assert_eq!(query, "serde");
542 assert_eq!(per_page, 10);
543 assert_eq!(sort, SortKind::Relevance);
544 assert_eq!(page, 1);
545 assert!(page_token.is_none());
546 }
547 _ => panic!("wrong command"),
548 }
549 }
550}