major main method cleanup and implemented quiet flag

This commit is contained in:
Valerie Wolfe 2024-08-28 13:46:11 -04:00
parent 2bae1475b6
commit ed0e572f14

View file

@ -5,12 +5,14 @@ use std::{
stdout,
Write
}
},
process::exit
};
use evalexpr::{
eval_with_context_mut,
ContextWithMutableVariables,
EvalexprError,
HashMapContext,
Value
};
@ -21,7 +23,6 @@ use termion::{
};
mod context;
mod eval;
mod flag;
mod util;
@ -41,13 +42,14 @@ fn main() {
}
let mut context = util::build_context(&mut args);
let quiet = args.contains(flag::QUIET);
// collect args and evaluate if present
let expressions = args.finish();
if expressions.len() > 0 {
for expression in expressions {
let expression: String = expression.to_string_lossy().into();
do_eval(expression, &mut context)
eval(&expression, &mut context, quiet);
}
} else {
// enter interactive mode if no args are given
@ -65,44 +67,44 @@ fn main() {
match line.as_str() {
"" |
"exit" => break,
_ => do_eval(line, &mut context)
_ => eval(&line, &mut context, quiet)
}
reset();
}
}
}
fn do_eval(i_expression: String, context: &mut HashMapContext) {
let expression = i_expression.as_str();
fn eval(expression: &str, context: &mut HashMapContext, quiet: bool) {
let result = eval_with_context_mut(expression, context);
if quiet {
if let Ok(result) = result { println!("{result}") }
else { exit(1) }
} else { format(expression, result) }
}
fn format(expression: &str, result: Result<Value, EvalexprError>) {
if let Ok(result) = result {
// display empty result
if result.is_empty() {
if !result.is_empty() {
let delimiter =
match result {
Value::Boolean(_) => "is",
Value::String(_) => "=>",
_ => "="
};
println!(
"{faint}{italic}{expression}{reset} {delimiter} {bold}{result}",
bold = style::Bold,
faint = style::Faint,
italic = style::Italic,
reset = style::Reset
);
} else {
println!(
"{green}✓ {bold}{expression}",
bold = style::Bold,
green = color::Fg(color::Green)
);
return;
}
// get appropriate symbol for result by type
let delimiter;
match result {
Value::Boolean(_bool) => delimiter = "is",
Value::String(ref _str) => delimiter = "=>",
_ => delimiter = "="
}
println!(
"{faint}{italic}{expression}{reset} {delimiter} {bold}{result}",
bold = style::Bold,
faint = style::Faint,
italic = style::Italic,
reset = style::Reset
);
// set "last" variable
context.set_value("$".to_string(), result).ok();
} else {
println!(
"{red}✕ {bold}{expression}",