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
//! `schema_oxidation`: conversion from JSON schemas to Rust objects.
//!
//! This crate provides a way to automatically generate Rust objects (with serialization /
//! deserialization provided by serde) from a pre-existing JSON schema. Currently only fairly basic
//! support is present, though it is sufficient for simple purposes.
//!
//! The schema JSON can either be loaded [from a file](generate_from_file!) located in the
//! project's source tree, or [from a string](generate_from_string!). The latter is primarily
//! useful for testing purposes, though they both function identically under the hood.
use TokenStream;
use syn;
use Parse;
use Result as SynResult;
/// Generate schema objects from a specified string.
///
/// The resulting objects are placed in a module named by the first parameter, with the schema root
/// object named `SchemaRoot`. All other object types will either be named by the names given
/// explicitly in the schema (e.g. for things defined by `$defs` or `definitions`) or given a name
/// based on the closest named ancestor container and the field name.
///
/// For example:
/// ```rust
/// schema_oxidation::generate_from_string!(example_schema: r#"
/// {
/// "$schema": "https://json-schema.org/draft/2020-12/schema",
/// "type": "object",
/// "properties": {
/// "fieldA": { "type": "int" },
/// "fieldB": { "type": "string" },
/// "fieldC": {
/// "type": "object",
/// "properties": {
/// "something": { "type": "string" }
/// }
/// }
/// }
/// }
/// "#);
/// ```
///
/// The generated output will be the following, modulo some extra fields to account for extra JSON
/// data that may be passed in data to be deserialized and not specified in the schema:
/// ```rust
/// mod example_schema {
/// use serde::{Serialize,Deserialize};
/// #[derive(Serialize,Deserialize)]
/// pub struct SchemaRoot {
/// pub fieldA: Option<i64>,
/// pub fieldB: Option<String>,
/// pub fieldC: Option<SchemaRoot_fieldC>
/// }
///
/// #[derive(Serialize,Deserialize)]
/// pub struct SchemaRoot_fieldC {
/// pub something: Option<String>
/// }
///
/// }
/// ```
/// Generate schema objects based on JSON loaded from a file, but is otherwise identical to
/// [generate_from_string!].
///
/// Note that the path passed here must be relative to the Cargo project root, or else
/// this will not work.