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
use crate::*;
use std::fmt;

struct Errors<'a>(&'a [Error]);

impl<'a> fmt::Display for Errors<'a> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    for error in self.0 {
      f.write_str("\n\nError: ")?;
      fmt::Display::fmt(error, f)?;
    }

    Ok(())
  }
}

impl<'a> fmt::Debug for Errors<'a> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    f.debug_list().entries(self.0).finish()
  }
}

error_chain! {
  errors {
    ValidationFailed(field: String, msg: String) {
      description("validation failed")
      display("validation failed for field {} with message: {}", field, msg)
    }

    MultipleErrors(errors: Vec<Error>) {
      description("validation failed")
      display("multiple validators failed: {}", Errors(errors))
    }
  }
}

impl Error {
  pub fn validation_failed<S1: Into<String>, S2: Into<String>>(field: S1, msg: S2) -> Self {
    Self::from(ErrorKind::ValidationFailed(field.into(), msg.into()))
  }

  #[doc(hidden)]
  pub fn append_to(self, errors: &mut Vec<Error>) {
    match self.0 {
      ErrorKind::MultipleErrors(e) => errors.extend(e),
      _ => errors.push(self),
    }
  }
}

impl From<Vec<Error>> for Error {
  fn from(mut inner: Vec<Error>) -> Self {
    if inner.len() == 0 {
      panic!("From<Vec<Error>> should not be called on empty vec's");
    } else if inner.len() == 1 {
      inner.remove(0)
    } else {
      ErrorKind::MultipleErrors(inner).into()
    }
  }
}

/// Helper trait for dealing with validation results.
/// Custon `validate` functions (used by the derive macro)
/// requires that the return value implements this trait.
pub trait ValidationResult {
  fn into_result(self) -> Result<()>;
}

impl ValidationResult for Result<()> {
  fn into_result(self) -> Result<()> {
    self
  }
}

impl ValidationResult for () {
  fn into_result(self) -> Result<()> {
    Ok(())
  }
}

impl<E: Into<Error>> ValidationResult for E {
  fn into_result(self) -> Result<()> {
    Err(self.into())
  }
}

/// A type which can be bound by configuration.
pub trait Options {
  /// Bind values from configuration - normally not called directly.
  fn bind_config<C: Configuration>(&mut self, config: &C) -> Result<()>;

  /// Validate current instance after binding.
  fn validate(&self) -> Result<()>;

  /// Bind and validate configuration.
  fn bind<C: Configuration>(&mut self, config: &C) -> Result<()> {
    self.bind_config(config)?;
    self.validate()
  }
}

/// Trait for validating options
pub trait ValidateOptions {
  /// Validate current instance after binding.
  fn validate(&self) -> Result<()> {
    Ok(())
  }
}

/// Trait to produce a value from config.
pub trait FromConfig: Sized {
  /// Get an instance of self from a configuration object.
  fn from_config<C: Configuration>(config: &C) -> Result<Self>;
}

/// Trait for types used as proxy for configuration to get around rust's
/// orphaning rules.
pub trait ConfigProxy<T> {
  /// Bind value based on mutable reference to original value.
  fn bind_proxy<C: Configuration>(value: &mut T, config: &C) -> Result<()>;
}

impl<T> FromConfig for T
where
  T: Options + Default + Sized,
{
  fn from_config<C: Configuration>(config: &C) -> Result<Self> {
    let mut ret = Self::default();
    ret.bind(config)?;
    Ok(ret)
  }
}

// TODO: This can be made better (no need for default)
impl<P, T> ConfigProxy<T> for P
where
  P: Options + Into<T>,
  T: Clone + Into<P>,
{
  fn bind_proxy<C: Configuration>(value: &mut T, config: &C) -> Result<()> {
    let mut proxy = value.clone().into();
    Options::bind(&mut proxy, config)?;
    std::mem::replace(value, proxy.into());
    Ok(())
  }
}

impl Options for String {
  fn bind_config<C: Configuration>(&mut self, config: &C) -> Result<()> {
    if let Some(val) = config.value() {
      *self = val.to_owned();
    }

    Ok(())
  }

  fn validate(&self) -> Result<()> {
    Ok(())
  }
}