Skip to content
Draft
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
9 changes: 9 additions & 0 deletions plugin-maven/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ any other maven phase (i.e. compile) then it can be configured as below;

<removeUnusedImports /> <!-- self-explanatory -->
<forbidWildcardImports /> <!-- yell if any import ends with '*' -->
<expandWildcardImports /> <!-- replace wildcard imports with explicit imports -->
<forbidModuleImports /> <!-- yell if any module imports are found (Java 25+) -->

<formatAnnotations /> <!-- fixes formatting of type annotations, see below -->
Expand All @@ -257,6 +258,14 @@ any other maven phase (i.e. compile) then it can be configured as below;
<forbidWildcardImports/>
```

### expandWildcardImports

Automatically replaces wildcard imports (e.g., `import java.util.*`) with explicit imports for the classes actually used in the code. This step analyzes your source code and project dependencies to determine which specific classes are needed and generates the appropriate import statements.

```xml
<expandWildcardImports/>
```

### forbidModuleImports

```xml
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ private FormatterConfig getFormatterConfig() {
FileLocator fileLocator = getFileLocator();
final Optional<String> optionalRatchetFrom = Optional.ofNullable(this.ratchetFrom)
.filter(ratchet -> !RATCHETFROM_NONE.equals(ratchet));
return new FormatterConfig(baseDir, encoding, lineEndings, optionalRatchetFrom, provisioner, fileLocator, formatterStepFactories, Optional.ofNullable(setLicenseHeaderYearsFromGitHistory), lintSuppressions);
return new FormatterConfig(baseDir, encoding, lineEndings, optionalRatchetFrom, provisioner, fileLocator, formatterStepFactories, Optional.ofNullable(setLicenseHeaderYearsFromGitHistory), lintSuppressions, project, repositorySystem, repositorySystemSession);
}

private FileLocator getFileLocator() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
import java.util.List;
import java.util.Optional;

import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;

