Skip to main content

docsrs_cli/
cli.rs

1//! Clap surface for docsrs-cli.
2
3use 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)]
50/// Top-level clap parser for the `docsrs-cli` binary.
51pub struct Cli {
52    /// Emit JSON envelope on stdout
53    #[arg(long, global = true)]
54    pub json: bool,
55
56    /// Output format (json is alias of --json)
57    #[arg(long, global = true, value_enum)]
58    pub format: Option<OutputFormat>,
59
60    /// Wall-clock timeout in seconds (must be >= 1 when set)
61    #[arg(long, global = true)]
62    pub timeout: Option<u64>,
63
64    /// Connect timeout in seconds (must be >= 1 when set)
65    #[arg(long, global = true)]
66    pub connect_timeout: Option<u64>,
67
68    /// Override User-Agent
69    #[arg(long, global = true)]
70    pub user_agent: Option<String>,
71
72    /// Force human stderr locale: en or pt-BR (fail-closed; JSON stays English)
73    #[arg(long, global = true)]
74    pub lang: Option<String>,
75
76    /// Override XDG config directory
77    #[arg(long, global = true)]
78    pub config_dir: Option<PathBuf>,
79
80    /// Override XDG cache directory for HTTP body cache
81    #[arg(long, global = true)]
82    pub cache_dir: Option<PathBuf>,
83
84    /// Disable disk cache (always hit network)
85    #[arg(long, global = true)]
86    pub no_cache: bool,
87
88    /// Disk cache TTL in seconds (default 86400 = 24h)
89    #[arg(long, global = true)]
90    pub cache_ttl_secs: Option<u64>,
91
92    /// Soft cap on disk cache size in bytes (default 268435456 = 256 MiB; 0 = unlimited)
93    #[arg(long, global = true)]
94    pub max_cache_bytes: Option<u64>,
95
96    /// Plan URLs without opening network sockets
97    #[arg(long, global = true)]
98    pub dry_run: bool,
99
100    /// Cap downloaded body size in bytes (hard max 10485760 = 10 MiB; cannot raise above)
101    #[arg(long, global = true)]
102    pub max_body_bytes: Option<u64>,
103
104    /// Cap emitted payload size in bytes (hard max 2097152 = 2 MiB; cannot raise above)
105    #[arg(long, global = true)]
106    pub max_output_bytes: Option<u64>,
107
108    /// Minimum delay between requests to the same host (ms)
109    #[arg(long, global = true)]
110    pub rate_limit_delay_ms: Option<u64>,
111
112    /// Max concurrent CPU parse workers (`0` = auto from CPUs and free RAM)
113    #[arg(long, global = true)]
114    pub max_concurrency: Option<u32>,
115
116    /// Max HTTP retries for transient errors (after the first attempt)
117    #[arg(long, global = true)]
118    pub max_retries: Option<u32>,
119
120    /// Base backoff delay in milliseconds for HTTP retries
121    #[arg(long, global = true)]
122    pub retry_base_ms: Option<u64>,
123
124    /// Maximum single HTTP retry sleep in milliseconds
125    #[arg(long, global = true)]
126    pub retry_max_delay_ms: Option<u64>,
127
128    /// Total HTTP retry wall budget in milliseconds (`0` = derive from --timeout)
129    #[arg(long, global = true)]
130    pub retry_max_elapsed_ms: Option<u64>,
131
132    /// Disable HTTP retries (incident kill switch / debug)
133    #[arg(long, global = true)]
134    pub disable_retry: bool,
135
136    /// Allow loopback origins (`127.0.0.1` / `localhost`) for offline wiremock
137    ///
138    /// Also settable via XDG `config.toml` `allow_loopback = true`. Never via env.
139    #[arg(long, global = true)]
140    pub allow_loopback: bool,
141
142    /// Increase stderr verbosity
143    #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
144    pub verbose: u8,
145
146    /// Suppress non-error stderr prose
147    #[arg(short = 'q', long, global = true)]
148    pub quiet: bool,
149
150    /// Disable ANSI colors on stderr
151    #[arg(long, global = true)]
152    pub no_color: bool,
153
154    #[command(subcommand)]
155    /// Subcommand to execute for this invocation.
156    pub command: Commands,
157}
158
159/// Human or machine output format selection.
160#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
161pub enum OutputFormat {
162    /// Markdown rendered for humans.
163    Markdown,
164    /// JSON envelope for agents.
165    Json,
166    /// Plain-text rendering (alias of markdown for most commands).
167    Text,
168}
169
170/// Product subcommands exposed on the CLI surface.
171#[derive(Debug, Clone, Subcommand)]
172pub enum Commands {
173    /// Search crates on crates.io
174    SearchCrates {
175        /// Search keywords (English). Optional when `--page-token` carries a full query string.
176        #[arg(default_value = "")]
177        query: String,
178        /// Results per page (max 100)
179        #[arg(long, default_value_t = 10)]
180        per_page: u32,
181        /// Sort order
182        #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
183        sort: SortKind,
184        /// Page number (1-based). Conflicts with `--page-token`.
185        #[arg(long, default_value_t = 1, conflicts_with = "page_token")]
186        page: u32,
187        /// Opaque pagination token from `meta.next_page` / `meta.prev_page` (full query or seek).
188        #[arg(long, conflicts_with = "page")]
189        page_token: Option<String>,
190    },
191    /// Fetch crate overview docblock from docs.rs (not git README)
192    Readme {
193        /// Crate name on crates.io or a stdlib crate (`name` or `name@1.2.3`).
194        crate_name: String,
195        /// Optional crate version (`latest` when omitted). Conflicts if it differs from `crate@…`.
196        #[arg(long)]
197        crate_version: Option<String>,
198    },
199    /// Fetch documentation for a typed item
200    GetItem {
201        /// Crate name on crates.io or a stdlib crate (`name` or `name@1.2.3`).
202        crate_name: String,
203        /// Kind: module|struct|trait|enum|union|fn|function|method|type|const|constant|static|macro|attr|attribute|derive
204        item_type: String,
205        /// Path with `::` or `/` (e.g. `Runtime::new`, `runtime/Runtime`, `tokio::spawn`)
206        item_path: String,
207        /// Optional crate version (`latest` when omitted). Conflicts if it differs from `crate@…`.
208        #[arg(long)]
209        crate_version: Option<String>,
210        /// On 404, suggest nearby symbols from all.html (one extra request; exact/prefix/substring/edit-distance).
211        #[arg(long)]
212        suggest: bool,
213    },
214    /// Search symbols in crate all.html index
215    SearchInCrate {
216        /// Crate name on crates.io or a stdlib crate (`name` or `name@1.2.3`).
217        crate_name: String,
218        /// Text filter; empty string lists all classified items
219        #[arg(default_value = "")]
220        query: String,
221        /// Optional crate version (`latest` when omitted). Conflicts if it differs from `crate@…`.
222        #[arg(long)]
223        crate_version: Option<String>,
224        /// Optional item-kind filter (`struct`, `fn`, `method`, …).
225        #[arg(long)]
226        item_type: Option<String>,
227        /// Maximum hits to emit (clamped to 1000).
228        #[arg(long, default_value_t = 100)]
229        limit: u32,
230        /// Match policy: exact | prefix (default) | substring
231        #[arg(long, default_value = "prefix")]
232        r#match: String,
233    },
234    /// Print binary version
235    Version,
236    /// Validate local TLS/config readiness
237    Doctor {
238        /// Probe crates.io / docs.rs over the network (opt-in)
239        #[arg(long)]
240        online: bool,
241    },
242    /// List the full command tree for agent discovery
243    Commands,
244    /// Emit JSON Schema for a command
245    Schema {
246        /// Command name whose schema should be printed.
247        #[arg(long)]
248        cmd: String,
249    },
250    /// Generate shell completions
251    Completions {
252        /// Target shell for completion scripts.
253        #[arg(value_enum)]
254        shell: Shell,
255    },
256    /// Inspect or clear the XDG HTTP disk cache
257    Cache {
258        /// Cache maintenance action.
259        #[command(subcommand)]
260        action: CacheAction,
261    },
262    /// Manage XDG config paths and the optional config.toml (no secrets / no .env)
263    Config {
264        /// Config lifecycle action.
265        #[command(subcommand)]
266        action: ConfigAction,
267    },
268}
269
270/// Cache maintenance subcommands.
271#[derive(Debug, Clone, Subcommand)]
272pub enum CacheAction {
273    /// Print resolved cache root and which layer won
274    Path,
275    /// Delete all cached HTTP bodies under the cache dir
276    Clear,
277    /// Report entry count, total bytes, and budget
278    Stats,
279}
280
281/// XDG config lifecycle subcommands (no API keys; product is public HTTP only).
282#[derive(Debug, Clone, Subcommand)]
283pub enum ConfigAction {
284    /// Print resolved config/cache directories and which layer won
285    Path,
286    /// Print effective runtime configuration (merged defaults + TOML + env + CLI)
287    Show,
288    /// Create a default config.toml under the resolved config directory
289    Init {
290        /// Overwrite an existing config.toml
291        #[arg(long)]
292        force: bool,
293    },
294}
295
296/// crates.io search sort order.
297#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
298pub enum SortKind {
299    /// Rank by search relevance.
300    Relevance,
301    /// Rank by total downloads.
302    Downloads,
303    /// Rank by recent downloads.
304    #[value(name = "recent-downloads")]
305    RecentDownloads,
306    /// Rank by recent crate updates.
307    #[value(name = "recent-updates")]
308    RecentUpdates,
309    /// Rank newest crates first.
310    New,
311    /// Rank alphabetically by crate name.
312    Alphabetical,
313}
314
315impl SortKind {
316    /// crates.io API `sort=` query value.
317    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/// Shells supported by the `completions` subcommand.
330#[derive(Debug, Clone, Copy, ValueEnum)]
331pub enum Shell {
332    /// Bash completions.
333    Bash,
334    /// Zsh completions.
335    Zsh,
336    /// Fish completions.
337    Fish,
338    /// Elvish completions.
339    Elvish,
340    /// Canonical CLI value is `power-shell`; `powershell` is accepted as alias.
341    #[value(name = "power-shell", alias = "powershell")]
342    PowerShell,
343}
344
345impl Shell {
346    /// Stable CLI / JSON name for this shell.
347    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    /// Convert to the `clap_complete` shell enum.
358    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    /// Stable wire command name used in success and error JSON envelopes (DRY).
371    ///
372    /// Nested cache/config actions use the same names as `schema --cmd` aliases
373    /// (`cache-path`, `config-show`, …).
374    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    /// Wire command name for the active subcommand (error/success envelopes).
401    pub fn wire_command(&self) -> &'static str {
402        self.command.wire_name()
403    }
404
405    /// Whether JSON envelope is requested.
406    ///
407    /// Agent-first rules (stdin/stdout LLM contract):
408    /// - `--json` or `--format json` → JSON
409    /// - `--format markdown|text` → human (never auto-JSON)
410    /// - otherwise → JSON when stdout is not a TTY (pipe/agent), markdown on TTY
411    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    /// Reject incompatible `--json` + `--format text|markdown`.
425    ///
426    /// # Errors
427    ///
428    /// Returns [`crate::error::ErrorKind::Usage`] when `--json` is combined with
429    /// `--format text` or `--format markdown`.
430    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}