docsrs_cli/cli/mod.rs
1//! Clap surface for docsrs-cli.
2//!
3//! [`overrides`] applies the parsed flags onto the loaded configuration.
4//! [`agent_args`] holds the payload reduction flags shared by every subcommand.
5
6pub mod agent_args;
7pub mod destructive;
8pub mod overrides;
9
10use std::path::PathBuf;
11
12use clap::{Parser, Subcommand, ValueEnum};
13
14pub use agent_args::AgentArgs;
15
16use crate::config::{DEFAULT_PER_PAGE, DEFAULT_SEARCH_LIMIT};
17
18#[derive(Debug, Clone, Parser)]
19#[command(
20 name = "docsrs-cli",
21 version,
22 about = "One-shot CLI for crates.io and docs.rs documentation",
23 long_about = "One-shot BORN→EXECUTE→DIE CLI for crates.io and docs.rs.
24\
25Stdout is the data contract (JSON or markdown). Stderr is diagnostics only.
26\
27JSON is automatic when stdout is not a TTY; force human with --format markdown|text.
28\
29First Ctrl-C / SIGINT cancels cooperatively (exit 130). Second Ctrl-C within 5s force-exits 130.
30\
31SIGTERM and SIGHUP cancel as terminate (exit 143). On Windows, Ctrl+Break and console close also terminate (143).
32\
33Broken pipe on stdout is exit 141 (pipeline-safe; no stack trace).",
34 after_help = "Examples:
35 \
36docsrs-cli search-crates serde --json
37 \
38docsrs-cli readme tokio --json
39 \
40docsrs-cli get-item clap trait clap::Parser --json
41 \
42docsrs-cli search-in-crate reqwest Client --json
43 \
44docsrs-cli doctor --json
45 \
46docsrs-cli config path --json
47 \
48docsrs-cli config show --json
49 \
50docsrs-cli config init --json
51 \
52docsrs-cli commands --json
53 \
54docsrs-cli completions bash
55 \
56docsrs-cli --dry-run readme serde
57 \
58# Agents: JSON is auto when stdout is not a TTY; force markdown with --format markdown",
59 disable_help_subcommand = false
60)]
61/// Top-level clap parser for the `docsrs-cli` binary.
62pub struct Cli {
63 /// Emit JSON envelope on stdout
64 #[arg(long, global = true)]
65 pub json: bool,
66
67 /// Output format (json is alias of --json)
68 #[arg(long, global = true, value_enum)]
69 pub format: Option<OutputFormat>,
70
71 /// Wall-clock timeout in seconds (must be >= 1 when set)
72 #[arg(long, global = true)]
73 pub timeout: Option<u64>,
74
75 /// Connect timeout in seconds (must be >= 1 when set)
76 #[arg(long, global = true)]
77 pub connect_timeout: Option<u64>,
78
79 /// Override User-Agent
80 #[arg(long, global = true)]
81 pub user_agent: Option<String>,
82
83 /// Force human stderr locale: en or pt-BR (fail-closed; JSON stays English)
84 #[arg(long, global = true)]
85 pub lang: Option<String>,
86
87 /// Override XDG config directory
88 #[arg(long, global = true)]
89 pub config_dir: Option<PathBuf>,
90
91 /// Override XDG cache directory for HTTP body cache
92 #[arg(long, global = true)]
93 pub cache_dir: Option<PathBuf>,
94
95 /// Disable disk cache (always hit network)
96 #[arg(long, global = true)]
97 pub no_cache: bool,
98
99 /// Disk cache TTL in seconds (default 86400 = 24h)
100 #[arg(long, global = true)]
101 pub cache_ttl_secs: Option<u64>,
102
103 /// Soft cap on disk cache size in bytes (default 268435456 = 256 MiB; 0 = unlimited)
104 #[arg(long, global = true)]
105 pub max_cache_bytes: Option<u64>,
106
107 /// Plan URLs without opening network sockets
108 #[arg(long, global = true)]
109 pub dry_run: bool,
110
111 /// Cap downloaded body size in bytes (hard max 10485760 = 10 MiB; cannot raise above)
112 #[arg(long, global = true)]
113 pub max_body_bytes: Option<u64>,
114
115 /// Agent-native payload reduction knobs (see [`AgentArgs`]).
116 #[command(flatten)]
117 pub agent: AgentArgs,
118
119 /// Minimum delay between requests to the same host (ms)
120 #[arg(long, global = true)]
121 pub rate_limit_delay_ms: Option<u64>,
122
123 /// Max concurrent CPU parse workers (`0` = auto from CPUs and free RAM)
124 #[arg(long, global = true)]
125 pub max_concurrency: Option<u32>,
126
127 /// Max HTTP retries for transient errors (after the first attempt)
128 #[arg(long, global = true)]
129 pub max_retries: Option<u32>,
130
131 /// Base backoff delay in milliseconds for HTTP retries
132 #[arg(long, global = true)]
133 pub retry_base_ms: Option<u64>,
134
135 /// Maximum single HTTP retry sleep in milliseconds
136 #[arg(long, global = true)]
137 pub retry_max_delay_ms: Option<u64>,
138
139 /// Total HTTP retry wall budget in milliseconds (`0` = derive from --timeout)
140 #[arg(long, global = true)]
141 pub retry_max_elapsed_ms: Option<u64>,
142
143 /// Disable HTTP retries (incident kill switch / debug)
144 #[arg(long, global = true)]
145 pub disable_retry: bool,
146
147 /// Allow loopback origins (`127.0.0.1` / `localhost`) for offline wiremock
148 ///
149 /// Also settable via XDG `config.toml` `allow_loopback = true`. Never via env.
150 #[arg(long, global = true)]
151 pub allow_loopback: bool,
152
153 /// Increase stderr verbosity
154 #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
155 pub verbose: u8,
156
157 /// Suppress non-error stderr prose
158 #[arg(short = 'q', long, global = true)]
159 pub quiet: bool,
160
161 /// Disable ANSI colors on stderr
162 #[arg(long, global = true)]
163 pub no_color: bool,
164
165 #[command(subcommand)]
166 /// Subcommand to execute for this invocation.
167 pub command: Commands,
168}
169
170/// Human or machine output format selection.
171#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
172pub enum OutputFormat {
173 /// Markdown rendered for humans.
174 Markdown,
175 /// JSON envelope for agents.
176 Json,
177 /// Plain-text rendering (alias of markdown for most commands).
178 Text,
179}
180
181/// Product subcommands exposed on the CLI surface.
182#[derive(Debug, Clone, Subcommand)]
183pub enum Commands {
184 /// Search crates on crates.io
185 SearchCrates {
186 /// Search keywords (English). Optional when `--page-token` carries a full query string.
187 #[arg(default_value = "")]
188 query: String,
189 /// Results per page (max 100)
190 #[arg(long, default_value_t = DEFAULT_PER_PAGE)]
191 per_page: u32,
192 /// Sort order
193 #[arg(long, value_enum, default_value_t = SortKind::Relevance)]
194 sort: SortKind,
195 /// Page number (1-based). Conflicts with `--page-token`.
196 #[arg(long, default_value_t = 1, conflicts_with = "page_token")]
197 page: u32,
198 /// Opaque pagination token from `meta.next_page` / `meta.prev_page` (full query or seek).
199 #[arg(long, conflicts_with = "page")]
200 page_token: Option<String>,
201 },
202 /// Fetch crate overview docblock from docs.rs (not git README)
203 Readme {
204 /// Crate name on crates.io or a stdlib crate (`name` or `name@1.2.3`).
205 crate_name: String,
206 /// Optional crate version (`latest` when omitted). Conflicts if it differs from `crate@…`.
207 #[arg(long)]
208 crate_version: Option<String>,
209 },
210 /// Fetch documentation for a typed item
211 GetItem {
212 /// Crate name on crates.io or a stdlib crate (`name` or `name@1.2.3`).
213 crate_name: String,
214 /// Kind: module|mod|struct|trait|enum|union|fn|function|method|type|const|constant|static|macro|attr|attribute|derive|variant|structfield|field
215 item_type: String,
216 /// Path with `::` or `/` (e.g. `Runtime::new`, `runtime/Runtime`, `tokio::spawn`)
217 ///
218 /// `method`, `type` and `const` also accept `Parent::member` for members
219 /// that rustdoc renders as an anchor on the parent page instead of a page
220 /// of their own (`iter::Iterator::Item`, `time::Duration::MAX`).
221 item_path: String,
222 /// Optional crate version (`latest` when omitted). Conflicts if it differs from `crate@…`.
223 #[arg(long)]
224 crate_version: Option<String>,
225 /// On 404, always report the suggestion list, even when it is empty ("(none)").
226 ///
227 /// Recovery already ranks nearby symbols from all.html without this flag
228 /// (exact/prefix/substring/edit-distance); the flag only guarantees the
229 /// field is present so an agent can tell "no candidates" from "not tried".
230 #[arg(long)]
231 suggest: bool,
232 },
233 /// Search symbols in crate all.html index
234 SearchInCrate {
235 /// Crate name on crates.io or a stdlib crate (`name` or `name@1.2.3`).
236 crate_name: String,
237 /// Text filter; empty string lists all classified items
238 #[arg(default_value = "")]
239 query: String,
240 /// Optional crate version (`latest` when omitted). Conflicts if it differs from `crate@…`.
241 #[arg(long)]
242 crate_version: Option<String>,
243 /// Optional item-kind filter (`struct`, `fn`, `method`, …).
244 #[arg(long)]
245 item_type: Option<String>,
246 /// Maximum hits to emit (clamped to 1000).
247 #[arg(long, default_value_t = DEFAULT_SEARCH_LIMIT)]
248 limit: u32,
249 /// Match policy: exact | prefix (default) | substring
250 #[arg(long, default_value = "prefix")]
251 r#match: String,
252 },
253 /// Print binary version
254 Version,
255 /// Validate local TLS/config readiness
256 Doctor {
257 /// Probe crates.io / docs.rs over the network (opt-in)
258 #[arg(long)]
259 online: bool,
260 },
261 /// List the full command tree for agent discovery
262 Commands,
263 /// Emit JSON Schema for a command
264 Schema {
265 /// Command name whose schema should be printed.
266 #[arg(long)]
267 cmd: String,
268 },
269 /// Generate shell completions
270 Completions {
271 /// Target shell for completion scripts.
272 #[arg(value_enum)]
273 shell: Shell,
274 },
275 /// Inspect or clear the XDG HTTP disk cache
276 Cache {
277 /// Cache maintenance action.
278 #[command(subcommand)]
279 action: CacheAction,
280 },
281 /// Manage XDG config paths and the optional config.toml (no secrets / no .env)
282 Config {
283 /// Config lifecycle action.
284 #[command(subcommand)]
285 action: ConfigAction,
286 },
287}
288
289/// Cache maintenance subcommands.
290#[derive(Debug, Clone, Subcommand)]
291pub enum CacheAction {
292 /// Print resolved cache root and which layer won
293 Path,
294 /// Delete all cached HTTP bodies under the cache dir
295 ///
296 /// Destructive verbs designate their target in argv and never inherit it
297 /// from ambient state. Without `--cache-dir` the root comes from the XDG
298 /// layer, which the caller never named, so `--yes` is the explicit waiver
299 /// that accepts an ambient target. Absent both, this fails with exit 64 and
300 /// deletes nothing.
301 Clear {
302 /// Accept the ambient (XDG-resolved) cache root as the deletion target
303 #[arg(long)]
304 yes: bool,
305 },
306 /// Report entry count, total bytes, and budget
307 Stats,
308}
309
310/// XDG config lifecycle subcommands (no API keys; product is public HTTP only).
311#[derive(Debug, Clone, Subcommand)]
312pub enum ConfigAction {
313 /// Print resolved config/cache directories and which layer won
314 Path,
315 /// Print effective runtime configuration (merged defaults + TOML + CLI; no env)
316 Show,
317 /// Create a default config.toml under the resolved config directory
318 ///
319 /// `--force` replaces a file the caller may never have named. Destructive
320 /// verbs designate their target in argv and never inherit it from ambient
321 /// state, so `--config-dir` names the directory and `--yes` is the explicit
322 /// waiver that accepts the XDG one. With `--force` and neither of the two,
323 /// this fails with exit 64 and writes nothing. Without `--force` nothing is
324 /// destroyed, so no waiver is asked for.
325 Init {
326 /// Overwrite an existing config.toml
327 #[arg(long)]
328 force: bool,
329 /// Accept the ambient (XDG-resolved) config directory as the target of `--force`
330 #[arg(long)]
331 yes: bool,
332 },
333}
334
335/// crates.io search sort order.
336#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
337pub enum SortKind {
338 /// Rank by search relevance.
339 Relevance,
340 /// Rank by total downloads.
341 Downloads,
342 /// Rank by recent downloads.
343 #[value(name = "recent-downloads")]
344 RecentDownloads,
345 /// Rank by recent crate updates.
346 #[value(name = "recent-updates")]
347 RecentUpdates,
348 /// Rank newest crates first.
349 New,
350 /// Rank alphabetically by crate name.
351 Alphabetical,
352}
353
354impl SortKind {
355 /// crates.io API `sort=` query value.
356 pub fn as_api_str(self) -> &'static str {
357 match self {
358 Self::Relevance => "relevance",
359 Self::Downloads => "downloads",
360 Self::RecentDownloads => "recent-downloads",
361 Self::RecentUpdates => "recent-updates",
362 Self::New => "new",
363 Self::Alphabetical => "alphabetical",
364 }
365 }
366}
367
368/// Shells supported by the `completions` subcommand.
369#[derive(Debug, Clone, Copy, ValueEnum)]
370pub enum Shell {
371 /// Bash completions.
372 Bash,
373 /// Zsh completions.
374 Zsh,
375 /// Fish completions.
376 Fish,
377 /// Elvish completions.
378 Elvish,
379 /// Canonical CLI value is `power-shell`; `powershell` is accepted as alias.
380 #[value(name = "power-shell", alias = "powershell")]
381 PowerShell,
382}
383
384impl Shell {
385 /// Stable CLI / JSON name for this shell.
386 pub fn as_str(self) -> &'static str {
387 match self {
388 Self::Bash => "bash",
389 Self::Zsh => "zsh",
390 Self::Fish => "fish",
391 Self::Elvish => "elvish",
392 Self::PowerShell => "power-shell",
393 }
394 }
395
396 /// Convert to the `clap_complete` shell enum.
397 pub fn to_clap_shell(self) -> clap_complete::Shell {
398 match self {
399 Self::Bash => clap_complete::Shell::Bash,
400 Self::Zsh => clap_complete::Shell::Zsh,
401 Self::Fish => clap_complete::Shell::Fish,
402 Self::Elvish => clap_complete::Shell::Elvish,
403 Self::PowerShell => clap_complete::Shell::PowerShell,
404 }
405 }
406}
407
408impl Commands {
409 /// Stable wire command name used in success and error JSON envelopes (DRY).
410 ///
411 /// Nested cache/config actions use the same names as `schema --cmd` aliases
412 /// (`cache-path`, `config-show`, …).
413 pub fn wire_name(&self) -> &'static str {
414 match self {
415 Self::SearchCrates { .. } => "search-crates",
416 Self::Readme { .. } => "readme",
417 Self::GetItem { .. } => "get-item",
418 Self::SearchInCrate { .. } => "search-in-crate",
419 Self::Version => "version",
420 Self::Doctor { .. } => "doctor",
421 Self::Commands => "commands",
422 Self::Schema { .. } => "schema",
423 Self::Completions { .. } => "completions",
424 Self::Cache { action } => match action {
425 CacheAction::Path => "cache-path",
426 CacheAction::Clear { .. } => "cache-clear",
427 CacheAction::Stats => "cache-stats",
428 },
429 Self::Config { action } => match action {
430 ConfigAction::Path => "config-path",
431 ConfigAction::Show => "config-show",
432 ConfigAction::Init { .. } => "config-init",
433 },
434 }
435 }
436}
437
438impl Cli {
439 /// Wire command name for the active subcommand (error/success envelopes).
440 pub fn wire_command(&self) -> &'static str {
441 self.command.wire_name()
442 }
443
444 /// Whether JSON envelope is requested.
445 ///
446 /// Agent-first rules (stdin/stdout LLM contract):
447 /// - `--json` or `--format json` → JSON
448 /// - `--format markdown|text` → human (never auto-JSON)
449 /// - otherwise → JSON when stdout is not a TTY (pipe/agent), markdown on TTY
450 pub fn wants_json(&self, stdout_is_terminal: bool) -> bool {
451 if self.json || matches!(self.format, Some(OutputFormat::Json)) {
452 return true;
453 }
454 if matches!(
455 self.format,
456 Some(OutputFormat::Markdown | OutputFormat::Text)
457 ) {
458 return false;
459 }
460 !stdout_is_terminal
461 }
462
463 /// Reject incompatible `--json` + `--format text|markdown`.
464 ///
465 /// # Errors
466 ///
467 /// Returns [`crate::error::ErrorKind::Usage`] when `--json` is combined with
468 /// `--format text` or `--format markdown`.
469 pub fn validate_format_conflict(&self) -> Result<(), crate::error::AppError> {
470 use crate::error::{AppError, ErrorDetail};
471 if self.json
472 && matches!(
473 self.format,
474 Some(OutputFormat::Text | OutputFormat::Markdown)
475 )
476 {
477 return Err(AppError::of(ErrorDetail::JsonFormatConflict));
478 }
479 Ok(())
480 }
481}
482
483#[cfg(test)]
484mod tests;