use crate::FileId; use super::{ReadFileError, WriteFileError}; use chrono::prelude::*; use serde::{Deserialize, Serialize}; use serde_json; use std::{ io::{Read, Write}, path::PathBuf, }; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FileInfo { pub id: FileId, pub size: usize, pub created: DateTime, pub file_type: String, pub hash: String, pub extension: String, } impl FileInfo { pub fn load(path: PathBuf) -> Result { let mut content: Vec = Vec::new(); let mut file = std::fs::File::open(path.clone()).map_err(|_| ReadFileError::FileNotFound(path))?; file.read_to_end(&mut content)?; let js = serde_json::from_slice(&content)?; Ok(js) } pub fn save(&self, path: PathBuf) -> Result<(), WriteFileError> { let ser = serde_json::to_string(self).unwrap(); let mut file = std::fs::File::create(path)?; file.write(ser.as_bytes())?; Ok(()) } } #[cfg(test)] mod test { use super::*; use crate::store::{filehandle::PathResolver, utils::FileCleanup, FileId}; use std::convert::TryFrom; #[test] fn it_saves_and_loads_metadata() { let resolver = PathResolver::try_from("var/1617654d-a588-4714-b4fa-e00ed0a8a607.png") .expect("a valid path"); let _cleanup = FileCleanup(resolver.metadata_path()); let created = Utc::now(); let info = FileInfo { id: FileId("temp-id".to_owned()), size: 23777, created, file_type: "image/png".to_owned(), hash: "abcdefg".to_owned(), extension: "png".to_owned(), }; info.save(resolver.metadata_path()).unwrap(); let info_ = FileInfo::load(resolver.metadata_path()).unwrap(); assert_eq!(info_.size, 23777); assert_eq!(info_.created, info.created); assert_eq!(info_.file_type, "image/png"); assert_eq!(info_.hash, info.hash); } }