clingwrap 0.7.0

types and functions to implement command line programs
Documentation
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Run a [`Command`], handling errors in a way that is convenient for
//! the caller to handle. Specifically, the error type returned by
//! this module distinguishes between "program doesn't exist" and "no
//! permission to execute program" and "program ran, but failed". See
//! [`CommandError`] for all possible errors.
//!
//! # Example
//! ```
//! use std::process::Command;
//! use clingwrap::runner::*;
//! let mut cmd = Command::new("echo");
//! cmd.arg("hello").arg("world");
//! let mut runner = CommandRunner::new(cmd);
//! runner.capture_stdout();
//! match runner.execute() {
//!     Ok(output) => {
//!         let stdout = String::from_utf8_lossy(&output.stdout).to_string();
//!         assert_eq!(stdout, "hello world\n");
//!     }
//!     Err(err)  => eprintln!("{err}"),
//! }
//! ```

use std::{
    ffi::{OsStr, OsString},
    fs::File,
    io::{PipeReader, Read, Seek, Write, pipe},
    os::unix::ffi::OsStrExt,
    path::PathBuf,
    process::{Command, Output, Stdio},
};

// On Unix, we need this to find out which signal terminated the
// program.
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;

use log::trace;
use tempfile::tempfile;

// The list of bytes that are safe to not quote for a shell.
const SAFE_BYTES: &[u8] =
    b"abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY01234567890-_./@=%:+,";

#[derive(Debug)]
enum Stdin {
    Null,
    Inherit,
    Feed(Vec<u8>),
}

/// Run a
/// [`Command`](https://doc.rust-lang.org/std/process/struct.Command.html)
/// that has already been set up and return a useful error type for
/// when anything goes wrong.
#[derive(Debug)]
pub struct CommandRunner {
    // The command to run.
    cmd: Command,

    // How should stdin be handled?
    stdin: Stdin,

    // Handle for reading from child stdout when we redirect it.
    // We need to keep it open it doesn't get closed.
    stdout: Option<PipeReader>,
}

impl CommandRunner {
    /// Create a new command runner.
    ///
    /// By default, the child process stdin will come from `/dev/null`
    /// or equivalent.
    pub fn new(cmd: Command) -> Self {
        trace!("new CommandRunner: {cmd:#?}");
        trace!("child process stdin is empty, stdout and stderr are inherited");
        Self {
            cmd,
            stdin: Stdin::Null,
            stdout: None,
        }
    }

    /// Let the child process inherit its stdin from the parent process.
    #[mutants::skip]
    pub fn inherit_stdin(&mut self) {
        trace!("run command so it inherits stdin from parent process");
        self.stdin = Stdin::Inherit;
    }

    /// Feed data to the child process via its stdin. This data is
    /// written to a temporary file, in this version, but that may
    /// change to a pipe in a future version of this module. By
    /// default, the child stdin is closed.
    pub fn feed_stdin(&mut self, data: impl Into<Vec<u8>>) {
        let data = data.into();
        trace!("feed child process stdin {} bytes of input", data.len());
        self.stdin = Stdin::Feed(data);
    }

    /// Set up the command to capture the child process stdout.
    /// This method is a convenience wrapper for [`Command:stdout`](std::process::Command::stdout).
    pub fn capture_stdout(&mut self) {
        trace!("capture child process stdout");
        self.cmd.stdout(Stdio::piped());
    }

    /// Set up the command to capture the child process stderr.
    /// This method is a convenience wrapper for [`Command:stderr`](std::process::Command::stderr).
    pub fn capture_stderr(&mut self) {
        trace!("capture child process stderr");
        self.cmd.stderr(Stdio::piped());
    }

    /// Set up the command to capture child process stdout and stderr as
    /// one combined stream. This means if the child writes to stdout,
    /// then to stderr, then to stdout again, the captured output stream
    /// has the tree writes interleaved.
    pub fn combine_stdouterr(&mut self) -> Result<(), CommandError> {
        trace!("capture child process combined stdout and stderr");
        let (r, w) = pipe().map_err(CommandError::PipeCapture)?;
        self.stdout = Some(r);
        self.cmd
            .stdout(w.try_clone().map_err(CommandError::PipeClone)?);
        self.cmd.stderr(w);
        Ok(())
    }

    /// Execute the command in a child process. Wait for it to terminate.
    #[mutants::skip]
    pub fn execute(mut self) -> Result<Output, CommandError> {
        if let Some(dirname) = self.cmd.get_current_dir() {
            if !dirname.exists() {
                return Err(CommandError::NoSuchDir(dirname.to_path_buf()));
            }
        }

        let program_name = self.cmd.get_program().to_os_string();

        match &self.stdin {
            Stdin::Null => {
                self.cmd.stdin(Stdio::null());
            }
            Stdin::Inherit => {
                self.cmd.stdin(Stdio::inherit());
            }
            Stdin::Feed(data) => {
                self.cmd
                    .stdin(write_temp_file(data).map_err(CommandError::Stdin)?);
            }
        }

        trace!("spawn child process");
        let r = self.cmd.spawn();
        let mut child = match r {
            // Child process started running OK.
            Ok(child) => child,

            // Program does not exist.
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                return Err(CommandError::NoSuchCommand(program_name));
            }

            // We lack permission to run program.
            Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => {
                return Err(CommandError::NoPermission(program_name));
            }

            // Other problem prevented the program from starting.
            Err(err) => {
                return Err(CommandError::Other {
                    program_name,
                    source: err,
                });
            }
        };

