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 
9 use std::fmt;
10 use std::path;
11 
12 use crate::reflection;
13 use crate::utils;
14 use crate::Predicate;
15 
16 /// Predicate that checks if a file is present
17 ///
18 /// This is created by the `predicate::path::exists` and `predicate::path::missing`.
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20 pub struct ExistencePredicate {
21     exists: bool,
22 }
23 
24 impl Predicate<path::Path> for ExistencePredicate {
eval(&self, path: &path::Path) -> bool25     fn eval(&self, path: &path::Path) -> bool {
26         path.exists() == self.exists
27     }
28 
find_case<'a>( &'a self, expected: bool, variable: &path::Path, ) -> Option<reflection::Case<'a>>29     fn find_case<'a>(
30         &'a self,
31         expected: bool,
32         variable: &path::Path,
33     ) -> Option<reflection::Case<'a>> {
34         utils::default_find_case(self, expected, variable).map(|case| {
35             case.add_product(reflection::Product::new(
36                 "var",
37                 variable.display().to_string(),
38             ))
39         })
40     }
41 }
42 
43 impl reflection::PredicateReflection for ExistencePredicate {}
44 
45 impl fmt::Display for ExistencePredicate {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result46     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47         let palette = crate::Palette::new(f.alternate());
48         write!(
49             f,
50             "{}({})",
51             palette.description(if self.exists { "exists" } else { "missing" }),
52             palette.var("var")
53         )
54     }
55 }
56 
57 /// Creates a new `Predicate` that ensures the path exists.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use std::path::Path;
63 /// use predicates::prelude::*;
64 ///
65 /// let predicate_fn = predicate::path::exists();
66 /// assert_eq!(true, predicate_fn.eval(Path::new("Cargo.toml")));
67 /// ```
exists() -> ExistencePredicate68 pub fn exists() -> ExistencePredicate {
69     ExistencePredicate { exists: true }
70 }
71 
72 /// Creates a new `Predicate` that ensures the path doesn't exist.
73 ///
74 /// # Examples
75 ///
76 /// ```
77 /// use std::path::Path;
78 /// use predicates::prelude::*;
79 ///
80 /// let predicate_fn = predicate::path::missing();
81 /// assert_eq!(true, predicate_fn.eval(Path::new("non-existent-file.foo")));
82 /// ```
missing() -> ExistencePredicate83 pub fn missing() -> ExistencePredicate {
84     ExistencePredicate { exists: false }
85 }
86