Skip to main content

tracevault_cli/
user_project_default.rs

1//! User-level default project binding: a session-independent binding any Claude
2//! Code session inherits when nothing more specific resolves. Set by
3//! `tracevault project switch --user` (or a no-session `project switch`); read by
4//! `project status` as the lowest-precedence tier. (The capture path — `stream`
5//! hooks — does not yet consume this; wiring the resolved project into ingest is
6//! future work, tracked separately from this binding store.) Lets a container
7//! bind its project *before* Claude launches — no session id required.
8
9use std::path::{Path, PathBuf};
10
11use crate::session_state::ProjectBinding;
12
13/// `dirs::config_dir()/tracevault/user_project.toml` — beside `credentials.json`.
14pub fn default_project_path() -> Option<PathBuf> {
15    dirs::config_dir().map(|d| d.join("tracevault").join("user_project.toml"))
16}
17
18fn load_from(dir: &Path) -> Option<ProjectBinding> {
19    let path = dir.join("user_project.toml");
20    let s = std::fs::read_to_string(path).ok()?;
21    toml::from_str(&s).ok()
22}
23
24fn save_in(dir: &Path, binding: &ProjectBinding) -> Result<(), Box<dyn std::error::Error>> {
25    std::fs::create_dir_all(dir)?;
26    // Atomic write: temp file in the same dir, then rename over the target so a
27    // crash or concurrent reader never sees a partial file (mirrors session_state).
28    let path = dir.join("user_project.toml");
29    let tmp = dir.join(format!("user_project.toml.{}.tmp", std::process::id()));
30    std::fs::write(&tmp, toml::to_string(binding)?)?;
31    std::fs::rename(&tmp, path)?;
32    Ok(())
33}
34
35fn clear_at(path: &Path) -> std::io::Result<()> {
36    match std::fs::remove_file(path) {
37        Ok(()) => Ok(()),
38        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
39        Err(e) => Err(e),
40    }
41}
42
43/// Load the user-level default binding; `None` if unset or malformed.
44pub fn load() -> Option<ProjectBinding> {
45    let path = default_project_path()?;
46    let dir = path.parent()?;
47    load_from(dir)
48}
49
50/// Persist the user-level default binding, creating the config dir if needed.
51pub fn save(binding: &ProjectBinding) -> Result<(), Box<dyn std::error::Error>> {
52    let path = default_project_path().ok_or("cannot determine user config dir")?;
53    let dir = path.parent().ok_or("cannot determine parent directory")?;
54    save_in(dir, binding)
55}
56
57/// Remove the user-level default binding (ok if already absent).
58#[allow(dead_code)]
59pub fn clear() -> Result<(), Box<dyn std::error::Error>> {
60    let path = default_project_path().ok_or("cannot determine user config dir")?;
61    clear_at(&path)?;
62    Ok(())
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn user_project_default_roundtrips() {
71        let tmp = tempfile::tempdir().unwrap();
72        let pb = ProjectBinding {
73            project_id: "id".into(),
74            project_name: "p".into(),
75            updated_at: "t".into(),
76        };
77        save_in(tmp.path(), &pb).unwrap();
78        assert_eq!(load_from(tmp.path()), Some(pb));
79    }
80
81    #[test]
82    fn user_project_default_absent_is_none() {
83        let tmp = tempfile::tempdir().unwrap();
84        assert_eq!(load_from(tmp.path()), None);
85    }
86
87    #[test]
88    fn save_then_load_roundtrips_via_real_paths() {
89        // Exercises the REAL `save()`/`load()` entry points (not `save_in`/
90        // `load_from` directly) so a regression like `load()` looking for
91        // `.../user_project.toml/user_project.toml` (passing the file path
92        // instead of its parent dir into `load_from`) would be caught.
93
94        // `commands::project`'s `switch_without_session_or_user_flag_skips_
95        // codebase_check` test also redirects XDG_CONFIG_HOME (to keep its
96        // credential resolution off the developer's real config); both hold
97        // this process-wide lock for their duration so they can't interleave.
98        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
99        let tmp = tempfile::tempdir().unwrap();
100
101        // SAFETY: test-scoped env mutation, restored in a guard so a panic
102        // in `save`/`load` still cleans up the process env.
103        let mut _guard = crate::test_helpers::EnvVarGuard::new();
104        _guard.set("XDG_CONFIG_HOME", tmp.path());
105
106        let pb = ProjectBinding {
107            project_id: "id".into(),
108            project_name: "p".into(),
109            updated_at: "t".into(),
110        };
111        save(&pb).unwrap();
112        assert_eq!(load(), Some(pb));
113    }
114}