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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//! This crate grants a enum with one variant for each file type.
//!
//! **Cross-platform and small**, this crate has a single file with around _150_
//! lines of source code. Simplest implementation, should be in `std`. If you
//! want to check file types, here's a _enum_ for you, don't rewrite it.
//!
//! # Enum FileType:
//! ```rust
//! pub enum FileType {
//!     File,
//!     Directory,
//!     Symlink,
//!     BlockDevice, // unix only
//!     CharDevice,  // unix only
//!     Fifo,        // unix only
//!     Socket,      // unix only
//! }
//! ```
//!
//! # Examples:
//! ```rust
//! use file_type_enum::FileType;
//!
//! fn main() {
//!     let path = "/tmp";
//!     let file_type = FileType::from_path(path).unwrap();
//!
//!     println!("There's a {} at {}!", file_type, path);
//!     // Outputs: "There's a directory at /tmp!"
//! }
//! ```
//!
//! Note: `FileType::from_path(path)` returns a io::Error if:
//! * Path does not exist.
//! * The user lacks permissions to read metadata on the path.
//!
//! ---
//!
//! For each variant, there's a short hand `.is_VARIANT()`:
//!
//! `file_type.is_file()`      for `FileType::File`,
//! `file_type.is_directory()` for `FileType::Directory`,
//! `file_type.is_symlink()`   for `FileType::Symlink`,
//! _And so on..._
//!
//! ```rust
//! use file_type_enum::FileType;
//!
//! fn main() {
//!     let path = ".git";
//!     let file_type = FileType::from_path(path).unwrap();
//!
//!     if file_type.is_directory() {
//!         println!("We are at the root a git repository.");
//!     }
//! }
//! ```
//!
//! ---
//!
//! By default, if `path` points to _symlink_ `FileType::from_path()` considers
//! the path at the symlink's target location (this implies that the returned
//! file type can't be `FileType::Symlink`).
//!
//! If you don't wanna follow _symlinks_, use `FileType::from_symlink_path`
//! instead, this function may return `Ok(FileType::Symlink)`.
//!
//! ```rust
//! use file_type_enum::FileType;
//!
//! fn main() {
//!     let path = "/dev/stdout";
//!     let file_type = FileType::from_symlink_path(path).unwrap();
//!
//!     println!("There's a {} at {}!", file_type, path);
//!     // Outputs: "There's a symbolic link at /dev/stdout!"
//! }
//! ```
//!
//! ---
//!
//! `FileType::from::<fs::FileType>(fs_ft)` is also available.
//!
//! # Helping and contributing:
//! It's easy to contribute to this crate, here are some options:
//! - Share it to a friend.
//! - Help improve this README.md, even with little details.
//! - Open issues to the repository.
//! - Leave a star on GitHub.
//! - Use it!

use std::{fmt, fs, io, path::Path};

#[cfg(unix)]
use std::os::unix::fs::FileTypeExt;

/// # Variants:
///
/// ```ignore
/// match file_type {
///     FileType::File        => { /* ... */ },
///     FileType::Directory   => { /* ... */ },
///     FileType::Symlink     => { /* ... */ },
///     FileType::BlockDevice => { /* ... */ },
///     FileType::CharDevice  => { /* ... */ },
///     FileType::Fifo        => { /* ... */ },
///     FileType::Socket      => { /* ... */ },
/// }
/// ```
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy, Ord, PartialOrd)]
pub enum FileType {
    File,
    Directory,
    Symlink,
    #[cfg(unix)]
    BlockDevice,
    #[cfg(unix)]
    CharDevice,
    #[cfg(unix)]
    Fifo,
    #[cfg(unix)]
    Socket,
}

impl FileType {
    /// Try to get `FileType` from a path.
    ///
    /// This function follows symlinks, so it can never return a
    /// FileType::Symlink.
    pub fn from_path(path: &dyn AsRef<Path>) -> Result<Self, io::Error> {
        let fs_file_type = fs::metadata(path.as_ref())?.file_type();
        let result = FileType::from(fs_file_type);
        Ok(result)
    }

    /// Try to get `FileType` from a path.
    ///
    /// Don't follow symlinks, so the result can be the variant
    /// `FileType::Symlink` too.
    pub fn from_symlink_path(path: &dyn AsRef<Path>) -> Result<Self, io::Error> {
        let fs_file_type = fs::symlink_metadata(path.as_ref())?.file_type();
        let result = FileType::from(fs_file_type);
        Ok(result)
    }

    pub fn is_file(&self) -> bool {
        match self {
            FileType::File => true,
            _ => false,
        }
    }

    pub fn is_directory(&self) -> bool {
        match self {
            FileType::Directory => true,
            _ => false,
        }
    }

    pub fn is_symlink(&self) -> bool {
        match self {
            FileType::Symlink => true,
            _ => false,
        }
    }

    #[cfg(unix)]
    pub fn is_block_device(&self) -> bool {
        match self {
            FileType::BlockDevice => true,
            _ => false,
        }
    }

    #[cfg(unix)]
    pub fn is_char_device(&self) -> bool {
        match self {
            FileType::CharDevice => true,
            _ => false,
        }
    }

    #[cfg(unix)]
    pub fn is_fifo(&self) -> bool {
        match self {
            FileType::Fifo => true,
            _ => false,
        }
    }

    #[cfg(unix)]
    pub fn is_socket(&self) -> bool {
        match self {
            FileType::Socket => true,
            _ => false,
        }
    }
}

impl From<fs::FileType> for FileType {
    fn from(ft: fs::FileType) -> Self {
        // Check each type, except for symlink, because fs::metadata() follows symlinks
        #[cfg(unix)]
        let result = {
            if ft.is_file() {
                FileType::File
            } else if ft.is_dir() {
                FileType::Directory
            } else if ft.is_symlink() {
                FileType::Symlink
            } else if ft.is_block_device() {
                FileType::BlockDevice
            } else if ft.is_char_device() {
                FileType::CharDevice
            } else if ft.is_fifo() {
                FileType::Fifo
            } else if ft.is_socket() {
                FileType::Socket
            } else {
                panic!();
            }
        };

        #[cfg(windows)]
        let result = {
            if ft.is_file() {
                FileType::File
            } else if ft.is_dir() {
                FileType::Directory
            } else if ft.is_symlink() {
                FileType::Symlink
            } else {
                panic!();
            }
        };

        result
    }
}

impl fmt::Display for FileType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            FileType::File => write!(f, "regular file"),
            FileType::Directory => write!(f, "directory"),
            FileType::Symlink => write!(f, "symbolic link"),
            #[cfg(unix)]
            FileType::BlockDevice => write!(f, "block device"),
            #[cfg(unix)]
            FileType::CharDevice => write!(f, "char device"),
            #[cfg(unix)]
            FileType::Fifo => write!(f, "FIFO"),
            #[cfg(unix)]
            FileType::Socket => write!(f, "socket"),
        }
    }
}