From abbaecbdf0e349bedc913436b9c2ea52fc652fb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arnaud=20Barr=C3=A9?= Date: Mon, 30 May 2022 15:09:30 +0200 Subject: [PATCH] Avoid initial new line when using custom group separator --- src/utils/get-sorted-nodes-by-import-order.ts | 12 ++++++++---- .../__snapshots__/ppsi.spec.js.snap | 1 - 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/utils/get-sorted-nodes-by-import-order.ts b/src/utils/get-sorted-nodes-by-import-order.ts index 30d2d5f..016426d 100644 --- a/src/utils/get-sorted-nodes-by-import-order.ts +++ b/src/utils/get-sorted-nodes-by-import-order.ts @@ -70,8 +70,13 @@ export const getSortedNodesByImportOrder: GetSortedNodes = (nodes, options) => { for (const group of importOrder) { // If it's a custom separator, all we need to do is add a newline if (isCustomGroupSeparator(group)) { + const lastNode = finalNodes[finalNodes.length - 1]; + // Avoid empty new line if first group is empty + if (!lastNode) { + continue; + } // Don't add multiple newlines - if (isLastNodeANewline(finalNodes)) { + if (isNodeANewline(lastNode)) { continue; } finalNodes.push(newLineNode); @@ -111,7 +116,6 @@ function isCustomGroupSeparator(pattern: string) { return pattern.trim() === ''; } -function isLastNodeANewline(nodes: ImportOrLine[]) { - const lastNode = nodes[nodes.length - 1]; - return lastNode?.type === 'ExpressionStatement'; +function isNodeANewline(node: ImportOrLine) { + return node.type === 'ExpressionStatement'; } diff --git a/tests/ImportsSeparatedByEmptyRegex/__snapshots__/ppsi.spec.js.snap b/tests/ImportsSeparatedByEmptyRegex/__snapshots__/ppsi.spec.js.snap index 8791ca1..bd23fd5 100644 --- a/tests/ImportsSeparatedByEmptyRegex/__snapshots__/ppsi.spec.js.snap +++ b/tests/ImportsSeparatedByEmptyRegex/__snapshots__/ppsi.spec.js.snap @@ -241,7 +241,6 @@ import fourLevelRelativePath from "../../../../fourLevelRelativePath"; import something from "@server/something"; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // I am top level comment - import abc from "@core/abc"; import otherthing from "@core/otherthing"; import something from "@server/something";