Skip to main content

jhol_core/
config.rs

1//! Optional config from .jholrc or ~/.jholrc (JSON). Merged with env and CLI.
2
3use std::path::Path;
4
5use crate::Backend;
6
7/// Optional config from file. CLI and env override these.
8#[derive(Default)]
9pub struct Config {
10    pub backend: Option<Backend>,
11    pub cache_dir: Option<String>,
12    pub offline: Option<bool>,
13    pub frozen: Option<bool>,
14}
15
16/// Load config from .jholrc in dir, then ~/.jholrc. Missing or invalid file = default.
17pub fn load_config(dir: &Path) -> Config {
18    let mut cfg = Config::default();
19    let home = dirs_home();
20    let candidates = [
21        dir.join(".jholrc"),
22        home.map(|h| h.join(".jholrc")).unwrap_or_else(|| dir.join(".none")),
23    ];
24    for path in &candidates {
25        if path.is_file() {
26            if let Ok(s) = std::fs::read_to_string(path) {
27                if let Ok(v) = serde_json::from_str::<serde_json::Value>(&s) {
28                    if let Some(b) = v.get("backend").and_then(|x| x.as_str()) {
29                        cfg.backend = match b {
30                            "bun" => Some(Backend::Bun),
31                            "npm" => Some(Backend::Npm),
32                            _ => None,
33                        };
34                    }
35                    if let Some(c) = v.get("cacheDir").and_then(|x| x.as_str()) {
36                        cfg.cache_dir = Some(c.to_string());
37                    }
38                    if let Some(o) = v.get("offline").and_then(|x| x.as_bool()) {
39                        cfg.offline = Some(o);
40                    }
41                    if let Some(f) = v.get("frozen").and_then(|x| x.as_bool()) {
42                        cfg.frozen = Some(f);
43                    }
44                }
45            }
46            break;
47        }
48    }
49    cfg
50}
51
52fn dirs_home() -> Option<std::path::PathBuf> {
53    #[cfg(unix)]
54    {
55        std::env::var("HOME").ok().map(std::path::PathBuf::from)
56    }
57    #[cfg(windows)]
58    {
59        std::env::var("USERPROFILE").ok().map(std::path::PathBuf::from)
60    }
61}