diff --git a/src/context/mod.rs b/src/context/mod.rs index 0e66319..77f15a9 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -5,7 +5,7 @@ pub use builder::*; pub use command_group_config::CommandGroupConfig; use nu_protocol::{ ast::{Block, Call}, - engine::{EngineState, Stack}, + engine::{EngineState, Stack, StateWorkingSet}, PipelineData, Span, }; @@ -13,7 +13,7 @@ use crate::{ argument::IntoArgument, error::{CrateError, CrateResult}, utils::parse_nu_script, - NewEmpty, + IntoValue, NewEmpty, }; /// Represents the evaluation context of nu scripts and commands @@ -125,4 +125,21 @@ impl Context { Ok(()) } + + /// Adds a variable to the context + pub fn add_var(&mut self, name: S, value: V) -> CrateResult<()> { + let mut working_set = StateWorkingSet::new(&self.engine_state); + + let var_id = working_set.add_variable( + name.to_string().into_bytes(), + Span::empty(), + nu_protocol::Type::Any, + false, + ); + self.stack.add_var(var_id, value.into_value()); + let delta = working_set.render(); + self.engine_state.merge_delta(delta)?; + + Ok(()) + } } diff --git a/tests/test_eval.rs b/tests/test_eval.rs index 0940a08..b2f5c36 100644 --- a/tests/test_eval.rs +++ b/tests/test_eval.rs @@ -24,6 +24,15 @@ fn it_returns_variables() { assert_eq!(val.as_string().unwrap(), String::from("world")) } +#[test] +fn it_accepts_variables() { + let mut ctx = get_context(); + ctx.add_var("hello", "world").unwrap(); + + let val = ctx.get_var("hello").expect("No variable returned"); + assert_eq!(val.as_string().unwrap(), String::from("world")) +} + #[derive(RustyValue)] struct TestArg { foo: String,