From a7053123e201192c2f909db9dc2270e1b4a2514a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=80=E1=85=B5=E1=86=B7=E1=84=89=E1=85=A1=E1=86=BC?= =?UTF-8?q?=E1=84=83=E1=85=AE?= Date: Sat, 13 Jan 2024 01:42:54 +0900 Subject: [PATCH] feat: fix considerComments option when require --- src/rules/newline-after-import.js | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/rules/newline-after-import.js b/src/rules/newline-after-import.js index a33bb615b..53d8e75c4 100644 --- a/src/rules/newline-after-import.js +++ b/src/rules/newline-after-import.js @@ -124,7 +124,7 @@ module.exports = { } } - function commentAfterImport(node, nextComment) { + function commentAfterImport(node, nextComment, type) { const lineDifference = getLineDifference(node, nextComment); const EXPECTED_LINE_DIFFERENCE = options.count + 1; @@ -140,7 +140,7 @@ module.exports = { line: node.loc.end.line, column, }, - message: `Expected ${options.count} empty line${options.count > 1 ? 's' : ''} after import statement not followed by another import.`, + message: `Expected ${options.count} empty line${options.count > 1 ? 's' : ''} after ${type} statement not followed by another ${type}.`, fix: options.exactCount && EXPECTED_LINE_DIFFERENCE < lineDifference ? undefined : (fixer) => fixer.insertTextAfter( node, '\n'.repeat(EXPECTED_LINE_DIFFERENCE - lineDifference), @@ -178,7 +178,7 @@ module.exports = { } if (nextComment && typeof nextComment !== 'undefined') { - commentAfterImport(node, nextComment); + commentAfterImport(node, nextComment, 'import'); } else if (nextNode && nextNode.type !== 'ImportDeclaration' && (nextNode.type !== 'TSImportEqualsDeclaration' || nextNode.isExport)) { checkForNewLine(node, nextNode, 'import'); } @@ -201,6 +201,7 @@ module.exports = { const nodePosition = findNodeIndexInScopeBody(scopeBody, node); log('node position in scope:', nodePosition); + const endLine = node.loc.end.line; const statementWithRequireCall = scopeBody[nodePosition]; const nextStatement = scopeBody[nodePosition + 1]; const nextRequireCall = requireCalls[index + 1]; @@ -215,8 +216,17 @@ module.exports = { || !containsNodeOrEqual(nextStatement, nextRequireCall) ) ) { + let nextComment; + if (typeof statementWithRequireCall.parent.comments !== 'undefined' && options.considerComments) { + nextComment = statementWithRequireCall.parent.comments.find((o) => o.loc.start.line >= endLine && o.loc.start.line <= endLine + options.count + 1); + } + + if (nextComment && typeof nextComment !== 'undefined') { - checkForNewLine(statementWithRequireCall, nextStatement, 'require'); + commentAfterImport(statementWithRequireCall, nextComment, 'require'); + } else { + checkForNewLine(statementWithRequireCall, nextStatement, 'require'); + } } }); },