commemorate/utils/
file.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use crate::error::{CommemorateError, CommemorateResult};
5
6pub fn ensure_commemorate_dir() -> CommemorateResult<PathBuf> {
7    let home_dir = dirs::home_dir().ok_or_else(|| {
8        CommemorateError::DirectoryCreationError("Unable to determine home directory".to_string())
9    })?;
10    let commemorate_dir = home_dir.join(".commemorate");
11    if !commemorate_dir.exists() {
12        fs::create_dir(&commemorate_dir).map_err(|e| {
13            CommemorateError::DirectoryCreationError(format!(
14                "Failed to create .commemorate directory: {}",
15                e
16            ))
17        })?;
18    }
19    Ok(commemorate_dir)
20}
21
22pub fn read_file(path: &Path) -> CommemorateResult<Vec<u8>> {
23    std::fs::read(path).map_err(|e| match e.kind() {
24        std::io::ErrorKind::NotFound => CommemorateError::MemoryNotFound,
25        std::io::ErrorKind::PermissionDenied => CommemorateError::MemoryAccessError,
26        _ => CommemorateError::FileReadError(e),
27    })
28}
29
30pub fn write_file(path: &Path, contents: &[u8]) -> CommemorateResult<()> {
31    std::fs::write(path, contents).map_err(|e| match e.kind() {
32        std::io::ErrorKind::NotFound => CommemorateError::MemoryNotFound,
33        std::io::ErrorKind::PermissionDenied => CommemorateError::MemoryAccessError,
34        _ => CommemorateError::FileReadError(e),
35    })?;
36    Ok(())
37}
38
39pub fn list_memoria_files() -> CommemorateResult<Vec<PathBuf>> {
40    let commemorate_dir = ensure_commemorate_dir()?;
41    let entries = fs::read_dir(commemorate_dir).map_err(CommemorateError::FileReadError)?;
42    let mut memoria_files = Vec::new();
43
44    for entry in entries {
45        let entry = entry.map_err(CommemorateError::FileReadError)?;
46        let path = entry.path();
47        if path.is_file() && path.extension().map_or(false, |ext| ext == "memoria") {
48            memoria_files.push(path);
49        }
50    }
51
52    memoria_files.sort_by(|a, b| {
53        b.metadata()
54            .and_then(|m| m.modified())
55            .unwrap_or_else(|_| std::time::SystemTime::UNIX_EPOCH)
56            .cmp(
57                &a.metadata()
58                    .and_then(|m| m.modified())
59                    .unwrap_or_else(|_| std::time::SystemTime::UNIX_EPOCH),
60            )
61    });
62
63    Ok(memoria_files)
64}
65
66pub fn get_memoria_path(name: &str) -> CommemorateResult<PathBuf> {
67    let commemorate_dir = ensure_commemorate_dir()?;
68    Ok(commemorate_dir.join(format!("{}.memoria", name)))
69}