Skip to content

Commit

Permalink
#414: simplify running external commands
Browse files Browse the repository at this point in the history
  • Loading branch information
andrey-kuprianov committed Aug 6, 2020
1 parent 08450a7 commit 04ab1aa
Showing 1 changed file with 52 additions and 21 deletions.
73 changes: 52 additions & 21 deletions tendermint/tests/lite_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,41 +93,72 @@ impl MockRequester {
}
}

/// Thin wrapper around process::Command to facilitate running external commands.
/// A thin wrapper around process::Command to facilitate running external commands.
pub struct Command {
pub command: process::Command,
program: Option<String>,
args: Vec<String>,
dir: Option<String>
}

impl Command {
/// Constructs a new Command for the given program with arguments.
pub fn new(program: &str, args: Vec<&str>) -> Command {
let mut command = process::Command::new(program);
command.args(args);
pub fn new() -> Command {
Command {
command
program: None,
args: vec![],
dir: None
}
}

/// Sets the program to run
pub fn program(&mut self, program: &str) -> &mut Self {
self.program = Some(program.to_owned());
self
}

/// Adds a new program argument
pub fn arg(&mut self, arg: &str) -> &mut Self {
self.args.push(arg.to_owned());
self
}

/// Adds a new program argument, concatenated from several parts
pub fn arg_from_parts(&mut self, parts: Vec<&str>) -> &mut Self {
let mut arg: String = String::new();
for part in parts {
arg = arg + part;
}
self.args.push(arg);
self
}

/// Sets the working directory for the child process
pub fn current_dir(&mut self, dir: &str) -> &mut Self {
self.command.current_dir(dir);
self.dir = Some(dir.to_owned());
self
}

/// Executes the command as a child process, and extracts its status, stdout, stderr.
pub fn spawn(&mut self) -> io::Result<CommandRun> {
let mut process = self.command
.stdout(process::Stdio::piped())
.stderr(process::Stdio::piped())
.spawn()?;
let status = process.wait()?;
let mut stdout = String::new();
process.stdout.unwrap().read_to_string(&mut stdout)?;
let mut stderr = String::new();
process.stderr.unwrap().read_to_string(&mut stderr)?;
Ok(CommandRun {
status,
stdout,
stderr
})
match &self.program {
None => Err(io::Error::new(io::ErrorKind::InvalidInput, "")),
Some(program) => {
let mut process = process::Command::new(program)
.stdout(process::Stdio::piped())
.stderr(process::Stdio::piped())
.spawn()?;
let status = process.wait()?;
let mut stdout = String::new();
process.stdout.unwrap().read_to_string(&mut stdout)?;
let mut stderr = String::new();
process.stderr.unwrap().read_to_string(&mut stderr)?;
Ok(CommandRun {
status,
stdout,
stderr
})
}
}
}
}

Expand Down

0 comments on commit 04ab1aa

Please sign in to comment.