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 Display for FileItem {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.write_fmt(format_args!("{}", self.path.display()))
43    }
44}
45
46impl FileItem {
47    pub fn path(&self) -> &Path {
48        &self.path
49    }
50
51    pub fn into_path_buf(self) -> PathBuf {
52        self.path
53    }
54
55    pub fn relative_path(&self, base: &Path) -> &Path {
56        SimplePath::strip_prefix(&self.path, base).unwrap()
57    }
58
59    pub fn size(&self) -> u64 {
60        self.size
61    }
62
63    pub fn modified(&self) -> SystemTime {
64        self.modified
65    }
66}