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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Structures for representing configuration items and values.
//!
//! This basic `Item` structure is used to create the two fundamental types
//! of just-config:
//!
//! - [`StringItem`]
//! - [`TypedItem`]
//!
//! The configuration pipeline uses the two types of configuration items at
//! different stages. The configuration pipeline looks like the following:
//!
//! ```text
//! +--------+   +------------+   +------------+   +----------------+
//! | source +-->| processors +-->| validators |-->| ValueExtractor |
//! +--------+   +------------+   +------------+   +----------------+
//! ```
//!
//! To make this more transparent take the following example:
//!
//! ```rust
//! # use justconfig::Config;
//! # use justconfig::ConfPath;
//! # use justconfig::item::ValueExtractor;
//! # use justconfig::sources::defaults::Defaults;
//! # use justconfig::processors::Trim;
//! # use justconfig::validators::Range;
//! #
//! # let mut conf = Config::default();
//! # let mut defaults = Defaults::default();
//! # defaults.set(conf.root().push_all(&["myvalue"]), "3", "source info");
//! # conf.add_source(defaults);
//! #
//! let myvalue: u32 = conf.get(ConfPath::from(&["myvalue"])).trim().max(5).value().expect("myvalue not found");
//! ```
//!
//! The first part `conf.get` searches all registered configuration sources and
//! returns a `Result<StringItem, ConfigError>`.
//!
//! The following `trim()` method is a processor. Processors operate on the
//! string value of the configuration item and manipulate the string without
//! knowing anything about the meaning of the string.
//!
//! The next call is `max(5)`. This is a validator. Validators need to know more
//! about the meaning of the string value. Therefore the first call of validator
//! converts the `Result<StringItem, ConfigError>` into a
//! `Result<TypedItem<T>, ConfigError>`. To make this conversion possible, T must
//! implement the `FromStr` trait.
//!
//! This conversion is also responsible for the restriction, that all processors
//! have to be placed before the validators within the pipeline.
//!
//! The last call `value()` is implemented via the
//! [`ValueExtractor`] trait.
//! The `ValueExtractor` can (like [`validators`](crate::validators)) be called on
//! `Result<`[`StringItem`]`, `[`ConfigError`]`>` or `Result<`[`TypedItem<T>`]`, `[`ConfigError`]`>`. It
//! extracts the value from the pipeline and returns it to the caller. There are
//! multiple methods implemented for the [`ValueExtractor`] trait to be able to
//! return different kinds of values:
//!
//! * Optional values
//! * Multiple values
//! * Single, mandatory values
use crate::confpath::ConfPath;
use crate::error::ConfigError;
use std::str::FromStr;
use std::rc::Rc;
use std::convert::TryInto;
use std::error::Error;
use std::ops::RangeBounds;

/// Trait implemented by source location structs provided by data sources.
///
/// This trait is used to provide the source of a configuration entry, for
/// example, for use in error messages.
pub trait SourceLocation : std::fmt::Display + std::fmt::Debug {}

/// Structure representing a configuration value.
///
/// Any configuration item can have multiple configuration values.
///
/// Every configuration value is linked to its source. Every configuration source
/// implements a struct that implements the `SourceLocation` trait. The source
/// location is used to supply information to the user where the configuration
/// value is coming from.
///
/// See [`Item`](crate::item) for more Information.
pub struct Value<T> {
	value: T,
	source: Rc<dyn SourceLocation>
}

impl <T> Value<T> {
	/// Create a new configuration value.
	///
	/// Configuration values are normally created to be included into configuration
	/// [`Item`](crate::item)s.
	pub fn new(value: T, source: Rc<dyn SourceLocation>) -> Rc<Self> {
		Rc::new(Self {
			value,
			source
		})
	}

	/// Returns the source of this configuration value.
	pub fn source(&self) -> Rc<dyn SourceLocation>{
		self.source.clone()
	}
}

#[derive(Clone)]
struct Item<T> {
	key: ConfPath,
	values: Vec<Rc<Value<T>>>
}

/// Newtype for Items while they are passed though the processors of the config
/// pipeline.
///
/// `StringItem` implements some additional methods that are useful while a new
/// `Item` is created within a config source.
/// See [`Source`](crate::Source) for more information.
///
/// For more information about processors and validators see
/// [`Item`](crate::item).
#[derive(Clone)]
pub struct StringItem(Item<String>);

