diff --git a/src/comments.ts b/src/comments.ts index f7833251..5bf1a4be 100644 --- a/src/comments.ts +++ b/src/comments.ts @@ -510,6 +510,62 @@ function printTrailingComments(path: NamedNodePath) { return docs; } +export function isFirstImportDeclaration(path: AstPath) { + const { node, parent } = path; + return ( + node.type === SyntaxType.ImportDeclaration && + parent?.type === SyntaxType.Program && + parent.namedChildren.find( + ({ type }) => type === SyntaxType.ImportDeclaration + ) === node + ); +} + +export function printImportComments(path: NamedNodePath) { + const header: Doc[] = []; + const leading: Doc[] = []; + if (hasChild(path, "comments")) { + const leadingComments = path.node.comments.filter( + comment => comment.leading + ); + const ignoreIndex = leadingComments.findIndex(isPrettierIgnore); + let splitIndex = ignoreIndex === -1 ? leadingComments.length : ignoreIndex; + let stopRow = + ignoreIndex === -1 + ? path.node.start.row + : leadingComments[ignoreIndex].start.row; + + while ( + splitIndex > 0 && + leadingComments[splitIndex - 1].end.row >= stopRow + ) { + splitIndex--; + stopRow = Math.min(stopRow, leadingComments[splitIndex].start.row); + } + + const headerComments = new Set(leadingComments.slice(0, splitIndex)); + + path.each(commentPath => { + const { node: comment } = commentPath; + if (!comment.leading) { + return; + } + + if (headerComments.has(comment)) { + header.push(printLeadingComment(commentPath)); + } else { + leading.push(printLeadingComment(commentPath)); + } + }, "comments"); + } + + return { + header, + leading, + trailing: printTrailingComments(path) + }; +} + export function printCommentsSeparately(path: NamedNodePath) { return { leading: printLeadingComments(path), diff --git a/src/printer.ts b/src/printer.ts index 45d4cd74..970854cd 100644 --- a/src/printer.ts +++ b/src/printer.ts @@ -3,6 +3,7 @@ import { canAttachComment, handleLineComment, handleRemainingComment, + isFirstImportDeclaration, isFullyBetweenPrettierIgnore, isPrettierIgnore } from "./comments.ts"; @@ -40,6 +41,7 @@ export default { ); }, canAttachComment, + willPrintOwnComments: isFirstImportDeclaration, isBlockComment(node) { return (node as unknown as CommentNode).type === SyntaxType.BlockComment; }, diff --git a/src/printers/packages-and-modules.ts b/src/printers/packages-and-modules.ts index e4431d03..31b9a9c7 100644 --- a/src/printers/packages-and-modules.ts +++ b/src/printers/packages-and-modules.ts @@ -1,5 +1,6 @@ import type { Doc } from "prettier"; import { builders } from "prettier/doc"; +import { printImportComments } from "../comments.ts"; import { SyntaxType, type NamedNode } from "../node-types.ts"; import { printBlock, @@ -28,11 +29,20 @@ export default { const staticImports: { doc: Doc; names: string[] }[] = []; const imports: { doc: Doc; names: string[] }[] = []; const otherDeclarations: Doc[] = []; + let importHeaderComments: Doc[] = []; + let hasSeenImport = false; path.each(child => { - const doc = print(child); - if (child.node.type === SyntaxType.ImportDeclaration) { + let doc = print(child); + if (!hasSeenImport) { + hasSeenImport = true; + const { header, leading, trailing } = printImportComments(child); + importHeaderComments = header; + if (leading.length || trailing.length) { + doc = [leading, doc, trailing]; + } + } const names = extractNames( child.node.namedChildren[0] as NamedNode< SyntaxType.Identifier | SyntaxType.ScopedIdentifier @@ -53,21 +63,24 @@ export default { : imports ).push({ doc, names }); } else if (!child.isFirst) { - otherDeclarations.push(doc); + otherDeclarations.push(print(child)); } }, "namedChildren"); - parts.push( - ...[moduleImports, staticImports, imports] - .filter(imports => imports.length) - .map(imports => - join( - hardline, - imports.sort(compareFqn).map(({ doc }) => doc) - ) - ), - ...otherDeclarations - ); + const importGroups = [moduleImports, staticImports, imports] + .filter(imports => imports.length) + .map(imports => + join( + hardline, + imports.sort(compareFqn).map(({ doc }) => doc) + ) + ); + + if (importGroups.length && importHeaderComments.length) { + importGroups[0] = [...importHeaderComments, importGroups[0]]; + } + + parts.push(...importGroups, ...otherDeclarations); return [...join([hardline, hardline], parts), hardline]; }, diff --git a/test/unit-test/package_and_imports/classWithHeaderCommentAndImports/_input.java b/test/unit-test/package_and_imports/classWithHeaderCommentAndImports/_input.java new file mode 100644 index 00000000..d75eb9a8 --- /dev/null +++ b/test/unit-test/package_and_imports/classWithHeaderCommentAndImports/_input.java @@ -0,0 +1,11 @@ +package org.mypackage; + +/*- + * License header + */ + +import java.lang.Util; +import java.util.Map; +import com.me.Util; + +public class Prettier {} diff --git a/test/unit-test/package_and_imports/classWithHeaderCommentAndImports/_output.java b/test/unit-test/package_and_imports/classWithHeaderCommentAndImports/_output.java new file mode 100644 index 00000000..d3992ed1 --- /dev/null +++ b/test/unit-test/package_and_imports/classWithHeaderCommentAndImports/_output.java @@ -0,0 +1,11 @@ +package org.mypackage; + +/*- + * License header + */ + +import com.me.Util; +import java.lang.Util; +import java.util.Map; + +public class Prettier {} diff --git a/test/unit-test/package_and_imports/package_and_imports-spec.ts b/test/unit-test/package_and_imports/package_and_imports-spec.ts index 2228de16..258c3207 100644 --- a/test/unit-test/package_and_imports/package_and_imports-spec.ts +++ b/test/unit-test/package_and_imports/package_and_imports-spec.ts @@ -1,10 +1,11 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; -import { testSample } from "../../test-utils.ts"; +import { expectSnippetToBeFormatted, testSample } from "../../test-utils.ts"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); describe("prettier-java", () => { + testSample(path.resolve(__dirname, "./classWithHeaderCommentAndImports")); testSample(path.resolve(__dirname, "./classWithMixedCaseImports")); testSample(path.resolve(__dirname, "./classWithMixedImports")); testSample(path.resolve(__dirname, "./classWithNoImports")); @@ -15,4 +16,242 @@ describe("prettier-java", () => { testSample(path.resolve(__dirname, "./moduleWithOnlyStaticImports")); testSample(path.resolve(__dirname, "./moduleWithOnlyNonStaticImports")); testSample(path.resolve(__dirname, "./packageWithAnnotationsAndImports")); + + describe("import header comments", () => { + it("keeps file header comment before sorted imports without package", async () => { + const snippet = `/* + * Copyright header + */ + +import java.util.List; +import com.example.Foo; + +public class Example {} +`; + const expectedOutput = `/* + * Copyright header + */ + +import com.example.Foo; +import java.util.List; + +public class Example {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + + it("keeps @format pragma before sorted imports with requirePragma", async () => { + const snippet = `/** + * @format + */ + +import java.util.List; +import com.example.Foo; + +public class Example {} +`; + const expectedOutput = `/** + * @format + */ + +import com.example.Foo; +import java.util.List; + +public class Example {} +`; + await expectSnippetToBeFormatted({ + snippet, + expectedOutput, + prettierOptions: { requirePragma: true } + }); + }); + + it("preserves header comment without a following blank line", async () => { + const snippet = `package org.mypackage; + +/*- + * Header + */ +import java.lang.Util; +import com.me.Util; + +public class Example {} +`; + const expectedOutput = `package org.mypackage; + +/*- + * Header + */ +import com.me.Util; +import java.lang.Util; + +public class Example {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + + it("keeps multiple header comments before sorted import groups", async () => { + const snippet = `package org.mypackage; + +// Header 1 + +/* Header 2 */ + +import java.util.Map; +import static com.me.Util.foo; +import module java.base; + +public class Example {} +`; + const expectedOutput = `package org.mypackage; + +// Header 1 + +/* Header 2 */ + +import module java.base; + +import static com.me.Util.foo; + +import java.util.Map; + +public class Example {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + + it("keeps prettier-ignore attached to its import declaration", async () => { + const snippet = `package org.mypackage; + +/* License */ + +// prettier-ignore +import java.util.Map; +import com.me.Util; + +public class Example {} +`; + const expectedOutput = `package org.mypackage; + +/* License */ + +import com.me.Util; +// prettier-ignore +import java.util.Map; + +public class Example {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + + it("keeps inline leading block comment attached to its import declaration", async () => { + const snippet = `package org.mypackage; + +/* License */ +/* inline */ import java.util.Map; +import com.me.Util; + +public class Example {} +`; + const expectedOutput = `package org.mypackage; + +/* License */ +import com.me.Util; +/* inline */ import java.util.Map; + +public class Example {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + + it("does not split same-line comment chains spanning onto the first import or prettier-ignore", async () => { + await expectSnippetToBeFormatted({ + snippet: `package a; + +/* c1 */ /* c2 +*/ import java.util.Map; +import com.me.Util; + +class A {} +`, + expectedOutput: `package a; + +import com.me.Util; +/* c1 */ /* c2 + */ import java.util.Map; + +class A {} +` + }); + + await expectSnippetToBeFormatted({ + snippet: `package a; + +/* license */ + +/* c1 */ /* c2 +*/ /* prettier-ignore */ +import java.util.Map; +import com.me.Util; + +class A {} +`, + expectedOutput: `package a; + +/* license */ + +import com.me.Util; +/* c1 */ /* c2 + */ /* prettier-ignore */ +import java.util.Map; + +class A {} +` + }); + }); + + it("keeps trailing comment on the first import attached to that import", async () => { + const snippet = `package org.mypackage; + +/* License */ + +import java.util.Map; // keep with Map +import com.me.Util; + +public class Example {} +`; + const expectedOutput = `package org.mypackage; + +/* License */ + +import com.me.Util; +import java.util.Map; // keep with Map + +public class Example {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + + it("keeps header comment before sorted imports in module declaration", async () => { + const snippet = `/* + * License header + */ + +import java.util.List; +import com.example.Service; + +module com.example.app {} +`; + const expectedOutput = `/* + * License header + */ + +import com.example.Service; +import java.util.List; + +module com.example.app {} +`; + await expectSnippetToBeFormatted({ snippet, expectedOutput }); + }); + }); });