A Gradle plugin to organize imports in Java and Groovy source files.
NOTE This plugin is no longer maintained. I recommend using diffplug/spotless instead.
See the Gradle plugin portal for instructions on applying the latest version of the plugin.
The plugin adds a single task called organizeImports
. By default, the task is configured
to process all .java
and .groovy
files in all source sets.
It has two main behaviors:
- Sort imports into sections.
- Remove unused imports.
NOTE: You should only run this on versioned code. This will ensure that you can revert if you either don't like the behavior or find a bug.
Just run the organizeImports
task.
./gradlew organizeImports
Just directly configure the task:
organizeImports {
sourceSets = project.sourceSets
sortOrder = [/^(javax?)\./, /^(groovyx?)\./, /^([^\.]+\.[^\.]+)\./]
staticImportsFirst = true
removeUnused = true
includes = ['**/*.java', '**/*..groovy']
}
The main one that needs explanation is the sort order. This is based on a list of regular expressions that match against the fully qualified class names. It should have one capture group that returns the section of the class name that will be sorted on.
The sorting is done in 4 steps:
- Static import or not.
- Index of the
sortOrder
pattern it matched against. - Result of capture group of matched pattern.
- Full class name
As an example (using the default sortOrder
). The following imports:
import groovy.transform.Immutable
import org.ajoberstar.grgit.Grgit
import org.ajoberstar.grgit.Commit
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.Repository
import java.util.regex.Matcher
import java.io.File
import static org.junit.Assert.*
Result in:
import static org.junit.Assert.*
import java.io.File
import java.util.regex.Matcher
import groovy.transform.Immutable
import org.ajoberstar.grgit.Commit
import org.ajoberstar.grgit.Grgit
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.Repository
The approach to determining unused imports is to search for uses of the class's simple name after the import declarations in the file. As mentioned above, this isn't meant to be a robust parser, so ensure you have your files versioned before running it.
See the Groovydoc for more information.
- Support ! in front of class name.
- Changing plugin ID from
organize-imports
toorg.ajoberstar.organize-imports
to be compatible with plugin portal. - Waiting to configure sourceSets on task until the
java
plugin applied to work around ordering issues.
- Initial release.
- See this commit for an example of the changes it makes.