1use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use directories::ProjectDirs;
9use serde::{Deserialize, Serialize};
10
11use crate::error::{AppError, AppResult, ErrorKind};
12use crate::platform::{restrict_private_dir, restrict_private_file};
13
14pub const DEFAULT_TIMEOUT_SECS: u64 = 30;
16pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 10;
18pub const DEFAULT_MAX_BODY_BYTES: u64 = 10_485_760;
20pub const HARD_MAX_BODY_BYTES: u64 = DEFAULT_MAX_BODY_BYTES;
25pub const DEFAULT_MAX_OUTPUT_BYTES: u64 = 2_097_152;
27pub const HARD_MAX_OUTPUT_BYTES: u64 = DEFAULT_MAX_OUTPUT_BYTES;
29pub const DEFAULT_MAX_REDIRECTS: u32 = 5;
31pub const DEFAULT_MAX_RETRIES: u32 = crate::retry::DEFAULT_MAX_RETRIES;
33pub const DEFAULT_RETRY_BASE_MS: u64 = crate::retry::DEFAULT_RETRY_BASE_MS;
35pub const DEFAULT_RETRY_MAX_DELAY_MS: u64 = crate::retry::DEFAULT_RETRY_MAX_DELAY_MS;
37pub const DEFAULT_RATE_LIMIT_DELAY_MS: u64 = 1000;
39pub const DEFAULT_PER_PAGE: u32 = 10;
41pub const DEFAULT_SEARCH_LIMIT: u32 = 100;
43pub const MAX_PER_PAGE: u32 = 100;
45pub const MAX_SEARCH_IN_CRATE_LIMIT: u32 = 1000;
47pub const MAX_QUERY_CHARS: usize = 256;
49pub const MAX_CRATE_NAME_CHARS: usize = 64;
51pub const MAX_ITEM_PATH_CHARS: usize = 512;
53pub const MAX_VERSION_CHARS: usize = 64;
55pub const MAX_USER_AGENT_CHARS: usize = 256;
57pub const DEFAULT_CACHE_TTL_SECS: u64 = crate::cache::DEFAULT_CACHE_TTL_SECS;
59pub const DEFAULT_MAX_CACHE_BYTES: u64 = crate::cache::DEFAULT_MAX_CACHE_BYTES;
61pub const APP_NAME: &str = "docsrs-cli";
63pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
65pub const MSRV: &str = "1.88.0";
67pub const SCHEMA_VERSION: u32 = 1;
69
70pub const HOST_CRATES_IO: &str = "crates.io";
72pub const HOST_DOCS_RS: &str = "docs.rs";
74pub const HOST_STATIC_DOCS_RS: &str = "static.docs.rs";
76pub const HOST_DOC_RUST_LANG_ORG: &str = "doc.rust-lang.org";
78
79#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "kebab-case")]
86pub enum PathSource {
87 CliOrEnv,
89 HomeSandbox,
91 Xdg,
93 #[default]
95 Unresolved,
96}
97
98impl PathSource {
99 pub const fn as_str(self) -> &'static str {
101 match self {
102 Self::CliOrEnv => "cli-or-env",
103 Self::HomeSandbox => "home-sandbox",
104 Self::Xdg => "xdg",
105 Self::Unresolved => "unresolved",
106 }
107 }
108}
109
110pub const DEFAULT_CONFIG_TOML: &str = r#"# docsrs-cli XDG configuration
115# Precedence: CLI flags > this file (XDG) > built-in defaults.
116# Path: /docsrs-cli/config.toml (or platform equivalent).
117# No .env file is required after cargo install. Product stores no API keys.
118# Product settings are NOT read from DOCSRS_CLI_* environment variables.
119#
120# timeout_secs = 30
121# connect_timeout_secs = 10
122# max_body_bytes = 10485760
123# max_output_bytes = 2097152
124# max_redirects = 5
125# max_retries = 3
126# retry_base_ms = 200
127# retry_max_delay_ms = 30000
128# disable_retry = false
129# rate_limit_delay_ms = 1000
130# max_concurrency = 0
131# user_agent = "docsrs-cli/1.1.0 (+https://github.com/danilo-aguiar-br/docsrs-cli)"
132# contact = "https://github.com/danilo-aguiar-br/docsrs-cli"
133# lang = "en"
134# crates_io_origin = "https://crates.io"
135# docs_rs_origin = "https://docs.rs"
136# cache_ttl_secs = 86400
137# max_cache_bytes = 268435456
138# no_cache = false
139"#;
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct Config {
144 pub timeout_secs: u64,
146 pub connect_timeout_secs: u64,
148 pub max_body_bytes: u64,
150 pub max_output_bytes: u64,
152 pub max_redirects: u32,
154 pub max_retries: u32,
156 pub retry_base_ms: u64,
158 pub retry_max_delay_ms: u64,
160 pub disable_retry: bool,
162 pub rate_limit_delay_ms: u64,
164 pub max_concurrency: u32,
168 pub user_agent: String,
170 pub contact: Option<String>,
172 pub lang: Option<String>,
174 pub config_dir: Option<PathBuf>,
176 pub cache_dir: Option<PathBuf>,
178 pub cache_ttl_secs: u64,
180 pub max_cache_bytes: u64,
182 pub no_cache: bool,
184 pub crates_io_origin: String,
186 pub docs_rs_origin: String,
188 pub config_path_source: PathSource,
190 pub cache_path_source: PathSource,
192 pub config_toml_loaded: bool,
194}
195
196impl Default for Config {
197 fn default() -> Self {
198 let contact: Option<String> = None;
200 let ua = default_user_agent(contact.as_deref());
201 Self {
202 timeout_secs: DEFAULT_TIMEOUT_SECS,
203 connect_timeout_secs: DEFAULT_CONNECT_TIMEOUT_SECS,
204 max_body_bytes: DEFAULT_MAX_BODY_BYTES,
205 max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
206 max_redirects: DEFAULT_MAX_REDIRECTS,
207 max_retries: DEFAULT_MAX_RETRIES,
208 retry_base_ms: DEFAULT_RETRY_BASE_MS,
209 retry_max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
210 disable_retry: false,
211 rate_limit_delay_ms: DEFAULT_RATE_LIMIT_DELAY_MS,
212 max_concurrency: 0,
213 user_agent: ua,
214 contact,
215 lang: None,
216 config_dir: None,
217 cache_dir: None,
218 cache_ttl_secs: DEFAULT_CACHE_TTL_SECS,
219 max_cache_bytes: DEFAULT_MAX_CACHE_BYTES,
220 no_cache: false,
221 crates_io_origin: format!("https://{HOST_CRATES_IO}"),
222 docs_rs_origin: format!("https://{HOST_DOCS_RS}"),
223 config_path_source: PathSource::Unresolved,
224 cache_path_source: PathSource::Unresolved,
225 config_toml_loaded: false,
226 }
227 }
228}
229
230pub fn default_user_agent(contact: Option<&str>) -> String {
232 match contact {
233 Some(c) if !c.is_empty() => {
234 if c.starts_with("http://") || c.starts_with("https://") {
235 format!("{APP_NAME}/{APP_VERSION} (+{c})")
236 } else {
237 format!("{APP_NAME}/{APP_VERSION} ({c})")
238 }
239 }
240 _ => format!(
241 "{APP_NAME}/{APP_VERSION} (+https://github.com/danilo-aguiar-br/docsrs-cli)"
242 ),
243 }
244}
245
246pub fn normalize_origin(raw: &str) -> String {
248 raw.trim().trim_end_matches('/').to_string()
249}
250
251#[derive(Debug, Default, Deserialize)]
252struct TomlConfig {
253 timeout_secs: Option<u64>,
254 connect_timeout_secs: Option<u64>,
255 max_body_bytes: Option<u64>,
256 max_output_bytes: Option<u64>,
257 max_redirects: Option<u32>,
258 max_retries: Option<u32>,
259 retry_base_ms: Option<u64>,
260 retry_max_delay_ms: Option<u64>,
261 disable_retry: Option<bool>,
262 rate_limit_delay_ms: Option<u64>,
263 max_concurrency: Option<u32>,
264 user_agent: Option<String>,
265 contact: Option<String>,
266 lang: Option<String>,
267 crates_io_origin: Option<String>,
268 docs_rs_origin: Option<String>,
269 cache_ttl_secs: Option<u64>,
270 max_cache_bytes: Option<u64>,
271 no_cache: Option<bool>,
272}
273
274impl Config {
275 pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
281 Self::load_with_cache_dir(config_dir_override, None)
282 }
283
284 pub fn load_with_cache_dir(
290 config_dir_override: Option<PathBuf>,
291 cache_dir_override: Option<PathBuf>,
292 ) -> AppResult<Self> {
293 let mut cfg = Self::default();
294
295 let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
296 cfg.config_path_source = config_source;
297
298 let (cache_dir, cache_source) =
299 crate::cache::resolve_cache_dir_with_source(cache_dir_override);
300 cfg.cache_dir = cache_dir;
301 cfg.cache_path_source = cache_source;
302
303 if let Some(dir) = &config_dir {
305 let path = dir.join("config.toml");
306 if path.is_file() {
307 let text = fs::read_to_string(&path).map_err(|e| {
308 AppError::with_source(
309 ErrorKind::Config,
310 format!("failed to read {}", path.display()),
311 e,
312 )
313 })?;
314 let parsed: TomlConfig = toml::from_str(&text).map_err(|e| {
315 AppError::with_source(ErrorKind::Config, "invalid config.toml", e)
316 })?;
317 cfg.apply_toml(parsed);
318 cfg.config_toml_loaded = true;
319 }
320 }
321 cfg.config_dir = config_dir;
322
323 cfg.apply_env()?;
324 cfg.clamp_resource_limits();
325 Ok(cfg)
326 }
327
328 pub fn config_file_path(&self) -> Option<PathBuf> {
330 self.config_dir.as_ref().map(|d| d.join("config.toml"))
331 }
332
333 pub fn clamp_resource_limits(&mut self) {
339 self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
340 self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
341 self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
342 if self.retry_base_ms == 0 {
343 self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
344 }
345 if self.retry_max_delay_ms == 0 {
346 self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
347 }
348 self.retry_max_delay_ms = self
349 .retry_max_delay_ms
350 .min(crate::retry::HARD_MAX_DELAY_MS)
351 .max(self.retry_base_ms);
352 }
353
354 fn apply_toml(&mut self, t: TomlConfig) {
355 if let Some(v) = t.timeout_secs {
356 self.timeout_secs = v;
357 }
358 if let Some(v) = t.connect_timeout_secs {
359 self.connect_timeout_secs = v;
360 }
361 if let Some(v) = t.max_body_bytes {
362 self.max_body_bytes = v;
363 }
364 if let Some(v) = t.max_output_bytes {
365 self.max_output_bytes = v;
366 }
367 if let Some(v) = t.max_redirects {
368 self.max_redirects = v;
369 }
370 if let Some(v) = t.max_retries {
371 self.max_retries = v;
372 }
373 if let Some(v) = t.retry_base_ms {
374 self.retry_base_ms = v;
375 }
376 if let Some(v) = t.retry_max_delay_ms {
377 self.retry_max_delay_ms = v;
378 }
379 if let Some(v) = t.disable_retry {
380 self.disable_retry = v;
381 }
382 if let Some(v) = t.rate_limit_delay_ms {
383 self.rate_limit_delay_ms = v;
384 }
385 if let Some(v) = t.max_concurrency {
386 self.max_concurrency = v;
387 }
388 if let Some(v) = t.contact {
389 self.contact = Some(v);
390 }
391 if let Some(v) = t.user_agent {
392 self.user_agent = v;
393 } else if let Some(c) = &self.contact {
394 self.user_agent = default_user_agent(Some(c));
395 }
396 if let Some(v) = t.lang {
397 self.lang = Some(v);
398 }
399 if let Some(v) = t.crates_io_origin {
400 self.crates_io_origin = normalize_origin(&v);
401 }
402 if let Some(v) = t.docs_rs_origin {
403 self.docs_rs_origin = normalize_origin(&v);
404 }
405 if let Some(v) = t.cache_ttl_secs {
406 self.cache_ttl_secs = v;
407 }
408 if let Some(v) = t.max_cache_bytes {
409 self.max_cache_bytes = v;
410 }
411 if let Some(v) = t.no_cache {
412 self.no_cache = v;
413 }
414 }
415
416 fn apply_env(&mut self) -> AppResult<()> {
422 if self.cache_dir.is_none() {
423 let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
424 self.cache_dir = dir;
425 self.cache_path_source = source;
426 }
427 Ok(())
428 }
429}
430
431pub fn resolve_config_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
438 resolve_config_dir_with_source(override_dir).0
439}
440
441pub fn resolve_config_dir_with_source(override_dir: Option<PathBuf>) -> (Option<PathBuf>, PathSource) {
443 if let Some(p) = override_dir {
444 return (Some(p), PathSource::CliOrEnv);
445 }
446 if let Some(p) = std::env::var_os("DOCSRS_CLI_CONFIG_DIR") {
447 return (Some(PathBuf::from(p)), PathSource::CliOrEnv);
448 }
449 if let Some(p) = home_config_dir() {
450 return (Some(p), PathSource::HomeSandbox);
451 }
452 if let Some(p) = ProjectDirs::from("", "", APP_NAME).map(|d| d.config_dir().to_path_buf()) {
453 return (Some(p), PathSource::Xdg);
454 }
455 (None, PathSource::Unresolved)
456}
457
458fn home_config_dir() -> Option<PathBuf> {
460 std::env::var_os("DOCSRS_CLI_HOME").map(|h| PathBuf::from(h).join("config"))
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
465pub struct ConfigInitResult {
466 pub path: String,
468 pub config_dir: String,
470 pub source: PathSource,
472 pub created: bool,
474 pub overwritten: bool,
476}
477
478pub fn init_config_toml(
485 config_dir_override: Option<PathBuf>,
486 force: bool,
487) -> AppResult<ConfigInitResult> {
488 let (dir, source) = resolve_config_dir_with_source(config_dir_override);
489 let dir = dir.ok_or_else(|| {
490 AppError::new(
491 ErrorKind::Config,
492 "config directory could not be resolved (set --config-dir or DOCSRS_CLI_CONFIG_DIR)",
493 )
494 })?;
495 fs::create_dir_all(&dir).map_err(|e| {
496 AppError::with_source(
497 ErrorKind::Config,
498 format!("failed to create config dir {}", dir.display()),
499 e,
500 )
501 })?;
502 restrict_private_dir(&dir);
503
504 let path = dir.join("config.toml");
505 let existed = path.is_file();
506 if existed && !force {
507 return Err(AppError::new(
508 ErrorKind::Config,
509 format!(
510 "config already exists: {} (pass --force to overwrite)",
511 path.display()
512 ),
513 ));
514 }
515
516 let tmp = dir.join("config.toml.docsrs-cli.tmp");
518 {
519 let mut f = fs::File::create(&tmp).map_err(|e| {
520 AppError::with_source(
521 ErrorKind::Config,
522 format!("failed to create {}", tmp.display()),
523 e,
524 )
525 })?;
526 f.write_all(DEFAULT_CONFIG_TOML.as_bytes()).map_err(|e| {
527 AppError::with_source(
528 ErrorKind::Config,
529 format!("failed to write {}", tmp.display()),
530 e,
531 )
532 })?;
533 f.sync_all().map_err(|e| {
534 AppError::with_source(
535 ErrorKind::Config,
536 format!("failed to sync {}", tmp.display()),
537 e,
538 )
539 })?;
540 }
541 restrict_private_file(&tmp);
542 fs::rename(&tmp, &path).map_err(|e| {
543 let _ = fs::remove_file(&tmp);
544 AppError::with_source(
545 ErrorKind::Config,
546 format!("failed to install {}", path.display()),
547 e,
548 )
549 })?;
550 restrict_private_file(&path);
551
552 Ok(ConfigInitResult {
553 path: path.display().to_string(),
554 config_dir: dir.display().to_string(),
555 source,
556 created: true,
557 overwritten: existed,
558 })
559}
560
561#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
563pub struct ConfigPathData {
564 pub config_dir: Option<String>,
566 pub config_source: PathSource,
568 pub config_file: Option<String>,
570 pub config_file_exists: bool,
572 pub config_toml_loaded: bool,
574 pub cache_dir: Option<String>,
576 pub cache_source: PathSource,
578 pub dotenv_runtime: bool,
580 pub secrets_layers: &'static str,
582}
583
584pub fn config_path_data(cfg: &Config) -> ConfigPathData {
586 let config_file = cfg.config_file_path();
587 let exists = config_file.as_ref().is_some_and(|p| p.is_file());
588 ConfigPathData {
589 config_dir: cfg.config_dir.as_ref().map(|p| p.display().to_string()),
590 config_source: cfg.config_path_source,
591 config_file: config_file.as_ref().map(|p| p.display().to_string()),
592 config_file_exists: exists,
593 config_toml_loaded: cfg.config_toml_loaded,
594 cache_dir: cfg.cache_dir.as_ref().map(|p| p.display().to_string()),
595 cache_source: cfg.cache_path_source,
596 dotenv_runtime: false,
597 secrets_layers: "none (public HTTP only; no API keys)",
598 }
599}
600
601pub fn config_toml_under(dir: &Path) -> PathBuf {
603 dir.join("config.toml")
604}
605
606impl Config {
607
608 pub fn timeout(&self) -> Duration {
610 Duration::from_secs(self.timeout_secs.max(1))
611 }
612
613 pub fn connect_timeout(&self) -> Duration {
615 Duration::from_secs(self.connect_timeout_secs.max(1))
616 }
617
618 pub fn rate_limit_delay(&self) -> Duration {
620 Duration::from_millis(self.rate_limit_delay_ms)
621 }
622
623 pub fn cache_ttl(&self) -> Duration {
625 Duration::from_secs(self.cache_ttl_secs)
626 }
627
628 pub fn cache_enabled(&self) -> bool {
630 !self.no_cache && self.cache_dir.is_some()
631 }
632}
633
634pub fn validate_crate_name(name: &str) -> AppResult<()> {
640 crate::domain::CrateName::parse(name).map(|_| ())
641}
642
643pub fn is_stdlib_crate(name: &str) -> bool {
645 matches!(name, "std" | "core" | "alloc")
646}
647
648pub fn docs_origin_for_crate(cfg: &Config, crate_name: &str) -> String {
650 if is_stdlib_crate(crate_name) {
651 format!("https://{HOST_DOC_RUST_LANG_ORG}")
652 } else {
653 cfg.docs_rs_origin.clone()
654 }
655}
656
657pub fn stdlib_channel(version: &str) -> &str {
661 match version {
662 "latest" => "stable",
663 other => other,
664 }
665}
666
667pub fn validate_query(query: &str, allow_empty: bool) -> AppResult<()> {
673 crate::domain::SearchQuery::parse(query, allow_empty).map(|_| ())
674}
675
676pub fn validate_item_path(path: &str) -> AppResult<Vec<String>> {
682 crate::domain::ItemPath::parse(path).map(|p| p.into_segments())
683}
684
685pub fn resolve_version_arg(raw: Option<&str>) -> AppResult<String> {
691 crate::domain::VersionArg::parse_opt(raw).map(|v| v.as_str().to_string())
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697 use std::fs;
698 use std::io::Write;
699
700 #[test]
701 fn crate_name_rules() {
702 assert!(validate_crate_name("serde").is_ok());
703 assert!(validate_crate_name("async-trait").is_ok());
704 assert!(validate_crate_name("std").is_ok());
706 assert!(validate_crate_name("core").is_ok());
707 assert!(validate_crate_name("alloc").is_ok());
708 assert!(is_stdlib_crate("std"));
709 assert!(!is_stdlib_crate("serde"));
710 assert!(validate_crate_name("").is_err());
711 assert!(validate_crate_name("1bad").is_err());
712 assert!(validate_crate_name(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
713 }
714
715 #[test]
716 fn version_policy() {
717 assert_eq!(resolve_version_arg(None).unwrap(), "latest");
718 assert_eq!(resolve_version_arg(Some("")).unwrap(), "latest");
719 assert_eq!(resolve_version_arg(Some("1.0.0")).unwrap(), "1.0.0");
720 assert_eq!(
721 resolve_version_arg(Some("1.0.0-rc.1")).unwrap(),
722 "1.0.0-rc.1"
723 );
724 assert!(resolve_version_arg(Some("v1.0.0")).is_err());
725 assert!(resolve_version_arg(Some("1.0.0+build")).is_err());
726 assert!(resolve_version_arg(Some("not-a-version")).is_err());
727 }
728
729 #[test]
730 fn query_and_path_rules() {
731 assert!(validate_query("serde", false).is_ok());
732 assert!(validate_query("", false).is_err());
733 assert!(validate_query("", true).is_ok());
734 assert!(validate_query(&"q".repeat(MAX_QUERY_CHARS + 1), true).is_err());
735 let segs = validate_item_path("clap::Parser").unwrap();
736 assert_eq!(segs, vec!["clap", "Parser"]);
737 assert!(validate_item_path("::").is_err());
738 assert!(validate_item_path("").is_err());
739 assert!(validate_item_path(&format!("a::{}", "b".repeat(MAX_ITEM_PATH_CHARS))).is_err());
740 }
741
742 #[test]
743 fn item_path_accepts_slash_and_rejects_bad_segments() {
744 let segs = validate_item_path("runtime/Runtime").unwrap();
745 assert_eq!(segs, vec!["runtime", "Runtime"]);
746 let mixed = validate_item_path("tokio::runtime/Runtime").unwrap();
747 assert_eq!(mixed, vec!["tokio", "runtime", "Runtime"]);
748 assert_eq!(
749 validate_item_path("async_trait").unwrap(),
750 vec!["async_trait"]
751 );
752 assert!(validate_item_path("has space").is_err());
753 assert!(validate_item_path("foo.bar").is_err());
754 assert!(validate_item_path("..").is_err());
755 assert!(validate_item_path("a/../b").is_err());
756 assert!(validate_item_path("/").is_err());
757 }
758
759 #[test]
760 fn default_user_agent_variants() {
761 let ua = default_user_agent(None);
762 assert!(ua.contains(APP_NAME));
763 let ua2 = default_user_agent(Some("dev@example.com"));
764 assert!(ua2.contains("dev@example.com"));
765 let ua3 = default_user_agent(Some("https://example.com"));
766 assert!(ua3.contains("+https://example.com"));
767 }
768
769 #[test]
770 fn config_load_toml_and_durations() {
771 let dir = tempfile::tempdir().unwrap();
772 let path = dir.path().join("config.toml");
773 let mut f = fs::File::create(&path).unwrap();
774 writeln!(
775 f,
776 "timeout_secs = 12\nrate_limit_delay_ms = 50\ncontact = \"a@b.c\"\ncrates_io_origin = \"http://127.0.0.1:9/\"\ndocs_rs_origin = \"http://127.0.0.1:9/\"\nlang = \"pt-BR\"\nmax_retries = 2\nmax_body_bytes = 1000\nmax_output_bytes = 2000\ncache_ttl_secs = 3600\nno_cache = false\n"
777 )
778 .unwrap();
779 let cache_dir = dir.path().join("cache");
780 let cfg =
781 Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
782 .unwrap();
783 assert_eq!(cfg.timeout_secs, 12);
784 assert_eq!(cfg.rate_limit_delay_ms, 50);
785 assert!(cfg.user_agent.contains("a@b.c"));
786 assert_eq!(cfg.timeout(), Duration::from_secs(12));
787 assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
788 assert!(cfg.connect_timeout() >= Duration::from_secs(1));
789 assert_eq!(cfg.crates_io_origin, "http://127.0.0.1:9");
790 assert_eq!(cfg.docs_rs_origin, "http://127.0.0.1:9");
791 assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
792 assert_eq!(cfg.max_retries, 2);
793 assert_eq!(cfg.max_body_bytes, 1000);
794 assert_eq!(cfg.max_output_bytes, 2000);
795 assert_eq!(cfg.cache_ttl_secs, 3600);
796 assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
797 assert!(cfg.cache_enabled());
798 }
799
800 #[test]
801 fn config_invalid_toml_errors() {
802 let dir = tempfile::tempdir().unwrap();
803 fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
804 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
805 assert_eq!(err.kind(), ErrorKind::Config);
806 }
807
808 #[test]
809 fn normalize_origin_trims_slash() {
810 assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
811 }
812
813 #[test]
814 fn resolve_config_dir_prefers_explicit_override() {
815 let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
816 let got = resolve_config_dir(Some(explicit.clone()));
817 assert_eq!(got.as_deref(), Some(explicit.as_path()));
818 }
819
820 #[test]
821 fn resolve_cache_dir_home_layout() {
822 let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
824 let cache = home.join("cache");
825 assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
826 let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
828 assert_eq!(got.as_deref(), Some(cache.as_path()));
829 }
830
831 #[test]
832 fn config_defaults_positive() {
833 let cfg = Config::default();
834 assert!(cfg.timeout_secs >= 1);
835 assert!(cfg.max_body_bytes > 0);
836 assert!(cfg.user_agent.contains(APP_NAME));
837 }
838
839 #[test]
840 fn clamp_resource_limits_caps_body_and_output() {
841 let mut cfg = Config {
842 max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
843 max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
844 ..Config::default()
845 };
846 cfg.clamp_resource_limits();
847 assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
848 assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
849 cfg.max_body_bytes = 64;
851 cfg.max_output_bytes = 32;
852 cfg.clamp_resource_limits();
853 assert_eq!(cfg.max_body_bytes, 64);
854 assert_eq!(cfg.max_output_bytes, 32);
855 }
856
857 #[test]
858 fn toml_cannot_raise_max_body_above_hard_ceiling() {
859 let dir = tempfile::tempdir().unwrap();
860 let path = dir.path().join("config.toml");
861 let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
862 let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
863 fs::write(
864 &path,
865 format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
866 )
867 .unwrap();
868 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
869 assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
870 assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
871 }
872
873 #[test]
874 fn hard_ceilings_equal_defaults() {
875 assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
877 assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
878 assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
879 assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
880 }
881
882 #[test]
883 fn path_source_tokens_are_stable() {
884 assert_eq!(PathSource::CliOrEnv.as_str(), "cli-or-env");
885 assert_eq!(PathSource::HomeSandbox.as_str(), "home-sandbox");
886 assert_eq!(PathSource::Xdg.as_str(), "xdg");
887 assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
888 }
889
890 #[test]
891 fn resolve_config_dir_with_source_reports_cli() {
892 let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
893 let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
894 assert_eq!(got.as_deref(), Some(explicit.as_path()));
895 assert_eq!(source, PathSource::CliOrEnv);
896 }
897
898 #[test]
899 fn init_config_toml_creates_and_refuses_without_force() {
900 let dir = tempfile::tempdir().unwrap();
901 let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
902 assert!(r1.created);
903 assert!(!r1.overwritten);
904 assert!(Path::new(&r1.path).is_file());
905 let text = fs::read_to_string(&r1.path).unwrap();
906 assert!(text.contains("docsrs-cli XDG configuration"));
907 assert!(text.contains("No .env file is required"));
908 #[cfg(unix)]
909 {
910 use std::os::unix::fs::PermissionsExt;
911 let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
912 assert_eq!(mode, 0o600);
913 }
914 let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
915 assert_eq!(err.kind(), ErrorKind::Config);
916 let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
917 assert!(r2.created);
918 assert!(r2.overwritten);
919 }
920
921 #[test]
922 fn config_load_marks_toml_loaded() {
923 let dir = tempfile::tempdir().unwrap();
924 fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
925 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
926 assert!(cfg.config_toml_loaded);
927 assert_eq!(cfg.timeout_secs, 9);
928 assert_eq!(cfg.config_path_source, PathSource::CliOrEnv);
929 let inv = config_path_data(&cfg);
930 assert!(inv.config_file_exists);
931 assert!(!inv.dotenv_runtime);
932 }
933
934 #[test]
935 fn config_load_without_toml_is_not_loaded() {
936 let dir = tempfile::tempdir().unwrap();
937 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
938 assert!(!cfg.config_toml_loaded);
939 assert!(!config_path_data(&cfg).config_file_exists);
940 }
941}