rusty_ci/helper/cmd.rs
1use std::fmt::Display;
2use std::process::Command;
3use std::str::from_utf8;
4
5/// This struct is basically identical to the std::process::Command,
6/// but when it is executed, it returns the stdout of the process as a string.
7#[derive(Clone, PartialEq, Debug)]
8pub struct Cmd {
9 pub program: String,
10 pub args: Vec<String>,
11}
12
13impl Cmd {
14 /// Create a command that will call `program`.
15 /// For example, if you want to run the command
16 /// `echo 'hello world!'`, you would write:
17 /// Cmd::new("echo").arg("'hello world!'").run();
18 pub fn new<S: Display>(program: S) -> Self {
19 Self {
20 program: program.to_string(),
21 args: vec![],
22 }
23 }
24
25 /// Give another arg to the program we're calling
26 pub fn arg<S: Display>(mut self, s: S) -> Self {
27 self.args.push(s.to_string());
28 self
29 }
30
31 /// Execute the shell command we've defined
32 pub fn run(&self) -> String {
33 match Command::new(&self.program).args(&self.args).output() {
34 // If Ok, return stdout as String
35 Ok(o) => match from_utf8(&o.stdout) {
36 Ok(s) => s.to_string(),
37 Err(_) => String::from(""),
38 },
39 Err(_) => String::from(""),
40 }
41 }
42}