2024-07-14 14:19:15 +01:00
|
|
|
use std::{
|
|
|
|
ffi::OsStr,
|
|
|
|
io::{BufRead, BufReader},
|
2024-07-22 15:41:45 +01:00
|
|
|
path::Path,
|
2024-07-14 14:19:15 +01:00
|
|
|
process::{Command, Stdio},
|
|
|
|
thread::spawn,
|
|
|
|
};
|
|
|
|
|
2024-07-22 15:41:45 +01:00
|
|
|
pub fn execute_script<A: IntoIterator<Item = S>, S: AsRef<OsStr>, P: AsRef<Path>>(
|
2024-07-14 14:19:15 +01:00
|
|
|
script_name: Option<&str>,
|
2024-07-22 15:41:45 +01:00
|
|
|
script_path: &Path,
|
2024-07-14 14:19:15 +01:00
|
|
|
args: A,
|
2024-07-22 15:41:45 +01:00
|
|
|
cwd: P,
|
|
|
|
return_stdout: bool,
|
|
|
|
) -> Result<Option<String>, std::io::Error> {
|
2024-07-14 14:19:15 +01:00
|
|
|
match Command::new("lune")
|
|
|
|
.arg("run")
|
2024-07-22 15:41:45 +01:00
|
|
|
.arg(script_path.as_os_str())
|
2024-07-14 14:19:15 +01:00
|
|
|
.args(args)
|
2024-07-22 15:41:45 +01:00
|
|
|
.current_dir(cwd)
|
2024-07-14 14:19:15 +01:00
|
|
|
.stdin(Stdio::null())
|
|
|
|
.stdout(Stdio::piped())
|
|
|
|
.stderr(Stdio::piped())
|
|
|
|
.spawn()
|
|
|
|
{
|
|
|
|
Ok(mut child) => {
|
|
|
|
let stdout = BufReader::new(child.stdout.take().unwrap());
|
|
|
|
let stderr = BufReader::new(child.stderr.take().unwrap());
|
|
|
|
|
|
|
|
let script = match script_name {
|
|
|
|
Some(script) => script.to_string(),
|
2024-07-22 15:41:45 +01:00
|
|
|
None => script_path.to_string_lossy().to_string(),
|
2024-07-14 14:19:15 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
let script_2 = script.to_string();
|
|
|
|
|
|
|
|
spawn(move || {
|
|
|
|
for line in stderr.lines() {
|
|
|
|
match line {
|
|
|
|
Ok(line) => {
|
|
|
|
log::error!("[{script}]: {line}");
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("ERROR IN READING STDERR OF {script}: {e}");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2024-07-22 15:41:45 +01:00
|
|
|
let mut stdout_str = String::new();
|
|
|
|
|
2024-07-14 14:19:15 +01:00
|
|
|
for line in stdout.lines() {
|
|
|
|
match line {
|
|
|
|
Ok(line) => {
|
|
|
|
log::info!("[{script_2}]: {line}");
|
2024-07-22 15:41:45 +01:00
|
|
|
|
|
|
|
if return_stdout {
|
|
|
|
stdout_str.push_str(&line);
|
|
|
|
stdout_str.push('\n');
|
|
|
|
}
|
2024-07-14 14:19:15 +01:00
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
log::error!("ERROR IN READING STDOUT OF {script_2}: {e}");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-07-22 15:41:45 +01:00
|
|
|
|
|
|
|
if return_stdout {
|
|
|
|
Ok(Some(stdout_str))
|
|
|
|
} else {
|
|
|
|
Ok(None)
|
|
|
|
}
|
2024-07-14 14:19:15 +01:00
|
|
|
}
|
|
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
2024-07-22 15:41:45 +01:00
|
|
|
log::warn!("Lune could not be found in PATH: {e}");
|
2024-07-14 14:19:15 +01:00
|
|
|
|
2024-07-22 15:41:45 +01:00
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
Err(e) => Err(e),
|
2024-07-14 14:19:15 +01:00
|
|
|
}
|
|
|
|
}
|