Skip to main content

grant/
validate.rs

1use crate::config::Config;
2use ansi_term::Colour::{Green, Red};
3use anyhow::{anyhow, Result};
4use std::path::{Path, PathBuf};
5use walkdir::WalkDir;
6
7/// Validate the target PathBuf
8pub fn validate_target(target: &Path) -> Result<()> {
9    let target = PathBuf::from(target);
10
11    if !target.exists() {
12        return Err(anyhow!(
13            "{:?} ... {} - file/directory does not exist",
14            target,
15            Red.paint("Failed")
16        ));
17    }
18
19    // Scan all files recursive from current directory
20    // that match *.yaml or *.yml and validate them
21    if target.is_dir() {
22        let mut files = vec![];
23        for entry in WalkDir::new(target) {
24            let entry = entry?;
25            if entry.path().is_file() {
26                if let Some(file_name) = entry.path().file_name() {
27                    if let Some(name_str) = file_name.to_str() {
28                        if name_str.ends_with(".yaml") || name_str.ends_with(".yml") {
29                            let path = entry.path().to_path_buf();
30                            files.push(path);
31                        }
32                    }
33                }
34            }
35        }
36
37        // Collect all validation errors
38        let mut errors = vec![];
39        for file in &files {
40            if let Err(e) = validate_file(file) {
41                println!("{}", e);
42                errors.push(file.clone());
43            }
44        }
45
46        // Return error if any files failed validation
47        if !errors.is_empty() {
48            return Err(anyhow!(
49                "{} - {} file(s) failed validation",
50                Red.paint("Failed"),
51                errors.len()
52            ));
53        }
54
55        return Ok(());
56    }
57
58    // Validate single file
59    validate_file(&target)
60}
61
62/// Validate target yaml file
63pub fn validate_file(file: &Path) -> Result<()> {
64    let file = PathBuf::from(file);
65    let value = Config::new(&file)
66        .map_err(|e| anyhow!("{:?} ... {} - {}", file, Red.paint("invalid"), e))?;
67
68    value
69        .validate()
70        .map_err(|e| anyhow!("{:?} ... {} - {}", file, Red.paint("invalid"), e))?;
71
72    // "OK" in green color
73    println!("{:?} ... {}", file, Green.paint("ok"));
74
75    Ok(())
76}