Skip to main content

git_nav/
config.rs

1//! Persistent config stored at `~/.config/git-nav/config.toml`.
2//! First run prompts for the root directory and writes it there.
3
4use std::env;
5use std::fs;
6use std::io::{self, IsTerminal, Write};
7use std::path::PathBuf;
8
9use serde::{Deserialize, Serialize};
10
11const DEFAULT_DEPTH: u32 = 4;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct Config {
15    pub root: PathBuf,
16    #[serde(default = "default_depth")]
17    pub depth: u32,
18}
19
20fn default_depth() -> u32 {
21    DEFAULT_DEPTH
22}
23
24impl Config {
25    pub fn expanded_root(&self) -> PathBuf {
26        let s = self.root.to_string_lossy();
27        let expanded = expand_tilde(&s);
28        fs::canonicalize(&expanded).unwrap_or(expanded)
29    }
30}
31
32pub fn expand_tilde(path: &str) -> PathBuf {
33    if path == "~" {
34        return PathBuf::from(home());
35    }
36    if let Some(rest) = path.strip_prefix("~/") {
37        return PathBuf::from(home()).join(rest);
38    }
39    PathBuf::from(path)
40}
41
42fn home() -> String {
43    env::var("HOME").unwrap_or_else(|_| "/".into())
44}
45
46/// XDG-style config path on every platform (`~/.config/git-nav/config.toml`
47/// unless `XDG_CONFIG_HOME` is set).
48pub fn path() -> PathBuf {
49    if let Ok(xdg) = env::var("XDG_CONFIG_HOME") {
50        return PathBuf::from(xdg).join("git-nav/config.toml");
51    }
52    PathBuf::from(home()).join(".config/git-nav/config.toml")
53}
54
55pub fn load_or_init() -> crate::Result<Config> {
56    let path = path();
57    if path.exists() {
58        let data = fs::read_to_string(&path)?;
59        let cfg: Config = toml::from_str(&data)?;
60        return Ok(cfg);
61    }
62    prompt_and_save()
63}
64
65pub fn prompt_and_save() -> crate::Result<Config> {
66    let default_root = default_initial_root();
67    let interactive = io::stdin().is_terminal() && io::stderr().is_terminal();
68    let root = if interactive {
69        let mut stderr = io::stderr();
70        writeln!(stderr, "Welcome to git-nav! Let's set up.")?;
71        write!(
72            stderr,
73            "Top-level directory to scan for git repos [{}]: ",
74            default_root.display()
75        )?;
76        stderr.flush().ok();
77        let mut buf = String::new();
78        io::stdin().read_line(&mut buf)?;
79        let raw = buf.trim();
80        if raw.is_empty() {
81            default_root
82        } else {
83            expand_tilde(raw)
84        }
85    } else {
86        default_root
87    };
88
89    let cfg = Config {
90        root,
91        depth: DEFAULT_DEPTH,
92    };
93    save(&cfg)?;
94    Ok(cfg)
95}
96
97pub fn save(cfg: &Config) -> crate::Result<()> {
98    let path = path();
99    if let Some(parent) = path.parent() {
100        fs::create_dir_all(parent)?;
101    }
102    let text = toml::to_string_pretty(cfg)?;
103    fs::write(&path, text)?;
104    Ok(())
105}
106
107fn default_initial_root() -> PathBuf {
108    let projects = PathBuf::from(home()).join("projects");
109    if projects.exists() {
110        projects
111    } else {
112        PathBuf::from(home())
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn expand_tilde_home() {
122        // SAFETY: env mutation is unsafe in Rust 2024 because env vars are
123        // process-global. This test only reads HOME after setting it, and
124        // no other test in this module races on HOME.
125        unsafe { std::env::set_var("HOME", "/tmp/faux-home") };
126        assert_eq!(expand_tilde("~"), PathBuf::from("/tmp/faux-home"));
127        assert_eq!(
128            expand_tilde("~/projects"),
129            PathBuf::from("/tmp/faux-home/projects")
130        );
131        assert_eq!(expand_tilde("/abs/path"), PathBuf::from("/abs/path"));
132    }
133
134    #[test]
135    fn config_serialization_roundtrip() {
136        let cfg = Config {
137            root: PathBuf::from("/tmp/repos"),
138            depth: 3,
139        };
140        let text = toml::to_string_pretty(&cfg).unwrap();
141        let parsed: Config = toml::from_str(&text).unwrap();
142        assert_eq!(parsed.root, cfg.root);
143        assert_eq!(parsed.depth, cfg.depth);
144    }
145
146    #[test]
147    fn depth_defaults_when_missing() {
148        let cfg: Config = toml::from_str("root = \"/tmp/x\"\n").unwrap();
149        assert_eq!(cfg.depth, DEFAULT_DEPTH);
150    }
151}