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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use crate::{
error::*,
util::{collect_directory_children, fs_filetype_from_path, symlink_target},
File,
};
use std::{
fmt,
path::{Path, PathBuf},
};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FileType {
Regular,
Directory(Vec<File>),
Symlink(PathBuf),
}
impl FileType {
pub fn from_path(path: impl AsRef<Path>, follow_symlinks: bool) -> FSResult<Self> {
let result = match FileType::from_path_shallow(&path, follow_symlinks)? {
FileType::Directory(_) => {
FileType::Directory(collect_directory_children(&path, follow_symlinks)?)
},
other => other,
};
Ok(result)
}
pub fn from_path_shallow(path: impl AsRef<Path>, follow_symlink: bool) -> FSResult<Self> {
let fs_file_type = fs_filetype_from_path(&path, follow_symlink)?;
let result = {
if fs_file_type.is_file() {
FileType::Regular
} else if fs_file_type.is_dir() {
FileType::Directory(vec![])
} else if fs_file_type.is_symlink() {
FileType::Symlink(symlink_target(path)?)
} else {
todo!("Other file types.")
}
};
Ok(result)
}
pub fn is_regular(&self) -> bool {
matches!(self, FileType::Regular)
}
pub fn is_dir(&self) -> bool {
matches!(self, FileType::Directory(_))
}
pub fn is_symlink(&self) -> bool {
matches!(self, FileType::Symlink(_))
}
pub fn children(&self) -> Option<&Vec<File>> {
match self {
FileType::Directory(ref children) => Some(children),
_ => None,
}
}
}
impl Default for FileType {
fn default() -> Self {
Self::Regular
}
}
impl fmt::Display for FileType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
FileType::Regular => write!(f, "file"),
FileType::Directory(_) => write!(f, "directory"),
FileType::Symlink(_) => write!(f, "symbolic link"),
}
}
}