Add IntoArgment trait to pass arguments directly without wrapping them

pull/3/head
trivernis 2 years ago
parent ca5057ea04
commit 895945fb78
Signed by: Trivernis
GPG Key ID: DFFFCC2C7A02DB45

@ -33,3 +33,20 @@ impl Argument {
} }
} }
} }
/// Converts a given type into an argument
pub trait IntoArgument {
fn into_argument(self) -> Argument;
}
impl<E: IntoExpression> IntoArgument for E {
fn into_argument(self) -> Argument {
Argument::positional(self)
}
}
impl IntoArgument for Argument {
fn into_argument(self) -> Argument {
self
}
}

@ -10,7 +10,7 @@ use nu_protocol::{
}; };
use crate::{ use crate::{
argument::Argument, argument::IntoArgument,
error::{CrateError, CrateResult}, error::{CrateError, CrateResult},
utils::parse_nu_script, utils::parse_nu_script,
NewEmpty, NewEmpty,
@ -63,14 +63,14 @@ impl Context {
/// Calls a function by the given name /// Calls a function by the given name
/// Errs if the function doesn't exist /// Errs if the function doesn't exist
pub fn call_fn<S: AsRef<str>, I: IntoIterator<Item = Argument>>( pub fn call_fn<S: AsRef<str>, I: IntoIterator<Item = A>, A: IntoArgument>(
&mut self, &mut self,
name: S, name: S,
args: I, args: I,
) -> CrateResult<PipelineData> { ) -> CrateResult<PipelineData> {
let args = args let args = args
.into_iter() .into_iter()
.map(|a: Argument| a.into_nu_argument()) .map(|a| a.into_argument().into_nu_argument())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let decl_id = self let decl_id = self

@ -1,4 +1,4 @@
use embed_nu::{Argument, CommandGroupConfig, Context, NewEmpty}; use embed_nu::{CommandGroupConfig, Context, NewEmpty};
use nu_protocol::PipelineData; use nu_protocol::PipelineData;
#[test] #[test]
@ -28,11 +28,10 @@ fn it_executes_functions() {
PipelineData::empty(), PipelineData::empty(),
) )
.unwrap(); .unwrap();
ctx.call_fn("hello", []).unwrap(); ctx.call_fn("hello", [] as [String; 0]).unwrap();
assert!(ctx.has_fn("world") == false); assert!(ctx.has_fn("world") == false);
let arg = Argument::positional("Hello from rust"); let pipeline = ctx.call_fn("echo", ["Hello from Rust"]).unwrap();
let pipeline = ctx.call_fn("echo", [arg]).unwrap();
ctx.print_pipeline(pipeline).unwrap(); ctx.print_pipeline(pipeline).unwrap();
} }

Loading…
Cancel
Save