rusty_bin/monitor/storage/
utils.rs1use super::{FileNaming, Result};
3use std::path::Path;
4use tokio::fs;
5
6pub async fn calculate_checksum(file_path: &Path) -> Result<String> {
8 use sha2::{Digest, Sha256};
9
10 let data = fs::read(file_path).await?;
11 let mut hasher = Sha256::new();
12 hasher.update(&data);
13 let result = hasher.finalize();
14 Ok(format!("{result:x}"))
15}
16
17pub async fn get_file_size(file_path: &Path) -> Result<u64> {
19 let metadata = fs::metadata(file_path).await?;
20 Ok(metadata.len())
21}
22
23pub async fn file_exists(file_path: &Path) -> bool {
25 fs::metadata(file_path).await.is_ok()
26}
27
28pub async fn ensure_dir_exists(dir_path: &Path) -> Result<()> {
30 if !dir_path.exists() {
31 fs::create_dir_all(dir_path).await?;
32 }
33 Ok(())
34}
35
36pub async fn cleanup_old_files(dir_path: &Path, retention_days: u32) -> Result<u64> {
38 let cutoff_date = crate::monitor::utils::time::days_ago(retention_days);
39 let mut deleted_count = 0;
40
41 let mut entries = fs::read_dir(dir_path).await?;
42 while let Some(entry) = entries.next_entry().await? {
43 if let Some(filename) = entry.file_name().to_str()
44 && let Some(naming) = FileNaming::parse_filename(filename)
45 && naming.date < cutoff_date
46 {
47 fs::remove_file(entry.path()).await?;
48 deleted_count += 1;
49 log::info!("Deleted old file: {filename}");
50 }
51 }
52
53 Ok(deleted_count)
54}