nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use nlcalc::{Calculator, Context};
use std::io::{self, BufRead};
#[path = "nlcalc/rates.rs"]
mod rates;
fn main() {
    let calc = Calculator::extended();
    let mut context = Context::default();
    let mut rates_attempted = false;
    let mut args: Vec<String> = std::env::args().skip(1).collect();
    let online = args.iter().any(|arg| arg == "--online")
        || std::env::var("NLCALC_ONLINE").is_ok_and(|value| matches!(value.as_str(), "1" | "true"));
    args.retain(|arg| arg != "--online");
    if args
        .iter()
        .any(|arg| matches!(arg.as_str(), "--help" | "-h"))
    {
        println!(
            "nlcalc [--online] [expression]\nNo expression: read one request per stdin line; matching outer quotes may span lines.\nOffline by default. --online enables cached daily ECB fiat rates.\nNLCALC_RATES=/path/to/rates.json supplies offline rates."
        );
        return;
    }
    if std::env::var_os("NLCALC_RATES").is_some() {
        match rates::exchange_rates(false) {
            Ok(rates) => {
                context.rates = rates;
                rates_attempted = true;
            }
            Err(e) => {
                eprintln!("exchange_rates_unavailable: {e}");
                return;
            }
        }
    }
    if !args.is_empty() {
        show(
            &calc,
            &args.join(" "),
            &mut context,
            &mut rates_attempted,
            online,
        );
        return;
    }
    let mut quoted: Option<(char, String)> = None;
    for line in io::stdin().lock().lines() {
        match line {
            Ok(s) => {
                if let Some((quote, mut request)) = quoted.take() {
                    request.push('\n');
                    if let Some(end) = s.trim_end().strip_suffix(quote) {
                        request.push_str(end);
                        show(&calc, &request, &mut context, &mut rates_attempted, online);
                    } else {
                        request.push_str(&s);
                        quoted = Some((quote, request));
                    }
                } else if let Some(quote) = s
                    .trim_start()
                    .chars()
                    .next()
                    .filter(|c| *c == '\'' || *c == '"')
                {
                    let request = s.trim_start();
                    let end = request.trim_end();
                    if end.len() >= 2 && end.ends_with(quote) {
                        show(
                            &calc,
                            &end[1..end.len() - 1],
                            &mut context,
                            &mut rates_attempted,
                            online,
                        );
                    } else {
                        quoted = Some((quote, request[1..].to_owned()));
                    }
                } else {
                    show(&calc, &s, &mut context, &mut rates_attempted, online);
                }
            }
            Err(e) => {
                eprintln!("{e}");
                break;
            }
        }
    }
    if quoted.is_some() {
        eprintln!("invalid_expression");
    }
}
fn show(
    calc: &Calculator,
    input: &str,
    context: &mut Context,
    rates_attempted: &mut bool,
    online: bool,
) {
    context.now = chrono::Utc::now();
    if !*rates_attempted && rates::needs_rates(input) {
        *rates_attempted = true;
        match rates::exchange_rates(online) {
            Ok(rates) => {
                context.rates = rates;
            }
            Err(e) => {
                eprintln!("exchange_rates_unavailable: {e}");
                *rates_attempted = false;
                return;
            }
        }
    }
    match calc.evaluate_with(input, context) {
        Ok(a) => println!("{}", a.display),
        Err(e) => eprintln!("{e}"),
    }
}