brush_core/
tests.rs

1//! Shell test conditional expressions
2
3use crate::{ExecutionParameters, Shell, error, extendedtests};
4
5/// Evaluate the given test expression within the provided shell and
6/// execution context. Returns true if the expression evaluates to true,
7/// false otherwise.
8///
9/// # Arguments
10///
11/// * `expr` - The test expression to evaluate.
12/// * `shell` - The shell context in which to evaluate the expression.
13/// * `params` - The execution parameters to use during evaluation.
14pub fn eval_expr(
15    expr: &brush_parser::ast::TestExpr,
16    shell: &mut Shell,
17    params: &ExecutionParameters,
18) -> Result<bool, error::Error> {
19    match expr {
20        brush_parser::ast::TestExpr::False => Ok(false),
21        brush_parser::ast::TestExpr::Literal(s) => Ok(!s.is_empty()),
22        brush_parser::ast::TestExpr::And(left, right) => {
23            Ok(eval_expr(left, shell, params)? && eval_expr(right, shell, params)?)
24        }
25        brush_parser::ast::TestExpr::Or(left, right) => {
26            Ok(eval_expr(left, shell, params)? || eval_expr(right, shell, params)?)
27        }
28        brush_parser::ast::TestExpr::Not(expr) => Ok(!eval_expr(expr, shell, params)?),
29        brush_parser::ast::TestExpr::Parenthesized(expr) => eval_expr(expr, shell, params),
30        brush_parser::ast::TestExpr::UnaryTest(op, operand) => {
31            extendedtests::apply_unary_predicate_to_str(op, operand, shell, params)
32        }
33        brush_parser::ast::TestExpr::BinaryTest(op, left, right) => {
34            extendedtests::apply_binary_predicate_to_strs(op, left.as_str(), right.as_str(), shell)
35        }
36    }
37}