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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
extern crate clap;
extern crate preftool;
#[macro_use]
extern crate bitflags;

use clap::{App, Arg, ArgMatches};
use preftool::*;
use std::collections::HashMap;
use std::ffi::OsString;
use std::rc::Rc;

pub type Validator = dyn Fn(String) -> Result<(), String>;
pub use context::Context;

pub struct ArgBuilder {
  name: ConfigKey,
  long: String,
  help: Option<&'static str>,
  takes_value: bool,
  validate: Option<Rc<Validator>>,
}

impl ArgBuilder {
  pub fn new(name: ConfigKey, long: String) -> Self {
    ArgBuilder {
      name,
      long,
      help: None,
      takes_value: false,
      validate: None,
    }
  }

  pub(crate) fn name(&self) -> &str {
    self.name.as_ref()
  }

  pub fn help(&mut self, help: Option<&'static str>) {
    self.help = help;
  }

  pub fn get_help(&self) -> Option<&str> {
    match self.help {
      None => None,
      Some(s) => Some(s),
    }
  }

  pub fn takes_value(&mut self, takes_value: bool) {
    self.takes_value = takes_value;
  }

  pub fn validate<F>(&mut self, f: F)
  where
    F: Fn(String) -> Result<(), String> + 'static,
  {
    self.validate = Some(Rc::new(f));
  }

  pub(crate) fn partial_clone(&self) -> Self {
    ArgBuilder {
      name: self.name.clone(),
      long: self.long.clone(),
      help: self.help,
      takes_value: self.takes_value,
      validate: None,
    }
  }
}

impl<'a, 'b, 'c> Into<Arg<'a, 'b>> for &'c ArgBuilder
where
  'a: 'b,
  'c: 'a,
{
  fn into(self) -> Arg<'a, 'b> {
    let mut arg = Arg::with_name(self.name.as_ref())
      .long(self.long.as_ref())
      .takes_value(self.takes_value);

    if let Some(help) = self.help {
      arg = arg.help(help);
    }

    if let Some(validate) = &self.validate {
      let validate = validate.clone();
      arg = arg.validator(move |val| validate(val));
    }

    if self.takes_value {
      arg = arg.value_name(self.name.as_ref());
    }

    arg
  }
}

#[derive(Default)]
pub struct AppBuilder {
  args: Vec<ArgBuilder>,
}

// TODO: This should be a trait, so config providers could modify behaivour for "children".
impl AppBuilder {
  pub fn new() -> Self {
    AppBuilder { args: Vec::new() }
  }

  pub fn arg(&mut self, arg: ArgBuilder) {
    self.args.push(arg);
  }

  pub fn adopt(&mut self, builder: AppBuilder) {
    for arg in builder.args.into_iter() {
      self.arg(arg);
    }
  }

  pub fn variants(&mut self, variants: &[AppBuilder]) {
    let mut args = HashMap::new();
    for variant in variants.iter() {
      for arg in variant.args.iter() {
        let name = arg.name();
        let variants = match args.get_mut(name) {
          None => {
            args.insert(name, Vec::new());
            args.get_mut(name).unwrap()
          }

          Some(v) => v,
        };

        variants.push(arg);
      }
    }

    for (_name, args) in args.into_iter() {
      // TODO: Validate that HELP text is the same
      let arg = args.first().unwrap().partial_clone();
      self.arg(arg);
    }
  }
}

pub trait ClapConfig {
  fn configure<'c>(app: &mut AppBuilder, context: Context<'c>, help: Option<&'static str>);
  fn populate<'a, 'c>(
    builder: &mut ConfigurationProviderBuilder,
    matches: &ArgMatches<'a>,
    context: Context<'c>,
  );
}

pub trait AppExt {
  fn get_config<T: ClapConfig>(self) -> DefaultConfigurationProvider;
  fn get_config_from_args<T, I, S>(self, args: I) -> clap::Result<DefaultConfigurationProvider>
  where
    T: ClapConfig,
    I: IntoIterator<Item = S>,
    S: Into<OsString> + Clone;
}

pub trait ClapConfigExt: ClapConfig + Sized {
  fn from_cli<'a, 'b>(app: App<'a, 'b>) -> DefaultConfigurationProvider
  where
    'a: 'b,
  {
    app.get_config::<Self>()
  }

