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
use std::fmt;
use std::marker::PhantomData;
use std::str::FromStr;

use regex::Regex;
use serde_derive::Deserialize;
use serde_json::{Number, Value};

// Reexport everything except mapping, which is a public module
pub use self::{
    property::Property,
    r#enum::EnumEntry,
    r#type::{PrimitiveType, Type},
    unique_items::UniqueItems,
    version::Version,
};

use crate::{deref::OptionDeref, error::Error};

mod r#enum;
pub mod mapping;
mod property;
mod r#type;
mod unique_items;
mod version;

/// JellySchema structure
///
/// # WARNING
///
/// JellySchema is YAML based. Althought, we're deserializing everything into
/// `serde_json` structures like `Value`, `Number` or Rust types. The reason is
/// that we're generating JSON values from the JellySchema. And this allows us
/// to catch missing JSON features (when compared with YAML) during deserialization.
#[derive(Debug, Deserialize)]
pub struct Schema {
    #[serde(default)]
    version: Option<Version>,
    //
    // Mapping extension
    //
    #[serde(default, skip_serializing_if = "Option::is_none")]
    mapping: Option<mapping::Mapping>,
    //
    // Any instance type validation keywords
    //
    #[serde(default, rename = "type", deserialize_with = "deserialize_from_str")]
    r#type: Type,
    #[serde(default, rename = "const", skip_serializing_if = "Option::is_none")]
    r#const: Option<Value>,
    #[serde(default, rename = "default", skip_serializing_if = "Option::is_none")]
    r#default: Option<Value>,
    #[serde(default, rename = "enum", skip_serializing_if = "Vec::is_empty")]
    r#enum: Vec<EnumEntry>,
    #[serde(
        default,
        deserialize_with = "deserialize_as_optional_string",
        skip_serializing_if = "Option::is_none"
    )]
    formula: Option<String>,
    #[serde(default, rename = "readOnly")]
    read_only: bool,
    #[serde(default, rename = "writeOnly")]
    write_only: bool,
    #[serde(default)]
    placeholder: Option<String>,
    #[serde(default)]
    hidden: bool,
    //
    // Object validation keywords
    //
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    properties: Vec<Property>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    keys: Option<Box<Schema>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    values: Option<Box<Schema>>,
    #[serde(default, rename = "additionalProperties")]
    additional_properties: bool,
    //
    // StringList keywords
    //
    #[serde(default, skip_serializing_if = "Option::is_none")]
    separator: Option<String>,
    //
    // Annotation keywords
    //
    #[serde(default, skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    help: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    warning: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    collapsible: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    collapsed: Option<bool>,
    //
    // Array validation keywords
    //
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "deserialize_struct_or_vec"
    )]
    items: Vec<Schema>,
    #[serde(default, rename = "maxItems", skip_serializing_if = "Option::is_none")]
    max_items: Option<usize>,
    #[serde(default, rename = "minItems", skip_serializing_if = "Option::is_none")]
    min_items: Option<usize>,
    #[serde(default, rename = "uniqueItems")]
    unique_items: UniqueItems,
    #[serde(default)]
    orderable: Option<bool>,
    #[serde(default)]
    addable: Option<bool>,
    #[serde(default)]
    removable: Option<bool>,
    //
    // Number validation keywords
    //
    #[serde(default, rename = "multipleOf", skip_serializing_if = "Option::is_none")]
    multiple_of: Option<Number>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    max: Option<Number>,
    #[serde(default, rename = "exclusiveMax", skip_serializing_if = "Option::is_none")]
    exclusive_max: Option<Number>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    min: Option<Number>,
    #[serde(default, rename = "exclusiveMin", skip_serializing_if = "Option::is_none")]
    exclusive_min: Option<Number>,
    //
    // String based types validation keywords
    //
    #[serde(default, rename = "maxLength", skip_serializing_if = "Option::is_none")]
    max_length: Option<usize>,
    #[serde(default, rename = "minLength", skip_serializing_if = "Option::is_none")]
    min_length: Option<usize>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_option_from_str"
    )]
    pattern: Option<Regex>,
}

impl Schema {
    pub fn version(&self) -> Option<u8> {
        self.version.as_ref().map(Version::value)
    }
}

//
// Any instance type
//
impl Schema {
    pub fn r#type(&self) -> &Type {
        &self.r#type
    }

    pub fn r#const(&self) -> Option<&Value> {
        self.r#const.as_ref()
    }

    pub fn r#default(&self) -> Option<&Value> {
        self.r#default.as_ref()
    }

    pub fn r#enum(&self) -> &[EnumEntry] {
        self.r#enum.as_slice()
    }

    pub fn formula(&self) -> Option<&str> {
        self.formula.as_deref()
    }

    pub fn placeholder(&self) -> Option<&str> {
        self.placeholder.as_deref()
    }

    pub fn read_only(&self) -> bool {
        self.read_only
    }

    pub fn write_only(&self) -> bool {
        self.write_only
    }

    pub fn hidden(&self) -> bool {
        self.hidden
    }
}

