use std::path::Path;
pub(super) fn extract(path: &Path, source: &str) -> Option<String> {
matches!(path.extension()?.to_str()?, "ts" | "tsx" | "js" | "jsx").then_some(())?;
let mut in_jsdoc = false;
for line in source.lines().take(10) {
let line = line.trim();
if line.is_empty() {
continue;
}
let parsed = if in_jsdoc {
parse_jsdoc_body(line)
} else {
parse_first_comment(line)
};
match parsed {
CommentLine::Found(description) => return Some(description),
CommentLine::End => return None,
CommentLine::EnterBlock => in_jsdoc = true,
CommentLine::Skip => {}
}
}
None
}
enum CommentLine {
Found(String),
End,
EnterBlock,
Skip,
}
fn parse_jsdoc_body(line: &str) -> CommentLine {
if let Some(body) = line.strip_prefix('*') {
let body = body.trim();
let body = body.strip_suffix("*/").map_or(body, str::trim);
if !body.is_empty() && body != "/" {
return CommentLine::Found(body.to_string());
}
}
if line.contains("*/") {
CommentLine::End
} else {
CommentLine::Skip
}
}
fn parse_first_comment(line: &str) -> CommentLine {
if let Some(body) = line.strip_prefix("/**") {
return parse_jsdoc_opening(body.trim());
}
line.strip_prefix("//")
.map(str::trim)
.filter(|description| !description.is_empty())
.map_or(CommentLine::End, |description| {
CommentLine::Found(description.to_string())
})
}
fn parse_jsdoc_opening(body: &str) -> CommentLine {
if let Some(body) = body.strip_suffix("*/") {
let body = body.trim();
return if body.is_empty() {
CommentLine::End
} else {
CommentLine::Found(body.to_string())
};
}
if body.is_empty() {
CommentLine::EnterBlock
} else {
CommentLine::Found(body.to_string())
}
}