pub mod files;
mod tests;
use crate::errors::{config::ConfigError, io::IoError, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::{fs, path::PathBuf};
use self::files::FilesConfig;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Config {
#[serde(skip)]
pub path: PathBuf,
pub repository_url: Option<String>,
#[serde(default)]
pub files: FilesConfig,
}
impl Default for Config {
fn default() -> Self {
Config {
path: PathBuf::new(), repository_url: None, files: FilesConfig::default(),
}
}
}
impl Config {
pub fn load_config<P>(path: P) -> Result<Self>
where
P: AsRef<Path>,
{
let path = path.as_ref();
let mut config: Config;
if !path.exists() {
return Err(ConfigError::NotFound {
path: path.to_path_buf(),
}
.into());
}
let config_str = fs::read_to_string(path).map_err(|err| IoError::Read {
source: err,
path: path.to_path_buf(),
})?;
config = toml::from_str(&config_str)?;
config.path = path.to_path_buf();
Ok(config)
}
pub fn save_config(&self) -> Result<()> {
if !self.path.exists() {
return Err(ConfigError::NotFound {
path: self.path.to_path_buf(),
}
.into());
}
let config_str = toml::to_string_pretty(self)?;
fs::write(&self.path, config_str).map_err(|err| IoError::Write {
source: err,
path: self.path.to_path_buf(),
})?;
Ok(())
}
pub fn create_config<P>(path: P) -> Result<Self>
where
P: AsRef<Path>,
{
let path: &Path = path.as_ref();
if path.exists() {
return Err(ConfigError::AlreadyExists {
path: path.to_path_buf(),
}
.into());
} else {
fs::create_dir_all(path.parent().unwrap()).map_err(|err| IoError::Create {
source: err,
path: path.to_path_buf(),
})?;
fs::File::create(path).map_err(|err| IoError::Create {
source: err,
path: path.to_path_buf(),
})?;
}
let mut config = Config::default();
let config_str = toml::to_string(&config)?;
fs::write(path, config_str).map_err(|err| IoError::Write {
source: err,
path: path.to_path_buf(),
})?;
config.path = path.to_path_buf();
Ok(config)
}
pub fn delete_config(self) -> Result<()> {
if !self.path.exists() {
return Err(ConfigError::NotFound { path: self.path }.into());
}
fs::remove_file(&self.path).map_err(|err| IoError::Write {
source: err,
path: self.path,
})?;
Ok(())
}
}