Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(andax/fns/io): exec() #84

Merged
merged 4 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 108 additions & 1 deletion andax/src/fns/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,18 @@ use rhai::{
use std::io::Write;
use std::process::Command;
use tracing::{debug, instrument};

macro_rules! _sh_out {
($ctx:expr, $o:expr) => {
Ok((
$o.status.code().ok_or::<Box<EvalAltResult>>("No exit code".into())?,
_sh_out!($o)?,
String::from_utf8($o.stdout).ehdl($ctx)?,
String::from_utf8($o.stderr).ehdl($ctx)?,
))
};
($o:expr) => {{
$o.status.code().ok_or::<Box<EvalAltResult>>("No exit code".into())
}};
}
macro_rules! _cmd {
($cmd:expr) => {{
Expand All @@ -32,6 +36,12 @@ macro_rules! _cmd {
}};
}

macro_rules! _stream_cmd {
($cmd:expr) => {{
_cmd!($cmd).stdout(Stdio::inherit()).stderr(Stdio::inherit())
}};
}

type T = Result<(i32, String, String), Box<EvalAltResult>>;

/// for andax, shell():
Expand All @@ -46,6 +56,22 @@ type T = Result<(i32, String, String), Box<EvalAltResult>>;
/// We will let rhai handle all the nasty things.
#[export_module]
pub mod ar {
use core::str::FromStr;
use std::process::Stdio;

macro_rules! die {
($id:literal, $expect:expr, $found:expr) => {{
let mut e = rhai::Map::new();
let mut inner = std::collections::BTreeMap::new();
e.insert("outcome".into(), rhai::Dynamic::from_str("fatal").unwrap());
inner.insert("kind".into(), rhai::Dynamic::from_str($id).unwrap());
inner.insert("expect".into(), rhai::Dynamic::from_str($expect).unwrap());
inner.insert("found".into(), rhai::Dynamic::from_str($found).unwrap());
e.insert("ctx".into(), rhai::Dynamic::from_map(inner));
e
}};
}

/// get the return code from the return value of `sh()`
#[rhai_fn(global)]
pub fn sh_rc(o: (i32, String, String)) -> i32 {
Expand All @@ -62,6 +88,87 @@ pub mod ar {
o.2
}

fn _parse_io_opt(opt: Option<&mut rhai::Dynamic>) -> Result<impl Into<Stdio>, rhai::Map> {
let Some(s) = opt else { return Ok(Stdio::inherit()) };
let s = match std::mem::take(s).into_string() {
Ok(s) => s,
Err(e) => return Err(die!("bad_stdio_type", r#""inherit" | "null" | "piped""#, e)),
};
Ok(match &*s {
"inherit" => Stdio::inherit(),
"null" => Stdio::null(),
"piped" => Stdio::piped(),
_ => return Err(die!("bad_stdio_opt", r#""inherit" | "null" | "piped""#, &s)),
})
}

/// Run a command
#[instrument]
#[rhai_fn(global, name = "sh")]
pub fn exec_cmd(command: Dynamic, mut opts: rhai::Map) -> rhai::Map {
let mut cmd: Command;
if command.is_string() {
cmd = Command::new("sh");
cmd.arg("-c").arg(command.into_string().unwrap())
} else {
let res = command.into_typed_array();
let Ok(arr) = res else {
return die!("bad_param_type", "String | Vec<String>", res.unwrap_err());
};
let [exec, args @ ..]: &[&str] = &arr[..] else {
return die!("empty_cmd_arr", "cmd.len() >= 1", "cmd.len() == 0");
};
cmd = Command::new(exec);
cmd.args(args)
};

cmd.stdout(match _parse_io_opt(opts.get_mut("stdout")) {
Ok(io) => io,
Err(e) => return e,
});
cmd.stderr(match _parse_io_opt(opts.get_mut("stderr")) {
Ok(io) => io,
Err(e) => return e,
});

if let Some(cwd) = opts.get_mut("cwd") {
match std::mem::take(cwd).into_string() {
Ok(cwd) => _ = cmd.current_dir(cwd),
Err(e) => return die!("bad_cwd_type", "String", e),
}
}

let out = match cmd.output() {
Ok(x) => x,
Err(err) => {
let mut e = rhai::Map::new();
let mut inner = rhai::Map::new();
e.insert("outcome".into(), rhai::Dynamic::from_str("failure").unwrap());
inner.insert("error".into(), rhai::Dynamic::from_str(&err.to_string()).unwrap());
e.insert("ctx".into(), rhai::Dynamic::from_map(inner));
return e;
}
};

let mut ret = rhai::Map::new();
let mut inner = rhai::Map::new();
ret.insert("outcome".into(), rhai::Dynamic::from_str("success").unwrap());
inner.insert(
"stdout".into(),
rhai::Dynamic::from_str(&String::from_utf8_lossy(&out.stdout)).unwrap(),
);
inner.insert(
"stderr".into(),
rhai::Dynamic::from_str(&String::from_utf8_lossy(&out.stderr)).unwrap(),
);
inner.insert(
"rc".into(),
rhai::Dynamic::from_int(i64::from(out.status.code().unwrap_or(0))),
);
ret.insert("ctx".into(), rhai::Dynamic::from_map(inner));
ret
}

/// run a command using `cmd` on Windows and `sh` on other systems
#[instrument(skip(ctx))]
#[rhai_fn(return_raw, name = "sh", global)]
Expand Down
4 changes: 2 additions & 2 deletions andax/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,10 +294,10 @@ fn hint_ear(sl: &str, lns: &str, ear: &EvalAltResult, rhai_fn: &str) -> Option<S
let s = d.clone().into_string().expect("sting.");
if s == "env(`GITHUB_TOKEN`) not present" {
h!(
r#"gh() requires the environment variable `GITHUB_TOKEN` to be set as a Github token so as to avoid rate-limits:
r"gh() requires the environment variable `GITHUB_TOKEN` to be set as a Github token so as to avoid rate-limits:
https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting
To create a Github token, see:
https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token"#
https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token"
);
}
}
Expand Down
Loading