Skip to content

Commit

Permalink
..
Browse files Browse the repository at this point in the history
  • Loading branch information
infiniteregrets committed Sep 17, 2024
1 parent 1c08115 commit d43d3dd
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};

use config::{Config, FileFormat};
use serde::{Deserialize, Serialize};
Expand All @@ -13,25 +13,24 @@ pub struct S2Config {

/// Path to the configuration file
pub fn config_path() -> Result<PathBuf, S2CliError> {
let mut path = dirs::config_dir().ok_or(S2ConfigError::ConfigDirNotFound)?;
let mut path = dirs::config_dir().ok_or(S2ConfigError::DirNotFound)?;
path.push("s2");
path.push("config.toml");
Ok(path)
}

#[allow(dead_code)]
pub fn load_config(path: &PathBuf) -> Result<S2Config, S2ConfigError> {
pub fn load_config(path: &Path) -> Result<S2Config, S2ConfigError> {
let cfg = Config::builder()
.add_source(config::File::new(
path.to_str().ok_or(S2ConfigError::ConfigPathError)?,
path.to_str().ok_or(S2ConfigError::PathError)?,
FileFormat::Toml,
))
.build()
.map_err(|_| S2ConfigError::ConfigLoadError)?;
.map_err(|_| S2ConfigError::LoadError)?;

Ok(cfg
.try_deserialize::<S2Config>()
.map_err(|_| S2ConfigError::ConfigLoadError)?)
cfg.try_deserialize::<S2Config>()
.map_err(|_| S2ConfigError::LoadError)
}

pub fn create_config(config_path: &PathBuf, token: &str) -> Result<(), S2ConfigError> {
Expand All @@ -40,23 +39,23 @@ pub fn create_config(config_path: &PathBuf, token: &str) -> Result<(), S2ConfigE
};

if let Some(parent) = config_path.parent() {
std::fs::create_dir_all(parent).map_err(|_| S2ConfigError::ConfigWriteError)?;
std::fs::create_dir_all(parent).map_err(|_| S2ConfigError::WriteError)?;
}

let toml = toml::to_string(&cfg).unwrap();
std::fs::write(config_path, toml).map_err(|_| S2ConfigError::ConfigWriteError)?;
std::fs::write(config_path, toml).map_err(|_| S2ConfigError::WriteError)?;

Ok(())
}

#[derive(Error, Debug)]
pub enum S2ConfigError {
#[error("Failed to find config directory")]
ConfigDirNotFound,
DirNotFound,
#[error("Failed to find config file")]
ConfigPathError,
PathError,
#[error("Failed to load config file")]
ConfigLoadError,
LoadError,
#[error("Failed to write config file")]
ConfigWriteError,
WriteError,
}

0 comments on commit d43d3dd

Please sign in to comment.