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)
35 }
36}
37
38impl reflection::PredicateReflection for ExistencePredicate {}
39
40impl fmt::Display for ExistencePredicate {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 write!(f, "{}(var)", if self.exists { "exists" } else { "missing" })
43 }
44}
45
46/// Creates a new `Predicate` that ensures the path exists.
47///
48/// # Examples
49///
50/// ```
51/// use std::path::Path;
52/// use predicates::prelude::*;
53///
54/// let predicate_fn = predicate::path::exists();
55/// assert_eq!(true, predicate_fn.eval(Path::new("Cargo.toml")));
56/// ```
57pub fn exists() -> ExistencePredicate {
58 ExistencePredicate { exists: true }
59}
60
61/// Creates a new `Predicate` that ensures the path doesn't exist.
62///
63/// # Examples
64///
65/// ```
66/// use std::path::Path;
67/// use predicates::prelude::*;
68///
69/// let predicate_fn = predicate::path::missing();
70/// assert_eq!(true, predicate_fn.eval(Path::new("non-existent-file.foo")));
71/// ```
72pub fn missing() -> ExistencePredicate {
73 ExistencePredicate { exists: false }
74}