1use std::{collections::HashMap, path::PathBuf};
6
7use color_eyre::eyre::{OptionExt, Result};
8
9use crate::models::Entries;
10
11pub 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
23pub fn get_config_path() -> Result<String> {
27 Ok(format!("{}/config.json", get_directory()?))
28}
29
30pub fn ensure_created() -> Result<()> {
36 std::fs::create_dir_all(get_directory()?)?;
37
38 Ok(())
39}
40
41pub 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
63pub 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}