1pub use config::NO_CONFIG_FILE_FOUND;
2use std::collections::HashMap;
3use tracing::instrument;
4
5mod config;
6mod git;
7mod init_directory;
8
9mod hooks;
10pub use config::ConfigFile;
11pub use hooks::{HOOK_NAMES, NO_CONFIG_FILE_FOUND_ERROR_CODE};
12
13pub fn init<F, G, H>(
14 run_command: F,
15 write_file: G,
16 file_exists: H,
17 hook_file_skip_list: Vec<&str>,
18) -> Result<(), String>
19where
20 F: Fn(
21 &str,
22 Option<&str>,
23 bool,
24 Option<&HashMap<String, String>>,
25 ) -> Result<Option<String>, Option<String>>,
26 G: Fn(&str, &str, bool) -> Result<(), String>,
27 H: Fn(&str) -> Result<bool, ()>,
28{
29 init_directory::init_directory(
30 &run_command,
31 &write_file,
32 &file_exists,
33 None,
34 hook_file_skip_list,
35 )
36}
37
38pub async fn run<F, G, H>(
39 run_command: F,
40 file_exists: G,
41 read_file: H,
42 hook_name: &str,
43) -> Result<(), Box<dyn std::error::Error>>
44where
45 F: Fn(
46 &str,
47 Option<&str>,
48 bool,
49 Option<&HashMap<String, String>>,
50 ) -> Result<Option<String>, Option<String>>,
51 G: Fn(&str) -> Result<bool, ()>,
52 H: Fn(&str) -> Result<String, ()>,
53{
54 let root_directory_path = match git::get_root_directory_path(&run_command, None) {
55 Ok(Some(path)) => path,
56 _ => {
57 return Err(String::from("Failure determining git repo root directory"))?;
58 }
59 };
60
61 let config_file_contents =
62 config::get_config_file_contents(read_file, file_exists, &root_directory_path).map_err(
63 |e| {
64 if e == config::NO_CONFIG_FILE_FOUND {
65 e
66 } else {
67 String::from("Failed to parse config file")
68 }
69 },
70 )?;
71
72 let mut config_file = ConfigFile::try_from_str(&config_file_contents)?;
73
74 let Some(hooks) = config_file.hooks.remove(hook_name) else {
75 return Ok(());
76 };
77
78 let mut handle = tokio::task::JoinSet::new();
79
80 for xs in hooks {
81 let root_directory_path = root_directory_path.clone();
82
83 handle.spawn(async move {
84 for x in xs {
85 run_task(x, root_directory_path.clone()).await?;
86 }
87
88 Ok::<_, std::io::Error>(())
89 });
90 }
91
92 while let Some(x) = handle.join_next().await {
93 x??;
94 }
95
96 Ok(())
97}
98
99#[instrument(skip(root_directory_path), err)]
100async fn run_task(x: String, root_directory_path: String) -> Result<(), std::io::Error> {
101 tracing::info!("Running {x}");
102
103 let (envs, cmd) = parse_env_and_command(&x);
104
105 let mut args = cmd.into_iter();
106
107 let cmd = args.next().unwrap();
108
109 let mut cmd = tokio::process::Command::new(cmd);
110
111 cmd.args(args).current_dir(&root_directory_path);
112
113 if !envs.is_empty() {
114 cmd.envs(&envs);
115 }
116
117 let output = cmd.output().await?;
118
119 if !output.status.success() {
120 if !output.stdout.is_empty() {
121 tracing::error!("Stdout: {}", String::from_utf8_lossy(&output.stdout));
122 }
123
124 if !output.stderr.is_empty() {
125 tracing::error!("Stderr: {}", String::from_utf8_lossy(&output.stderr));
126 }
127
128 return Err(std::io::Error::other(format!(
129 "Command `{x}` failed with exit code {:?}",
130 output.status.code()
131 )));
132 }
133
134 tracing::info!("Finished {x}");
135
136 Ok(())
137}
138
139fn parse_env_and_command(input: &str) -> (HashMap<String, String>, Vec<String>) {
140 let mut env_vars = HashMap::new();
141 let mut command_args = Vec::new();
142
143 if let Some(parts) = shlex::split(input) {
144 let mut found_command = false;
145
146 for part in parts {
147 if !found_command
149 && part.contains('=')
150 && let Some((key, value)) = part.split_once('=')
151 {
152 if key.chars().all(|c| c.is_alphanumeric() || c == '_')
154 && !key.is_empty()
155 && !key.chars().next().unwrap().is_numeric()
156 {
157 env_vars.insert(key.to_string(), value.to_string());
158 continue;
159 }
160 }
161
162 found_command = true;
164 command_args.push(part);
165 }
166 }
167
168 (env_vars, command_args)
169}
170
171#[cfg(test)]
172mod tests;