|
| 1 | +use std::{fs, io, marker::PhantomData, path::PathBuf}; |
| 2 | + |
| 3 | +use serde::{Deserialize, Serialize}; |
| 4 | +use thiserror::Error; |
| 5 | + |
| 6 | +pub trait Merge<T> { |
| 7 | + fn merge(&self, other: &T) -> Self; |
| 8 | +} |
| 9 | + |
| 10 | +#[derive(Debug, Error)] |
| 11 | +pub enum ConfigPathError { |
| 12 | + #[error("Unable to get OS-specific config directory")] |
| 13 | + UnknownBasePath, |
| 14 | +} |
| 15 | + |
| 16 | +#[derive(Debug, Error)] |
| 17 | +pub enum ConfigInitError { |
| 18 | + #[error("Unable to get config path: {0}")] |
| 19 | + Path(#[from] ConfigPathError), |
| 20 | + |
| 21 | + #[error("I/O error: {0}")] |
| 22 | + IO(#[from] io::Error), |
| 23 | +} |
| 24 | + |
| 25 | +#[derive(Debug, Error)] |
| 26 | +pub enum ConfigSaveError { |
| 27 | + #[error("Unable to get config path: {0}")] |
| 28 | + Path(#[from] ConfigPathError), |
| 29 | + |
| 30 | + #[error("Unable to init config: {0}")] |
| 31 | + Init(#[from] ConfigInitError), |
| 32 | + |
| 33 | + #[error("Unable to serialize config: {0}")] |
| 34 | + Serde(#[from] serde_json::Error), |
| 35 | + |
| 36 | + #[error("I/O error: {0}")] |
| 37 | + IO(#[from] io::Error), |
| 38 | +} |
| 39 | + |
| 40 | +#[derive(Debug, Error)] |
| 41 | +pub enum FileConfigParseError { |
| 42 | + #[error("Unable to get config path: {0}")] |
| 43 | + Path(#[from] ConfigPathError), |
| 44 | + |
| 45 | + #[error("Unable to initialize config: {0}")] |
| 46 | + Init(#[from] ConfigInitError), |
| 47 | + |
| 48 | + #[error("Unable to save config: {0}")] |
| 49 | + Save(#[from] ConfigSaveError), |
| 50 | + |
| 51 | + #[error("I/O error: {0}")] |
| 52 | + IO(#[from] io::Error), |
| 53 | + |
| 54 | + #[error("Unable to serialize or deserialize config: {0}")] |
| 55 | + Serde(#[from] serde_json::Error), |
| 56 | +} |
| 57 | + |
| 58 | +#[derive(Debug, Error)] |
| 59 | +pub enum EnvironmentConfigParseError { |
| 60 | + #[error("Unable to parse environment variables: {0}")] |
| 61 | + Envy(#[from] serde_env::Error), |
| 62 | +} |
| 63 | + |
| 64 | +#[derive(Debug, Error)] |
| 65 | +pub enum ConfigParseError { |
| 66 | + #[error("Unable to parse config from file: {0}")] |
| 67 | + File(#[from] FileConfigParseError), |
| 68 | + |
| 69 | + #[error("Unable to parse config from environment: {0}")] |
| 70 | + Env(#[from] EnvironmentConfigParseError), |
| 71 | +} |
| 72 | + |
| 73 | +#[derive(Debug)] |
| 74 | +pub struct ConfigHandler<FILE, ENV> |
| 75 | +where |
| 76 | + FILE: Serialize + for<'de> Deserialize<'de> + Merge<ENV>, |
| 77 | + ENV: Serialize + for<'de> Deserialize<'de>, |
| 78 | +{ |
| 79 | + pub app_name: String, |
| 80 | + _phantom_file: PhantomData<FILE>, |
| 81 | + _phantom_env: PhantomData<ENV>, |
| 82 | +} |
| 83 | + |
| 84 | +impl<FILE, ENV> ConfigHandler<FILE, ENV> |
| 85 | +where |
| 86 | + FILE: Serialize + for<'de> Deserialize<'de> + Merge<ENV>, |
| 87 | + ENV: Serialize + for<'de> Deserialize<'de>, |
| 88 | +{ |
| 89 | + pub fn new(app_name: &str) -> Self { |
| 90 | + ConfigHandler { |
| 91 | + app_name: app_name.to_string(), |
| 92 | + _phantom_file: PhantomData, |
| 93 | + _phantom_env: PhantomData, |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + pub fn get_config_dir_path(&self) -> Result<PathBuf, ConfigPathError> { |
| 98 | + let mut path = match dirs::config_dir() { |
| 99 | + Some(path) => path, |
| 100 | + None => return Err(ConfigPathError::UnknownBasePath), |
| 101 | + }; |
| 102 | + path.push(&self.app_name); |
| 103 | + |
| 104 | + Ok(path) |
| 105 | + } |
| 106 | + |
| 107 | + pub fn create_config_dir_path(&self) -> Result<(), ConfigInitError> { |
| 108 | + let path = self.get_config_dir_path()?; |
| 109 | + fs::create_dir_all(path)?; |
| 110 | + |
| 111 | + Ok(()) |
| 112 | + } |
| 113 | + |
| 114 | + pub fn get_config_file_path(&self) -> Result<PathBuf, ConfigPathError> { |
| 115 | + let mut path = self.get_config_dir_path()?; |
| 116 | + path.push("config.json"); |
| 117 | + |
| 118 | + Ok(path) |
| 119 | + } |
| 120 | + |
| 121 | + pub fn save_config(&self, config: &FILE) -> Result<(), ConfigSaveError> { |
| 122 | + let path = self.get_config_file_path()?; |
| 123 | + if !path.exists() { |
| 124 | + self.create_config_dir_path()?; |
| 125 | + } |
| 126 | + |
| 127 | + let config_json = serde_json::to_string_pretty(config)?; |
| 128 | + fs::write(path, config_json)?; |
| 129 | + |
| 130 | + Ok(()) |
| 131 | + } |
| 132 | + |
| 133 | + pub fn load_config_from_file(&self) -> Result<FILE, FileConfigParseError> { |
| 134 | + let path = self.get_config_file_path()?; |
| 135 | + if !path.exists() { |
| 136 | + self.create_config_dir_path()?; |
| 137 | + fs::write(&path, "{}")?; |
| 138 | + } |
| 139 | + |
| 140 | + let config_json = fs::read_to_string(path)?; |
| 141 | + let config = serde_json::from_str(&config_json)?; |
| 142 | + self.save_config(&config)?; // In case the config file was missing some fields which serde used the defaults for |
| 143 | + |
| 144 | + Ok(config) |
| 145 | + } |
| 146 | + |
| 147 | + pub fn load_config_from_env(&self) -> Result<ENV, EnvironmentConfigParseError> { |
| 148 | + let prefix = self.app_name.to_uppercase(); |
| 149 | + let config = serde_env::from_env_with_prefix(&prefix)?; |
| 150 | + |
| 151 | + Ok(config) |
| 152 | + } |
| 153 | + |
| 154 | + pub fn merge_configs(prioritized_config: &ENV, secondary_config: FILE) -> FILE { |
| 155 | + secondary_config.merge(prioritized_config) |
| 156 | + } |
| 157 | + |
| 158 | + pub fn load_config(&self) -> Result<FILE, ConfigParseError> { |
| 159 | + let env_config = self.load_config_from_env()?; |
| 160 | + let file_config = self.load_config_from_file()?; |
| 161 | + let merged_config = ConfigHandler::merge_configs(&env_config, file_config); |
| 162 | + |
| 163 | + Ok(merged_config) |
| 164 | + } |
| 165 | +} |
0 commit comments