predicates/path/
fc.rs
1use std::fmt;
10use std::fs;
11use std::io::{self, Read};
12use std::path;
13
14use crate::reflection;
15use crate::Predicate;
16
17fn read_file(path: &path::Path) -> io::Result<Vec<u8>> {
18 let mut buffer = Vec::new();
19 fs::File::open(path)?.read_to_end(&mut buffer)?;
20 Ok(buffer)
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct FileContentPredicate<P>
28where
29 P: Predicate<[u8]>,
30{
31 p: P,
32}
33
34impl<P> FileContentPredicate<P>
35where
36 P: Predicate<[u8]>,
37{
38 fn eval(&self, path: &path::Path) -> io::Result<bool> {
39 let buffer = read_file(path)?;
40 Ok(self.p.eval(&buffer))
41 }
42}
43
44impl<P> reflection::PredicateReflection for FileContentPredicate<P>
45where
46 P: Predicate<[u8]>,
47{
48 fn children<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Child<'a>> + 'a> {
49 let params = vec![reflection::Child::new("predicate", &self.p)];
50 Box::new(params.into_iter())
51 }
52}
53
54impl<P> fmt::Display for FileContentPredicate<P>
55where
56 P: Predicate<[u8]>,
57{
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(f, "{}", self.p)
60 }
61}
62
63impl<P> Predicate<path::Path> for FileContentPredicate<P>
64where
65 P: Predicate<[u8]>,
66{
67 fn eval(&self, path: &path::Path) -> bool {
68 self.eval(path).unwrap_or(false)
69 }
70
71 fn find_case<'a>(
72 &'a self,
73 expected: bool,
74 variable: &path::Path,
75 ) -> Option<reflection::Case<'a>> {
76 let buffer = read_file(variable);
77 match (expected, buffer) {
78 (_, Ok(buffer)) => self
79 .p
80 .find_case(expected, &buffer)
81 .map(|child| reflection::Case::new(Some(self), expected).add_child(child)),
82 (true, Err(_)) => None,
83 (false, Err(err)) => Some(
84 reflection::Case::new(Some(self), false)
85 .add_product(reflection::Product::new("error", err)),
86 ),
87 }
88 }
89}
90
91pub trait PredicateFileContentExt
93where
94 Self: Predicate<[u8]>,
95 Self: Sized,
96{
97 fn from_file_path(self) -> FileContentPredicate<Self> {
110 FileContentPredicate { p: self }
111 }
112}
113
114impl<P> PredicateFileContentExt for P where P: Predicate<[u8]> {}