Skip to main content

file_organizer/models/
file.rs

1use std::{fs::{self, Metadata}, path::PathBuf};
2use chrono::{DateTime, Local};
3use super::FileType;
4
5#[derive(Debug)]
6pub struct CustomFile {
7    pub extension: String,
8    pub name: String,
9    pub path: PathBuf,
10    pub meta: Metadata,
11}
12
13impl CustomFile {
14    pub fn from_path(path: &PathBuf) -> Option<Self> {
15        let file_name = path.file_name()?.to_str()?;
16        let extension = path.extension()?.to_str()?;
17
18        let metadata = fs::metadata(path)
19            .map_err(|e| {
20                eprintln!("Failed to read metadata for '{}': {}", path.display(), e);
21                e
22            })
23            .ok()?;
24
25        Some(CustomFile {
26            name: file_name.to_string(),
27            extension: extension.to_string(),
28            path: path.clone(),
29            meta: metadata,
30        })
31    }
32
33    pub fn get_type(&self) -> FileType {
34        FileType::from_extension(&self.extension)
35    }
36
37    pub fn get_creation_date(&self) -> Result<String, String> {
38        let created = self.meta.created().map_err(|e| {
39            format!(
40                "Failed to get creation time for '{}': {}",
41                self.path.display(),
42                e
43            )
44        })?;
45
46        let datetime: DateTime<Local> = created.into();
47        Ok(datetime.format("%Y-%m-%d").to_string())
48    }
49}