impl StringItem {
	pub(crate) fn new(key: ConfPath) -> Self {
		Self {
			0: Item {
				key,
				values: Vec::with_capacity(1)
			}
		}
	}

	pub(crate) fn from(key: ConfPath, values: &[Rc<Value<String>>]) -> Self {
		Self {
			0: Item {
				key,
				values: Vec::from(values)
			}
		}
	}

	pub(crate) fn push(&mut self, new_value: Rc<Value<String>>) {
		self.0.values.push(new_value);
	}

	pub(crate) fn clear(&mut self) -> &mut Self {
		self.0.values.clear();
		self
	}
}

/// Newtype for Items while they are passed though the validators of the config
/// pipeline and to the [`ValueExtractor`].
///
/// See [`Item`](crate::item) for more Information.
#[derive(Clone)]
pub struct TypedItem<T: FromStr>(Item<T>);

impl <T: FromStr> TypedItem<T> {
	pub(crate) fn new(key: ConfPath, values: Vec<Rc<Value<T>>>) -> Self {
		Self {
			0: Item {
				key,
				values
			}
		}
	}
}

impl <T: FromStr> TypedItem<T> {
	pub fn filter(self, filter: impl Fn(&T) -> Result<(), Box<dyn Error>>) -> Result<Self, ConfigError> {
		for v in self.0.values.iter() {
			filter(&v.value).map_err(|e| ConfigError::ValueError(e, v.source.clone()))?;
		}

		Ok(self)
	}
}

pub enum MapAction {
	Keep,
	Replace(Vec<String>),
	Drop,
	Fail(Box<dyn Error>)
}

impl StringItem {
	pub fn map(self, mapper: impl Fn(&String) -> MapAction) -> Result<Self, ConfigError> {
		let mut mapped_item = StringItem::new(self.0.key);

		for v in self.0.values.into_iter() {
			match mapper(&v.value) {
				MapAction::Keep => mapped_item.push(v),
				MapAction::Replace(new_values_list) => for value in new_values_list.into_iter().map(|mapped_v| Value::new(mapped_v, v.source.clone())) { mapped_item.push(value); },
				MapAction::Drop => (),
				MapAction::Fail(error) => return Err(ConfigError::ValueError(error, v.source.clone()))
			}
		}

		Ok(mapped_item)
	}
}

impl <T: FromStr> TryInto<TypedItem<T>> for Result<StringItem, ConfigError> where T::Err: Error + 'static {
	type Error = ConfigError;

	fn try_into(self) -> Result<TypedItem<T>, ConfigError> {
		let s = self?;

		// Iterate all String-Values...
		let typed_values: Result<Vec<Rc<Value<T>>>, ConfigError> = s.0.values.into_iter().map(|v|
			// ...and convert them to T...
			v.value.parse::<T>().map(|nv|
				Value::new(nv, v.source.clone())
			)
			// ...if an error occures while converting, map it to a ConfigError...
			.map_err(|e| ConfigError::from_error(e, v.source.clone()))
		)
		//.. and collect everything. If there is one Result::Err this will lead to an err on the final collection
		.collect();

		Ok(TypedItem::new(s.0.key, typed_values?))
	}
}

/// Trait implemented for `TypedItem` and `StringItem` to allow retrieval of the
/// stored config value.
///
/// This Trait is implemented for `Result<TypedItem<T>, ConfigError>` and
/// `Result<StringItem, ConfigError>`. This makes sure that the methods can be
/// called on the raw `StringItems` and on the `TypedItems` returned by
/// [validators](crate::validators).
///
/// The Implementation for `StringItem` will do the same conversion that is
/// normally done when calling a validator.
pub trait ValueExtractor<T: FromStr> {
	/// Returns a configuration value if it exists or ´None´ otherwise.
	///
	/// An error is only returned if one of the following occures:
	/// * The value of the configuration item could not be converted into the
	///   required data type.
	/// * A processor or validator returned an error.
	/// * There is more that one value available.
	///
	/// This method should be used to return optional configuration values.
	/// A default value can be provided by using `unwrap_or`.
	///
	/// ## Example
	///
	/// ```rust
	/// # use justconfig::Config;
	/// # use justconfig::ConfPath;
	/// # use justconfig::item::ValueExtractor;
	/// # use justconfig::sources::defaults::Defaults;
	/// #
	/// # let mut conf = Config::default();
	/// # let mut defaults = Defaults::default();
	/// # defaults.set(conf.root().push_all(&["myvalue"]), "3", "source info");
	/// # conf.add_source(defaults);
	/// #
	/// let myvalue: u32 = conf.get(ConfPath::from(&["myvalue"])).try_value().expect("Error").unwrap_or(0);
	/// ```
	fn try_value(self) -> Result<Option<T>, ConfigError>;

