1use crate::pkg::types::{Hooks, PlatformOrStringVec};
2use crate::utils;
3use anyhow::{Result, anyhow};
4use colored::*;
5use std::process::Command;
6
7pub enum HookType {
8 PreInstall,
9 PostInstall,
10 PreUpgrade,
11 PostUpgrade,
12 PreRemove,
13 PostRemove,
14}
15
16fn execute_commands(commands: &[String]) -> Result<()> {
17 for cmd_str in commands {
18 println!("> {}", cmd_str.cyan());
19 let status = if cfg!(target_os = "windows") {
20 Command::new("pwsh").arg("-Command").arg(cmd_str).status()?
21 } else {
22 Command::new("bash").arg("-c").arg(cmd_str).status()?
23 };
24
25 if !status.success() {
26 return Err(anyhow!("Hook command failed: {}", cmd_str));
27 }
28 }
29 Ok(())
30}
31
32pub fn run_hooks(hooks: &Hooks, hook_type: HookType) -> Result<()> {
33 let platform = utils::get_platform()?;
34
35 let commands_to_run = match hook_type {
36 HookType::PreInstall => &hooks.pre_install,
37 HookType::PostInstall => &hooks.post_install,
38 HookType::PreUpgrade => &hooks.pre_upgrade,
39 HookType::PostUpgrade => &hooks.post_upgrade,
40 HookType::PreRemove => &hooks.pre_remove,
41 HookType::PostRemove => &hooks.post_remove,
42 };
43
44 if let Some(platform_or_string_vec) = commands_to_run {
45 match platform_or_string_vec {
46 PlatformOrStringVec::StringVec(cmds) => {
47 execute_commands(cmds)?;
48 }
49 PlatformOrStringVec::Platform(platform_map) => {
50 if let Some(cmds) = platform_map.get(&platform) {
51 execute_commands(cmds)?;
52 } else if let Some(cmds) = platform_map.get("default") {
53 execute_commands(cmds)?;
54 }
55 }
56 }
57 }
58
59 Ok(())
60}