Skip to content

Commit

Permalink
Clean up, reduce repetition when writing comments
Browse files Browse the repository at this point in the history
  • Loading branch information
sisou committed Aug 14, 2023
1 parent 1816f9e commit 59a214d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 17 deletions.
11 changes: 9 additions & 2 deletions tsify-macros/src/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,21 @@ pub fn extract_doc_comments(attrs: &[syn::Attribute]) -> Vec<String> {
})
}

pub fn format_doc_comments(comments: &Vec<String>) -> String {
pub fn format_doc_comments(
f: &mut std::fmt::Formatter<'_>,
comments: &Vec<String>,
) -> Result<(), std::fmt::Error> {
if comments.is_empty() {
return Ok(());
}

let comment = comments
.iter()
.map(|line| format!(" *{}\n", line.trim_matches('"')))
.collect::<Vec<_>>()
.join("");

format!("/**\n{} */\n", comment)
write!(f, "{}", format!("/**\n{} */\n", comment))
}

pub fn clean_comments(typ: &mut TsType) -> () {
Expand Down
15 changes: 3 additions & 12 deletions tsify-macros/src/decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ impl Display for TsTypeAliasDecl {
format!("{}<{}>", self.id, type_params)
};

if !self.comments.is_empty() {
write!(f, "{}", format_doc_comments(&self.comments))?;
}
format_doc_comments(f, &self.comments)?;

if self.export {
write!(f, "export ")?;
Expand All @@ -57,9 +55,7 @@ pub struct TsInterfaceDecl {

impl Display for TsInterfaceDecl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if !self.comments.is_empty() {
write!(f, "{}", format_doc_comments(&self.comments))?;
}
format_doc_comments(f, &self.comments)?;

write!(f, "export interface {}", self.id)?;

Expand Down Expand Up @@ -226,9 +222,7 @@ impl Display for TsEnumDecl {
writeln!(f, "{}", type_ref)?;
}

if !self.comments.is_empty() {
write!(f, "{}", format_doc_comments(&self.comments))?;
}
format_doc_comments(f, &self.comments)?;

write!(f, "declare namespace {}", self.id)?;

Expand Down Expand Up @@ -267,9 +261,6 @@ impl Display for TsEnumDecl {
self.members
.iter()
.map(|member| {
// let mut type_refs = Vec::new();
// TsEnumDecl::replace_type_params(member.type_ann.clone(), &mut type_refs)

let mut clone = member.type_ann.clone();
clean_comments(&mut clone);
clone
Expand Down
4 changes: 1 addition & 3 deletions tsify-macros/src/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,9 +606,7 @@ impl Display for TsTypeElement {

let optional_ann = if self.optional { "?" } else { "" };

if !self.comments.is_empty() {
write!(f, "{}", format_doc_comments(&self.comments))?;
}
format_doc_comments(f, &self.comments)?;

if is_js_ident(key) {
write!(f, "{key}{optional_ann}: {type_ann}")
Expand Down

0 comments on commit 59a214d

Please sign in to comment.