//
// Mapping extension
//
impl Schema {
    pub fn mapping(&self) -> Option<&mapping::Mapping> {
        self.mapping.as_ref()
    }
}

//
// Object validation keywords
//
impl Schema {
    pub fn properties(&self) -> &[Property] {
        self.properties.as_slice()
    }

    pub fn keys(&self) -> Option<&Schema> {
        self.keys.as_deref()
    }

    pub fn values(&self) -> Option<&Schema> {
        self.values.as_deref()
    }

    pub fn additional_properties(&self) -> bool {
        self.additional_properties
    }
}

//
// StringList keywords
//
impl Schema {
    pub fn separator(&self) -> Option<&str> {
        self.separator.as_deref()
    }
}

//
// Annotation keywords
//
impl Schema {
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    pub fn help(&self) -> Option<&str> {
        self.help.as_deref()
    }

    pub fn warning(&self) -> Option<&str> {
        self.warning.as_deref()
    }

    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    pub fn collapsed(&self) -> Option<bool> {
        self.collapsed
    }

    pub fn collapsible(&self) -> Option<bool> {
        self.collapsible
    }
}

//
// Number validation keywords
//
impl Schema {
    pub fn multiple_of(&self) -> Option<&Number> {
        self.multiple_of.as_ref()
    }

    pub fn max(&self) -> Option<&Number> {
        self.max.as_ref()
    }

    pub fn min(&self) -> Option<&Number> {
        self.min.as_ref()
    }

    pub fn exclusive_max(&self) -> Option<&Number> {
        self.exclusive_max.as_ref()
    }

    pub fn exclusive_min(&self) -> Option<&Number> {
        self.exclusive_min.as_ref()
    }
}

//
// String based types validation keywords
//
impl Schema {
    pub fn max_length(&self) -> Option<usize> {
        self.max_length
    }

    pub fn min_length(&self) -> Option<usize> {
        self.min_length
    }

    pub fn pattern(&self) -> Option<&Regex> {
        self.pattern.as_ref()
    }
}

//
// Array validation keywords
//
impl Schema {
    pub fn items(&self) -> &[Schema] {
        self.items.as_slice()
    }

    pub fn max_items(&self) -> Option<usize> {
        self.max_items
    }

    pub fn min_items(&self) -> Option<usize> {
        self.min_items
    }

    pub fn unique_items(&self) -> &UniqueItems {
        &self.unique_items
    }

    pub fn addable(&self) -> Option<bool> {
        self.addable
    }

    pub fn removable(&self) -> Option<bool> {
        self.removable
    }

    pub fn orderable(&self) -> Option<bool> {
        self.orderable
    }
}

impl FromStr for Schema {
    type Err = Error;

    fn from_str(s: &str) -> Result<Schema, Error> {
        let schema: Schema = serde_yaml::from_str(s)?;
        Ok(schema)
    }
}

fn deserialize_from_str<'de, S, D>(deserializer: D) -> Result<S, D::Error>
where
    S: FromStr,
    S::Err: std::fmt::Display,
    D: serde::de::Deserializer<'de>,
{
    let s: String = serde::de::Deserialize::deserialize(deserializer)?;
    S::from_str(&s).map_err(serde::de::Error::custom)
}

fn deserialize_as_optional_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    let s: String = match serde::de::Deserialize::deserialize(deserializer)? {
        Value::Bool(x) => format!("{}", x),
        Value::Number(x) => format!("{}", x),
        Value::String(x) => x.clone(),
        _ => return Err(serde::de::Error::custom("unable to deserialize as string")),
    };

    Ok(Some(s))
}

fn deserialize_option_from_str<'de, S, D>(deserializer: D) -> Result<Option<S>, D::Error>
where
    S: FromStr,
    S::Err: std::fmt::Display,
    D: serde::de::Deserializer<'de>,
{
    let s: String = serde::de::Deserialize::deserialize(deserializer)?;
    Ok(Some(S::from_str(&s).map_err(serde::de::Error::custom)?))
}

fn deserialize_struct_or_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    T: serde::de::Deserialize<'de>,
    D: serde::de::Deserializer<'de>,
{
    struct StructOrVec<T>(PhantomData<T>);

    impl<'de, T> serde::de::Visitor<'de> for StructOrVec<T>
    where
        T: serde::de::Deserialize<'de>,
    {
        type Value = Vec<T>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("schema or list of schemas")
        }

        fn visit_map<M>(self, visitor: M) -> Result<Self::Value, M::Error>
        where
            M: serde::de::MapAccess<'de>,
        {
            serde::de::Deserialize::deserialize(serde::de::value::MapAccessDeserializer::new(visitor)).map(|x| vec![x])
        }

        fn visit_seq<S>(self, visitor: S) -> Result<Self::Value, S::Error>
        where
            S: serde::de::SeqAccess<'de>,
        {
            serde::de::Deserialize::deserialize(serde::de::value::SeqAccessDeserializer::new(visitor))
        }
    }

    deserializer.deserialize_any(StructOrVec(PhantomData))
}