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/0.1.2 (+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!("{APP_NAME}/{APP_VERSION} (+https://github.com/danilo-aguiar-br/docsrs-cli)"),
241 }
242}
243
244pub fn normalize_origin(raw: &str) -> String {
246 raw.trim().trim_end_matches('/').to_string()
247}
248
249#[derive(Debug, Default, Deserialize)]
250struct TomlConfig {
251 timeout_secs: Option<u64>,
252 connect_timeout_secs: Option<u64>,
253 max_body_bytes: Option<u64>,
254 max_output_bytes: Option<u64>,
255 max_redirects: Option<u32>,
256 max_retries: Option<u32>,
257 retry_base_ms: Option<u64>,
258 retry_max_delay_ms: Option<u64>,
259 disable_retry: Option<bool>,
260 rate_limit_delay_ms: Option<u64>,
261 max_concurrency: Option<u32>,
262 user_agent: Option<String>,
263 contact: Option<String>,
264 lang: Option<String>,
265 crates_io_origin: Option<String>,
266 docs_rs_origin: Option<String>,
267 cache_ttl_secs: Option<u64>,
268 max_cache_bytes: Option<u64>,
269 no_cache: Option<bool>,
270}
271
272impl Config {
273 pub fn load(config_dir_override: Option<PathBuf>) -> AppResult<Self> {
279 Self::load_with_cache_dir(config_dir_override, None)
280 }
281
282 pub fn load_with_cache_dir(
288 config_dir_override: Option<PathBuf>,
289 cache_dir_override: Option<PathBuf>,
290 ) -> AppResult<Self> {
291 let mut cfg = Self::default();
292
293 let (config_dir, config_source) = resolve_config_dir_with_source(config_dir_override);
294 cfg.config_path_source = config_source;
295
296 let (cache_dir, cache_source) =
297 crate::cache::resolve_cache_dir_with_source(cache_dir_override);
298 cfg.cache_dir = cache_dir;
299 cfg.cache_path_source = cache_source;
300
301 if let Some(dir) = &config_dir {
303 let path = dir.join("config.toml");
304 if path.is_file() {
305 let text = fs::read_to_string(&path).map_err(|e| {
306 AppError::with_source(
307 ErrorKind::Config,
308 format!("failed to read {}", path.display()),
309 e,
310 )
311 })?;
312 let parsed: TomlConfig = toml::from_str(&text).map_err(|e| {
313 AppError::with_source(ErrorKind::Config, "invalid config.toml", e)
314 })?;
315 cfg.apply_toml(parsed);
316 cfg.config_toml_loaded = true;
317 }
318 }
319 cfg.config_dir = config_dir;
320
321 cfg.apply_env()?;
322 cfg.clamp_resource_limits();
323 Ok(cfg)
324 }
325
326 pub fn config_file_path(&self) -> Option<PathBuf> {
328 self.config_dir.as_ref().map(|d| d.join("config.toml"))
329 }
330
331 pub fn clamp_resource_limits(&mut self) {
337 self.max_body_bytes = self.max_body_bytes.min(HARD_MAX_BODY_BYTES);
338 self.max_output_bytes = self.max_output_bytes.min(HARD_MAX_OUTPUT_BYTES);
339 self.max_retries = self.max_retries.min(crate::retry::HARD_MAX_RETRIES);
340 if self.retry_base_ms == 0 {
341 self.retry_base_ms = DEFAULT_RETRY_BASE_MS;
342 }
343 if self.retry_max_delay_ms == 0 {
344 self.retry_max_delay_ms = DEFAULT_RETRY_MAX_DELAY_MS;
345 }
346 self.retry_max_delay_ms = self
347 .retry_max_delay_ms
348 .min(crate::retry::HARD_MAX_DELAY_MS)
349 .max(self.retry_base_ms);
350 }
351
352 fn apply_toml(&mut self, t: TomlConfig) {
353 if let Some(v) = t.timeout_secs {
354 self.timeout_secs = v;
355 }
356 if let Some(v) = t.connect_timeout_secs {
357 self.connect_timeout_secs = v;
358 }
359 if let Some(v) = t.max_body_bytes {
360 self.max_body_bytes = v;
361 }
362 if let Some(v) = t.max_output_bytes {
363 self.max_output_bytes = v;
364 }
365 if let Some(v) = t.max_redirects {
366 self.max_redirects = v;
367 }
368 if let Some(v) = t.max_retries {
369 self.max_retries = v;
370 }
371 if let Some(v) = t.retry_base_ms {
372 self.retry_base_ms = v;
373 }
374 if let Some(v) = t.retry_max_delay_ms {
375 self.retry_max_delay_ms = v;
376 }
377 if let Some(v) = t.disable_retry {
378 self.disable_retry = v;
379 }
380 if let Some(v) = t.rate_limit_delay_ms {
381 self.rate_limit_delay_ms = v;
382 }
383 if let Some(v) = t.max_concurrency {
384 self.max_concurrency = v;
385 }
386 if let Some(v) = t.contact {
387 self.contact = Some(v);
388 }
389 if let Some(v) = t.user_agent {
390 self.user_agent = v;
391 } else if let Some(c) = &self.contact {
392 self.user_agent = default_user_agent(Some(c));
393 }
394 if let Some(v) = t.lang {
395 self.lang = Some(v);
396 }
397 if let Some(v) = t.crates_io_origin {
398 self.crates_io_origin = normalize_origin(&v);
399 }
400 if let Some(v) = t.docs_rs_origin {
401 self.docs_rs_origin = normalize_origin(&v);
402 }
403 if let Some(v) = t.cache_ttl_secs {
404 self.cache_ttl_secs = v;
405 }
406 if let Some(v) = t.max_cache_bytes {
407 self.max_cache_bytes = v;
408 }
409 if let Some(v) = t.no_cache {
410 self.no_cache = v;
411 }
412 }
413
414 fn apply_env(&mut self) -> AppResult<()> {
420 if self.cache_dir.is_none() {
421 let (dir, source) = crate::cache::resolve_cache_dir_with_source(None);
422 self.cache_dir = dir;
423 self.cache_path_source = source;
424 }
425 Ok(())
426 }
427}
428
429pub fn resolve_config_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
436 resolve_config_dir_with_source(override_dir).0
437}
438
439pub fn resolve_config_dir_with_source(
441 override_dir: Option<PathBuf>,
442) -> (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 pub fn timeout(&self) -> Duration {
609 Duration::from_secs(self.timeout_secs.max(1))
610 }
611
612 pub fn connect_timeout(&self) -> Duration {
614 Duration::from_secs(self.connect_timeout_secs.max(1))
615 }
616
617 pub fn rate_limit_delay(&self) -> Duration {
619 Duration::from_millis(self.rate_limit_delay_ms)
620 }
621
622 pub fn cache_ttl(&self) -> Duration {
624 Duration::from_secs(self.cache_ttl_secs)
625 }
626
627 pub fn cache_enabled(&self) -> bool {
629 !self.no_cache && self.cache_dir.is_some()
630 }
631}
632
633pub fn validate_crate_name(name: &str) -> AppResult<()> {
639 crate::domain::CrateName::parse(name).map(|_| ())
640}
641
642pub fn is_stdlib_crate(name: &str) -> bool {
644 matches!(name, "std" | "core" | "alloc")
645}
646
647pub fn docs_origin_for_crate(cfg: &Config, crate_name: &str) -> String {
649 if is_stdlib_crate(crate_name) {
650 format!("https://{HOST_DOC_RUST_LANG_ORG}")
651 } else {
652 cfg.docs_rs_origin.clone()
653 }
654}
655
656pub fn stdlib_channel(version: &str) -> &str {
660 match version {
661 "latest" => "stable",
662 other => other,
663 }
664}
665
666pub fn validate_query(query: &str, allow_empty: bool) -> AppResult<()> {
672 crate::domain::SearchQuery::parse(query, allow_empty).map(|_| ())
673}
674
675pub fn validate_item_path(path: &str) -> AppResult<Vec<String>> {
681 crate::domain::ItemPath::parse(path).map(|p| p.into_segments())
682}
683
684pub fn resolve_version_arg(raw: Option<&str>) -> AppResult<String> {
690 crate::domain::VersionArg::parse_opt(raw).map(|v| v.as_str().to_string())
691}
692
693#[cfg(test)]
694mod tests {
695 use super::*;
696 use std::fs;
697 use std::io::Write;
698
699 #[test]
700 fn crate_name_rules() {
701 assert!(validate_crate_name("serde").is_ok());
702 assert!(validate_crate_name("async-trait").is_ok());
703 assert!(validate_crate_name("std").is_ok());
705 assert!(validate_crate_name("core").is_ok());
706 assert!(validate_crate_name("alloc").is_ok());
707 assert!(is_stdlib_crate("std"));
708 assert!(!is_stdlib_crate("serde"));
709 assert!(validate_crate_name("").is_err());
710 assert!(validate_crate_name("1bad").is_err());
711 assert!(validate_crate_name(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
712 }
713
714 #[test]
715 fn version_policy() {
716 assert_eq!(resolve_version_arg(None).unwrap(), "latest");
717 assert_eq!(resolve_version_arg(Some("")).unwrap(), "latest");
718 assert_eq!(resolve_version_arg(Some("1.0.0")).unwrap(), "1.0.0");
719 assert_eq!(
720 resolve_version_arg(Some("1.0.0-rc.1")).unwrap(),
721 "1.0.0-rc.1"
722 );
723 assert!(resolve_version_arg(Some("v1.0.0")).is_err());
724 assert!(resolve_version_arg(Some("1.0.0+build")).is_err());
725 assert!(resolve_version_arg(Some("not-a-version")).is_err());
726 }
727
728 #[test]
729 fn query_and_path_rules() {
730 assert!(validate_query("serde", false).is_ok());
731 assert!(validate_query("", false).is_err());
732 assert!(validate_query("", true).is_ok());
733 assert!(validate_query(&"q".repeat(MAX_QUERY_CHARS + 1), true).is_err());
734 let segs = validate_item_path("clap::Parser").unwrap();
735 assert_eq!(segs, vec!["clap", "Parser"]);
736 assert!(validate_item_path("::").is_err());
737 assert!(validate_item_path("").is_err());
738 assert!(validate_item_path(&format!("a::{}", "b".repeat(MAX_ITEM_PATH_CHARS))).is_err());
739 }
740
741 #[test]
742 fn item_path_accepts_slash_and_rejects_bad_segments() {
743 let segs = validate_item_path("runtime/Runtime").unwrap();
744 assert_eq!(segs, vec!["runtime", "Runtime"]);
745 let mixed = validate_item_path("tokio::runtime/Runtime").unwrap();
746 assert_eq!(mixed, vec!["tokio", "runtime", "Runtime"]);
747 assert_eq!(
748 validate_item_path("async_trait").unwrap(),
749 vec!["async_trait"]
750 );
751 assert!(validate_item_path("has space").is_err());
752 assert!(validate_item_path("foo.bar").is_err());
753 assert!(validate_item_path("..").is_err());
754 assert!(validate_item_path("a/../b").is_err());
755 assert!(validate_item_path("/").is_err());
756 }
757
758 #[test]
759 fn default_user_agent_variants() {
760 let ua = default_user_agent(None);
761 assert!(ua.contains(APP_NAME));
762 let ua2 = default_user_agent(Some("dev@example.com"));
763 assert!(ua2.contains("dev@example.com"));
764 let ua3 = default_user_agent(Some("https://example.com"));
765 assert!(ua3.contains("+https://example.com"));
766 }
767
768 #[test]
769 fn config_load_toml_and_durations() {
770 let dir = tempfile::tempdir().unwrap();
771 let path = dir.path().join("config.toml");
772 let mut f = fs::File::create(&path).unwrap();
773 writeln!(
774 f,
775 "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"
776 )
777 .unwrap();
778 let cache_dir = dir.path().join("cache");
779 let cfg =
780 Config::load_with_cache_dir(Some(dir.path().to_path_buf()), Some(cache_dir.clone()))
781 .unwrap();
782 assert_eq!(cfg.timeout_secs, 12);
783 assert_eq!(cfg.rate_limit_delay_ms, 50);
784 assert!(cfg.user_agent.contains("a@b.c"));
785 assert_eq!(cfg.timeout(), Duration::from_secs(12));
786 assert_eq!(cfg.rate_limit_delay(), Duration::from_millis(50));
787 assert!(cfg.connect_timeout() >= Duration::from_secs(1));
788 assert_eq!(cfg.crates_io_origin, "http://127.0.0.1:9");
789 assert_eq!(cfg.docs_rs_origin, "http://127.0.0.1:9");
790 assert_eq!(cfg.lang.as_deref(), Some("pt-BR"));
791 assert_eq!(cfg.max_retries, 2);
792 assert_eq!(cfg.max_body_bytes, 1000);
793 assert_eq!(cfg.max_output_bytes, 2000);
794 assert_eq!(cfg.cache_ttl_secs, 3600);
795 assert_eq!(cfg.cache_dir.as_deref(), Some(cache_dir.as_path()));
796 assert!(cfg.cache_enabled());
797 }
798
799 #[test]
800 fn config_invalid_toml_errors() {
801 let dir = tempfile::tempdir().unwrap();
802 fs::write(dir.path().join("config.toml"), "timeout_secs = [\n").unwrap();
803 let err = Config::load(Some(dir.path().to_path_buf())).unwrap_err();
804 assert_eq!(err.kind(), ErrorKind::Config);
805 }
806
807 #[test]
808 fn normalize_origin_trims_slash() {
809 assert_eq!(normalize_origin(" https://docs.rs/ "), "https://docs.rs");
810 }
811
812 #[test]
813 fn resolve_config_dir_prefers_explicit_override() {
814 let explicit = PathBuf::from("/tmp/docsrs-cli-explicit-config");
815 let got = resolve_config_dir(Some(explicit.clone()));
816 assert_eq!(got.as_deref(), Some(explicit.as_path()));
817 }
818
819 #[test]
820 fn resolve_cache_dir_home_layout() {
821 let home = PathBuf::from("/tmp/docsrs-cli-home-sandbox");
823 let cache = home.join("cache");
824 assert_eq!(cache.file_name().and_then(|s| s.to_str()), Some("cache"));
825 let got = crate::cache::resolve_cache_dir(Some(cache.clone()));
827 assert_eq!(got.as_deref(), Some(cache.as_path()));
828 }
829
830 #[test]
831 fn config_defaults_positive() {
832 let cfg = Config::default();
833 assert!(cfg.timeout_secs >= 1);
834 assert!(cfg.max_body_bytes > 0);
835 assert!(cfg.user_agent.contains(APP_NAME));
836 }
837
838 #[test]
839 fn clamp_resource_limits_caps_body_and_output() {
840 let mut cfg = Config {
841 max_body_bytes: HARD_MAX_BODY_BYTES.saturating_mul(8),
842 max_output_bytes: HARD_MAX_OUTPUT_BYTES.saturating_mul(8),
843 ..Config::default()
844 };
845 cfg.clamp_resource_limits();
846 assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
847 assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
848 cfg.max_body_bytes = 64;
850 cfg.max_output_bytes = 32;
851 cfg.clamp_resource_limits();
852 assert_eq!(cfg.max_body_bytes, 64);
853 assert_eq!(cfg.max_output_bytes, 32);
854 }
855
856 #[test]
857 fn toml_cannot_raise_max_body_above_hard_ceiling() {
858 let dir = tempfile::tempdir().unwrap();
859 let path = dir.path().join("config.toml");
860 let huge_body = HARD_MAX_BODY_BYTES.saturating_mul(10);
861 let huge_out = HARD_MAX_OUTPUT_BYTES.saturating_mul(10);
862 fs::write(
863 &path,
864 format!("max_body_bytes = {huge_body}\nmax_output_bytes = {huge_out}\n"),
865 )
866 .unwrap();
867 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
868 assert_eq!(cfg.max_body_bytes, HARD_MAX_BODY_BYTES);
869 assert_eq!(cfg.max_output_bytes, HARD_MAX_OUTPUT_BYTES);
870 }
871
872 #[test]
873 fn hard_ceilings_equal_defaults() {
874 assert_eq!(HARD_MAX_BODY_BYTES, DEFAULT_MAX_BODY_BYTES);
876 assert_eq!(HARD_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_BYTES);
877 assert_eq!(Config::default().max_body_bytes, HARD_MAX_BODY_BYTES);
878 assert_eq!(Config::default().max_output_bytes, HARD_MAX_OUTPUT_BYTES);
879 }
880
881 #[test]
882 fn path_source_tokens_are_stable() {
883 assert_eq!(PathSource::CliOrEnv.as_str(), "cli-or-env");
884 assert_eq!(PathSource::HomeSandbox.as_str(), "home-sandbox");
885 assert_eq!(PathSource::Xdg.as_str(), "xdg");
886 assert_eq!(PathSource::Unresolved.as_str(), "unresolved");
887 }
888
889 #[test]
890 fn resolve_config_dir_with_source_reports_cli() {
891 let explicit = PathBuf::from("/tmp/docsrs-cli-src-explicit");
892 let (got, source) = resolve_config_dir_with_source(Some(explicit.clone()));
893 assert_eq!(got.as_deref(), Some(explicit.as_path()));
894 assert_eq!(source, PathSource::CliOrEnv);
895 }
896
897 #[test]
898 fn init_config_toml_creates_and_refuses_without_force() {
899 let dir = tempfile::tempdir().unwrap();
900 let r1 = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap();
901 assert!(r1.created);
902 assert!(!r1.overwritten);
903 assert!(Path::new(&r1.path).is_file());
904 let text = fs::read_to_string(&r1.path).unwrap();
905 assert!(text.contains("docsrs-cli XDG configuration"));
906 assert!(text.contains("No .env file is required"));
907 #[cfg(unix)]
908 {
909 use std::os::unix::fs::PermissionsExt;
910 let mode = fs::metadata(&r1.path).unwrap().permissions().mode() & 0o777;
911 assert_eq!(mode, 0o600);
912 }
913 let err = init_config_toml(Some(dir.path().to_path_buf()), false).unwrap_err();
914 assert_eq!(err.kind(), ErrorKind::Config);
915 let r2 = init_config_toml(Some(dir.path().to_path_buf()), true).unwrap();
916 assert!(r2.created);
917 assert!(r2.overwritten);
918 }
919
920 #[test]
921 fn config_load_marks_toml_loaded() {
922 let dir = tempfile::tempdir().unwrap();
923 fs::write(dir.path().join("config.toml"), "timeout_secs = 9\n").unwrap();
924 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
925 assert!(cfg.config_toml_loaded);
926 assert_eq!(cfg.timeout_secs, 9);
927 assert_eq!(cfg.config_path_source, PathSource::CliOrEnv);
928 let inv = config_path_data(&cfg);
929 assert!(inv.config_file_exists);
930 assert!(!inv.dotenv_runtime);
931 }
932
933 #[test]
934 fn config_load_without_toml_is_not_loaded() {
935 let dir = tempfile::tempdir().unwrap();
936 let cfg = Config::load(Some(dir.path().to_path_buf())).unwrap();
937 assert!(!cfg.config_toml_loaded);
938 assert!(!config_path_data(&cfg).config_file_exists);
939 }
940}