-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathextract-leading-comments.ts
42 lines (40 loc) · 1.2 KB
/
extract-leading-comments.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { isOpeningParenToken } from "@eslint-community/eslint-utils"
import type { AST } from "svelte-eslint-parser"
import type { RuleContext } from "../../types"
import type { ASTNodeWithParent } from "../../types-for-node"
/** Extract comments */
export function extractLeadingComments(
context: RuleContext,
node: ASTNodeWithParent,
): (AST.Token | AST.Comment)[] {
const sourceCode = context.getSourceCode()
const beforeToken = sourceCode.getTokenBefore(node, {
includeComments: false,
filter(token) {
if (isOpeningParenToken(token)) {
return false
}
const astToken = token as AST.Token
if (astToken.type === "HTMLText") {
return false
}
return astToken.type !== "HTMLComment"
},
})
if (beforeToken) {
return sourceCode
.getTokensBetween(beforeToken, node, { includeComments: true })
.filter(isComment)
}
return sourceCode
.getTokensBefore(node, { includeComments: true })
.filter(isComment)
}
/** Checks whether given token is comment token */
function isComment(token: AST.Token | AST.Comment): boolean {
return (
token.type === "HTMLComment" ||
token.type === "Block" ||
token.type === "Line"
)
}