GitPolicyEnforcer/
lib.rs

1pub mod loggers;
2pub mod structs;
3pub mod traits;
4pub mod validators;
5
6use std::error::Error;
7use std::fs::File;
8use std::io::{BufReader, Read};
9use std::path::Path;
10use structs::*;
11
12pub fn parse_rules<P: AsRef<Path>>(path: P) -> Result<Rules, Box<dyn Error>> {
13    let file = File::open(path)?;
14    let reader = BufReader::new(file);
15
16    // Read the JSON contents of the file as an instance of `User`.
17    let rules: Rules = serde_json::from_reader(reader)?;
18    Ok(rules)
19}
20
21pub fn get_hook(path: &str) -> Hook {
22    // The path is like this /aa/bbb/
23    let parts: Vec<&str> = path
24        .split('/')
25        .collect::<Vec<&str>>()
26        .iter()
27        .filter(|value| !value.is_empty())
28        .copied()
29        .collect();
30    Hook::from(*parts.last().unwrap_or(&""))
31}
32
33pub fn get_stdin_data() -> String {
34    let mut stdin_input = String::new();
35    let stdin = std::io::stdin();
36    let mut stdin_handle = stdin.lock();
37    stdin_handle.read_to_string(&mut stdin_input).unwrap();
38    stdin_input = stdin_input.replace('\n', "");
39    stdin_input
40}
41
42pub fn get_repo_path(input: &str) -> String {
43    // Remove everything after .git, if exists and return the first part.
44    let parts: Vec<&str> = input.split(".git").collect();
45    return format!("{}.git", parts[0]);
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51    use crate::loggers::get_logging_directory;
52
53    #[test]
54    fn test_get_path() {
55        let path_str = "/home/user/repo.git";
56        assert_eq!(get_repo_path(path_str), path_str);
57
58        let path_str = "/home/user/repo.git/";
59        assert_eq!(get_repo_path(path_str), "/home/user/repo.git");
60
61        let path_str = "/home/user/repo.git/foo/bar";
62        assert_eq!(get_repo_path(path_str), "/home/user/repo.git");
63
64        let path_str = "/var/opt/gitlab/git-data/repositories/@hashed/4b/22/4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a.git/custom_hooks";
65        assert_eq!(
66            get_repo_path(path_str),
67            "/var/opt/gitlab/git-data/repositories/@hashed/4b/22/4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a.git"
68        );
69    }
70
71    #[test]
72    fn test_get_logging_directory() {
73        assert_eq!(get_logging_directory(), "./GitPolicyEnforcer".to_owned());
74    }
75}