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, env = "DOCSRS_CLI_TIMEOUT_SECS")]
62 pub timeout: Option<u64>,
63
64 #[arg(long, global = true)]
66 pub connect_timeout: Option<u64>,
67
68 #[arg(long, global = true, env = "DOCSRS_CLI_USER_AGENT")]
70 pub user_agent: Option<String>,
71
72 #[arg(long, global = true, env = "DOCSRS_CLI_LANG")]
74 pub lang: Option<String>,
75
76 #[arg(long, global = true, env = "DOCSRS_CLI_CONFIG_DIR")]
78 pub config_dir: Option<PathBuf>,
79
80 #[arg(long, global = true, env = "DOCSRS_CLI_CACHE_DIR")]
82 pub cache_dir: Option<PathBuf>,
83
84 #[arg(long, global = true)]
86 pub no_cache: bool,
87
88 #[arg(long, global = true, env = "DOCSRS_CLI_CACHE_TTL_SECS")]
90 pub cache_ttl_secs: Option<u64>,
91
92 #[arg(long, global = true, env = "DOCSRS_CLI_MAX_CACHE_BYTES")]
94 pub max_cache_bytes: Option<u64>,
95
96 #[arg(long, global = true)]
98 pub dry_run: bool,
99
100 #[arg(long, global = true, env = "DOCSRS_CLI_MAX_BODY_BYTES")]
102 pub max_body_bytes: Option<u64>,
103
104 #[arg(long, global = true, env = "DOCSRS_CLI_MAX_OUTPUT_BYTES")]
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, env = "DOCSRS_CLI_MAX_CONCURRENCY")]
114 pub max_concurrency: Option<u32>,
115
116 #[arg(long, global = true, env = "DOCSRS_CLI_MAX_RETRIES")]
118 pub max_retries: Option<u32>,
119
120 #[arg(long, global = true, env = "DOCSRS_CLI_RETRY_BASE_MS")]
122 pub retry_base_ms: Option<u64>,
123
124 #[arg(long, global = true, env = "DOCSRS_CLI_RETRY_MAX_DELAY_MS")]
126 pub retry_max_delay_ms: Option<u64>,
127
128 #[arg(long, global = true, env = "DOCSRS_CLI_DISABLE_RETRY")]
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 query: String,
167 #[arg(long, default_value_t = 10)]
169 per_page: u32,
170 #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
172 sort: SortKind,
173 #[arg(long, default_value_t = 1)]
175 page: u32,
176 },
177 Readme {
179 crate_name: String,
181 #[arg(long)]
183 crate_version: Option<String>,
184 },
185 GetItem {
187 crate_name: String,
189 item_type: String,
191 item_path: String,
193 #[arg(long)]
195 crate_version: Option<String>,
196 },
197 SearchInCrate {
199 crate_name: String,
201 #[arg(default_value = "")]
203 query: String,
204 #[arg(long)]
206 crate_version: Option<String>,
207 #[arg(long)]
209 item_type: Option<String>,
210 #[arg(long, default_value_t = 100)]
212 limit: u32,
213 },
214 Version,
216 Doctor,
218 Commands,
220 Schema {
222 #[arg(long)]
224 cmd: String,
225 },
226 Completions {
228 #[arg(value_enum)]
230 shell: Shell,
231 },
232 Cache {
234 #[command(subcommand)]
236 action: CacheAction,
237 },
238 Config {
240 #[command(subcommand)]
242 action: ConfigAction,
243 },
244}
245
246#[derive(Debug, Clone, Subcommand)]
248pub enum CacheAction {
249 Clear,
251 Stats,
253}
254
255#[derive(Debug, Clone, Subcommand)]
257pub enum ConfigAction {
258 Path,
260 Show,
262 Init {
264 #[arg(long)]
266 force: bool,
267 },
268}
269
270#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
272pub enum SortKind {
273 Relevance,
275 Downloads,
277 #[value(name = "recent-downloads")]
279 RecentDownloads,
280 #[value(name = "recent-updates")]
282 RecentUpdates,
283 New,
285 Alphabetical,
287}
288
289impl SortKind {
290 pub fn as_api_str(self) -> &'static str {
292 match self {
293 Self::Relevance => "relevance",
294 Self::Downloads => "downloads",
295 Self::RecentDownloads => "recent-downloads",
296 Self::RecentUpdates => "recent-updates",
297 Self::New => "new",
298 Self::Alphabetical => "alphabetical",
299 }
300 }
301}
302
303#[derive(Debug, Clone, Copy, ValueEnum)]
305pub enum Shell {
306 Bash,
308 Zsh,
310 Fish,
312 Elvish,
314 #[value(name = "power-shell", alias = "powershell")]
316 PowerShell,
317}
318
319impl Shell {
320 pub fn as_str(self) -> &'static str {
322 match self {
323 Self::Bash => "bash",
324 Self::Zsh => "zsh",
325 Self::Fish => "fish",
326 Self::Elvish => "elvish",
327 Self::PowerShell => "power-shell",
328 }
329 }
330
331 pub fn to_clap_shell(self) -> clap_complete::Shell {
333 match self {
334 Self::Bash => clap_complete::Shell::Bash,
335 Self::Zsh => clap_complete::Shell::Zsh,
336 Self::Fish => clap_complete::Shell::Fish,
337 Self::Elvish => clap_complete::Shell::Elvish,
338 Self::PowerShell => clap_complete::Shell::PowerShell,
339 }
340 }
341}
342
343impl Cli {
344 pub fn wants_json(&self, stdout_is_terminal: bool) -> bool {
351 if self.json || matches!(self.format, Some(OutputFormat::Json)) {
352 return true;
353 }
354 if matches!(
355 self.format,
356 Some(OutputFormat::Markdown | OutputFormat::Text)
357 ) {
358 return false;
359 }
360 !stdout_is_terminal
361 }
362
363 pub fn validate_format_conflict(&self) -> Result<(), crate::error::AppError> {
370 use crate::error::{AppError, ErrorKind};
371 if self.json
372 && matches!(
373 self.format,
374 Some(OutputFormat::Text | OutputFormat::Markdown)
375 )
376 {
377 return Err(AppError::new(
378 ErrorKind::Usage,
379 "cannot combine --json with --format text or --format markdown",
380 ));
381 }
382 Ok(())
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use clap::Parser;
390
391 #[test]
392 fn sort_api_strings() {
393 assert_eq!(SortKind::Relevance.as_api_str(), "relevance");
394 assert_eq!(SortKind::Downloads.as_api_str(), "downloads");
395 assert_eq!(SortKind::RecentDownloads.as_api_str(), "recent-downloads");
396 assert_eq!(SortKind::RecentUpdates.as_api_str(), "recent-updates");
397 assert_eq!(SortKind::New.as_api_str(), "new");
398 assert_eq!(SortKind::Alphabetical.as_api_str(), "alphabetical");
399 }
400
401 #[test]
402 fn wants_json_from_flag_or_format() {
403 let a = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
404 assert!(a.wants_json(true));
405 assert!(a.wants_json(false));
406 let b = Cli::try_parse_from(["docsrs-cli", "version", "--format", "json"]).unwrap();
407 assert!(b.wants_json(true));
408 let c = Cli::try_parse_from(["docsrs-cli", "version"]).unwrap();
409 assert!(!c.wants_json(true), "TTY defaults to human markdown");
410 assert!(c.wants_json(false), "non-TTY auto-JSON for agents");
411 let d = Cli::try_parse_from(["docsrs-cli", "version", "--format", "markdown"]).unwrap();
412 assert!(!d.wants_json(false), "explicit format overrides auto-JSON");
413 let e = Cli::try_parse_from(["docsrs-cli", "version", "--format", "text"]).unwrap();
414 assert!(!e.wants_json(false));
415 }
416
417 #[test]
418 fn parse_commands_subcommand() {
419 let cli = Cli::try_parse_from(["docsrs-cli", "commands"]).unwrap();
420 assert!(matches!(cli.command, Commands::Commands));
421 }
422
423 #[test]
424 fn format_conflict_detected() {
425 let cli =
426 Cli::try_parse_from(["docsrs-cli", "version", "--json", "--format", "text"]).unwrap();
427 assert!(cli.validate_format_conflict().is_err());
428 let ok = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
429 assert!(ok.validate_format_conflict().is_ok());
430 }
431
432 #[test]
433 fn shell_mapping() {
434 assert!(matches!(
435 Shell::Bash.to_clap_shell(),
436 clap_complete::Shell::Bash
437 ));
438 assert!(matches!(
439 Shell::Zsh.to_clap_shell(),
440 clap_complete::Shell::Zsh
441 ));
442 assert!(matches!(
443 Shell::Fish.to_clap_shell(),
444 clap_complete::Shell::Fish
445 ));
446 assert!(matches!(
447 Shell::Elvish.to_clap_shell(),
448 clap_complete::Shell::Elvish
449 ));
450 assert!(matches!(
451 Shell::PowerShell.to_clap_shell(),
452 clap_complete::Shell::PowerShell
453 ));
454 }
455
456 #[test]
457 fn powershell_alias_and_canonical_parse() {
458 let a = Cli::try_parse_from(["docsrs-cli", "completions", "powershell"]).unwrap();
459 let b = Cli::try_parse_from(["docsrs-cli", "completions", "power-shell"]).unwrap();
460 match (a.command, b.command) {
461 (Commands::Completions { shell: sa }, Commands::Completions { shell: sb }) => {
462 assert!(matches!(sa, Shell::PowerShell));
463 assert!(matches!(sb, Shell::PowerShell));
464 }
465 _ => panic!("expected completions commands"),
466 }
467 }
468
469 #[test]
470 fn parse_search_crates_defaults() {
471 let cli = Cli::try_parse_from(["docsrs-cli", "search-crates", "serde"]).unwrap();
472 match cli.command {
473 Commands::SearchCrates {
474 query,
475 per_page,
476 sort,
477 page,
478 } => {
479 assert_eq!(query, "serde");
480 assert_eq!(per_page, 10);
481 assert_eq!(sort, SortKind::Relevance);
482 assert_eq!(page, 1);
483 }
484 _ => panic!("wrong command"),
485 }
486 }
487}