diff --git a/pom.xml b/pom.xml
index 2a847ecd8..c2896b652 100644
--- a/pom.xml
+++ b/pom.xml
@@ -219,7 +219,7 @@ under the License.
org.apache.maven.shared
maven-dependency-analyzer
- 1.17.2
+ 1.18.0-SNAPSHOT
org.apache.maven.shared
diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java
index 104c833b1..c16f736f4 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AbstractAnalyzeMojo.java
@@ -73,7 +73,8 @@ public abstract class AbstractAnalyzeMojo extends AbstractMojo {
/**
* Output used dependencies. Under the used undeclared and non-test scoped warnings, also list each dependency
- * class involved and the project classes that use it.
+ * class involved and the project classes that use it. Since 3.12.0, also list the used classes that more than one
+ * dependency contains, with the dependency the analysis selected, and the used classes that no dependency contains.
*/
@Parameter(property = "verbose", defaultValue = "false")
private boolean verbose;
@@ -349,11 +350,8 @@ protected final boolean isSkip() {
private boolean checkDependencies() throws MojoExecutionException {
ProjectDependencyAnalysis analysis;
List unneededForcedUsage = Collections.emptyList();
- Map> usages;
try {
analysis = createProjectDependencyAnalyzer().analyze(project, excludedClasses);
- // read before forceDeclaredDependenciesUsage, which drops the usages of every used declared dependency
- usages = usagesOf(analysis);
if (usedDependencies != null) {
ForcedUsage forced = new ForcedUsage(analysis, usedDependencies);
@@ -370,6 +368,7 @@ private boolean checkDependencies() throws MojoExecutionException {
analysis = analysis.ignoreNonCompile();
}
+ Map> usages = usagesOf(analysis);
Set usedDeclared = new LinkedHashSet<>(analysis.getUsedDeclaredArtifacts());
Map> usedUndeclaredWithClasses =
new LinkedHashMap<>(analysis.getUsedUndeclaredArtifactsWithClasses());
@@ -480,6 +479,8 @@ private boolean checkDependencies() throws MojoExecutionException {
reported = true;
}
+ reported |= verbose && logUsedClassDetails(analysis);
+
if (outputXML) {
writeDependencyXML(usedUndeclaredWithClasses.keySet());
}
@@ -570,6 +571,52 @@ private void logArtifacts(Map> artifacts, Map ambiguous = analysis.getAmbiguousUsedDependencyClasses();
+ if (ambiguous.isEmpty()) {
+ return false;
+ }
+
+ getLog().info("Used classes found in more than one dependency:");
+ Map> candidates = analysis.getCandidateArtifactsByUsedClass();
+ Map selected = analysis.getSelectedArtifactByUsedClass();
+ for (String className : ambiguous) {
+ getLog().info(" class " + className);
+ for (Artifact candidate : candidates.getOrDefault(className, Collections.emptySet())) {
+ // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961
+ candidate.isSnapshot();
+ getLog().info(" in " + candidate
+ + (candidate.equals(selected.get(className)) ? " (selected)" : ""));
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Lists the used classes that no dependency contains.
+ */
+ private boolean logUnmappedClasses(ProjectDependencyAnalysis analysis) {
+ Set unmapped = analysis.getUnmappedUsedDependencyClasses();
+ if (unmapped.isEmpty()) {
+ return false;
+ }
+
+ getLog().info("Used classes not found in any dependency:");
+ for (String className : unmapped) {
+ getLog().info(" class " + className);
+ }
+ return true;
+ }
+
private String inProject() {
return " (in " + project.getGroupId() + ":" + project.getArtifactId() + ")";
}
diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java
index def988d87..834e28a90 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeDepMgt.java
@@ -39,6 +39,7 @@
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
+import org.apache.maven.shared.dependency.analyzer.ArtifactKeys;
/**
* This mojo looks at the dependencies after final resolution and looks for mismatches in your dependencyManagement
@@ -222,7 +223,7 @@ public List getExclusionErrors(Map exclusions, Set<
* @return the resulting GA
*/
public String getExclusionKey(Artifact artifact) {
- return artifact.getGroupId() + ":" + artifact.getArtifactId();
+ return ArtifactKeys.groupArtifactId(artifact);
}
/**
diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRenderer.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRenderer.java
index af46a1b6e..e5f1e3836 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRenderer.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRenderer.java
@@ -19,7 +19,10 @@
package org.apache.maven.plugins.dependency.analyze;
import java.util.Collection;
+import java.util.Collections;
import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.doxia.sink.Sink;
@@ -96,6 +99,32 @@ protected void renderBody() {
reported = true;
}
+ // Generate the classes provided by more than one dependency:
+ Set ambiguousClasses = analysis.getAmbiguousUsedDependencyClasses();
+ if (!ambiguousClasses.isEmpty()) {
+ startSection(getI18nString("AmbiguousUsedClasses"));
+ renderAmbiguousClassesTable(
+ ambiguousClasses,
+ analysis.getCandidateArtifactsByUsedClass(),
+ analysis.getSelectedArtifactByUsedClass());
+ endSection();
+ reported = true;
+ }
+
+ // Generate the classes that no dependency provides:
+ Set unmappedClasses = analysis.getUnmappedUsedDependencyClasses();
+ if (!unmappedClasses.isEmpty()) {
+ startSection(getI18nString("UnmappedUsedClasses"));
+ startTable();
+ tableHeader(new String[] {"Used class"});
+ for (String className : unmappedClasses) {
+ tableRow(new String[] {className});
+ }
+ endTable();
+ endSection();
+ reported = true;
+ }
+
if (!reported) {
text(getI18nString("noDependencyProblems"));
}
@@ -103,6 +132,33 @@ protected void renderBody() {
endSection();
}
+ private void renderAmbiguousClassesTable(
+ Set ambiguousClasses, Map> candidates, Map selected) {
+ startTable();
+ tableHeader(new String[] {"Used class", "Candidate artifacts", "Selected artifact"});
+
+ for (String className : ambiguousClasses) {
+ StringBuilder candidateList = new StringBuilder();
+ for (Artifact candidate : candidates.getOrDefault(className, Collections.emptySet())) {
+ if (candidateList.length() > 0) {
+ candidateList.append(", ");
+ }
+ candidateList.append(coordinates(candidate));
+ }
+ Artifact selectedArtifact = selected.get(className);
+ tableRow(new String[] {
+ className, candidateList.toString(), selectedArtifact == null ? "" : coordinates(selectedArtifact)
+ });
+ }
+
+ endTable();
+ }
+
+ private static String coordinates(Artifact artifact) {
+ // includes the type and the classifier, which can be all that tells two candidates apart
+ return artifact.getId();
+ }
+
private void renderDependenciesTable(Sink sink, Collection artifacts) {
startTable();
diff --git a/src/main/java/org/apache/maven/plugins/dependency/analyze/ForcedUsage.java b/src/main/java/org/apache/maven/plugins/dependency/analyze/ForcedUsage.java
index 216b36471..30522c512 100644
--- a/src/main/java/org/apache/maven/plugins/dependency/analyze/ForcedUsage.java
+++ b/src/main/java/org/apache/maven/plugins/dependency/analyze/ForcedUsage.java
@@ -24,6 +24,7 @@
import java.util.Set;
import org.apache.maven.artifact.Artifact;
+import org.apache.maven.shared.dependency.analyzer.ArtifactKeys;
import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalysis;
/**
@@ -39,11 +40,11 @@ final class ForcedUsage {
ForcedUsage(ProjectDependencyAnalysis analysis, String[] usedDependencies) {
Set usedDeclared = new HashSet<>();
for (Artifact artifact : analysis.getUsedDeclaredArtifacts()) {
- usedDeclared.add(key(artifact));
+ usedDeclared.add(ArtifactKeys.groupArtifactId(artifact));
}
// the analyzer first matches an entry against the unused declared artifacts, so such an entry is needed
for (Artifact artifact : analysis.getUnusedDeclaredArtifacts()) {
- usedDeclared.remove(key(artifact));
+ usedDeclared.remove(ArtifactKeys.groupArtifactId(artifact));
}
for (String entry : usedDependencies) {
(usedDeclared.contains(entry) ? unneeded : toForce).add(entry);
@@ -67,8 +68,4 @@ String[] getToForce() {
static String message(String entry) {
return "Unneeded forced usage of " + entry + ": the dependency is already detected as used";
}
-
- private static String key(Artifact artifact) {
- return artifact.getGroupId() + ":" + artifact.getArtifactId();
- }
}
diff --git a/src/main/resources/analyze-report.properties b/src/main/resources/analyze-report.properties
index a2848b5d8..fe50f9395 100644
--- a/src/main/resources/analyze-report.properties
+++ b/src/main/resources/analyze-report.properties
@@ -23,3 +23,5 @@ report.analyze.UsedDeclaredDependencies=Used and Declared Dependencies
report.analyze.UsedUndeclaredDependencies=Used but Undeclared Dependencies
report.analyze.UnusedDeclaredDependencies=Unused but Declared Dependencies
report.analyze.CompileScopeTestOnlyDependencies=Compile Scoped Test Dependencies
+report.analyze.AmbiguousUsedClasses=Ambiguous Used Classes
+report.analyze.UnmappedUsedClasses=Used Classes Not Found in Any Dependency
diff --git a/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojoIgnoreTest.java b/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojoIgnoreTest.java
index 3e64fecf3..d2fec3d03 100644
--- a/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojoIgnoreTest.java
+++ b/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeMojoIgnoreTest.java
@@ -392,6 +392,53 @@ void verboseShowsWhoUsesANonTestScopedDependencyAfterForcedUsage(AnalyzeOnlyMojo
order.verify(log).warn(" used by com.acme.ModelTest");
}
+ @Test
+ @InjectMojo(goal = "analyze-only")
+ @MojoParameter(name = "verbose", value = "true")
+ @MojoParameter(name = "failOnWarning", value = "true")
+ void verboseListsAmbiguousAndUnmappedClasses(AnalyzeOnlyMojo mojo) throws Exception {
+ setVariableValueToObject(mojo, "outputDirectory", outputDirectory);
+ when(analyzer.analyze(any(), any())).thenReturn(analysisWithAmbiguousAndUnmappedClasses());
+
+ mojo.execute();
+
+ InOrder order = inOrder(log);
+ order.verify(log).info("Used classes found in more than one dependency:");
+ order.verify(log).info(" class org.apache.maven.model.Model");
+ order.verify(log).info(" in " + MAVEN_MODEL);
+ order.verify(log).info(" in " + MAVEN_MODEL_3 + " (selected)");
+ order.verify(log).info("Used classes not found in any dependency:");
+ order.verify(log).info(" class com.missing.Gone");
+ verify(log, never()).info("No dependency problems found");
+ }
+
+ @Test
+ @InjectMojo(goal = "analyze-only")
+ void withoutVerboseAmbiguousAndUnmappedClassesAreNotListed(AnalyzeOnlyMojo mojo) throws Exception {
+ setVariableValueToObject(mojo, "outputDirectory", outputDirectory);
+ when(analyzer.analyze(any(), any())).thenReturn(analysisWithAmbiguousAndUnmappedClasses());
+
+ mojo.execute();
+
+ verify(log).info("No dependency problems found");
+ verify(log, never()).info("Used classes found in more than one dependency:");
+ verify(log, never()).info("Used classes not found in any dependency:");
+ }
+
+ private static ProjectDependencyAnalysis analysisWithAmbiguousAndUnmappedClasses() {
+ Map> candidates = new LinkedHashMap<>();
+ candidates.put("org.apache.maven.model.Model", new LinkedHashSet<>(Arrays.asList(MAVEN_MODEL, MAVEN_MODEL_3)));
+ candidates.put("com.missing.Gone", Collections.emptySet());
+ return new ProjectDependencyAnalysis(
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptySet(),
+ Collections.emptySet(),
+ new LinkedHashSet<>(Arrays.asList("org.apache.maven.model.Model", "com.missing.Gone")),
+ candidates,
+ Collections.singletonMap("org.apache.maven.model.Model", MAVEN_MODEL_3));
+ }
+
@Test
@InjectMojo(goal = "analyze-only")
void withoutVerboseNoClassesOrUsingClassesAreListed(AnalyzeOnlyMojo mojo) throws Exception {
diff --git a/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRendererTest.java b/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRendererTest.java
new file mode 100644
index 000000000..3445f5ff7
--- /dev/null
+++ b/src/test/java/org/apache/maven/plugins/dependency/analyze/AnalyzeReportRendererTest.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.apache.maven.plugins.dependency.analyze;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.DefaultArtifact;
+import org.apache.maven.artifact.handler.DefaultArtifactHandler;
+import org.apache.maven.doxia.sink.Sink;
+import org.apache.maven.shared.dependency.analyzer.ProjectDependencyAnalysis;
+import org.codehaus.plexus.i18n.I18N;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class AnalyzeReportRendererTest {
+
+ @Mock
+ private Sink sink;
+
+ @Mock
+ private I18N i18n;
+
+ @Test
+ void rendersAmbiguousUsedClassesWithCandidatesAndSelectedArtifact() {
+ Artifact api = artifact("com.example", "api", "1.0");
+ Artifact shaded = new DefaultArtifact(
+ "com.example",
+ "api",
+ "1.0",
+ Artifact.SCOPE_COMPILE,
+ "jar",
+ "shaded",
+ new DefaultArtifactHandler("jar"));
+ Map> candidates = new LinkedHashMap<>();
+ candidates.put("com.example.Service", new LinkedHashSet<>(Arrays.asList(api, shaded)));
+ Map selected = new LinkedHashMap<>();
+ selected.put("com.example.Service", shaded);
+ ProjectDependencyAnalysis analysis = new ProjectDependencyAnalysis(
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptySet(),
+ Collections.emptySet(),
+ Collections.singleton("com.example.Service"),
+ candidates,
+ selected);
+
+ render(analysis);
+
+ ArgumentCaptor written = ArgumentCaptor.forClass(String.class);
+ verify(sink, atLeastOnce()).text(written.capture());
+ assertThat(written.getAllValues())
+ .contains(
+ "report.analyze.AmbiguousUsedClasses",
+ "com.example.Service",
+ "com.example:api:jar:1.0, com.example:api:jar:shaded:1.0",
+ "com.example:api:jar:shaded:1.0")
+ .doesNotContain("report.analyze.noDependencyProblems");
+ }
+
+ @Test
+ void rendersUsedClassesThatNoDependencyProvides() {
+ ProjectDependencyAnalysis analysis = new ProjectDependencyAnalysis(
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptySet(),
+ Collections.emptySet(),
+ Collections.singleton("com.missing.Gone"),
+ Collections.singletonMap("com.missing.Gone", Collections.emptySet()),
+ Collections.emptyMap());
+
+ render(analysis);
+
+ ArgumentCaptor written = ArgumentCaptor.forClass(String.class);
+ verify(sink, atLeastOnce()).text(written.capture());
+ assertThat(written.getAllValues())
+ .contains("report.analyze.UnmappedUsedClasses", "com.missing.Gone")
+ .doesNotContain("report.analyze.noDependencyProblems");
+ }
+
+ @Test
+ void omitsAmbiguousSectionForAnalysisWithoutCandidateData() {
+ ProjectDependencyAnalysis analysis = new ProjectDependencyAnalysis(
+ Collections.emptyMap(), Collections.emptyMap(), Collections.emptySet(), Collections.emptySet());
+
+ render(analysis);
+
+ verify(sink, never()).text("report.analyze.AmbiguousUsedClasses");
+ verify(sink, never()).text("report.analyze.UnmappedUsedClasses");
+ }
+
+ private void render(ProjectDependencyAnalysis analysis) {
+ when(i18n.getString(anyString(), any(Locale.class), anyString()))
+ .thenAnswer(invocation -> invocation.getArgument(2));
+ new AnalyzeReportRenderer(sink, i18n, Locale.ENGLISH, analysis).renderBody();
+ }
+
+ private static Artifact artifact(String groupId, String artifactId, String version) {
+ return new DefaultArtifact(
+ groupId, artifactId, version, Artifact.SCOPE_COMPILE, "jar", null, new DefaultArtifactHandler("jar"));
+ }
+}