cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! Interactive prompts: confirmation, free text, hidden password, and single
//! selection. Zero dependencies — password entry toggles the terminal echo via
//! raw `termios` on unix. Every prompt errors cleanly when stdin is not a
//! terminal, so scripts fail loudly instead of hanging.

use crate::error::{Error, Result};
use crate::style as s;
use std::io::{self, BufRead, Write};

/// Whether stdin is a terminal; prompts require this.
pub fn is_interactive() -> bool {
    #[cfg(unix)]
    {
        extern "C" {
            fn isatty(fd: i32) -> i32;
        }
        unsafe { isatty(0) == 1 }
    }
    #[cfg(not(unix))]
    {
        true
    }
}

fn require_tty() -> Result<()> {
    if !is_interactive() {
        return Err(Error::usage(
            "this action needs an interactive terminal (stdin is not a tty)",
        )
        .note("pass the value as a flag/argument, or run without piping stdin"));
    }
    Ok(())
}

/// Ask a yes/no question. `default` is used when the user just presses Enter.
pub fn confirm(question: &str, default: bool) -> Result<bool> {
    require_tty()?;
    let hint = if default { "[Y/n]" } else { "[y/N]" };
    loop {
        print!("{} {} ", question, s::dim(hint));
        io::stdout().flush().ok();
        let line = read_line()?;
        let ans = line.trim().to_lowercase();
        match ans.as_str() {
            "" => return Ok(default),
            "y" | "yes" => return Ok(true),
            "n" | "no" => return Ok(false),
            _ => {
                eprintln!("{}", s::dim("please answer y or n"));
            }
        }
    }
}

/// Prompt for a line of free text. If `default` is given, an empty response
/// returns it.
pub fn text(prompt: &str, default: Option<&str>) -> Result<String> {
    require_tty()?;
    match default {
        Some(d) => print!("{} {} ", prompt, s::dim(format!("({})", d))),
        None => print!("{} ", prompt),
    }
    io::stdout().flush().ok();
    let line = read_line()?;
    let trimmed = line.trim_end_matches(['\n', '\r']);
    if trimmed.is_empty() {
        if let Some(d) = default {
            return Ok(d.to_string());
        }
    }
    Ok(trimmed.to_string())
}

/// Prompt for a hidden password (no echo). Falls back to visible input on
/// platforms where echo can't be toggled.
pub fn password(prompt: &str) -> Result<String> {
    require_tty()?;
    print!("{} ", prompt);
    io::stdout().flush().ok();
    let pw = read_hidden()?;
    println!();
    Ok(pw)
}

/// Present a numbered list and return the chosen index. Re-asks on invalid input.
pub fn select(prompt: &str, options: &[&str]) -> Result<usize> {
    require_tty()?;
    if options.is_empty() {
        return Err(Error::msg("select called with no options"));
    }
    println!("{}", prompt);
    for (i, opt) in options.iter().enumerate() {
        println!("  {} {}", s::cyan(format!("{})", i + 1)), opt);
    }
    loop {
        print!("{} ", s::dim(format!("choose 1-{}:", options.len())));
        io::stdout().flush().ok();
        let line = read_line()?;
        match line.trim().parse::<usize>() {
            Ok(n) if n >= 1 && n <= options.len() => return Ok(n - 1),
            _ => eprintln!("{}", s::dim("invalid choice")),
        }
    }
}

fn read_line() -> Result<String> {
    let mut line = String::new();
    let stdin = io::stdin();
    let n = stdin.lock().read_line(&mut line).map_err(Error::wrap)?;
    if n == 0 {
        // EOF (e.g. Ctrl-D) — treat as cancellation.
        return Err(Error::cancelled("input cancelled (EOF)"));
    }
    Ok(line)
}

