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 {
    /// Recursively creates `FileType` from path.
    ///
    /// # Example
    /// ```
    /// use file_structure::{FileType, FSError};
    ///
    /// fn main() -> Result<(), FSError> {
    ///     let file_type = FileType::from_path("src/", true)?;
    ///
    ///     if let FileType::Directory(ref children) = file_type {
    ///         println!("We found {} files!", children.len()); // vec.len()
    ///
    ///         for child in children {
    ///             println!("{:#?}", child);
    ///         }
    ///     }
    ///     Ok(())
    /// }
    /// ```
    ///
    /// Useful when
    ///
    /// # Notes:
    ///
    /// If `follow_symlinks` is `true`, when gathering information about the
    /// file type, this function will make a system call that
    /// traverses paths until there is no `symlink` left, this means that the
    /// return type in this case can never be the variant
    /// `FileType::Symlink(_)`, if you want to read from the path and also check
    /// if it is a `symlink`, set `follow_symlinks` to `false`.
    ///
    /// For each directory, call the function recursively.
    ///
    /// See also `from_path_shallow`.
    pub fn from_path(path: impl AsRef<Path>, follow_symlinks: bool) -> FSResult<Self> {
        // Reuse code from `from_path_shallow`
        //
        // If FileType::Directory, populate with it's children, else, do nothing
        let result = match FileType::from_path_shallow(&path, follow_symlinks)? {
            FileType::Directory(_) => {
                FileType::Directory(collect_directory_children(&path, follow_symlinks)?)
            },
            other => other,
        };

        Ok(result)
    }

    /// Similar to `from_path`, but leaves `Directory` and `Symlink` empty.
    ///
    /// This function is guaranteed to only make one syscall for the `FileType`,
    /// this means that it cannot read all the elements from inside of the
    /// directories.
    ///
    /// This is useful when you want to make a quick check on a file type
    /// without going into it's thousand subsequent files, that would take a lot
    /// of time.
    ///
    /// # Example:
    /// ```
    /// use file_structure::{FileType, FSError};
    ///
    /// fn main() -> Result<(), FSError> {
    ///     let file_type = FileType::from_path_shallow("/sbin", true)?;
    ///
    ///     if !file_type.is_dir() {
    ///         println!("There's something wrong with our file system.");
    ///     }
    ///     Ok(())
    /// }
    /// ```
    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)?;

        // From the `fs::FileType` check if it is regular file, directory, or 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)
    }

    /// Checks variant `FileType::Regular(_)`
    pub fn is_regular(&self) -> bool {
        matches!(self, FileType::Regular)
    }

    /// Checks variant `FileType::Directory(_)`
    pub fn is_dir(&self) -> bool {
        matches!(self, FileType::Directory(_))
    }

    /// Checks variant `FileType::Symlink(_)`
    pub fn is_symlink(&self) -> bool {
        matches!(self, FileType::Symlink(_))
    }

    /// Shorthand for unpacking `FileType::Directory(ref children)`
    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"),
        }
    }
}