Skip to content

Commit 2758bb5

Browse files
committed
Refactor CommandExt.
1 parent 3d4004c commit 2758bb5

File tree

1 file changed

+21
-24
lines changed

1 file changed

+21
-24
lines changed

src/extensions.rs

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,53 +3,50 @@ use std::process::{Command, ExitStatus};
33
use crate::errors::*;
44

55
pub trait CommandExt {
6+
fn print_verbose(&self, verbose: bool);
7+
fn status_result(&self, status: ExitStatus) -> Result<()>;
68
fn run(&mut self, verbose: bool) -> Result<()>;
79
fn run_and_get_status(&mut self, verbose: bool) -> Result<ExitStatus>;
810
fn run_and_get_stdout(&mut self, verbose: bool) -> Result<String>;
911
}
1012

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

20+
fn status_result(&self, status: ExitStatus) -> Result<()> {
1621
if status.success() {
1722
Ok(())
1823
} else {
19-
Err(format!("`{:?}` failed with exit code: {:?}",
20-
self,
21-
status.code()))?
24+
Err(format!("`{:?}` failed with exit code: {:?}", self, status.code()).into())
2225
}
2326
}
2427

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

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

3541
/// Runs the command to completion and returns its stdout
3642
fn run_and_get_stdout(&mut self, verbose: bool) -> Result<String> {
37-
if verbose {
38-
println!("+ {:?}", self);
39-
}
40-
43+
self.print_verbose(verbose);
4144
let out = self.output()
4245
.chain_err(|| format!("couldn't execute `{:?}`", self))?;
4346

44-
if out.status.success() {
45-
Ok(String::from_utf8(out.stdout).chain_err(|| {
46-
format!("`{:?}` output was not UTF-8",
47-
self)
48-
})?)
49-
} else {
50-
Err(format!("`{:?}` failed with exit code: {:?}",
51-
self,
52-
out.status.code()))?
53-
}
47+
self.status_result(out.status)?;
48+
49+
Ok(String::from_utf8(out.stdout)
50+
.chain_err(|| format!("`{:?}` output was not UTF-8", self))?)
5451
}
5552
}

0 commit comments

Comments
 (0)