fileinfo/
lib.rs

1mod parse;
2pub use parse::parse;
3use std::str::FromStr;
4
5#[derive(Debug, Default, PartialEq, PartialOrd)]
6pub struct FileInfo {
7    pub permissions: String,
8    pub hard_link_count: usize,
9    pub owner: String,
10    pub group: String,
11    pub size: usize,
12    pub last_modified: String,
13    pub name: String,
14    pub link: Option<String>,
15}
16
17impl FileInfo {
18    pub fn is_dir(&self) -> bool {
19        self.permissions.starts_with('d')
20    }
21
22    pub fn is_file(&self) -> bool {
23        !self.is_dir()
24    }
25
26    pub fn is_link(&self) -> bool {
27        self.permissions.starts_with('l')
28    }
29}
30
31impl<'a> TryFrom<&'a str> for FileInfo {
32    type Error = ();
33
34    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
35        parse(value).ok_or(())
36    }
37}
38
39impl FromStr for FileInfo {
40    type Err = ();
41
42    fn from_str(s: &str) -> Result<Self, Self::Err> {
43        parse(s).ok_or(())
44    }
45}
46
47#[cfg(test)]
48mod test {
49    use std::str::FromStr;
50
51    use crate::{parse, FileInfo};
52    #[test]
53    fn test() {
54        let s = "drwxr-xr-x 1 owner group         3452 Jun 11 10:15 device";
55        let info = parse(s);
56        assert_eq!(
57            info,
58            Some(FileInfo {
59                permissions: "drwxr-xr-x".to_string(),
60                hard_link_count: 1,
61                owner: "owner".to_string(),
62                group: "group".to_string(),
63                size: 3452,
64                last_modified: "Jun 11 10:15".to_string(),
65                name: "device".to_string(),
66                link: None
67            })
68        )
69    }
70
71    #[test]
72    fn test_link() {
73        let s = "lrwxrwxrwx 1 owner group           10 Jun 11 10:15 link.txt -> file1.txt";
74        let info = parse(s);
75        assert_eq!(
76            info,
77            Some(FileInfo {
78                permissions: "lrwxrwxrwx".to_string(),
79                hard_link_count: 1,
80                owner: "owner".to_string(),
81                group: "group".to_string(),
82                size: 10,
83                last_modified: "Jun 11 10:15".to_string(),
84                name: "link.txt".to_string(),
85                link: Some("file1.txt".to_string())
86            })
87        );
88    }
89
90    #[test]
91    fn test_from_str() {
92        let s = "lrwxrwxrwx 1 owner group           10 Jun 11 10:15 link.txt -> file1.txt";
93        let info = FileInfo::try_from(s);
94        assert!(info.is_ok());
95
96        let info = FileInfo::from_str(s);
97        assert!(info.is_ok());
98    }
99}