summaryrefslogtreecommitdiffstats
path: root/src/fs/metadata.rs
blob: 9f3ddd9af63544f22794c2db3c50932073679a67 (plain)
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::{fs, path, process, time};

#[derive(Clone, Debug)]
pub struct JoshutoMetadata {
    pub len: u64,
    pub modified: time::SystemTime,
    pub permissions: fs::Permissions,
    pub file_type: fs::FileType,
    pub mimetype: Option<String>,
    #[cfg(unix)]
    pub uid: u32,
    #[cfg(unix)]
    pub gid: u32,
    #[cfg(unix)]
    pub mode: u32,
}

impl JoshutoMetadata {
    pub fn from(path: &path::Path) -> std::io::Result<Self> {
        #[cfg(unix)]
        use std::os::unix::fs::MetadataExt;

        let metadata = fs::symlink_metadata(path)?;

        let len = metadata.len();
        let modified = metadata.modified()?;
        let permissions = metadata.permissions();
        let file_type = metadata.file_type();
        let mut mimetype = None;

        if file_type.is_file() {
            #[cfg(feature = "file_mimetype")]
            {
                mimetype = file_mimetype(path)
            }
        }

        #[cfg(unix)]
        let uid = metadata.uid();
        #[cfg(unix)]
        let gid = metadata.gid();
        #[cfg(unix)]
        let mode = metadata.mode();

        Ok(Self {
            len,
            modified,
            permissions,
            file_type,
            mimetype,
            #[cfg(unix)]
            uid,
            #[cfg(unix)]
            gid,
            #[cfg(unix)]
            mode,
        })
    }
}

fn file_mimetype(path: &path::Path) -> Option<String> {
    let output = process::Command::new("file")
        .args(&["-Lb", "--mime-type"])
        .arg(path)
        .output();

    match output {
        Ok(s) => {
            if s.status.success() {
                match String::from_utf8(s.stdout) {
                    Ok(s) => Some(s),
                    Err(_) => None,
                }
            } else {
                None
            }
        }
        Err(_) => None,
    }
}