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
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ under the License.
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-dependency-analyzer</artifactId>
<version>1.17.2</version>
<version>1.18.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -349,11 +350,8 @@ protected final boolean isSkip() {
private boolean checkDependencies() throws MojoExecutionException {
ProjectDependencyAnalysis analysis;
List<String> unneededForcedUsage = Collections.emptyList();
Map<Artifact, Set<DependencyUsage>> 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);
Expand All @@ -370,6 +368,7 @@ private boolean checkDependencies() throws MojoExecutionException {
analysis = analysis.ignoreNonCompile();
}

Map<Artifact, Set<DependencyUsage>> usages = usagesOf(analysis);
Set<Artifact> usedDeclared = new LinkedHashSet<>(analysis.getUsedDeclaredArtifacts());
Map<Artifact, Set<String>> usedUndeclaredWithClasses =
new LinkedHashMap<>(analysis.getUsedUndeclaredArtifactsWithClasses());
Expand Down Expand Up @@ -480,6 +479,8 @@ private boolean checkDependencies() throws MojoExecutionException {
reported = true;
}

reported |= verbose && logUsedClassDetails(analysis);

if (outputXML) {
writeDependencyXML(usedUndeclaredWithClasses.keySet());
}
Expand Down Expand Up @@ -570,6 +571,52 @@ private void logArtifacts(Map<Artifact, Set<String>> artifacts, Map<Artifact, Se
}
}

private boolean logUsedClassDetails(ProjectDependencyAnalysis analysis) {
boolean ambiguous = logAmbiguousClasses(analysis);
boolean unmapped = logUnmappedClasses(analysis);
return ambiguous || unmapped;
}

/**
* Lists the used classes that more than one dependency contains, with the dependency the analysis selected.
*/
private boolean logAmbiguousClasses(ProjectDependencyAnalysis analysis) {
Set<String> ambiguous = analysis.getAmbiguousUsedDependencyClasses();
if (ambiguous.isEmpty()) {
return false;
}

getLog().info("Used classes found in more than one dependency:");
Map<String, Set<Artifact>> candidates = analysis.getCandidateArtifactsByUsedClass();
Map<String, Artifact> 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<String> 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() + ")";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -222,7 +223,7 @@ public List<Artifact> getExclusionErrors(Map<String, Exclusion> exclusions, Set<
* @return the resulting GA
*/
public String getExclusionKey(Artifact artifact) {
return artifact.getGroupId() + ":" + artifact.getArtifactId();
return ArtifactKeys.groupArtifactId(artifact);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -96,13 +99,66 @@ protected void renderBody() {
reported = true;
}

// Generate the classes provided by more than one dependency:
Set<String> 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<String> 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"));
}

endSection();
}

private void renderAmbiguousClassesTable(
Set<String> ambiguousClasses, Map<String, Set<Artifact>> candidates, Map<String, Artifact> 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.<Artifact>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<Artifact> artifacts) {
startTable();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -39,11 +40,11 @@ final class ForcedUsage {
ForcedUsage(ProjectDependencyAnalysis analysis, String[] usedDependencies) {
Set<String> 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);
Expand All @@ -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();
}
}
2 changes: 2 additions & 0 deletions src/main/resources/analyze-report.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Set<Artifact>> 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 {
Expand Down
Loading
Loading