tracevault_cli/
install_state.rs1use serde::{Deserialize, Serialize};
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13
14#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct InstallState {
16 #[serde(default, skip_serializing_if = "Option::is_none")]
19 pub configured_version: Option<String>,
20 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
23 pub claude_telemetry_opt_out: bool,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub telemetry_auto_enabled: Option<String>,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
32 pub telemetry_added_interval: Option<bool>,
33 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
36 pub repos: BTreeMap<String, RepoState>,
37}
38
39#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct RepoState {
41 pub version: String,
42 #[serde(default)]
44 pub hook_files: Vec<PathBuf>,
45}
46
47pub fn state_path_in(config_root: &Path) -> PathBuf {
48 config_root.join("install-state.json")
49}
50
51pub fn load_in(config_root: &Path) -> InstallState {
54 std::fs::read_to_string(state_path_in(config_root))
55 .ok()
56 .and_then(|s| serde_json::from_str(&s).ok())
57 .unwrap_or_default()
58}
59
60pub fn save_in(config_root: &Path, state: &InstallState) -> std::io::Result<()> {
62 std::fs::create_dir_all(config_root)?;
63 let path = state_path_in(config_root);
64 let tmp = path.with_file_name(format!(
65 "install-state.json.{}.{}.tmp",
66 std::process::id(),
67 std::time::SystemTime::now()
68 .duration_since(std::time::UNIX_EPOCH)
69 .map(|d| d.subsec_nanos())
70 .unwrap_or_default()
71 ));
72 let body = serde_json::to_string_pretty(state).map_err(std::io::Error::other)?;
73 std::fs::write(&tmp, body)
74 .and_then(|()| std::fs::rename(&tmp, &path))
75 .inspect_err(|_| {
76 let _ = std::fs::remove_file(&tmp);
77 })
78}
79
80pub fn update_in(
82 config_root: &Path,
83 change: impl FnOnce(&mut InstallState),
84) -> std::io::Result<()> {
85 let mut state = load_in(config_root);
86 change(&mut state);
87 save_in(config_root, &state)
88}
89
90pub struct Lock(PathBuf);
97
98impl Lock {
99 const STALE: std::time::Duration = std::time::Duration::from_secs(60);
100
101 fn lock_path(config_root: &Path) -> PathBuf {
102 config_root.join("install-state.lock")
103 }
104
105 pub fn try_take(config_root: &Path) -> Option<Self> {
107 std::fs::create_dir_all(config_root).ok()?;
108 let path = Self::lock_path(config_root);
109 for _ in 0..2 {
110 match std::fs::OpenOptions::new()
111 .write(true)
112 .create_new(true)
113 .open(&path)
114 {
115 Ok(_) => return Some(Self(path)),
116 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
117 let stale = std::fs::metadata(&path)
118 .and_then(|m| m.modified())
119 .ok()
120 .and_then(|t| t.elapsed().ok())
121 .is_some_and(|age| age > Self::STALE);
122 if !stale {
123 return None;
124 }
125 let _ = std::fs::remove_file(&path);
126 }
127 Err(_) => return None,
128 }
129 }
130 None
131 }
132
133 pub fn take(config_root: &Path, timeout: std::time::Duration) -> std::io::Result<Self> {
136 let deadline = std::time::Instant::now() + timeout;
137 loop {
138 if let Some(lock) = Self::try_take(config_root) {
139 return Ok(lock);
140 }
141 if std::time::Instant::now() >= deadline {
142 return Err(std::io::Error::other(format!(
143 "{} is held by another TraceVault process; try again",
144 Self::lock_path(config_root).display()
145 )));
146 }
147 std::thread::sleep(std::time::Duration::from_millis(50));
148 }
149 }
150}
151
152impl Drop for Lock {
153 fn drop(&mut self) {
154 let _ = std::fs::remove_file(&self.0);
155 }
156}
157
158pub const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
160
161fn parse(version: &str) -> Option<(u64, u64, u64)> {
164 let core = version.trim().split(['-', '+']).next()?;
165 let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
166 let v = (parts.next()??, parts.next()??, parts.next()??);
167 parts.next().is_none().then_some(v)
168}
169
170pub fn is_newer(current: &str, recorded: Option<&str>) -> bool {
174 match (parse(current), recorded.and_then(parse)) {
175 (Some(current), Some(recorded)) => current > recorded,
176 _ => true,
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 #[test]
185 fn version_comparison() {
186 assert!(is_newer("0.30.0", None));
187 assert!(is_newer("0.30.0", Some("0.29.1")));
188 assert!(is_newer("1.0.0", Some("0.99.99")));
189 assert!(is_newer("0.30.0", Some("garbage")));
190 assert!(!is_newer("0.30.0", Some("0.30.0")));
191 assert!(!is_newer("0.29.1", Some("0.30.0")));
192 assert!(!is_newer("0.30.0-rc.1", Some("0.30.0")));
193 assert!(is_newer("0.10.0", Some("0.9.9")), "numeric, not lexical");
194 }
195
196 #[test]
197 fn missing_or_malformed_state_is_empty_and_round_trips() {
198 let dir = tempfile::tempdir().unwrap();
199 assert_eq!(load_in(dir.path()), InstallState::default());
200 std::fs::write(state_path_in(dir.path()), "{not json").unwrap();
201 assert_eq!(load_in(dir.path()), InstallState::default());
202
203 let mut state = InstallState {
204 configured_version: Some("0.30.0".into()),
205 claude_telemetry_opt_out: true,
206 ..Default::default()
207 };
208 state.repos.insert(
209 "/r".into(),
210 RepoState {
211 version: "0.30.0".into(),
212 hook_files: vec!["/r/.claude/settings.local.json".into()],
213 },
214 );
215 save_in(&dir.path().join("nested"), &state).unwrap();
216 assert_eq!(load_in(&dir.path().join("nested")), state);
217 }
218
219 #[test]
220 fn empty_state_serializes_to_an_empty_object() {
221 assert_eq!(
222 serde_json::to_string(&InstallState::default()).unwrap(),
223 "{}"
224 );
225 }
226}