import com.diffplug.spotless.LineEnding;
import com.diffplug.spotless.LintSuppression;
import com.diffplug.spotless.Provisioner;
Expand All @@ -35,9 +39,12 @@ public class FormatterConfig {
private final List<FormatterStepFactory> globalStepFactories;
private final Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory;
private final List<LintSuppression> lintSuppressions;
private final MavenProject project;
private final RepositorySystem repositorySystem;
private final RepositorySystemSession repositorySystemSession;

public FormatterConfig(File baseDir, String encoding, LineEnding lineEndings, Optional<String> ratchetFrom, Provisioner provisioner,
FileLocator fileLocator, List<FormatterStepFactory> globalStepFactories, Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory, List<LintSuppression> lintSuppressions) {
FileLocator fileLocator, List<FormatterStepFactory> globalStepFactories, Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory, List<LintSuppression> lintSuppressions, MavenProject project, RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession) {
this.encoding = encoding;
this.lineEndings = lineEndings;
this.ratchetFrom = ratchetFrom;
Expand All @@ -46,6 +53,9 @@ public FormatterConfig(File baseDir, String encoding, LineEnding lineEndings, Op
this.globalStepFactories = globalStepFactories;
this.spotlessSetLicenseHeaderYearsFromGitHistory = spotlessSetLicenseHeaderYearsFromGitHistory;
this.lintSuppressions = lintSuppressions;
this.project = project;
this.repositorySystem = repositorySystem;
this.repositorySystemSession = repositorySystemSession;
}

public String getEncoding() {
Expand Down Expand Up @@ -79,4 +89,16 @@ public FileLocator getFileLocator() {
public List<LintSuppression> getLintSuppressions() {
return unmodifiableList(lintSuppressions);
}

public MavenProject getProject() {
return project;
}

public RepositorySystem getRepositorySystem() {
return repositorySystem;
}

public RepositorySystemSession getRepositorySystemSession() {
return repositorySystemSession;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ Optional<String> ratchetFrom(FormatterConfig config) {
}

private FormatterStepConfig stepConfig(Charset encoding, FormatterConfig config) {
return new FormatterStepConfig(encoding, licenseHeaderDelimiter(), ratchetFrom(config), config.getProvisioner(), config.getFileLocator(), config.getSpotlessSetLicenseHeaderYearsFromGitHistory());
return new FormatterStepConfig(encoding, licenseHeaderDelimiter(), ratchetFrom(config), config.getProvisioner(), config.getFileLocator(), config.getSpotlessSetLicenseHeaderYearsFromGitHistory(), config.getProject(), config.getRepositorySystem(), config.getRepositorySystemSession());
}

private static List<FormatterStepFactory> gatherStepFactories(List<FormatterStepFactory> allGlobal, List<FormatterStepFactory> allConfigured) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
import java.nio.charset.Charset;
import java.util.Optional;

import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;

import com.diffplug.spotless.Provisioner;

public class FormatterStepConfig {
Expand All @@ -28,14 +32,20 @@ public class FormatterStepConfig {
private final Provisioner provisioner;
private final FileLocator fileLocator;
private final Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory;
private final MavenProject project;
private final RepositorySystem repositorySystem;
private final RepositorySystemSession repositorySystemSession;

public FormatterStepConfig(Charset encoding, String licenseHeaderDelimiter, Optional<String> ratchetFrom, Provisioner provisioner, FileLocator fileLocator, Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory) {
public FormatterStepConfig(Charset encoding, String licenseHeaderDelimiter, Optional<String> ratchetFrom, Provisioner provisioner, FileLocator fileLocator, Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory, MavenProject project, RepositorySystem repositorySystem, RepositorySystemSession repositorySystemSession) {
this.encoding = encoding;
this.licenseHeaderDelimiter = licenseHeaderDelimiter;
this.ratchetFrom = ratchetFrom;
this.provisioner = provisioner;
this.fileLocator = fileLocator;
this.spotlessSetLicenseHeaderYearsFromGitHistory = spotlessSetLicenseHeaderYearsFromGitHistory;
this.project = project;
this.repositorySystem = repositorySystem;
this.repositorySystemSession = repositorySystemSession;
}

public Charset getEncoding() {
Expand All @@ -61,4 +71,16 @@ public FileLocator getFileLocator() {
public Optional<String> spotlessSetLicenseHeaderYearsFromGitHistory() {
return spotlessSetLicenseHeaderYearsFromGitHistory;
}

public MavenProject getProject() {
return project;
}

public RepositorySystem getRepositorySystem() {
return repositorySystem;
}

public RepositorySystemSession getRepositorySystemSession() {
return repositorySystemSession;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* 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.maven.java;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.resolution.DependencyRequest;
import org.eclipse.aether.resolution.DependencyResolutionException;
import org.eclipse.aether.resolution.DependencyResult;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.java.ExpandWildcardImportsStep;
import com.diffplug.spotless.maven.FormatterStepConfig;
import com.diffplug.spotless.maven.FormatterStepFactory;

public class ExpandWildcardImports implements FormatterStepFactory {

@Override
public FormatterStep newFormatterStep(FormatterStepConfig config) {
MavenProject project = config.getProject();
Set<File> typeSolverClasspath = new HashSet<>();

// Add all main source roots
project.getCompileSourceRoots().stream()
.map(File::new)
.filter(File::exists)
.forEach(typeSolverClasspath::add);

// Add all test source roots
project.getTestCompileSourceRoots().stream()
.map(File::new)
.filter(File::exists)
.forEach(typeSolverClasspath::add);

// Resolve dependencies using Maven's DependencyResolver API
// This will properly handle reactor dependencies by including their target/classes directories
// via the WorkspaceReader in the RepositorySystemSession
typeSolverClasspath.addAll(resolveDependencies(project, config.getRepositorySystem(), config.getRepositorySystemSession()));

return ExpandWildcardImportsStep.create(typeSolverClasspath, config.getProvisioner());
}

private Set<File> resolveDependencies(MavenProject project, RepositorySystem repositorySystem, RepositorySystemSession session) {
try {
// Use the project's already-resolved artifacts (which includes transitives)
// and convert them to Aether dependencies for re-resolution
// This allows the WorkspaceReader to map reactor modules to target/classes
List<Dependency> dependencies = project.getArtifacts().stream()
.map(artifact -> new Dependency(
new org.eclipse.aether.artifact.DefaultArtifact(
artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getClassifier(),
artifact.getType(),
artifact.getVersion()),
artifact.getScope()))
.collect(Collectors.toList());

// Create a collect request with all dependencies
CollectRequest collectRequest = new CollectRequest();
collectRequest.setDependencies(dependencies);
collectRequest.setRepositories(project.getRemoteProjectRepositories());

// Create a dependency request to resolve all artifacts
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null);

// Resolve dependencies - this will use the WorkspaceReader in the session
// to resolve reactor modules to their target/classes directories
DependencyResult result = repositorySystem.resolveDependencies(session, dependencyRequest);

// Extract the resolved artifact files
return result.getArtifactResults().stream()
.map(ArtifactResult::getArtifact)
.map(Artifact::getFile)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
} catch (DependencyResolutionException e) {
// If resolution fails, fall back to using the artifacts already attached to the project
// This ensures the build doesn't fail, but reactor dependencies may not be properly resolved
// Note: Using System.err as this is a FormatterStepFactory without access to Maven's logger
System.err.println("Warning: Failed to resolve dependencies using RepositorySystem, " +
"falling back to project artifacts. Reactor dependencies may not be properly resolved: " + e.getMessage());
return getFallbackArtifacts(project);
}
}

private Set<File> getFallbackArtifacts(MavenProject project) {
return project.getArtifacts().stream()
.map(org.apache.maven.artifact.Artifact::getFile)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ public void addFormatAnnotations(FormatAnnotations formatAnnotations) {
addStepFactory(formatAnnotations);
}

public void addExpandWildcardImports(ExpandWildcardImports expandWildcardImports) {
addStepFactory(expandWildcardImports);
}

public void addCleanthat(CleanthatJava cleanthat) {
addStepFactory(cleanthat);
}
Expand Down
Loading