eslint-plugin-complete
Version:
An ESLint plugin that contains useful rules.
78 lines (77 loc) • 3.2 kB
JavaScript
import { TSESTree } from "@typescript-eslint/utils";
import { isCommentOnOwnLine, isSeparatorLine } from "./comments.js";
export function getLeadingLineComments(sourceCode, comments) {
return comments.filter((comment) => comment.type === TSESTree.AST_TOKEN_TYPES.Line // i.e. a "//" comment
&& comment.value.trim() !== ""
&& !comment.value.startsWith("/") // Filter out triple slash directives
&& isCommentOnOwnLine(sourceCode, comment));
}
/**
* Returns an array of grouped comments. For example, the following code would return an array of
* three comment blocks:
*
* ```ts
* // This is the first block.
*
* // This is the second block.
* // We are still in the second block, because there has not been a newline separator yet.
*
* // This is the third block.
* ```
*/
export function getCommentBlocks(comments) {
const commentBlocks = [];
// We cannot use the `comments.entries` method because we mutate `i`.
for (let i = 0; i < comments.length; i++) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const comment = comments[i];
/**
* Remove the initial space that will always live in front of comment line.
*
* For example, the comment of:
*
* ```ts
* // Foo.
* ```
*
* Has a comment value of: " Foo."
*/
const firstCharacter = comment.value[0];
const firstCharacterIsSpace = firstCharacter !== undefined && firstCharacter === " ";
const text = firstCharacterIsSpace ? comment.value.slice(1) : comment.value;
const commentBlock = {
mergedText: text,
originalComments: [comment],
};
const commentIndex = i; // Make a copy of the comment index since we will mutate i later.
const firstCommentStartLine = comment.loc.start.line;
// Look for one or more "connecting" comments on the next subsequent lines.
for (let j = i + 1; j < comments.length; j++) {
const nextComment = comments[j];
if (nextComment === undefined) {
break;
}
// Break if we are on a non-contiguous line.
const nextCommentStartLine = nextComment.loc.start.line;
const lineDelta = j - commentIndex;
if (nextCommentStartLine !== firstCommentStartLine + lineDelta) {
break;
}
// Break if this is a "separator" line.
if (isSeparatorLine(nextComment.value)) {
break;
}
commentBlock.mergedText += "\n";
const nextText = nextComment.value.slice(1);
commentBlock.mergedText += nextText;
commentBlock.originalComments.push(nextComment);
// Since we merged this comment, we can skip over examining it in the parent loop.
i++;
}
commentBlocks.push(commentBlock);
}
return commentBlocks;
}
export function allCommentsInBlockAreCommentedOutArrayElements(commentBlock) {
return commentBlock.originalComments.every((comment) => comment.value.match(/^\s*"[^"]*",\s*$/) !== null);
}