-
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
200 additions
and
43 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
use std::{collections::HashMap, error::Error, fs, path::PathBuf}; | ||
|
||
use bitcode::{Decode, Encode}; | ||
|
||
#[derive(Encode, Decode)] | ||
struct CacheData(HashMap<String, String>); | ||
|
||
pub struct Cache { | ||
path: PathBuf, | ||
data: CacheData, | ||
update: bool, | ||
} | ||
|
||
impl Cache { | ||
pub fn new() -> Result<Self, Box<dyn Error>> { | ||
let path = xdg::BaseDirectories::new()?.place_state_file("comma-choices")?; | ||
|
||
Ok(Self { | ||
data: if path.exists() { | ||
let bytes = fs::read(&path)?; | ||
bitcode::decode(&bytes)? | ||
} else { | ||
CacheData(HashMap::new()) | ||
}, | ||
path, | ||
update: false, | ||
}) | ||
} | ||
|
||
pub fn query(&self, command: &str) -> Option<String> { | ||
self.data.0.get(command).cloned() | ||
} | ||
|
||
pub fn update(&mut self, command: &str, derivation: &str) { | ||
self.data.0.insert(command.into(), derivation.into()); | ||
self.update = true; | ||
} | ||
|
||
pub fn delete(&mut self, command: &Option<String>) { | ||
if let Some(command) = command { | ||
self.data.0.remove(command); | ||
} else { | ||
self.data.0.clear(); | ||
} | ||
self.update = true; | ||
} | ||
} | ||
|
||
impl Drop for Cache { | ||
fn drop(&mut self) { | ||
if self.update { | ||
let bytes = bitcode::encode(&self.data.0); | ||
if let Err(e) = fs::write(&self.path, bytes) { | ||
eprintln!("failed to write cache: {e}"); | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters