From 41dc89108c142037d7620b4ad0ec5d3204c145df Mon Sep 17 00:00:00 2001 From: ARAYN7011 <88572149+ARAYN7011@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:43:40 +0530 Subject: [PATCH] Shorten fully qualified annotation names in shortenFullyQualifiedTypes Fixes #3159 Co-Authored-By: Claude Sonnet 5.5 --- CHANGES.md | 1 + .../ShortenQualifiedTypesFormatterFunc.java | 51 +++++++++++++++++++ plugin-gradle/CHANGES.md | 1 + plugin-maven/CHANGES.md | 1 + .../ShortenFullyQualifiedTypesStepTest.java | 48 +++++++++++++++-- 5 files changed, 99 insertions(+), 3 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 733abfd3d9..7a7d937326 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -13,6 +13,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ### Added - Add a `groupArtifact` option to `PalantirJavaFormatStep`. ([#3179](https://github.com/diffplug/spotless/pull/3179)) ### Fixed +- `shortenFullyQualifiedTypes` now also shortens fully qualified annotation names such as `@com.example.Foo`. ([#3159](https://github.com/diffplug/spotless/issues/3159)) - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) - DBeaver SQL formatter no longer prints an `IndexOutOfBoundsException` when a file starts with a keyword like `SET`. ([#1552](https://github.com/diffplug/spotless/issues/1552)) - `ExpandWildcardImportsStep` no longer fails with `Symbol resolution not configured` on records and other syntax newer than Java 11, and leaves files JavaParser cannot validate unchanged. ([#2946](https://github.com/diffplug/spotless/issues/2946)) diff --git a/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ShortenQualifiedTypesFormatterFunc.java b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ShortenQualifiedTypesFormatterFunc.java index 2fe629bac0..6d64781bdf 100644 --- a/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ShortenQualifiedTypesFormatterFunc.java +++ b/lib/src/javaParser/java/com/diffplug/spotless/glue/javaparser/ShortenQualifiedTypesFormatterFunc.java @@ -40,11 +40,16 @@ import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.ast.body.RecordDeclaration; import com.github.javaparser.ast.body.TypeDeclaration; +import com.github.javaparser.ast.expr.AnnotationExpr; import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.FieldAccessExpr; +import com.github.javaparser.ast.expr.MarkerAnnotationExpr; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.MethodReferenceExpr; +import com.github.javaparser.ast.expr.Name; import com.github.javaparser.ast.expr.NameExpr; +import com.github.javaparser.ast.expr.NormalAnnotationExpr; +import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; import com.github.javaparser.ast.expr.TypeExpr; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; @@ -149,6 +154,9 @@ public String apply(String rawUnix) throws Exception { cu.findAll(ClassOrInterfaceType.class).stream() .filter(type -> type.getScope().isEmpty()) .forEach(type -> unqualifiedTypeNames.add(type.getNameAsString())); + cu.findAll(AnnotationExpr.class).stream() + .filter(annotation -> annotation.getName().getQualifier().isEmpty()) + .forEach(annotation -> unqualifiedTypeNames.add(annotation.getNameAsString())); // 5. Build set of known packages from existing imports, own package, and java.lang Set knownPackages = new LinkedHashSet<>(); @@ -310,6 +318,49 @@ public void visit(ClassOrInterfaceType type, Void arg) { } } + @Override + public void visit(MarkerAnnotationExpr annotation, Void arg) { + super.visit(annotation, arg); + processAnnotation(annotation); + } + + @Override + public void visit(SingleMemberAnnotationExpr annotation, Void arg) { + super.visit(annotation, arg); + processAnnotation(annotation); + } + + @Override + public void visit(NormalAnnotationExpr annotation, Void arg) { + super.visit(annotation, arg); + processAnnotation(annotation); + } + + /** An annotation name is always a type, so {@code @pkg.Foo} can be shortened to {@code @Foo}. */ + private void processAnnotation(AnnotationExpr annotation) { + Name name = annotation.getName(); + if (name.getQualifier().isEmpty()) { + return; + } + String rawName = name.asString(); + if (!startsWithPackage(rawName)) { + return; + } + if (name.getBegin().isEmpty() || name.getEnd().isEmpty()) { + return; + } + Position scopeStart = name.getBegin().get(); + Position end = name.getEnd().get(); + String simple = name.getIdentifier(); + if (scopeStart.line != end.line) { + // qualifier and identifier are split across lines; leave it alone + return; + } + Position nameStart = new Position(end.line, end.column - simple.length() + 1); + simpleToFqns.computeIfAbsent(simple, k -> new LinkedHashSet<>()).add(rawName); + qualifiedRefs.add(new QualifiedTypeRef(rawName, simple, scopeStart, nameStart, annotation)); + } + @Override public void visit(MethodCallExpr expr, Void arg) { super.visit(expr, arg); diff --git a/plugin-gradle/CHANGES.md b/plugin-gradle/CHANGES.md index 27c78dde65..dc545b4595 100644 --- a/plugin-gradle/CHANGES.md +++ b/plugin-gradle/CHANGES.md @@ -9,6 +9,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( ### Changes - `SpotlessApply` now only reports that it did work (and is otherwise `UP-TO-DATE`) when it actually rewrote a file. ([#2715](https://github.com/diffplug/spotless/issues/2715)) ### Fixed +- `shortenFullyQualifiedTypes()` now also shortens fully qualified annotation names such as `@com.example.Foo`. ([#3159](https://github.com/diffplug/spotless/issues/3159)) - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) - DBeaver SQL formatter no longer prints an `IndexOutOfBoundsException` when a file starts with a keyword like `SET`. ([#1552](https://github.com/diffplug/spotless/issues/1552)) - `expandWildcardImports()` no longer fails with `Symbol resolution not configured` on records and other syntax newer than Java 11, and leaves files JavaParser cannot validate unchanged. ([#2946](https://github.com/diffplug/spotless/issues/2946)) diff --git a/plugin-maven/CHANGES.md b/plugin-maven/CHANGES.md index 7120684723..0a96eba939 100644 --- a/plugin-maven/CHANGES.md +++ b/plugin-maven/CHANGES.md @@ -8,6 +8,7 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format ( - Add a `spotless:report` goal that puts a Spotless page in the Maven site. ([#3175](https://github.com/diffplug/spotless/pull/3175)) List `spotless-maven-plugin` under `` and run `mvn site`: the page shows which files need formatting, with a colored diff for each, and their lint problems. It works with `maven-site-plugin` 3.12.1 and 3.20.0 or later. ### Fixed +- `` now also shortens fully qualified annotation names such as `@com.example.Foo`. ([#3159](https://github.com/diffplug/spotless/issues/3159)) - GrEclipse no longer leaves a `file%3A...` directory in the working directory. ([#2019](https://github.com/diffplug/spotless/issues/2019)) - DBeaver SQL formatter no longer prints an `IndexOutOfBoundsException` when a file starts with a keyword like `SET`. ([#1552](https://github.com/diffplug/spotless/issues/1552)) - `` no longer fails with `Symbol resolution not configured` on records and other syntax newer than Java 11, and leaves files JavaParser cannot validate unchanged. ([#2946](https://github.com/diffplug/spotless/issues/2946)) diff --git a/testlib/src/test/java/com/diffplug/spotless/java/ShortenFullyQualifiedTypesStepTest.java b/testlib/src/test/java/com/diffplug/spotless/java/ShortenFullyQualifiedTypesStepTest.java index d4d849b99b..a443c9c42a 100644 --- a/testlib/src/test/java/com/diffplug/spotless/java/ShortenFullyQualifiedTypesStepTest.java +++ b/testlib/src/test/java/com/diffplug/spotless/java/ShortenFullyQualifiedTypesStepTest.java @@ -649,9 +649,7 @@ void extendsInFileTypeWithNoMemberTypesStillShortens() throws Exception { @Test void multipleAnnotationsWithFqn() throws Exception { - // FQNs used as annotation types should NOT be treated as type references - // (annotations start with @, not handled by ClassOrInterfaceType) - // but FQN types in annotation values or alongside annotations should work + // FQN types alongside annotations should work (see issue3159_annotationsShortened for annotation names) String before = String.join("\n", "package com.example;", "", @@ -664,6 +662,50 @@ void multipleAnnotationsWithFqn() throws Exception { assertTrue(result.contains("import java.util.List;"), "should import List"); } + @Test + void issue3159_annotationsShortened() throws Exception { + String before = String.join("\n", + "package com.example;", + "", + "@com.fasterxml.jackson.annotation.JsonIgnoreProperties({\"traceId\"})", + "public record SuccessResponse() {", + " @com.fasterxml.jackson.annotation.JsonCreator", + " SuccessResponse(@com.fasterxml.jackson.annotation.JsonProperty(\"code\") String code, int x) {", + " this();", + " }", + " @com.example.other.Marker(name = \"a\")", + " void m() {}", + "}", + ""); + String result = apply(before); + assertFalse(codeBody(result).contains("com.fasterxml"), result); + assertFalse(codeBody(result).contains("com.example.other"), result); + assertTrue(result.contains("@JsonIgnoreProperties({\"traceId\"})"), result); + assertTrue(result.contains("@JsonCreator"), result); + assertTrue(result.contains("@JsonProperty(\"code\")"), result); + assertTrue(result.contains("@Marker(name = \"a\")"), result); + assertTrue(result.contains("import com.fasterxml.jackson.annotation.JsonCreator;"), result); + assertTrue(result.contains("import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"), result); + assertTrue(result.contains("import com.fasterxml.jackson.annotation.JsonProperty;"), result); + assertTrue(result.contains("import com.example.other.Marker;"), result); + } + + @Test + void annotationNotShortenedWhenSimpleNameClashes() throws Exception { + String before = String.join("\n", + "package com.example;", + "", + "@Marker", + "public class Foo {", + " @org.other.Marker", + " void m() {}", + "}", + ""); + String result = apply(before); + assertTrue(result.contains("@org.other.Marker"), result); + assertFalse(result.contains("import org.other.Marker;"), result); + } + @Test void issue3133_methodReferenceOnFieldNotShortened() throws Exception { // `localVar.field::method` is a field access on an expression, parsed by JavaParser