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
/*!
 * CLI Runner
 * 
 * is a library which makes it convenient to execute a command line String.
 * It is using shell_words crate to parse the command line, allowing it to accept a command
 * as it would be issued in a shell.
 * This is a multi-platform library.
 * 
 * Example:
 * ```
 * use cli_runner::{run, get_stdout, get_stderr};
 * 
 * let cmd = "ls -alF";
 * let output = run(cmd);
 * 
 * assert!(output.status.success());
 * 
 * let so = get_stdout(&output);
 * assert!(!so.is_empty());
 * 
 * let se = get_stderr(&output);
 * assert!(se.is_empty());
 * ```
 */

 use std::process::{Command, Output};

 /// Runs a CLI application.
 ///
 /// Runs a given command with parameters. The command is given as &str.
 ///
 /// Returns the output of the CLI application as a string.
 ///
 /// Example:
 /// ```
 /// let cmd = r#"ls -alF"#;
 /// let output = cli_runner::run(cmd);
 /// assert!(output.status.success());
 /// ```
 pub fn run(command: &str) -> Output {
     // parse attributes
     let args = shell_words::split(command)
         .expect("command arguments parsed");
 
     // the first argument is the application name
     let program = &args[0];
     let prog_args = &args[1..];
 
     Command::new(program)
         .args(prog_args)
         .output()
         .expect("CLI output")
 }
 
 /// Returns `stdout` as UTF-8 &str.
 pub fn get_stdout<'a>(output: &'a Output) -> &'a str {
     core::str::from_utf8(&output.stdout).expect("stdout as &str")
     // String::from_utf8(output.stdout).expect("stdout as string")
 }
 
 /// Returns `stderr` as UTF-8 &str.
 pub fn get_stderr<'a>(output: &'a Output) -> &'a str {
     core::str::from_utf8(&output.stderr).expect("stdout as &str")
     // String::from_utf8(output.stderr).expect("stderr as string")
 }
 
 //// Tests

 #[cfg(test)]
 mod tests {
    use super::{run, get_stdout, get_stderr};

    #[test]
    fn basic_test() {
        let cmd = "ls -alF";
        let output = run(cmd);

        assert!(output.status.success());

        let so = get_stdout(&output);
        assert!(!so.is_empty());

        let se = get_stderr(&output);
        assert!(se.is_empty());
    }
 }