xsshend/core/
validator.rs1use anyhow::{Context, Result};
3use std::fs;
4use std::path::Path;
5
6pub struct Validator;
7
8impl Validator {
9 pub fn validate_file(file_path: &Path) -> Result<()> {
11 if !file_path.exists() {
12 anyhow::bail!("Fichier non trouvé: {}", file_path.display());
13 }
14
15 if !file_path.is_file() {
16 anyhow::bail!(
17 "Le chemin ne pointe pas vers un fichier: {}",
18 file_path.display()
19 );
20 }
21
22 fs::File::open(file_path)
24 .with_context(|| format!("Impossible de lire le fichier: {}", file_path.display()))?;
25
26 Ok(())
27 }
28
29 pub fn get_file_size(file_path: &Path) -> Result<u64> {
31 let metadata = fs::metadata(file_path).with_context(|| {
32 format!(
33 "Impossible de lire les métadonnées: {}",
34 file_path.display()
35 )
36 })?;
37
38 Ok(metadata.len())
39 }
40
41 pub fn format_file_size(size: u64) -> String {
43 const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
44 let mut size = size as f64;
45 let mut unit_index = 0;
46
47 while size >= 1024.0 && unit_index < UNITS.len() - 1 {
48 size /= 1024.0;
49 unit_index += 1;
50 }
51
52 if unit_index == 0 {
53 format!("{:.0} {}", size, UNITS[unit_index])
54 } else {
55 format!("{:.1} {}", size, UNITS[unit_index])
56 }
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use std::io::Write;
64 use tempfile::NamedTempFile;
65
66 #[test]
67 fn test_file_validation() {
68 let mut temp_file = NamedTempFile::new().unwrap();
70 writeln!(temp_file, "test content").unwrap();
71
72 assert!(Validator::validate_file(temp_file.path()).is_ok());
74
75 let non_existent = Path::new("/path/that/does/not/exist");
77 assert!(Validator::validate_file(non_existent).is_err());
78 }
79
80 #[test]
81 fn test_file_size_formatting() {
82 assert_eq!(Validator::format_file_size(512), "512 B");
83 assert_eq!(Validator::format_file_size(1024), "1.0 KB");
84 assert_eq!(Validator::format_file_size(1536), "1.5 KB");
85 assert_eq!(Validator::format_file_size(1024 * 1024), "1.0 MB");
86 assert_eq!(
87 Validator::format_file_size(2 * 1024 * 1024 * 1024),
88 "2.0 GB"
89 );
90 }
91}