nushell/crates/nu-command/src/core_commands/if_.rs

78 lines
2.8 KiB
Rust
Raw Normal View History

2021-09-29 20:25:05 +02:00
use nu_engine::{eval_block, eval_expression};
use nu_protocol::ast::Call;
2021-10-25 18:58:58 +02:00
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Value,
};
2021-09-29 20:25:05 +02:00
2021-10-25 06:01:02 +02:00
#[derive(Clone)]
2021-09-29 20:25:05 +02:00
pub struct If;
impl Command for If {
fn name(&self) -> &str {
"if"
}
fn usage(&self) -> &str {
"Conditionally run a block."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("if")
.required("cond", SyntaxShape::Expression, "condition")
.required("then_block", SyntaxShape::Block(Some(vec![])), "then block")
.optional(
"else",
SyntaxShape::Keyword(b"else".to_vec(), Box::new(SyntaxShape::Expression)),
"optional else followed by else block",
)
.category(Category::Core)
2021-09-29 20:25:05 +02:00
}
fn run(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-09-29 20:25:05 +02:00
call: &Call,
2021-10-25 06:01:02 +02:00
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
2021-09-29 20:25:05 +02:00
let cond = &call.positional[0];
let then_block = call.positional[1]
.as_block()
.expect("internal error: expected block");
let else_case = call.positional.get(2);
2021-10-25 08:31:39 +02:00
let result = eval_expression(engine_state, stack, cond)?;
match &result {
2021-10-25 18:58:58 +02:00
Value::Bool { val, .. } => {
if *val {
2021-10-25 08:31:39 +02:00
let block = engine_state.get_block(then_block);
2021-10-25 22:04:23 +02:00
let mut stack = stack.collect_captures(&block.captures);
2021-10-25 18:58:58 +02:00
eval_block(engine_state, &mut stack, block, input)
2021-09-29 20:25:05 +02:00
} else if let Some(else_case) = else_case {
if let Some(else_expr) = else_case.as_keyword() {
if let Some(block_id) = else_expr.as_block() {
2021-10-25 08:31:39 +02:00
let block = engine_state.get_block(block_id);
2021-10-25 22:04:23 +02:00
let mut stack = stack.collect_captures(&block.captures);
2021-10-25 18:58:58 +02:00
eval_block(engine_state, &mut stack, block, input)
2021-09-29 20:25:05 +02:00
} else {
2021-10-25 18:58:58 +02:00
eval_expression(engine_state, stack, else_expr)
2021-10-25 08:31:39 +02:00
.map(|x| x.into_pipeline_data())
2021-09-29 20:25:05 +02:00
}
} else {
2021-10-25 18:58:58 +02:00
eval_expression(engine_state, stack, else_case)
2021-10-25 08:31:39 +02:00
.map(|x| x.into_pipeline_data())
2021-09-29 20:25:05 +02:00
}
} else {
Ok(PipelineData::new(call.head))
2021-09-29 20:25:05 +02:00
}
}
x => Err(ShellError::CantConvert(
"bool".into(),
x.get_type().to_string(),
result.span()?,
)),
2021-09-29 20:25:05 +02:00
}
}
}