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

79 lines
2.0 KiB
Rust
Raw Normal View History

2021-09-29 20:25:05 +02:00
use nu_engine::eval_expression;
use nu_protocol::ast::Call;
2021-10-25 18:58:58 +02:00
use nu_protocol::engine::{Command, EngineState, Stack};
2021-11-27 19:16:20 +01:00
use nu_protocol::{Category, Example, PipelineData, Signature, SyntaxShape};
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 Let;
impl Command for Let {
fn name(&self) -> &str {
"let"
}
fn usage(&self) -> &str {
"Create a variable and give it a value."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("let")
.required("var_name", SyntaxShape::VarWithOptType, "variable name")
.required(
"initial_value",
SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::Expression)),
"equals sign followed by value",
)
.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 var_id = call.positional[0]
.as_var()
.expect("internal error: missing variable");
let keyword_expr = call.positional[1]
.as_keyword()
.expect("internal error: missing keyword");
2021-10-25 18:58:58 +02:00
let rhs = eval_expression(engine_state, stack, keyword_expr)?;
2021-09-29 20:25:05 +02:00
//println!("Adding: {:?} to {}", rhs, var_id);
2021-10-25 08:31:39 +02:00
stack.add_var(var_id, rhs);
Ok(PipelineData::new(call.head))
2021-09-29 20:25:05 +02:00
}
2021-11-27 19:16:20 +01:00
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Set a variable to a value",
example: "let x = 10",
result: None,
},
Example {
description: "Set a variable to the result of an expression",
example: "let x = 10 + 100",
result: None,
},
]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Let {})
}
2021-09-29 20:25:05 +02:00
}