Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

1.8 KB
Raw Blame
//! Reads answers for CLI commands: a secret (typed without echo on a terminal, or one line of piped stdin) or a
//! yes or no.

use anyhow::{Result, bail};
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use crossterm::terminal;
use std::io::{BufRead, IsTerminal, Write};

/// One line of secret input, trimmed. Typed keys are never shown.
pub fn read_secret(prompt: &str) -> Result<String> {
    if !std::io::stdin().is_terminal() {
        let mut line = String::new();
        std::io::stdin().lock().read_line(&mut line)?;
        return Ok(line.trim().to_owned());
    }
    eprint!("{prompt}");
    std::io::stderr().flush()?;
    terminal::enable_raw_mode()?;
    let typed = read_keys();
    terminal::disable_raw_mode()?;
    eprintln!();
    typed
}

fn read_keys() -> Result<String> {
    let mut secret = String::new();
    loop {
        let Event::Key(key) = event::read()? else { continue };
        if key.kind != KeyEventKind::Press {
            continue;
        }
        match key.code {
            KeyCode::Enter => return Ok(secret.trim().to_owned()),
            KeyCode::Backspace => {
                secret.pop();
            }
            KeyCode::Esc => bail!("cancelled"),
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => bail!("cancelled"),
            KeyCode::Char(c) => secret.push(c),
            _ => {}
        }
    }
}

/// `true` for `y` or `yes` (any case); anything else is a no.
pub async fn ask_yes_no(prompt: &str) -> Result<bool> {
    print!("{prompt}");
    std::io::stdout().flush()?;
    let line = tokio::task::spawn_blocking(|| {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).map(|_| line)
    })
    .await??;
    Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
}