Skip to main content

fancy_tree/tree/entry/
mod.rs

1//! Utilities for entries in a file tree.
2pub use attributes::Attributes;
3use std::io;
4use std::path::Path;
5
6pub mod attributes;
7
8/// Represents an entry in a file tree and provides utilities for working with it.
9pub struct Entry<P: AsRef<Path>> {
10    /// The path of this entry.
11    path: P,
12    /// The file object. Either a directory or a file.
13    attributes: Attributes,
14}
15
16impl<P> Entry<P>
17where
18    P: AsRef<Path>,
19{
20    /// Creates a new [`Entry`]. `path` should be the full path to the entry from the tree's root.
21    #[inline]
22    pub fn new(path: P) -> io::Result<Self> {
23        let attributes = Attributes::new(path.as_ref())?;
24        let entry = Self { path, attributes };
25        Ok(entry)
26    }
27
28    /// Gets the path of this entry.
29    #[inline]
30    pub fn path(&self) -> &Path {
31        self.path.as_ref()
32    }
33
34    /// Gets the attributes of this entry.
35    #[inline]
36    pub fn attributes(&self) -> &Attributes {
37        &self.attributes
38    }
39
40    /// Gets if the entry is executable.
41    #[inline]
42    pub fn is_executable(&self) -> bool {
43        self.attributes.is_executable()
44    }
45
46    /// Is the file a dotfile?
47    ///
48    /// On Unix, this means that the file is hidden.
49    pub fn is_dotfile(&self) -> bool {
50        let path = self.path.as_ref();
51        path.file_name()
52            .is_some_and(|filename| filename.as_encoded_bytes().starts_with(b"."))
53    }
54
55    /// Is the file hidden?
56    ///
57    /// On Windows, this checks the file attribute. On Unix, it checks if it is a
58    /// dotfile.
59    pub fn is_hidden(&self) -> bool {
60        self.is_dotfile_hidden() || self.attributes.is_hidden()
61    }
62
63    /// Is the file hidden because it's a dotfile? Returns `true` if it is a dotfile
64    /// on Unix.
65    #[cfg(not(windows))]
66    #[inline]
67    fn is_dotfile_hidden(&self) -> bool {
68        self.is_dotfile()
69    }
70
71    /// Is the file hidden because it's a dotfile? Always returns `false` on Windows.
72    #[inline]
73    #[cfg(windows)]
74    fn is_dotfile_hidden(&self) -> bool {
75        false
76    }
77}