        trace!("wait for child process to terminate");
        let result = if let Some(mut combined) = self.stdout.take() {
            // We have to drop the `Command` here. Otherwise the child
            // process stdout has two write handles: one in the
            // `Command` and in the child process. This means we will
            // never hit EOF when reading child stdout via the read
            // end of the stdout pipe (`combined` here).
            std::mem::drop(self.cmd);
            let mut output = Vec::new();
            combined
                .read_to_end(&mut output)
                .map_err(CommandError::ReadCombined)?;
            match child.wait() {
                Err(err) => Err(err),
                Ok(status) => Ok(Output {
                    status,
                    stdout: output,
                    stderr: vec![],
                }),
            }
        } else {
            child.wait_with_output()
        };

        match result {
            // Child terminated, but it may have failed.
            Ok(output) => {
                // Did the child terminate due to a signal?
                #[cfg(unix)]
                if let Some(signal) = output.status.signal() {
                    return Err(CommandError::KilledBySignal {
                        program_name,
                        signal,
                    });
                }

                // Did the child terminate with a non-zero exit code?
                if let Some(code) = output.status.code() {
                    if code != 0 {
                        return Err(CommandError::command_failed(program_name, output));
                    }
                }

                // At this point we know the child terminated, because we
                // used `wait_with_output`. We also know that it didn't
                // fail, because it didn't get killed by a signal, and it
                // didn't have a non-zero exit code.
                assert!(output.status.success());

                Ok(output)
            }

            // Something unexpected went wrong.
            Err(err) => Err(CommandError::Other {
                program_name,
                source: err,
            }),
        }
    }
}

fn write_temp_file(data: &[u8]) -> Result<File, std::io::Error> {
    let mut tmp = tempfile()?;
    tmp.write_all(data)?;
    tmp.rewind()?;
    Ok(tmp)
}

/// All possible errors from using [`CommandRunner`].
#[derive(Debug, thiserror::Error)]
pub enum CommandError {
    /// The program is supposed to be run in a directory, but that
    /// directory does not exist.
    #[error("directory does not exist: {0}")]
    NoSuchDir(PathBuf),

    /// The program doesn't exist. Or, possibly, the program specifies
    /// an interpreter or shared library that does not exist. The
    /// operating system doesn't tell us which.
    #[error("command does not exist: {0:?}")]
    NoSuchCommand(OsString),

    /// The program exists, but we lack the permission to run it. On
    /// Unix, this means the program file lacks the x bit for us.
    #[error("no permission to run command: {0:?}")]
    NoPermission(OsString),

    /// The program ran, but terminated with a non-zero exit code. Note
    /// that this error variant includes any captured stdout and stderr
    /// output.
    #[error("command failed: {program_name:?}")]
    CommandFailed {
        /// Name of program.
        program_name: OsString,
        /// Output from program, if captured.
        output: Box<Output>,
    },

    /// The program ran, but was terminated by a signal.
    #[cfg(unix)]
    #[error("command {program_name:?} was terminated by signal number {signal:?}")]
    KilledBySignal {
        /// Name of program.
        program_name: OsString,
        /// Signal that caused program to terminate
        signal: i32,
    },

    /// There was some other error. There can be any number of errors,
    /// and over time they can vary. We can't know everything, so we
    /// have a catchall error variant to handle the unknowns.
    #[error("unknown error while running command: {program_name:?}")]
    Other {
        /// Name of program.
        program_name: OsString,
        /// Underlying error.
        #[source]
        source: std::io::Error,
    },

