Skip to main content

jump_start/
config.rs

1use crate::JumpStartInstance;
2use directories::ProjectDirs;
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::io;
6use std::path::PathBuf;
7
8#[derive(Debug, Serialize, Deserialize)]
9pub struct Config {
10    pub instances: Vec<JumpStartInstance>,
11}
12
13impl ::std::default::Default for Config {
14    fn default() -> Self {
15        Self {
16            instances: vec![JumpStartInstance {
17                name: "".to_string(),
18                path: PathBuf::new(),
19                default: Some(true),
20            }],
21        }
22    }
23}
24
25// Re-export the utility functions for testing
26pub fn get_config_path() -> PathBuf {
27    let project_dirs =
28        ProjectDirs::from("", "", "jump-start").expect("Could not find OS project directory");
29    let config_path = project_dirs.config_dir().join("config.json");
30    config_path
31}
32
33pub fn load_config(config_path: &PathBuf) -> Result<Config, io::Error> {
34    if let Some(parent) = config_path.parent() {
35        fs::create_dir_all(parent)?;
36    }
37
38    let config_contents = fs::read_to_string(config_path).unwrap_or_else(|_| {
39        let default_config = Config::default();
40        let json_contents = serde_json::to_string_pretty(&default_config)
41            .expect("Failed to serialize default config");
42        fs::write(config_path, &json_contents).expect("Failed to write default config file");
43        json_contents
44    });
45    let config: Config = serde_json::from_str(&config_contents)?;
46    Ok(config)
47}
48
49/// Get the default instance, or the first instance if none is marked default
50pub fn get_default_instance(config: &Config) -> &JumpStartInstance {
51    config
52        .instances
53        .iter()
54        .find(|i| i.default.unwrap_or(false))
55        .unwrap_or(&config.instances[0])
56}
57
58/// Get the specified instance path, or the default instance path
59pub fn resolve_instance_path(config: &Config, instance_path: Option<&str>) -> std::path::PathBuf {
60    match instance_path {
61        Some(path) => std::path::PathBuf::from(path),
62        None => {
63            let instance = get_default_instance(config);
64            std::path::PathBuf::from(&instance.path)
65        }
66    }
67}