1use crate::model::Snippet;
3use anyhow::{bail, Context, Result};
4use directories::ProjectDirs;
5use jasondb::Database;
6use std::path::PathBuf;
7
8pub type DatabaseModel = Database<Snippet>;
9
10pub fn get_location_database() -> Result<PathBuf> {
12 let path_root = match ProjectDirs::from("", "", "snippy-rs") {
13 Some(proj_dirs) => proj_dirs.data_dir().to_path_buf(),
14 None => bail!("Cannot find configuration folder!"),
15 };
16 std::fs::create_dir_all(&path_root)?; Ok(path_root.join("snippets.json"))
18}
19
20pub fn connect_db() -> Result<DatabaseModel> {
22 let filename = get_location_database()?;
23 let db: DatabaseModel = Database::new(filename).with_context(|| "Error opening database!")?;
24 Ok(db)
25}
26
27pub fn set_snippet(
29 db: &mut DatabaseModel,
30 name: &str,
31 description: &str,
32 content: &str,
33) -> Result<Snippet> {
34 let snippet = Snippet::new(name, description, content);
35 db.set(name, &snippet)
36 .with_context(|| "Error setting the snippet in the .json file!")?;
37 Ok(snippet)
38}
39
40pub fn remove_snippet(db: &mut DatabaseModel, name: &str) -> Result<()> {
42 let deletion = db.delete(name);
43 match deletion {
44 Ok(_) => Ok(()),
45 Err(jasondb::error::JasonError::InvalidKey) => {
46 eprintln!("The snippet does not exist!");
47 std::process::exit(1)
48 }
49 _ => bail!("Error removing the snippet in the .json file!"),
50 }
51}
52
53pub fn get_all_snippets(db: &mut DatabaseModel) -> Result<Vec<Snippet>> {
55 let snippets_and_keys = db
56 .iter()
57 .filter_map(|x| x.ok())
58 .collect::<Vec<(String, Snippet)>>();
59 let (_, vec_snippets): (Vec<_>, Vec<_>) = snippets_and_keys.into_iter().unzip();
61 Ok(vec_snippets)
62}