-
Notifications
You must be signed in to change notification settings - Fork 426
Feat/java add explicit imports #5318
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
BelmoMusta
wants to merge
10
commits into
openrewrite:main
Choose a base branch
from
BelmoMusta:feat/java-add-explicit-imports
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
10 commits
Select commit
Hold shift + click to select a range
653ddbe
feat(java): add explicit imports to a java file
BelmoMusta a02277e
feat(java): preserve already exisiting imports and support static imp…
BelmoMusta 348633f
Update rewrite-java/src/main/java/org/openrewrite/java/AddExplicitImp…
BelmoMusta 63d9dcb
Update rewrite-java/src/main/java/org/openrewrite/java/style/Preserve…
BelmoMusta cd6e497
Update rewrite-java/src/test/java/org/openrewrite/java/AddExplicitImp…
BelmoMusta f829b92
Update rewrite-java/src/test/java/org/openrewrite/java/AddExplicitImp…
BelmoMusta a4120c9
Update rewrite-java/src/main/java/org/openrewrite/java/AddExplicitImp…
BelmoMusta 5fe0d49
add multiple imports
BelmoMusta 38de4b2
feat(java): clean the code
BelmoMusta c7c5790
Apply suggestions from code review
BelmoMusta 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
63 changes: 63 additions & 0 deletions
63
rewrite-java/src/main/java/org/openrewrite/java/AddExplicitImport.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,63 @@ | ||
/* | ||
* Copyright 2025 the original author or authors. | ||
* <p> | ||
* 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 | ||
* <p> | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* <p> | ||
* 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 org.openrewrite.java; | ||
|
||
import lombok.EqualsAndHashCode; | ||
import lombok.Value; | ||
import org.openrewrite.ExecutionContext; | ||
import org.openrewrite.Option; | ||
import org.openrewrite.Preconditions; | ||
import org.openrewrite.Recipe; | ||
import org.openrewrite.TreeVisitor; | ||
import org.openrewrite.java.tree.J; | ||
import org.openrewrite.java.tree.JavaSourceFile; | ||
|
||
@Value | ||
@EqualsAndHashCode(callSuper = false) | ||
public class AddExplicitImport extends Recipe { | ||
@Option(displayName = "List of imports to add", | ||
description = "The list of imports, this field is multiline.", | ||
example = "foo.bar\nbiz.baz") | ||
String imports; | ||
|
||
@Override | ||
public String getDisplayName() { | ||
return "Add explicit imports"; | ||
} | ||
|
||
@Override | ||
public int maxCycles() { | ||
return 1; | ||
} | ||
@Override | ||
public String getDescription() { | ||
return "This recipe adds an explicit import to a single Java file."; | ||
} | ||
|
||
@Override | ||
public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
return Preconditions.check(true, new JavaIsoVisitor<ExecutionContext>() { | ||
@Override | ||
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext executionContext) { | ||
JavaSourceFile javaSourceFile = getCursor().firstEnclosing(JavaSourceFile.class); | ||
if (javaSourceFile != null) { | ||
addExplicitImport(imports); | ||
} | ||
return super.visitCompilationUnit(cu, executionContext); | ||
} | ||
}); | ||
} | ||
} |
109 changes: 109 additions & 0 deletions
109
rewrite-java/src/main/java/org/openrewrite/java/AddExplicitImportVisitor.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,109 @@ | ||
/* | ||
* Copyright 2021 the original author or authors. | ||
* <p> | ||
* 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 | ||
* <p> | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* <p> | ||
* 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 org.openrewrite.java; | ||
|
||
import lombok.EqualsAndHashCode; | ||
import org.jspecify.annotations.Nullable; | ||
import org.openrewrite.Cursor; | ||
import org.openrewrite.internal.ListUtils; | ||
import org.openrewrite.java.style.PreserveImportLayoutStyle; | ||
import org.openrewrite.java.tree.J; | ||
import org.openrewrite.java.tree.JLeftPadded; | ||
import org.openrewrite.java.tree.JRightPadded; | ||
import org.openrewrite.java.tree.JavaSourceFile; | ||
import org.openrewrite.java.tree.Javadoc; | ||
import org.openrewrite.java.tree.Space; | ||
import org.openrewrite.java.tree.TypeTree; | ||
import org.openrewrite.marker.Markers; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
|
||
import static org.openrewrite.Tree.randomId; | ||
|
||
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true) | ||
public class AddExplicitImportVisitor<P> extends AddImport<P> { | ||
final String imports; | ||
public AddExplicitImportVisitor(String imports) { | ||
this.imports = imports; | ||
} | ||
|
||
@Override | ||
public @Nullable J preVisit(J tree, P p) { | ||
stopAfterPreVisit(); | ||
J j = tree; | ||
if (tree instanceof JavaSourceFile) { | ||
JavaSourceFile cu = (JavaSourceFile) tree; | ||
final String[] split = imports.split("\n"); | ||
final List<String> receivedImports = Arrays.stream(split) | ||
.map(String::trim) | ||
.filter(s -> !s.isEmpty()) | ||
.collect(Collectors.toList()); | ||
|
||
final List<J.Import> jImports = new ArrayList<>(); | ||
final Space firstClassPrefix = cu.getClasses().get(0).getPrefix(); | ||
final List<JRightPadded<J.Import>> existingImports = new ArrayList<>(cu.getPadding().getImports()); | ||
for (String anImport : receivedImports) { | ||
final JLeftPadded<Boolean> statik; | ||
if (anImport.startsWith("static ")) { | ||
statik = JLeftPadded.build(true).withBefore(Space.SINGLE_SPACE); | ||
anImport = anImport.replace("static ", ""); | ||
} else { | ||
statik = new JLeftPadded<>(Space.EMPTY, false, Markers.EMPTY); | ||
} | ||
final int lastDotIdx = anImport.lastIndexOf('.'); | ||
final String packageName = lastDotIdx != -1 ? anImport.substring(0, lastDotIdx) : null; | ||
if (packageName == null) { | ||
continue; | ||
} | ||
|
||
J.Import aJimport = new J.Import(randomId(), | ||
Space.EMPTY, | ||
Markers.EMPTY, | ||
statik, | ||
TypeTree.build(anImport).withPrefix(Space.SINGLE_SPACE), | ||
null); | ||
|
||
if ((jImports.isEmpty() || existingImports.isEmpty()) && !cu.getClasses().isEmpty() && cu.getPackageDeclaration() == null) { | ||
aJimport = aJimport.withPrefix(firstClassPrefix | ||
.withComments(ListUtils.map(firstClassPrefix.getComments(), | ||
comment -> comment instanceof Javadoc ? null : comment)) | ||
.withWhitespace("")); | ||
} | ||
jImports.add(aJimport); | ||
} | ||
|
||
PreserveImportLayoutStyle layoutStyle = new PreserveImportLayoutStyle(cu.getPadding().getImports()); | ||
List<JRightPadded<J.Import>> newImports = layoutStyle.addImports(jImports); | ||
|
||
// ImportLayoutStyle::addImport adds always `\n` as newlines. Checking if we need to fix them | ||
newImports = checkCRLF(cu, newImports); | ||
|
||
cu = cu.getPadding().withImports(newImports); | ||
|
||
JavaSourceFile c = cu; | ||
cu = cu.withClasses(ListUtils.mapFirst(cu.getClasses(), clazz -> { | ||
J.ClassDeclaration cl = autoFormat(clazz, clazz.getName(), p, new Cursor(null, c)); | ||
return clazz.withPrefix(clazz.getPrefix().withWhitespace(cl.getPrefix().getWhitespace())); | ||
})); | ||
|
||
j = cu; | ||
} | ||
return j; | ||
} | ||
} |
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
63 changes: 63 additions & 0 deletions
63
rewrite-java/src/main/java/org/openrewrite/java/style/PreserveImportLayoutStyle.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,63 @@ | ||
/* | ||
* Copyright 2025 the original author or authors. | ||
* <p> | ||
* 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 | ||
* <p> | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* <p> | ||
* 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 org.openrewrite.java.style; | ||
BelmoMusta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import lombok.EqualsAndHashCode; | ||
import lombok.Getter; | ||
import org.openrewrite.java.tree.J; | ||
import org.openrewrite.java.tree.JRightPadded; | ||
import org.openrewrite.java.tree.Space; | ||
import org.openrewrite.marker.Markers; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.List; | ||
|
||
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true) | ||
@Getter | ||
public class PreserveImportLayoutStyle extends ImportLayoutStyle { | ||
|
||
final List<JRightPadded<J.Import>> existingImports; | ||
|
||
public PreserveImportLayoutStyle(List<JRightPadded<J.Import>> imports) { | ||
super(0, 0, Collections.emptyList(), Collections.emptyList()); | ||
this.existingImports = imports; | ||
} | ||
|
||
public List<JRightPadded<J.Import>> addImports(List<J.Import> toAdd) { | ||
List<JRightPadded<J.Import>> paddings = new ArrayList<>(); | ||
Space prefix = Space.format("\n"); | ||
if (existingImports.isEmpty()) { | ||
prefix = Space.EMPTY; | ||
} | ||
|
||
boolean first = true; | ||
for (J.Import anImport : toAdd) { | ||
if (!first) { | ||
prefix = Space.format("\n"); | ||
} | ||
JRightPadded<J.Import> paddedImport = new JRightPadded<>(anImport, Space.EMPTY, Markers.EMPTY); | ||
paddedImport = paddedImport.withElement(paddedImport.getElement().withPrefix(prefix)); | ||
paddings.add(paddedImport); | ||
first = false; | ||
|
||
} | ||
final List<JRightPadded<J.Import>> newImports = new ArrayList<>(existingImports); | ||
newImports.addAll(paddings); | ||
return newImports; | ||
} | ||
} | ||
|
||
BelmoMusta marked this conversation as resolved.
Show resolved
Hide resolved
BelmoMusta marked this conversation as resolved.
Show resolved
Hide resolved
BelmoMusta marked this conversation as resolved.
Show resolved
Hide resolved
BelmoMusta marked this conversation as resolved.
Show resolved
Hide resolved
BelmoMusta marked this conversation as resolved.
Show resolved
Hide resolved
|
Oops, something went wrong.
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.