|
| 1 | +use anyhow::anyhow; |
| 2 | +use serde::{Deserialize, Serialize}; |
| 3 | +use std::{ |
| 4 | + collections::HashMap, |
| 5 | + fs::File, |
| 6 | + io::{Read, Write}, |
| 7 | + path::PathBuf, |
| 8 | + sync::{Arc, Mutex}, |
| 9 | +}; |
| 10 | + |
| 11 | +#[derive(Clone)] |
| 12 | +pub enum MnemonicsType { |
| 13 | + PROJECT, |
| 14 | + TAG, |
| 15 | +} |
| 16 | + |
| 17 | +pub trait MnemonicsCache { |
| 18 | + fn insert( |
| 19 | + &mut self, |
| 20 | + mn_type: MnemonicsType, |
| 21 | + key: &str, |
| 22 | + value: &str, |
| 23 | + ) -> Result<(), anyhow::Error>; |
| 24 | + fn remove(&mut self, mn_type: MnemonicsType, key: &str) -> Result<(), anyhow::Error>; |
| 25 | + fn get(&self, mn_type: MnemonicsType, key: &str) -> Option<String>; |
| 26 | + fn save(&self) -> Result<(), anyhow::Error>; |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Debug, Clone, Serialize, Deserialize, Default)] |
| 30 | +pub struct MnemonicsTable { |
| 31 | + tags: HashMap<String, String>, |
| 32 | + projects: HashMap<String, String>, |
| 33 | +} |
| 34 | + |
| 35 | +impl MnemonicsTable { |
| 36 | + pub fn get(&self, mn_type: MnemonicsType) -> &HashMap<String, String> { |
| 37 | + match mn_type { |
| 38 | + MnemonicsType::PROJECT => &self.projects, |
| 39 | + MnemonicsType::TAG => &self.tags, |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + pub fn insert(&mut self, mn_type: MnemonicsType, key: &str, value: &str) { |
| 44 | + let _ = match mn_type { |
| 45 | + MnemonicsType::PROJECT => self.projects.insert(key.to_string(), value.to_string()), |
| 46 | + MnemonicsType::TAG => self.tags.insert(key.to_string(), value.to_string()), |
| 47 | + }; |
| 48 | + } |
| 49 | + |
| 50 | + pub fn remove(&mut self, mn_type: MnemonicsType, key: &str) { |
| 51 | + let _ = match mn_type { |
| 52 | + MnemonicsType::PROJECT => self.projects.remove(key), |
| 53 | + MnemonicsType::TAG => self.tags.remove(key), |
| 54 | + }; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +#[derive(Debug, Clone)] |
| 59 | +pub struct FileMnemonicsCache { |
| 60 | + cfg_path: Arc<Mutex<PathBuf>>, |
| 61 | + map: MnemonicsTable, |
| 62 | +} |
| 63 | + |
| 64 | +impl FileMnemonicsCache { |
| 65 | + pub fn new(path: Arc<Mutex<PathBuf>>) -> Self { |
| 66 | + Self { |
| 67 | + cfg_path: path, |
| 68 | + map: MnemonicsTable::default(), |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + pub fn load(&mut self) -> Result<(), anyhow::Error> { |
| 73 | + let cfg_path_lck = self.cfg_path.lock().expect("Cannot lock file"); |
| 74 | + let file = File::open(cfg_path_lck.as_path()); |
| 75 | + if let Ok(mut file_obj) = file { |
| 76 | + let mut buf = String::new(); |
| 77 | + let _ = file_obj.read_to_string(&mut buf); |
| 78 | + if !buf.is_empty() { |
| 79 | + let x: MnemonicsTable = toml::from_str(&buf).map_err(|p| { |
| 80 | + anyhow!("Could not parse configuration file: {}!", p.to_string()) |
| 81 | + })?; |
| 82 | + self.map = x; |
| 83 | + } |
| 84 | + } |
| 85 | + Ok(()) |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl MnemonicsCache for FileMnemonicsCache { |
| 90 | + fn insert( |
| 91 | + &mut self, |
| 92 | + mn_type: MnemonicsType, |
| 93 | + key: &str, |
| 94 | + value: &str, |
| 95 | + ) -> Result<(), anyhow::Error> { |
| 96 | + // Ensure its unique. Check if the key is already used somewhere. |
| 97 | + let x = self |
| 98 | + .map |
| 99 | + .get(MnemonicsType::PROJECT) |
| 100 | + .values() |
| 101 | + .find(|p| p.as_str().eq(value)); |
| 102 | + if x.is_some() { |
| 103 | + return Err(anyhow!("Duplicate key generated!")); |
| 104 | + } |
| 105 | + let x = self |
| 106 | + .map |
| 107 | + .get(MnemonicsType::TAG) |
| 108 | + .values() |
| 109 | + .find(|p| p.as_str().eq(value)); |
| 110 | + if x.is_some() { |
| 111 | + return Err(anyhow!("Duplicate key generated!")); |
| 112 | + } |
| 113 | + |
| 114 | + self.map.insert(mn_type, key, value); |
| 115 | + self.save()?; |
| 116 | + Ok(()) |
| 117 | + } |
| 118 | + |
| 119 | + fn remove(&mut self, mn_type: MnemonicsType, key: &str) -> Result<(), anyhow::Error> { |
| 120 | + self.map.remove(mn_type, &key); |
| 121 | + self.save()?; |
| 122 | + Ok(()) |
| 123 | + } |
| 124 | + |
| 125 | + fn get(&self, mn_type: MnemonicsType, key: &str) -> Option<String> { |
| 126 | + self.map.get(mn_type).get(key).cloned() |
| 127 | + } |
| 128 | + |
| 129 | + fn save(&self) -> Result<(), anyhow::Error> { |
| 130 | + let p = self.cfg_path.lock().expect("Can lock file"); |
| 131 | + let toml = toml::to_string(&self.map).unwrap(); |
| 132 | + let mut f = File::create(p.as_path())?; |
| 133 | + let _ = f.write_all(toml.as_bytes()); |
| 134 | + Ok(()) |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +pub(crate) type MnemonicsCacheType = dyn MnemonicsCache + Send + Sync; |
| 139 | + |
| 140 | +#[cfg(test)] |
| 141 | +mod tests { |
| 142 | + use std::{io::{Read, Seek}, str::FromStr}; |
| 143 | + |
| 144 | + use super::*; |
| 145 | + use tempfile::NamedTempFile; |
| 146 | + |
| 147 | + #[test] |
| 148 | + fn test_mnemonics_cache() { |
| 149 | + let mut file1 = NamedTempFile::new().expect("Cannot create named temp files."); |
| 150 | + let x = PathBuf::from(file1.path()); |
| 151 | + let file_mtx = Arc::new(Mutex::new(x)); |
| 152 | + |
| 153 | + let mut mock = FileMnemonicsCache::new(file_mtx); |
| 154 | + assert_eq!(mock.get(MnemonicsType::PROJECT, "personal"), None); |
| 155 | + assert_eq!( |
| 156 | + mock.insert(MnemonicsType::TAG, "personal", "xz").is_ok(), |
| 157 | + true |
| 158 | + ); |
| 159 | + assert_eq!( |
| 160 | + mock.get(MnemonicsType::TAG, "personal"), |
| 161 | + Some(String::from("xz")) |
| 162 | + ); |
| 163 | + // how to validate content? |
| 164 | + file1.reopen().expect("Cannot reopen"); |
| 165 | + let mut buf = String::new(); |
| 166 | + let read_result = file1.read_to_string(&mut buf); |
| 167 | + assert_eq!(read_result.is_ok(), true); |
| 168 | + let read_result = read_result.expect("Could not read fro file"); |
| 169 | + assert!(read_result > 0); |
| 170 | + assert_eq!( |
| 171 | + buf, |
| 172 | + String::from("[tags]\npersonal = \"xz\"\n\n[projects]\n") |
| 173 | + ); |
| 174 | + assert_eq!( |
| 175 | + mock.insert(MnemonicsType::PROJECT, "taskwarrior", "xz") |
| 176 | + .is_ok(), |
| 177 | + false |
| 178 | + ); |
| 179 | + assert_eq!(mock.remove(MnemonicsType::TAG, "personal").is_ok(), true); |
| 180 | + assert_eq!(mock.get(MnemonicsType::TAG, "personal"), None); |
| 181 | + assert_eq!( |
| 182 | + mock.insert(MnemonicsType::PROJECT, "taskwarrior", "xz") |
| 183 | + .is_ok(), |
| 184 | + true |
| 185 | + ); |
| 186 | + assert_eq!( |
| 187 | + mock.insert(MnemonicsType::TAG, "personal", "xz").is_ok(), |
| 188 | + false |
| 189 | + ); |
| 190 | + assert_eq!(mock.remove(MnemonicsType::PROJECT, "taskwarrior").is_ok(), true); |
| 191 | + file1.reopen().expect("Cannot reopen"); |
| 192 | + let _ = file1.as_file().set_len(0); |
| 193 | + let _ = file1.seek(std::io::SeekFrom::Start(0)); |
| 194 | + let data = String::from("[tags]\npersonal = \"xz\"\n\n[projects]\n"); |
| 195 | + let _ = file1.write_all(data.as_bytes()); |
| 196 | + let _ = file1.flush(); |
| 197 | + assert_eq!(mock.load().is_ok(), true); |
| 198 | + assert_eq!( |
| 199 | + mock.get(MnemonicsType::TAG, "personal"), |
| 200 | + Some(String::from("xz")) |
| 201 | + ); |
| 202 | + file1.reopen().expect("Cannot reopen"); |
| 203 | + let _ = file1.as_file().set_len(0); |
| 204 | + let _ = file1.seek(std::io::SeekFrom::Start(0)); |
| 205 | + let data = String::from("**********"); |
| 206 | + let _ = file1.write_all(data.as_bytes()); |
| 207 | + let _ = file1.flush(); |
| 208 | + assert_eq!(mock.load().is_ok(), false); |
| 209 | + // Empty file cannot be parsed, but should not through an error! |
| 210 | + let _ = file1.as_file().set_len(0); |
| 211 | + let _ = file1.seek(std::io::SeekFrom::Start(0)); |
| 212 | + let _ = file1.flush(); |
| 213 | + assert_eq!(mock.load().is_ok(), true); |
| 214 | + // If the configuration file does not exist yet (close will delete), |
| 215 | + // it is fine as well. |
| 216 | + let _ = file1.close(); |
| 217 | + assert_eq!(mock.load().is_ok(), true); |
| 218 | + |
| 219 | + } |
| 220 | + |
| 221 | + #[test] |
| 222 | + fn test_mnemonics_cache_file_fail() { |
| 223 | + let x = PathBuf::from_str("/4bda0a6b-da0d-46be-98e6-e06d43385fba/asdfa.cache").unwrap(); |
| 224 | + let file_mtx = Arc::new(Mutex::new(x)); |
| 225 | + |
| 226 | + let mut mock = FileMnemonicsCache::new(file_mtx); |
| 227 | + assert_eq!( |
| 228 | + mock.insert(MnemonicsType::TAG, "personal", "xz").is_ok(), |
| 229 | + false |
| 230 | + ); |
| 231 | + assert_eq!(mock.remove(MnemonicsType::PROJECT, "taskwarrior").is_ok(), false); |
| 232 | + } |
| 233 | +} |
0 commit comments