krankerl/packaging/
commands.rs

1use std::convert::From;
2use std::path::Path;
3use std::process::Command;
4use std::vec::Vec;
5
6use color_eyre::{Report, Result};
7
8use crate::config::app::PackageConfig;
9use color_eyre::eyre::WrapErr;
10
11pub trait PackageCommands {
12    fn execute(&self, cwd: &Path) -> Result<()>;
13}
14
15#[derive(Debug)]
16pub struct CommandList {
17    cmds: Vec<String>,
18}
19
20impl PackageCommands for CommandList {
21    fn execute(&self, cwd: &Path) -> Result<()> {
22        println!("Executing packaging commands...");
23        for cmd in &self.cmds {
24            println!("Running `{}`...", cmd);
25            Command::new("sh")
26                .arg("-c")
27                .arg(cmd)
28                .current_dir(cwd)
29                .output()
30                .wrap_err_with(|| format!("Cannot start command <{}>: ", cmd))
31                .and_then(|output| {
32                    if output.status.success() {
33                        Ok(())
34                    } else {
35                        match output.status.code() {
36                            Some(code) => Err(Report::msg(format!(
37                                "Command <{}> returned exit status {:?}\n\nstdout: {}\nstderr: {}",
38                                cmd,
39                                code,
40                                String::from_utf8_lossy(&output.stdout),
41                                String::from_utf8_lossy(&output.stderr)
42                            ))),
43                            None => Err(Report::msg(format!(
44                                "Command <{}> was aborted by a signal",
45                                cmd
46                            ))),
47                        }
48                    }
49                })?;
50        }
51        println!("Executed all packaging commands.");
52        Ok(())
53    }
54}
55
56impl<'a> From<&'a PackageConfig> for CommandList {
57    fn from(config: &'a PackageConfig) -> Self {
58        CommandList {
59            cmds: config.before_cmds().clone(),
60        }
61    }
62}
63
64impl From<PackageConfig> for CommandList {
65    fn from(config: PackageConfig) -> Self {
66        CommandList {
67            cmds: config.before_cmds().clone(),
68        }
69    }
70}