Set schema title and description from #[doc]s

Work in progress
This commit is contained in:
Graham Esau 2019-12-07 22:14:23 +00:00
parent c630264ef9
commit feefd418d4
6 changed files with 262 additions and 47 deletions

View file

@ -121,6 +121,22 @@ impl SchemaGenerator {
&self.settings
}
// TODO document/rename
#[doc(hidden)]
pub fn objectify(&self, schema: SchemaObject) -> SchemaObject {
if schema.is_ref() {
SchemaObject {
subschemas: Some(Box::new(SubschemaValidation {
all_of: Some(vec![schema.into()]),
..Default::default()
})),
..Default::default()
}
} else {
schema
}
}
/// Returns a `Schema` that matches everything, such as the empty schema `{}`.
///
/// The exact value returned depends on this generator's [`BoolSchemas`](struct.SchemaSettings.html#structfield.bool_schemas) setting.
@ -196,7 +212,7 @@ impl SchemaGenerator {
/// [`definitions`](../schema/struct.Metadata.html#structfield.definitions)
pub fn root_schema_for<T: ?Sized + JsonSchema>(&mut self) -> RootSchema {
let mut schema: SchemaObject = T::json_schema(self).into();
schema.metadata().title = Some(T::schema_name());
schema.metadata().title.get_or_insert_with(T::schema_name);
RootSchema {
meta_schema: self.settings.meta_schema.clone(),
definitions: self.definitions.clone(),
@ -210,7 +226,7 @@ impl SchemaGenerator {
/// include them in the returned `SchemaObject`'s [`definitions`](../schema/struct.Metadata.html#structfield.definitions)
pub fn into_root_schema_for<T: ?Sized + JsonSchema>(mut self) -> RootSchema {
let mut schema: SchemaObject = T::json_schema(&mut self).into();
schema.metadata().title = Some(T::schema_name());
schema.metadata().title.get_or_insert_with(T::schema_name);
RootSchema {
meta_schema: self.settings.meta_schema,
definitions: self.definitions,

53
schemars/tests/docs.rs Normal file
View file

@ -0,0 +1,53 @@
mod util;
use schemars::JsonSchema;
use util::*;
#[derive(Debug, JsonSchema)]
/**
*
* # This is the struct's title
*
* This is the struct's description.
*
*/
pub struct MyStruct {
/// # An integer
pub my_int: i32,
pub my_undocumented_bool: bool,
/// A unit struct instance
pub my_unit: MyUnitStruct,
}
/// # A Unit
#[derive(Debug, JsonSchema)]
pub struct MyUnitStruct;
#[doc = " # This is the enum's title "]
#[doc = " This is..."]
#[derive(Debug, JsonSchema)]
#[doc = "...the enum's description. "]
pub enum MyEnum {
UndocumentedUnit,
/// This comment is not included in the generated schema :(
DocumentedUnit,
/// ## Complex variant
/// This is a struct-like variant.
Complex {
/// ### A nullable string
///
/// This field is a nullable string.
///
/// This is another line!
my_nullable_string: Option<String>,
},
}
#[test]
fn doc_comments_struct() -> TestResult {
test_default_generated_schema::<MyStruct>("doc_comments_struct")
}
#[test]
fn doc_comments_enum() -> TestResult {
test_default_generated_schema::<MyEnum>("doc_comments_enum")
}