predicates/path/
fc.rs

1// Copyright (c) 2018 The predicates-rs Project Developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use 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/// Predicate adapter that converts a `path` predicate to a byte predicate on its content.
24///
25/// This is created by `pred.from_path()`.
26#[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
91/// `Predicate` extension adapting a `slice` Predicate.
92pub trait PredicateFileContentExt
93where
94    Self: Predicate<[u8]>,
95    Self: Sized,
96{
97    /// Returns a `FileContentPredicate` that adapts `Self` to a file content `Predicate`.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// use predicates::prelude::*;
103    /// use std::path::Path;
104    ///
105    /// let predicate_fn = predicate::str::is_empty().not().from_utf8().from_file_path();
106    /// assert_eq!(true, predicate_fn.eval(Path::new("./tests/hello_world")));
107    /// assert_eq!(false, predicate_fn.eval(Path::new("./tests/empty_file")));
108    /// ```
109    fn from_file_path(self) -> FileContentPredicate<Self> {
110        FileContentPredicate { p: self }
111    }
112}
113
114impl<P> PredicateFileContentExt for P where P: Predicate<[u8]> {}