Skip to main content

docsrs_cli/
lib.rs

1//! One-shot library and CLI for crates.io search and docs.rs documentation.
2//!
3//! `docsrs-cli` is agent-first: structured data on stdout, diagnostics on stderr,
4//! deterministic exit codes, and a BORN → EXECUTE → FINALIZE → DIE lifecycle with
5//! no daemon or sticky session state.
6//!
7//! This crate **consumes** published documentation from crates.io and docs.rs
8//! (and stdlib pages on `doc.rust-lang.org`). It does **not** replace docs.rs
9//! or re-implement `cargo doc` as a proprietary host.
10//!
11//! # Concurrency model (Rules Rust — parallelism)
12//!
13//! Workload is **mixed I/O + CPU** (see binary `main`, [`concurrency`], [`http::HttpClient`]):
14//! multi-thread Tokio for HTTPS, `spawn_blocking` under
15//! [`concurrency::ConcurrencyBudget`] for HTML parse, and `rayon` for large
16//! `all.html` hit scans. Bound via `--max-concurrency` / auto CPU+RAM formula.
17//! Fixed auxiliary tasks (double-interrupt, [`shutdown::ProgressGuard`]) still
18//! abort-on-drop. Shared cancel uses `Arc<AtomicU8>`, not `Mutex` across `.await`.
19//!
20//! # HTTP retry (Rules Rust — retry/backoff)
21//!
22//! Product GETs use [`retry::RetryConfig`]: exponential full-jitter backoff,
23//! `Retry-After` delta-seconds on 429/503, no retry on permanent 4xx/parse.
24//! Kill switch: `--disable-retry` / TOML `disable_retry` / `max_retries=0`. Policy is
25//! single-layer inside [`http::HttpClient`] only.
26//!
27//! # Features
28//!
29//! This package has no Cargo feature flags. All product capabilities ship in the
30//! default build. Optional network live tests are gated by environment variables
31//! (`DOCSRS_CLI_NETWORK_TESTS`, `DOCSRS_CLI_STDLIB_NETWORK_TESTS`), not features.
32//!
33//! # Safety
34//!
35//! - Product code in `src/` contains no `unsafe` blocks.
36//! - docs.rs builds enable `doc_cfg` via `#![cfg_attr(docsrs, feature(doc_cfg))]`
37//!   (post-2025 merge of `doc_auto_cfg` into `doc_cfg`). Local `cargo +stable doc`
38//!   does not require the nightly feature gate.
39//! - TLS is rustls-only; HTTP product methods are GET-only against an allowlist.
40//! - Mermaid diagrams for the agent lifecycle live on [`run`] via `aquamarine`
41//!   (attribute macros apply to items, not the crate root).
42//!
43//! # Examples
44//!
45//! Parse a crate name at the domain boundary:
46//!
47//! ```
48//! use docsrs_cli::domain::CrateName;
49//!
50//! let name = CrateName::parse("serde").expect("valid crate name");
51//! assert_eq!(name.as_str(), "serde");
52//! ```
53//!
54//! Map error kinds to process exit codes:
55//!
56//! ```
57//! use docsrs_cli::error::ErrorKind;
58//!
59//! assert_eq!(ErrorKind::NotFound.exit_code(), 66);
60//! assert!(ErrorKind::Timeout.retryable());
61//! ```
62
63#![warn(missing_docs)]
64#![warn(rustdoc::missing_crate_level_docs)]
65#![warn(rustdoc::broken_intra_doc_links)]
66#![warn(rustdoc::private_intra_doc_links)]
67#![deny(rustdoc::invalid_html_tags)]
68#![deny(rustdoc::invalid_rust_codeblocks)]
69#![deny(rustdoc::bare_urls)]
70#![warn(rustdoc::redundant_explicit_links)]
71#![cfg_attr(docsrs, feature(doc_cfg))]
72
73pub mod cache;
74pub mod cli;
75pub mod concurrency;
76pub mod config;
77pub mod crates_io;
78pub mod docs_rs;
79pub mod domain;
80pub mod error;
81pub mod http;
82pub mod i18n;
83pub mod item_kind;
84pub mod platform;
85pub mod render;
86pub mod retry;
87pub mod shutdown;
88pub mod telemetry;
89
90use std::io::{self, IsTerminal, Write};
91use std::path::Path;
92use std::process::ExitCode;
93use std::time::Duration;
94
95use clap::{CommandFactory, Parser};
96use serde::Serialize;
97use tokio::time::Instant;
98
99use crate::cache::DiskCache;
100use crate::cli::{CacheAction, Cli, Commands, ConfigAction};
101use crate::config::{
102    APP_NAME, APP_VERSION, Config, MSRV, SCHEMA_VERSION, config_path_data, docs_origin_for_crate,
103    init_config_toml,
104};
105use crate::domain::{CrateName, ItemPath, SearchQuery, VersionArg};
106use crate::error::{AppError, AppResult, ErrorKind};
107use crate::http::HttpClient;
108use crate::i18n::Locale;
109use crate::item_kind::ItemKind;
110use crate::render::{
111    apply_truncation_to_item, apply_truncation_to_readme, dry_run_envelope, error_envelope,
112    render_item_markdown, render_readme_markdown, render_search_in_crate_markdown,
113    render_search_markdown, success_envelope,
114};
115use crate::shutdown::{
116    CancelFlag, ProgressGuard, duration_ms, flush_stdio, race_op_with_cancel_and_deadline,
117    spawn_double_interrupt_force_exit,
118};
119use crate::telemetry::init_tracing;
120
121/// Parse argv and execute one command. Returns process exit code.
122///
123/// This is the binary entrypoint wrapper (stdin/stdout/stderr are process defaults).
124/// Agent-first: when stdout is not a TTY, JSON is auto-selected unless `--format` forces human.
125///
126/// # Lifecycle
127///
128/// ```mermaid
129/// sequenceDiagram
130///   participant A as Agent
131///   participant C as docsrs-cli
132///   participant N as crates.io / docs.rs
133///   A->>C: BORN spawn
134///   C->>N: EXECUTE GET
135///   N-->>C: body
136///   C-->>A: stdout envelope
137///   C->>C: FINALIZE flush
138///   C->>C: DIE exit code
139/// ```
140#[cfg_attr(doc, aquamarine::aquamarine)]
141pub async fn run<I, T>(args: I) -> ExitCode
142where
143    I: IntoIterator<Item = T>,
144    T: Into<std::ffi::OsString> + Clone,
145{
146    let stdout_is_terminal = io::stdout().is_terminal();
147    run_with_io(
148        args,
149        io::stdin(),
150        io::stdout(),
151        io::stderr(),
152        stdout_is_terminal,
153    )
154    .await
155}
156
157/// Injectable IO entrypoint for tests (`run(args, stdin, stdout, stderr, stdout_is_terminal)`).
158///
159/// `stdin` is reserved for future payload flows and is unused by current ops.
160/// Pass `stdout_is_terminal = true` to keep human markdown default in unit tests;
161/// the binary path passes the real `IsTerminal` of process stdout.
162pub async fn run_with_io<I, T, In, Out, ErrW>(
163    args: I,
164    _stdin: In,
165    mut stdout: Out,
166    mut stderr: ErrW,
167    stdout_is_terminal: bool,
168) -> ExitCode
169where
170    I: IntoIterator<Item = T>,
171    T: Into<std::ffi::OsString> + Clone,
172    In: io::Read,
173    Out: Write,
174    ErrW: Write,
175{
176    let cli = match Cli::try_parse_from(args) {
177        Ok(c) => c,
178        Err(e) => {
179            // clap prints help/usage itself to its preferred stream
180            let _ = e.print();
181            flush_stdio();
182            return if e.use_stderr() {
183                ExitCode::from(2)
184            } else {
185                ExitCode::SUCCESS
186            };
187        }
188    };
189
190    let code = match run_cli(cli, &mut stdout, &mut stderr, stdout_is_terminal).await {
191        Ok(code) => code,
192        Err(err) if err.kind() == ErrorKind::BrokenPipe => ExitCode::from(141),
193        Err(err) => {
194            // Domain errors should already have been turned into ExitCode via
195            // `emit_error` inside `run_cli`. This path is a last-resort safety net
196            // (preserves kind exit code; never hardcodes 70).
197            tracing::error!(
198                target: "docsrs_cli::telemetry",
199                error = %err,
200                kind = ?err.kind(),
201                "error escaped structured emit path"
202            );
203            let _ = writeln!(stderr, "error: {}", err.message());
204            err.exit_code()
205        }
206    };
207    flush_stdio();
208    let _ = stdout.flush();
209    let _ = stderr.flush();
210    code
211}
212
213async fn run_cli<Out: Write, ErrW: Write>(
214    cli: Cli,
215    stdout: &mut Out,
216    stderr: &mut ErrW,
217    stdout_is_terminal: bool,
218) -> Result<ExitCode, AppError> {
219    if let Err(e) = cli.validate_format_conflict() {
220        return Ok(emit_error(
221            &cli,
222            &e,
223            Locale::En,
224            stdout,
225            stderr,
226            stdout_is_terminal,
227        ));
228    }
229
230    init_tracing(&cli);
231
232    // Config load must go through `emit_error` so exit 78 / JSON envelope are correct.
233    // A bare `?` would bubble to `run_with_io` and historically forced exit 70.
234    let mut cfg = match Config::load_with_cache_dir(cli.config_dir.clone(), cli.cache_dir.clone())
235    {
236        Ok(c) => c,
237        Err(e) => {
238            return Ok(emit_error(
239                &cli,
240                &e,
241                Locale::En,
242                stdout,
243                stderr,
244                stdout_is_terminal,
245            ));
246        }
247    };
248    apply_cli_overrides(&cli, &mut cfg);
249
250    // Fail-closed on explicit/config/env lang before any network work.
251    let locale = match Locale::resolve(cli.lang.as_deref().or(cfg.lang.as_deref())) {
252        Ok(l) => l,
253        Err(e) => {
254            return Ok(emit_error(
255                &cli,
256                &e,
257                Locale::En,
258                stdout,
259                stderr,
260                stdout_is_terminal,
261            ));
262        }
263    };
264    let start = Instant::now();
265    let wants_json = cli.wants_json(stdout_is_terminal);
266    let dry_run = cli.dry_run;
267    let wall = Duration::from_secs(cfg.timeout_secs.max(1));
268    let cancel = CancelFlag::new();
269    // Rules Rust: first Ctrl-C is cooperative; second within 5s force-exits 130.
270    let force_on_second = spawn_double_interrupt_force_exit();
271
272    let cli_ref = &cli;
273    let cfg_ref = &cfg;
274    let result = race_op_with_cancel_and_deadline(wall, cancel.clone(), async {
275        dispatch(
276            cli_ref, cfg_ref, locale, dry_run, wants_json, start, cancel, stdout, stderr,
277        )
278        .await
279    })
280    .await;
281
282    force_on_second.abort();
283
284    match result {
285        Ok(code) => Ok(code),
286        Err(e) if e.kind() == ErrorKind::BrokenPipe => Ok(ExitCode::from(141)),
287        Err(e) => Ok(emit_error(
288            &cli,
289            &e,
290            locale,
291            stdout,
292            stderr,
293            stdout_is_terminal,
294        )),
295    }
296}
297
298fn apply_cli_overrides(cli: &Cli, cfg: &mut Config) {
299    if let Some(t) = cli.timeout {
300        cfg.timeout_secs = t;
301    }
302    if let Some(t) = cli.connect_timeout {
303        cfg.connect_timeout_secs = t;
304    }
305    if let Some(ref ua) = cli.user_agent {
306        cfg.user_agent.clone_from(ua);
307    }
308    if let Some(b) = cli.max_body_bytes {
309        cfg.max_body_bytes = b;
310    }
311    if let Some(b) = cli.max_output_bytes {
312        cfg.max_output_bytes = b;
313    }
314    if let Some(d) = cli.rate_limit_delay_ms {
315        cfg.rate_limit_delay_ms = d;
316    }
317    if let Some(n) = cli.max_concurrency {
318        cfg.max_concurrency = n;
319    }
320    if let Some(r) = cli.max_retries {
321        cfg.max_retries = r;
322    }
323    if let Some(ms) = cli.retry_base_ms {
324        cfg.retry_base_ms = ms;
325    }
326    if let Some(ms) = cli.retry_max_delay_ms {
327        cfg.retry_max_delay_ms = ms;
328    }
329    if cli.disable_retry {
330        cfg.disable_retry = true;
331    }
332    if let Some(ref l) = cli.lang {
333        match &mut cfg.lang {
334            Some(dst) => dst.clone_from(l),
335            None => cfg.lang = Some(l.clone()),
336        }
337    }
338    if cli.no_cache {
339        cfg.no_cache = true;
340    }
341    if let Some(ttl) = cli.cache_ttl_secs {
342        cfg.cache_ttl_secs = ttl;
343    }
344    if let Some(max) = cli.max_cache_bytes {
345        cfg.max_cache_bytes = max;
346    }
347    if let Some(ref dir) = cli.cache_dir {
348        cfg.cache_dir = Some(dir.clone());
349    }
350    // After all CLI mutations: hard ceiling (cannot elevate above HARD_MAX_*).
351    cfg.clamp_resource_limits();
352}
353
354#[allow(clippy::too_many_arguments)]
355async fn dispatch<Out: Write, ErrW: Write>(
356    cli: &Cli,
357    cfg: &Config,
358    locale: Locale,
359    dry_run: bool,
360    wants_json: bool,
361    start: Instant,
362    cancel: CancelFlag,
363    stdout: &mut Out,
364    _stderr: &mut ErrW,
365) -> AppResult<ExitCode> {
366    match &cli.command {
367        Commands::Version => {
368            if wants_json {
369                let data = VersionData {
370                    name: APP_NAME,
371                    version: APP_VERSION,
372                    msrv: MSRV,
373                    os: std::env::consts::OS,
374                    arch: std::env::consts::ARCH,
375                };
376                write_json(
377                    stdout,
378                    &success_envelope("version", &data, duration_ms(start), None),
379                )?;
380            } else {
381                writeln!(stdout, "{APP_NAME} {APP_VERSION}").map_err(map_stdout_err)?;
382            }
383            Ok(ExitCode::SUCCESS)
384        }
385        Commands::Doctor { online } => doctor(cfg, *online, wants_json, start, locale, stdout),
386        Commands::Commands => commands_cmd(wants_json, start, stdout),
387        Commands::Schema { cmd } => schema_cmd(cmd, wants_json, cli.format, start, stdout),
388        Commands::Completions { shell } => {
389            // Completions emit shell script by default (even on non-TTY). JSON only if --json/--format json.
390            let explicit_json = cli.json || matches!(cli.format, Some(crate::cli::OutputFormat::Json));
391            completions_cmd(*shell, explicit_json, start, stdout)
392        }
393        Commands::Cache { action } => cache_cmd(cfg, action, wants_json, start, stdout),
394        Commands::Config { action } => config_cmd(cli, cfg, action, wants_json, start, stdout),
395        Commands::SearchCrates {
396            query,
397            per_page,
398            sort,
399            page,
400            page_token,
401        } => {
402            // Full `meta.next_page` tokens already embed `q=…`; allow empty positional query then.
403            let token_carries_query = page_token.as_deref().is_some_and(|t| {
404                let qs = t.trim().trim_start_matches('?');
405                qs.contains('=')
406            });
407            let query = SearchQuery::parse(query, token_carries_query)?;
408            let sort_s = sort.as_api_str();
409            let (per_page, page) = crates_io::clamp_search_pagination(*per_page, *page);
410            let url = if let Some(token) = page_token.as_deref() {
411                crates_io::planned_url_with_page_token(
412                    &cfg.crates_io_origin,
413                    query.as_str(),
414                    per_page,
415                    sort_s,
416                    token,
417                )?
418            } else {
419                crates_io::planned_url_on_host(
420                    &cfg.crates_io_origin,
421                    query.as_str(),
422                    per_page,
423                    sort_s,
424                    page,
425                )?
426            };
427            if dry_run {
428                return emit_dry_run(
429                    "search-crates",
430                    url.as_str(),
431                    SearchCratesDryParams {
432                        q: query.as_str(),
433                        per_page,
434                        sort: sort_s,
435                        page,
436                        page_token: page_token.as_deref(),
437                    },
438                    wants_json,
439                    start,
440                    stdout,
441                );
442            }
443            let progress = ProgressGuard::start(
444                cli.quiet,
445                Duration::from_secs(2),
446                locale.progress_fetching("crates.io"),
447            );
448            let http = HttpClient::new(cfg.clone(), cancel)?;
449            let data =
450                crates_io::search_crates_at(&http, &url, query.as_str(), per_page, sort_s, page)
451                    .await;
452            progress.finish();
453            let data = data?;
454            if wants_json {
455                write_json(
456                    stdout,
457                    &success_envelope(
458                        "search-crates",
459                        &data,
460                        duration_ms(start),
461                        Some(url.as_str()),
462                    ),
463                )?;
464            } else {
465                let md = render_search_markdown(&data);
466                let (out, _) = render::truncate_output(&md, cfg.max_output_bytes);
467                write!(stdout, "{out}").map_err(map_stdout_err)?;
468            }
469            Ok(ExitCode::SUCCESS)
470        }
471        Commands::Readme {
472            crate_name,
473            crate_version,
474        } => {
475            let crate_name = CrateName::parse(crate_name)?;
476            let version = VersionArg::parse_opt(crate_version.as_deref())?;
477            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
478            let url =
479                docs_rs::readme_url_on_origin(&origin, crate_name.as_str(), version.as_str())?;
480            if dry_run {
481                return emit_dry_run(
482                    "readme",
483                    url.as_str(),
484                    ReadmeDryParams {
485                        crate_name: crate_name.as_str(),
486                        version: version.as_str(),
487                    },
488                    wants_json,
489                    start,
490                    stdout,
491                );
492            }
493            let progress = ProgressGuard::start(
494                cli.quiet,
495                Duration::from_secs(2),
496                locale.progress_fetching(crate_name.as_str()),
497            );
498            let http = HttpClient::new(cfg.clone(), cancel)?;
499            let data = docs_rs::fetch_readme_on_origin(
500                &http,
501                &origin,
502                crate_name.as_str(),
503                version.as_str(),
504            )
505            .await;
506            progress.finish();
507            let data = apply_truncation_to_readme(data?, cfg);
508            if wants_json {
509                write_json(
510                    stdout,
511                    &success_envelope("readme", &data, duration_ms(start), Some(&data.source_url)),
512                )?;
513            } else {
514                write!(stdout, "{}", render_readme_markdown(&data)).map_err(map_stdout_err)?;
515            }
516            Ok(ExitCode::SUCCESS)
517        }
518        Commands::GetItem {
519            crate_name,
520            item_type,
521            item_path,
522            crate_version,
523            suggest,
524        } => {
525            let crate_name = CrateName::parse(crate_name)?;
526            let kind = ItemKind::parse(item_type)?;
527            let item_path = ItemPath::parse(item_path)?;
528            let segs = item_path.segments();
529            if let Some(first) = segs.first() {
530                let rustc = item_kind::rustc_crate_name(crate_name.as_str());
531                if first.as_str() != crate_name.as_str()
532                    && first.as_str() != rustc.as_str()
533                    && (first.contains('-') || first.contains('_'))
534                {
535                    tracing::warn!(
536                        path_crate = %first,
537                        expected = %crate_name,
538                        "item_path crate prefix differs from crate_name"
539                    );
540                }
541            }
542            let version = VersionArg::parse_opt(crate_version.as_deref())?;
543            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
544            let url = docs_rs::get_item_url_on_origin(
545                &origin,
546                crate_name.as_str(),
547                version.as_str(),
548                kind,
549                segs,
550            )?;
551            if dry_run {
552                return emit_dry_run(
553                    "get-item",
554                    url.as_str(),
555                    GetItemDryParams {
556                        crate_name: crate_name.as_str(),
557                        item_type: kind.as_str(),
558                        item_path: item_path.as_str(),
559                        version: version.as_str(),
560                    },
561                    wants_json,
562                    start,
563                    stdout,
564                );
565            }
566            let progress = ProgressGuard::start(
567                cli.quiet,
568                Duration::from_secs(2),
569                locale.progress_fetching(item_path.as_str()),
570            );
571            let http = HttpClient::new(cfg.clone(), cancel)?;
572            let data = docs_rs::fetch_item_on_origin(
573                &http,
574                &origin,
575                crate_name.as_str(),
576                version.as_str(),
577                kind,
578                segs,
579            )
580            .await;
581            progress.finish();
582            let data = match data {
583                Ok(d) => apply_truncation_to_item(d, cfg),
584                Err(e) if *suggest && e.kind() == ErrorKind::NotFound => {
585                    // Opt-in recovery: list nearby symbols from all.html
586                    let all_url = docs_rs::all_html_url_on_origin(
587                        &origin,
588                        crate_name.as_str(),
589                        version.as_str(),
590                    )?;
591                    let leaf = segs.last().map(|s| s.as_str()).unwrap_or(item_path.as_str());
592                    if let Ok(sugg) = docs_rs::search_in_crate_at(
593                        &http,
594                        crate_name.as_str(),
595                        version.as_str(),
596                        leaf,
597                        None,
598                        5,
599                        crate::domain::MatchMode::Prefix,
600                        &all_url,
601                    )
602                    .await
603                    {
604                        let names: Vec<String> =
605                            sugg.hits.into_iter().map(|h| format!("{} ({})", h.name, h.kind)).collect();
606                        return Err(AppError::new(
607                            ErrorKind::NotFound,
608                            format!(
609                                "{}; suggestions: {}",
610                                e.message(),
611                                if names.is_empty() {
612                                    "(none)".into()
613                                } else {
614                                    names.join(", ")
615                                }
616                            ),
617                        ));
618                    }
619                    return Err(e);
620                }
621                Err(e) => return Err(e),
622            };
623            if wants_json {
624                write_json(
625                    stdout,
626                    &success_envelope(
627                        "get-item",
628                        &data,
629                        duration_ms(start),
630                        Some(&data.source_url),
631                    ),
632                )?;
633            } else {
634                write!(stdout, "{}", render_item_markdown(&data)).map_err(map_stdout_err)?;
635            }
636            Ok(ExitCode::SUCCESS)
637        }
638        Commands::SearchInCrate {
639            crate_name,
640            query,
641            crate_version,
642            item_type,
643            limit,
644            r#match,
645        } => {
646            let crate_name = CrateName::parse(crate_name)?;
647            let query = SearchQuery::parse(query, true)?;
648            let kind_filter = match item_type {
649                Some(t) if !t.is_empty() => Some(ItemKind::parse(t)?),
650                _ => None,
651            };
652            let match_mode = crate::domain::MatchMode::parse(r#match)?;
653            let version = VersionArg::parse_opt(crate_version.as_deref())?;
654            let origin = docs_origin_for_crate(cfg, crate_name.as_str());
655            let url =
656                docs_rs::all_html_url_on_origin(&origin, crate_name.as_str(), version.as_str())?;
657            let limit = (*limit).min(crate::config::MAX_SEARCH_IN_CRATE_LIMIT);
658            if dry_run {
659                return emit_dry_run(
660                    "search-in-crate",
661                    url.as_str(),
662                    SearchInCrateDryParams {
663                        crate_name: crate_name.as_str(),
664                        query: query.as_str(),
665                        version: version.as_str(),
666                        item_type: kind_filter.map(|k| k.as_str()),
667                        match_mode: Some(match_mode.as_str()),
668                        limit,
669                    },
670                    wants_json,
671                    start,
672                    stdout,
673                );
674            }
675            let progress = ProgressGuard::start(
676                cli.quiet,
677                Duration::from_secs(2),
678                locale.progress_fetching(&format!("{} all.html", crate_name.as_str())),
679            );
680            let http = HttpClient::new(cfg.clone(), cancel)?;
681            let data = docs_rs::search_in_crate_on_origin(
682                &http,
683                &origin,
684                crate_name.as_str(),
685                version.as_str(),
686                query.as_str(),
687                kind_filter,
688                limit,
689                match_mode,
690            )
691            .await;
692            progress.finish();
693            let data = data?;
694            if wants_json {
695                write_json(
696                    stdout,
697                    &success_envelope(
698                        "search-in-crate",
699                        &data,
700                        duration_ms(start),
701                        Some(&data.source_url),
702                    ),
703                )?;
704            } else {
705                let md = render_search_in_crate_markdown(&data);
706                let (out, _) = render::truncate_output(&md, cfg.max_output_bytes);
707                write!(stdout, "{out}").map_err(map_stdout_err)?;
708            }
709            Ok(ExitCode::SUCCESS)
710        }
711    }
712}
713
714fn doctor<Out: Write>(
715    cfg: &Config,
716    online: bool,
717    wants_json: bool,
718    start: Instant,
719    locale: Locale,
720    stdout: &mut Out,
721) -> AppResult<ExitCode> {
722    let mut checks = Vec::new();
723
724    checks.push(DoctorCheck {
725        name: "platform",
726        ok: true,
727        detail: crate::platform::platform_detail(),
728    });
729    checks.push(DoctorCheck {
730        name: "rustls_client",
731        ok: true,
732        detail: "reqwest built with rustls-tls".into(),
733    });
734    checks.push(DoctorCheck {
735        name: "user_agent",
736        ok: !cfg.user_agent.is_empty() && cfg.user_agent.contains(APP_NAME),
737        detail: cfg.user_agent.clone(),
738    });
739
740    let (config_ok, config_detail) = match &cfg.config_dir {
741        Some(p) => dir_ready_check(p),
742        None => (false, "default-not-resolved".into()),
743    };
744    checks.push(DoctorCheck {
745        name: "config_dir",
746        ok: config_ok,
747        detail: config_detail,
748    });
749
750    // XDG storage layer diagnostics (no .env runtime; no secret layers).
751    checks.push(DoctorCheck {
752        name: "config_source",
753        ok: cfg.config_path_source != crate::config::PathSource::Unresolved,
754        detail: cfg.config_path_source.as_str().into(),
755    });
756    let (cfg_file_ok, cfg_file_detail) = match cfg.config_file_path() {
757        Some(p) => {
758            if p.is_file() {
759                (
760                    true,
761                    format!(
762                        "present loaded={} path={}",
763                        cfg.config_toml_loaded,
764                        p.display()
765                    ),
766                )
767            } else {
768                (
769                    true,
770                    format!(
771                        "absent (optional; run config init) path={}",
772                        p.display()
773                    ),
774                )
775            }
776        }
777        None => (false, "config file path unresolved".into()),
778    };
779    checks.push(DoctorCheck {
780        name: "config_file",
781        ok: cfg_file_ok,
782        detail: cfg_file_detail,
783    });
784    checks.push(DoctorCheck {
785        name: "cache_source",
786        ok: cfg.no_cache || cfg.cache_path_source != crate::config::PathSource::Unresolved,
787        detail: if cfg.no_cache {
788            "n/a (--no-cache)".into()
789        } else {
790            cfg.cache_path_source.as_str().into()
791        },
792    });
793    checks.push(DoctorCheck {
794        name: "dotenv_runtime",
795        ok: true,
796        detail: "disabled (XDG + env allowlist only; no .env required after install)".into(),
797    });
798    checks.push(DoctorCheck {
799        name: "secrets_layers",
800        ok: true,
801        detail: "none (public HTTP only; keyring/cloud secret managers out of scope)".into(),
802    });
803
804    // Runtime clamps both to min 1s (`Config::timeout` / `connect_timeout`); report effective values.
805    let eff_timeout = cfg.timeout_secs.max(1);
806    let eff_connect = cfg.connect_timeout_secs.max(1);
807    checks.push(DoctorCheck {
808        name: "timeouts",
809        ok: true,
810        detail: format!("timeout={eff_timeout}s connect={eff_connect}s"),
811    });
812
813    let resolved_conc = crate::concurrency::resolve_max_concurrency(cfg.max_concurrency);
814    let workers = crate::concurrency::runtime_worker_threads();
815    checks.push(DoctorCheck {
816        name: "concurrency",
817        ok: true,
818        detail: format!(
819            "max_concurrency={} (configured={}; 0=auto) runtime_workers≈{} formula=min(cpus,free_ram/2/{}MiB) cap={}",
820            resolved_conc,
821            cfg.max_concurrency,
822            workers,
823            crate::concurrency::RAM_PER_TASK_MIB,
824            crate::concurrency::MAX_AUTO_CONCURRENCY
825        ),
826    });
827
828    let retry = crate::retry::RetryConfig::from_config(cfg);
829    checks.push(DoctorCheck {
830        name: "retry_policy",
831        ok: true,
832        detail: format!(
833            "enabled={} max_retries={} base_ms={} max_delay_ms={} max_attempts={} formula=full_jitter(min(base*2^n,max_delay)) kill_switch=--disable-retry",
834            retry.enabled,
835            retry.max_retries,
836            retry.base_ms,
837            retry.max_delay_ms,
838            retry.max_attempts()
839        ),
840    });
841
842    let (cache_ok, cache_detail) = if cfg.no_cache {
843        (true, "disabled (--no-cache)".to_string())
844    } else {
845        match &cfg.cache_dir {
846            Some(p) => {
847                let (ready, ready_detail) = dir_ready_check(p);
848                if !ready {
849                    (false, ready_detail)
850                } else {
851                    let stats =
852                        DiskCache::new(p.clone(), cfg.cache_ttl(), cfg.max_cache_bytes).stats();
853                    let budget = if cfg.max_cache_bytes == 0 {
854                        "unlimited".to_string()
855                    } else {
856                        format!("{}B", cfg.max_cache_bytes)
857                    };
858                    (
859                        true,
860                        format!(
861                            "enabled dir={} ttl={}s max={} entries={} used={}B parser={}",
862                            p.display(),
863                            cfg.cache_ttl_secs,
864                            budget,
865                            stats.entries,
866                            stats.total_bytes,
867                            crate::cache::CACHE_PARSER_VERSION
868                        ),
869                    )
870                }
871            }
872            None => (false, "no cache dir resolved".to_string()),
873        }
874    };
875    checks.push(DoctorCheck {
876        name: "disk_cache",
877        ok: cache_ok,
878        detail: cache_detail,
879    });
880
881    // Cross-process rate-limit lock+stamp directory (same root as disk cache).
882    let (rl_ok, rl_detail) = if cfg.no_cache {
883        (
884            true,
885            "n/a (--no-cache; in-process rate limit only)".to_string(),
886        )
887    } else {
888        match &cfg.cache_dir {
889            Some(p) => {
890                let rl = p.join("rate-limit");
891                dir_ready_check(&rl)
892            }
893            None => (
894                false,
895                "no cache dir resolved (cross-process rate limit unavailable)".to_string(),
896            ),
897        }
898    };
899    checks.push(DoctorCheck {
900        name: "rate_limit_dir",
901        ok: rl_ok,
902        detail: rl_detail,
903    });
904
905    // Resolved human locale for stderr prose (JSON messages stay English).
906    checks.push(DoctorCheck {
907        name: "lang",
908        ok: true,
909        detail: locale.as_bcp47().into(),
910    });
911
912    // Contact URL should not be the historical placeholder host.
913    let ua_contact_ok = !cfg.user_agent.contains("github.com/docsrs-cli/docsrs-cli");
914    checks.push(DoctorCheck {
915        name: "user_agent_contact",
916        ok: ua_contact_ok,
917        detail: if ua_contact_ok {
918            "contact is not the placeholder docsrs-cli org".into()
919        } else {
920            "placeholder contact host github.com/docsrs-cli/docsrs-cli is invalid".into()
921        },
922    });
923
924    if online {
925        // Sync DNS/TCP probe (no async runtime needed inside doctor).
926        for (name, host) in [("online_crates_io", "crates.io"), ("online_docs_rs", "docs.rs")] {
927            let ok_probe = std::net::ToSocketAddrs::to_socket_addrs(&format!("{host}:443"))
928                .map(|mut it| it.next().is_some())
929                .unwrap_or(false);
930            checks.push(DoctorCheck {
931                name,
932                ok: ok_probe,
933                detail: if ok_probe {
934                    format!("{host}:443 resolves")
935                } else {
936                    format!("{host}:443 DNS/resolve failed")
937                },
938            });
939        }
940    }
941
942    let ok = checks.iter().all(|c| c.ok);
943    let data = DoctorData { ok, checks };
944    if wants_json {
945        write_json(
946            stdout,
947            &success_envelope("doctor", &data, duration_ms(start), None),
948        )?;
949    } else {
950        writeln!(stdout, "{}", locale.doctor_ok(ok)).map_err(map_stdout_err)?;
951        for c in &data.checks {
952            writeln!(
953                stdout,
954                "- {} [{}] {}",
955                c.name,
956                if c.ok { "ok" } else { "fail" },
957                c.detail
958            )
959            .map_err(map_stdout_err)?;
960        }
961    }
962    Ok(if ok {
963        ExitCode::SUCCESS
964    } else {
965        ExitCode::from(78)
966    })
967}
968
969/// Check that `path` is an existing writable directory, or can be created under a
970/// writable ancestor. Does not leave directories behind when only probing parents.
971fn dir_ready_check(path: &Path) -> (bool, String) {
972    if path.is_dir() {
973        let probe = path.join(".docsrs-cli-doctor-write-probe");
974        return match std::fs::OpenOptions::new()
975            .write(true)
976            .create(true)
977            .truncate(true)
978            .open(&probe)
979        {
980            Ok(_) => {
981                let _ = std::fs::remove_file(&probe);
982                (true, path.display().to_string())
983            }
984            Err(e) => (false, format!("{} (not writable: {e})", path.display())),
985        };
986    }
987    if path.exists() {
988        return (
989            false,
990            format!("{} (exists but is not a directory)", path.display()),
991        );
992    }
993    let mut ancestor = path.parent();
994    while let Some(a) = ancestor {
995        if a.as_os_str().is_empty() {
996            break;
997        }
998        if a.is_dir() {
999            let probe = a.join(".docsrs-cli-doctor-write-probe");
1000            return match std::fs::OpenOptions::new()
1001                .write(true)
1002                .create(true)
1003                .truncate(true)
1004                .open(&probe)
1005            {
1006                Ok(_) => {
1007                    let _ = std::fs::remove_file(&probe);
1008                    (
1009                        true,
1010                        format!("{} (creatable under {})", path.display(), a.display()),
1011                    )
1012                }
1013                Err(e) => (
1014                    false,
1015                    format!("{} (ancestor not writable: {e})", path.display()),
1016                ),
1017            };
1018        }
1019        if a.exists() {
1020            return (
1021                false,
1022                format!("{} (ancestor is not a directory)", path.display()),
1023            );
1024        }
1025        ancestor = a.parent();
1026    }
1027    (
1028        false,
1029        format!("{} (missing; no writable ancestor)", path.display()),
1030    )
1031}
1032
1033fn cache_cmd<Out: Write>(
1034    cfg: &Config,
1035    action: &CacheAction,
1036    wants_json: bool,
1037    start: Instant,
1038    stdout: &mut Out,
1039) -> AppResult<ExitCode> {
1040    let root = cfg.cache_dir.clone().ok_or_else(|| {
1041        AppError::new(
1042            ErrorKind::Config,
1043            "cache directory could not be resolved (set --cache-dir or DOCSRS_CLI_CACHE_DIR)",
1044        )
1045    })?;
1046    let cache = DiskCache::new(root, cfg.cache_ttl(), cfg.max_cache_bytes);
1047    match action {
1048        CacheAction::Clear => {
1049            let result = cache.clear()?;
1050            if wants_json {
1051                write_json(
1052                    stdout,
1053                    &success_envelope("cache-clear", &result, duration_ms(start), None),
1054                )?;
1055            } else {
1056                writeln!(
1057                    stdout,
1058                    "cache cleared: {} entries, {} bytes freed ({})",
1059                    result.removed_entries, result.freed_bytes, result.root
1060                )
1061                .map_err(map_stdout_err)?;
1062            }
1063        }
1064        CacheAction::Stats => {
1065            let stats = cache.stats();
1066            if wants_json {
1067                write_json(
1068                    stdout,
1069                    &success_envelope("cache-stats", &stats, duration_ms(start), None),
1070                )?;
1071            } else {
1072                let budget = if stats.max_bytes == 0 {
1073                    "unlimited".to_string()
1074                } else {
1075                    format!("{}B", stats.max_bytes)
1076                };
1077                writeln!(
1078                    stdout,
1079                    "cache root={} layout={} entries={} used={}B max={} ttl={}s parser={}",
1080                    stats.root,
1081                    stats.layout,
1082                    stats.entries,
1083                    stats.total_bytes,
1084                    budget,
1085                    stats.ttl_secs,
1086                    stats.parser_version
1087                )
1088                .map_err(map_stdout_err)?;
1089            }
1090        }
1091    }
1092    Ok(ExitCode::SUCCESS)
1093}
1094
1095/// XDG config lifecycle: path inventory, effective show, init template.
1096fn config_cmd<Out: Write>(
1097    cli: &Cli,
1098    cfg: &Config,
1099    action: &ConfigAction,
1100    wants_json: bool,
1101    start: Instant,
1102    stdout: &mut Out,
1103) -> AppResult<ExitCode> {
1104    match action {
1105        ConfigAction::Path => {
1106            let data = config_path_data(cfg);
1107            if wants_json {
1108                write_json(
1109                    stdout,
1110                    &success_envelope("config-path", &data, duration_ms(start), None),
1111                )?;
1112            } else {
1113                writeln!(
1114                    stdout,
1115                    "config_dir={} source={}",
1116                    data.config_dir.as_deref().unwrap_or("<unresolved>"),
1117                    data.config_source.as_str()
1118                )
1119                .map_err(map_stdout_err)?;
1120                writeln!(
1121                    stdout,
1122                    "config_file={} exists={} loaded={}",
1123                    data.config_file.as_deref().unwrap_or("<unresolved>"),
1124                    data.config_file_exists,
1125                    data.config_toml_loaded
1126                )
1127                .map_err(map_stdout_err)?;
1128                writeln!(
1129                    stdout,
1130                    "cache_dir={} source={}",
1131                    data.cache_dir.as_deref().unwrap_or("<unresolved>"),
1132                    data.cache_source.as_str()
1133                )
1134                .map_err(map_stdout_err)?;
1135                writeln!(
1136                    stdout,
1137                    "dotenv_runtime={} secrets={}",
1138                    data.dotenv_runtime, data.secrets_layers
1139                )
1140                .map_err(map_stdout_err)?;
1141            }
1142        }
1143        ConfigAction::Show => {
1144            if wants_json {
1145                write_json(
1146                    stdout,
1147                    &success_envelope("config-show", cfg, duration_ms(start), None),
1148                )?;
1149            } else {
1150                let pretty = serde_json::to_string_pretty(cfg).map_err(|e| {
1151                    AppError::with_source(ErrorKind::Internal, "failed to serialize config", e)
1152                })?;
1153                writeln!(stdout, "{pretty}").map_err(map_stdout_err)?;
1154            }
1155        }
1156        ConfigAction::Init { force } => {
1157            let result = init_config_toml(cli.config_dir.clone(), *force)?;
1158            if wants_json {
1159                write_json(
1160                    stdout,
1161                    &success_envelope("config-init", &result, duration_ms(start), None),
1162                )?;
1163            } else {
1164                let verb = if result.overwritten {
1165                    "overwrote"
1166                } else {
1167                    "created"
1168                };
1169                writeln!(
1170                    stdout,
1171                    "config init: {verb} {} (source={})",
1172                    result.path,
1173                    result.source.as_str()
1174                )
1175                .map_err(map_stdout_err)?;
1176            }
1177        }
1178    }
1179    Ok(ExitCode::SUCCESS)
1180}
1181
1182/// Emit the full command tree for agent discovery (`commands` subcommand).
1183fn commands_cmd<Out: Write>(
1184    wants_json: bool,
1185    start: Instant,
1186    stdout: &mut Out,
1187) -> AppResult<ExitCode> {
1188    let data = command_tree_data();
1189    if wants_json {
1190        write_json(
1191            stdout,
1192            &success_envelope("commands", &data, duration_ms(start), None),
1193        )?;
1194    } else {
1195        writeln!(
1196            stdout,
1197            "{} {} — command tree",
1198            data.name, data.version
1199        )
1200        .map_err(map_stdout_err)?;
1201        for c in data.commands {
1202            writeln!(stdout, "- {}: {}", c.name, c.about).map_err(map_stdout_err)?;
1203            for s in c.subcommands {
1204                writeln!(stdout, "  - {} {}: {}", c.name, s.name, s.about)
1205                    .map_err(map_stdout_err)?;
1206            }
1207        }
1208    }
1209    Ok(ExitCode::SUCCESS)
1210}
1211
1212/// Typed `version` success data (matches `docs/schemas/version.schema.json`).
1213#[derive(Debug, Serialize)]
1214struct VersionData {
1215    name: &'static str,
1216    version: &'static str,
1217    msrv: &'static str,
1218    os: &'static str,
1219    arch: &'static str,
1220}
1221
1222/// One doctor health check row.
1223#[derive(Debug, Serialize)]
1224struct DoctorCheck {
1225    name: &'static str,
1226    ok: bool,
1227    detail: String,
1228}
1229
1230/// Typed `doctor` success data (matches `docs/schemas/doctor.schema.json`).
1231#[derive(Debug, Serialize)]
1232struct DoctorData {
1233    ok: bool,
1234    checks: Vec<DoctorCheck>,
1235}
1236
1237/// Agent notes embedded in the `commands` tree.
1238#[derive(Debug, Serialize)]
1239struct AgentNotes {
1240    stdout: &'static str,
1241    stderr: &'static str,
1242    json_auto: &'static str,
1243    lifecycle: &'static str,
1244}
1245
1246/// One nested subcommand entry under `cache`.
1247#[derive(Debug, Serialize)]
1248struct SubCommandNode {
1249    name: &'static str,
1250    about: &'static str,
1251}
1252
1253/// One top-level command entry in the discovery tree.
1254#[derive(Debug, Serialize)]
1255struct CommandNode {
1256    name: &'static str,
1257    about: &'static str,
1258    args: &'static [&'static str],
1259    subcommands: &'static [SubCommandNode],
1260}
1261
1262/// Stable, ordered command tree for agents (no HashMap iteration).
1263#[derive(Debug, Serialize)]
1264struct CommandTree {
1265    name: &'static str,
1266    version: &'static str,
1267    msrv: &'static str,
1268    schema_version: u32,
1269    agent_notes: AgentNotes,
1270    commands: &'static [CommandNode],
1271}
1272
1273/// Schema command payload (`schema` stays `Value` — embedded JSON Schema document).
1274#[derive(Debug, Serialize)]
1275struct SchemaData<'a> {
1276    command: &'a str,
1277    schema: serde_json::Value,
1278    schema_version: u32,
1279}
1280
1281/// Completions command payload.
1282#[derive(Debug, Serialize)]
1283struct CompletionsData {
1284    shell: &'static str,
1285    script: String,
1286}
1287
1288/// Stable, ordered command tree for agents (no HashMap iteration).
1289fn command_tree_data() -> CommandTree {
1290    CommandTree {
1291        name: APP_NAME,
1292        version: APP_VERSION,
1293        msrv: MSRV,
1294        schema_version: SCHEMA_VERSION,
1295        agent_notes: AgentNotes {
1296            stdout: "data only (JSON envelope or markdown)",
1297            stderr: "diagnostics only",
1298            json_auto: "JSON is selected automatically when stdout is not a TTY unless --format markdown|text",
1299            lifecycle: "BORN → EXECUTE → FINALIZE → DIE (one-shot, no daemon)",
1300        },
1301        commands: &[
1302            CommandNode {
1303                name: "search-crates",
1304                about: "Search crates on crates.io",
1305                args: &["query", "--per-page", "--sort", "--page", "--page-token"],
1306                subcommands: &[],
1307            },
1308            CommandNode {
1309                name: "readme",
1310                about: "Fetch crate overview docblock from docs.rs (not git README)",
1311                args: &["crate_name", "--crate-version"],
1312                subcommands: &[],
1313            },
1314            CommandNode {
1315                name: "get-item",
1316                about: "Fetch documentation for a typed item",
1317                args: &["crate_name", "item_type", "item_path", "--crate-version", "--suggest"],
1318                subcommands: &[],
1319            },
1320            CommandNode {
1321                name: "search-in-crate",
1322                about: "Search symbols in crate all.html index",
1323                args: &["crate_name", "query", "--crate-version", "--item-type", "--limit", "--match"],
1324                subcommands: &[],
1325            },
1326            CommandNode {
1327                name: "version",
1328                about: "Print binary version",
1329                args: &[],
1330                subcommands: &[],
1331            },
1332            CommandNode {
1333                name: "doctor",
1334                about: "Validate local TLS/config readiness",
1335                args: &["--online"],
1336                subcommands: &[],
1337            },
1338            CommandNode {
1339                name: "commands",
1340                about: "List the full command tree for agent discovery",
1341                args: &[],
1342                subcommands: &[],
1343            },
1344            CommandNode {
1345                name: "schema",
1346                about: "Emit JSON Schema for a command",
1347                args: &["--cmd"],
1348                subcommands: &[],
1349            },
1350            CommandNode {
1351                name: "completions",
1352                about: "Generate shell completions",
1353                args: &["shell"],
1354                subcommands: &[],
1355            },
1356            CommandNode {
1357                name: "cache",
1358                about: "Inspect or clear the XDG HTTP disk cache",
1359                args: &[],
1360                subcommands: &[
1361                    SubCommandNode {
1362                        name: "clear",
1363                        about: "Delete all cached HTTP bodies under the cache dir",
1364                    },
1365                    SubCommandNode {
1366                        name: "stats",
1367                        about: "Report entry count, total bytes, and budget",
1368                    },
1369                ],
1370            },
1371            CommandNode {
1372                name: "config",
1373                about: "Manage XDG config paths and optional config.toml (no secrets / no .env)",
1374                args: &[],
1375                subcommands: &[
1376                    SubCommandNode {
1377                        name: "path",
1378                        about: "Print resolved config/cache directories and which layer won",
1379                    },
1380                    SubCommandNode {
1381                        name: "show",
1382                        about: "Print effective runtime configuration",
1383                    },
1384                    SubCommandNode {
1385                        name: "init",
1386                        about: "Create default config.toml under the resolved config directory",
1387                    },
1388                ],
1389            },
1390        ],
1391    }
1392}
1393
1394fn schema_cmd<Out: Write>(
1395    cmd: &str,
1396    wants_json: bool,
1397    format: Option<crate::cli::OutputFormat>,
1398    start: Instant,
1399    stdout: &mut Out,
1400) -> AppResult<ExitCode> {
1401    let schema = match cmd {
1402        "search-crates" => include_str!("../docs/schemas/search-crates.schema.json"),
1403        "readme" => include_str!("../docs/schemas/readme.schema.json"),
1404        "get-item" => include_str!("../docs/schemas/get-item.schema.json"),
1405        "search-in-crate" => include_str!("../docs/schemas/search-in-crate.schema.json"),
1406        "version" => include_str!("../docs/schemas/version.schema.json"),
1407        "doctor" => include_str!("../docs/schemas/doctor.schema.json"),
1408        "commands" => include_str!("../docs/schemas/commands.schema.json"),
1409        "schema" => include_str!("../docs/schemas/schema.schema.json"),
1410        "completions" => include_str!("../docs/schemas/completions.schema.json"),
1411        "error" => include_str!("../docs/schemas/error.schema.json"),
1412        "dry-run" => include_str!("../docs/schemas/dry-run.schema.json"),
1413        "cache" | "cache-clear" | "cache-stats" => {
1414            include_str!("../docs/schemas/cache.schema.json")
1415        }
1416        "config" | "config-path" | "config-show" | "config-init" => {
1417            include_str!("../docs/schemas/config.schema.json")
1418        }
1419        other => {
1420            return Err(AppError::new(
1421                ErrorKind::Usage,
1422                format!("unknown schema command '{other}'"),
1423            ));
1424        }
1425    };
1426    let schema_val: serde_json::Value = serde_json::from_str(schema).map_err(|e| {
1427        AppError::with_source(ErrorKind::Internal, "embedded schema is invalid JSON", e)
1428    })?;
1429    // Branch first so JSON path can move `schema_val` into the envelope (no clone).
1430    if wants_json {
1431        let data = SchemaData {
1432            command: cmd,
1433            schema: schema_val,
1434            schema_version: SCHEMA_VERSION,
1435        };
1436        write_json(
1437            stdout,
1438            &success_envelope("schema", &data, duration_ms(start), None),
1439        )?;
1440    } else if matches!(format, Some(crate::cli::OutputFormat::Markdown)) {
1441        let md = render::render_schema_markdown(cmd, &schema_val);
1442        write!(stdout, "{md}").map_err(map_stdout_err)?;
1443    } else {
1444        writeln!(
1445            stdout,
1446            "{}",
1447            serde_json::to_string_pretty(&schema_val).unwrap_or_default()
1448        )
1449        .map_err(map_stdout_err)?;
1450    }
1451    Ok(ExitCode::SUCCESS)
1452}
1453
1454fn completions_cmd<Out: Write>(
1455    shell: crate::cli::Shell,
1456    wants_json: bool,
1457    start: Instant,
1458    stdout: &mut Out,
1459) -> AppResult<ExitCode> {
1460    let mut buf = Vec::new();
1461    let mut cmd = Cli::command();
1462    clap_complete::generate(shell.to_clap_shell(), &mut cmd, APP_NAME, &mut buf);
1463    let script = String::from_utf8_lossy(&buf).into_owned();
1464    if wants_json {
1465        let data = CompletionsData {
1466            shell: shell.as_str(),
1467            script,
1468        };
1469        write_json(
1470            stdout,
1471            &success_envelope("completions", &data, duration_ms(start), None),
1472        )?;
1473    } else {
1474        write!(stdout, "{script}").map_err(map_stdout_err)?;
1475        let _ = stdout.flush();
1476    }
1477    Ok(ExitCode::SUCCESS)
1478}
1479
1480/// Typed dry-run params for `search-crates` (keys match crates.io query string).
1481#[derive(Debug, Serialize)]
1482struct SearchCratesDryParams<'a> {
1483    q: &'a str,
1484    per_page: u32,
1485    sort: &'a str,
1486    page: u32,
1487    #[serde(skip_serializing_if = "Option::is_none")]
1488    page_token: Option<&'a str>,
1489}
1490
1491/// Typed dry-run params for `readme`.
1492#[derive(Debug, Serialize)]
1493struct ReadmeDryParams<'a> {
1494    crate_name: &'a str,
1495    version: &'a str,
1496}
1497
1498/// Typed dry-run params for `get-item`.
1499#[derive(Debug, Serialize)]
1500struct GetItemDryParams<'a> {
1501    crate_name: &'a str,
1502    item_type: &'a str,
1503    item_path: &'a str,
1504    version: &'a str,
1505}
1506
1507/// Typed dry-run params for `search-in-crate`.
1508#[derive(Debug, Serialize)]
1509struct SearchInCrateDryParams<'a> {
1510    crate_name: &'a str,
1511    query: &'a str,
1512    version: &'a str,
1513    #[serde(skip_serializing_if = "Option::is_none")]
1514    item_type: Option<&'a str>,
1515    #[serde(skip_serializing_if = "Option::is_none")]
1516    match_mode: Option<&'a str>,
1517    limit: u32,
1518}
1519
1520fn emit_dry_run<Out: Write, P: Serialize>(
1521    command: &str,
1522    planned_url: &str,
1523    planned_params: P,
1524    wants_json: bool,
1525    start: Instant,
1526    stdout: &mut Out,
1527) -> AppResult<ExitCode> {
1528    if wants_json {
1529        write_json(
1530            stdout,
1531            &dry_run_envelope(command, planned_url, &planned_params, duration_ms(start)),
1532        )?;
1533    } else {
1534        writeln!(stdout, "dry-run {command}").map_err(map_stdout_err)?;
1535        writeln!(stdout, "planned_url: {planned_url}").map_err(map_stdout_err)?;
1536        writeln!(
1537            stdout,
1538            "planned_params: {}",
1539            serde_json::to_string_pretty(&planned_params).unwrap_or_default()
1540        )
1541        .map_err(map_stdout_err)?;
1542    }
1543    Ok(ExitCode::SUCCESS)
1544}
1545
1546fn map_stdout_err(e: io::Error) -> AppError {
1547    if e.kind() == io::ErrorKind::BrokenPipe {
1548        AppError::broken_pipe()
1549    } else {
1550        AppError::with_source(ErrorKind::Internal, "stdout write", e)
1551    }
1552}
1553
1554/// Serialize one RFC 8259 JSON object (compact, single line) + trailing `\n`.
1555///
1556/// Product stdout is a single JSON document per invocation (not NDJSON streams).
1557/// Optional fields are omitted when `None` (`skip_serializing_if`), never `NaN`/`Infinity`.
1558///
1559/// Serialize to an intermediate buffer first so broken-pipe on write is mapped to
1560/// exit 141 without conflating pure serde failures with I/O.
1561fn write_json<Out: Write, T: Serialize>(stdout: &mut Out, v: &T) -> AppResult<()> {
1562    let mut buf = Vec::with_capacity(256);
1563    serde_json::to_writer(&mut buf, v)
1564        .map_err(|e| AppError::with_source(ErrorKind::Internal, "json serialize failed", e))?;
1565    buf.push(b'\n');
1566    stdout.write_all(&buf).map_err(map_stdout_err)?;
1567    let _ = stdout.flush();
1568    Ok(())
1569}
1570
1571fn emit_error<Out: Write, ErrW: Write>(
1572    cli: &Cli,
1573    err: &AppError,
1574    locale: Locale,
1575    stdout: &mut Out,
1576    stderr: &mut ErrW,
1577    stdout_is_terminal: bool,
1578) -> ExitCode {
1579    if cli.wants_json(stdout_is_terminal) {
1580        // Best-effort: preserve the original error exit code even if stdout is gone.
1581        let _ = write_json(stdout, &error_envelope(err));
1582    } else {
1583        // Human path: error on stderr; stdout stays empty.
1584        // Force with --format text|markdown even when stdout is a pipe.
1585        let _ = writeln!(stderr, "{}", locale.format_error(err.message()));
1586        let _ = stderr.flush();
1587    }
1588    flush_stdio();
1589    err.exit_code()
1590}