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};
@ -15,6 +15,12 @@ enum TciError {
#[error("git error")]
GitError(#[from] git2::Error),
#[error("subprocess finished with non-zero exit code")]
SubprocessError(i32),
#[error("subprocess terminated")]
SubprocessTerminated,
}
#[derive(Debug, Default, serde::Deserialize)]
@ -54,20 +60,12 @@ fn main() {
}
}
fn shell<S : AsRef<std::ffi::OsStr>>(cmd: S) -> std::io::Result<String> {
let output = std::process::Command::new(cmd).output()?;
let stderr = match std::str::from_utf8(&output.stderr) {
Ok(s) => s.to_string(),
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 shell_out<S : AsRef<std::ffi::OsStr>>(cmd: S) -> Result<(), TciError> {
match std::process::Command::new(cmd).status()?.code() {
Some(0) => Ok(()),
Some(x) => Err(TciError::SubprocessError(x)),
None => Err(TciError::SubprocessTerminated),
}
}
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
for setup in cfg.setup {
print!("[+] setting up ({setup})");
println!("{}", shell(setup)?);
println!("[+] setting up ({setup})");
shell_out(setup)?;
}
let res = tci_hook(&repo_path, &tci_script);
for cleanup in cfg.cleanup {
print!("[-] cleaning up ({cleanup}) ");
println!("{}", shell(cleanup)?);
println!("[-] cleaning up ({cleanup}) ");
shell_out(cleanup)?;
}
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);
}
std::env::set_current_dir(tmp.path())?;
println!("[=] running tci script for repo '{name}'");
let res = shell(tmp.path().join(tci_script))?;
println!("[:] {}", res.replace('\n', "\n[:]"));
std::env::set_current_dir(tmp.path())?;
let res = shell_out(tmp.path().join(tci_script));
std::env::set_current_dir(repo_path)?;
Ok(())
res
}