Skip to main content

docsrs_cli/config/
path_source.rs

1//! Path resolution layers for config/cache (CLI flags + ProjectDirs only).
2//!
3//! Product never reads `DOCSRS_CLI_*` path env vars. Precedence:
4//! 1. Explicit CLI `--config-dir` / `--cache-dir`
5//! 2. `directories::ProjectDirs` (XDG / AppData / Library)
6
7use std::path::PathBuf;
8
9use directories::ProjectDirs;
10use serde::{Deserialize, Serialize};
11
12use super::constants::APP_NAME;
13
14/// Which layer won when resolving a storage path (XDG hierarchy diagnostics).
15///
16/// Product has no API keys; layers for OS keyring / cloud secret managers are
17/// out of scope. Precedence for paths: explicit CLI dir override →
18/// `ProjectDirs` XDG/AppData/Library. Product knobs are never read from env.
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "kebab-case")]
21pub enum PathSource {
22    /// `--config-dir` / `--cache-dir` CLI flags.
23    #[serde(rename = "cli")]
24    CliFlag,
25    /// `directories::ProjectDirs` platform defaults.
26    #[serde(rename = "xdg")]
27    Xdg,
28    /// No path could be resolved.
29    #[default]
30    #[serde(rename = "unresolved")]
31    Unresolved,
32}
33
34impl PathSource {
35    /// Stable machine token for doctor / config path JSON.
36    pub const fn as_str(self) -> &'static str {
37        match self {
38            Self::CliFlag => "cli",
39            Self::Xdg => "xdg",
40            Self::Unresolved => "unresolved",
41        }
42    }
43}
44
45/// Resolve config directory: CLI override, then XDG.
46///
47/// Precedence:
48/// 1. Explicit override (`--config-dir`)
49/// 2. `directories::ProjectDirs` config dir (platform XDG / AppData / Library)
50pub fn resolve_config_dir(override_dir: Option<PathBuf>) -> Option<PathBuf> {
51    resolve_config_dir_with_source(override_dir).0
52}
53
54/// Resolve config directory and report which layer won.
55pub fn resolve_config_dir_with_source(
56    override_dir: Option<PathBuf>,
57) -> (Option<PathBuf>, PathSource) {
58    if let Some(p) = override_dir {
59        return (Some(p), PathSource::CliFlag);
60    }
61    if let Some(p) = ProjectDirs::from("", "", APP_NAME).map(|d| d.config_dir().to_path_buf()) {
62        return (Some(p), PathSource::Xdg);
63    }
64    (None, PathSource::Unresolved)
65}