zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The `:` command bar: real zc words, parsed here and never handed to a
//! shell. Native commands act inside the session; the zc verbs in
//! [`EXTERNAL`] run outside it, with the terminal, like vim's `:!`.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabName {
    Mesh,
    Account,
    Share,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    Price(f64),
    Workers(u32),
    Share(bool),
    Refresh,
    Copy(String),
    Quit,
    Tab(TabName),
    /// A zc verb and its arguments, run as `zc <args…>` outside the session.
    External(Vec<String>),
}

/// Commands the session runs itself.
pub const NATIVE: &[&str] = &[
    "account", "copy", "mesh", "price", "quit", "refresh", "share", "workers",
];

/// zc verbs that may prompt, need sudo or print progress: run with the
/// terminal handed back. Anything not here or in [`NATIVE`] is refused.
pub const EXTERNAL: &[&str] = &[
    "balance",
    "brokers",
    "connect",
    "deployments",
    "disconnect",
    "down",
    "info",
    "init",
    "join",
    "login",
    "me",
    "status",
    "token",
    "up",
    "update",
    "whoami",
];

/// Parse one line. `Err("")` for a blank line (nothing to say); any other
/// `Err` is a message for the user.
pub fn parse(line: &str) -> Result<Command, String> {
    let words: Vec<&str> = line.split_whitespace().collect();
    let Some(&verb) = words.first() else {
        return Err(String::new());
    };
    // A word that is not plain zc vocabulary is refused before anything
    // else looks at it, so `connect; rm x` never reaches a process.
    if words.iter().any(|w| {
        w.chars()
            .any(|c| matches!(c, ';' | '|' | '&' | '`' | '$' | '>' | '<'))
    }) {
        return Err(format!("unknown command `{verb}` — ? lists them"));
    }
    let arg = words.get(1).copied();
    match verb {
        "price" => match arg.and_then(|a| a.parse::<f64>().ok()) {
            Some(p) if p > 0.0 && words.len() == 2 => Ok(Command::Price(p)),
            _ => Err("usage: price <yen per hour>".into()),
        },
        "workers" => match arg.and_then(|a| a.parse::<u32>().ok()) {
            Some(n) if words.len() == 2 => Ok(Command::Workers(n)),
            _ => Err("usage: workers <count>".into()),
        },
        "share" => match arg {
            None => Ok(Command::Tab(TabName::Share)),
            Some("on") => Ok(Command::Share(true)),
            Some("off") => Ok(Command::Share(false)),
            Some(_) => Err("usage: share [on|off]".into()),
        },
        "mesh" => Ok(Command::Tab(TabName::Mesh)),
        "account" => Ok(Command::Tab(TabName::Account)),
        "refresh" | "r" => Ok(Command::Refresh),
        "quit" | "q" => Ok(Command::Quit),
        "copy" => match arg {
            Some(a) => Ok(Command::Copy(a.to_string())),
            None => Err("usage: copy <zc://…>".into()),
        },
        v if EXTERNAL.contains(&v) => Ok(Command::External(
            words.iter().map(|w| w.to_string()).collect(),
        )),
        other => Err(format!("unknown command `{other}` — ? lists them")),
    }
}

/// What completion can offer besides the vocabulary.
#[derive(Debug, Clone, Default)]
pub struct Completions {
    /// `zc://node-…` addresses on the mesh.
    pub addresses: Vec<String>,
}

