From 3742f5732a2579e6d988b0f4c6a3d5fa5d6fda1a Mon Sep 17 00:00:00 2001 From: Kevin Mark Date: Mon, 10 Oct 2022 11:38:46 -0400 Subject: [PATCH] [stylelint-plugin] feat: Improve copyright comment detection (#5655) --- .../src/utils/insertImport.ts | 30 +++++++++++++++---- .../test/insertImport.test.js | 18 +++++++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/packages/stylelint-plugin/src/utils/insertImport.ts b/packages/stylelint-plugin/src/utils/insertImport.ts index bc65c0c015..54ace71db3 100644 --- a/packages/stylelint-plugin/src/utils/insertImport.ts +++ b/packages/stylelint-plugin/src/utils/insertImport.ts @@ -87,16 +87,34 @@ function getLastImport(cssSyntaxType: CssSyntax.SASS | CssSyntax.LESS, root: Roo } /** - * Returns the first copyright header in the file, or undefined if one does not exist + * Returns the first copyright header in the file, or undefined if one does not exist. + * If the first copyright header spans multiple lines, the last line is returned. */ function getCopyrightHeader(root: Root): Comment | undefined { - let copyrightComment: Comment | undefined; + let lastCopyrightComment: Comment | undefined; root.walkComments(comment => { - if (comment.text.toLowerCase().includes("copyright")) { - copyrightComment = comment; - return false; // Stop the iteration + if (lastCopyrightComment) { + if (comment.source?.start === undefined || lastCopyrightComment.source?.end === undefined) { + return false; + } + if (comment.source.start.line === lastCopyrightComment.source.end.line + 1) { + // Copyright continues in next comment via // + lastCopyrightComment = comment; + } else { + // The next comment is not directly under the prior comment + return false; + } + } else if (comment.text.toLowerCase().includes("copyright")) { + lastCopyrightComment = comment; + if (comment.source?.start === undefined || comment.source?.end === undefined) { + return false; + } + if (comment.source.start.line !== comment.source.end.line) { + // A multi-line copyright comment such as /* */ + return false; // Stop the iteration + } } return; }); - return copyrightComment; + return lastCopyrightComment; } diff --git a/packages/stylelint-plugin/test/insertImport.test.js b/packages/stylelint-plugin/test/insertImport.test.js index fcbc2a27cc..9a2d89361f 100644 --- a/packages/stylelint-plugin/test/insertImport.test.js +++ b/packages/stylelint-plugin/test/insertImport.test.js @@ -51,6 +51,24 @@ describe("insertImport", () => { @import "some_path"; +.some-class { width: 10px }`); + }); + + it("Inserts an import below a multi-line copyright header if no other imports exist", () => { + const root = postcss.parse(` +/* copyright 2021 + * and some additional licensing info here + */ + +.some-class { width: 10px }`); + insertImport(CssSyntax.SASS, root, { newline: "\n" }, "some_path"); + expect(root.toString()).to.be.eq(` +/* copyright 2021 + * and some additional licensing info here + */ + +@use "some_path"; + .some-class { width: 10px }`); });