schematic 0.20.12

A layered serde configuration and schema library.
Documentation
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
// Each format's renderer uses a different subset of these helpers, so a build
// without every format leaves some unused
#![cfg_attr(
    not(all(feature = "json", feature = "pkl", feature = "toml", feature = "yaml")),
    allow(dead_code)
)]

use crate::schema::RenderResult;
use indexmap::IndexMap;
use miette::miette;
use schematic_types::*;
use std::collections::{HashMap, VecDeque};
use std::mem;

/// Options to control the rendered template.
pub struct TemplateOptions {
    /// Include field comments in output.
    pub comments: bool,

    /// List of field names to render but comment out.
    pub comment_fields: Vec<String>,

    /// Characters to prefix a comment line.
    pub comment_prefix: String,

    /// Custom values for each field. Supports dot notation.
    pub custom_values: HashMap<String, Schema>,

    /// List of array and object field names to expand and render a fake item.
    pub expand_fields: Vec<String>,

    /// Content to append to the bottom of the output.
    pub footer: String,

    /// Content to prepend to the top of the output.
    pub header: String,

    /// List of field names to not render.
    pub hide_fields: Vec<String>,

    /// Character(s) to use for indentation.
    pub indent_char: String,

    /// Insert an extra newline between fields.
    pub newline_between_fields: bool,

    /// List of field names to only render.
    pub only_fields: Vec<String>,
}

impl Default for TemplateOptions {
    fn default() -> Self {
        Self {
            comments: true,
            comment_fields: vec![],
            comment_prefix: "# ".into(),
            custom_values: HashMap::new(),
            expand_fields: vec![],
            footer: String::new(),
            header: String::new(),
            hide_fields: vec![],
            indent_char: "  ".into(),
            newline_between_fields: true,
            only_fields: vec![],
        }
    }
}

pub fn lit_to_string(lit: &LiteralValue) -> String {
    match lit {
        LiteralValue::Bool(inner) => inner.to_string(),
        LiteralValue::F32(inner) => inner.to_string(),
        LiteralValue::F64(inner) => inner.to_string(),
        LiteralValue::Int(inner) => inner.to_string(),
        LiteralValue::UInt(inner) => inner.to_string(),
        LiteralValue::String(inner) => format!("\"{inner}\""),
    }
}

pub fn is_nested_type(schema: &SchemaType) -> bool {
    match schema {
        SchemaType::Struct(sct) => !sct.fields.is_empty(),
        SchemaType::Union(uni) if uni.has_null() && uni.variants_types.len() == 2 => uni
            .variants_types
            .iter()
            .find(|v| !v.is_null())
            .is_some_and(|v| is_nested_type(&v.ty)),
        _ => false,
    }
}

pub struct TemplateContext {
    pub depth: usize,
    pub options: TemplateOptions,

    stack: VecDeque<String>,
}

impl TemplateContext {
    pub fn new(options: TemplateOptions) -> Self {
        Self {
            depth: 0,
            options,
            stack: VecDeque::new(),
        }
    }

    pub fn indent(&self) -> String {
        if self.depth == 0 {
            String::new()
        } else {
            self.options.indent_char.repeat(self.depth)
        }
    }

    pub fn gap(&self) -> &str {
        if self.options.newline_between_fields {
            "\n\n"
        } else {
            "\n"
        }
    }

    pub fn create_field_comment(&self, field: &SchemaField) -> String {
        if !self.options.comments {
            return String::new();
        }

        let mut lines = vec![];
        let indent = self.indent();
        let prefix = self.get_comment_prefix();

        let mut push = |line: String| {
            lines.push(format!("{indent}{prefix}{line}"));
        };

        if let Some(comment) = &field.comment {
            comment
                .trim()
                .split('\n')
                .for_each(|c| push(c.trim().to_owned()));
        }

        if let Some(deprecated) = &field.deprecated {
            push(if deprecated.is_empty() {
                "@deprecated".into()
            } else {
                format!("@deprecated {deprecated}")
            });
        }

        if let Some(env_var) = &field.env_var
            && !env_var.is_empty()
        {
            push(format!("@env {env_var}"));
        }

        if let SchemaType::Enum(enu) = &field.schema.ty
            && let Ok(enum_values) = render_enum_values(enu)
            && !enum_values.is_empty()
        {
            push(format!("@values {enum_values}"));
        }

        if lines.is_empty() {
            return String::new();
        }

        let mut out = lines.join("\n");
        out.push('\n');
        out
    }

    pub fn create_field(&self, field: &SchemaField, property: String) -> String {
        let key = self.get_stack_key();

        format!(
            "{}{}{}{property}",
            self.create_field_comment(field),
            self.indent(),
            if self.options.comment_fields.contains(&key) {
                self.get_comment_prefix()
            } else {
                ""
            },
        )
    }

    pub fn get_comment_prefix(&self) -> &str {
        &self.options.comment_prefix
    }

    pub fn get_stack_key(&self) -> String {
        let mut key = String::new();
        let last_index = self.stack.len() - 1;

        for (index, item) in self.stack.iter().enumerate() {
            key.push_str(item);

            if index != last_index {
                key.push('.');
            }
        }

        key
    }

