use std::path::PathBuf;
use clap::{Parser, Subcommand, ValueEnum};
#[derive(Debug, Clone, Parser)]
#[command(
name = "docsrs-cli",
version,
about = "One-shot CLI for crates.io and docs.rs documentation",
long_about = "One-shot BORN→EXECUTE→DIE CLI for crates.io and docs.rs.
\
Stdout is the data contract (JSON or markdown). Stderr is diagnostics only.
\
JSON is automatic when stdout is not a TTY; force human with --format markdown|text.
\
First Ctrl-C / SIGINT cancels cooperatively (exit 130). Second Ctrl-C within 5s force-exits 130.
\
SIGTERM and SIGHUP cancel as terminate (exit 143). On Windows, Ctrl+Break and console close also terminate (143).
\
Broken pipe on stdout is exit 141 (pipeline-safe; no stack trace).",
after_help = "Examples:
\
docsrs-cli search-crates serde --json
\
docsrs-cli readme tokio --json
\
docsrs-cli get-item clap trait clap::Parser --json
\
docsrs-cli search-in-crate reqwest Client --json
\
docsrs-cli doctor --json
\
docsrs-cli config path --json
\
docsrs-cli config show --json
\
docsrs-cli config init --json
\
docsrs-cli commands --json
\
docsrs-cli completions bash
\
docsrs-cli --dry-run readme serde
\
# Agents: JSON is auto when stdout is not a TTY; force markdown with --format markdown",
disable_help_subcommand = false
)]
pub struct Cli {
#[arg(long, global = true)]
pub json: bool,
#[arg(long, global = true, value_enum)]
pub format: Option<OutputFormat>,
#[arg(long, global = true, env = "DOCSRS_CLI_TIMEOUT_SECS")]
pub timeout: Option<u64>,
#[arg(long, global = true)]
pub connect_timeout: Option<u64>,
#[arg(long, global = true, env = "DOCSRS_CLI_USER_AGENT")]
pub user_agent: Option<String>,
#[arg(long, global = true, env = "DOCSRS_CLI_LANG")]
pub lang: Option<String>,
#[arg(long, global = true, env = "DOCSRS_CLI_CONFIG_DIR")]
pub config_dir: Option<PathBuf>,
#[arg(long, global = true, env = "DOCSRS_CLI_CACHE_DIR")]
pub cache_dir: Option<PathBuf>,
#[arg(long, global = true)]
pub no_cache: bool,
#[arg(long, global = true, env = "DOCSRS_CLI_CACHE_TTL_SECS")]
pub cache_ttl_secs: Option<u64>,
#[arg(long, global = true, env = "DOCSRS_CLI_MAX_CACHE_BYTES")]
pub max_cache_bytes: Option<u64>,
#[arg(long, global = true)]
pub dry_run: bool,
#[arg(long, global = true, env = "DOCSRS_CLI_MAX_BODY_BYTES")]
pub max_body_bytes: Option<u64>,
#[arg(long, global = true, env = "DOCSRS_CLI_MAX_OUTPUT_BYTES")]
pub max_output_bytes: Option<u64>,
#[arg(long, global = true)]
pub rate_limit_delay_ms: Option<u64>,
#[arg(long, global = true, env = "DOCSRS_CLI_MAX_CONCURRENCY")]
pub max_concurrency: Option<u32>,
#[arg(long, global = true, env = "DOCSRS_CLI_MAX_RETRIES")]
pub max_retries: Option<u32>,
#[arg(long, global = true, env = "DOCSRS_CLI_RETRY_BASE_MS")]
pub retry_base_ms: Option<u64>,
#[arg(long, global = true, env = "DOCSRS_CLI_RETRY_MAX_DELAY_MS")]
pub retry_max_delay_ms: Option<u64>,
#[arg(long, global = true, env = "DOCSRS_CLI_DISABLE_RETRY")]
pub disable_retry: bool,
#[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
pub verbose: u8,
#[arg(short = 'q', long, global = true)]
pub quiet: bool,
#[arg(long, global = true)]
pub no_color: bool,
#[command(subcommand)]
pub command: Commands,
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum OutputFormat {
Markdown,
Json,
Text,
}
#[derive(Debug, Clone, Subcommand)]
pub enum Commands {
SearchCrates {
query: String,
#[arg(long, default_value_t = 10)]
per_page: u32,
#[arg(long, value_enum, default_value_t = SortKind::Relevance)]
sort: SortKind,
#[arg(long, default_value_t = 1)]
page: u32,
},
Readme {
crate_name: String,
#[arg(long)]
crate_version: Option<String>,
},
GetItem {
crate_name: String,
item_type: String,
item_path: String,
#[arg(long)]
crate_version: Option<String>,
},
SearchInCrate {
crate_name: String,
#[arg(default_value = "")]
query: String,
#[arg(long)]
crate_version: Option<String>,
#[arg(long)]
item_type: Option<String>,
#[arg(long, default_value_t = 100)]
limit: u32,
},
Version,
Doctor,
Commands,
Schema {
#[arg(long)]
cmd: String,
},
Completions {
#[arg(value_enum)]
shell: Shell,
},
Cache {
#[command(subcommand)]
action: CacheAction,
},
Config {
#[command(subcommand)]
action: ConfigAction,
},
}
#[derive(Debug, Clone, Subcommand)]
pub enum CacheAction {
Clear,
Stats,
}
#[derive(Debug, Clone, Subcommand)]
pub enum ConfigAction {
Path,
Show,
Init {
#[arg(long)]
force: bool,
},
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
pub enum SortKind {
Relevance,
Downloads,
#[value(name = "recent-downloads")]
RecentDownloads,
#[value(name = "recent-updates")]
RecentUpdates,
New,
Alphabetical,
}
impl SortKind {
pub fn as_api_str(self) -> &'static str {
match self {
Self::Relevance => "relevance",
Self::Downloads => "downloads",
Self::RecentDownloads => "recent-downloads",
Self::RecentUpdates => "recent-updates",
Self::New => "new",
Self::Alphabetical => "alphabetical",
}
}
}
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Shell {
Bash,
Zsh,
Fish,
Elvish,
#[value(name = "power-shell", alias = "powershell")]
PowerShell,
}
impl Shell {
pub fn as_str(self) -> &'static str {
match self {
Self::Bash => "bash",
Self::Zsh => "zsh",
Self::Fish => "fish",
Self::Elvish => "elvish",
Self::PowerShell => "power-shell",
}
}
pub fn to_clap_shell(self) -> clap_complete::Shell {
match self {
Self::Bash => clap_complete::Shell::Bash,
Self::Zsh => clap_complete::Shell::Zsh,
Self::Fish => clap_complete::Shell::Fish,
Self::Elvish => clap_complete::Shell::Elvish,
Self::PowerShell => clap_complete::Shell::PowerShell,
}
}
}
impl Cli {
pub fn wants_json(&self, stdout_is_terminal: bool) -> bool {
if self.json || matches!(self.format, Some(OutputFormat::Json)) {
return true;
}
if matches!(
self.format,
Some(OutputFormat::Markdown | OutputFormat::Text)
) {
return false;
}
!stdout_is_terminal
}
pub fn validate_format_conflict(&self) -> Result<(), crate::error::AppError> {
use crate::error::{AppError, ErrorKind};
if self.json
&& matches!(
self.format,
Some(OutputFormat::Text | OutputFormat::Markdown)
)
{
return Err(AppError::new(
ErrorKind::Usage,
"cannot combine --json with --format text or --format markdown",
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
#[test]
fn sort_api_strings() {
assert_eq!(SortKind::Relevance.as_api_str(), "relevance");
assert_eq!(SortKind::Downloads.as_api_str(), "downloads");
assert_eq!(SortKind::RecentDownloads.as_api_str(), "recent-downloads");
assert_eq!(SortKind::RecentUpdates.as_api_str(), "recent-updates");
assert_eq!(SortKind::New.as_api_str(), "new");
assert_eq!(SortKind::Alphabetical.as_api_str(), "alphabetical");
}
#[test]
fn wants_json_from_flag_or_format() {
let a = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
assert!(a.wants_json(true));
assert!(a.wants_json(false));
let b = Cli::try_parse_from(["docsrs-cli", "version", "--format", "json"]).unwrap();
assert!(b.wants_json(true));
let c = Cli::try_parse_from(["docsrs-cli", "version"]).unwrap();
assert!(!c.wants_json(true), "TTY defaults to human markdown");
assert!(c.wants_json(false), "non-TTY auto-JSON for agents");
let d = Cli::try_parse_from(["docsrs-cli", "version", "--format", "markdown"]).unwrap();
assert!(!d.wants_json(false), "explicit format overrides auto-JSON");
let e = Cli::try_parse_from(["docsrs-cli", "version", "--format", "text"]).unwrap();
assert!(!e.wants_json(false));
}
#[test]
fn parse_commands_subcommand() {
let cli = Cli::try_parse_from(["docsrs-cli", "commands"]).unwrap();
assert!(matches!(cli.command, Commands::Commands));
}
#[test]
fn format_conflict_detected() {
let cli =
Cli::try_parse_from(["docsrs-cli", "version", "--json", "--format", "text"]).unwrap();
assert!(cli.validate_format_conflict().is_err());
let ok = Cli::try_parse_from(["docsrs-cli", "version", "--json"]).unwrap();
assert!(ok.validate_format_conflict().is_ok());
}
#[test]
fn shell_mapping() {
assert!(matches!(
Shell::Bash.to_clap_shell(),
clap_complete::Shell::Bash
));
assert!(matches!(
Shell::Zsh.to_clap_shell(),
clap_complete::Shell::Zsh
));
assert!(matches!(
Shell::Fish.to_clap_shell(),
clap_complete::Shell::Fish
));
assert!(matches!(
Shell::Elvish.to_clap_shell(),
clap_complete::Shell::Elvish
));
assert!(matches!(
Shell::PowerShell.to_clap_shell(),
clap_complete::Shell::PowerShell
));
}
#[test]
fn powershell_alias_and_canonical_parse() {
let a = Cli::try_parse_from(["docsrs-cli", "completions", "powershell"]).unwrap();
let b = Cli::try_parse_from(["docsrs-cli", "completions", "power-shell"]).unwrap();
match (a.command, b.command) {
(Commands::Completions { shell: sa }, Commands::Completions { shell: sb }) => {
assert!(matches!(sa, Shell::PowerShell));
assert!(matches!(sb, Shell::PowerShell));
}
_ => panic!("expected completions commands"),
}
}
#[test]
fn parse_search_crates_defaults() {
let cli = Cli::try_parse_from(["docsrs-cli", "search-crates", "serde"]).unwrap();
match cli.command {
Commands::SearchCrates {
query,
per_page,
sort,
page,
} => {
assert_eq!(query, "serde");
assert_eq!(per_page, 10);
assert_eq!(sort, SortKind::Relevance);
assert_eq!(page, 1);
}
_ => panic!("wrong command"),
}
}
}