From 895945fb7894b2fd213f4d7bca93e69c1429a130 Mon Sep 17 00:00:00 2001 From: trivernis Date: Mon, 3 Oct 2022 20:07:48 +0200 Subject: [PATCH] Add IntoArgment trait to pass arguments directly without wrapping them --- src/argument.rs | 17 +++++++++++++++++ src/context/mod.rs | 6 +++--- tests/test_eval.rs | 7 +++---- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/argument.rs b/src/argument.rs index 11128d5..611c5b6 100644 --- a/src/argument.rs +++ b/src/argument.rs @@ -33,3 +33,20 @@ impl Argument { } } } + +/// Converts a given type into an argument +pub trait IntoArgument { + fn into_argument(self) -> Argument; +} + +impl IntoArgument for E { + fn into_argument(self) -> Argument { + Argument::positional(self) + } +} + +impl IntoArgument for Argument { + fn into_argument(self) -> Argument { + self + } +} diff --git a/src/context/mod.rs b/src/context/mod.rs index 091052e..7d4d1d2 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -10,7 +10,7 @@ use nu_protocol::{ }; use crate::{ - argument::Argument, + argument::IntoArgument, error::{CrateError, CrateResult}, utils::parse_nu_script, NewEmpty, @@ -63,14 +63,14 @@ impl Context { /// Calls a function by the given name /// Errs if the function doesn't exist - pub fn call_fn, I: IntoIterator>( + pub fn call_fn, I: IntoIterator, A: IntoArgument>( &mut self, name: S, args: I, ) -> CrateResult { let args = args .into_iter() - .map(|a: Argument| a.into_nu_argument()) + .map(|a| a.into_argument().into_nu_argument()) .collect::>(); let decl_id = self diff --git a/tests/test_eval.rs b/tests/test_eval.rs index d5bd023..f7ed505 100644 --- a/tests/test_eval.rs +++ b/tests/test_eval.rs @@ -1,4 +1,4 @@ -use embed_nu::{Argument, CommandGroupConfig, Context, NewEmpty}; +use embed_nu::{CommandGroupConfig, Context, NewEmpty}; use nu_protocol::PipelineData; #[test] @@ -28,11 +28,10 @@ fn it_executes_functions() { PipelineData::empty(), ) .unwrap(); - ctx.call_fn("hello", []).unwrap(); + ctx.call_fn("hello", [] as [String; 0]).unwrap(); assert!(ctx.has_fn("world") == false); - let arg = Argument::positional("Hello from rust"); - let pipeline = ctx.call_fn("echo", [arg]).unwrap(); + let pipeline = ctx.call_fn("echo", ["Hello from Rust"]).unwrap(); ctx.print_pipeline(pipeline).unwrap(); }