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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//! Wrapper around std::process::Command which make the use of Rust for shell scripting more
//! appealing.
//!
//! ## Simple example
//!
//! ```rust
//! #[macro_use]
//! extern crate shells;
//!
//! fn main() {
//!     let (code, stdout, stderr) = sh!("echo '{} + {}' | cat", 1, 3);
//!
//!     assert_eq!(code, 0);
//!     assert_eq!(&stdout[..], "1 + 3\n");
//!     assert_eq!(&stderr[..], "");
//!
//!     // Using the new `wrap_*` macros.
//!     assert_eq!(wrap_sh!("echo '{} + {}' | cat", 1, 3).unwrap(), "1 + 3\n");
//! }
//! ```
//!
//! A mnemotechnic to remember the ordering of the elements in the resulting tuple is the positions
//! of stdout and stderr, they correspond to the standard streams numbers: 1 and 2 respectively.
//!
//! The implementation for all the different shells is the same: the arguments of the macro is
//! passed directly to `format!` and the resulting string is passed to the shell using its '-c'
//! command line option. Thus you can use `sh!` and friends the same way you would use `format!` or
//! `println!`.
//!

/// Type returned by the `wrap_*` family of macros. Will either be `Ok(stdout)` or an error
/// containing code, stdout and stderr resulting from executing the command.
///
pub type Result = ::std::result::Result<String, Error>;

/// Struct holding the resulting environment after executing a failed command with the `wrap_*`
/// family of macros. It implements the Error trait and its implementation of the Display trait is
/// identical to the implementation of the Display trait of its `stderr` field.
///
#[derive(Debug, Clone, PartialEq)]
pub struct Error {
    pub code: i32,
    pub stdout: String,
    pub stderr: String,
}

impl ::std::error::Error for Error {
    fn description(&self) -> &str {
        "Unix command failed."
    }
}

impl ::std::fmt::Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "{}", self.stderr)
    }
}

/// Macro to execute the given command using the Posix Shell.
///
#[macro_export]
macro_rules! sh {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("sh", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Almquist Shell.
///
#[macro_export]
macro_rules! ash {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("ash", &format!($( $cmd )*))
    }}; 
}

/// Macro to execute the given command using the C Shell.
///
#[macro_export]
macro_rules! csh {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("csh", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Korn Shell.
///
#[macro_export]
macro_rules! ksh {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("ksh", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Z Shell.
///
#[macro_export]
macro_rules! zsh {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("zsh", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Bourne Again Shell.
///
#[macro_export]
macro_rules! bash {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("bash", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Debian Almquist Shell.
///
#[macro_export]
macro_rules! dash {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("dash", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Fish Shell.
///
#[macro_export]
macro_rules! fish {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("fish", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the MirBSD Korn Shell.
///
#[macro_export]
macro_rules! mksh {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("mksh", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the TENEX C Shell.
///
#[macro_export]
macro_rules! tcsh {
    ( $( $cmd:tt )* ) => {{
        $crate::execute_with("tcsh", &format!($( $cmd )*))
    }};
}

/// Macro to execute the given command using the Posix Shell and wraping the resulting tuple into a
/// Result.
///
#[macro_export]
macro_rules! wrap_sh {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("sh", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the Almquist Shell and wraping the resulting tuple
/// into a Result.
///
#[macro_export]
macro_rules! wrap_ash {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("ash", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the C Shell and wraping the resulting tuple into a
/// Result.
///
#[macro_export]
macro_rules! wrap_csh {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("csh", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the Korn Shell and wraping the resulting tuple into a
/// Result.
///
#[macro_export]
macro_rules! wrap_ksh {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("ksh", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the Z Shell and wraping the resulting tuple into a
/// Result.
///
#[macro_export]
macro_rules! wrap_zsh {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("zsh", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the Bourne Again Shell and wraping the resulting tuple
/// into a Result.
///
#[macro_export]
macro_rules! wrap_bash {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("bash", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the Debian Almquist Shell and wraping the resulting
/// tuple into a Result.
///
#[macro_export]
macro_rules! wrap_dash {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("dash", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the Fish Shell and wraping the resulting tuple into a
/// Result.
///
#[macro_export]
macro_rules! wrap_fish {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("fish", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the MirBSD Korn Shell and wraping the resulting tuple
/// into a Result.
///
#[macro_export]
macro_rules! wrap_mksh {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("mksh", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

/// Macro to execute the given command using the TENEX C Shell and wraping the resulting tuple into
/// a Result.
///
#[macro_export]
macro_rules! wrap_tcsh {
    ( $( $cmd:tt )* ) => {{
        match $crate::execute_with("tcsh", &format!($( $cmd )*)) {
            (0, stdout, _) => Ok(stdout),

            (code, stdout, stderr) => {
                Err($crate::Error {
                    code: code,
                    stdout: stdout,
                    stderr: stderr,
                })
            },
        }
    }};
}

#[doc(hidden)]
pub fn execute_with(shell: &str, cmd: &String) -> (i32, String, String) {
    let mut command = {
        let mut command = ::std::process::Command::new(shell);
        command.arg("-c").arg(cmd);
        command
    };

    match command.output() {
        Ok(output) => {
            (output.status.code().unwrap_or(if output.status.success() { 0 } else { 1 }),
             String::from_utf8_lossy(&output.stdout[..]).into_owned(),
             String::from_utf8_lossy(&output.stderr[..]).into_owned())
        },

        Err(e) => (126, String::new(), e.to_string()),
    }
}