collective_score_client/validator/
file.rs

1use anyhow::{bail, Context, Result};
2use std::{fs, path::PathBuf};
3
4use super::{string_content::StringContent, Validator};
5
6// TODO: Why 'a has to be 'static?
7// pub struct FileContent<'a> {
8//     pub file: &'a Path,
9//     pub expected: StringContent<'a>,
10// }
11pub struct FileContent<'a> {
12    pub file: PathBuf,
13    pub expected: StringContent<'a>,
14}
15
16impl<'a> Validator for FileContent<'a> {
17    fn validate(&self) -> Result<()> {
18        // TODO: Improve this conversion from files not containing valid UTF-8.
19        let content = fs::read(&self.file).with_context(|| {
20            format!(
21                "Failed to read the content of the file {}!",
22                self.file.display()
23            )
24        })?;
25
26        let content = String::from_utf8_lossy(&content);
27
28        if !self.expected.is_match(&content) {
29            bail!("Content mismatch for the file {}!", self.file.display());
30        }
31
32        Ok(())
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use std::path::PathBuf;
39
40    use crate::{
41        check::{Check, RunnableCheck},
42        validator::string_content::StringContent,
43    };
44
45    use super::FileContent;
46
47    #[test]
48    fn file() {
49        Check::builder()
50            .description("Checking src/validator/mod.rs")
51            .validator(FileContent {
52                file: PathBuf::from("src/validator/mod.rs"),
53                expected: StringContent::Part("pub mod file;\n"),
54            })
55            .build()
56            .run()
57            .unwrap()
58    }
59}