From 67235f436a8b4d5dee6d616f22253fa3f0f83416 Mon Sep 17 00:00:00 2001 From: Filip Tibell Date: Thu, 19 Jan 2023 00:23:06 -0500 Subject: [PATCH] Add support for script args --- .lune/hello_lune.luau | 18 +++++++++++++++--- src/cli.rs | 35 ++++++++++++++++++++++++++++++----- src/main.rs | 3 ++- 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/.lune/hello_lune.luau b/.lune/hello_lune.luau index 7cbf056..946690a 100644 --- a/.lune/hello_lune.luau +++ b/.lune/hello_lune.luau @@ -12,6 +12,18 @@ module.hello() --[==[ EXAMPLE #2 + Using arguments given to the program +]==] + +local arg: string? = ... +if arg then + print("\nGot an argument while running hello_lune:") + print(arg) +end + +--[==[ + EXAMPLE #3 + Get & set environment variables Checks if environment variables are empty or not, @@ -32,7 +44,7 @@ for _, key in vars do end --[==[ - EXAMPLE #3 + EXAMPLE #4 Read files in the current directory @@ -79,7 +91,7 @@ if process.getEnvVar("GITHUB_ACTIONS") then end --[==[ - EXAMPLE #4 + EXAMPLE #5 Call out to another program / executable @@ -94,7 +106,7 @@ local result = process.spawn("ping", { }) --[==[ - EXAMPLE #5 + EXAMPLE #6 Using the result of a spawned process, exiting the process diff --git a/src/cli.rs b/src/cli.rs index 952cd42..fb568dd 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -4,7 +4,7 @@ use std::{ }; use clap::Parser; -use mlua::{Lua, Result}; +use mlua::{Lua, MultiValue, Result, ToLua}; use crate::lune::{fs::LuneFs, json::LuneJson, process::LuneProcess}; @@ -14,13 +14,31 @@ use crate::lune::{fs::LuneFs, json::LuneJson, process::LuneProcess}; pub struct Cli { /// Path to the file to run path: String, + /// Arguments to pass to the file + args: Vec, } impl Cli { #[allow(dead_code)] - pub fn from_path>(path: S) -> Self { + pub fn from_path(path: S) -> Self + where + S: Into, + { Self { - path: path.as_ref().to_owned(), + path: path.into(), + args: vec![], + } + } + + #[allow(dead_code)] + pub fn from_path_with_args(path: S, args: A) -> Self + where + S: Into, + A: Into>, + { + Self { + path: path.into(), + args: args.into(), } } @@ -35,8 +53,15 @@ impl Cli { globals.set("process", LuneProcess::new())?; globals.set("json", LuneJson::new())?; lua.sandbox(true)?; - // Run the file - lua.load(&file_contents).exec_async().await?; + // Load & call the file with the given args + let lua_args = self + .args + .iter() + .map(|value| value.to_owned().to_lua(&lua)) + .collect::>>()?; + lua.load(&file_contents) + .call_async(MultiValue::from_vec(lua_args)) + .await?; Ok(()) } } diff --git a/src/main.rs b/src/main.rs index 148bf75..029b8a6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,7 +26,8 @@ async fn main() -> Result<()> { #[tokio::test] async fn hello_lune() { - let cli = Cli::from_path("hello_lune"); + let args = vec!["Hello, test! ✅".to_owned()]; + let cli = Cli::from_path_with_args("hello_lune", args); let result = cli.run().await; assert!(result.is_ok()); }