/// Full-line candidates for `line`, sorted.
pub fn complete(line: &str, c: &Completions) -> Vec<String> {
    let mut out: Vec<String> = match line.split_once(' ') {
        None => NATIVE
            .iter()
            .chain(EXTERNAL)
            .filter(|w| w.starts_with(line))
            .map(|w| w.to_string())
            .collect(),
        Some((verb, rest)) => {
            let options: Vec<String> = match verb {
                "share" => vec!["on".into(), "off".into()],
                "copy" => c.addresses.clone(),
                _ => vec![],
            };
            options
                .into_iter()
                .filter(|o| o.starts_with(rest.trim_start()))
                .map(|o| format!("{verb} {o}"))
                .collect()
        }
    };
    out.sort();
    out.dedup();
    out
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct CommandBar {
    pub input: String,
    /// Position in the history while walking it with ↑/↓.
    pub hist_idx: Option<usize>,
    /// The candidates the last Tab found, shown in the footer.
    pub matches: Vec<String>,
}

impl CommandBar {
    pub fn new() -> Self {
        Self::default()
    }

    /// One match: take it (and a space, ready for the next word). Several:
    /// extend to their common prefix and list them.
    pub fn tab(&mut self, c: &Completions) {
        let found = complete(&self.input, c);
        match found.len() {
            0 => self.matches.clear(),
            1 => {
                self.input = format!("{} ", found[0]);
                self.matches.clear();
            }
            _ => {
                let mut prefix = found[0].clone();
                for f in &found[1..] {
                    while !f.starts_with(&prefix) {
                        prefix.pop();
                    }
                }
                if prefix.len() > self.input.len() {
                    self.input = prefix;
                }
                self.matches = found;
            }
        }
    }

    pub fn history_up(&mut self, history: &[String]) {
        if history.is_empty() {
            return;
        }
        let i = match self.hist_idx {
            None => history.len() - 1,
            Some(i) => i.saturating_sub(1),
        };
        self.hist_idx = Some(i);
        self.input = history[i].clone();
    }

    pub fn history_down(&mut self, history: &[String]) {
        match self.hist_idx {
            Some(i) if i + 1 < history.len() => {
                self.hist_idx = Some(i + 1);
                self.input = history[i + 1].clone();
            }
            _ => {
                self.hist_idx = None;
                self.input.clear();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn native_commands_parse_with_their_arguments() {
        assert_eq!(parse("price 22"), Ok(Command::Price(22.0)));
        assert_eq!(parse("  workers 3 "), Ok(Command::Workers(3)));
        assert_eq!(parse("share on"), Ok(Command::Share(true)));
        assert_eq!(parse("share off"), Ok(Command::Share(false)));
        assert_eq!(parse("share"), Ok(Command::Tab(TabName::Share)));
        assert_eq!(parse("mesh"), Ok(Command::Tab(TabName::Mesh)));
        assert_eq!(parse("refresh"), Ok(Command::Refresh));
        assert_eq!(parse("q"), Ok(Command::Quit));
        assert_eq!(
            parse("copy zc://node-ab"),
            Ok(Command::Copy("zc://node-ab".into()))
        );
    }

    #[test]
    fn bad_arguments_say_how_to_use_the_command() {
        assert!(parse("price").unwrap_err().contains("usage: price"));
        assert!(parse("price -1").unwrap_err().contains("usage: price"));
        assert!(parse("workers many")
            .unwrap_err()
            .contains("usage: workers"));
        assert!(parse("share maybe").unwrap_err().contains("usage: share"));
    }

    #[test]
    fn known_zc_verbs_run_outside_the_session() {
        assert_eq!(
            parse("connect --native"),
            Ok(Command::External(vec!["connect".into(), "--native".into()]))
        );
        assert_eq!(
            parse("update"),
            Ok(Command::External(vec!["update".into()]))
        );
    }

    #[test]
    fn unknown_and_shellish_input_is_rejected() {
        assert!(parse("rm -rf /")
            .unwrap_err()
            .contains("unknown command `rm`"));
        assert!(parse("; ls").unwrap_err().contains("unknown command"));
        assert!(parse("connect; rm x")
            .unwrap_err()
            .contains("unknown command"));
        assert_eq!(parse("   "), Err(String::new()));
    }

    #[test]
    fn completion_offers_commands_then_arguments() {
        let c = Completions {
            addresses: vec!["zc://node-aaaa".into(), "zc://node-abcd".into()],
        };
        assert_eq!(complete("pr", &c), vec!["price".to_string()]);
        assert!(complete("", &c).len() > 5);
        assert_eq!(
            complete("share o", &c),
            vec!["share off".to_string(), "share on".to_string()]
        );
        assert_eq!(
            complete("copy zc://node-ab", &c),
            vec!["copy zc://node-abcd".to_string()]
        );
    }

    #[test]
    fn tab_fills_a_single_match_or_the_common_prefix() {
        let c = Completions { addresses: vec![] };
        let mut bar = CommandBar::new();
        bar.input = "ref".into();
        bar.tab(&c);
        assert_eq!(bar.input, "refresh ");
        bar.input = "di".into();
        bar.tab(&c);
        assert_eq!(bar.input, "disconnect ");
        bar.input = "d".into();
        bar.tab(&c);
        assert_eq!(bar.input, "d"); // deployments, disconnect, down: no common prefix
        assert!(bar.matches.len() >= 3);
    }

    #[test]
    fn history_walks_back_and_forward() {
        let h = vec!["price 18".to_string(), "workers 2".to_string()];
        let mut bar = CommandBar::new();
        bar.history_up(&h);
        assert_eq!(bar.input, "workers 2");
        bar.history_up(&h);
        assert_eq!(bar.input, "price 18");
        bar.history_up(&h);
        assert_eq!(bar.input, "price 18");
        bar.history_down(&h);
        assert_eq!(bar.input, "workers 2");
        bar.history_down(&h);
        assert_eq!(bar.input, "");
    }
}