1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
extern crate clap;
extern crate preftool;
extern crate preftool_clap;
extern crate preftool_dirs;
extern crate preftool_env;
extern crate preftool_file;
extern crate preftool_toml;
#[macro_use]
extern crate slog;

use preftool::*;
use preftool_clap::*;
use preftool_dirs::*;
use preftool_env::*;
use preftool_file::*;
use slog::Drain;
use std::io::{Read, Result};
use std::marker::PhantomData;
use std::sync::Arc;

trait ConfigSource {
  fn build(&self, builder: ConfigBuilder) -> Result<ConfigBuilder>;
}

struct ConfigSourceWrapper<S: ConfigurationSource> {
  source: S,
}

impl<S: ConfigurationSource + Clone> ConfigSource for ConfigSourceWrapper<S> {
  fn build(&self, builder: ConfigBuilder) -> Result<ConfigBuilder> {
    self.source.clone().build(builder)
  }
}

impl<S: ConfigurationSource> From<S> for ConfigSourceWrapper<S> {
  fn from(source: S) -> Self {
    Self { source }
  }
}

trait ConfigFileFormat {
  fn get_config(&self, reader: Box<dyn Read>) -> Result<Box<dyn ConfigurationProvider>>;
  fn default_suffixes(&self) -> &'static [&'static str];
  fn default_config(
    &self,
    search_paths: SearchPathOwner,
    app_name: String,
  ) -> Box<dyn ConfigSource>;
}

struct ConfigFileFormatWrapper<F: ConfigurationFileFormat> {
  format: PhantomData<*const F>,
}

impl<F: ConfigurationFileFormat> ConfigFileFormatWrapper<F> {
  fn new(_format: F) -> Self {
    Self {
      format: PhantomData,
    }
  }
}

impl<F: ConfigurationFileFormat + 'static> ConfigFileFormat for ConfigFileFormatWrapper<F> {
  fn get_config(&self, reader: Box<dyn Read>) -> Result<Box<dyn ConfigurationProvider>> {
    let provider = F::get_config(reader)?;
    Ok(Box::new(provider))
  }

  fn default_suffixes(&self) -> &'static [&'static str] {
    F::default_suffixes()
  }

  fn default_config(
    &self,
    search_paths: SearchPathOwner,
    app_name: String,
  ) -> Box<dyn ConfigSource> {
    Box::new(ConfigSourceWrapper::from(F::default_config_files(
      search_paths,
      app_name,
    )))
  }
}

trait ConfigArgsFormat<'a: 'b, 'b> {
  fn get_config(&self, app: clap::App<'a, 'b>) -> Result<Box<dyn ConfigurationProvider>>;
}

struct ConfigArgsFormatWrapper<T: ClapConfig> {
  args_type: PhantomData<*const T>,
}

impl<T: ClapConfig + Sized> ConfigArgsFormatWrapper<T> {
  fn new() -> Self {
    Self {
      args_type: PhantomData,
    }
  }
}

impl<'a: 'b, 'b, T: ClapConfig + Sized> ConfigArgsFormat<'a, 'b> for ConfigArgsFormatWrapper<T> {
  fn get_config(&self, app: clap::App<'a, 'b>) -> Result<Box<dyn ConfigurationProvider>> {
    let config = T::from_cli(app);
    Ok(Box::new(config))
  }
}

trait DynSearchPaths {
  fn iter(&self) -> Box<dyn Iterator<Item = ConfigPath>>;
  fn logger(&self) -> &slog::Logger;
}

struct SearchPathsWrapper<S: SearchPaths> {
  inner: S,
}

impl<S: SearchPaths> DynSearchPaths for SearchPathsWrapper<S> {
  fn iter(&self) -> Box<dyn Iterator<Item = ConfigPath>> {
    Box::new(self.inner.iter())
  }

  fn logger(&self) -> &slog::Logger {
    self.inner.logger()
  }
}

impl<S: SearchPaths> From<S> for SearchPathsWrapper<S> {
  fn from(inner: S) -> SearchPathsWrapper<S> {
    SearchPathsWrapper { inner }
  }
}

#[derive(Clone)]
struct SearchPathOwner {
  inner: Arc<dyn DynSearchPaths>,
}

impl From<Arc<dyn DynSearchPaths>> for SearchPathOwner {
  fn from(inner: Arc<dyn DynSearchPaths>) -> Self {
    Self { inner }
  }
}

