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