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    /// Disable HTTP retries (incident kill switch / debug)
129    #[arg(long, global = true)]
130    pub disable_retry: bool,
131
132    /// Increase stderr verbosity
133    #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
134    pub verbose: u8,
135
136    /// Suppress non-error stderr prose
137    #[arg(short = 'q', long, global = true)]
138    pub quiet: bool,
139
140    /// Disable ANSI colors on stderr
141    #[arg(long, global = true)]
142    pub no_color: bool,
143
144    #[command(subcommand)]
145    /// Subcommand to execute for this invocation.
146    pub command: Commands,
147}
148
149/// Human or machine output format selection.
150#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
151pub enum OutputFormat {
152    /// Markdown rendered for humans.
153    Markdown,
154    /// JSON envelope for agents.
155    Json,
156    /// Plain-text rendering (alias of markdown for most commands).
157    Text,
158}
159
160/// Product subcommands exposed on the CLI surface.
161#[derive(Debug, Clone, Subcommand)]
162pub enum Commands {
163    /// Search crates on crates.io
164    SearchCrates {
165        /// Search keywords (English). Optional when `--page-token` carries a full query string.
166        #[arg(default_value = "")]
167        query: String,
168        /// Results per page (max 100)
169        #[arg(long, default_value_t = 10)]
170        per_page: u32,
171        /// Sort order
172        #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
173        sort: SortKind,
174        /// Page number (1-based). Conflicts with `--page-token`.
175        #[arg(long, default_value_t = 1, conflicts_with = "page_token")]
176        page: u32,
177        /// Opaque pagination token from `meta.next_page` / `meta.prev_page` (full query or seek).
178        #[arg(long, conflicts_with = "page")]
179        page_token: Option<String>,
180    },
181    /// Fetch crate overview docblock from docs.rs (not git README)
182    Readme {
183        /// Crate name on crates.io or a stdlib crate.
184        crate_name: String,
185        /// Optional crate version (`latest` when omitted).
186        #[arg(long)]
187        crate_version: Option<String>,
188    },
189    /// Fetch documentation for a typed item
190    GetItem {
191        /// Crate name on crates.io or a stdlib crate.
192        crate_name: String,
193        /// Kind: module|struct|trait|enum|union|fn|function|method|type|const|constant|static|macro|attr|attribute|derive
194        item_type: String,
195        /// Path with `::` or `/` (e.g. `tokio::runtime::Runtime`, `runtime/Runtime`, `async_trait`)
196        item_path: String,
197        /// Optional crate version (`latest` when omitted).
198        #[arg(long)]
199        crate_version: Option<String>,
200        /// On 404, suggest nearby symbols from all.html (one extra request; exact/prefix/substring/edit-distance).
201        #[arg(long)]
202        suggest: bool,
203    },
204    /// Search symbols in crate all.html index
205    SearchInCrate {
206        /// Crate name on crates.io or a stdlib crate.
207        crate_name: String,
208        /// Text filter; empty string lists all classified items
209        #[arg(default_value = "")]
210        query: String,
211        /// Optional crate version (`latest` when omitted).
212        #[arg(long)]
213        crate_version: Option<String>,
214        /// Optional item-kind filter (`struct`, `fn`, `method`, …).
215        #[arg(long)]
216        item_type: Option<String>,
217        /// Maximum hits to emit (clamped to 1000).
218        #[arg(long, default_value_t = 100)]
219        limit: u32,
220        /// Match policy: exact | prefix (default) | substring
221        #[arg(long, default_value = "prefix")]
222        r#match: String,
223    },
224    /// Print binary version
225    Version,
226    /// Validate local TLS/config readiness
227    Doctor {
228        /// Probe crates.io / docs.rs over the network (opt-in)
229        #[arg(long)]
230        online: bool,
231    },
232    /// List the full command tree for agent discovery
233    Commands,
234    /// Emit JSON Schema for a command
235    Schema {
236        /// Command name whose schema should be printed.
237        #[arg(long)]
238        cmd: String,
239    },
240    /// Generate shell completions
241    Completions {
242        /// Target shell for completion scripts.
243        #[arg(value_enum)]
244        shell: Shell,
245    },
246    /// Inspect or clear the XDG HTTP disk cache
247    Cache {
248        /// Cache maintenance action.
249        #[command(subcommand)]
250        action: CacheAction,
251    },
252    /// Manage XDG config paths and the optional config.toml (no secrets / no .env)
253    Config {
254        /// Config lifecycle action.
255        #[command(subcommand)]
256        action: ConfigAction,
257    },
258}
259
260/// Cache maintenance subcommands.
261#[derive(Debug, Clone, Subcommand)]
262pub enum CacheAction {
263    /// Delete all cached HTTP bodies under the cache dir
264    Clear,
265    /// Report entry count, total bytes, and budget
266    Stats,
267}
268
269/// XDG config lifecycle subcommands (no API keys; product is public HTTP only).
270#[derive(Debug, Clone, Subcommand)]
271pub enum ConfigAction {
272    /// Print resolved config/cache directories and which layer won
273    Path,
274    /// Print effective runtime configuration (merged defaults + TOML + env + CLI)
275    Show,
276    /// Create a default config.toml under the resolved config directory
277    Init {
278        /// Overwrite an existing config.toml
279        #[arg(long)]
280        force: bool,
281    },
282}
283
284/// crates.io search sort order.
285#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
286pub enum SortKind {
287    /// Rank by search relevance.
288    Relevance,
289    /// Rank by total downloads.
290    Downloads,
291    /// Rank by recent downloads.
292    #[value(name = "recent-downloads")]
293    RecentDownloads,
294    /// Rank by recent crate updates.
295    #[value(name = "recent-updates")]
296    RecentUpdates,
297    /// Rank newest crates first.
298    New,
299    /// Rank alphabetically by crate name.
300    Alphabetical,
301}
302
303impl SortKind {
304    /// crates.io API `sort=` query value.
305    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/// Shells supported by the `completions` subcommand.
318#[derive(Debug, Clone, Copy, ValueEnum)]
319pub enum Shell {
320    /// Bash completions.
321    Bash,
322    /// Zsh completions.
323    Zsh,
324    /// Fish completions.
325    Fish,
326    /// Elvish completions.
327    Elvish,
328    /// Canonical CLI value is `power-shell`; `powershell` is accepted as alias.
329    #[value(name = "power-shell", alias = "powershell")]
330    PowerShell,
331}
332
333impl Shell {
334    /// Stable CLI / JSON name for this shell.
335    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    /// Convert to the `clap_complete` shell enum.
346    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    /// Whether JSON envelope is requested.
359    ///
360    /// Agent-first rules (stdin/stdout LLM contract):
361    /// - `--json` or `--format json` → JSON
362    /// - `--format markdown|text` → human (never auto-JSON)
363    /// - otherwise → JSON when stdout is not a TTY (pipe/agent), markdown on TTY
364    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    /// Reject incompatible `--json` + `--format text|markdown`.
378    ///
379    /// # Errors
380    ///
381    /// Returns [`crate::error::ErrorKind::Usage`] when `--json` is combined with
382    /// `--format text` or `--format markdown`.
383    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}