@truenine/eslint9-config
Version:
ESLint 9 configuration package for Compose Client projects with TypeScript, Vue, and modern JavaScript support
79 lines (78 loc) • 2.93 kB
JavaScript
//#region src/rules/code-style/beside-comment.ts
const rule = {
meta: {
type: "layout",
docs: {
description: "Enforce all comments (except JSDoc and tooling) to be beside code to save lines",
recommended: false
},
fixable: "whitespace",
messages: { besideComment: "Comment must be on the same line as code (inline/beside) to save vertical space" },
schema: []
},
create(context) {
const { sourceCode } = context;
return { Program() {
const comments = sourceCode.getAllComments();
const { lines } = sourceCode;
for (const comment of comments) {
if (comment.type === "Shebang") continue;
if (comment.type === "Block" && comment.value.startsWith("*")) continue;
const trimmedValue = comment.value.trim();
if (comment.type === "Line" && (trimmedValue.startsWith("/") || trimmedValue.startsWith("!"))) continue;
if (trimmedValue.startsWith("#")) continue;
if (comment.type === "Line" && (/^(?:TODO|FIXME)\b/i.test(trimmedValue) || trimmedValue.startsWith("@ts-") || trimmedValue.startsWith("ts-") || trimmedValue.startsWith("eslint"))) continue;
const { loc, range } = comment;
if (!loc || !range) continue;
const startLine = loc.start.line;
const endLine = loc.end.line;
for (let i = startLine; i <= endLine; i++) {
const lineText = lines[i - 1];
let lineWithCode = lineText;
if (i === startLine && i === endLine) lineWithCode = lineText.slice(0, loc.start.column) + lineText.slice(loc.end.column);
else if (i === startLine) lineWithCode = lineText.slice(0, loc.start.column);
else if (i === endLine) lineWithCode = lineText.slice(loc.end.column);
else lineWithCode = "";
if (lineWithCode.trim() === "") {
context.report({
loc: {
start: {
line: i,
column: 0
},
end: {
line: i,
column: lineText.length
}
},
messageId: "besideComment",
fix(fixer) {
if (i === endLine && lines[i] !== void 0 && lines[i].trim() !== "") {
const nextLineText = lines[i];
const commentText = sourceCode.getText(comment).trim();
const nextLineEnd = sourceCode.getIndexFromLoc({
line: i + 1,
column: nextLineText.length
});
return fixer.replaceTextRange([range[0], nextLineEnd], `${nextLineText} ${commentText}`);
}
if (i <= 1 || i !== startLine && lines[i - 2].trim() !== "") return null;
const prevLineText = lines[i - 2];
const commentText = sourceCode.getText(comment).trim();
const prevLineStart = sourceCode.getIndexFromLoc({
line: i - 1,
column: 0
});
return fixer.replaceTextRange([prevLineStart, range[1]], `${prevLineText} ${commentText}`);
}
});
break;
}
}
}
} };
}
};
//#endregion
export { rule as default };
//# sourceMappingURL=beside-comment.mjs.map