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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
extern crate errno;
extern crate libc;
use errno::{Errno, errno};
use std::error;
use std::error::Error as ErrorTrait;
use std::ffi::{CString, NulError, OsStr, OsString};
use std::iter::{IntoIterator, Iterator};
use std::fmt;
use std::ptr;
use std::os::unix::ffi::OsStrExt;
#[derive(Debug)]
#[must_use]
pub enum Error {
BadArgument(NulError),
Errno(Errno),
}
impl error::Error for Error {
fn description(&self) -> &str {
match self {
&Error::BadArgument(_) => "bad argument to exec",
&Error::Errno(_) => "couldn't exec process",
}
}
fn cause(&self) -> Option<&error::Error> {
match self {
&Error::BadArgument(ref err) => Some(err),
&Error::Errno(_) => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Error::BadArgument(ref err) =>
write!(f, "{}: {}", self.description(), err),
&Error::Errno(err) =>
write!(f, "{}: {}", self.description(), err),
}
}
}
impl From<NulError> for Error {
fn from(err: NulError) -> Error {
Error::BadArgument(err)
}
}
macro_rules! exec_try {
( $ expr : expr ) => {
match $expr {
Ok(val) => val,
Err(err) => return From::from(err),
}
};
}
pub fn execvp<S, I>(program: S, args: I) -> Error
where S: AsRef<OsStr>, I: IntoIterator, I::Item: AsRef<OsStr>
{
let program_cstring =
exec_try!(CString::new(program.as_ref().as_bytes()));
let arg_cstrings = exec_try!(args.into_iter().map(|arg| {
CString::new(arg.as_ref().as_bytes())
}).collect::<Result<Vec<_>, _>>());
let mut arg_charptrs: Vec<_> = arg_cstrings.iter().map(|arg| {
arg.as_ptr()
}).collect();
arg_charptrs.push(ptr::null());
let res = unsafe {
libc::execvp(program_cstring.as_ptr(), arg_charptrs.as_ptr())
};
if res < 0 {
Error::Errno(errno())
} else {
panic!("execvp returned unexpectedly")
}
}
pub struct Command {
argv: Vec<OsString>,
}
impl Command {
pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
Command {
argv: vec!(program.as_ref().to_owned()),
}
}
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
self.argv.push(arg.as_ref().to_owned());
self
}
pub fn args<S: AsRef<OsStr>>(&mut self, args: &[S]) -> &mut Command {
for arg in args {
self.arg(arg.as_ref());
}
self
}
pub fn exec(&mut self) -> Error {
execvp(&self.argv[0], &self.argv)
}
}