rsproject/src/setting.rs
2024-02-28 18:09:29 +08:00

74 lines
2.3 KiB
Rust

use crate::error::SettingError;
use dirs::home_dir;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::io::Write;
use std::path::{Path, PathBuf};
use url::Url;
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
pub alg_list_repo: String,
pub source_list_loc: PathBuf,
pub alg_source: String,
pub gitlab_key: Option<String>
}
impl Default for Config {
fn default() -> Self {
let default_source_list_loc = home_dir().unwrap().join(".cache/rsp/lts");
Self {
alg_list_repo: "http://192.168.1.70:6020/awesomeradaralgorithms/lts.git".to_string(),
source_list_loc: default_source_list_loc,
alg_source: "http://192.168.1.70:6020".to_string(),
gitlab_key: None
}
}
}
impl Config {
fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, SettingError> {
let file = std::fs::read_to_string(path)?;
let config = toml::from_str(&file)?;
Ok(config)
}
pub fn from_env() -> Result<Self, SettingError> {
if let Some(dir_path) = env::var("RSP_CONFIG")
.ok()
.map(|x| PathBuf::from(x))
.or(dirs::config_dir())
{
let path = dir_path.join("rsp.toml");
println!("{:?}", path);
if path.exists() {
return Ok(Self::from_file(path)?);
} else {
let default_config = Config::default();
let mut file = std::fs::File::create(path)?;
let ser_config = toml::to_string_pretty(&default_config).unwrap();
file.write_all(ser_config.as_bytes());
return Ok(default_config);
}
}
Err(SettingError::CantLocateDefaultConfig)
}
pub fn save(&self) -> Result<(), SettingError> {
if let Some(dir_path) = env::var("RADARG_CONFIG")
.ok()
.map(|x| PathBuf::from(x))
.or(dirs::config_dir())
{
let path = dir_path.join("rsp.toml");
let mut file = std::fs::File::create(path)?;
let ser_config = toml::to_string_pretty(&self).unwrap();
file.write_all(ser_config.as_bytes());
Ok(())
} else {
Err(SettingError::CantLocateDefaultConfig)
}
}
}