This is an automated email from the ASF dual-hosted git repository. slachiewicz pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/maven-dependency-plugin.git
commit 4b6ef24aaeea06fdb3177a59218c07a21c34ac52 Author: Sylwester Lachiewicz <[email protected]> AuthorDate: Sat Nov 14 14:21:49 2026 +0100 Count every artifact a dependency brings in for showSizes totals --- .../tree-show-sizes-verbose/invoker.properties | 3 +- .../projects/tree-show-sizes-verbose/verify.groovy | 15 +- src/it/projects/tree-show-sizes/lib/system.jar | Bin 0 -> 100 bytes src/it/projects/tree-show-sizes/pom.xml | 9 +- src/it/projects/tree-show-sizes/verify.groovy | 14 +- .../plugins/dependency/tree/DependencyNode.java | 53 ++++-- .../plugins/dependency/tree/DependencySizes.java | 192 +++++++++++++++----- .../dependency/tree/DependencyTreeBuilder.java | 1 + .../dependency/tree/JsonDependencyNodeVisitor.java | 52 +++--- .../maven/plugins/dependency/tree/TreeMojo.java | 107 +++++++---- src/site/markdown/examples/tree-mojo.md | 2 +- src/site/markdown/usage.md.vm | 9 +- .../dependency/tree/DependencySizesTest.java | 201 ++++++++++++++------- 13 files changed, 443 insertions(+), 215 deletions(-) diff --git a/src/it/projects/tree-show-sizes-verbose/invoker.properties b/src/it/projects/tree-show-sizes-verbose/invoker.properties index 74bcbca4..021d4ef0 100644 --- a/src/it/projects/tree-show-sizes-verbose/invoker.properties +++ b/src/it/projects/tree-show-sizes-verbose/invoker.properties @@ -15,4 +15,5 @@ # specific language governing permissions and limitations # under the License. -invoker.goals = ${project.groupId}:${project.artifactId}:${project.version}:tree -Dverbose -DshowSizes -DoutputFile=target/tree.txt +invoker.goals.1 = ${project.groupId}:${project.artifactId}:${project.version}:tree -Dverbose -DshowSizes -DoutputFile=target/tree.txt +invoker.goals.2 = ${project.groupId}:${project.artifactId}:${project.version}:tree -DshowSizes -DoutputFile=target/tree-plain.txt diff --git a/src/it/projects/tree-show-sizes-verbose/verify.groovy b/src/it/projects/tree-show-sizes-verbose/verify.groovy index 91892b8e..10fa2fdf 100644 --- a/src/it/projects/tree-show-sizes-verbose/verify.groovy +++ b/src/it/projects/tree-show-sizes-verbose/verify.groovy @@ -28,12 +28,21 @@ long leaf = jarSize("tree-sizes-leaf") long root = jarSize("tree-sizes-root") assertThat(leaf + root).isLessThan(1024L) -// the leaf is a direct dependency, so the one below tree-sizes-root is omitted: no size, and not counted again -assertThat(new File(basedir, "target/tree.txt").readLines()).containsExactly( +// the leaf is a direct dependency, so the one below tree-sizes-root is omitted: it shows no size, but the root +// still brings it in, and the project counts it once +def verbose = [ "org.apache.maven.plugins.dependency.its:tree-show-sizes-verbose:jar:1.0-SNAPSHOT (total ${leaf + root} B)".toString(), - "+- org.apache.maven.its.dependency:tree-sizes-root:jar:1.0:compile (${root} B, total ${root} B)".toString(), + "+- org.apache.maven.its.dependency:tree-sizes-root:jar:1.0:compile (${root} B, total ${root + leaf} B)".toString(), "| +- (org.apache.maven.its.dependency:tree-sizes-leaf:jar:1.0:compile - omitted for duplicate)", "| \\- org.apache.maven.its.dependency:tree-sizes-gone:jar:1.0:compile (size unknown)", + "\\- org.apache.maven.its.dependency:tree-sizes-leaf:jar:1.0:compile (${leaf} B)".toString()] +assertThat(new File(basedir, "target/tree.txt").readLines()).containsExactlyElementsOf(verbose) + +// the plain tree shows what Maven resolves, and the same totals: the root brings in the leaf kept elsewhere +assertThat(new File(basedir, "target/tree-plain.txt").readLines()).containsExactly( + "org.apache.maven.plugins.dependency.its:tree-show-sizes-verbose:jar:1.0-SNAPSHOT (total ${leaf + root} B)".toString(), + "+- org.apache.maven.its.dependency:tree-sizes-root:jar:1.0:compile (${root} B, total ${root + leaf} B)".toString(), + "| \\- org.apache.maven.its.dependency:tree-sizes-gone:jar:1.0:compile (size unknown)", "\\- org.apache.maven.its.dependency:tree-sizes-leaf:jar:1.0:compile (${leaf} B)".toString()) return true diff --git a/src/it/projects/tree-show-sizes/lib/system.jar b/src/it/projects/tree-show-sizes/lib/system.jar new file mode 100644 index 00000000..eeb57607 Binary files /dev/null and b/src/it/projects/tree-show-sizes/lib/system.jar differ diff --git a/src/it/projects/tree-show-sizes/pom.xml b/src/it/projects/tree-show-sizes/pom.xml index 6c3c2389..e7b76a2b 100644 --- a/src/it/projects/tree-show-sizes/pom.xml +++ b/src/it/projects/tree-show-sizes/pom.xml @@ -25,7 +25,7 @@ <artifactId>tree-show-sizes</artifactId> <version>1.0-SNAPSHOT</version> <description> - dependency:tree with showSizes resolves the artifacts and shows sizes and totals in text and json, ignoring them for dot. + dependency:tree with showSizes resolves the artifacts, measures a system dependency at its systemPath, and shows sizes and totals in text and json, ignoring them for dot. </description> <dependencies> <dependency> @@ -33,5 +33,12 @@ <artifactId>tree-sizes-root</artifactId> <version>1.0</version> </dependency> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-system</artifactId> + <version>1.0</version> + <scope>system</scope> + <systemPath>${basedir}/lib/system.jar</systemPath> + </dependency> </dependencies> </project> diff --git a/src/it/projects/tree-show-sizes/verify.groovy b/src/it/projects/tree-show-sizes/verify.groovy index 5d345617..97c5e7d4 100644 --- a/src/it/projects/tree-show-sizes/verify.groovy +++ b/src/it/projects/tree-show-sizes/verify.groovy @@ -29,22 +29,26 @@ def jarSize = { String artifactId -> } long leaf = jarSize("tree-sizes-leaf") long root = jarSize("tree-sizes-root") -long total = leaf + root +long system = new File(basedir, "lib/system.jar").length() +assertThat(system).isEqualTo(100L) +long total = leaf + root + system // the sizes are formatted as bytes below 1 KB assertThat(total).isLessThan(1024L) assertThat(new File(basedir, "target/tree.txt").readLines()).containsExactly( "org.apache.maven.plugins.dependency.its:tree-show-sizes:jar:1.0-SNAPSHOT (total ${total} B)".toString(), - "\\- org.apache.maven.its.dependency:tree-sizes-root:jar:1.0:compile (${root} B, total ${total} B)".toString(), - " +- org.apache.maven.its.dependency:tree-sizes-leaf:jar:1.0:compile (${leaf} B)".toString(), - " \\- org.apache.maven.its.dependency:tree-sizes-gone:jar:1.0:compile (size unknown)") + "+- org.apache.maven.its.dependency:tree-sizes-root:jar:1.0:compile (${root} B, total ${root + leaf} B)".toString(), + "| +- org.apache.maven.its.dependency:tree-sizes-leaf:jar:1.0:compile (${leaf} B)".toString(), + "| \\- org.apache.maven.its.dependency:tree-sizes-gone:jar:1.0:compile (size unknown)", + "\\- org.apache.maven.its.dependency:tree-sizes-system:jar:1.0:system (${system} B)".toString()) def json = new JsonSlurper().parse(new File(basedir, "target/tree.json")) assertThat(json).doesNotContainKey("size") assertThat(json.totalSize).isEqualTo(total) def node = json.children[0] assertThat(node.size).isEqualTo(root) -assertThat(node.totalSize).isEqualTo(total) +assertThat(node.totalSize).isEqualTo(root + leaf) +assertThat(json.children[1].size).isEqualTo(system) assertThat(node.children[0].size).isEqualTo(leaf) assertThat(node.children[0].totalSize).isEqualTo(leaf) assertThat(node.children[1]).doesNotContainKey("size") diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyNode.java b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyNode.java index 03b6276a..fa1458ce 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyNode.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyNode.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.function.Predicate; import org.apache.maven.artifact.Artifact; +import org.eclipse.aether.repository.RemoteRepository; /** * A node of the dependency tree displayed by the {@link TreeMojo}. @@ -41,6 +42,12 @@ public class DependencyNode { private boolean sized; + private boolean bringsOthers; + + private org.eclipse.aether.artifact.Artifact resolverArtifact; + + private List<RemoteRepository> repositories = Collections.emptyList(); + private Long size; private long totalSize; @@ -88,37 +95,58 @@ public class DependencyNode { this.verboseInfo = verboseInfo; } - /** - * @return whether the sizes were computed for this node, which they are for the nodes of the tree displayed by - * <code>dependency:tree -DshowSizes</code> that are not omitted - * @since 3.12.0 - */ - public boolean hasSizes() { + boolean hasSizes() { return sized; } /** * @return the size in bytes of the file of the artifact, or <code>null</code> if it is not known, or for the root * node, which is the project - * @since 3.12.0 */ - public Long getSize() { + Long getSize() { return size; } /** - * @return the size in bytes of the distinct artifacts of this node and its descendants, those of unknown size + * @return the size in bytes of the distinct artifacts this node brings in, itself included, those of unknown size * counted as zero - * @since 3.12.0 */ - public long getTotalSize() { + long getTotalSize() { return totalSize; } - void setSizes(Long size, long totalSize) { + /** + * @return whether the node brings in artifacts other than its own + */ + boolean bringsOthers() { + return bringsOthers; + } + + void setSizes(Long size, long totalSize, boolean bringsOthers) { this.sized = true; this.size = size; this.totalSize = totalSize; + this.bringsOthers = bringsOthers; + } + + /** + * @return the artifact of the resolver graph, which keeps the <code>systemPath</code> of a dependency of scope + * <code>system</code>, or <code>null</code> + */ + org.eclipse.aether.artifact.Artifact getResolverArtifact() { + return resolverArtifact; + } + + /** + * @return the repositories the artifact can be resolved from, empty if not known + */ + List<RemoteRepository> getRepositories() { + return repositories; + } + + void setResolution(org.eclipse.aether.artifact.Artifact resolverArtifact, List<RemoteRepository> repositories) { + this.resolverArtifact = resolverArtifact; + this.repositories = repositories == null ? Collections.<RemoteRepository>emptyList() : repositories; } /** @@ -162,6 +190,7 @@ public class DependencyNode { DependencyNode copy = new DependencyNode(newParent, artifact, nodeString); copy.setVerboseInfo(verboseInfo); + copy.setResolution(resolverArtifact, repositories); List<DependencyNode> copiedChildren = new ArrayList<>(children.size()); for (DependencyNode child : children) { DependencyNode copiedChild = child.filter(copy, keep, include); diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/DependencySizes.java b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencySizes.java index 7ec0953e..794f38ad 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/DependencySizes.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencySizes.java @@ -18,21 +18,31 @@ */ package org.apache.maven.plugins.dependency.tree; +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; 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.eclipse.aether.artifact.ArtifactProperties; /** * Computes and formats the sizes shown by <code>dependency:tree -DshowSizes</code>. * <p> * The size of a node is the length of the file of its artifact. The total of a node is the sum of the sizes of the - * distinct artifacts in its subtree: the artifact of the node itself and the artifacts of all its descendants, each - * counted once even when it occurs several times in the subtree. Nodes that the verbose tree marks as omitted are - * neither shown with a size nor counted, so the totals are the same with and without <code>-Dverbose</code>. An - * artifact without a known size counts as zero. The project itself, the root of the tree, has no size of its own and - * its total is the sum over all its dependencies. + * distinct artifacts that the dependency brings in as Maven resolves them: its own artifact and the artifacts of all + * its dependencies, transitively, each counted once. Distinct means a different + * <code>groupId:artifactId:type[:classifier]:version</code>. A dependency that Maven resolves once, below another + * node, still counts for every node that depends on it: the totals are computed on the verbose tree, where a node + * that is omitted for being a duplicate, or for losing to another version, stands for the node that Maven kept, and + * adds the artifacts of that node and of its dependencies. The omitted version itself does not count. An artifact + * without a known size counts as zero. The project, the root of the tree, has no size of its own and its total is + * the sum over all its dependencies. */ final class DependencySizes { private static final String[] UNITS = {"B", "KB", "MB", "GB", "TB"}; @@ -40,65 +50,136 @@ final class DependencySizes { private DependencySizes() {} /** - * Collects the distinct artifacts whose size is needed: those of the nodes below the root that are not omitted. + * Collects the nodes whose size is needed, one per distinct artifact: those of the trees below the roots that are + * not omitted. * - * @param root the root of the displayed tree - * @return the artifacts by {@link #key(Artifact)}, in tree order + * @param displayed the root of the displayed tree + * @param complete the root of the verbose tree the totals are computed on + * @return the nodes by {@link #key(Artifact)}, in tree order */ - static Map<String, Artifact> artifacts(DependencyNode root) { - Map<String, Artifact> artifacts = new LinkedHashMap<>(); - for (DependencyNode child : root.getChildren()) { - collect(child, artifacts); + static Map<String, DependencyNode> nodes(DependencyNode displayed, DependencyNode complete) { + Map<String, DependencyNode> nodes = new LinkedHashMap<>(); + for (DependencyNode child : complete.getChildren()) { + collect(child, nodes); } - return artifacts; + for (DependencyNode child : displayed.getChildren()) { + collect(child, nodes); + } + return nodes; } - private static void collect(DependencyNode node, Map<String, Artifact> artifacts) { + private static void collect(DependencyNode node, Map<String, DependencyNode> nodes) { if (!isIncluded(node)) { return; } - artifacts.putIfAbsent(key(node.getArtifact()), node.getArtifact()); + nodes.putIfAbsent(key(node.getArtifact()), node); for (DependencyNode child : node.getChildren()) { - collect(child, artifacts); + collect(child, nodes); } } /** - * Sets the size and the total on every node of the tree that is not omitted. + * Sets the size and the total on every node of the displayed tree that is not omitted. * - * @param root the root of the displayed tree + * @param displayed the root of the displayed tree + * @param complete the root of the verbose tree, as collected, that the totals are computed on * @param fileSizes the size in bytes of the artifacts by {@link #key(Artifact)}; an artifact that is not in the * map has an unknown size */ - static void annotate(DependencyNode root, Map<String, Long> fileSizes) { - annotate(root, fileSizes, true); + static void annotate(DependencyNode displayed, DependencyNode complete, Map<String, Long> fileSizes) { + Totals totals = new Totals(complete); + Set<String> all = new LinkedHashSet<>(); + for (DependencyNode child : complete.getChildren()) { + all.addAll(totals.brought(child)); + } + displayed.setSizes(null, sum(all, fileSizes), true); + for (DependencyNode child : displayed.getChildren()) { + annotateDisplayed(child, totals, fileSizes); + } + } + + private static void annotateDisplayed(DependencyNode node, Totals totals, Map<String, Long> fileSizes) { + if (!isIncluded(node)) { + return; + } + Set<String> brought = totals.brought(node); + node.setSizes(fileSizes.get(key(node.getArtifact())), sum(brought, fileSizes), brought.size() > 1); + for (DependencyNode child : node.getChildren()) { + annotateDisplayed(child, totals, fileSizes); + } + } + + private static long sum(Set<String> keys, Map<String, Long> fileSizes) { + long total = 0; + for (String key : keys) { + Long size = fileSizes.get(key); + if (size != null) { + total += size; + } + } + return total; } /** - * @return the distinct artifacts of the subtree with their sizes, those of unknown size left out + * The artifacts that the nodes of the verbose tree bring in, with the node that Maven kept standing for each + * omitted one. */ - private static Map<String, Long> annotate(DependencyNode node, Map<String, Long> fileSizes, boolean isRoot) { - Map<String, Long> subtree = new LinkedHashMap<>(); - Long own = null; - if (!isRoot) { - own = fileSizes.get(key(node.getArtifact())); - if (own != null) { - subtree.put(key(node.getArtifact()), own); - } + private static final class Totals { + private final Map<String, DependencyNode> kept = new HashMap<>(); + + private final Map<String, Set<String>> brought = new HashMap<>(); + + private final Set<String> inProgress = new HashSet<>(); + + Totals(DependencyNode complete) { + index(complete); } - for (DependencyNode child : node.getChildren()) { - if (isIncluded(child)) { - subtree.putAll(annotate(child, fileSizes, false)); + + private void index(DependencyNode node) { + for (DependencyNode child : node.getChildren()) { + if (isIncluded(child)) { + kept.putIfAbsent(key(child.getArtifact()), child); + index(child); + } } } - long total = 0; - for (Long size : subtree.values()) { - total += size; + /** + * @return the keys of the node itself and of everything it brings in, also for a node of another tree such + * as the displayed one + */ + Set<String> brought(DependencyNode node) { + String key = key(node.getArtifact()); + DependencyNode complete = kept.getOrDefault(key, node); + Set<String> known = brought.get(key); + if (known != null) { + return known; + } + if (!inProgress.add(key)) { + return Collections.singleton(key); + } + Set<String> result = new LinkedHashSet<>(); + result.add(key); + for (DependencyNode child : complete.getChildren()) { + if (isIncluded(child)) { + result.addAll(brought(child)); + } else { + DependencyNode winner = kept.get(winnerKey(child)); + if (winner != null) { + result.addAll(brought(winner)); + } + } + } + inProgress.remove(key); + brought.put(key, result); + return result; } - node.setSizes(own, total); + } - return subtree; + private static String winnerKey(DependencyNode omitted) { + Artifact artifact = omitted.getArtifact(); + return artifact.getDependencyConflictId() + ":" + + omitted.getVerboseInfo().getWinnerVersion(); } private static boolean isIncluded(DependencyNode node) { @@ -112,30 +193,43 @@ final class DependencySizes { return artifact.getDependencyConflictId() + ":" + artifact.getVersion(); } + /** + * The file of a node that is known without resolving it: the file of the artifact, or the <code>systemPath</code> + * of a dependency of scope <code>system</code>. + * + * @return the file, or <code>null</code> if the artifact has to be resolved + */ + static File localFile(DependencyNode node) { + if (node.getArtifact().getFile() != null) { + return node.getArtifact().getFile(); + } + org.eclipse.aether.artifact.Artifact resolverArtifact = node.getResolverArtifact(); + if (resolverArtifact == null) { + return null; + } + if (resolverArtifact.getFile() != null) { + return resolverArtifact.getFile(); + } + String localPath = resolverArtifact.getProperty(ArtifactProperties.LOCAL_PATH, null); + return localPath != null ? new File(localPath) : null; + } + /** * The text shown after the label of a node, such as <code> (200 KB, total 1.5 MB)</code>, or the empty string for a - * node without sizes. + * node without sizes. The total is shown for the project and for a node that brings in other artifacts. */ static String describe(DependencyNode node) { if (!node.hasSizes()) { return ""; } - - StringBuilder text = new StringBuilder(" ("); - boolean hasSizedChild = false; - for (DependencyNode child : node.getChildren()) { - hasSizedChild |= child.hasSizes(); - } if (node.getParent() == null) { // the project has no size of its own - return text.append("total ") - .append(format(node.getTotalSize())) - .append(')') - .toString(); + return " (total " + format(node.getTotalSize()) + ")"; } + StringBuilder text = new StringBuilder(" ("); text.append(node.getSize() != null ? format(node.getSize()) : "size unknown"); - if (hasSizedChild) { + if (node.bringsOthers()) { text.append(", total ").append(format(node.getTotalSize())); } return text.append(')').toString(); diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyTreeBuilder.java b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyTreeBuilder.java index ccd771fa..ebdb4c86 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyTreeBuilder.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencyTreeBuilder.java @@ -129,6 +129,7 @@ class DependencyTreeBuilder { DependencyNode current = new DependencyNode( parent, artifact, verbose ? verboseNodeString(info, artifact) : nodeString(artifact)); current.setVerboseInfo(info); + current.setResolution(node.getArtifact(), node.getRepositories()); List<DependencyNode> children = new ArrayList<>(node.getChildren().size()); for (org.eclipse.aether.graph.DependencyNode child : node.getChildren()) { diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/JsonDependencyNodeVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/JsonDependencyNodeVisitor.java index d25e5dce..5d21aa86 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/JsonDependencyNodeVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/JsonDependencyNodeVisitor.java @@ -131,21 +131,20 @@ public class JsonDependencyNodeVisitor extends AbstractSerializingVisitor implem */ private void appendNodeValues(StringBuilder sb, int indent, DependencyNode node, boolean hasChildren) { Artifact artifact = node.getArtifact(); - Map<String, String> verboseValues = verboseValues(node.getVerboseInfo()); - sizeValues(node, verboseValues); + Map<String, String> extraValues = extraValues(node); appendKeyValue(sb, indent, "groupId", artifact.getGroupId()); appendKeyValue(sb, indent, "artifactId", artifact.getArtifactId()); appendKeyValue(sb, indent, "version", artifact.getVersion()); appendKeyValue(sb, indent, "type", artifact.getType()); appendKeyValue(sb, indent, "scope", artifact.getScope()); appendKeyValue(sb, indent, "classifier", artifact.getClassifier()); - if (hasChildren || !verboseValues.isEmpty()) { + if (hasChildren || !extraValues.isEmpty()) { appendKeyValue(sb, indent, "optional", String.valueOf(artifact.isOptional())); } else { appendKeyWithoutComma(sb, indent, "optional", String.valueOf(artifact.isOptional())); } - Iterator<Map.Entry<String, String>> entries = verboseValues.entrySet().iterator(); + Iterator<Map.Entry<String, String>> entries = extraValues.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); sb.append(indent(indent)) @@ -159,39 +158,32 @@ public class JsonDependencyNodeVisitor extends AbstractSerializingVisitor implem } /** - * The additional JSON values of a verbose node, in output order. The values are already JSON strings, like the - * existing <code>optional</code>. + * The additional JSON values of a node, in output order: those of a verbose node, as far as the tree was built + * verbose, then <code>size</code>, when known, and <code>totalSize</code> in bytes, as far as the node has sizes. + * The values are already JSON, strings in quotes and numbers without, like the existing <code>optional</code>. */ - private static Map<String, String> verboseValues(DependencyNode.VerboseInfo info) { + private static Map<String, String> extraValues(DependencyNode node) { Map<String, String> values = new LinkedHashMap<>(); - if (info == null) { - return values; + DependencyNode.VerboseInfo info = node.getVerboseInfo(); + if (info != null) { + putString(values, "included", String.valueOf(info.isIncluded())); + putString(values, "omittedReason", info.getOmittedReason()); + if (DependencyNode.VerboseInfo.OMITTED_FOR_CONFLICT.equals(info.getOmittedReason())) { + putString(values, "winnerVersion", info.getWinnerVersion()); + } + putString(values, "versionManagedFrom", info.getPremanagedVersion()); + putString(values, "scopeManagedFrom", info.getPremanagedScope()); + putString(values, "scopeNotUpdatedTo", info.getScopeNotUpdatedTo()); } - putString(values, "included", String.valueOf(info.isIncluded())); - putString(values, "omittedReason", info.getOmittedReason()); - if (DependencyNode.VerboseInfo.OMITTED_FOR_CONFLICT.equals(info.getOmittedReason())) { - putString(values, "winnerVersion", info.getWinnerVersion()); + if (node.hasSizes()) { + if (node.getSize() != null) { + values.put("size", String.valueOf(node.getSize())); + } + values.put("totalSize", String.valueOf(node.getTotalSize())); } - putString(values, "versionManagedFrom", info.getPremanagedVersion()); - putString(values, "scopeManagedFrom", info.getPremanagedScope()); - putString(values, "scopeNotUpdatedTo", info.getScopeNotUpdatedTo()); return values; } - /** - * Adds <code>size</code>, when known, and <code>totalSize</code> in bytes, as JSON numbers, to a node that has - * sizes. - */ - private static void sizeValues(DependencyNode node, Map<String, String> values) { - if (!node.hasSizes()) { - return; - } - if (node.getSize() != null) { - values.put("size", String.valueOf(node.getSize())); - } - values.put("totalSize", String.valueOf(node.getTotalSize())); - } - private static void putString(Map<String, String> values, String key, String value) { if (value != null) { values.put(key, "\"" + value + "\""); diff --git a/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java b/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java index 7a80397f..15b65670 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/TreeMojo.java @@ -28,14 +28,13 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedHashMap; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Predicate; import org.apache.maven.RepositoryUtils; -import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.execution.MavenSession; @@ -46,7 +45,6 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.plugins.dependency.tree.SerializingDependencyNodeVisitor.GraphTokens; import org.apache.maven.plugins.dependency.utils.DependencyUtil; -import org.apache.maven.plugins.dependency.utils.ResolverUtil; import org.apache.maven.project.DependencyResolutionException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectDependenciesResolver; @@ -54,6 +52,8 @@ import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilt import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.collection.DependencyCollectionException; +import org.eclipse.aether.repository.RemoteRepository; +import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; @@ -182,12 +182,19 @@ public class TreeMojo extends AbstractMojo { private List<String> excludes; /** - * Whether to show the size of the file of each artifact and, for an artifact with dependencies, the total size of - * the artifact and its dependencies. Showing sizes downloads the artifacts that are not in the local repository - * yet, which the goal does not do otherwise. In the total each distinct artifact of the subtree counts once, the - * nodes that <code>verbose</code> shows as omitted do not count, and an artifact that cannot be resolved counts as - * zero and is shown as <code>(size unknown)</code>. The total of the project, the root of the tree, is the size - * of all distinct dependencies. A size is shown with the units B, KB, MB, GB and TB, where 1 KB is 1024 bytes. + * Whether to show the size of the file of each artifact and, for an artifact that brings in others, its total. + * Showing sizes downloads the artifacts that are not in the local repository yet, which the goal does not do + * otherwise. + * <p> + * The total of a node is the size of all the distinct artifacts that the dependency brings in as Maven resolves + * them: its own artifact and those of its dependencies, transitively, each counted once, where distinct means a + * different <code>groupId:artifactId:type[:classifier]:version</code>. A dependency that Maven resolves once, below + * another node, counts for every node that depends on it, so the totals of two branches can overlap and the total + * of the project, which is the size of all distinct dependencies, is less than the sum of the totals of its + * dependencies. The totals are computed on the verbose tree even without <code>verbose</code>, and on the tree + * before <code>includes</code> and <code>excludes</code> filter it. An artifact that cannot be resolved is shown as + * <code>(size unknown)</code> and counts as zero. A size is shown with the units B, KB, MB, GB and TB, where 1 KB + * is 1024 bytes. * <p> * The sizes are shown for the output types <code>text</code>, as in * <code>+- org.foo:foo-all:jar:2.0:compile (200 KB, total 1.5 MB)</code>, and <code>json</code>, as the numbers @@ -257,8 +264,22 @@ public class TreeMojo extends AbstractMojo { rootNode = dependencyTreeBuilder.build(project, session.getRepositorySession(), artifactFilter); } + DependencyNode completeRoot = null; + if (showSizes) { + if (isSizesOutputType()) { + // the totals of the plain tree count what a node brings in, also where Maven kept it elsewhere + completeRoot = verbose + ? rootNode + : dependencyTreeBuilder.buildVerbose( + project, session.getRepositorySession(), artifactFilter); + } else { + getLog().warn("showSizes is ignored for outputType " + outputType + + ", it applies to text and json"); + } + } + boolean joinDotGraphs = outputFile != null && appendOutput && "dot".equals(outputType); - String dependencyTreeString = serializeDependencyTree(rootNode, !joinDotGraphs); + String dependencyTreeString = serializeDependencyTree(rootNode, completeRoot, !joinDotGraphs); if (outputFile != null) { String encoding = Objects.toString(outputEncoding, "UTF-8"); @@ -339,16 +360,18 @@ public class TreeMojo extends AbstractMojo { * Serializes the specified dependency tree to a string. * * @param theRootNode the dependency tree root node to serialize + * @param completeRoot the verbose tree to compute the sizes on, or <code>null</code> to show no sizes * @return the serialized dependency tree */ - private String serializeDependencyTree(DependencyNode theRootNode, boolean dotGraphEnvelope) { + private String serializeDependencyTree( + DependencyNode theRootNode, DependencyNode completeRoot, boolean dotGraphEnvelope) { StringWriter writer = new StringWriter(); DependencyNode displayed = theRootNode.filter(null, createExcludesDependencyNodeFilter(), createIncludesDependencyNodeFilter()); if (displayed != null) { - if (showSizes) { - annotateSizes(displayed); + if (completeRoot != null) { + annotateSizes(displayed, completeRoot); } displayed.accept( dotGraphEnvelope @@ -360,56 +383,62 @@ public class TreeMojo extends AbstractMojo { } /** - * Resolves the artifacts of the tree, in one request, and sets their sizes on the nodes. An artifact that cannot - * be resolved, or whose file is not a regular file such as the classes directory of a module of the reactor, has - * an unknown size. + * Resolves the artifacts of the tree, in one request, and sets their sizes and totals on the displayed nodes. An + * artifact that cannot be resolved, or whose file is not a regular file such as the classes directory of a module + * of the reactor, has an unknown size. A dependency of scope <code>system</code> is measured at its + * <code>systemPath</code>. */ - private void annotateSizes(DependencyNode displayed) { - if (!isSizesOutputType()) { - getLog().warn("showSizes is ignored for outputType " + outputType + ", it applies to text and json"); - return; - } - - Map<String, Artifact> artifacts = DependencySizes.artifacts(displayed); + private void annotateSizes(DependencyNode displayed, DependencyNode complete) { + Map<String, DependencyNode> nodes = DependencySizes.nodes(displayed, complete); Map<String, Long> sizes = new HashMap<>(); - Map<String, org.eclipse.aether.artifact.Artifact> toResolve = new LinkedHashMap<>(); - for (Map.Entry<String, Artifact> entry : artifacts.entrySet()) { - File file = entry.getValue().getFile(); + List<ArtifactRequest> requests = new ArrayList<>(); + Map<org.eclipse.aether.artifact.Artifact, String> keys = new IdentityHashMap<>(); + for (Map.Entry<String, DependencyNode> entry : nodes.entrySet()) { + DependencyNode node = entry.getValue(); + File file = DependencySizes.localFile(node); if (file != null) { if (file.isFile()) { sizes.put(entry.getKey(), file.length()); + } else { + getLog().debug("No size for " + node.getArtifact() + ", not a file: " + file); } } else { - toResolve.put(entry.getKey(), RepositoryUtils.toArtifact(entry.getValue())); + org.eclipse.aether.artifact.Artifact artifact = node.getResolverArtifact() != null + ? node.getResolverArtifact() + : RepositoryUtils.toArtifact(node.getArtifact()); + List<RemoteRepository> repositories = node.getRepositories().isEmpty() + ? project.getRemoteProjectRepositories() + : node.getRepositories(); + requests.add(new ArtifactRequest(artifact, repositories, null)); + keys.put(artifact, entry.getKey()); } } - if (!toResolve.isEmpty()) { - List<String> keys = new ArrayList<>(toResolve.keySet()); + if (!requests.isEmpty()) { List<ArtifactResult> results; try { - results = new ResolverUtil(repositorySystem, () -> session) - .resolveArtifacts(toResolve.values(), project.getRemoteProjectRepositories()); + results = repositorySystem.resolveArtifacts(session.getRepositorySession(), requests); } catch (ArtifactResolutionException e) { results = e.getResults(); } - for (int i = 0; i < results.size() && i < keys.size(); i++) { - File file = results.get(i).isResolved() - ? results.get(i).getArtifact().getFile() - : null; - if (file != null && file.isFile()) { - sizes.put(keys.get(i), file.length()); + for (ArtifactResult result : results) { + String key = keys.get(result.getRequest().getArtifact()); + File file = result.isResolved() ? result.getArtifact().getFile() : null; + if (key != null && file != null && file.isFile()) { + sizes.put(key, file.length()); + } else { + getLog().debug("No size for " + result.getRequest().getArtifact() + ": " + result.getExceptions()); } } } - int unknown = artifacts.size() - sizes.size(); + int unknown = nodes.size() - sizes.size(); if (unknown > 0) { getLog().warn("The size of " + unknown + (unknown > 1 ? " artifacts is" : " artifact is") + " unknown, counted as zero in the totals"); } - DependencySizes.annotate(displayed, sizes); + DependencySizes.annotate(displayed, complete, sizes); } private boolean isSizesOutputType() { diff --git a/src/site/markdown/examples/tree-mojo.md b/src/site/markdown/examples/tree-mojo.md index 7c278669..54505b1b 100644 --- a/src/site/markdown/examples/tree-mojo.md +++ b/src/site/markdown/examples/tree-mojo.md @@ -65,7 +65,7 @@ mvn dependency:tree -DoutputType=<format> -DoutputFile=<filename> - `optional`: Whether the dependency is optional (`true` or `false`). - `children`: An array of dependency objects with the same structure, representing transitive dependencies. - With `-Dverbose`, every node also has `included` (the string `"true"`, or `"false"` for a node Maven leaves out of the resolved tree), and, when they apply, `omittedReason` (`duplicate` or `conflict`), `winnerVersion` (the version kept instead, for `conflict`), `versionManagedFrom`, `scopeManagedFrom` and `scopeNotUpdatedTo`. These fields are not written without `-Dverbose`. - - With `-DshowSizes` (since 3.12.0), every node that is not omitted also has the number `totalSize`, the size in bytes of its distinct artifacts and those of its dependencies, and, when the artifact could be resolved, the number `size`, the size in bytes of its file. The project has only `totalSize`. These members are not written without `-DshowSizes`. + - With `-DshowSizes` (since 3.12.0), every node that is not omitted also has the number `totalSize`, the size in bytes of the distinct artifacts it brings in, its own and those of its dependencies, and, when the artifact could be resolved, the number `size`, the size in bytes of its file. The project has only `totalSize`. These members are not written without `-DshowSizes`. - **Nested Dependencies**: Each dependency in the `children` array follows the same structure, allowing for recursive representation of the dependency tree. **Example**: diff --git a/src/site/markdown/usage.md.vm b/src/site/markdown/usage.md.vm index 240ffa7a..a11ba7f9 100644 --- a/src/site/markdown/usage.md.vm +++ b/src/site/markdown/usage.md.vm @@ -594,11 +594,12 @@ org.example:app:jar:1.0-SNAPSHOT (total 1.5 MB) \- org.foo:foo-gone:jar:2.0:compile (size unknown) ``` -- The total of a node is the sum of the sizes of the distinct artifacts in its subtree: the node itself and all its descendants, each artifact counted once even when it occurs several times in the subtree. The total of the project at the top is the size of all its distinct dependencies. +- The total of a node is the size of all the distinct artifacts that the dependency brings in as Maven resolves them: its own artifact and those of its dependencies, transitively, each counted once. Distinct means a different `groupId:artifactId:type[:classifier]:version`. +- A dependency that Maven resolves once, below another node, counts for every node that depends on it, also in the tree without `-Dverbose`, where it is shown only once. The totals of two branches can therefore overlap, and the total of the project at the top, which is the size of all distinct dependencies, is less than the sum of the totals of its dependencies. An artifact that Maven leaves out, because it is a duplicate or loses to another version, does not count itself; the kept one does. +- The totals are computed on the verbose tree even without `-Dverbose`, and before the `includes` and `excludes` filters apply, so a filter changes which nodes are shown, not their totals. - Sizes use the units B, KB, MB, GB and TB, where 1 KB is 1024 bytes, rounded to one decimal. -- An artifact that cannot be resolved is shown as `(size unknown)`, counts as zero in the totals, and the goal logs one warning with the number of such artifacts. An artifact whose file is not a regular file, such as the classes directory of a module of the same reactor build, is shown the same way. -- Nodes that `-Dverbose` shows as omitted are not resolved, show no size and do not count, so the totals count the artifacts that Maven resolves. -- The `includes` and `excludes` filters apply first: the totals cover the tree as displayed. +- A dependency of scope `system` is measured at its `systemPath`. An artifact that cannot be resolved is shown as `(size unknown)`, counts as zero in the totals, and the goal logs one warning with the number of such artifacts. An artifact whose file is not a regular file, such as the classes directory of a module of the same reactor build, is shown the same way. Run with `-X` to see why. +- Nodes that `-Dverbose` shows as omitted are not resolved and show no size. - With `-DoutputType=json` each node that is not omitted gets the number `totalSize` and, when known, the number `size`, both in bytes. The `dot`, `graphml`, `tgf` and `mermaid` formats ignore the parameter with a warning and download nothing. The `verbose` parameter explains the tree. By default the tree shows what Maven resolves: each artifact once, at the version and scope Maven selected. With `-Dverbose` the goal collects the dependencies again and also shows the nodes that Maven left out, and why: diff --git a/src/test/java/org/apache/maven/plugins/dependency/tree/DependencySizesTest.java b/src/test/java/org/apache/maven/plugins/dependency/tree/DependencySizesTest.java index 4f595542..595902d7 100644 --- a/src/test/java/org/apache/maven/plugins/dependency/tree/DependencySizesTest.java +++ b/src/test/java/org/apache/maven/plugins/dependency/tree/DependencySizesTest.java @@ -18,7 +18,10 @@ */ package org.apache.maven.plugins.dependency.tree; +import java.io.File; +import java.io.IOException; import java.io.StringWriter; +import java.nio.file.Files; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -28,7 +31,9 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.handler.DefaultArtifactHandler; import org.apache.maven.plugins.dependency.tree.DependencyNode.VerboseInfo; +import org.eclipse.aether.artifact.ArtifactProperties; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -36,84 +41,120 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class DependencySizesTest { + // the verbose tree Maven collects; sizes in brackets // root - // +- a (1000) - // | +- shared (100) - // | \- a2 (10) - // \- b (2000) - // +- shared (100) - // \- (shared2 omitted for duplicate, 5000) - private final DependencyNode root = node(null, "root"); - private final DependencyNode a = node(root, "a"); - private final DependencyNode aShared = node(a, "shared"); - private final DependencyNode a2 = node(a, "a2"); - private final DependencyNode b = node(root, "b"); - private final DependencyNode bShared = node(b, "shared"); - private final DependencyNode omitted = node(b, "omitted"); + // +- a:1.0 [1000] + // | +- shared:1.0 [100] + // | | \- deep:1.0 [5] + // | +- a2:1.0 [10] + // | \- lib:1.0 [50] + // \- b:1.0 [2000] + // +- (shared:1.0, omitted for duplicate) + // \- (lib:2.0 [999], omitted for conflict with 1.0) + private final DependencyNode root = node(null, "root", "1.0"); + private final DependencyNode a = node(root, "a", "1.0"); + private final DependencyNode shared = node(a, "shared", "1.0"); + private final DependencyNode deep = node(shared, "deep", "1.0"); + private final DependencyNode a2 = node(a, "a2", "1.0"); + private final DependencyNode lib = node(a, "lib", "1.0"); + private final DependencyNode b = node(root, "b", "1.0"); + private final DependencyNode sharedAgain = node(b, "shared", "1.0"); + private final DependencyNode libLoser = node(b, "lib", "2.0"); private final Map<String, Long> sizes = new HashMap<>(); DependencySizesTest() { root.setChildren(Arrays.asList(a, b)); - a.setChildren(Arrays.asList(aShared, a2)); - b.setChildren(Arrays.asList(bShared, omitted)); - omitted.setVerboseInfo(new VerboseInfo(VerboseInfo.OMITTED_FOR_DUPLICATE, "1.0", null, null, null)); - sizes.put(DependencySizes.key(a.getArtifact()), 1000L); - sizes.put(DependencySizes.key(aShared.getArtifact()), 100L); - sizes.put(DependencySizes.key(a2.getArtifact()), 10L); - sizes.put(DependencySizes.key(b.getArtifact()), 2000L); - sizes.put(DependencySizes.key(omitted.getArtifact()), 5000L); + a.setChildren(Arrays.asList(shared, a2, lib)); + shared.setChildren(Arrays.asList(deep)); + b.setChildren(Arrays.asList(sharedAgain, libLoser)); + sharedAgain.setVerboseInfo(new VerboseInfo(VerboseInfo.OMITTED_FOR_DUPLICATE, "1.0", null, null, null)); + libLoser.setVerboseInfo(new VerboseInfo(VerboseInfo.OMITTED_FOR_CONFLICT, "1.0", null, null, null)); + size(a, 1000); + size(shared, 100); + size(deep, 5); + size(a2, 10); + size(lib, 50); + size(b, 2000); + size(libLoser, 999); } - @Test - void totalIsOwnSizePlusDescendants() { - DependencySizes.annotate(root, sizes); - - assertEquals(Long.valueOf(1000), a.getSize()); - assertEquals(1110, a.getTotalSize()); - assertEquals(Long.valueOf(10), a2.getSize()); - assertEquals(10, a2.getTotalSize()); - assertEquals(2100, b.getTotalSize()); + /** The tree as Maven resolves it, without the omitted nodes. */ + private DependencyNode plain() { + return root.filter( + null, n -> n.getVerboseInfo() == null || n.getVerboseInfo().isIncluded(), null); } @Test - void artifactOccurringTwiceInASubtreeCountsOnce() { - // the same artifact below a and below b, counted once in the total of the root and once in each branch - DependencySizes.annotate(root, sizes); + void totalCountsWhatTheDependencyBringsInAlsoWhereMavenKeptItElsewhere() { + DependencyNode plain = plain(); + DependencySizes.annotate(plain, root, sizes); + + DependencyNode plainA = plain.getChildren().get(0); + DependencyNode plainB = plain.getChildren().get(1); + assertEquals(1000 + 100 + 5 + 10 + 50, plainA.getTotalSize()); + // b keeps no child in the plain tree, but depends on shared (with deep) and on lib 1.0 + assertTrue(plainB.getChildren().isEmpty()); + assertEquals(2000 + 100 + 5 + 50, plainB.getTotalSize()); + assertEquals(Long.valueOf(2000), plainB.getSize()); + // shared counts once for the project, the omitted lib 2.0 not at all + assertEquals(1000 + 100 + 5 + 10 + 50 + 2000, plain.getTotalSize()); + assertNull(plain.getSize()); + } - assertEquals(1000 + 100 + 10 + 2000, root.getTotalSize()); - assertNull(root.getSize()); + @Test + void sameTotalsInTheVerboseTree() { + DependencySizes.annotate(root, root, sizes); + + assertEquals(1165, a.getTotalSize()); + assertEquals(2155, b.getTotalSize()); + assertEquals(105, shared.getTotalSize()); + assertEquals(3165, root.getTotalSize()); + assertEquals(Long.valueOf(100), shared.getSize()); } @Test - void omittedNodeContributesNothingAndGetsNoSizes() { - DependencySizes.annotate(root, sizes); + void omittedNodeShowsNoSizeAndTheOmittedVersionDoesNotCount() { + DependencySizes.annotate(root, root, sizes); - assertFalse(omitted.hasSizes()); - assertEquals("", DependencySizes.describe(omitted)); - assertFalse(DependencySizes.artifacts(root).containsKey(DependencySizes.key(omitted.getArtifact()))); - assertEquals(2100, b.getTotalSize()); + assertFalse(sharedAgain.hasSizes()); + assertFalse(libLoser.hasSizes()); + assertEquals("", DependencySizes.describe(libLoser)); + assertFalse(DependencySizes.nodes(root, root).containsKey(DependencySizes.key(libLoser.getArtifact()))); } @Test void unknownSizeIsReportedAndCountsAsZero() { - sizes.remove(DependencySizes.key(a.getArtifact())); - - DependencySizes.annotate(root, sizes); - - assertNull(a.getSize()); - assertEquals(110, a.getTotalSize()); - assertEquals(" (size unknown, total 110 B)", DependencySizes.describe(a)); - assertEquals(" (10 B)", DependencySizes.describe(a2)); + sizes.remove(DependencySizes.key(a2.getArtifact())); + sizes.remove(DependencySizes.key(b.getArtifact())); + + DependencyNode plain = plain(); + DependencySizes.annotate(plain, root, sizes); + + assertEquals( + " (1000 B, total 1.1 KB)", + DependencySizes.describe(plain.getChildren().get(0))); + DependencyNode plainB = plain.getChildren().get(1); + assertNull(plainB.getSize()); + assertEquals(155, plainB.getTotalSize()); + assertEquals(" (size unknown, total 155 B)", DependencySizes.describe(plainB)); } @Test - void leafShowsOnlyItsSizeAndParentsShowTotal() { - DependencySizes.annotate(root, sizes); - - assertEquals(" (10 B)", DependencySizes.describe(a2)); - assertEquals(" (1000 B, total 1.1 KB)", DependencySizes.describe(a)); - assertEquals(" (total 3 KB)", DependencySizes.describe(root)); + void leafShowsOnlyItsSizeAndAnArtifactThatBringsInOthersShowsTotal() { + DependencyNode plain = plain(); + DependencySizes.annotate(plain, root, sizes); + + DependencyNode plainA = plain.getChildren().get(0); + assertEquals(" (10 B)", DependencySizes.describe(plainA.getChildren().get(1))); + assertEquals( + " (100 B, total 105 B)", + DependencySizes.describe(plainA.getChildren().get(0))); + // b has no child to show in the plain tree, still it brings in others + assertEquals( + " (2 KB, total 2.1 KB)", + DependencySizes.describe(plain.getChildren().get(1))); + assertEquals(" (total 3.1 KB)", DependencySizes.describe(plain)); } @Test @@ -124,25 +165,27 @@ class DependencySizesTest { @Test void collectsDistinctArtifactsExceptRootAndOmitted() { - Map<String, Artifact> artifacts = DependencySizes.artifacts(root); + Map<String, DependencyNode> nodes = DependencySizes.nodes(plain(), root); - assertEquals(4, artifacts.size()); - assertTrue(artifacts.containsKey(DependencySizes.key(aShared.getArtifact()))); - assertFalse(artifacts.containsKey(DependencySizes.key(root.getArtifact()))); + assertEquals(6, nodes.size()); + assertTrue(nodes.containsKey(DependencySizes.key(deep.getArtifact()))); + assertFalse(nodes.containsKey(DependencySizes.key(root.getArtifact()))); + assertFalse(nodes.containsKey(DependencySizes.key(libLoser.getArtifact()))); } @Test void textOutputAppendsSizes() { - DependencySizes.annotate(root, sizes); + DependencyNode plain = plain(); + DependencySizes.annotate(plain, root, sizes); StringWriter writer = new StringWriter(); - root.accept(new SerializingDependencyNodeVisitor(writer, SerializingDependencyNodeVisitor.STANDARD_TOKENS)); + plain.accept(new SerializingDependencyNodeVisitor(writer, SerializingDependencyNodeVisitor.STANDARD_TOKENS)); List<String> lines = Arrays.asList(writer.toString().split("\\R")); - assertEquals("root (total 3 KB)", lines.get(0)); + assertEquals("root (total 3.1 KB)", lines.get(0)); assertEquals("+- a (1000 B, total 1.1 KB)", lines.get(1)); - assertEquals("| +- shared (100 B)", lines.get(2)); - assertEquals("\\- b (2 KB, total 2.1 KB)", lines.get(4)); - assertEquals(" \\- omitted", lines.get(6)); + assertEquals("| +- shared (100 B, total 105 B)", lines.get(2)); + assertEquals("| | \\- deep (5 B)", lines.get(3)); + assertEquals("\\- b (2 KB, total 2.1 KB)", lines.get(6)); } @Test @@ -167,20 +210,38 @@ class DependencySizesTest { // a2 has an unknown size: totalSize only sizes.remove(DependencySizes.key(a2.getArtifact())); - DependencySizes.annotate(root, sizes); + DependencySizes.annotate(root, root, sizes); StringWriter withSizes = new StringWriter(); root.accept(new JsonDependencyNodeVisitor(withSizes)); String json = withSizes.toString(); assertTrue(json.contains("\"size\": 1000,")); - assertTrue(json.contains("\"totalSize\": 1100")); + assertTrue(json.contains("\"totalSize\": 1155")); assertTrue(json.contains("\"totalSize\": 0")); assertFalse(json.contains("\"size\": 10,")); - assertFalse(json.contains("\"size\": 10\n")); } - private static DependencyNode node(DependencyNode parent, String artifactId) { + @Test + void systemScopeUsesTheSystemPathNotTheResolver(@TempDir File dir) throws IOException { + File jar = new File(dir, "system.jar"); + Files.write(jar.toPath(), new byte[123]); + DependencyNode system = node(root, "system", "1.0"); + system.setResolution( + new org.eclipse.aether.artifact.DefaultArtifact("g:system:jar:1.0") + .setProperties(java.util.Collections.singletonMap( + ArtifactProperties.LOCAL_PATH, jar.getAbsolutePath())), + null); + + assertEquals(jar, DependencySizes.localFile(system)); + assertNull(DependencySizes.localFile(a)); + } + + private void size(DependencyNode node, long bytes) { + sizes.put(DependencySizes.key(node.getArtifact()), bytes); + } + + private static DependencyNode node(DependencyNode parent, String artifactId, String version) { Artifact artifact = new DefaultArtifact( - "g", artifactId, "1.0", Artifact.SCOPE_COMPILE, "jar", null, new DefaultArtifactHandler("jar")); + "g", artifactId, version, Artifact.SCOPE_COMPILE, "jar", null, new DefaultArtifactHandler("jar")); return new DependencyNode(parent, artifact, artifactId); } }
