Skip to main content

tracevault_cli/
program.rs

1//! Which command the hooks this CLI installs call.
2//!
3//! The library runs as two binaries: the `tracevault` command and, under
4//! `visdom trace`, the `visdom` one that replaces it. Whatever one of them
5//! installs for an agent or for git to run later — hooks, the telemetry
6//! helper, plugins — has to name a command, and it names the one that
7//! installed it: a machine set up with `visdom` alone has no `tracevault` on
8//! `PATH`.
9//!
10//! The move goes one way. `visdom` rewrites `tracevault …` commands it finds
11//! to `visdom trace …`; `tracevault` leaves `visdom trace …` commands as they
12//! are (see [`installs_visdom`]), so an automatic refresh started by one
13//! binary never undoes what the other set up.
14
15use std::sync::atomic::{AtomicBool, Ordering};
16
17static VISDOM: AtomicBool = AtomicBool::new(false);
18
19/// How the `tracevault` binary spells a tracing command.
20pub const TRACEVAULT: &str = "tracevault";
21/// How the `visdom` binary spells one.
22pub const VISDOM_TRACE: &str = "visdom trace";
23
24/// Called once by the `visdom` binary before it runs anything.
25pub fn run_as_visdom() {
26    VISDOM.store(true, Ordering::Relaxed);
27}
28
29/// Whether this process is the `visdom` binary.
30pub fn is_visdom() -> bool {
31    VISDOM.load(Ordering::Relaxed)
32}
33
34/// What comes after the command name when `command` is one of ours
35/// (`tracevault stream …` or `visdom trace stream …` → `stream …`).
36pub fn subcommand(command: &str) -> Option<&str> {
37    [VISDOM_TRACE, TRACEVAULT].iter().find_map(|name| {
38        command
39            .strip_prefix(name)
40            .filter(|rest| rest.starts_with(' '))
41            .map(str::trim_start)
42    })
43}
44
45/// Whether `command` is one of ours and names the `visdom` binary.
46pub fn is_visdom_command(command: &str) -> bool {
47    command
48        .strip_prefix(VISDOM_TRACE)
49        .is_some_and(|rest| rest.starts_with(' '))
50}
51
52/// Whether what is being installed should call `visdom`: this is the `visdom`
53/// binary, or what is already there (`existing_is_visdom`) does.
54pub fn installs_visdom(existing_is_visdom: bool) -> bool {
55    is_visdom() || existing_is_visdom
56}
57
58/// The command name to install.
59pub fn name(visdom: bool) -> &'static str {
60    if visdom {
61        VISDOM_TRACE
62    } else {
63        TRACEVAULT
64    }
65}
66
67/// `command` (one of ours, under either name) spelled for the binary chosen
68/// by `visdom`. Anything else comes back unchanged.
69pub fn spelled(command: &str, visdom: bool) -> String {
70    match subcommand(command) {
71        Some(rest) => format!("{} {rest}", name(visdom)),
72        None => command.to_string(),
73    }
74}
75
76/// The command name in a message, for the running binary: `{CLI} repo
77/// switch` reads `tracevault repo switch` or `visdom trace repo switch`.
78pub struct Cli;
79/// See [`Cli`].
80pub const CLI: Cli = Cli;
81
82impl std::fmt::Display for Cli {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.write_str(name(is_visdom()))
85    }
86}
87
88/// The binary's own name in a message, for the commands `visdom` has at its
89/// top level and for message prefixes: `{TOP} login`, `{TOP}: warning: …`.
90pub struct Top;
91/// See [`Top`].
92pub const TOP: Top = Top;
93
94impl std::fmt::Display for Top {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.write_str(if is_visdom() { "visdom" } else { TRACEVAULT })
97    }
98}
99
100/// The prefix of the environment variables in a message: `{ENV}_API_KEY`
101/// reads `TRACEVAULT_API_KEY` or `VISDOM_API_KEY` (which `visdom` accepts
102/// for it).
103pub struct Env;
104/// See [`Env`].
105pub const ENV: Env = Env;
106
107impl std::fmt::Display for Env {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.write_str(if is_visdom() { "VISDOM" } else { "TRACEVAULT" })
110    }
111}
112
113/// `text` — a message written with `tracevault …` commands and
114/// `TRACEVAULT_…` variables — as the running binary says it. For messages
115/// that are not format strings; those use [`CLI`], [`TOP`] and [`ENV`].
116pub fn say(text: &str) -> String {
117    say_as(text, is_visdom())
118}
119
120fn say_as(text: &str, visdom: bool) -> String {
121    if !visdom {
122        return text.to_string();
123    }
124    let mut out = String::with_capacity(text.len() + 16);
125    let mut rest = text;
126    while let Some(at) = rest.find(TRACEVAULT) {
127        let (before, from) = rest.split_at(at);
128        out.push_str(before);
129        let after = &from[TRACEVAULT.len()..];
130        let word_start = !before
131            .chars()
132            .next_back()
133            .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '-' || c == '.' || c == '/');
134        let sub: String = after
135            .strip_prefix(' ')
136            .map(|a| {
137                a.chars()
138                    .take_while(|c| c.is_ascii_lowercase() || *c == '-')
139                    .collect()
140            })
141            .unwrap_or_default();
142        if word_start && ["login", "logout", "init"].contains(&sub.as_str()) {
143            out.push_str("visdom");
144        } else if word_start && (!sub.is_empty() || after.starts_with(": ")) {
145            out.push_str(if sub.is_empty() {
146                "visdom"
147            } else {
148                VISDOM_TRACE
149            });
150        } else {
151            out.push_str(TRACEVAULT);
152        }
153        rest = after;
154    }
155    out.push_str(rest);
156    out.replace("TRACEVAULT_", "VISDOM_")
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn our_commands_are_recognised_under_either_name() {
165        assert_eq!(
166            subcommand("tracevault stream --event stop"),
167            Some("stream --event stop")
168        );
169        assert_eq!(
170            subcommand("visdom trace stream --event stop"),
171            Some("stream --event stop")
172        );
173        assert_eq!(subcommand("tracevaultx stream"), None);
174        assert_eq!(subcommand("visdom doctor"), None);
175        assert_eq!(subcommand("visdom tracer stream"), None);
176        assert_eq!(subcommand("echo tracevault stream"), None);
177        assert!(is_visdom_command("visdom trace user-prompt"));
178        assert!(!is_visdom_command("tracevault user-prompt"));
179    }
180
181    #[test]
182    fn a_command_is_spelled_for_the_chosen_binary() {
183        assert_eq!(
184            spelled("tracevault session-start", true),
185            "visdom trace session-start"
186        );
187        assert_eq!(
188            spelled("visdom trace session-start", false),
189            "tracevault session-start"
190        );
191        assert_eq!(
192            spelled("visdom trace session-start", true),
193            "visdom trace session-start"
194        );
195        assert_eq!(spelled("my-own-hook --flag", true), "my-own-hook --flag");
196    }
197
198    #[test]
199    fn a_message_is_said_with_the_running_binarys_names() {
200        let text = "tracevault: no login. Set TRACEVAULT_API_KEY or run `tracevault login`, \
201                    then `tracevault repo switch <path>` (see .tracevault/ and my-tracevault tool)";
202        assert_eq!(say_as(text, false), text);
203        assert_eq!(
204            say_as(text, true),
205            "visdom: no login. Set VISDOM_API_KEY or run `visdom login`, \
206             then `visdom trace repo switch <path>` (see .tracevault/ and my-tracevault tool)"
207        );
208        assert_eq!(
209            say_as("run 'tracevault init' first", true),
210            "run 'visdom init' first"
211        );
212        assert_eq!(
213            format!("`{CLI} sync`, `{TOP} login`, {ENV}_PROJECT"),
214            "`tracevault sync`, `tracevault login`, TRACEVAULT_PROJECT"
215        );
216    }
217}