	/// Returns a configuration value or raises an error if it does not exists.
	///
	/// This method works like [`try_value()`](Self::try_value) but returns an error if the
	/// configuration item does not exist.
	///
	/// This method should be used to return mandatory configuration values that
	/// should result in an error if they are not found.
	///
	/// ## Example
	///
	/// ```rust
	/// # use justconfig::Config;
	/// # use justconfig::ConfPath;
	/// # use justconfig::item::ValueExtractor;
	/// # use justconfig::sources::defaults::Defaults;
	/// #
	/// # let mut conf = Config::default();
	/// # let mut defaults = Defaults::default();
	/// # defaults.set(conf.root().push_all(&["myvalue"]), "3", "source info");
	/// # conf.add_source(defaults);
	/// #
	/// let myvalue: u32 = conf.get(ConfPath::from(&["myvalue"])).value().expect("Error or not found");
	/// ```
	fn value(self) -> Result<T, ConfigError>;

	/// Returns all configuration values for a configuration item.
	///
	/// This is the only method that allows more than one configuration value
	/// to exist. Use this method to read multi value items. If the
	/// configuration item does not exist, an empty array is returned.
	///
	/// The method accepts a range to specify how many configuration values can
	/// be set for this item. If any number of configuration values are
	/// acceptible, just specify `..`. If the number of values should be
	/// limited, specify a range.
	///
	/// ## Example
	///
	/// ```rust
	/// # use justconfig::Config;
	/// # use justconfig::ConfPath;
	/// # use justconfig::item::ValueExtractor;
	/// # use justconfig::sources::defaults::Defaults;
	/// #
	/// # let mut conf = Config::default();
	/// # let mut defaults = Defaults::default();
	/// # defaults.set(conf.root().push_all(&["myvalue"]), "3", "source info");
	/// # conf.add_source(defaults);
	/// #
	/// let myvalue: Vec<u32> = conf.get(ConfPath::from(&["myvalue"])).values(..).expect("Error");
	/// ```
	///
	/// If there must be at least one instance of `myvalue` specify a range of
	/// `1..`:
	///
	/// ```rust
	/// # use justconfig::Config;
	/// # use justconfig::ConfPath;
	/// # use justconfig::item::ValueExtractor;
	/// # use justconfig::sources::defaults::Defaults;
	/// #
	/// # let mut conf = Config::default();
	/// # let mut defaults = Defaults::default();
	/// # defaults.set(conf.root().push_all(&["myvalue"]), "3", "source info");
	/// # conf.add_source(defaults);
	/// #
	/// let myvalue: Vec<u32> = conf.get(ConfPath::from(&["myvalue"])).values(1..).expect("Error");
	/// ```
	///
	/// If the number of values should be limited to at most 3 values the range
	/// must be `..=3`.
	///
	fn values<R: RangeBounds<usize>>(self, range: R) -> Result<Vec<T>, ConfigError>;
}

