Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ This table tracks the auto-fix support status of OpenRewrite recipes for each Ch
| 🔴 | [`ImportControl`](https://checkstyle.sourceforge.io/checks/imports/importcontrol.html#ImportControl) | | Restructure imports per rules |
| 🟢 | [`ImportOrder`](https://checkstyle.sourceforge.io/checks/imports/importorder.html#ImportOrder) | `TBD` | |
| 🟢 | [`RedundantImport`](https://checkstyle.sourceforge.io/checks/imports/redundantimport.html#RedundantImport) | [`RedundantImport`](https://github.com/checkstyle/checkstyle-openrewrite-recipes/blob/main/src/main/java/org/checkstyle/autofix/recipe/RedundantImport.java) | |
| 🟢 | [`UnusedImports`](https://checkstyle.sourceforge.io/checks/imports/unusedimports.html#UnusedImports) | `TBD` | |
| 🟢 | [`UnusedImports`](https://checkstyle.sourceforge.io/checks/imports/unusedimports.html#UnusedImports) | [`UnusedImports`](https://github.com/checkstyle/checkstyle-openrewrite-recipes/blob/main/src/main/java/org/checkstyle/autofix/recipe/UnusedImports.java) | |


### Javadoc Comments
Expand Down
1 change: 1 addition & 0 deletions config/suppressions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@
<suppress checks="MissingNullCaseInSwitch" files="[\\/]src[\\/]main[\\/]java[\\/]org[\\/]checkstyle[\\/]autofix[\\/]recipe[\\/]NewlineAtEndOfFile\.java"/>

<suppress checks="ImportControlCheck" files="[\\/]src[\\/]test[\\/]java[\\/]org[\\/]checkstyle[\\/]autofix[\\/]recipe[\\/]NumericalPrefixesInfixesSuffixesCharacterCaseTest\.java"/>
<suppress checks="ImportControlCheck" files="[\\/]src[\\/]test[\\/]java[\\/]org[\\/]checkstyle[\\/]autofix[\\/]recipe[\\/]UnusedImportsTest\.java"/>
</suppressions>
1 change: 1 addition & 0 deletions src/main/java/org/checkstyle/autofix/CheckFullName.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public enum CheckFullName {
HEX_LITERAL_CASE("com.puppycrawl.tools.checkstyle.checks.HexLiteralCaseCheck"),
NUMERICAL_PREFIXES_INF_SUF_CASE(
"com.puppycrawl.tools.checkstyle.checks.NumericalPrefixesInfixesSuffixesCharacterCaseCheck"),
UNUSED_IMPORT("com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck"),
REDUNDANT_IMPORT("com.puppycrawl.tools.checkstyle.checks.imports.RedundantImportCheck");

private final String id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.checkstyle.autofix.recipe.NewlineAtEndOfFile;
import org.checkstyle.autofix.recipe.NumericalPrefixesInfixesSuffixesCharacterCase;
import org.checkstyle.autofix.recipe.RedundantImport;
import org.checkstyle.autofix.recipe.UnusedImports;
import org.checkstyle.autofix.recipe.UpperEll;
import org.openrewrite.Recipe;

Expand All @@ -54,6 +55,7 @@ public final class CheckstyleRecipeRegistry {
RECIPE_MAP.put(CheckFullName.NUMERICAL_PREFIXES_INF_SUF_CASE,
NumericalPrefixesInfixesSuffixesCharacterCase::new);
RECIPE_MAP.put(CheckFullName.REDUNDANT_IMPORT, RedundantImport::new);
RECIPE_MAP.put(CheckFullName.UNUSED_IMPORT, UnusedImports::new);
}

private CheckstyleRecipeRegistry() {
Expand Down
92 changes: 92 additions & 0 deletions src/main/java/org/checkstyle/autofix/recipe/UnusedImports.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle-openrewrite-recipes: Automatically fix Checkstyle violations with OpenRewrite.
// Copyright (C) 2025 The Checkstyle OpenRewrite Recipes Authors
//
// 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 org.checkstyle.autofix.recipe;

import java.nio.file.Path;
import java.util.List;

import org.checkstyle.autofix.parser.CheckstyleViolation;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;

/**
* Fixes Checkstyle UnusedImports violations by removing unused imports.
*/
public class UnusedImports extends Recipe {

private final List<CheckstyleViolation> violations;

public UnusedImports(List<CheckstyleViolation> violations) {
this.violations = violations;
}

@Override
public String getDisplayName() {
return "UnusedImports Recipe";
}

@Override
public String getDescription() {
return "Remove unused imports";
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new UnusedImports.UnusedImportsVisitor();
}

private final class UnusedImportsVisitor extends JavaIsoVisitor<ExecutionContext> {

private static final String DOT_OPERATOR = ".";

private Path sourcePath;

@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu,
ExecutionContext executionContext) {

this.sourcePath = cu.getSourcePath();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cu --> compileUnit, compilationUnit

return cu.withImports(
cu.getImports().stream()
.filter(importStmt -> !isAtViolationLocation(importStmt))
.toList()
);
}

private String createMessage(J.Import literal) {
String fullImport = literal.getTypeName();
if (literal.isStatic()) {
fullImport += DOT_OPERATOR + literal.getQualid().getSimpleName();
}
return "Unused import - " + fullImport + DOT_OPERATOR;
}

private boolean isAtViolationLocation(J.Import literal) {

final String message = createMessage(literal);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

strange that we rely on message ....
it can be changed by user or be in non English.

why you isAtViolationLocation is so different from:

private boolean isAtViolationLocation(J.Literal literal) {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think to not match the violation on the basis of line and column basically what i did is extract each import from lst and match that import with violation message import but as suggested by you that the language is a problem.
so i will try to implement by line or column number

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's do as all other for now, ones we get better model, we will refactor all at ones

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my exams are going on i will continue this after my exams

return violations.stream().anyMatch(violation -> {
final Path absolutePath = violation.getFilePath();
return violation.getMessage().equals(message)
&& absolutePath.endsWith(sourcePath);
});
}
}
}
69 changes: 69 additions & 0 deletions src/test/java/org/checkstyle/autofix/recipe/UnusedImportsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle-openrewrite-recipes: Automatically fix Checkstyle violations with OpenRewrite.
// Copyright (C) 2025 The Checkstyle OpenRewrite Recipes Authors
//
// 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 org.checkstyle.autofix.recipe;

import static com.google.common.truth.Truth.assertWithMessage;

import org.checkstyle.autofix.parser.ReportParser;
import org.junit.jupiter.api.Test;

public class UnusedImportsTest extends AbstractRecipeTestSupport {

@Override
protected String getSubpackage() {
return "unusedimports";
}

@Test
public void checkDescription() {
final UnusedImports recipe = new UnusedImports(null);
final String expectedDescription = "Remove unused imports";
assertWithMessage("Invalid description")
.that(recipe.getDescription())
.isEqualTo(expectedDescription);
}

@Test
public void checkDisplayName() {
final UnusedImports recipe = new UnusedImports(null);
final String expectedDisplayName = "UnusedImports Recipe";
assertWithMessage("Invalid display name")
.that(recipe.getDisplayName())
.isEqualTo(expectedDisplayName);
}

@RecipeTest
void unusedImportsCaseOne(ReportParser parser) throws Exception {
verify(parser, "UnusedCaseOne");
}

@RecipeTest
void unusedImportsCaseTwo(ReportParser parser) throws Exception {
verify(parser, "UnusedCaseTwo");
}

@RecipeTest
void unusedImportsCaseThree(ReportParser parser) throws Exception {
verify(parser, "UnusedCaseOne", "UnusedCaseTwo");
}

@RecipeTest
void unusedImportsCaseFour(ReportParser parser) throws Exception {
verify(parser, "UnusedCaseThree");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
--- src/test/resources/org/checkstyle/autofix/recipe/unusedimports/unusedcaseone/InputUnusedCaseOne.java
+++ src/test/resources/org/checkstyle/autofix/recipe/unusedimports/unusedcaseone/OutputUnusedCaseOne.java
@@ -11,28 +11,17 @@

import java.io.*;
import java.lang.*;
-import java.lang.String; // violation 'Unused import - java.lang.String.'
-
-import java.util.List; // violation 'Unused import - java.util.List.'
-import java.util.List; // violation 'Unused import - java.util.List.'
import java.lang.*;
import java.util.Iterator;
-import java.util.Enumeration; // violation 'Unused import - java.util.Enumeration.'
import java.util.Arrays;
import javax.swing.JToolBar;
-import javax.swing.JToggleButton; // violation 'Unused import - javax.swing.JToggleButton.'
-
-import javax.swing.BorderFactory; // violation 'Unused import - javax.swing.BorderFactory.'

import static java.io.File.listRoots;

import static javax.swing.WindowConstants.*;
-import static java.io.File. // violation 'Unused import - java.io.File.createTempFile.'
- createTempFile;

import java.awt.Graphics2D;
import java.awt.HeadlessException;
-import java.awt.Label; // violation 'Unused import - java.awt.Label.'
import java.util.Date;
import java.util.Calendar;
import java.util.BitSet;
@@ -42,7 +31,7 @@
* Here's an import used only by javadoc: {@link Date}.
* @see Calendar Should avoid unused import for Calendar
**/
-public class InputUnusedCaseOne {
+public class OutputUnusedCaseOne {

private Class mUse1 = null;
private Class mUse2 = java.io.File.class;
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*xml
<module name="Checker">
<module name="TreeWalker">
<module name="com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck"/>
</module>
</module>

*/

package org.checkstyle.autofix.recipe.unusedimports.unusedcaseone;

import java.io.*;
import java.lang.*;
import java.lang.String; // violation 'Unused import - java.lang.String.'

import java.util.List; // violation 'Unused import - java.util.List.'
import java.util.List; // violation 'Unused import - java.util.List.'
import java.lang.*;
import java.util.Iterator;
import java.util.Enumeration; // violation 'Unused import - java.util.Enumeration.'
import java.util.Arrays;
import javax.swing.JToolBar;
import javax.swing.JToggleButton; // violation 'Unused import - javax.swing.JToggleButton.'

import javax.swing.BorderFactory; // violation 'Unused import - javax.swing.BorderFactory.'

import static java.io.File.listRoots;

import static javax.swing.WindowConstants.*;
import static java.io.File. // violation 'Unused import - java.io.File.createTempFile.'
createTempFile;

import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Label; // violation 'Unused import - java.awt.Label.'
import java.util.Date;
import java.util.Calendar;
import java.util.BitSet;

/**
* Test case for imports
* Here's an import used only by javadoc: {@link Date}.
* @see Calendar Should avoid unused import for Calendar
**/
public class InputUnusedCaseOne {

private Class mUse1 = null;
private Class mUse2 = java.io.File.class;
private Class mUse3 = Iterator[].class;
private Class mUse4 = java.util.Enumeration[].class;

{
int[] x = {};
Arrays.sort(x);
Object obj = javax.swing.BorderFactory.createEmptyBorder();
File[] files = listRoots();
}

private JToolBar.Separator mSep = null;

private Object mUse5 = new Object();

private Object mUse6 = new javax.swing.JToggleButton.ToggleButtonModel();

private int Component;

/**
* method comment with JavaDoc-only import {@link BitSet}
*/
public void Label() {}

/**
* Renders to a {@linkplain Graphics2D graphics context}.
* @throws HeadlessException if no graphis environment can be found.
*/
public void render() {}

public void aMethodWithManyLinks() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*xml
<module name="Checker">
<module name="TreeWalker">
<module name="com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck"/>
</module>
</module>

*/

package org.checkstyle.autofix.recipe.unusedimports.unusedcaseone;

import java.io.*;
import java.lang.*;
import java.lang.*;
import java.util.Iterator;
import java.util.Arrays;
import javax.swing.JToolBar;

import static java.io.File.listRoots;

import static javax.swing.WindowConstants.*;

import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.util.Date;
import java.util.Calendar;
import java.util.BitSet;

/**
* Test case for imports
* Here's an import used only by javadoc: {@link Date}.
* @see Calendar Should avoid unused import for Calendar
**/
public class OutputUnusedCaseOne {

private Class mUse1 = null;
private Class mUse2 = java.io.File.class;
private Class mUse3 = Iterator[].class;
private Class mUse4 = java.util.Enumeration[].class;

{
int[] x = {};
Arrays.sort(x);
Object obj = javax.swing.BorderFactory.createEmptyBorder();
File[] files = listRoots();
}

private JToolBar.Separator mSep = null;

private Object mUse5 = new Object();

private Object mUse6 = new javax.swing.JToggleButton.ToggleButtonModel();

private int Component;

/**
* method comment with JavaDoc-only import {@link BitSet}
*/
public void Label() {}

/**
* Renders to a {@linkplain Graphics2D graphics context}.
* @throws HeadlessException if no graphis environment can be found.
*/
public void render() {}

public void aMethodWithManyLinks() {}
}
Loading