use std::collections::HashMap;
use std::path::Path;
use serde::Deserialize;
use url::Url;
use crate::Error;
#[derive(Debug, Deserialize, Clone)]
#[allow(dead_code)]
pub(crate) struct Network {
pub(crate) state: Url,
pub(crate) prover: Url,
pub(crate) archiver: Option<Url>,
pub(crate) explorer: Option<Url>,
pub(crate) network: Option<HashMap<String, Network>>,
}
use std::{fs, io};
#[derive(Debug)]
pub struct Config {
pub(crate) network: Network,
}
fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<Option<String>> {
fs::read_to_string(&path)
.map(Some)
.or_else(|e| match e.kind() {
io::ErrorKind::NotFound => Ok(None),
_ => Err(e),
})
}
impl Config {
pub fn load(profile: &Path) -> Result<Config, Error> {
let profile = profile.join("config.toml");
let mut global_config = dirs::home_dir();
match global_config {
Some(ref mut path) => {
path.push(".config");
path.push(env!("CARGO_BIN_NAME"));
path.push("config.toml");
let contents = match read_to_string(&profile)? {
Some(contents) => Some(contents),
None => read_to_string(path.clone())?,
};
let contents = match contents {
Some(contents) => contents,
None => {
let default_config =
include_str!("../../default.config.toml");
if let Some(parent) = path.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::write(path, default_config);
default_config.to_string()
}
};
let network: Network = toml::from_str(&contents)
.map_err(|_| Error::NetworkNotFound)?;
Ok(Config { network })
}
None => Err(Error::OsNotSupported),
}
}
}