1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::path::Path;
use std::{fs, io};
use crate::core::Match;
use super::Expectation;
/// How an [`FileExistsMatcher`] should match.
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum FileExistsMode {
/// Succeeds if the file exists.
///
/// This mode follows symlinks.
Exists,
/// Succeeds if the file exists and is a regular file.
///
/// This mode follows symlinks.
RegularFile,
/// Succeeds if the file exists and is a directory.
///
/// This mode follows symlinks.
Directory,
/// Succeeds if the file exists and is a symbolic link.
Symlink,
}
/// The matcher for [`be_existing_file`], [`be_regular_file`], [`be_directory`], and [`be_symlink`].
///
/// [`be_existing_file`]: crate::be_existing_file
/// [`be_regular_file`]: crate::be_regular_file
/// [`be_directory`]: crate::be_directory
/// [`be_symlink`]: crate::be_symlink
#[derive(Debug)]
pub struct FileExistsMatcher {
mode: FileExistsMode,
}
impl FileExistsMatcher {
/// Create a new [`FileExistsMatcher`] with the given `mode`.
pub fn new(mode: FileExistsMode) -> Self {
Self { mode }
}
}
impl<Actual> Match<Actual> for FileExistsMatcher
where
Actual: AsRef<Path>,
{
type Fail = Expectation<Actual>;
fn matches(&mut self, actual: &Actual) -> crate::Result<bool> {
let metadata_result = if self.mode == FileExistsMode::Symlink {
fs::symlink_metadata(actual)
} else {
fs::metadata(actual.as_ref())
};
let metadata = match metadata_result {
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(error.into()),
Ok(metadata) => metadata,
};
match self.mode {
FileExistsMode::Exists => Ok(true),
FileExistsMode::RegularFile if metadata.is_file() => Ok(true),
FileExistsMode::Directory if metadata.is_dir() => Ok(true),
FileExistsMode::Symlink if metadata.is_symlink() => Ok(true),
_ => Ok(false),
}
}
fn fail(self, actual: Actual) -> Self::Fail {
Expectation { actual }
}
}