path_filetype/lib.rs
1/*!
2# Path FileType
3If you don't know chinese, the next may give you a chance to learn chinses.
4
5在有一个确定的路径时,如何获得此路径是哪种文件类型,这就是这个库完成的工作。
6
7它提供了一个特性`PathFileType`,使你可以直接在使用 Path 类型时,通过 p.filetype()
8来获得此路径的文件类型(万物皆文件)。
9```rust
10#[cfg(unix)]
11pub enum FileType {
12 Regular,
13 Directory,
14 Symlink,
15 CharDevice,
16 BlockDevice,
17 Fifo,
18 Socket,
19}
20```
21
22其只支持 Uinx 类系统,因为目前我只在 Linux 上有使用的需要,后续将继续完善,添加
23常用系统,如 MacOS、Windows 的支持。
24
25## 示例
26下面是一些简单的例子,使用很方便。
27
28### 获取文件类型
29这是一个简单的示例,例在此项目的根目录里,有一个 data 目录,其里面有一个普通
30文件,在测试时还会创建一个链接文件(用完即删)。
31
32```rust
33extern crate path_filetype;
34
35use std::path::Path;
36
37use path_filetype::*;
38
39let _not_exist = Path::new("not_exist_path");
40let _dir = Path::new("data");
41let _regular_file = Path::new("data/regular_file");
42
43// 若文件不存在,则返回为 ErrorKind::NotFound
44assert_eq!("entity not found", format!("{}", _not_exist.filetype().unwrap_err()));
45
46// 判断是否为普通文件
47if let Ok(regular_file) = _regular_file.filetype() {
48 assert_eq!(regular_file, FileType::Regular);
49}
50
51// 判断是否为目录
52assert_eq!(_dir.filetype().unwrap(), FileType::Directory);
53
54// 创建一个链接文件,并检测其文件类型
55#[cfg(unix)]
56{
57 use std::os::unix::fs;
58 use std::fs::remove_file;
59
60 let _symlink_file = Path::new("data/symlink_file");
61 let _ = fs::symlink("regular_file", _symlink_file);
62
63 assert_eq!(_symlink_file.filetype().unwrap(), FileType::Symlink);
64
65 let _ = remove_file(_symlink_file);
66}
67```
68
69此外,亦可直接对期望类型进行判断,提供 `is_symlink()`、`is_char_device()`、
70`is_block_device()`、`is_fifo()`、`is_socket()`方法,返回值为`bool`:
71```rust
72extern crate path_filetype;
73
74use std::path::Path;
75
76use path_filetype::*;
77
78#[cfg(unix)]
79{
80 use std::os::unix::fs;
81 use std::fs::remove_file;
82
83 let _symlink_file = Path::new("data/symlink_file");
84 let _ = fs::symlink("regular_file", _symlink_file);
85
86 assert_eq!(_symlink_file.is_symlink(), true);
87
88 // Path 中原提供的`is_file()`和`is_dir()`方法不能判断链接
89 assert_eq!(_symlink_file.is_file(), true);
90
91 let _ = remove_file(_symlink_file);
92}
93```
94## 注意
95下面几项,在使用时需要注意一下:
96 * `Path`中原有的`is_file()`和`is_dir()`方法,不能用来判断路径是否为链接文件。
97*/
98#[cfg(unix)]
99pub mod unix;
100
101#[cfg(unix)]
102pub use unix::*;
103
104// TODO: Windows