  fn from_cli_args<'a, 'b, I, S>(
    app: App<'a, 'b>,
    args: I,
  ) -> clap::Result<DefaultConfigurationProvider>
  where
    'a: 'b,
    I: IntoIterator<Item = S>,
    S: Into<OsString> + Clone,
  {
    app.get_config_from_args::<Self, I, S>(args)
  }
}

impl<T: ClapConfig + Sized> ClapConfigExt for T {}

impl<'a, 'b> AppExt for App<'a, 'b>
where
  'a: 'b,
{
  fn get_config<T: ClapConfig>(self) -> DefaultConfigurationProvider {
    let mut builder = AppBuilder::new();
    T::configure(&mut builder, Context::new(), None);

    let mut app = self;
    for arg in builder.args.iter() {
      app = app.arg(arg);
    }

    let mut builder = ConfigurationProviderBuilder::new();
    let matches = app.get_matches();
    // println!("Matches: {:#?}", matches);
    T::populate(&mut builder, &matches, Context::new());

    builder.build()
  }

  fn get_config_from_args<T, I, S>(self, args: I) -> clap::Result<DefaultConfigurationProvider>
  where
    T: ClapConfig,
    I: IntoIterator<Item = S>,
    S: Into<OsString> + Clone,
  {
    let mut builder = AppBuilder::new();
    T::configure(&mut builder, Context::new(), None);

    let mut app = self;
    for arg in builder.args.iter() {
      app = app.arg(arg);
    }

    let mut builder = ConfigurationProviderBuilder::new();
    let matches = app.get_matches_from_safe(args)?;
    T::populate(&mut builder, &matches, Context::new());

    Ok(builder.build())
  }
}

pub mod paths {
  use crate::Context;
  use preftool::ConfigKey;

  pub fn arg_name(context: &Context<'_>) -> ConfigKey {
    context.join_path(ConfigKey::separator()).into()
  }

  pub fn arg_long(context: &Context<'_>) -> String {
    context.join_path("-")
  }
}

impl ClapConfig for String {
  fn configure<'c>(app: &mut AppBuilder, context: Context<'c>, help: Option<&'static str>) {
    let name = paths::arg_name(&context);
    let long = paths::arg_long(&context);
    let mut arg = ArgBuilder::new(name, long);
    arg.help(help);
    arg.takes_value(true);

    app.arg(arg);
  }

  fn populate<'a, 'c>(
    builder: &mut ConfigurationProviderBuilder,
    matches: &ArgMatches<'a>,
    context: Context<'c>,
  ) {
    let name = paths::arg_name(&context);
    match matches.value_of(&name) {
      None => (),
      Some(v) => {
        builder.add(name, v);
      }
    }
  }
}

impl<T: ClapConfig> ClapConfig for Option<T> {
  fn configure<'c>(app: &mut AppBuilder, context: Context<'c>, help: Option<&'static str>) {
    T::configure(app, context.optional(), help);
  }

  fn populate<'a, 'c>(
    builder: &mut ConfigurationProviderBuilder,
    matches: &ArgMatches<'a>,
    context: Context<'c>,
  ) {
    T::populate(builder, matches, context.optional());
  }
}

impl ClapConfig for usize {
  fn configure<'c>(app: &mut AppBuilder, context: Context<'c>, help: Option<&'static str>) {
    let name = paths::arg_name(&context);
    let long = paths::arg_long(&context);
    let mut arg = ArgBuilder::new(name, long);
    arg.help(help);
    arg.takes_value(true);
    arg.validate(|s| match s.parse::<usize>() {
      Ok(_) => Ok(()),
      Err(e) => Err(format!("{:?}", e)),
    });

    app.arg(arg);
  }

  fn populate<'a, 'c>(
    builder: &mut ConfigurationProviderBuilder,
    matches: &ArgMatches<'a>,
    context: Context<'c>,
  ) {
    let name = paths::arg_name(&context);
    match matches.value_of(&name) {
      None => (),
      Some(v) => {
        builder.add(name, v);
      }
    }
  }
}

mod context;