Skip to main content

hashiverse_cli/
repl.rs

1//! Interactive prompt, used when `hashiverse-cli` is run without a command.
2//!
3//! Each line is split into words (see [`split_repl_words`]) and is either a REPL-only command (`help`, `quit`/`exit`,
4//! `login <client_id_hex>`) or one of the regular [`Command`]s, parsed by the same clap
5//! definitions as the one-shot CLI. The identity and network connection persist across lines,
6//! so repeating `user X` / `hashtag Y` walks further back in that timeline.
7//!
8//! The loop is generic over [`ReplSession`] so it can be tested without a network.
9
10use std::io::Write;
11
12use anyhow::{anyhow, Result};
13use clap::{CommandFactory, Parser};
14use hashiverse_client_rust::Hashiverse;
15use tokio::io::{AsyncBufRead, AsyncBufReadExt};
16
17use crate::cli_args::{CliArgs, Command, ENV_PASSWORD};
18use crate::commands::run_command;
19use crate::unlock::{is_guest, resolve_unlock_method, unlock};
20
21/// What a single REPL line looks like to clap: a [`Command`] plus a per-line `--json`.
22#[derive(Parser, Debug)]
23#[command(name = "", no_binary_name = true, disable_help_subcommand = true, disable_version_flag = true)]
24struct ReplCommandLine {
25    /// Emit machine-readable JSON instead of text.
26    #[arg(long, global = true)]
27    json: bool,
28
29    #[command(subcommand)]
30    command: Command,
31}
32
33#[derive(Debug, PartialEq, Eq)]
34pub enum ReplLine {
35    Empty,
36    Help,
37    Quit,
38    Login { client_id_hex: String },
39    Command { command: Command, json: bool },
40}
41
42/// Splits a line into words, shell-style: whitespace separates words, `"..."` and `'...'` group
43/// them, and a backslash escapes the next character (outside single quotes). Unlike a real
44/// shell there is no comment syntax, so `#hashtag` is an ordinary word.
45pub fn split_repl_words(line: &str) -> std::result::Result<Vec<String>, String> {
46    let mut words = Vec::new();
47    let mut current_word = String::new();
48    let mut in_word = false;
49    let mut characters = line.chars();
50
51    while let Some(character) = characters.next() {
52        match character {
53            character if character.is_whitespace() => {
54                if in_word {
55                    words.push(std::mem::take(&mut current_word));
56                    in_word = false;
57                }
58            }
59            '\\' => {
60                current_word.push(characters.next().ok_or("trailing backslash")?);
61                in_word = true;
62            }
63            '\'' => {
64                in_word = true;
65                loop {
66                    match characters.next() {
67                        Some('\'') => break,
68                        Some(quoted_character) => current_word.push(quoted_character),
69                        None => return Err("unterminated single quote".to_string()),
70                    }
71                }
72            }
73            '"' => {
74                in_word = true;
75                loop {
76                    match characters.next() {
77                        Some('"') => break,
78                        Some('\\') => current_word.push(characters.next().ok_or("unterminated double quote")?),
79                        Some(quoted_character) => current_word.push(quoted_character),
80                        None => return Err("unterminated double quote".to_string()),
81                    }
82                }
83            }
84            character => {
85                current_word.push(character);
86                in_word = true;
87            }
88        }
89    }
90    if in_word {
91        words.push(current_word);
92    }
93    Ok(words)
94}
95
96/// Parses one line. `Err` carries a message ready to show the user (including clap's usage
97/// text, or a command's `--help` output).
98pub fn parse_repl_line(line: &str) -> std::result::Result<ReplLine, String> {
99    let words = split_repl_words(line).map_err(|error| format!("could not parse line: {}", error))?;
100    let Some(first_word) = words.first() else {
101        return Ok(ReplLine::Empty);
102    };
103
104    match first_word.as_str() {
105        "help" => Ok(ReplLine::Help),
106        "quit" | "exit" => Ok(ReplLine::Quit),
107        "login" => match words.as_slice() {
108            [_, client_id_hex] => Ok(ReplLine::Login { client_id_hex: client_id_hex.trim().to_string() }),
109            _ => Err("usage: login <client_id_hex>".to_string()),
110        },
111        _ => ReplCommandLine::try_parse_from(&words)
112            .map(|repl_command_line| ReplLine::Command { command: repl_command_line.command, json: repl_command_line.json })
113            .map_err(|error| error.render().to_string()),
114    }
115}
116
117/// The list shown by `help`, built from the clap definitions so it never drifts from them.
118pub fn help_text() -> String {
119    let mut text = String::from("Commands:\n");
120    for subcommand in ReplCommandLine::command().get_subcommands() {
121        let about = subcommand.get_about().map(|about| about.to_string()).unwrap_or_default();
122        text.push_str(&format!("  {:<10} {}\n", subcommand.get_name(), about));
123    }
124    text.push_str(&format!("  {:<10} {}\n", "login", "Switch to a stored profile: login <client_id_hex> (uses HASHIVERSE_PASSWORD)"));
125    text.push_str(&format!("  {:<10} {}\n", "help", "Show this list"));
126    text.push_str(&format!("  {:<10} {}\n", "quit", "Leave (also: exit, or end-of-input)"));
127    text.push_str("\nUse <command> --help for a command's options; add --json to any command for JSON output.");
128    text
129}
130
131pub fn format_prompt(guest: bool, client_id_hex: &str) -> String {
132    if guest {
133        "guest> ".to_string()
134    } else {
135        format!("{}> ", &client_id_hex[..client_id_hex.len().min(8)])
136    }
137}
138
139/// The state the REPL drives: the current identity and how to run commands against it.
140#[allow(async_fn_in_trait)]
141pub trait ReplSession {
142    fn prompt(&self) -> String;
143    async fn run_command(&mut self, command: &Command, json: bool) -> Result<String>;
144    /// Switches identity. On failure the current identity must be kept.
145    async fn login(&mut self, client_id_hex: &str) -> Result<String>;
146}
147
148pub struct LiveReplSession<'a> {
149    cli_args: &'a CliArgs,
150    password_env: Option<String>,
151    hashiverse: Hashiverse,
152}
153
154impl<'a> LiveReplSession<'a> {
155    pub fn new(cli_args: &'a CliArgs, password_env: Option<String>, hashiverse: Hashiverse) -> Self {
156        Self { cli_args, password_env, hashiverse }
157    }
158}
159
160impl ReplSession for LiveReplSession<'_> {
161    fn prompt(&self) -> String {
162        format_prompt(is_guest(&self.hashiverse), &self.hashiverse.client_id().id_hex())
163    }
164
165    async fn run_command(&mut self, command: &Command, json: bool) -> Result<String> {
166        run_command(&self.hashiverse, command, json).await
167    }
168
169    async fn login(&mut self, client_id_hex: &str) -> Result<String> {
170        if self.password_env.is_none() {
171            return Err(anyhow!("login needs {} in the environment (it may be empty)", ENV_PASSWORD));
172        }
173        let unlock_method = resolve_unlock_method(Some(client_id_hex.to_string()), None, self.password_env.clone())?;
174        // Only replace the current client once the new one is fully built.
175        let hashiverse = unlock(self.cli_args, unlock_method).await?;
176        let message = format!("logged in as {}", hashiverse.client_id().id_hex());
177        self.hashiverse = hashiverse;
178        Ok(message)
179    }
180}
181
182/// Where non-data output (prompts, help, login status) goes: `output` normally, but
183/// `error_output` in a `--json` session so that `output` carries nothing but JSON.
184fn chatter_output<'a>(session_json: bool, output: &'a mut dyn Write, error_output: &'a mut dyn Write) -> &'a mut dyn Write {
185    if session_json { error_output } else { output }
186}
187
188/// Runs the prompt loop until `quit`/`exit` or end of input. Command output goes to `output`,
189/// errors to `error_output`; a failing line never ends the loop. In a `--json` session
190/// (`session_json`) prompts, help and login status also go to `error_output`, keeping `output`
191/// JSON-only. A per-line `--json` only changes that command's output.
192pub async fn run_repl<TReplSession: ReplSession, TInput: AsyncBufRead + Unpin>(
193    repl_session: &mut TReplSession,
194    input: TInput,
195    output: &mut impl Write,
196    error_output: &mut impl Write,
197    session_json: bool,
198    show_prompt: bool,
199) -> Result<()> {
200    let mut lines = input.lines();
201    loop {
202        if show_prompt {
203            let chatter = chatter_output(session_json, output, error_output);
204            write!(chatter, "{}", repl_session.prompt())?;
205            chatter.flush()?;
206        }
207
208        let Some(line) = lines.next_line().await? else {
209            if show_prompt {
210                writeln!(chatter_output(session_json, output, error_output))?;
211            }
212            break;
213        };
214
215        match parse_repl_line(&line) {
216            Ok(ReplLine::Empty) => {}
217            Ok(ReplLine::Help) => writeln!(chatter_output(session_json, output, error_output), "{}", help_text())?,
218            Ok(ReplLine::Quit) => break,
219            Ok(ReplLine::Login { client_id_hex }) => match repl_session.login(&client_id_hex).await {
220                Ok(message) => writeln!(chatter_output(session_json, output, error_output), "{}", message)?,
221                Err(error) => writeln!(error_output, "error: {:#}", error)?,
222            },
223            Ok(ReplLine::Command { command, json }) => match repl_session.run_command(&command, json || session_json).await {
224                Ok(command_output) => writeln!(output, "{}", command_output)?,
225                Err(error) => writeln!(error_output, "error: {:#}", error)?,
226            },
227            Err(message) => writeln!(error_output, "{}", message.trim_end())?,
228        }
229    }
230    Ok(())
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236    use crate::cli_args::DEFAULT_TRENDING_LIMIT;
237    use std::io::Cursor;
238
239    fn words(values: &[&str]) -> Vec<String> {
240        values.iter().map(|value| value.to_string()).collect()
241    }
242
243    #[test]
244    fn split_plain_words_and_hashtags() {
245        assert_eq!(split_repl_words("  post hello  #rust @abc "), Ok(words(&["post", "hello", "#rust", "@abc"])));
246    }
247
248    #[test]
249    fn split_quotes_and_escapes() {
250        assert_eq!(split_repl_words("post \"a  b\" 'c \\ d' e\\ f"), Ok(words(&["post", "a  b", "c \\ d", "e f"])));
251        assert_eq!(split_repl_words("post \"say \\\"hi\\\"\""), Ok(words(&["post", "say \"hi\""])));
252        assert_eq!(split_repl_words("post \"\""), Ok(words(&["post", ""])));
253        assert_eq!(split_repl_words("ab\"c d\"e"), Ok(words(&["abc de"])));
254    }
255
256    #[test]
257    fn split_errors() {
258        assert!(split_repl_words("post \"open").is_err());
259        assert!(split_repl_words("post 'open").is_err());
260        assert!(split_repl_words("post trailing\\").is_err());
261    }
262
263    #[test]
264    fn parse_empty_and_whitespace() {
265        assert_eq!(parse_repl_line(""), Ok(ReplLine::Empty));
266        assert_eq!(parse_repl_line("   "), Ok(ReplLine::Empty));
267    }
268
269    #[test]
270    fn parse_repl_only_commands() {
271        assert_eq!(parse_repl_line("help"), Ok(ReplLine::Help));
272        assert_eq!(parse_repl_line("quit"), Ok(ReplLine::Quit));
273        assert_eq!(parse_repl_line("exit"), Ok(ReplLine::Quit));
274        assert_eq!(parse_repl_line("login abcd"), Ok(ReplLine::Login { client_id_hex: "abcd".to_string() }));
275    }
276
277    #[test]
278    fn parse_login_needs_exactly_one_id() {
279        assert!(parse_repl_line("login").unwrap_err().contains("usage: login"));
280        assert!(parse_repl_line("login a b").unwrap_err().contains("usage: login"));
281    }
282
283    #[test]
284    fn parse_regular_commands() {
285        assert_eq!(parse_repl_line("trending"), Ok(ReplLine::Command { command: Command::Trending { limit: DEFAULT_TRENDING_LIMIT }, json: false }));
286        assert_eq!(parse_repl_line("hashtag #rust --pages 2 --json"), Ok(ReplLine::Command { command: Command::Hashtag { hashtag: "#rust".to_string(), pages: 2 }, json: true }));
287    }
288
289    #[test]
290    fn parse_post_with_quotes_and_bare_words() {
291        assert_eq!(parse_repl_line("post \"hello   world\" #rust"), Ok(ReplLine::Command { command: Command::Post { text: vec!["hello   world".to_string(), "#rust".to_string()] }, json: false }));
292    }
293
294    #[test]
295    fn parse_errors_are_messages() {
296        assert!(parse_repl_line("frobnicate").is_err());
297        assert!(parse_repl_line("post").is_err());
298        assert!(parse_repl_line("post \"unterminated").unwrap_err().contains("could not parse line"));
299        assert!(parse_repl_line("user abcd --help").unwrap_err().contains("--pages"));
300    }
301
302    #[test]
303    fn help_lists_every_command() {
304        let text = help_text();
305        for command_name in ["post", "user", "hashtag", "trending", "login", "help", "quit"] {
306            assert!(text.contains(&format!("  {}", command_name)), "help missing {}: {}", command_name, text);
307        }
308    }
309
310    #[test]
311    fn prompts() {
312        assert_eq!(format_prompt(true, "fe050cc21479"), "guest> ");
313        assert_eq!(format_prompt(false, "04bfbfacadd0b89c"), "04bfbfac> ");
314    }
315
316    struct FakeReplSession {
317        client_id_hex: Option<String>,
318        commands_run: Vec<(Command, bool)>,
319    }
320
321    impl ReplSession for FakeReplSession {
322        fn prompt(&self) -> String {
323            match &self.client_id_hex {
324                Some(client_id_hex) => format_prompt(false, client_id_hex),
325                None => format_prompt(true, ""),
326            }
327        }
328
329        async fn run_command(&mut self, command: &Command, json: bool) -> Result<String> {
330            self.commands_run.push((command.clone(), json));
331            match command {
332                Command::Post { .. } if self.client_id_hex.is_none() => Err(anyhow!("posting requires an identity")),
333                _ => Ok(format!("ran {:?}", command)),
334            }
335        }
336
337        async fn login(&mut self, client_id_hex: &str) -> Result<String> {
338            if client_id_hex.starts_with("bad") {
339                return Err(anyhow!("Key file not found for {}", client_id_hex));
340            }
341            self.client_id_hex = Some(client_id_hex.to_string());
342            Ok(format!("logged in as {}", client_id_hex))
343        }
344    }
345
346    async fn run_script(script: &str, session_json: bool, show_prompt: bool) -> (FakeReplSession, String, String) {
347        let mut fake_repl_session = FakeReplSession { client_id_hex: None, commands_run: Vec::new() };
348        let mut output = Vec::new();
349        let mut error_output = Vec::new();
350        run_repl(&mut fake_repl_session, Cursor::new(script.as_bytes().to_vec()), &mut output, &mut error_output, session_json, show_prompt).await.unwrap();
351        (fake_repl_session, String::from_utf8(output).unwrap(), String::from_utf8(error_output).unwrap())
352    }
353
354    #[tokio::test]
355    async fn errors_do_not_end_the_loop() {
356        let (fake_repl_session, output, error_output) = run_script("frobnicate\npost hi\ntrending\n", false, false).await;
357        assert_eq!(fake_repl_session.commands_run.len(), 2, "both post and trending should run");
358        assert!(error_output.contains("posting requires an identity"));
359        assert!(output.contains("ran Trending"));
360    }
361
362    #[tokio::test]
363    async fn login_switches_identity_and_failed_login_keeps_it() {
364        let (fake_repl_session, output, error_output) = run_script("login 04bfbfacadd0\nlogin badbad\npost hi\n", false, true).await;
365        assert_eq!(fake_repl_session.client_id_hex.as_deref(), Some("04bfbfacadd0"));
366        assert!(error_output.contains("Key file not found for badbad"));
367        assert!(output.contains("ran Post"), "post should succeed after login: {}", output);
368        assert!(output.starts_with("guest> logged in as 04bfbfacadd0\n04bfbfac> "), "prompt should follow identity: {:?}", output);
369    }
370
371    #[tokio::test]
372    async fn quit_stops_reading() {
373        let (fake_repl_session, _, _) = run_script("trending\nquit\ntrending\n", false, false).await;
374        assert_eq!(fake_repl_session.commands_run.len(), 1);
375    }
376
377    #[tokio::test]
378    async fn end_of_input_without_trailing_newline() {
379        let (fake_repl_session, _, _) = run_script("trending", false, false).await;
380        assert_eq!(fake_repl_session.commands_run.len(), 1);
381    }
382
383    #[tokio::test]
384    async fn json_comes_from_session_or_line() {
385        let (fake_repl_session, _, _) = run_script("trending\ntrending --json\n", false, false).await;
386        assert_eq!(fake_repl_session.commands_run.iter().map(|(_, json)| *json).collect::<Vec<_>>(), vec![false, true]);
387        let (fake_repl_session, _, _) = run_script("trending\n", true, false).await;
388        assert!(fake_repl_session.commands_run[0].1);
389    }
390
391    #[tokio::test]
392    async fn json_session_keeps_output_json_only() {
393        let (fake_repl_session, output, error_output) = run_script("help\nlogin 04bfbfacadd0\ntrending\n", true, true).await;
394        assert_eq!(fake_repl_session.commands_run.len(), 1);
395        assert_eq!(output, "ran Trending { limit: 20 }\n", "only command output belongs on stdout");
396        assert!(error_output.contains("Commands:"));
397        assert!(error_output.contains("logged in as 04bfbfacadd0"));
398        assert!(error_output.contains("guest> ") && error_output.contains("04bfbfac> "));
399    }
400
401    #[tokio::test]
402    async fn json_flag_before_post_text_is_an_option() {
403        let (fake_repl_session, _, _) = run_script("login 04bfbfacadd0\npost --json hello world\n", false, false).await;
404        assert_eq!(fake_repl_session.commands_run, vec![(Command::Post { text: words(&["hello", "world"]) }, true)]);
405    }
406
407    #[tokio::test]
408    async fn help_and_no_prompt_when_not_interactive() {
409        let (_, output, _) = run_script("help\n", false, false).await;
410        assert!(output.starts_with("Commands:"));
411        assert!(!output.contains("guest> "));
412    }
413}