2022-10-30 20:14:12 +00:00
|
|
|
use std::{io::Read, process::exit};
|
|
|
|
|
|
|
|
use {
|
|
|
|
color_eyre::{eyre::eyre, Result},
|
|
|
|
hooked_library::{Config, ExitAction},
|
|
|
|
owo_colors::{OwoColorize, Style},
|
|
|
|
subprocess::{Exec, Redirection},
|
|
|
|
};
|
|
|
|
|
|
|
|
pub fn hooked_run(config: Config, hook_type: String) -> Result<()> {
|
|
|
|
let success_style = Style::new().bold().green();
|
|
|
|
let warn_style = Style::new().bold().yellow();
|
|
|
|
let error_style = Style::new().bold().red();
|
|
|
|
|
|
|
|
if hook_type == "pre-commit" {
|
2022-10-31 10:36:55 +00:00
|
|
|
println!(
|
|
|
|
"Hooked: Running {} pre-commit hooks.",
|
|
|
|
config.pre_commit.len()
|
|
|
|
);
|
|
|
|
|
2022-10-30 20:14:12 +00:00
|
|
|
for hook in config.pre_commit {
|
|
|
|
let hook_name = hook.name.unwrap_or_else(|| "Unnamed Hook".to_string());
|
|
|
|
|
|
|
|
let command = match (hook.task.command, hook.task.script) {
|
|
|
|
(Some(command), _) => Ok(Exec::shell(command)),
|
|
|
|
|
|
|
|
(None, Some(script_file)) => {
|
|
|
|
let script_path = config.general.directory.join(script_file);
|
|
|
|
let script_path_str = script_path
|
|
|
|
.to_str()
|
|
|
|
.ok_or_else(|| eyre!("Failed to convert path to str"))?;
|
|
|
|
Ok(Exec::shell(script_path_str))
|
|
|
|
}
|
|
|
|
|
|
|
|
(None, None) => Err(eyre!(
|
|
|
|
"No command or script provided for hook: {}",
|
|
|
|
hook_name
|
|
|
|
)),
|
|
|
|
}?;
|
|
|
|
|
2022-10-31 10:45:36 +00:00
|
|
|
let mut process = command
|
|
|
|
.stderr(Redirection::Merge)
|
|
|
|
.stdout(Redirection::Pipe)
|
|
|
|
.popen()?;
|
2022-10-30 20:14:12 +00:00
|
|
|
let exit_status = process.wait()?;
|
|
|
|
let output = {
|
|
|
|
let mut output = String::new();
|
|
|
|
let mut stdout_file = process.stdout.take().unwrap();
|
|
|
|
stdout_file.read_to_string(&mut output)?;
|
|
|
|
output
|
|
|
|
};
|
|
|
|
|
2022-10-31 10:45:36 +00:00
|
|
|
let (stop, print_output, prefix, style) =
|
|
|
|
match (exit_status.success(), hook.on_failure) {
|
|
|
|
(true, _) => (false, false, "✓", success_style),
|
|
|
|
(false, ExitAction::Continue) => (false, true, "⚠", warn_style),
|
|
|
|
(false, ExitAction::Stop) => (true, true, "✗", error_style),
|
|
|
|
};
|
2022-10-30 20:14:12 +00:00
|
|
|
|
|
|
|
println!("\t{} {}", prefix.style(style), hook_name.style(style));
|
2022-10-31 10:45:36 +00:00
|
|
|
if !output.is_empty() && print_output {
|
|
|
|
println!("{}", output);
|
|
|
|
}
|
2022-10-30 20:14:12 +00:00
|
|
|
|
|
|
|
if stop {
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|