summaryrefslogblamecommitdiff
path: root/src/config.rs
blob: 075d884715b0fb1ac40335de48ad6e7160954784 (plain) (tree)
1
2
3
4
5
6
7
8
9
                                       
 

                                    
                                

                                               
                
                     


                   
                                               




                         



                                                                               




                                                                                                                                              

                                                                                       
                                                                               
                                                                     








                                                      

     
use std::{fs::File, io::{Read, Write}};

use serde::{Serialize, Deserialize};

use crate::{error::MLE, devdir};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Cfg {
    pub data: String,
    pub apis: Apis,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Apis {
    pub modrinth: String,
}

impl Cfg {
    pub fn init(filename: &str) -> MLE<Self> {
        let configfile = dirs::config_dir().unwrap().join(filename);

        let mut file = match File::open(devdir(configfile.to_str().unwrap())) {
            Ok(file) => file,
            Err(err) => {
                if err.kind() == std::io::ErrorKind::NotFound {
                    println!("No config file found, creating one");
                    let default_cfg = Cfg { data: String::from("./"), apis: Apis { modrinth: String::from("https://api.modrinth.com/v2/") } };
                    let mut file = File::create(devdir(configfile.to_str().unwrap()))?;
                    println!("Created config file");
                    file.write_all(toml::to_string(&default_cfg)?.as_bytes())?;
                    File::open(devdir(configfile.to_str().unwrap()))?
                } else {
                    return Err(err.into());
                }
            }
        };
        let mut content = String::new();
        file.read_to_string(&mut content)?;
        let config = toml::from_str::<Cfg>(&content)?;
        Ok(config)
    }
}