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
61    #[arg(long, global = true, env = "DOCSRS_CLI_TIMEOUT_SECS")]
62    pub timeout: Option<u64>,
63
64    /// Connect timeout in seconds
65    #[arg(long, global = true)]
66    pub connect_timeout: Option<u64>,
67
68    /// Override User-Agent
69    #[arg(long, global = true, env = "DOCSRS_CLI_USER_AGENT")]
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, env = "DOCSRS_CLI_LANG")]
74    pub lang: Option<String>,
75
76    /// Override XDG config directory
77    #[arg(long, global = true, env = "DOCSRS_CLI_CONFIG_DIR")]
78    pub config_dir: Option<PathBuf>,
79
80    /// Override XDG cache directory for HTTP body cache
81    #[arg(long, global = true, env = "DOCSRS_CLI_CACHE_DIR")]
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, env = "DOCSRS_CLI_CACHE_TTL_SECS")]
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, env = "DOCSRS_CLI_MAX_CACHE_BYTES")]
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, env = "DOCSRS_CLI_MAX_BODY_BYTES")]
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, env = "DOCSRS_CLI_MAX_OUTPUT_BYTES")]
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, env = "DOCSRS_CLI_MAX_CONCURRENCY")]
114    pub max_concurrency: Option<u32>,
115
116    /// Max HTTP retries for transient errors (after the first attempt)
117    #[arg(long, global = true, env = "DOCSRS_CLI_MAX_RETRIES")]
118    pub max_retries: Option<u32>,
119
120    /// Base backoff delay in milliseconds for HTTP retries
121    #[arg(long, global = true, env = "DOCSRS_CLI_RETRY_BASE_MS")]
122    pub retry_base_ms: Option<u64>,
123
124    /// Maximum single HTTP retry sleep in milliseconds
125    #[arg(long, global = true, env = "DOCSRS_CLI_RETRY_MAX_DELAY_MS")]
126    pub retry_max_delay_ms: Option<u64>,
127
128    /// Disable HTTP retries (incident kill switch / debug)
129    #[arg(long, global = true, env = "DOCSRS_CLI_DISABLE_RETRY")]
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)
166        query: String,
167        /// Results per page (max 100)
168        #[arg(long, default_value_t = 10)]
169        per_page: u32,
170        /// Sort order
171        #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
172        sort: SortKind,
173        /// Page number (1-based)
174        #[arg(long, default_value_t = 1)]
175        page: u32,
176    },
177    /// Fetch crate overview docblock from docs.rs (not git README)
178    Readme {
179        /// Crate name on crates.io or a stdlib crate.
180        crate_name: String,
181        /// Optional crate version (`latest` when omitted).
182        #[arg(long)]
183        crate_version: Option<String>,
184    },
185    /// Fetch documentation for a typed item
186    GetItem {
187        /// Crate name on crates.io or a stdlib crate.
188        crate_name: String,
189        /// Kind: module|struct|trait|enum|union|fn|function|type|const|constant|static|macro|attr|attribute|derive
190        item_type: String,
191        /// Path with `::` or `/` (e.g. `tokio::runtime::Runtime`, `runtime/Runtime`, `async_trait`)
192        item_path: String,
193        /// Optional crate version (`latest` when omitted).
194        #[arg(long)]
195        crate_version: Option<String>,
196    },
197    /// Search symbols in crate all.html index
198    SearchInCrate {
199        /// Crate name on crates.io or a stdlib crate.
200        crate_name: String,
201        /// Substring filter; empty string lists all classified items
202        #[arg(default_value = "")]
203        query: String,
204        /// Optional crate version (`latest` when omitted).
205        #[arg(long)]
206        crate_version: Option<String>,
207        /// Optional item-kind filter (`struct`, `fn`, …).
208        #[arg(long)]
209        item_type: Option<String>,
210        /// Maximum hits to emit.
211        #[arg(long, default_value_t = 100)]
212        limit: u32,
213    },
214    /// Print binary version
215    Version,
216    /// Validate local TLS/config readiness
217    Doctor,
218    /// List the full command tree for agent discovery
219    Commands,
220    /// Emit JSON Schema for a command
221    Schema {
222        /// Command name whose schema should be printed.
223        #[arg(long)]
224        cmd: String,
225    },
226    /// Generate shell completions
227    Completions {
228        /// Target shell for completion scripts.
229        #[arg(value_enum)]
230        shell: Shell,
231    },
232    /// Inspect or clear the XDG HTTP disk cache
233    Cache {
234        /// Cache maintenance action.
235        #[command(subcommand)]
236        action: CacheAction,
237    },
238    /// Manage XDG config paths and the optional config.toml (no secrets / no .env)
239    Config {
240        /// Config lifecycle action.
241        #[command(subcommand)]
242        action: ConfigAction,
243    },
244}
245
246/// Cache maintenance subcommands.
247#[derive(Debug, Clone, Subcommand)]
248pub enum CacheAction {
249    /// Delete all cached HTTP bodies under the cache dir
250    Clear,
251    /// Report entry count, total bytes, and budget
252    Stats,
253}
254
255/// XDG config lifecycle subcommands (no API keys; product is public HTTP only).
256#[derive(Debug, Clone, Subcommand)]
257pub enum ConfigAction {
258    /// Print resolved config/cache directories and which layer won
259    Path,
260    /// Print effective runtime configuration (merged defaults + TOML + env + CLI)
261    Show,
262    /// Create a default config.toml under the resolved config directory
263    Init {
264        /// Overwrite an existing config.toml
265        #[arg(long)]
266        force: bool,
267    },
268}
269
270/// crates.io search sort order.
271#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
272pub enum SortKind {
273    /// Rank by search relevance.
274    Relevance,
275    /// Rank by total downloads.
276    Downloads,
277    /// Rank by recent downloads.
278    #[value(name = "recent-downloads")]
279    RecentDownloads,
280    /// Rank by recent crate updates.
281    #[value(name = "recent-updates")]
282    RecentUpdates,
283    /// Rank newest crates first.
284    New,
285    /// Rank alphabetically by crate name.
286    Alphabetical,
287}
288
289impl SortKind {
290    /// crates.io API `sort=` query value.
291    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/// Shells supported by the `completions` subcommand.
304#[derive(Debug, Clone, Copy, ValueEnum)]
305pub enum Shell {
306    /// Bash completions.
307    Bash,
308    /// Zsh completions.
309    Zsh,
310    /// Fish completions.
311    Fish,
312    /// Elvish completions.
313    Elvish,
314    /// Canonical CLI value is `power-shell`; `powershell` is accepted as alias.
315    #[value(name = "power-shell", alias = "powershell")]
316    PowerShell,
317}
318
319impl Shell {
320    /// Stable CLI / JSON name for this shell.
321    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    /// Convert to the `clap_complete` shell enum.
332    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    /// Whether JSON envelope is requested.
345    ///
346    /// Agent-first rules (stdin/stdout LLM contract):
347    /// - `--json` or `--format json` → JSON
348    /// - `--format markdown|text` → human (never auto-JSON)
349    /// - otherwise → JSON when stdout is not a TTY (pipe/agent), markdown on TTY
350    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    /// Reject incompatible `--json` + `--format text|markdown`.
364    ///
365    /// # Errors
366    ///
367    /// Returns [`crate::error::ErrorKind::Usage`] when `--json` is combined with
368    /// `--format text` or `--format markdown`.
369    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}