summaryrefslogtreecommitdiffstats
path: root/src/file/mod.rs
blob: 3f3439748b5a78a6b369bad515a229b79f42b07b (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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use crate::{
    disk,
    user::{
        args::{Metric, TimeFormat, TimeStamp},
        Context,
    },
};
use ignore::DirEntry;
use std::{
    fmt::{self, Display},
    fs::{self, Metadata},
    io,
    ops::Deref,
    path::{Path, PathBuf},
};

#[cfg(unix)]
use crate::file::unix::permissions::{file_type::FileType, SymbolicNotation};

/// Concerned with querying information about a file's underlying inode.
pub mod inode;
use inode::{INodeError, Inode};

/// Rules on how to order entries relative to their siblings or all other files.
pub mod order;

/// Concerned with the tree data structure that is used to produce the program output.
pub mod tree;
pub use tree::Tree;

/// File attributes specific to Unix systems.
#[cfg(unix)]
pub mod unix;

/// Erdtree's wrapper around [`DirEntry`], it's metadata ([`Metadata`]). Also contains disk usage
/// information of files. Directories will always be initialized to have a size of zero as they
/// must be recursively computed.
#[derive(Debug)]
pub struct File {
    data: DirEntry,
    metadata: Metadata,
    size: disk::Usage,
    symlink_target: Option<PathBuf>,

    #[cfg(unix)]
    unix_attrs: unix::Attrs,
}

/// [`Display`] implementation concerned with human-readable presentation of the file-name.
pub struct DisplayName<'a> {
    file: &'a File,
}

/// [`Display`] implementation concerned with human-readable presentation of the file-path.
pub struct DisplayPath<'a> {
    file: &'a File,
    path_prefix: Option<&'a Path>,
}

impl File {
    /// Plain Jane constructor for [`File`].
    pub fn new(
        data: DirEntry,
        metadata: Metadata,
        size: disk::Usage,
        symlink_target: Option<PathBuf>,
        #[cfg(unix)] unix_attrs: unix::Attrs,
    ) -> Self {
        Self {
            data,
            metadata,
            size,
            symlink_target,
            #[cfg(unix)]
            unix_attrs,
        }
    }

    /// Initializes [`File`] from the given [`DirEntry`] and [`Context`].
    pub fn init(
        data: DirEntry,
        Context {
            metric,
            byte_units,
            follow,
            #[cfg(unix)]
            long,
            ..
        }: &Context,
    ) -> Result<Self, io::Error> {
        let path = data.path();

        let (symlink_target, metadata) = if data.file_type().is_some_and(|ft| ft.is_symlink()) {
            if *follow {
                (fs::read_link(path).ok(), fs::metadata(path)?)
            } else {
                (fs::read_link(path).ok(), fs::symlink_metadata(path)?)
            }
        } else {
            (None, fs::symlink_metadata(path)?)
        };

        let size = match metric {
            Metric::Physical => disk::Usage::init_physical(&metadata, *byte_units),
            Metric::Logical => disk::Usage::init_logical(&metadata, *byte_units),
            Metric::Word => disk::Usage::init_word_count(&data, &metadata, *follow)?,
            Metric::Line => disk::Usage::init_line_count(&data, &metadata, *follow)?,

            #[cfg(unix)]
            Metric::Blocks => disk::Usage::init_blocks(&metadata),
        };

        #[cfg(unix)]
        let unix_attrs = long
            .then(|| unix::Attrs::from((&metadata, &data)))
            .unwrap_or_else(unix::Attrs::default);

        Ok(Self::new(
            data,
            metadata,
            size,
            symlink_target,
            #[cfg(unix)]
            unix_attrs,
        ))
    }

    /// Attempts to query the [`File`]'s underlying inode which is represented by [`Inode`].
    pub fn inode(&self) -> Result<Inode, INodeError> {
        Inode::try_from(&self.metadata)
    }

