added rustyline

This commit is contained in:
Valerie Wolfe 2024-08-29 09:17:30 -04:00
parent 8c1610bcf9
commit 17165ff634
2 changed files with 24 additions and 17 deletions

View file

@ -15,6 +15,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
evalexpr = "11.0.0" evalexpr = "11.0.0"
pico-args = "0.5.0" pico-args = "0.5.0"
rustyline = "14.0.0"
termion = "1.5.6" termion = "1.5.6"
[profile.release] [profile.release]

View file

@ -5,6 +5,7 @@ use std::{
stdout, stdout,
IsTerminal, IsTerminal,
Read,
Write Write
}, },
process::exit process::exit
@ -18,6 +19,7 @@ use evalexpr::{
Value Value
}; };
use pico_args::Arguments; use pico_args::Arguments;
use rustyline::DefaultEditor;
use termion::{ use termion::{
color, color,
style style
@ -43,7 +45,8 @@ fn main() {
} }
let mut context = context::build(&mut args); let mut context = context::build(&mut args);
let quiet = args.contains(flag::QUIET) || !stdout().is_terminal(); let is_terminal = stdin().is_terminal() && stdout().is_terminal();
let quiet = args.contains(flag::QUIET) || !is_terminal;
// collect args and evaluate if present // collect args and evaluate if present
let expressions = args.finish(); let expressions = args.finish();
@ -53,26 +56,29 @@ fn main() {
eval(&expression, &mut context, quiet); eval(&expression, &mut context, quiet);
} }
} else { } else {
if !is_terminal {
let mut buffer = String::with_capacity(0);
if let Ok(_) = stdin().read_to_string(&mut buffer) {
for expression in buffer.lines() {
eval(&expression.to_string(), &mut context, quiet);
}
}
} else if let Ok(mut rl) = DefaultEditor::new() {
// enter interactive mode if no args are given // enter interactive mode if no args are given
version_text(); version_text();
println!("{}Interactive Mode{}", style::Faint, style::Reset); println!("{}Interactive Mode{}", style::Faint, style::Reset);
loop { loop {
print!("> "); if let Ok(line) = rl.readline("> ") {
stdout().flush().unwrap();
let mut i_line = String::new();
let line_result = stdin().read_line(&mut i_line);
if line_result.is_err() {
break;
}
let line = i_line.trim().to_string();
match line.as_str() { match line.as_str() {
"" | "" |
"exit" => break, "exit" => break,
_ => eval(&line, &mut context, quiet) _ => eval(&line, &mut context, quiet)
} }
}
reset(); reset();
} }
} }
}
} }
fn eval(expression: &str, context: &mut HashMapContext, quiet: bool) { fn eval(expression: &str, context: &mut HashMapContext, quiet: bool) {