with_java/
persistence.rs

1//!
2//! utilities for reading and persisting configuration
3//!
4
5use std::{collections::HashMap, path::PathBuf};
6
7use color_eyre::eyre::{OptionExt, Result};
8
9use crate::models::Entries;
10
11///
12/// get the base config directory path
13///
14pub fn get_directory() -> Result<String> {
15    Ok(format!(
16        "{}/with-java",
17        dirs::config_dir()
18            .ok_or_eyre("could not get config directory")?
19            .display()
20    ))
21}
22
23///
24/// get the full config path
25///
26pub fn get_config_path() -> Result<String> {
27    Ok(format!("{}/config.json", get_directory()?))
28}
29
30///
31/// make sure the config directory path exists,
32/// creating it if necessary and returning an error
33/// if creation failed
34///
35pub fn ensure_created() -> Result<()> {
36    std::fs::create_dir_all(get_directory()?)?;
37
38    Ok(())
39}
40
41///
42/// try to read and deserialize our config file,
43/// returning any errors that might occur
44///
45/// `ensure_created` should have been called beforehand
46///
47pub fn read_config() -> Result<Entries> {
48    let path = PathBuf::from(get_config_path()?);
49
50    if !path.exists() {
51        return Ok(HashMap::new());
52    }
53
54    let buf = std::fs::read_to_string(path)?;
55
56    if buf.is_empty() {
57        return Ok(HashMap::new());
58    }
59
60    Ok(serde_json::from_str(&buf)?)
61}
62
63///
64/// try to write configuration to file,
65/// returning any errors that might occur
66///
67/// `ensure_created` should have been called beforehand
68///
69pub fn write_config(config: &Entries) -> Result<()> {
70    let path = get_config_path()?;
71    let str = serde_json::to_string(config)?;
72
73    Ok(std::fs::write(path, str)?)
74}