Skip to content

Commit

Permalink
refactor: extract common part of exec_checkall and exec_checkerr
Browse files Browse the repository at this point in the history
  • Loading branch information
rami3l committed Dec 19, 2020
1 parent ed0d85f commit 64e2a72
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 24 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ authors = ["Rami3L <[email protected]>"]
description = "A pacman-like wrapper for many package managers."
edition = "2018"
name = "pacaptr"
version = "0.9.1"
version = "0.9.2"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
46 changes: 24 additions & 22 deletions src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,26 @@ impl<S: AsRef<OsStr>> Cmd<S> {
}
}

/// Helper macro to implement `exec_checkerr` and `exec_checkall`.
/// Take contents from the input stream `$src` and copy to `$out1` and `$out2`,
/// and finally return `$out2`.
/// The boolean `$mute1` decides whether to mute `$out1`.
macro_rules! exec_tee {
( $src:expr, $out1:expr, $out2:expr, $mute1:expr ) => {{
while let Some(mb) = $src.next().await {
let b = mb?;
let b = b.as_ref();
if $mute1 {
$out2.write_all(b).await?;
} else {
try_join!($out1.write_all(b), $out2.write_all(b))?;
}
}

$out2
}};
}

impl<S: AsRef<OsStr> + AsRef<str>> Cmd<S> {
/// Execute a command and return a `Result<Vec<u8>, _>`.
/// The exact behavior depends on the `mode` passed in.
Expand Down Expand Up @@ -182,19 +202,10 @@ impl<S: AsRef<OsStr> + AsRef<str>> Cmd<S> {

let mut out = Vec::<u8>::new();
let mut stdout = tokio::io::stdout();

while let Some(mb) = merged_reader.next().await {
let b = mb?;
let b = b.as_ref();
if mute {
out.write_all(b).await?;
} else {
try_join!(stdout.write_all(b), out.write_all(b))?;
}
}
let contents = exec_tee!(merged_reader, stdout, out, mute);

Ok(Output {
contents: out,
contents,
code: code.await.unwrap()?,
})
}
Expand Down Expand Up @@ -223,19 +234,10 @@ impl<S: AsRef<OsStr> + AsRef<str>> Cmd<S> {

let mut out = Vec::<u8>::new();
let mut stderr = tokio::io::stderr();

while let Some(mb) = stderr_reader.next().await {
let b = mb?;
let b = b.as_ref();
if mute {
out.write_all(b).await?;
} else {
try_join!(stderr.write_all(b), out.write_all(b))?;
}
}
let contents = exec_tee!(stderr_reader, stderr, out, mute);

Ok(Output {
contents: out,
contents,
code: code.await.unwrap()?,
})
}
Expand Down

0 comments on commit 64e2a72

Please sign in to comment.