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 { |
25 | fn eval(&self, path: &path::Path) -> bool { |
26 | path.exists() == self.exists |
27 | } |
28 | |
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 { |
46 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
47 | let palette = crate::Palette::current(); |
48 | write!( |
49 | f, |
50 | "{}({})" , |
51 | palette |
52 | .description |
53 | .paint(if self.exists { "exists" } else { "missing" }), |
54 | palette.var.paint("var" ) |
55 | ) |
56 | } |
57 | } |
58 | |
59 | /// Creates a new `Predicate` that ensures the path exists. |
60 | /// |
61 | /// # Examples |
62 | /// |
63 | /// ``` |
64 | /// use std::path::Path; |
65 | /// use predicates::prelude::*; |
66 | /// |
67 | /// let predicate_fn = predicate::path::exists(); |
68 | /// assert_eq!(true, predicate_fn.eval(Path::new("Cargo.toml" ))); |
69 | /// ``` |
70 | pub fn exists() -> ExistencePredicate { |
71 | ExistencePredicate { exists: true } |
72 | } |
73 | |
74 | /// Creates a new `Predicate` that ensures the path doesn't exist. |
75 | /// |
76 | /// # Examples |
77 | /// |
78 | /// ``` |
79 | /// use std::path::Path; |
80 | /// use predicates::prelude::*; |
81 | /// |
82 | /// let predicate_fn = predicate::path::missing(); |
83 | /// assert_eq!(true, predicate_fn.eval(Path::new("non-existent-file.foo" ))); |
84 | /// ``` |
85 | pub fn missing() -> ExistencePredicate { |
86 | ExistencePredicate { exists: false } |
87 | } |
88 | |