impl LogOwner for SearchPathOwner {
  fn logger(&self) -> &slog::Logger {
    self.inner.logger()
  }
}

impl SearchPaths for SearchPathOwner {
  type Iter = Box<Iterator<Item = ConfigPath> + 'static>;

  fn iter(&self) -> Self::Iter {
    self.inner.iter()
  }
}

pub struct AppConfigBuilder {
  logger: slog::Logger,
  name: String,
  builder: ConfigBuilder,
  formats: Vec<Box<dyn ConfigFileFormat>>,
  args_format: Option<Box<dyn for<'a> ConfigArgsFormat<'a, 'a>>>,
  app_config: Box<dyn for<'a, 'b> Fn(clap::App<'a, 'b>) -> clap::App<'a, 'b>>,
  search_paths: Arc<dyn DynSearchPaths>,
}

impl AppConfigBuilder {
  pub fn new<S: AsRef<str>>(name: S, logger: Option<slog::Logger>) -> std::io::Result<Self> {
    let logger = logger.unwrap_or_else(|| slog::Logger::root(slog_stdlog::StdLog.fuse(), o!()));
    let config_dirs = ConfigDirs::new(&name, Some(logger.clone()))?;
    let search_paths = Arc::new(SearchPathsWrapper::from(config_dirs));
    Ok(Self {
      logger,
      name: name.as_ref().to_owned(),
      builder: ConfigBuilder::new(),
      formats: Vec::new(),
      args_format: None,
      app_config: Box::new(|app| app),
      search_paths,
    })
  }

  pub fn add_format<F: ConfigurationFileFormat + 'static>(mut self, format: F) -> Self {
    self
      .formats
      .push(Box::new(ConfigFileFormatWrapper::new(format)));
    self
  }

  pub fn with_args<T: ClapConfig + 'static>(mut self) -> Self {
    match &self.args_format {
      Some(_) => panic!("Only one args format can be provided."),
      None => {
        self.args_format = Some(Box::new(ConfigArgsFormatWrapper::<T>::new()));
      }
    }

    self
  }

  pub fn configure<F>(mut self, f: F) -> Self
  where
    for<'a, 'b> F: 'static + Fn(clap::App<'a, 'b>) -> clap::App<'a, 'b>,
  {
    let f_old = self.app_config;
    let configure: Box<dyn for<'a, 'b> Fn(clap::App<'a, 'b>) -> clap::App<'a, 'b>> =
      Box::new(move |app| {
        let app = f_old(app);
        f(app)
      });

    self.app_config = configure;
    self
  }
}

impl ConfigurationBuilder for AppConfigBuilder {
  type Config = <ConfigBuilder as ConfigurationBuilder>::Config;

  // TODO: IntoConfigurationProvider trait?
  fn push_provider<P: ConfigurationProvider + 'static>(mut self, source: P) -> Self {
    self.builder = self.builder.push_provider(source);
    self
  }

  fn build(self) -> Result<Self::Config> {
    fn trim_and_lowercase_then_replace_spaces(name: &str, replacement: &str) -> String {
      let mut buf = String::with_capacity(name.len());
      let mut parts = name.split_whitespace();
      let mut current_part = parts.next();
      let replace = !replacement.is_empty();
      while current_part.is_some() {
        let value = current_part.unwrap().to_lowercase();
        buf.push_str(&value);
        current_part = parts.next();
        if replace && current_part.is_some() {
          buf.push_str(replacement);
        }
      }

      buf
    }

    let mut builder = self.builder;
    let search_paths = self.search_paths;
    for format in self.formats {
      let sources = format.default_config(
        search_paths.clone().into(),
        trim_and_lowercase_then_replace_spaces(&self.name, "-"),
      );
      builder = sources.build(builder)?;
    }

    builder = EnvironmentVariablesConfigurationSource::with_prefix(format!("{}_", &self.name))
      .build(builder)?;

    let app = clap::App::new(self.name);
    let app = (self.app_config)(app);

    // TODO: provide different args...
    trace!(self.logger, "Parse application args");
    match self.args_format {
      None => {
        app.get_matches();
      }
      Some(args_fmt) => {
        let provider = args_fmt.get_config(app)?;
        builder = builder.push_provider(provider);
      }
    }

    builder.build()
  }
}