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