Skip to main content

tracevault_cli/
user_default.rs

1//! User-level default repo binding: a session-independent binding any Claude
2//! Code session inherits when nothing more specific resolves. Set by
3//! `tracevault repo switch --user` (or a no-session `repo switch`); read by
4//! `stream`/`repo status` as the lowest-precedence tier. Lets a container bind
5//! its repo *before* Claude launches — no session id required.
6
7use std::path::{Path, PathBuf};
8
9use crate::session_state::RepoBinding;
10
11const FILE: &str = "default_repo.toml";
12
13/// `dirs::config_dir()/visdom/default_repo.toml` — beside `credentials.json`.
14pub fn default_repo_path() -> Option<PathBuf> {
15    dirs::config_dir().map(|d| crate::layout::user_dir_in(&d).join(FILE))
16}
17
18/// The file an earlier release kept the binding in.
19fn legacy_repo_path() -> Option<PathBuf> {
20    crate::layout::legacy_sibling(default_repo_path()?.parent()?).map(|dir| dir.join(FILE))
21}
22
23fn load_from(path: &Path) -> Option<RepoBinding> {
24    let s = std::fs::read_to_string(path).ok()?;
25    toml::from_str(&s).ok()
26}
27
28fn save_to(path: &Path, binding: &RepoBinding) -> Result<(), Box<dyn std::error::Error>> {
29    if let Some(parent) = path.parent() {
30        std::fs::create_dir_all(parent)?;
31    }
32    // Atomic write: temp file in the same dir, then rename over the target so a
33    // crash or concurrent reader never sees a partial file (mirrors session_state).
34    let tmp = path.with_file_name(format!("default_repo.toml.{}.tmp", std::process::id()));
35    std::fs::write(&tmp, toml::to_string(binding)?)?;
36    std::fs::rename(&tmp, path)?;
37    Ok(())
38}
39
40fn clear_at(path: &Path) -> std::io::Result<()> {
41    match std::fs::remove_file(path) {
42        Ok(()) => Ok(()),
43        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
44        Err(e) => Err(e),
45    }
46}
47
48/// Load the user-level default binding; `None` if unset or malformed.
49pub fn load() -> Option<RepoBinding> {
50    let path = default_repo_path()?;
51    if !path.exists() {
52        if let Some(legacy) = legacy_repo_path() {
53            return load_from(&legacy);
54        }
55    }
56    load_from(&path)
57}
58
59/// Persist the user-level default binding, creating the config dir if needed.
60pub fn save(binding: &RepoBinding) -> Result<(), Box<dyn std::error::Error>> {
61    let path = default_repo_path().ok_or("cannot determine user config dir")?;
62    save_to(&path, binding)
63}
64
65/// Remove the user-level default binding (ok if already absent).
66pub fn clear() -> Result<(), Box<dyn std::error::Error>> {
67    let path = default_repo_path().ok_or("cannot determine user config dir")?;
68    clear_at(&path)?;
69    // Otherwise the binding an earlier release left would come back.
70    if let Some(legacy) = legacy_repo_path() {
71        clear_at(&legacy)?;
72    }
73    Ok(())
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    fn binding(id: &str) -> RepoBinding {
81        RepoBinding {
82            repo_id: id.into(),
83            git_url: None,
84            remote_id: None,
85            codebase_name: None,
86            updated_at: "t".into(),
87        }
88    }
89
90    #[test]
91    fn save_to_then_load_from_round_trips() {
92        let tmp = tempfile::tempdir().unwrap();
93        let path = tmp.path().join("default_repo.toml");
94        let b = binding("r1");
95        save_to(&path, &b).unwrap();
96        assert_eq!(load_from(&path), Some(b));
97    }
98
99    #[test]
100    fn load_from_missing_is_none() {
101        let tmp = tempfile::tempdir().unwrap();
102        assert_eq!(load_from(&tmp.path().join("nope.toml")), None);
103    }
104
105    #[test]
106    fn load_from_malformed_is_none() {
107        let tmp = tempfile::tempdir().unwrap();
108        let path = tmp.path().join("default_repo.toml");
109        std::fs::write(&path, "this is not valid toml : : :").unwrap();
110        assert_eq!(load_from(&path), None);
111    }
112
113    #[test]
114    fn clear_at_removes_and_is_idempotent() {
115        let tmp = tempfile::tempdir().unwrap();
116        let path = tmp.path().join("default_repo.toml");
117        save_to(&path, &binding("r1")).unwrap();
118        assert!(path.exists());
119        clear_at(&path).unwrap();
120        assert!(!path.exists());
121        // Second clear on an absent file is still Ok.
122        clear_at(&path).unwrap();
123        assert_eq!(load_from(&path), None);
124    }
125
126    #[test]
127    fn save_to_leaves_no_tmp_file() {
128        let tmp = tempfile::tempdir().unwrap();
129        let path = tmp.path().join("default_repo.toml");
130        save_to(&path, &binding("r1")).unwrap();
131        let leftover = std::fs::read_dir(tmp.path())
132            .unwrap()
133            .filter_map(|e| e.ok())
134            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
135        assert!(!leftover, "temp file must be renamed away");
136    }
137
138    #[test]
139    fn clearing_removes_the_legacy_default_too() {
140        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
141        let tmp = tempfile::tempdir().unwrap();
142        let mut _guard = crate::test_helpers::EnvVarGuard::new();
143        _guard.set("XDG_CONFIG_HOME", tmp.path());
144        let legacy = tmp.path().join("tracevault/default_repo.toml");
145        save_to(&legacy, &binding("old")).unwrap();
146        // Read from the legacy file until one is saved.
147        assert_eq!(load(), Some(binding("old")));
148        save(&binding("new")).unwrap();
149        assert_eq!(load(), Some(binding("new")));
150        assert!(legacy.exists());
151
152        clear().unwrap();
153
154        assert!(!legacy.exists());
155        assert!(!tmp.path().join("visdom/default_repo.toml").exists());
156        assert_eq!(load(), None);
157    }
158}