#[allow(clippy::unnecessary_unwrap)] // Until https://github.com/rust-lang/rfcs/pull/2497 gets implemented
fn values_out_of_range<T: FromStr, R: RangeBounds<usize>>(mut item: TypedItem<T>, range: R) -> Result<Vec<T>, ConfigError> {
	let num_items = item.0.values.len();

	if range.contains(&num_items) {
		item.0.values.drain(..).map(|r| Rc::try_unwrap(r).map(|v| v.value).map_err(|_| ConfigError::MultipleReferences)).collect()
	} else {
		// The number of items is not part of the range. Check if the upper or lower bound
		// was violated.
		// The lower limit is inclusive, the upper is exlusive. This is done to make sure
		// we do not underflow the unsigned value.
		let lower_limit_inc = match range.start_bound() {
			std::ops::Bound::Included(min) => Some(*min),
			std::ops::Bound::Excluded(min) => Some(*min + 1),
			std::ops::Bound::Unbounded => None
		};

		let upper_limit_excl = match range.end_bound() {
			std::ops::Bound::Included(max) => Some(*max + 1),
			std::ops::Bound::Excluded(max) => Some(*max),
			std::ops::Bound::Unbounded => None
		};

		if lower_limit_inc.is_some() && (num_items < lower_limit_inc.unwrap()) {
			// Lower bound violated
			Err(ConfigError::NotEnoughValues(lower_limit_inc.unwrap(), item.0.key))
		} else if upper_limit_excl.is_some() && (num_items >= upper_limit_excl.unwrap()) {
			let first_surplus_index = upper_limit_excl.unwrap().saturating_sub(1);
			// Upper bound violated
			let surplus_sources = item.0.values.drain(first_surplus_index..).map(|r| Rc::try_unwrap(r).map(|v| v.source).map_err(|_| ConfigError::MultipleReferences)).collect::<Result<Vec<Rc<dyn SourceLocation>>, ConfigError>>()?;

			Err(ConfigError::TooManyValues(first_surplus_index, item.0.key, surplus_sources))
		} else {
			unreachable!("This is not possible because we checked that num_items is not contained in range.");
		}
	}
}

impl <T: FromStr> ValueExtractor<T> for Result<TypedItem<T>, ConfigError> {
	fn try_value(self) -> Result<Option<T>, ConfigError> {
		match self.value() {
			Ok(value) => Ok(Some(value)),
			Err(ConfigError::ValueNotFound(_)) => Ok(None),
			Err(error) => Err(error)
		}
	}

	fn value(self) -> Result<T, ConfigError> {
		let mut ci = self?.0;

		match ci.values.len() {
			0 => Err(ConfigError::ValueNotFound(ci.key)),
			1 => Rc::try_unwrap(ci.values.pop().unwrap()).map(|v| v.value).map_err(|_| ConfigError::MultipleReferences),
			_ => Err(ConfigError::TooManyValues(1, ci.key, ci.values.iter().map(|v| v.source()).collect()))
		}
	}

	fn values<R: RangeBounds<usize>>(self, range: R) -> Result<Vec<T>, ConfigError> {
		// This match converts a ValueNotFound error into an empty vector.
		// This makes sure that an empty value-vectors is equvalent with an ValueNotFound error for all purposes.
		match self {
			Ok(item) => values_out_of_range(item, range),
			Err(ConfigError::ValueNotFound(_)) => Ok(Vec::default()),
			Err(error) => Err(error)
		}
	}
}

