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
use crate::{collect_directory_children, error::*, fs_filetype_from_path, symlink_target, File};

use std::{
    fmt,
    path::{Path, PathBuf},
};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FileType {
    File,
    Directory { children: Vec<File> },
    Symlink { target_path: PathBuf },
}

impl FileType {
    pub fn from_path(path: impl AsRef<Path>, follow_symlinks: bool) -> Result<Self> {
        let fs_file_type = fs_filetype_from_path(&path, follow_symlinks)?;

        // Is file, directory, or symlink
        let result = if fs_file_type.is_file() {
            FileType::File
        } else if fs_file_type.is_dir() {
            let children = collect_directory_children(&path, follow_symlinks)?;
            FileType::Directory { children }
        } else if fs_file_type.is_symlink() {
            let target_path = symlink_target(path)?;
            FileType::Symlink { target_path }
        } else {
            todo!("Other file types.")
        };

        Ok(result)
    }

    pub fn from_path_shallow(path: impl AsRef<Path>, follow_symlink: bool) -> Result<Self> {
        let fs_file_type = fs_filetype_from_path(&path, follow_symlink)?;

        // Is file, directory, or symlink
        let result = {
            if fs_file_type.is_file() {
                FileType::File
            } else if fs_file_type.is_dir() {
                FileType::Directory { children: vec![] }
            } else if fs_file_type.is_symlink() {
                FileType::Symlink {
                    target_path: PathBuf::new(),
                }
            } else {
                todo!("Other file types.")
            }
        };
        Ok(result)
    }

    pub fn is_file(&self) -> bool {
        matches!(self, FileType::File)
    }

    pub fn is_dir(&self) -> bool {
        matches!(self, FileType::Directory { .. })
    }

    pub fn is_symlink(&self) -> bool {
        matches!(self, FileType::Symlink { .. })
    }
}

impl Default for FileType {
    fn default() -> Self {
        Self::File
    }
}

impl fmt::Display for FileType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            FileType::File => write!(f, "file"),
            FileType::Directory { .. } => write!(f, "directory"),
            FileType::Symlink { .. } => write!(f, "symbolic link"),
        }
    }
}