Skip to main content

tracevault_cli/
config.rs

1use serde::{Deserialize, Serialize};
2use std::path::{Path, PathBuf};
3
4#[derive(Debug, Serialize, Deserialize)]
5pub struct TracevaultConfig {
6    pub agent: String,
7    pub server_url: Option<String>,
8    pub api_key: Option<String>,
9    pub org_slug: Option<String>,
10    pub repo_id: Option<String>,
11}
12
13impl Default for TracevaultConfig {
14    fn default() -> Self {
15        Self {
16            agent: "claude-code".to_string(),
17            server_url: None,
18            api_key: None,
19            org_slug: None,
20            repo_id: None,
21        }
22    }
23}
24
25impl TracevaultConfig {
26    pub fn config_dir(project_root: &Path) -> PathBuf {
27        project_root.join(".tracevault")
28    }
29
30    pub fn config_path(project_root: &Path) -> PathBuf {
31        Self::config_dir(project_root).join("config.toml")
32    }
33
34    /// Runtime artifacts inside a `.tracevault/` directory that must never be
35    /// committed (`config.toml` and the `.gitignore` itself stay tracked).
36    const GITIGNORE_CONTENTS: &'static str = "sessions/\ncache/\n*.local.toml\n";
37
38    /// Ensure a `.gitignore` exists inside `config_dir` (a `.tracevault/` dir)
39    /// so runtime artifacts are ignored no matter where the directory was
40    /// created — including the per-subproject `.tracevault/` dirs the stream
41    /// hook may create from a nested working directory. Idempotent: an existing
42    /// `.gitignore` is never overwritten. Best-effort; callers may ignore the
43    /// result (a failure must never break the hook).
44    pub fn ensure_gitignore(config_dir: &Path) -> std::io::Result<()> {
45        let path = config_dir.join(".gitignore");
46        if path.exists() {
47            return Ok(());
48        }
49        std::fs::write(path, Self::GITIGNORE_CONTENTS)
50    }
51
52    pub fn to_toml(&self) -> String {
53        let mut out = format!("# TraceVault configuration\nagent = \"{}\"\n", self.agent);
54        if let Some(url) = &self.server_url {
55            out.push_str(&format!("server_url = \"{url}\"\n"));
56        }
57        if let Some(slug) = &self.org_slug {
58            out.push_str(&format!("org_slug = \"{slug}\"\n"));
59        }
60        if let Some(rid) = &self.repo_id {
61            out.push_str(&format!("repo_id = \"{rid}\"\n"));
62        }
63        out
64    }
65
66    /// Parse config from the TOML file using simple line-based parsing
67    /// (consistent with the existing resolve_credentials approach).
68    pub fn load(project_root: &Path) -> Option<Self> {
69        let path = Self::config_path(project_root);
70        let content = std::fs::read_to_string(path).ok()?;
71
72        let parse_field = |key: &str| -> Option<String> {
73            content
74                .lines()
75                .find(|l| l.starts_with(key))
76                .and_then(|l| l.split('=').nth(1))
77                .map(|s| s.trim().trim_matches('"').to_string())
78        };
79
80        Some(Self {
81            agent: parse_field("agent").unwrap_or_else(|| "claude-code".to_string()),
82            server_url: parse_field("server_url"),
83            api_key: parse_field("api_key"),
84            org_slug: parse_field("org_slug"),
85            repo_id: parse_field("repo_id"),
86        })
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use std::fs;
94
95    #[test]
96    fn to_toml_all_fields() {
97        let cfg = TracevaultConfig {
98            agent: "claude-code".into(),
99            server_url: Some("https://example.com".into()),
100            api_key: None, // api_key not included in to_toml
101            org_slug: Some("my-org".into()),
102            repo_id: Some("repo-1".into()),
103        };
104        let toml = cfg.to_toml();
105        assert!(toml.contains("agent = \"claude-code\""));
106        assert!(toml.contains("server_url = \"https://example.com\""));
107        assert!(toml.contains("org_slug = \"my-org\""));
108        assert!(toml.contains("repo_id = \"repo-1\""));
109    }
110
111    #[test]
112    fn to_toml_minimal() {
113        let cfg = TracevaultConfig::default();
114        let toml = cfg.to_toml();
115        assert!(toml.contains("agent = \"claude-code\""));
116        assert!(!toml.contains("server_url"));
117    }
118
119    #[test]
120    fn load_valid_config() {
121        let dir = tempfile::tempdir().unwrap();
122        let tv_dir = dir.path().join(".tracevault");
123        fs::create_dir_all(&tv_dir).unwrap();
124        fs::write(
125            tv_dir.join("config.toml"),
126            "agent = \"claude-code\"\nserver_url = \"https://example.com\"\norg_slug = \"myorg\"\n",
127        )
128        .unwrap();
129        let cfg = TracevaultConfig::load(dir.path()).unwrap();
130        assert_eq!(cfg.agent, "claude-code");
131        assert_eq!(cfg.server_url.unwrap(), "https://example.com");
132        assert_eq!(cfg.org_slug.unwrap(), "myorg");
133    }
134
135    #[test]
136    fn load_missing_file_returns_none() {
137        let dir = tempfile::tempdir().unwrap();
138        assert!(TracevaultConfig::load(dir.path()).is_none());
139    }
140
141    #[test]
142    fn ensure_gitignore_creates_runtime_ignore_file() {
143        let dir = tempfile::tempdir().unwrap();
144        let config_dir = dir.path().join(".tracevault");
145        fs::create_dir_all(&config_dir).unwrap();
146
147        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
148
149        let gitignore = config_dir.join(".gitignore");
150        assert!(gitignore.exists(), ".gitignore must be created");
151        let content = fs::read_to_string(&gitignore).unwrap();
152        assert!(content.contains("sessions/"), "must ignore sessions/");
153        assert!(content.contains("cache/"), "must ignore cache/");
154        assert!(content.contains("*.local.toml"), "must ignore *.local.toml");
155    }
156
157    #[test]
158    fn ensure_gitignore_preserves_existing_file() {
159        let dir = tempfile::tempdir().unwrap();
160        let config_dir = dir.path().join(".tracevault");
161        fs::create_dir_all(&config_dir).unwrap();
162        let gitignore = config_dir.join(".gitignore");
163        fs::write(&gitignore, "custom-user-content\n").unwrap();
164
165        TracevaultConfig::ensure_gitignore(&config_dir).unwrap();
166
167        // Idempotent: an existing .gitignore is never overwritten.
168        assert_eq!(
169            fs::read_to_string(&gitignore).unwrap(),
170            "custom-user-content\n"
171        );
172    }
173}