Skip to main content

tracevault_cli/
layout.rs

1//! Where this CLI keeps its files, and where releases before the `visdom`
2//! naming kept them.
3//!
4//! Everything new is written under `.visdom/` (in a repository or workspace
5//! folder) and `visdom/` (in the user's config and state directories). The
6//! older `.tracevault/` and `tracevault/` locations are still **read**: each
7//! file is looked for in the new place first, then in the old one, so an
8//! installation made by an earlier release keeps working without a migration
9//! step. Nothing is moved on its own — an earlier `tracevault` still on `PATH`
10//! keeps finding its files — except by `init`, which carries the old files
11//! over (see `commands::relocate`).
12
13use std::path::{Path, PathBuf};
14
15/// The directory in a repository (or workspace folder).
16pub const REPO_DIR: &str = ".visdom";
17/// What [`REPO_DIR`] was called before.
18pub const LEGACY_REPO_DIR: &str = ".tracevault";
19/// The directory under the user's config and state directories.
20pub const USER_DIR: &str = "visdom";
21/// What [`USER_DIR`] was called before.
22pub const LEGACY_USER_DIR: &str = "tracevault";
23/// The tracing config's file name. `config.toml` in the same directories is
24/// the `visdom` launcher's own (agent, tracing mode, gateway).
25pub const TRACING_CONFIG: &str = "tracing.toml";
26/// The tracing config's file name in the legacy directories.
27pub const LEGACY_TRACING_CONFIG: &str = "config.toml";
28
29/// `<root>/.visdom`.
30pub fn repo_dir(root: &Path) -> PathBuf {
31    root.join(REPO_DIR)
32}
33
34/// `<root>/.tracevault`.
35pub fn legacy_repo_dir(root: &Path) -> PathBuf {
36    root.join(LEGACY_REPO_DIR)
37}
38
39/// Whether `root` holds this CLI's directory under either name.
40pub fn has_repo_dir(root: &Path) -> bool {
41    repo_dir(root).is_dir() || legacy_repo_dir(root).is_dir()
42}
43
44/// Whether `root` has been set up for tracing: a legacy `.tracevault/`, or a
45/// `.visdom/` with more in it than the `config.toml` a team commits for the
46/// `visdom` launcher — a checkout that only carries that file has not been.
47pub fn is_set_up(root: &Path) -> bool {
48    let new = repo_dir(root);
49    legacy_repo_dir(root).is_dir()
50        || std::fs::read_dir(new).is_ok_and(|entries| {
51            entries
52                .flatten()
53                .any(|entry| entry.file_name() != "config.toml")
54        })
55}
56
57/// `new` unless only `legacy` exists: the path to read, or to keep using for
58/// something that is already there.
59pub fn existing_or_new(new: PathBuf, legacy: PathBuf) -> PathBuf {
60    if !new.exists() && legacy.exists() {
61        legacy
62    } else {
63        new
64    }
65}
66
67/// `rel` inside `root`'s directory: under `.visdom/` unless it exists only
68/// under `.tracevault/`.
69pub fn repo_path(root: &Path, rel: &str) -> PathBuf {
70    existing_or_new(repo_dir(root).join(rel), legacy_repo_dir(root).join(rel))
71}
72
73/// Where `root`'s tracing config is written: `.visdom/tracing.toml`.
74pub fn tracing_config(root: &Path) -> PathBuf {
75    repo_dir(root).join(TRACING_CONFIG)
76}
77
78/// `root`'s tracing config as an earlier release wrote it:
79/// `.tracevault/config.toml`.
80pub fn legacy_tracing_config(root: &Path) -> PathBuf {
81    legacy_repo_dir(root).join(LEGACY_TRACING_CONFIG)
82}
83
84/// `root`'s tracing config to read: the new file, else the legacy one.
85pub fn existing_tracing_config(root: &Path) -> PathBuf {
86    existing_or_new(tracing_config(root), legacy_tracing_config(root))
87}
88
89/// Where new sessions under `root` are kept: `.visdom/sessions`.
90pub fn sessions_dir(root: &Path) -> PathBuf {
91    repo_dir(root).join("sessions")
92}
93
94/// `.tracevault/sessions` under `root`.
95pub fn legacy_sessions_dir(root: &Path) -> PathBuf {
96    legacy_repo_dir(root).join("sessions")
97}
98
99/// Every sessions directory under `root` that exists, the new one first.
100pub fn existing_sessions_dirs(root: &Path) -> Vec<PathBuf> {
101    [sessions_dir(root), legacy_sessions_dir(root)]
102        .into_iter()
103        .filter(|dir| dir.is_dir())
104        .collect()
105}
106
107/// The directory of session `id` under `root`: `.visdom/sessions/<id>`, or
108/// the session's `.tracevault/sessions/<id>` when an earlier release started
109/// it there — a session keeps one directory for its whole life.
110pub fn session_dir(root: &Path, id: &str) -> PathBuf {
111    existing_or_new(
112        sessions_dir(root).join(id),
113        legacy_sessions_dir(root).join(id),
114    )
115}
116
117/// The project root a session directory (`<root>/.visdom/sessions/<id>`, or
118/// the legacy spelling) lives under. `None` when the layout does not match.
119pub fn session_dir_root(session_dir: &Path) -> Option<&Path> {
120    let sessions = session_dir.parent()?;
121    let dir = sessions.parent()?;
122    let name = dir.file_name()?;
123    if sessions.file_name()? != "sessions" || (name != REPO_DIR && name != LEGACY_REPO_DIR) {
124        return None;
125    }
126    dir.parent()
127}
128
129/// The user-level directory under `base` (a config or state directory).
130pub fn user_dir_in(base: &Path) -> PathBuf {
131    base.join(USER_DIR)
132}
133
134/// The legacy directory beside a user-level directory: `<base>/tracevault`
135/// for `<base>/visdom`. `None` for a directory with another name (an injected
136/// one, as tests use), which has no legacy sibling.
137pub fn legacy_sibling(user_dir: &Path) -> Option<PathBuf> {
138    (user_dir.file_name()? == USER_DIR).then(|| user_dir.with_file_name(LEGACY_USER_DIR))
139}
140
141/// `name` inside the user-level directory `user_dir`, or — when it exists
142/// only there — `legacy_name` inside the legacy directory beside it.
143pub fn user_path_renamed(user_dir: &Path, name: &str, legacy_name: &str) -> PathBuf {
144    let new = user_dir.join(name);
145    match legacy_sibling(user_dir) {
146        Some(legacy) => existing_or_new(new, legacy.join(legacy_name)),
147        None => new,
148    }
149}
150
151/// `name` inside the user-level directory `user_dir`, or inside the legacy
152/// directory beside it when it exists only there.
153pub fn user_path(user_dir: &Path, name: &str) -> PathBuf {
154    user_path_renamed(user_dir, name, name)
155}
156
157/// The user's tracing config to read under `user_dir`: `tracing.toml`, else
158/// the legacy directory's `config.toml`.
159pub fn existing_user_tracing_config(user_dir: &Path) -> PathBuf {
160    user_path_renamed(user_dir, TRACING_CONFIG, LEGACY_TRACING_CONFIG)
161}
162
163/// Where an earlier release would have kept the file or directory `path`:
164/// the same path with its `.visdom` component spelled `.tracevault`, or — for
165/// a file directly in a `visdom` user directory — the one in the `tracevault`
166/// directory beside it. `None` for a path that is in neither.
167pub fn legacy_twin(path: &Path) -> Option<PathBuf> {
168    let parts: Vec<_> = path.components().collect();
169    if let Some(at) = parts.iter().rposition(|c| c.as_os_str() == REPO_DIR) {
170        let mut twin: PathBuf = parts[..at].iter().collect();
171        twin.push(LEGACY_REPO_DIR);
172        twin.extend(&parts[at + 1..]);
173        return Some(twin);
174    }
175    Some(legacy_sibling(path.parent()?)?.join(path.file_name()?))
176}
177
178/// `path`, or its [`legacy_twin`] when `path` does not exist and the twin
179/// does: the file to **read**.
180pub fn existing_or_twin(path: &Path) -> PathBuf {
181    if !path.exists() {
182        if let Some(twin) = legacy_twin(path).filter(|twin| twin.exists()) {
183            return twin;
184        }
185    }
186    path.to_path_buf()
187}
188
189/// `sessions_dir` (a checkout's `.visdom/sessions`) and, when there is one,
190/// the `.tracevault/sessions` beside it: every directory to scan for the
191/// checkout's sessions. A directory laid out differently is scanned alone.
192pub fn with_legacy_sessions(sessions_dir: &Path) -> Vec<PathBuf> {
193    let mut dirs = vec![sessions_dir.to_path_buf()];
194    if let Some(root) = session_dir_root(&sessions_dir.join("x")) {
195        let legacy = legacy_sessions_dir(root);
196        if legacy != sessions_dir && legacy.is_dir() {
197            dirs.push(legacy);
198        }
199    }
200    dirs
201}
202
203/// Every entry of `sessions_dir` and of the legacy directory beside it.
204pub fn session_entries(sessions_dir: &Path) -> Vec<std::fs::DirEntry> {
205    with_legacy_sessions(sessions_dir)
206        .iter()
207        .filter_map(|dir| std::fs::read_dir(dir).ok())
208        .flatten()
209        .filter_map(|entry| entry.ok())
210        .collect()
211}
212
213/// The legacy state directory matching a user-level sessions directory:
214/// `<state>/tracevault/sessions` for `<state>/visdom/sessions`. `None` for a
215/// directory laid out differently (an injected one).
216pub fn legacy_user_sessions_dir(sessions_dir: &Path) -> Option<PathBuf> {
217    if sessions_dir.file_name()? != "sessions" {
218        return None;
219    }
220    Some(legacy_sibling(sessions_dir.parent()?)?.join("sessions"))
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226    use std::fs;
227
228    #[test]
229    fn a_new_file_is_preferred_and_a_legacy_one_is_the_fallback() {
230        let dir = tempfile::tempdir().unwrap();
231        let root = dir.path();
232        // Nothing exists: the new place.
233        assert_eq!(
234            repo_path(root, "context.json"),
235            root.join(".visdom/context.json")
236        );
237        fs::create_dir_all(root.join(".tracevault")).unwrap();
238        fs::write(root.join(".tracevault/context.json"), "{}").unwrap();
239        assert_eq!(
240            repo_path(root, "context.json"),
241            root.join(".tracevault/context.json")
242        );
243        fs::create_dir_all(root.join(".visdom")).unwrap();
244        fs::write(root.join(".visdom/context.json"), "{}").unwrap();
245        assert_eq!(
246            repo_path(root, "context.json"),
247            root.join(".visdom/context.json")
248        );
249    }
250
251    #[test]
252    fn the_tracing_config_is_renamed_between_the_directories() {
253        let dir = tempfile::tempdir().unwrap();
254        let root = dir.path();
255        assert_eq!(
256            existing_tracing_config(root),
257            root.join(".visdom/tracing.toml")
258        );
259        fs::create_dir_all(root.join(".tracevault")).unwrap();
260        fs::write(root.join(".tracevault/config.toml"), "").unwrap();
261        assert_eq!(
262            existing_tracing_config(root),
263            root.join(".tracevault/config.toml")
264        );
265        // The launcher's own `.visdom/config.toml` is not the tracing config.
266        fs::create_dir_all(root.join(".visdom")).unwrap();
267        fs::write(root.join(".visdom/config.toml"), "").unwrap();
268        assert_eq!(
269            existing_tracing_config(root),
270            root.join(".tracevault/config.toml")
271        );
272    }
273
274    #[test]
275    fn a_session_stays_in_the_directory_it_started_in() {
276        let dir = tempfile::tempdir().unwrap();
277        let root = dir.path();
278        fs::create_dir_all(root.join(".tracevault/sessions/old")).unwrap();
279        assert_eq!(
280            session_dir(root, "old"),
281            root.join(".tracevault/sessions/old")
282        );
283        assert_eq!(session_dir(root, "new"), root.join(".visdom/sessions/new"));
284        assert_eq!(
285            existing_sessions_dirs(root),
286            vec![root.join(".tracevault/sessions")]
287        );
288        assert_eq!(
289            session_dir_root(&root.join(".visdom/sessions/new")),
290            Some(root)
291        );
292        assert_eq!(
293            session_dir_root(&root.join(".tracevault/sessions/old")),
294            Some(root)
295        );
296        assert_eq!(session_dir_root(&root.join("elsewhere/sessions/x")), None);
297    }
298
299    #[test]
300    fn only_the_real_user_directory_has_a_legacy_sibling() {
301        let dir = tempfile::tempdir().unwrap();
302        let base = dir.path();
303        fs::create_dir_all(base.join("tracevault")).unwrap();
304        fs::write(base.join("tracevault/credentials.json"), "{}").unwrap();
305        fs::write(base.join("tracevault/config.toml"), "").unwrap();
306        let user = user_dir_in(base);
307        assert_eq!(
308            user_path(&user, "credentials.json"),
309            base.join("tracevault/credentials.json")
310        );
311        assert_eq!(
312            existing_user_tracing_config(&user),
313            base.join("tracevault/config.toml")
314        );
315        assert_eq!(
316            user_path(&user, "default_repo.toml"),
317            base.join("visdom/default_repo.toml")
318        );
319        // An injected directory is used as it is.
320        let injected = base.join("injected");
321        assert_eq!(
322            user_path(&injected, "credentials.json"),
323            injected.join("credentials.json")
324        );
325    }
326
327    #[test]
328    fn a_legacy_twin_is_the_same_path_under_the_old_name() {
329        assert_eq!(
330            legacy_twin(Path::new("/repo/.visdom/worktrees/wt/context.json")),
331            Some(PathBuf::from("/repo/.tracevault/worktrees/wt/context.json"))
332        );
333        assert_eq!(
334            legacy_twin(Path::new("/home/u/.config/visdom/context.json")),
335            Some(PathBuf::from("/home/u/.config/tracevault/context.json"))
336        );
337        assert_eq!(legacy_twin(Path::new("/somewhere/else/context.json")), None);
338
339        let dir = tempfile::tempdir().unwrap();
340        let new = dir.path().join(".visdom/context.json");
341        assert_eq!(existing_or_twin(&new), new);
342        fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
343        fs::write(dir.path().join(".tracevault/context.json"), "{}").unwrap();
344        assert_eq!(
345            existing_or_twin(&new),
346            dir.path().join(".tracevault/context.json")
347        );
348    }
349}