|
| 1 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 | +// you may not use this file except in compliance with the License. |
| 3 | +// You may obtain a copy of the License at |
| 4 | +// |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +// |
| 7 | +// Unless required by applicable law or agreed to in writing, software |
| 8 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +// See the License for the specific language governing permissions and |
| 11 | +// limitations under the License. |
| 12 | +// |
| 13 | +// SPDX-License-Identifier: Apache-2.0 |
| 14 | +//! OpenStackClient configuration |
| 15 | +//! |
| 16 | +
|
| 17 | +use eyre::Result; |
| 18 | +use serde::Deserialize; |
| 19 | +use std::{ |
| 20 | + collections::HashMap, |
| 21 | + fmt, |
| 22 | + path::{Path, PathBuf}, |
| 23 | +}; |
| 24 | +use structable::OutputConfig; |
| 25 | +use thiserror::Error; |
| 26 | +use tracing::error; |
| 27 | + |
| 28 | +const CONFIG: &str = include_str!("../.config/config.yaml"); |
| 29 | + |
| 30 | +/// Errors which may occur when dealing with OpenStack connection |
| 31 | +/// configuration data. |
| 32 | +#[derive(Debug, Error)] |
| 33 | +#[non_exhaustive] |
| 34 | +pub enum ConfigError { |
| 35 | + /// Parsing error |
| 36 | + #[error("failed to parse config: {}", source)] |
| 37 | + Parse { |
| 38 | + /// The source of the error. |
| 39 | + #[from] |
| 40 | + source: config::ConfigError, |
| 41 | + }, |
| 42 | +} |
| 43 | + |
| 44 | +impl ConfigError { |
| 45 | + /// Build a `[ConfigError::Parse]` error from `[config::ConfigError]` |
| 46 | + pub fn parse(source: config::ConfigError) -> Self { |
| 47 | + ConfigError::Parse { source } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/// Errors which may occur when adding sources to the [`ConfigFileBuilder`]. |
| 52 | +#[derive(Error)] |
| 53 | +#[non_exhaustive] |
| 54 | +pub enum ConfigFileBuilderError { |
| 55 | + /// File parsing error |
| 56 | + #[error("failed to parse file {path:?}: {source}")] |
| 57 | + FileParse { |
| 58 | + /// Error source |
| 59 | + source: Box<config::ConfigError>, |
| 60 | + /// Builder object |
| 61 | + builder: ConfigFileBuilder, |
| 62 | + /// Error file path |
| 63 | + path: PathBuf, |
| 64 | + }, |
| 65 | + /// Config file deserialization error |
| 66 | + #[error("failed to deserialize config {path:?}: {source}")] |
| 67 | + ConfigDeserialize { |
| 68 | + /// Error source |
| 69 | + source: Box<config::ConfigError>, |
| 70 | + /// Builder object |
| 71 | + builder: ConfigFileBuilder, |
| 72 | + /// Error file path |
| 73 | + path: PathBuf, |
| 74 | + }, |
| 75 | +} |
| 76 | + |
| 77 | +/// OpenStackClient configuration |
| 78 | +#[derive(Clone, Debug, Default, Deserialize)] |
| 79 | +pub struct Config { |
| 80 | + /// Map of views with the key being the resource key (<SERVICE_NAME>/<RESOURCE>[/<SUBRESOURCE>) |
| 81 | + /// and the value being an `[OutputConfig]` |
| 82 | + #[serde(default)] |
| 83 | + pub views: HashMap<String, OutputConfig>, |
| 84 | +} |
| 85 | + |
| 86 | +/// A builder to create a [`ConfigFile`] by specifying which files to load. |
| 87 | +pub struct ConfigFileBuilder { |
| 88 | + /// Config source files |
| 89 | + sources: Vec<config::Config>, |
| 90 | +} |
| 91 | + |
| 92 | +impl ConfigFileBuilder { |
| 93 | + /// Add a source to the builder. This will directly parse the config and check if it is valid. |
| 94 | + /// Values of sources added first will be overridden by later added sources, if the keys match. |
| 95 | + /// In other words, the sources will be merged, with the later taking precedence over the |
| 96 | + /// earlier ones. |
| 97 | + pub fn add_source(mut self, source: impl AsRef<Path>) -> Result<Self, ConfigFileBuilderError> { |
| 98 | + let config = match config::Config::builder() |
| 99 | + .add_source(config::File::from(source.as_ref())) |
| 100 | + .build() |
| 101 | + { |
| 102 | + Ok(config) => config, |
| 103 | + Err(error) => { |
| 104 | + return Err(ConfigFileBuilderError::FileParse { |
| 105 | + source: Box::new(error), |
| 106 | + builder: self, |
| 107 | + path: source.as_ref().to_owned(), |
| 108 | + }); |
| 109 | + } |
| 110 | + }; |
| 111 | + |
| 112 | + if let Err(error) = config.clone().try_deserialize::<Config>() { |
| 113 | + return Err(ConfigFileBuilderError::ConfigDeserialize { |
| 114 | + source: Box::new(error), |
| 115 | + builder: self, |
| 116 | + path: source.as_ref().to_owned(), |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + self.sources.push(config); |
| 121 | + Ok(self) |
| 122 | + } |
| 123 | + |
| 124 | + /// This will build a [`ConfigFile`] with the previously specified sources. Since |
| 125 | + /// the sources have already been checked on errors, this will not fail. |
| 126 | + pub fn build(self) -> Config { |
| 127 | + let mut config = config::Config::builder(); |
| 128 | + |
| 129 | + for source in self.sources { |
| 130 | + config = config.add_source(source); |
| 131 | + } |
| 132 | + |
| 133 | + config.build().unwrap().try_deserialize().unwrap() |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +impl fmt::Debug for ConfigFileBuilderError { |
| 138 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 139 | + match self { |
| 140 | + ConfigFileBuilderError::FileParse { source, path, .. } => f |
| 141 | + .debug_struct("FileParse") |
| 142 | + .field("source", source) |
| 143 | + .field("path", path) |
| 144 | + .finish_non_exhaustive(), |
| 145 | + ConfigFileBuilderError::ConfigDeserialize { source, path, .. } => f |
| 146 | + .debug_struct("ConfigDeserialize") |
| 147 | + .field("source", source) |
| 148 | + .field("path", path) |
| 149 | + .finish_non_exhaustive(), |
| 150 | + } |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +impl Config { |
| 155 | + /// Instantiate new config reading default config updating it with local configuration |
| 156 | + pub fn new() -> Result<Self, ConfigError> { |
| 157 | + let default_config: config::Config = config::Config::builder() |
| 158 | + .add_source(config::File::from_str(CONFIG, config::FileFormat::Yaml)) |
| 159 | + .build()?; |
| 160 | + |
| 161 | + let config_dir = get_config_dir(); |
| 162 | + let mut builder = ConfigFileBuilder { |
| 163 | + sources: Vec::from([default_config]), |
| 164 | + }; |
| 165 | + |
| 166 | + let config_files = [ |
| 167 | + ("config.yaml", config::FileFormat::Yaml), |
| 168 | + ("views.yaml", config::FileFormat::Yaml), |
| 169 | + ]; |
| 170 | + let mut found_config = false; |
| 171 | + for (file, _format) in &config_files { |
| 172 | + if config_dir.join(file).exists() { |
| 173 | + found_config = true; |
| 174 | + |
| 175 | + builder = match builder.add_source(config_dir.join(file)) { |
| 176 | + Ok(builder) => builder, |
| 177 | + Err(ConfigFileBuilderError::FileParse { source, .. }) => { |
| 178 | + return Err(ConfigError::parse(*source)); |
| 179 | + } |
| 180 | + Err(ConfigFileBuilderError::ConfigDeserialize { |
| 181 | + source, |
| 182 | + builder, |
| 183 | + path, |
| 184 | + }) => { |
| 185 | + error!( |
| 186 | + "The file {path:?} could not be deserialized and will be ignored: {source}" |
| 187 | + ); |
| 188 | + builder |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + } |
| 193 | + if !found_config { |
| 194 | + tracing::error!("No configuration file found. Application may not behave as expected"); |
| 195 | + } |
| 196 | + |
| 197 | + Ok(builder.build()) |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +fn get_config_dir() -> PathBuf { |
| 202 | + dirs::config_dir() |
| 203 | + .expect("Cannot determine users XDG_CONFIG_HOME") |
| 204 | + .join("osc") |
| 205 | +} |
| 206 | + |
| 207 | +impl fmt::Display for Config { |
| 208 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 209 | + write!(f, "") |
| 210 | + } |
| 211 | +} |
0 commit comments