2022-02-04 22:19:13 +01:00
|
|
|
use nu_engine::{current_dir, eval_expression_with_input, CallExt};
|
2021-09-29 20:25:05 +02:00
|
|
|
use nu_protocol::ast::Call;
|
2021-10-25 18:58:58 +02:00
|
|
|
use nu_protocol::engine::{Command, EngineState, Stack};
|
2022-02-18 17:19:37 +01:00
|
|
|
use nu_protocol::{Category, Example, PipelineData, 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 LetEnv;
|
|
|
|
|
|
|
|
impl Command for LetEnv {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"let-env"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Create an environment variable and give it a value."
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
|
|
Signature::build("let-env")
|
|
|
|
.required("var_name", SyntaxShape::String, "variable name")
|
|
|
|
.required(
|
|
|
|
"initial_value",
|
2022-02-09 19:41:41 +01:00
|
|
|
SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::Expression)),
|
2021-09-29 20:25:05 +02:00
|
|
|
"equals sign followed by value",
|
|
|
|
)
|
2021-11-17 05:22:37 +01:00
|
|
|
.category(Category::Env)
|
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,
|
2022-01-26 20:00:25 +01:00
|
|
|
input: PipelineData,
|
2021-10-25 06:01:02 +02:00
|
|
|
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
|
2022-02-04 22:19:13 +01:00
|
|
|
let env_var = call.req(engine_state, stack, 0)?;
|
2021-09-29 20:25:05 +02:00
|
|
|
|
2022-04-09 04:55:02 +02:00
|
|
|
let keyword_expr = call
|
|
|
|
.positional_nth(1)
|
|
|
|
.expect("checked through parser")
|
2021-09-29 20:25:05 +02:00
|
|
|
.as_keyword()
|
|
|
|
.expect("internal error: missing keyword");
|
|
|
|
|
2022-02-21 23:22:21 +01:00
|
|
|
let rhs =
|
|
|
|
eval_expression_with_input(engine_state, stack, keyword_expr, input, false, true)?
|
|
|
|
.into_value(call.head);
|
2021-09-29 20:25:05 +02:00
|
|
|
|
2022-01-05 01:26:01 +01:00
|
|
|
if env_var == "PWD" {
|
|
|
|
let cwd = current_dir(engine_state, stack)?;
|
|
|
|
let rhs = rhs.as_string()?;
|
|
|
|
let rhs = nu_path::expand_path_with(rhs, cwd);
|
|
|
|
stack.add_env_var(
|
|
|
|
env_var,
|
|
|
|
Value::String {
|
|
|
|
val: rhs.to_string_lossy().to_string(),
|
|
|
|
span: call.head,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
stack.add_env_var(env_var, rhs);
|
|
|
|
}
|
2021-11-06 06:50:33 +01:00
|
|
|
Ok(PipelineData::new(call.head))
|
2021-09-29 20:25:05 +02:00
|
|
|
}
|
2022-02-18 17:19:37 +01:00
|
|
|
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
|
|
vec![Example {
|
|
|
|
description: "Create an environment variable and display it",
|
|
|
|
example: "let-env MY_ENV_VAR = 1; $env.MY_ENV_VAR",
|
|
|
|
result: Some(Value::test_int(1)),
|
|
|
|
}]
|
|
|
|
}
|
2021-09-29 20:25:05 +02:00
|
|
|
}
|