impl <T: FromStr> ValueExtractor<T> for Result<StringItem, ConfigError> where T::Err: Error + 'static {
	fn try_value(self) -> Result<Option<T>, ConfigError> {
		(self.try_into() as Result<TypedItem<T>, ConfigError>).try_value()
	}

	fn value(self) -> Result<T, ConfigError> {
		(self.try_into() as Result<TypedItem<T>, ConfigError>).value()
	}

	fn values<R: RangeBounds<usize>>(self, range: R) -> Result<Vec<T>, ConfigError> {
		(self.try_into() as Result<TypedItem<T>, ConfigError>).values(range)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::Config;
	use crate::sources::defaults::{Defaults};
	use crate::error::ConfigError;

	fn prepare_test_config() -> Config {
		let mut c = Config::default();

		let mut defaults = Defaults::default();
		defaults.empty(c.root().push_all(&["no_value"]));
		defaults.set(c.root().push_all(&["one_value"]), "one_value", "1.1");
		defaults.put(c.root().push_all(&["two_values"]), "two_values", "2.1");
		defaults.put(c.root().push_all(&["two_values"]), "two_values", "2.2");
		c.add_source(defaults);

		c
	}

	#[test]
	fn value_no_value() {
		let c = prepare_test_config();

		assert_eq!(format!("{}", (c.get(c.root().push_all(&["no_value"])).value() as Result<String, ConfigError>).unwrap_err()), "Missing value for config key 'no_value'.");
	}

	#[test]
	fn value_one_value() {
		let c = prepare_test_config();

		assert_eq!((c.get(c.root().push_all(&["one_value"])).value() as Result<String, ConfigError>).unwrap(), "one_value");
	}

	#[test]
	fn value_two_values() {
		let c = prepare_test_config();

		assert_eq!(format!("{}", (c.get(c.root().push_all(&["two_values"])).value() as Result<String, ConfigError>).unwrap_err()), "More than 1 value found for key two_values@['default from 2.1', 'default from 2.2']");
	}

	#[test]
	fn try_value_no_value() {
		let c = prepare_test_config();

		assert!((c.get(c.root().push_all(&["no_value"])).try_value() as Result<Option<String>, ConfigError>).unwrap().is_none());
	}

	#[test]
	fn try_value_one_value() {
		let c = prepare_test_config();

		assert_eq!((c.get(c.root().push_all(&["one_value"])).try_value() as Result<Option<String>, ConfigError>).unwrap().unwrap(), "one_value");
	}

	#[test]
	fn try_value_two_values() {
		let c = prepare_test_config();

		assert_eq!(format!("{}", (c.get(c.root().push_all(&["two_values"])).try_value() as Result<Option<String>, ConfigError>).unwrap_err()), "More than 1 value found for key two_values@['default from 2.1', 'default from 2.2']");
	}

	#[test]
	fn values_no_value() {
		let c = prepare_test_config();

		let values: Vec<String> = c.get(c.root().push_all(&["no_value"])).values(..).unwrap();
		assert_eq!(values.len(), 0);
	}

	#[test]
	fn values_one_value() {
		let c = prepare_test_config();

		let mut values: Vec<String> = c.get(c.root().push_all(&["one_value"])).values(..).unwrap();
		assert_eq!(values.len(), 1);
		assert_eq!(values.pop().unwrap(), "one_value");
	}

	#[test]
	fn values_two_values() {
		let c = prepare_test_config();

		let mut values: Vec<String> = c.get(c.root().push_all(&["two_values"])).values(..).unwrap();
		assert_eq!(values.len(), 2);
		assert_eq!(values.pop().unwrap(), "two_values");
		assert_eq!(values.pop().unwrap(), "two_values");
	}

	#[test]
	fn range_lower_limit() {
		let c = prepare_test_config();

		assert_eq!(format!("{}", (c.get(c.root().push_all(&["two_values"])).values(3..) as Result<Vec<String>, ConfigError>).unwrap_err()), "Key \'two_values\' must have at least 3 values.");
		assert_eq!(format!("{}", (c.get(c.root().push_all(&["two_values"])).values(4..5) as Result<Vec<String>, ConfigError>).unwrap_err()), "Key \'two_values\' must have at least 4 values.");
	}

	#[test]
	fn range_upper_limit() {
		let c = prepare_test_config();

		assert_eq!(format!("{}", (c.get(c.root().push_all(&["two_values"])).values(..=1) as Result<Vec<String>, ConfigError>).unwrap_err()), "More than 1 value found for key two_values@['default from 2.2']");
		assert_eq!(format!("{}", (c.get(c.root().push_all(&["two_values"])).values(1..=1) as Result<Vec<String>, ConfigError>).unwrap_err()), "More than 1 value found for key two_values@['default from 2.2']");
	}

	#[test]
	fn range_ok() {
		let c = prepare_test_config();

		let mut values: Vec<String> = c.get(c.root().push_all(&["two_values"])).values(1..=2).unwrap();
		assert_eq!(values.len(), 2);
		assert_eq!(values.pop().unwrap(), "two_values");
		assert_eq!(values.pop().unwrap(), "two_values");

		let mut values: Vec<String> = c.get(c.root().push_all(&["two_values"])).values(2..3).unwrap();
		assert_eq!(values.len(), 2);
		assert_eq!(values.pop().unwrap(), "two_values");
		assert_eq!(values.pop().unwrap(), "two_values");

		let mut values: Vec<String> = c.get(c.root().push_all(&["two_values"])).values(0..10).unwrap();
		assert_eq!(values.len(), 2);
		assert_eq!(values.pop().unwrap(), "two_values");
		assert_eq!(values.pop().unwrap(), "two_values");

		let mut values: Vec<String> = c.get(c.root().push_all(&["one_value"])).values(..3).unwrap();
		assert_eq!(values.len(), 1);
		assert_eq!(values.pop().unwrap(), "one_value");

		let mut values: Vec<String> = c.get(c.root().push_all(&["one_value"])).values(1..).unwrap();
		assert_eq!(values.len(), 1);
		assert_eq!(values.pop().unwrap(), "one_value");
	}
}