Skip to content

Commit

Permalink
Refactor CommandExt.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Nov 16, 2019
1 parent 3d4004c commit 2758bb5
Showing 1 changed file with 21 additions and 24 deletions.
45 changes: 21 additions & 24 deletions src/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,50 @@ use std::process::{Command, ExitStatus};
use crate::errors::*;

pub trait CommandExt {
fn print_verbose(&self, verbose: bool);
fn status_result(&self, status: ExitStatus) -> Result<()>;
fn run(&mut self, verbose: bool) -> Result<()>;
fn run_and_get_status(&mut self, verbose: bool) -> Result<ExitStatus>;
fn run_and_get_stdout(&mut self, verbose: bool) -> Result<String>;
}

impl CommandExt for Command {
/// Runs the command to completion
fn run(&mut self, verbose: bool) -> Result<()> {
let status = self.run_and_get_status(verbose)?;
fn print_verbose(&self, verbose: bool) {
if verbose {
println!("+ {:?}", self);
}
}

fn status_result(&self, status: ExitStatus) -> Result<()> {
if status.success() {
Ok(())
} else {
Err(format!("`{:?}` failed with exit code: {:?}",
self,
status.code()))?
Err(format!("`{:?}` failed with exit code: {:?}", self, status.code()).into())
}
}

/// Runs the command to completion
fn run_and_get_status(&mut self, verbose: bool) -> Result<ExitStatus> {
if verbose {
println!("+ {:?}", self);
}
fn run(&mut self, verbose: bool) -> Result<()> {
let status = self.run_and_get_status(verbose)?;
self.status_result(status)
}

/// Runs the command to completion
fn run_and_get_status(&mut self, verbose: bool) -> Result<ExitStatus> {
self.print_verbose(verbose);
self.status()
.chain_err(|| format!("couldn't execute `{:?}`", self))
}

/// Runs the command to completion and returns its stdout
fn run_and_get_stdout(&mut self, verbose: bool) -> Result<String> {
if verbose {
println!("+ {:?}", self);
}

self.print_verbose(verbose);
let out = self.output()
.chain_err(|| format!("couldn't execute `{:?}`", self))?;

if out.status.success() {
Ok(String::from_utf8(out.stdout).chain_err(|| {
format!("`{:?}` output was not UTF-8",
self)
})?)
} else {
Err(format!("`{:?}` failed with exit code: {:?}",
self,
out.status.code()))?
}
self.status_result(out.status)?;

Ok(String::from_utf8(out.stdout)
.chain_err(|| format!("`{:?}` output was not UTF-8", self))?)
}
}

0 comments on commit 2758bb5

Please sign in to comment.