diff --git a/CHANGES.md b/CHANGES.md index 50b28f3e72..04a0cbc602 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -11,6 +11,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] +### Fixed +- `forbidWildcardImports` no longer reports import statements inside Java text blocks or comments. ([#2997](https://github.com/diffplug/spotless/issues/2997)) + ## [4.11.0] - 2026-11-02 ### Added - Add a `cleanup` option to `GoogleJavaFormatStep` to disable google-java-format's non-whitespace cleanups. ([#3157](https://github.com/diffplug/spotless/pull/3157)) diff --git a/lib/src/main/java/com/diffplug/spotless/java/ForbidWildcardImportsStep.java b/lib/src/main/java/com/diffplug/spotless/java/ForbidWildcardImportsStep.java index 73eab5be9b..ab155f7753 100644 --- a/lib/src/main/java/com/diffplug/spotless/java/ForbidWildcardImportsStep.java +++ b/lib/src/main/java/com/diffplug/spotless/java/ForbidWildcardImportsStep.java @@ -15,8 +15,14 @@ */ package com.diffplug.spotless.java; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import com.diffplug.spotless.FormatterFunc; import com.diffplug.spotless.FormatterStep; -import com.diffplug.spotless.generic.ReplaceRegexStep; +import com.diffplug.spotless.Lint; /** Forbids any wildcard import statements. */ public final class ForbidWildcardImportsStep { @@ -31,6 +37,137 @@ public final class ForbidWildcardImportsStep { private ForbidWildcardImportsStep() {} public static FormatterStep create() { - return ReplaceRegexStep.lint(NAME, REGEX, ERROR); + return FormatterStep.create(NAME, Pattern.compile(REGEX, Pattern.UNIX_LINES | Pattern.MULTILINE), ForbidWildcardImportsStep::toFormatter); + } + + private static FormatterFunc toFormatter(Pattern regex) { + return new FormatterFunc() { + @Override + public String apply(String raw) { + return raw; + } + + @Override + public List lint(String raw, File file) { + var matcher = regex.matcher(raw); + if (!matcher.find()) { + return List.of(); + } + List lints = new ArrayList<>(); + LexicalInput input = new LexicalInput(raw); + int scanOffset = 0; + int lineOffset = 0; + int line = 1; + do { + // A skipped literal or comment may extend past this apparent import. + while (input.rawOffset(scanOffset) < matcher.start()) { + scanOffset = skipLiteralOrComment(input.text, scanOffset); + } + if (input.rawOffset(scanOffset) > matcher.start()) { + continue; + } + while (lineOffset < matcher.start()) { + if (raw.charAt(lineOffset++) == '\n') { + ++line; + } + } + String errorCode = matcher.group().trim(); + int firstNewline = errorCode.indexOf('\n'); + if (firstNewline != -1) { + errorCode = errorCode.substring(0, firstNewline); + } + lints.add(Lint.atLine(line, errorCode, ERROR)); + } while (matcher.find()); + return lints; + } + }; + } + + /** Skips a complete literal or comment, or advances one character through ordinary code. */ + private static int skipLiteralOrComment(String raw, int offset) { + if (raw.startsWith("//", offset)) { + int end = raw.indexOf('\n', offset + 2); + return end == -1 ? raw.length() : end; + } + if (raw.startsWith("/*", offset)) { + int end = raw.indexOf("*/", offset + 2); + return end == -1 ? raw.length() : end + 2; + } + char c = raw.charAt(offset); + if (c == '"' || c == '\'') { + String delimiter = raw.startsWith("\"\"\"", offset) ? "\"\"\"" : String.valueOf(c); + int end = offset + delimiter.length(); + while (end < raw.length()) { + if (raw.charAt(end) == '\\') { + // An escaped quote cannot close a literal or text block. + end += 2; + } else if (raw.startsWith(delimiter, end)) { + return end + delimiter.length(); + } else { + ++end; + } + } + return raw.length(); + } + return offset + 1; + } + + /** Translates Unicode escapes for lexing, while retaining raw offsets for diagnostics. */ + private static final class LexicalInput { + private final String text; + private final int[] rawOffsets; + + LexicalInput(String raw) { + if (!raw.contains("\\u")) { + text = raw; + rawOffsets = new int[0]; + return; + } + StringBuilder translated = new StringBuilder(raw.length()); + rawOffsets = new int[raw.length() + 1]; + int backslashes = 0; + boolean previousWasEscape = false; + for (int offset = 0; offset < raw.length();) { + char c = raw.charAt(offset); + int next = offset + 1; + boolean isEscape = false; + // JLS 3.3: eligibility depends on the translated backslashes, not just the raw input. + if (c == '\\' && (previousWasEscape || backslashes % 2 == 0)) { + int digits = next; + while (digits < raw.length() && raw.charAt(digits) == 'u') { + ++digits; + } + if (digits > next && digits + 4 <= raw.length()) { + int value = 0; + for (int i = digits; i < digits + 4; ++i) { + char digit = raw.charAt(i); + int hex = Character.digit(digit, 16); + if (digit > 127 || hex == -1) { + value = -1; + break; + } + value = value * 16 + hex; + } + if (value != -1) { + c = (char) value; + next = digits + 4; + isEscape = true; + } + } + } + rawOffsets[translated.length()] = offset; + // Unicode escapes can introduce either kind of Java line terminator. + translated.append(c == '\r' ? '\n' : c); + backslashes = c == '\\' ? backslashes + 1 : 0; + previousWasEscape = isEscape; + offset = next; + } + rawOffsets[translated.length()] = raw.length(); + text = translated.toString(); + } + + int rawOffset(int offset) { + return rawOffsets.length == 0 ? offset : rawOffsets[offset]; + } } } diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index ca01a77fe6..ad64937195 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -4,6 +4,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] +### Fixed +- `forbidWildcardImports` no longer reports import statements inside Java text blocks or comments. ([#2997](https://github.com/diffplug/spotless/issues/2997)) + ## [8.11.0] - 2026-11-02 ### Added - Add `cleanup(false)` to `googleJavaFormat()` to disable google-java-format's non-whitespace cleanups. ([#3157](https://github.com/diffplug/spotless/pull/3157)) diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 3a79292d20..9412483668 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -4,6 +4,9 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ## [Unreleased] +### Fixed +- `forbidWildcardImports` no longer reports import statements inside Java text blocks or comments. ([#2997](https://github.com/diffplug/spotless/issues/2997)) + ## [3.11.0] - 2026-11-02 ### Added - Add `false` to `` to disable google-java-format's non-whitespace cleanups. ([#3157](https://github.com/diffplug/spotless/pull/3157)) diff --git a/testlib/src/test/java/com/diffplug/spotless/java/ForbidWildcardImportsStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/ForbidWildcardImportsStepTest.java index e7025a3f43..023e42866a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/ForbidWildcardImportsStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/ForbidWildcardImportsStepTest.java @@ -19,6 +19,7 @@ import com.diffplug.common.base.StringPrinter; import com.diffplug.spotless.FormatterStep; +import com.diffplug.spotless.SerializableEqualityTester; import com.diffplug.spotless.StepHarness; class ForbidWildcardImportsStepTest { @@ -44,4 +45,235 @@ void detectsIndentedWildcardImport() { .toBe("L1 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this", "L2 forbidWildcardImports(import static java.util.Collections.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); } + + @Test + void ignoresTextBlocks() { + String source = StringPrinter.buildStringFromLines( + "import java.util.List;", + "class Example {", + " String source = \"\"\"", + " import java.util.*;", + " import static java.util.Collections.*;", + " \"\"\";", + "}"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source).toBe("(none)"); + } + + @Test + void ignoresEscapedQuotesAndCommentMarkersInsideTextBlocks() { + String source = StringPrinter.buildStringFromLines( + "class Example {", + " String source = \"\"\"", + " \" and \"\" and \\\"\"\" do not close the text block", + " import java.util.*;", + " /* // ' are text, not comments or character literals", + " import static java.util.Collections.*;", + " \\\\", + " \"\"\";", + " String other = \"\"\"", + " import java.io.*;", + " \"\"\";", + "}"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source).toBe("(none)"); + } + + @Test + void ignoresComments() { + String source = StringPrinter.buildStringFromLines( + "// \"\"\" is not a text block", + "/* \"\"\" ' //", + "import java.util.*;", + "import static java.util.Collections.*;", + "*/", + "/**", + "import java.io.*;", + "*/", + "// import java.net.*;", + "import java.util.List;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source).toBe("(none)"); + } + + @Test + void preservesRealImportDiagnosticsAfterComments() { + String source = StringPrinter.buildStringFromLines( + "/* \"\"\" " + "\ud83d\ude00".repeat(80), + "import ignored.*;", + "*/", + " import java.util.*; // keep the original diagnostic", + "// \"\"\"", + "\timport static java.util.Collections.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L4 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this", + "L6 forbidWildcardImports(import static java.util.Collections.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void quotesInOrdinaryLiteralsDoNotStartTextBlocksOrComments() { + String source = StringPrinter.buildStringFromLines( + "@Example(text = \"\\\"\\\"\\\"\", quote = '\"', apostrophe = '\\'', backslash = '\\\\', block = \"/*\", line = \"//\", escaped = \"\\\\\")", + "package example;", + "import java.util.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L3 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void detectsRealImportAfterTextBlockWithEscapedBackslash() { + String source = StringPrinter.buildStringFromLines( + "@Example(\"\"\"", + " import ignored.*;", + " " + "\\\\" + "\"\"\")", + "package example;", + "import java.util.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L5 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void detectsImportWithoutFinalNewline() { + String source = "import java.util.*;"; + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L1 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void ignoresUnterminatedCommentsAndTextBlocks() { + StepHarness harness = StepHarness.forStep(ForbidWildcardImportsStep.create()); + for (String opening : new String[]{"/*", "String source = \"\"\""}) { + String source = opening + "\nimport java.util.*;\n"; + harness.testUnaffected(source).expectLintsOf(source).toBe("(none)"); + } + } + + @Test + void ignoresLargeTextBlock() { + String source = "class Example { String source = \"\"\"\n" + "text ".repeat(20_000) + + "\nimport java.util.*;\n\"\"\"; }\n"; + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source).toBe("(none)"); + } + + @Test + void unicodeEscapesInStringsDoNotHideRealImports() { + StepHarness harness = StepHarness.forStep(ForbidWildcardImportsStep.create()); + for (String literal : new String[]{ + "\"\\u005c\"\"", + "\"\\uuuu005c\"\"", + "\"\\\\u0022\"", + "\"\\\\\\u006e\"", + "\"\\u005c\\u005c\"", + "\"\\u005c\\u0022\""}) { + String source = StringPrinter.buildStringFromLines( + "@Example(" + literal + ")", + "package example;", + "import java.util.*;"); + harness.testUnaffected(source).expectLintsOf(source) + .toBe("L3 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + } + + @Test + void unicodeEscapesCanDelimitComments() { + String source = StringPrinter.buildStringFromLines( + "\\u002f\\u002a", + "import ignored.*;", + "\\u002a/", + "import java.util.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L4 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void unicodeEscapesCanDelimitTextBlocks() { + String delimiter = "\\u0022".repeat(3); + String source = StringPrinter.buildStringFromLines( + "@Example(" + delimiter, + " import ignored.*;", + delimiter + ")", + "package example;", + "import java.util.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L5 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void unicodeLineTerminatorsEndLineComments() { + StepHarness harness = StepHarness.forStep(ForbidWildcardImportsStep.create()); + for (String newline : new String[]{"\\u000a", "\\u000d", "\\u000d\\u000a"}) { + String source = StringPrinter.buildStringFromLines( + "// " + newline + "@Example(\"\"\"", + " import ignored.*;", + "\"\"\")", + "package example;", + "import java.util.*;"); + harness.testUnaffected(source).expectLintsOf(source) + .toBe("L5 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + } + + @Test + void unicodeTranslationIsNotRecursive() { + String source = StringPrinter.buildStringFromLines( + "// \\u005cu000a \"\"\"", + "import java.util.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L2 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void unicodeTranslationPreservesRawDiagnostics() { + String source = StringPrinter.buildStringFromLines( + "// \\u000a // another comment", + "import java.\\u0075til.*;"); + StepHarness.forStep(ForbidWildcardImportsStep.create()) + .testUnaffected(source) + .expectLintsOf(source) + .toBe("L2 forbidWildcardImports(import java.\\u0075til.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + + @Test + void malformedUnicodeEscapesDoNotThrow() { + StepHarness harness = StepHarness.forStep(ForbidWildcardImportsStep.create()); + for (String escape : new String[]{"\\u00g0", "\\uu00", "\\u0022"}) { + String source = "// " + escape + "\nimport java.util.*;\n"; + harness.testUnaffected(source).expectLintsOf(source) + .toBe("L2 forbidWildcardImports(import java.util.*;) Do not use wildcard imports (e.g. java.util.*) - replace with specific class imports (e.g. java.util.List) as 'spotlessApply' cannot auto-fix this"); + } + } + + @Test + void equality() { + new SerializableEqualityTester() { + @Override + protected void setupTest(API api) { + api.areDifferentThan(); + } + + @Override + protected FormatterStep create() { + return ForbidWildcardImportsStep.create(); + } + }.testEquals(); + } }