    /// Reader for `metadata` field.
    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Gets a mutable reference to the `size` field.
    pub fn size_mut(&mut self) -> &mut disk::Usage {
        &mut self.size
    }

    /// Gets an immmutable reference to the `size` field.
    pub fn size(&self) -> &disk::Usage {
        &self.size
    }

    pub fn symlink_target(&self) -> Option<&Path> {
        self.symlink_target.as_deref()
    }

    pub fn display_name(&self) -> DisplayName<'_> {
        DisplayName { file: self }
    }

    pub fn display_path<'a>(&'a self, path_prefix: Option<&'a Path>) -> DisplayPath<'a> {
        DisplayPath {
            file: self,
            path_prefix,
        }
    }

    #[cfg(unix)]
    pub fn unix_attrs(&self) -> &unix::Attrs {
        &self.unix_attrs
    }

    #[cfg(unix)]
    pub fn timestamp_from_ctx(&self, ctx: &Context) -> Option<String> {
        use chrono::{DateTime, Local};

        let system_time = match ctx.time {
            TimeStamp::Mod => self.metadata().accessed().ok(),
            TimeStamp::Create => self.metadata().created().ok(),
            TimeStamp::Access => self.metadata().accessed().ok(),
        };

        system_time
            .map(DateTime::<Local>::from)
            .map(|local_time| match ctx.time_format {
                TimeFormat::Default => local_time.format("%d %h %H:%M %g"),
                TimeFormat::Iso => local_time.format("%Y-%m-%d %H:%M:%S"),
                TimeFormat::IsoStrict => local_time.format("%Y-%m-%dT%H:%M:%S%Z"),
                TimeFormat::Short => local_time.format("%Y-%m-%d"),
            })
            .map(|dt| format!("{dt}"))
    }

    #[cfg(unix)]
    pub fn is_fifo(&self) -> bool {
        self.metadata()
            .permissions()
            .try_mode_symbolic_notation()
            .map_or(false, |mode| mode.file_type() == &FileType::Fifo)
    }

    #[cfg(unix)]
    pub fn is_socket(&self) -> bool {
        self.metadata()
            .permissions()
            .try_mode_symbolic_notation()
            .map_or(false, |mode| mode.file_type() == &FileType::Socket)
    }

    #[cfg(unix)]
    pub fn is_char_device(&self) -> bool {
        self.metadata()
            .permissions()
            .try_mode_symbolic_notation()
            .map_or(false, |mode| mode.file_type() == &FileType::CharDevice)
    }

    #[cfg(unix)]
    pub fn is_block_device(&self) -> bool {
        self.metadata()
            .permissions()
            .try_mode_symbolic_notation()
            .map_or(false, |mode| mode.file_type() == &FileType::BlockDevice)
    }

    pub fn is_dir(&self) -> bool {
        self.file_type().is_some_and(|ft| ft.is_dir())
    }

    pub fn is_file(&self) -> bool {
        self.file_type().is_some_and(|ft| ft.is_file())
    }

    pub fn is_symlink(&self) -> bool {
        self.file_type().is_some_and(|ft| ft.is_symlink())
    }
}

impl Deref for File {
    type Target = DirEntry;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

impl Display for DisplayName<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let file_name = self.file.file_name().to_string_lossy();
        let link_target = self.file.symlink_target().map(|p| p.canonicalize());

        if let Some(Ok(target)) = link_target {
            write!(f, "{file_name} \u{2192} {}", target.display())
        } else {
            write!(f, "{file_name}")
        }
    }
}

impl Display for DisplayPath<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let display = match self.path_prefix {
            Some(prefix) => {
                let path = self.file.path();
                path.strip_prefix(prefix)
                    .map_or_else(|_| path.display(), |p| p.display())
            },
            None => self.file.path().display(),
        };

        let link_target = self.file.symlink_target().map(|p| p.canonicalize());

        if let Some(Ok(target)) = link_target {
            write!(f, "{display} \u{2192} {}", target.display())
        } else {
            write!(f, "{display}")
        }
    }
}