feat: better shelling out

This commit is contained in:
əlemi 2024-02-13 22:32:25 +01:00
parent dcc4dda7c9
commit c07f4ed1e7
Signed by: alemi
GPG key ID: A4895B84D311642C

View file

@ -1,4 +1,4 @@
use std::path::PathBuf; use std::{path::PathBuf, process::Command};
use git2::{Config, Repository}; use git2::{Config, Repository};
@ -15,6 +15,12 @@ enum TciError {
#[error("git error")] #[error("git error")]
GitError(#[from] git2::Error), GitError(#[from] git2::Error),
#[error("subprocess finished with non-zero exit code")]
SubprocessError(i32),
#[error("subprocess terminated")]
SubprocessTerminated,
} }
#[derive(Debug, Default, serde::Deserialize)] #[derive(Debug, Default, serde::Deserialize)]
@ -54,20 +60,12 @@ fn main() {
} }
} }
fn shell<S : AsRef<std::ffi::OsStr>>(cmd: S) -> std::io::Result<String> { fn shell_out<S : AsRef<std::ffi::OsStr>>(cmd: S) -> Result<(), TciError> {
let output = std::process::Command::new(cmd).output()?; match std::process::Command::new(cmd).status()?.code() {
Some(0) => Ok(()),
let stderr = match std::str::from_utf8(&output.stderr) { Some(x) => Err(TciError::SubprocessError(x)),
Ok(s) => s.to_string(), None => Err(TciError::SubprocessTerminated),
Err(_) => format!("{:?}", output.stderr), }
};
let stdout = match std::str::from_utf8(&output.stdout) {
Ok(s) => s.to_string(),
Err(_) => format!("{:?}", output.stdout),
};
Ok(format!("{stderr}{stdout}"))
} }
fn tci(cfg: TciConfig) -> Result<(), Box<dyn std::error::Error>> { fn tci(cfg: TciConfig) -> Result<(), Box<dyn std::error::Error>> {
@ -84,15 +82,15 @@ fn tci(cfg: TciConfig) -> Result<(), Box<dyn std::error::Error>> {
// run hooks // run hooks
for setup in cfg.setup { for setup in cfg.setup {
print!("[+] setting up ({setup})"); println!("[+] setting up ({setup})");
println!("{}", shell(setup)?); shell_out(setup)?;
} }
let res = tci_hook(&repo_path, &tci_script); let res = tci_hook(&repo_path, &tci_script);
for cleanup in cfg.cleanup { for cleanup in cfg.cleanup {
print!("[-] cleaning up ({cleanup}) "); println!("[-] cleaning up ({cleanup}) ");
println!("{}", shell(cleanup)?); shell_out(cleanup)?;
} }
res?; // only check error AFTER running cleanup hooks res?; // only check error AFTER running cleanup hooks
@ -126,13 +124,10 @@ fn tci_hook(repo_path: &PathBuf, tci_script: &str) -> Result<(), TciError> {
return Err(TciError::MissingScript); return Err(TciError::MissingScript);
} }
std::env::set_current_dir(tmp.path())?;
println!("[=] running tci script for repo '{name}'"); println!("[=] running tci script for repo '{name}'");
let res = shell(tmp.path().join(tci_script))?; std::env::set_current_dir(tmp.path())?;
println!("[:] {}", res.replace('\n', "\n[:]")); let res = shell_out(tmp.path().join(tci_script));
std::env::set_current_dir(repo_path)?; std::env::set_current_dir(repo_path)?;
Ok(()) res
} }