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            org_slug: "acme".into(),
74            project_id: "id".into(),
75            project_name: "p".into(),
76            updated_at: "t".into(),
77        };
78        save_in(tmp.path(), &pb).unwrap();
79        assert_eq!(load_from(tmp.path()), Some(pb));
80    }
81
82    #[test]
83    fn user_project_default_absent_is_none() {
84        let tmp = tempfile::tempdir().unwrap();
85        assert_eq!(load_from(tmp.path()), None);
86    }
87
88    #[test]
89    fn save_then_load_roundtrips_via_real_paths() {
90        // Exercises the REAL `save()`/`load()` entry points (not `save_in`/
91        // `load_from` directly) so a regression like `load()` looking for
92        // `.../user_project.toml/user_project.toml` (passing the file path
93        // instead of its parent dir into `load_from`) would be caught.
94
95        // `commands::project`'s `switch_without_session_or_user_flag_skips_
96        // codebase_check` test also redirects XDG_CONFIG_HOME (to keep its
97        // credential resolution off the developer's real config); both hold
98        // this process-wide lock for their duration so they can't interleave.
99        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
100        let tmp = tempfile::tempdir().unwrap();
101
102        // SAFETY: test-scoped env mutation, restored in a guard so a panic
103        // in `save`/`load` still cleans up the process env.
104        let mut _guard = crate::test_helpers::EnvVarGuard::new();
105        _guard.set("XDG_CONFIG_HOME", tmp.path());
106
107        let pb = ProjectBinding {
108            org_slug: "acme".into(),
109            project_id: "id".into(),
110            project_name: "p".into(),
111            updated_at: "t".into(),
112        };
113        save(&pb).unwrap();
114        assert_eq!(load(), Some(pb));
115    }
116}