#![deny(rust_2018_idioms, missing_docs)]
#![forbid(unsafe_code)]
use std::ffi::OsString;
pub struct Prepare {
pub command: OsString,
pub stdin: std::process::Stdio,
pub stdout: std::process::Stdio,
pub stderr: std::process::Stdio,
pub args: Vec<OsString>,
pub env: Vec<(OsString, OsString)>,
pub use_shell: bool,
}
mod prepare {
use std::{
ffi::OsString,
process::{Command, Stdio},
};
use bstr::ByteSlice;
use crate::Prepare;
impl Prepare {
pub fn with_shell(mut self) -> Self {
self.use_shell = self.command.to_str().map_or(true, |cmd| {
cmd.as_bytes().find_byteset(b"|&;<>()$`\\\"' \t\n*?[#~=%").is_some()
});
self
}
pub fn without_shell(mut self) -> Self {
self.use_shell = false;
self
}
pub fn stdin(mut self, stdio: Stdio) -> Self {
self.stdin = stdio;
self
}
pub fn stdout(mut self, stdio: Stdio) -> Self {
self.stdout = stdio;
self
}
pub fn stderr(mut self, stdio: Stdio) -> Self {
self.stderr = stdio;
self
}
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
self.args.push(arg.into());
self
}
pub fn args(mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
self.args
.append(&mut args.into_iter().map(Into::into).collect::<Vec<_>>());
self
}
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
self.env.push((key.into(), value.into()));
self
}
}
impl Prepare {
pub fn spawn(self) -> std::io::Result<std::process::Child> {
Command::from(self).spawn()
}
}
impl From<Prepare> for Command {
fn from(mut prep: Prepare) -> Command {
let mut cmd = if prep.use_shell {
let mut cmd = Command::new(if cfg!(windows) { "sh" } else { "/bin/sh" });
cmd.arg("-c");
if !prep.args.is_empty() {
prep.command.push(" \"$@\"")
}
cmd.arg(prep.command);
cmd.arg("--");
cmd
} else {
Command::new(prep.command)
};
cmd.stdin(prep.stdin)
.stdout(prep.stdout)
.stderr(prep.stderr)
.envs(prep.env)
.args(prep.args);
cmd
}
}
}
pub fn prepare(cmd: impl Into<OsString>) -> Prepare {
Prepare {
command: cmd.into(),
stdin: std::process::Stdio::null(),
stdout: std::process::Stdio::piped(),
stderr: std::process::Stdio::inherit(),
args: Vec::new(),
env: Vec::new(),
use_shell: false,
}
}