-
Notifications
You must be signed in to change notification settings - Fork 494
new step to expand java wildcard imports #2744
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Plunts
wants to merge
7
commits into
diffplug:main
Choose a base branch
from
Plunts:expandWildcardImports
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
66b5758
new step to expand java wildcard imports
Plunts 06b33ff
Remove error-prone from our build.
nedtwigg 9085e20
Add missing serialVersionUID.
nedtwigg 1a293cb
Merge branch 'main' into expandWildcardImports
nedtwigg c5febe3
rewriteRun
nedtwigg a7e043c
add ExpandWildcardImportsStep to feature matrix
Plunts bf76643
prevent false resolving of wildcard subpackages
Plunts File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
209 changes: 209 additions & 0 deletions
209
...c/javaParser/java/com/diffplug/spotless/glue/javaParser/ExpandWildcardsFormatterFunc.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| /* | ||
| * Copyright 2023-2025 DiffPlug | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package com.diffplug.spotless.glue.javaparser; | ||
|
|
||
| import static java.util.stream.Collectors.joining; | ||
| import static java.util.stream.Collectors.toMap; | ||
|
|
||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.Set; | ||
| import java.util.TreeSet; | ||
| import java.util.function.Function; | ||
| import java.util.regex.Pattern; | ||
| import javassist.ClassPool; | ||
|
|
||
| import com.github.javaparser.JavaParser; | ||
| import com.github.javaparser.ast.CompilationUnit; | ||
| import com.github.javaparser.ast.ImportDeclaration; | ||
| import com.github.javaparser.ast.Node; | ||
| import com.github.javaparser.ast.expr.AnnotationExpr; | ||
| import com.github.javaparser.ast.expr.MarkerAnnotationExpr; | ||
| import com.github.javaparser.ast.expr.MethodCallExpr; | ||
| import com.github.javaparser.ast.expr.NormalAnnotationExpr; | ||
| import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; | ||
| import com.github.javaparser.ast.type.ClassOrInterfaceType; | ||
| import com.github.javaparser.ast.visitor.VoidVisitorAdapter; | ||
| import com.github.javaparser.resolution.SymbolResolver; | ||
| import com.github.javaparser.resolution.UnsolvedSymbolException; | ||
| import com.github.javaparser.resolution.declarations.ResolvedAnnotationDeclaration; | ||
| import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; | ||
| import com.github.javaparser.resolution.types.ResolvedType; | ||
| import com.github.javaparser.symbolsolver.JavaSymbolSolver; | ||
| import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver; | ||
| import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver; | ||
| import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver; | ||
| import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver; | ||
|
|
||
| import com.diffplug.spotless.FormatterFunc; | ||
| import com.diffplug.spotless.LineEnding; | ||
| import com.diffplug.spotless.Lint; | ||
|
|
||
| public class ExpandWildcardsFormatterFunc implements FormatterFunc.NeedsFile { | ||
|
|
||
| private final JavaParser parser; | ||
| static { | ||
| // If ClassPool is allowed to cache class files, it does not free the file-lock | ||
| ClassPool.cacheOpenedJarFile = false; | ||
| } | ||
|
|
||
| public ExpandWildcardsFormatterFunc(Collection<File> typeSolverClasspath) throws IOException { | ||
| this.parser = new JavaParser(); | ||
|
|
||
| CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(); | ||
| combinedTypeSolver.add(new ReflectionTypeSolver()); | ||
| for (File element : typeSolverClasspath) { | ||
| if (element.isFile()) { | ||
| combinedTypeSolver.add(new JarTypeSolver(element)); | ||
| } else if (element.isDirectory()) { | ||
| combinedTypeSolver.add(new JavaParserTypeSolver(element)); | ||
| } // gracefully ignore non-existing src-directories | ||
| } | ||
|
|
||
| SymbolResolver symbolSolver = new JavaSymbolSolver(combinedTypeSolver); | ||
| parser.getParserConfiguration().setSymbolResolver(symbolSolver); | ||
| } | ||
|
|
||
| @Override | ||
| public String applyWithFile(String rawUnix, File file) throws Exception { | ||
nedtwigg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Optional<CompilationUnit> parseResult = parser.parse(rawUnix).getResult(); | ||
| if (parseResult.isEmpty()) { | ||
| return rawUnix; | ||
| } | ||
| CompilationUnit cu = parseResult.get(); | ||
| Map<ImportDeclaration, Set<ImportDeclaration>> importMap = findWildcardImports(cu) | ||
| .stream() | ||
| .collect(toMap(Function.identity(), | ||
| t -> new TreeSet<>(Comparator.comparing(ImportDeclaration::getNameAsString)))); | ||
| if (importMap.isEmpty()) { | ||
| // No wildcards found => do not change anything | ||
| return rawUnix; | ||
| } | ||
|
|
||
| cu.accept(new CollectImportedTypesVisitor(), importMap); | ||
| for (var entry : importMap.entrySet()) { | ||
| String pattern = Pattern.quote(LineEnding.toUnix(entry.getKey().toString())); | ||
| String replacement = entry.getValue().stream().map(ImportDeclaration::toString).collect(joining()); | ||
| rawUnix = rawUnix.replaceAll(pattern, replacement); | ||
| } | ||
|
|
||
| return rawUnix; | ||
| } | ||
|
|
||
| private List<ImportDeclaration> findWildcardImports(CompilationUnit cu) { | ||
| List<ImportDeclaration> wildcardImports = new ArrayList<>(); | ||
| for (ImportDeclaration importDeclaration : cu.getImports()) { | ||
| if (importDeclaration.isAsterisk()) { | ||
| wildcardImports.add(importDeclaration); | ||
| } | ||
| } | ||
| return wildcardImports; | ||
| } | ||
|
|
||
| private static final class CollectImportedTypesVisitor | ||
| extends VoidVisitorAdapter<Map<ImportDeclaration, Set<ImportDeclaration>>> { | ||
|
|
||
| @Override | ||
| public void visit(final ClassOrInterfaceType n, | ||
| final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { | ||
| // default imports | ||
| ResolvedType resolvedType = wrapUnsolvedSymbolException(n, ClassOrInterfaceType::resolve); | ||
| if (resolvedType.isReference()) { | ||
| matchTypeName(importMap, resolvedType.asReferenceType().getQualifiedName(), false); | ||
| } | ||
| super.visit(n, importMap); | ||
| } | ||
|
|
||
| private void matchTypeName(Map<ImportDeclaration, Set<ImportDeclaration>> importMap, String qualifiedName, | ||
| boolean isStatic) { | ||
| int lastDot = qualifiedName.lastIndexOf('.'); | ||
| if (lastDot < 0) { | ||
| return; | ||
| } | ||
|
|
||
| String packageName = qualifiedName.substring(0, lastDot); | ||
| for (var entry : importMap.entrySet()) { | ||
| if (entry.getKey().isStatic() == isStatic | ||
| && packageName.equals(entry.getKey().getName().asString())) { | ||
| entry.getValue().add(new ImportDeclaration(qualifiedName, isStatic, false)); | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void visit(final MarkerAnnotationExpr n, | ||
| final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { | ||
| visitAnnotation(n, importMap); | ||
| super.visit(n, importMap); | ||
| } | ||
|
|
||
| @Override | ||
| public void visit(final SingleMemberAnnotationExpr n, | ||
| final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { | ||
| visitAnnotation(n, importMap); | ||
| super.visit(n, importMap); | ||
| } | ||
|
|
||
| @Override | ||
| public void visit(final NormalAnnotationExpr n, | ||
| final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { | ||
| visitAnnotation(n, importMap); | ||
| super.visit(n, importMap); | ||
| } | ||
|
|
||
| private void visitAnnotation(final AnnotationExpr n, | ||
| final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { | ||
| ResolvedAnnotationDeclaration resolvedType = wrapUnsolvedSymbolException(n, AnnotationExpr::resolve); | ||
| matchTypeName(importMap, resolvedType.getQualifiedName(), false); | ||
| } | ||
|
|
||
| @Override | ||
| public void visit(final MethodCallExpr n, final Map<ImportDeclaration, Set<ImportDeclaration>> importMap) { | ||
| // static imports | ||
| ResolvedMethodDeclaration resolved = wrapUnsolvedSymbolException(n, MethodCallExpr::resolve); | ||
| if (resolved.isStatic()) { | ||
| matchTypeName(importMap, resolved.getQualifiedName(), true); | ||
| } | ||
| super.visit(n, importMap); | ||
| } | ||
|
|
||
| private static <T extends Node, R> R wrapUnsolvedSymbolException(T node, Function<T, R> func) { | ||
| try { | ||
| return func.apply(node); | ||
| } catch (UnsolvedSymbolException ex) { | ||
| if (node.getBegin().isPresent() && node.getEnd().isPresent()) { | ||
| throw Lint.atLineRange(node.getBegin().get().line, node.getEnd().get().line, "UnsolvedSymbolException", ex.getMessage()).shortcut(); | ||
| } | ||
| if (node.getBegin().isPresent()) { | ||
| throw Lint.atLine(node.getBegin().get().line, "UnsolvedSymbolException", ex.getMessage()).shortcut(); | ||
| } else if (node.getEnd().isPresent()) { | ||
| throw Lint.atLine(node.getEnd().get().line, "UnsolvedSymbolException", ex.getMessage()).shortcut(); | ||
| } else { | ||
| throw Lint.atUndefinedLine("UnsolvedSymbolException", ex.getMessage()).shortcut(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
||
| } | ||
87 changes: 87 additions & 0 deletions
87
lib/src/main/java/com/diffplug/spotless/java/ExpandWildcardImportsStep.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /* | ||
| * Copyright 2025 DiffPlug | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package com.diffplug.spotless.java; | ||
|
|
||
| import java.io.File; | ||
| import java.io.Serial; | ||
| import java.io.Serializable; | ||
| import java.lang.reflect.Constructor; | ||
| import java.lang.reflect.InvocationTargetException; | ||
| import java.util.Collection; | ||
| import java.util.Objects; | ||
| import java.util.Set; | ||
|
|
||
| import com.diffplug.spotless.FormatterFunc; | ||
| import com.diffplug.spotless.FormatterStep; | ||
| import com.diffplug.spotless.JarState; | ||
| import com.diffplug.spotless.Provisioner; | ||
|
|
||
| public final class ExpandWildcardImportsStep implements Serializable { | ||
| @Serial | ||
| private static final long serialVersionUID = 1L; | ||
|
|
||
| private static final String INCOMPATIBLE_ERROR_MESSAGE = "There was a problem interacting with Java-Parser; maybe you set an incompatible version?"; | ||
| private static final String MAVEN_COORDINATES = "com.github.javaparser:javaparser-symbol-solver-core"; | ||
| public static final String DEFAULT_VERSION = "3.27.1"; | ||
|
|
||
| private final Collection<File> typeSolverClasspath; | ||
| private final JarState.Promised jarState; | ||
|
|
||
| private ExpandWildcardImportsStep(Collection<File> typeSolverClasspath, JarState.Promised jarState) { | ||
| this.typeSolverClasspath = typeSolverClasspath; | ||
| this.jarState = jarState; | ||
| } | ||
|
|
||
| public static FormatterStep create(Set<File> typeSolverClasspath, Provisioner provisioner) { | ||
| Objects.requireNonNull(provisioner, "provisioner cannot be null"); | ||
| return FormatterStep.create("expandwildcardimports", | ||
| new ExpandWildcardImportsStep(typeSolverClasspath, | ||
| JarState.promise(() -> JarState.from(MAVEN_COORDINATES + ":" + DEFAULT_VERSION, provisioner))), | ||
| ExpandWildcardImportsStep::equalityState, | ||
| State::toFormatter); | ||
| } | ||
|
|
||
| private State equalityState() { | ||
| return new State(typeSolverClasspath, jarState.get()); | ||
| } | ||
|
|
||
| private static class State implements Serializable { | ||
| @Serial | ||
| private static final long serialVersionUID = 1L; | ||
|
|
||
| private final Collection<File> typeSolverClasspath; | ||
| private final JarState jarState; | ||
|
|
||
| public State(Collection<File> typeSolverClasspath, JarState jarState) { | ||
| this.typeSolverClasspath = typeSolverClasspath; | ||
| this.jarState = jarState; | ||
| } | ||
|
|
||
| FormatterFunc toFormatter() { | ||
| try { | ||
| Class<?> formatterFunc = jarState.getClassLoader() | ||
| .loadClass("com.diffplug.spotless.glue.javaparser.ExpandWildcardsFormatterFunc"); | ||
| Constructor<?> constructor = formatterFunc.getConstructor(Collection.class); | ||
| return (FormatterFunc) constructor.newInstance(typeSolverClasspath); | ||
| } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | ||
| | InstantiationException | IllegalAccessException | NoClassDefFoundError cause) { | ||
| throw new IllegalStateException(INCOMPATIBLE_ERROR_MESSAGE, cause); | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.