    pub fn get_stack_value(&self) -> Option<Schema> {
        let key = self.get_stack_key();

        self.options.custom_values.get(&key).cloned()
    }

    pub fn is_expanded(&self, key: &String) -> bool {
        self.options.expand_fields.contains(key)
    }

    pub fn is_hidden(&self, field: &SchemaField) -> bool {
        let key = self.get_stack_key();

        field.hidden
            || self.options.hide_fields.contains(&key)
            || !self.options.only_fields.is_empty() && !self.options.only_fields.contains(&key)
    }

    pub fn push_stack(&mut self, name: &str) {
        self.stack.push_back(name.to_owned());
    }

    pub fn pop_stack(&mut self) {
        self.stack.pop_back();
    }

    pub fn resolve_schema(&self, initial: &Schema, schemas: &IndexMap<String, Schema>) -> Schema {
        if let SchemaType::Reference { name, .. } = &initial.ty {
            if let Some(schema) = schemas.get(name) {
                return schema.to_owned();
            }
        }

        initial.to_owned()
    }

    pub fn validate_schema_variant<'a>(
        &self,
        custom: Option<&'a Schema>,
        fallback: &'a Schema,
    ) -> &'a Schema {
        if let Some(custom) = custom {
            if mem::discriminant(&custom.ty) == mem::discriminant(&fallback.ty) {
                return custom;
            } else {
                panic!(
                    "Received an invalid custom value for `{}`, mismatched schema types.\n\nExpected: {:#?}\n\nReceived: {:#?}",
                    self.get_stack_key(),
                    fallback,
                    custom
                );
            }
        }

        fallback
    }
}

pub fn render_array(_array: &ArrayType) -> RenderResult {
    Ok("[]".into())
}

pub fn render_boolean(boolean: &BooleanType) -> RenderResult {
    if let Some(default) = &boolean.default {
        return Ok(lit_to_string(default));
    }

    Ok("false".into())
}

pub fn render_enum(enu: &EnumType) -> RenderResult {
    // `default_index` indexes the variants, not the values, so resolve it
    // through the enum rather than subscripting `values` directly.
    if let Some(value) = enu.get_default().or_else(|| enu.values.first()) {
        return Ok(lit_to_string(value));
    }

    render_null()
}

pub fn render_enum_values(enu: &EnumType) -> RenderResult {
    let values: Vec<String> = match &enu.variants {
        Some(variants) => variants
            .iter()
            .filter_map(|(_, variant)| {
                if variant.hidden {
                    None
                } else if let SchemaType::Literal(lit) = &variant.schema.ty {
                    Some(lit_to_string(&lit.value))
                } else {
                    None
                }
            })
            .collect(),
        None => enu.values.iter().map(lit_to_string).collect(),
    };

    Ok(values.join(" | "))
}

pub fn render_float(float: &FloatType) -> RenderResult {
    if let Some(default) = &float.default {
        return Ok(lit_to_string(default));
    }

    Ok("0.0".into())
}

pub fn render_integer(integer: &IntegerType) -> RenderResult {
    if let Some(default) = &integer.default {
        return Ok(lit_to_string(default));
    }

    Ok("0".into())
}

pub fn render_literal(literal: &LiteralType) -> RenderResult {
    Ok(lit_to_string(&literal.value))
}

pub fn render_null() -> RenderResult {
    Ok("null".into())
}

pub fn render_object(_object: &ObjectType) -> RenderResult {
    Ok("{}".into())
}

pub fn render_reference(reference: &str) -> RenderResult {
    Ok(reference.into())
}

pub const EMPTY_STRING: &str = "\"\"";

pub fn render_string(string: &StringType) -> RenderResult {
    if let Some(default) = &string.default {
        return Ok(lit_to_string(default));
    }

    Ok(EMPTY_STRING.into())
}

pub fn render_tuple(
    tuple: &TupleType,
    mut render: impl FnMut(&Schema) -> RenderResult,
) -> RenderResult {
    let mut items = vec![];

    for item in &tuple.items_types {
        items.push(render(item)?);
    }

    Ok(format!("[{}]", items.join(", ")))
}

pub fn render_union(
    uni: &UnionType,
    mut render: impl FnMut(&Schema) -> RenderResult,
) -> RenderResult {
    if let Some(index) = &uni.default_index {
        if let Some(variant) = uni.variants_types.get(*index) {
            return render(variant);
        }
    }

    // We have a nullable type, so render the non-null value
    if uni.has_null() {
        if let Some(variant) = uni.variants_types.iter().find(|v| !v.is_null()) {
            return render(variant);
        }
    }

    if let Some(variant) = uni.variants_types.first() {
        return render(variant);
    }

    render_null()
}

pub fn render_unknown() -> RenderResult {
    render_null()
}

pub fn validate_root(schemas: &IndexMap<String, Schema>) -> miette::Result<Schema> {
    let Some(schema) = schemas.values().last() else {
        return Err(miette!(
            "At least 1 schema is required to generate a template."
        ));
    };

    if !schema.is_struct() {
        return Err(miette!("The last registered schema must be a struct type."));
    };

    Ok(schema.to_owned())
}