1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#![deny(rust_2018_idioms, missing_docs)]
#![forbid(unsafe_code)]
use std::ffi::OsString;
pub struct Prepare {
command: OsString,
stdin: std::process::Stdio,
stdout: std::process::Stdio,
stderr: std::process::Stdio,
args: Vec<OsString>,
use_shell: bool,
}
mod prepare {
use std::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 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<std::ffi::OsString>) -> Self {
self.args.push(arg.into());
self
}
}
impl Prepare {
pub fn spawn(self) -> std::io::Result<std::process::Child> {
let mut cmd: Command = self.into();
cmd.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)
.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(),
use_shell: false,
}
}