From a1c3daaed8ea20007cee943983eb14f7d1caa4c4 Mon Sep 17 00:00:00 2001 From: Graham Esau Date: Sat, 7 Dec 2019 23:05:55 +0000 Subject: [PATCH] Join adjacent lines in descriptions from #[doc]s --- schemars/tests/docs.rs | 15 +++++++++--- schemars_derive/src/doc_attrs.rs | 40 +++++++++++++++++--------------- 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/schemars/tests/docs.rs b/schemars/tests/docs.rs index 6877fd5..bcbb513 100644 --- a/schemars/tests/docs.rs +++ b/schemars/tests/docs.rs @@ -19,13 +19,14 @@ pub struct MyStruct { } /// # A Unit +/// #[derive(Debug, JsonSchema)] pub struct MyUnitStruct; #[doc = " # This is the enum's title "] -#[doc = " This is..."] +#[doc = " This is "] #[derive(Debug, JsonSchema)] -#[doc = "...the enum's description. "] +#[doc = " the enum's description."] pub enum MyEnum { UndocumentedUnit, /// This comment is not included in the generated schema :( @@ -37,7 +38,15 @@ pub enum MyEnum { /// /// This field is a nullable string. /// - /// This is another line! + /// This + ///is + /// the second + /// line! + /// + /// + /// + /// + /// And this is the third! my_nullable_string: Option, }, } diff --git a/schemars_derive/src/doc_attrs.rs b/schemars_derive/src/doc_attrs.rs index 70ef2ef..ba822e4 100644 --- a/schemars_derive/src/doc_attrs.rs +++ b/schemars_derive/src/doc_attrs.rs @@ -14,23 +14,25 @@ pub fn get_title_and_desc_from_docs(attrs: &[Attribute]) -> (Option, Opt .trim_start_matches('#') .trim() .to_owned(); - let maybe_desc = split.next().map(|s| s.trim().to_owned()); + let maybe_desc = split.next().and_then(get_description); (none_if_empty(title), maybe_desc) } else { - (None, none_if_empty(docs)) + (None, get_description(&docs)) } } -fn none_if_empty(s: String) -> Option { - if s.is_empty() { - None - } else { - Some(s) - } +fn get_description(docs: &str) -> Option { + let desc = docs + .trim() + .split("\n\n") + .filter_map(|line| none_if_empty(line.trim().replace('\n', " "))) + .collect::>() + .join("\n\n"); + none_if_empty(desc) } fn get_docs(attrs: &[Attribute]) -> Option { - let doc_attrs = attrs + let docs = attrs .iter() .filter_map(|attr| { if !attr.path.is_ident("doc") { @@ -44,20 +46,20 @@ fn get_docs(attrs: &[Attribute]) -> Option { None }) - .collect::>(); - - if doc_attrs.is_empty() { - return None; - } - - let mut docs = doc_attrs + .collect::>() .iter() .flat_map(|a| a.split('\n')) .map(str::trim) .skip_while(|s| *s == "") .collect::>() .join("\n"); - - docs.truncate(docs.trim_end().len()); - Some(docs) + none_if_empty(docs) +} + +fn none_if_empty(s: String) -> Option { + if s.is_empty() { + None + } else { + Some(s) + } }