predicates/path/
existence.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::path;
11
12use crate::reflection;
13use crate::utils;
14use 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)]
20pub struct ExistencePredicate {
21    exists: bool,
22}
23
24impl 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
43impl reflection::PredicateReflection for ExistencePredicate {}
44
45impl fmt::Display for ExistencePredicate {
46    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/// ```
68pub 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/// ```
83pub fn missing() -> ExistencePredicate {
84    ExistencePredicate { exists: false }
85}