#[cfg(unix)]
fn read_hidden() -> Result<String> {
    // Toggle off terminal echo via termios, read a line, restore.
    use std::os::unix::io::AsRawFd;

    #[repr(C)]
    #[derive(Clone)]
    struct Termios {
        c_iflag: u32,
        c_oflag: u32,
        c_cflag: u32,
        c_lflag: u32,
        c_line: u8,
        c_cc: [u8; 32],
        c_ispeed: u32,
        c_ospeed: u32,
    }
    extern "C" {
        fn tcgetattr(fd: i32, termios: *mut Termios) -> i32;
        fn tcsetattr(fd: i32, optional_actions: i32, termios: *const Termios) -> i32;
    }
    const ECHO: u32 = 0o0000010;
    const TCSANOW: i32 = 0;

    let fd = io::stdin().as_raw_fd();
    let mut term = Termios {
        c_iflag: 0,
        c_oflag: 0,
        c_cflag: 0,
        c_lflag: 0,
        c_line: 0,
        c_cc: [0; 32],
        c_ispeed: 0,
        c_ospeed: 0,
    };
    unsafe {
        if tcgetattr(fd, &mut term) != 0 {
            // Can't query the terminal; fall back to visible input.
            return read_line().map(|l| l.trim_end_matches(['\n', '\r']).to_string());
        }
    }
    let saved = term.clone();
    term.c_lflag &= !ECHO;
    unsafe {
        tcsetattr(fd, TCSANOW, &term);
    }
    let result = read_line().map(|l| l.trim_end_matches(['\n', '\r']).to_string());
    unsafe {
        tcsetattr(fd, TCSANOW, &saved);
    }
    result
}

#[cfg(not(unix))]
fn read_hidden() -> Result<String> {
    // No portable echo toggle here; read visibly.
    read_line().map(|l| l.trim_end_matches(['\n', '\r']).to_string())
}

/// Prompt for a number within an optional inclusive range, re-asking on invalid
/// input. Returns the parsed value.
pub fn number(prompt: &str, min: Option<i64>, max: Option<i64>) -> Result<i64> {
    require_tty()?;
    loop {
        let mut hint = String::new();
        match (min, max) {
            (Some(lo), Some(hi)) => hint = format!("({}-{})", lo, hi),
            (Some(lo), None) => hint = format!("(>= {})", lo),
            (None, Some(hi)) => hint = format!("(<= {})", hi),
            (None, None) => {}
        }
        if hint.is_empty() {
            print!("{} ", prompt);
        } else {
            print!("{} {} ", prompt, s::dim(&hint));
        }
        io::stdout().flush().ok();
        let line = read_line()?;
        match line.trim().parse::<i64>() {
            Ok(n) => {
                if let Some(lo) = min {
                    if n < lo {
                        eprintln!("{}", s::dim("too small"));
                        continue;
                    }
                }
                if let Some(hi) = max {
                    if n > hi {
                        eprintln!("{}", s::dim("too large"));
                        continue;
                    }
                }
                return Ok(n);
            }
            Err(_) => eprintln!("{}", s::dim("please enter a number")),
        }
    }
}

/// Present a checkbox-style multiple selection. The user enters a comma- or
/// space-separated list of numbers; returns the chosen indices. An empty
/// response returns an empty vec.
pub fn multiselect(prompt: &str, options: &[&str]) -> Result<Vec<usize>> {
    require_tty()?;
    if options.is_empty() {
        return Err(Error::msg("multiselect called with no options"));
    }
    println!("{}", prompt);
    for (i, opt) in options.iter().enumerate() {
        println!("  {} {}", s::cyan(format!("{})", i + 1)), opt);
    }
    loop {
        print!(
            "{} ",
            s::dim(format!("choose 1-{} (comma/space separated):", options.len()))
        );
        io::stdout().flush().ok();
        let line = read_line()?;
        let trimmed = line.trim();
        if trimmed.is_empty() {
            return Ok(Vec::new());
        }
        let parts: Vec<&str> = trimmed
            .split(|c: char| c == ',' || c.is_whitespace())
            .filter(|s| !s.is_empty())
            .collect();
        let mut chosen = Vec::new();
        let mut ok = true;
        for p in parts {
            match p.parse::<usize>() {
                Ok(n) if n >= 1 && n <= options.len() => chosen.push(n - 1),
                _ => {
                    ok = false;
                    break;
                }
            }
        }
        if ok {
            chosen.sort_unstable();
            chosen.dedup();
            return Ok(chosen);
        }
        eprintln!("{}", s::dim("invalid selection"));
    }
}