schemars_derive/
metadata.rs

1use proc_macro2::TokenStream;
2
3#[derive(Debug, Clone)]
4pub struct SchemaMetadata<'a> {
5    pub title: Option<&'a str>,
6    pub description: Option<&'a str>,
7    pub deprecated: bool,
8    pub read_only: bool,
9    pub write_only: bool,
10    pub examples: &'a [syn::Path],
11    pub default: Option<TokenStream>,
12}
13
14impl<'a> SchemaMetadata<'a> {
15    pub fn apply_to_schema(&self, schema_expr: &mut TokenStream) {
16        if let Some(title) = &self.title {
17            *schema_expr = quote! {
18                schemars::_private::metadata::add_title(#schema_expr, #title)
19            };
20        }
21        if let Some(description) = &self.description {
22            *schema_expr = quote! {
23                schemars::_private::metadata::add_description(#schema_expr, #description)
24            };
25        }
26
27        if self.deprecated {
28            *schema_expr = quote! {
29                schemars::_private::metadata::add_deprecated(#schema_expr, true)
30            };
31        }
32
33        if self.read_only {
34            *schema_expr = quote! {
35                schemars::_private::metadata::add_read_only(#schema_expr, true)
36            };
37        }
38        if self.write_only {
39            *schema_expr = quote! {
40                schemars::_private::metadata::add_write_only(#schema_expr, true)
41            };
42        }
43
44        if !self.examples.is_empty() {
45            let examples = self.examples.iter().map(|eg| {
46                quote! {
47                    schemars::_serde_json::value::to_value(#eg())
48                }
49            });
50
51            *schema_expr = quote! {
52                schemars::_private::metadata::add_examples(#schema_expr,  [#(#examples),*].into_iter().flatten())
53            };
54        }
55
56        if let Some(default) = &self.default {
57            *schema_expr = quote! {
58                schemars::_private::metadata::add_default(#schema_expr, #default.and_then(|d| schemars::_schemars_maybe_to_value!(d)))
59            };
60        }
61    }
62}