Skip to main content

compare_dir/
file_item.rs

1use simple_path::SimplePath;
2use std::fmt::Display;
3use std::fs;
4use std::path::{Path, PathBuf};
5use std::time::SystemTime;
6
7#[derive(Clone, Debug)]
8pub struct FileItem {
9    path: PathBuf,
10    size: u64,
11    modified: SystemTime,
12}
13
14impl TryFrom<&walkdir::DirEntry> for FileItem {
15    type Error = anyhow::Error;
16
17    fn try_from(entry: &walkdir::DirEntry) -> Result<Self, Self::Error> {
18        let metadata = entry.metadata()?;
19        Ok(Self {
20            path: entry.path().to_path_buf(),
21            size: metadata.len(),
22            modified: metadata.modified()?,
23        })
24    }
25}
26
27impl TryFrom<&Path> for FileItem {
28    type Error = anyhow::Error;
29
30    fn try_from(path: &Path) -> Result<Self, Self::Error> {
31        let metadata = fs::metadata(path)?;
32        Ok(Self {
33            path: path.to_path_buf(),
34            size: metadata.len(),
35            modified: metadata.modified()?,
36        })
37    }
38}
39
40impl From<FileItem> for PathBuf {
41    fn from(value: FileItem) -> Self {
42        value.path
43    }
44}
45
46impl Display for FileItem {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.write_fmt(format_args!("{}", self.path.display()))
49    }
50}
51
52impl FileItem {
53    pub fn path(&self) -> &Path {
54        &self.path
55    }
56
57    #[deprecated(note = "Please use `into` instead")]
58    pub fn into_path_buf(self) -> PathBuf {
59        self.path
60    }
61
62    pub fn relative_path(&self, base: &Path) -> &Path {
63        SimplePath::strip_prefix(&self.path, base).unwrap()
64    }
65
66    pub fn size(&self) -> u64 {
67        self.size
68    }
69
70    pub fn modified(&self) -> SystemTime {
71        self.modified
72    }
73}