Skip to main content

visdom_cli/
interactive.rs

1//! Asking for what `visdom init` was not told on the command line. Only ever
2//! used when both stdin and stderr are a terminal; without one, init behaves
3//! as if nothing could be asked and says what to pass instead.
4
5use std::io::{BufRead, IsTerminal, Write};
6use std::path::Path;
7
8use tracevault_cli::agent::Agent;
9
10/// Whether there is somebody to ask.
11pub fn is_interactive() -> bool {
12    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
13}
14
15/// Print `question` and read one line, trimmed. `None` at end of input.
16fn ask_line(question: &str) -> Option<String> {
17    eprint!("{question} ");
18    let _ = std::io::stderr().flush();
19    let mut line = String::new();
20    match std::io::stdin().lock().read_line(&mut line) {
21        Ok(0) | Err(_) => None,
22        Ok(_) => Some(line.trim().to_string()),
23    }
24}
25
26/// The agent an answer names: its number in the list, or its name. An empty
27/// answer takes the default, Claude Code. `None` when it names neither.
28pub fn parse_agent_choice(answer: &str) -> Option<Agent> {
29    match answer.trim().to_ascii_lowercase().as_str() {
30        "" | "1" | "claude" | "claude-code" => Some(Agent::ClaudeCode),
31        "2" | "codex" => Some(Agent::Codex),
32        _ => None,
33    }
34}
35
36/// Ask which agent to set up. End of input takes the default.
37pub fn ask_agent() -> Agent {
38    loop {
39        let Some(answer) = ask_line("Which agent? [1] Claude Code  [2] Codex  (default 1):") else {
40            return Agent::ClaudeCode;
41        };
42        match parse_agent_choice(&answer) {
43            Some(agent) => return agent,
44            None => eprintln!("Answer 1 or 2."),
45        }
46    }
47}
48
49/// What a typed URL answer means.
50#[derive(Debug, PartialEq, Eq)]
51pub enum UrlAnswer {
52    Url(String),
53    /// Nothing typed.
54    Skipped,
55    Invalid,
56}
57
58/// A bare host is taken as https; anything that is then not an absolute
59/// http(s) URL is invalid.
60pub fn parse_url_answer(answer: &str) -> UrlAnswer {
61    let answer = answer.trim();
62    if answer.is_empty() {
63        return UrlAnswer::Skipped;
64    }
65    if answer.starts_with('-') {
66        return UrlAnswer::Invalid;
67    }
68    let candidate = if answer.contains("://") {
69        answer.to_string()
70    } else {
71        format!("https://{answer}")
72    };
73    if crate::components::bazaar::is_http_url(&candidate) {
74        UrlAnswer::Url(candidate.trim_end_matches('/').to_string())
75    } else {
76        UrlAnswer::Invalid
77    }
78}
79
80/// Ask for a URL until one is given or the question is skipped (Enter, or
81/// end of input).
82pub fn ask_url(question: &str) -> Option<String> {
83    loop {
84        match parse_url_answer(&ask_line(question)?) {
85            UrlAnswer::Url(url) => return Some(url),
86            UrlAnswer::Skipped => return None,
87            UrlAnswer::Invalid => eprintln!("That is not an http(s) URL."),
88        }
89    }
90}
91
92/// Record `bazaar_url` in the user config at `path`, creating the file if
93/// needed and leaving everything else in it as it is.
94pub fn save_bazaar_url(path: &Path, url: &str) -> Result<(), String> {
95    let existing = match std::fs::read_to_string(path) {
96        Ok(text) => text,
97        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
98        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
99    };
100    let mut table: toml::Table =
101        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
102    let line = format!("bazaar_url = {}\n", toml::Value::String(url.to_string()));
103    let updated = if table.contains_key("bazaar_url") {
104        // Already there (empty, or it would not have been asked for): the
105        // file is rewritten from its parsed form.
106        table.insert(
107            "bazaar_url".to_string(),
108            toml::Value::String(url.to_string()),
109        );
110        toml::to_string(&table).map_err(|e| e.to_string())?
111    } else {
112        // A top-level key must come before the first table: put it first, and
113        // keep the rest of the file, comments included, byte for byte.
114        format!("{line}{existing}")
115    };
116    if let Some(dir) = path.parent() {
117        std::fs::create_dir_all(dir)
118            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
119    }
120    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::config::load_user_config_in;
127
128    #[test]
129    fn agent_choice_by_number_name_or_default() {
130        assert_eq!(parse_agent_choice(""), Some(Agent::ClaudeCode));
131        assert_eq!(parse_agent_choice("1"), Some(Agent::ClaudeCode));
132        assert_eq!(parse_agent_choice(" Claude-Code "), Some(Agent::ClaudeCode));
133        assert_eq!(parse_agent_choice("2"), Some(Agent::Codex));
134        assert_eq!(parse_agent_choice("codex"), Some(Agent::Codex));
135        assert_eq!(parse_agent_choice("3"), None);
136        assert_eq!(parse_agent_choice("amp"), None);
137    }
138
139    #[test]
140    fn url_answers() {
141        assert_eq!(parse_url_answer("  "), UrlAnswer::Skipped);
142        assert_eq!(
143            parse_url_answer("https://tv.example.com/"),
144            UrlAnswer::Url("https://tv.example.com".to_string())
145        );
146        assert_eq!(
147            parse_url_answer("tv.example.com"),
148            UrlAnswer::Url("https://tv.example.com".to_string())
149        );
150        assert_eq!(
151            parse_url_answer("http://localhost:3000/mcp/remote"),
152            UrlAnswer::Url("http://localhost:3000/mcp/remote".to_string())
153        );
154        for bad in ["ftp://x.example.com", "--flag", "two words", "https://"] {
155            assert_eq!(parse_url_answer(bad), UrlAnswer::Invalid, "{bad}");
156        }
157    }
158
159    #[test]
160    fn bazaar_url_is_saved_into_a_new_file() {
161        let tmp = tempfile::tempdir().unwrap();
162        let path = crate::config::user_config_path_in(tmp.path());
163        save_bazaar_url(&path, "https://ctx.example.com/mcp/remote").unwrap();
164        let user = load_user_config_in(tmp.path()).unwrap();
165        assert_eq!(
166            user.bazaar_url.as_deref(),
167            Some("https://ctx.example.com/mcp/remote")
168        );
169    }
170
171    #[test]
172    fn bazaar_url_is_added_without_touching_the_rest() {
173        let tmp = tempfile::tempdir().unwrap();
174        let path = crate::config::user_config_path_in(tmp.path());
175        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
176        let before = "# my settings\nagent = \"codex\"\n\n[agents]\n# the nightly build\ncodex = \"/opt/codex\"\n";
177        std::fs::write(&path, before).unwrap();
178        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
179        let after = std::fs::read_to_string(&path).unwrap();
180        assert_eq!(
181            after,
182            format!("bazaar_url = \"https://ctx.example.com/mcp\"\n{before}")
183        );
184        let user = load_user_config_in(tmp.path()).unwrap();
185        assert_eq!(user.agent, Some(Agent::Codex));
186        assert_eq!(
187            user.bazaar_url.as_deref(),
188            Some("https://ctx.example.com/mcp")
189        );
190        assert_eq!(
191            user.agents.program_for(Agent::Codex).as_deref(),
192            Some("/opt/codex")
193        );
194    }
195
196    #[test]
197    fn an_empty_bazaar_url_is_replaced() {
198        let tmp = tempfile::tempdir().unwrap();
199        let path = crate::config::user_config_path_in(tmp.path());
200        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
201        std::fs::write(&path, "bazaar_url = \"\"\nagent = \"codex\"\n").unwrap();
202        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
203        let user = load_user_config_in(tmp.path()).unwrap();
204        assert_eq!(
205            user.bazaar_url.as_deref(),
206            Some("https://ctx.example.com/mcp")
207        );
208        assert_eq!(user.agent, Some(Agent::Codex));
209    }
210
211    #[test]
212    fn a_config_that_cannot_be_parsed_is_left_alone() {
213        let tmp = tempfile::tempdir().unwrap();
214        let path = crate::config::user_config_path_in(tmp.path());
215        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
216        std::fs::write(&path, "agent = [broken").unwrap();
217        let err = save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap_err();
218        assert!(err.contains("cannot parse"), "{err}");
219        assert_eq!(std::fs::read_to_string(&path).unwrap(), "agent = [broken");
220    }
221}