Skip to content

Commit

Permalink
fix(lib): simplify and improve sh! macro
Browse files Browse the repository at this point in the history
instead of trying to manually parse the script and potentially making errors,
let the actual `sh` command do the work correctly
  • Loading branch information
jackstar12 committed Aug 26, 2023
1 parent ef42bf4 commit 361a5db
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions coffee_lib/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,27 @@ macro_rules! error {
macro_rules! sh {
($root: expr, $script:expr, $verbose:expr) => {{
let script = $script.trim();
let cmds = script.split("\n"); // Check if the script contains `\`
log::debug!("cmds: {:?}", cmds);
for cmd in cmds {
log::debug!("cmd {:?}", cmd);
let cmd_tok: Vec<&str> = cmd.split(" ").collect();
let command = cmd_tok.first().unwrap().to_string();
let mut cmd = Command::new(command);
cmd.args(&cmd_tok[1..cmd_tok.len()]);
cmd.current_dir($root);
let command = if $verbose {
cmd.spawn()
.expect("Unable to run the command")
.wait_with_output()
.await?
} else {
cmd.output().await?
};
log::debug!("script: {:?}", script);

if !command.status.success() {
let mut content = String::from_utf8(command.stderr).unwrap();
if content.trim().is_empty() {
content = String::from_utf8(command.stdout).unwrap();
}
return Err(CoffeeError::new(2, &content));
let mut cmd = Command::new("sh");
cmd.args(&["-c", &script]);
cmd.current_dir($root);

let command = if $verbose {
cmd.spawn()
.expect("Unable to run the command")
.wait_with_output()
.await?
} else {
cmd.output().await?
};

if !command.status.success() {
let mut content = String::from_utf8(command.stderr).unwrap();
if content.trim().is_empty() {
content = String::from_utf8(command.stdout).unwrap();
}
return Err(CoffeeError::new(2, &content));
}
}};

Expand Down

0 comments on commit 361a5db

Please sign in to comment.