    /// Can't write data to be fed to stdin to a temporary file.
    #[error("failed to create temporary file for stdin")]
    Stdin(#[source] std::io::Error),

    /// Can't create an anonymous pipe for capturing stdout and stderr.
    #[error("failed to create pipe for capturing output")]
    PipeCapture(#[source] std::io::Error),

    /// Can't clone write end of pipe.
    #[error("failed to clone write end of anonymous pipe")]
    PipeClone(#[source] std::io::Error),

    /// Can't read combined output of child process.
    #[error("failed to read child process combined output")]
    ReadCombined(#[source] std::io::Error),
}

impl CommandError {
    fn command_failed<O: Into<OsString>>(program_name: O, output: Output) -> Self {
        Self::CommandFailed {
            program_name: program_name.into(),
            output: Box::new(output),
        }
    }
}

/// Quote an OS string so it's parsed as the input string in the Unix Bourne shell.
pub fn shell_quote(s: &OsStr) -> OsString {
    // We do not try to minimize quoting. Out approach is simple, and borrowed
    // from Python shlex.quote: a single quote is quoted using double quotes,
    // and everything else is quoted using single quotes. In addition, if the
    // input consists only of safe characters, it is not quoted at all.

    let out = if s.as_bytes().iter().all(|byte| SAFE_BYTES.contains(byte)) {
        // If input consists only of safe bytes, no need to quote.
        s.as_bytes().to_vec()
    } else {
        // There's at least one unsafe byte. Quote everything. We don't need
        // to track if we're inside single quotes: we're always inside them.

        const SINGLE: u8 = b'\'';

        let mut out = vec![SINGLE];

        for byte in s.as_bytes() {
            // If we encounter a single quote, end current single-quote part, insert
            // double-quoted single quote, and start a new single-quote part.
            if *byte == SINGLE {
                out.push(SINGLE);
                out.push(b'"');
                out.push(SINGLE);
                out.push(b'"');
                out.push(SINGLE);
            } else {
                out.push(*byte);
            }
        }
        out.push(SINGLE);

        out
    };

    unsafe { OsString::from_encoded_bytes_unchecked(out) }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod test {
    use std::os::unix::ffi::OsStrExt;

    use tempfile::tempdir;

    use super::*;

    fn quote(bytes: &[u8]) -> Vec<u8> {
        shell_quote(OsStr::from_bytes(bytes))
            .into_encoded_bytes()
            .to_vec()
    }

    #[test]
    fn empty() {
        assert_eq!(quote(b""), b"");
    }

    #[test]
    fn quote_safe_bytes() {
        assert_eq!(quote(SAFE_BYTES), SAFE_BYTES);
    }

    #[test]
    fn minimal_quote_safe() {
        assert_eq!(quote(b"hello"), b"hello");
    }

    #[test]
    fn minimal_quote_unsafe() {
        assert_eq!(quote(b"hello world"), b"'hello world'");
    }

    #[test]
    fn single_quote() {
        assert_eq!(quote(b"'"), b"''\"'\"''");
    }

    #[test]
    fn mix() {
        assert_eq!(
            quote(b"it's a !#$ travesty"),
            b"'it'\"'\"'s a !#$ travesty'"
        );
    }

    #[test]
    fn run_inherit_stdin_combine_outputs() {
        let mut cmd = Command::new("echo");
        cmd.args(["hello", "world"]);
        let mut runner = CommandRunner::new(cmd);
        runner.combine_stdouterr().unwrap();
        let output = runner.execute().unwrap();
        eprintln!("{output:#?}");
        assert!(output.status.success());
        assert_eq!(output.stdout, b"hello world\n");
        assert!(output.stderr.is_empty());
    }

    #[test]
    fn run_feed_stdin_capture_outputs_separately() {
        let cmd = Command::new("cat");
        let mut runner = CommandRunner::new(cmd);
        runner.feed_stdin(b"hello");
        runner.capture_stdout();
        runner.capture_stderr();
        let output = runner.execute().unwrap();
        eprintln!("{output:#?}");
        assert!(output.status.success());
        assert_eq!(output.stdout, b"hello");
        assert!(output.stderr.is_empty());
    }

    #[test]
    fn capture_stderr() {
        let mut cmd = Command::new("sh");
        cmd.arg("-c");
        cmd.arg("echo foo 1>&2");

        let mut runner = CommandRunner::new(cmd);
        runner.capture_stderr();

        let output = runner.execute().unwrap();
        assert_eq!(output.stderr, b"foo\n");
    }

    #[test]
    fn run_non_exec() {
        let tmp = tempdir().unwrap();
        let bin = tmp.path().join("noexec.sh");
        std::fs::write(&bin, b"").unwrap();
        let cmd = Command::new(&bin);
        let runner = CommandRunner::new(cmd);
        let r = runner.execute();
        eprintln!("r={r:#?}");
        assert!(matches!(r, Err(CommandError::NoPermission(_))));
    }

    #[test]
    fn run_nonexistent() {
        let cmd = Command::new("./does-not-exist");
        let runner = CommandRunner::new(cmd);
        let r = runner.execute();
        eprintln!("r={r:#?}");
        assert!(matches!(r, Err(CommandError::NoSuchCommand(_))));
    }

    #[test]
    #[allow(clippy::panic)]
    fn current_dir_does_not_exist() {
        let dirname = PathBuf::from("/does/not/exist");
        let mut cmd = Command::new("true");
        cmd.current_dir(&dirname);
        let runner = CommandRunner::new(cmd);
        let r = runner.execute();
        eprintln!("r={r:#?}");
        match r {
            Err(CommandError::NoSuchDir(actual)) if actual == dirname => (),
            _ => panic!("unexpected result"),
        }
    }
}