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 2fd398daa58bf4b7278e0f9189f2747b8a27d62d Author: Sylwester Lachiewicz <[email protected]> AuthorDate: Sat Nov 14 14:07:58 2026 +0100 Add showSizes to dependency:tree --- src/it/mrm/repository/tree-sizes-leaf-1.0.pom | 25 +++ src/it/mrm/repository/tree-sizes-off-1.0.pom | 25 +++ src/it/mrm/repository/tree-sizes-root-1.0.pom | 37 ++++ .../tree-show-sizes-off/invoker.properties | 19 +++ src/it/projects/tree-show-sizes-off/pom.xml | 37 ++++ src/it/projects/tree-show-sizes-off/verify.groovy | 31 ++++ .../tree-show-sizes-verbose/invoker.properties | 18 ++ src/it/projects/tree-show-sizes-verbose/pom.xml | 42 +++++ .../projects/tree-show-sizes-verbose/verify.groovy | 39 +++++ src/it/projects/tree-show-sizes/invoker.properties | 20 +++ src/it/projects/tree-show-sizes/pom.xml | 37 ++++ src/it/projects/tree-show-sizes/verify.groovy | 57 +++++++ .../plugins/dependency/tree/DependencyNode.java | 39 +++++ .../plugins/dependency/tree/DependencySizes.java | 168 +++++++++++++++++++ .../dependency/tree/JsonDependencyNodeVisitor.java | 15 ++ .../tree/SerializingDependencyNodeVisitor.java | 2 +- .../maven/plugins/dependency/tree/TreeMojo.java | 93 +++++++++++ src/site/markdown/examples/tree-mojo.md | 1 + src/site/markdown/usage.md.vm | 20 +++ .../dependency/tree/DependencySizesTest.java | 186 +++++++++++++++++++++ 20 files changed, 910 insertions(+), 1 deletion(-) diff --git a/src/it/mrm/repository/tree-sizes-leaf-1.0.pom b/src/it/mrm/repository/tree-sizes-leaf-1.0.pom new file mode 100644 index 00000000..ec1c8f39 --- /dev/null +++ b/src/it/mrm/repository/tree-sizes-leaf-1.0.pom @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ 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. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-leaf</artifactId> + <version>1.0</version> +</project> diff --git a/src/it/mrm/repository/tree-sizes-off-1.0.pom b/src/it/mrm/repository/tree-sizes-off-1.0.pom new file mode 100644 index 00000000..d2fdb060 --- /dev/null +++ b/src/it/mrm/repository/tree-sizes-off-1.0.pom @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ 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. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-off</artifactId> + <version>1.0</version> +</project> diff --git a/src/it/mrm/repository/tree-sizes-root-1.0.pom b/src/it/mrm/repository/tree-sizes-root-1.0.pom new file mode 100644 index 00000000..49e033ba --- /dev/null +++ b/src/it/mrm/repository/tree-sizes-root-1.0.pom @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ 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. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-root</artifactId> + <version>1.0</version> + <dependencies> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-leaf</artifactId> + <version>1.0</version> + </dependency> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-gone</artifactId> + <version>1.0</version> + </dependency> + </dependencies> +</project> diff --git a/src/it/projects/tree-show-sizes-off/invoker.properties b/src/it/projects/tree-show-sizes-off/invoker.properties new file mode 100644 index 00000000..5283c0e2 --- /dev/null +++ b/src/it/projects/tree-show-sizes-off/invoker.properties @@ -0,0 +1,19 @@ +# 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. + +invoker.goals.1 = ${project.groupId}:${project.artifactId}:${project.version}:tree -DoutputFile=target/tree.txt +invoker.goals.2 = ${project.groupId}:${project.artifactId}:${project.version}:tree -DshowSizes -DoutputType=dot -DoutputFile=target/tree.dot diff --git a/src/it/projects/tree-show-sizes-off/pom.xml b/src/it/projects/tree-show-sizes-off/pom.xml new file mode 100644 index 00000000..c776ece3 --- /dev/null +++ b/src/it/projects/tree-show-sizes-off/pom.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ 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. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.maven.plugins.dependency.its</groupId> + <artifactId>tree-show-sizes-off</artifactId> + <version>1.0-SNAPSHOT</version> + <description> + dependency:tree without showSizes does not download the artifacts and shows no sizes. + </description> + <dependencies> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-off</artifactId> + <version>1.0</version> + </dependency> + </dependencies> +</project> diff --git a/src/it/projects/tree-show-sizes-off/verify.groovy b/src/it/projects/tree-show-sizes-off/verify.groovy new file mode 100644 index 00000000..aa077106 --- /dev/null +++ b/src/it/projects/tree-show-sizes-off/verify.groovy @@ -0,0 +1,31 @@ +/* + * 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. + */ + +import static org.assertj.core.api.Assertions.assertThat + +assertThat(new File(basedir, "target/tree.txt").readLines()).containsExactly( + "org.apache.maven.plugins.dependency.its:tree-show-sizes-off:jar:1.0-SNAPSHOT", + "\\- org.apache.maven.its.dependency:tree-sizes-off:jar:1.0:compile") + +// only the POM was read, the jar was not downloaded, also not for an output type that ignores showSizes +def dir = new File(localRepositoryPath, "org/apache/maven/its/dependency/tree-sizes-off/1.0") +assertThat(new File(dir, "tree-sizes-off-1.0.pom")).exists() +assertThat(new File(dir, "tree-sizes-off-1.0.jar")).doesNotExist() + +return true diff --git a/src/it/projects/tree-show-sizes-verbose/invoker.properties b/src/it/projects/tree-show-sizes-verbose/invoker.properties new file mode 100644 index 00000000..74bcbca4 --- /dev/null +++ b/src/it/projects/tree-show-sizes-verbose/invoker.properties @@ -0,0 +1,18 @@ +# 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. + +invoker.goals = ${project.groupId}:${project.artifactId}:${project.version}:tree -Dverbose -DshowSizes -DoutputFile=target/tree.txt diff --git a/src/it/projects/tree-show-sizes-verbose/pom.xml b/src/it/projects/tree-show-sizes-verbose/pom.xml new file mode 100644 index 00000000..f4062a75 --- /dev/null +++ b/src/it/projects/tree-show-sizes-verbose/pom.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ 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. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.maven.plugins.dependency.its</groupId> + <artifactId>tree-show-sizes-verbose</artifactId> + <version>1.0-SNAPSHOT</version> + <description> + dependency:tree with verbose and showSizes shows no size for an omitted node. + </description> + <dependencies> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-root</artifactId> + <version>1.0</version> + </dependency> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-leaf</artifactId> + <version>1.0</version> + </dependency> + </dependencies> +</project> diff --git a/src/it/projects/tree-show-sizes-verbose/verify.groovy b/src/it/projects/tree-show-sizes-verbose/verify.groovy new file mode 100644 index 00000000..91892b8e --- /dev/null +++ b/src/it/projects/tree-show-sizes-verbose/verify.groovy @@ -0,0 +1,39 @@ +/* + * 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. + */ + +import static org.assertj.core.api.Assertions.assertThat + +def jarSize = { String artifactId -> + def jar = new File(localRepositoryPath, "org/apache/maven/its/dependency/${artifactId}/1.0/${artifactId}-1.0.jar") + assertThat(jar).exists() + return jar.length() +} +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( + "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-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()) + +return true diff --git a/src/it/projects/tree-show-sizes/invoker.properties b/src/it/projects/tree-show-sizes/invoker.properties new file mode 100644 index 00000000..836eeb49 --- /dev/null +++ b/src/it/projects/tree-show-sizes/invoker.properties @@ -0,0 +1,20 @@ +# 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. + +invoker.goals.1 = ${project.groupId}:${project.artifactId}:${project.version}:tree -DshowSizes -DoutputFile=target/tree.txt +invoker.goals.2 = ${project.groupId}:${project.artifactId}:${project.version}:tree -DshowSizes=true -DoutputType=json -DoutputFile=target/tree.json +invoker.goals.3 = ${project.groupId}:${project.artifactId}:${project.version}:tree -DshowSizes=true -DoutputType=dot -DoutputFile=target/tree.dot diff --git a/src/it/projects/tree-show-sizes/pom.xml b/src/it/projects/tree-show-sizes/pom.xml new file mode 100644 index 00000000..6c3c2389 --- /dev/null +++ b/src/it/projects/tree-show-sizes/pom.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ~ 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. + --> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.apache.maven.plugins.dependency.its</groupId> + <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. + </description> + <dependencies> + <dependency> + <groupId>org.apache.maven.its.dependency</groupId> + <artifactId>tree-sizes-root</artifactId> + <version>1.0</version> + </dependency> + </dependencies> +</project> diff --git a/src/it/projects/tree-show-sizes/verify.groovy b/src/it/projects/tree-show-sizes/verify.groovy new file mode 100644 index 00000000..5d345617 --- /dev/null +++ b/src/it/projects/tree-show-sizes/verify.groovy @@ -0,0 +1,57 @@ +/* + * 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. + */ + +import groovy.json.JsonSlurper + +import static org.assertj.core.api.Assertions.assertThat + +// the mock repository serves a stub jar for each artifact with a POM; tree-sizes-gone has neither, so its size is unknown +def jarSize = { String artifactId -> + def jar = new File(localRepositoryPath, "org/apache/maven/its/dependency/${artifactId}/1.0/${artifactId}-1.0.jar") + assertThat(jar).exists() + return jar.length() +} +long leaf = jarSize("tree-sizes-leaf") +long root = jarSize("tree-sizes-root") +long total = leaf + root +// 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)") + +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.children[0].size).isEqualTo(leaf) +assertThat(node.children[0].totalSize).isEqualTo(leaf) +assertThat(node.children[1]).doesNotContainKey("size") +assertThat(node.children[1].totalSize).isEqualTo(0) + +// the DOT output ignores the parameter +def dot = new File(basedir, "target/tree.dot").text +assertThat(dot).contains("tree-sizes-root").doesNotContain("KB").doesNotContain("total") + +return true 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 cae0a933..03b6276a 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 @@ -39,6 +39,12 @@ public class DependencyNode { private VerboseInfo verboseInfo; + private boolean sized; + + private Long size; + + private long totalSize; + /** * @param parent the parent node, or <code>null</code> for the root * @param artifact the artifact of this node @@ -82,6 +88,39 @@ 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() { + 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() { + return size; + } + + /** + * @return the size in bytes of the distinct artifacts of this node and its descendants, those of unknown size + * counted as zero + * @since 3.12.0 + */ + public long getTotalSize() { + return totalSize; + } + + void setSizes(Long size, long totalSize) { + this.sized = true; + this.size = size; + this.totalSize = totalSize; + } + /** * @return the label of this node */ 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 new file mode 100644 index 00000000..7ec0953e --- /dev/null +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/DependencySizes.java @@ -0,0 +1,168 @@ +/* + * 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.tree; + +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +import org.apache.maven.artifact.Artifact; + +/** + * 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. + */ +final class DependencySizes { + private static final String[] UNITS = {"B", "KB", "MB", "GB", "TB"}; + + private DependencySizes() {} + + /** + * Collects the distinct artifacts whose size is needed: those of the nodes below the root that are not omitted. + * + * @param root the root of the displayed tree + * @return the artifacts 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); + } + return artifacts; + } + + private static void collect(DependencyNode node, Map<String, Artifact> artifacts) { + if (!isIncluded(node)) { + return; + } + artifacts.putIfAbsent(key(node.getArtifact()), node.getArtifact()); + for (DependencyNode child : node.getChildren()) { + collect(child, artifacts); + } + } + + /** + * Sets the size and the total on every node of the tree that is not omitted. + * + * @param root the root of the displayed tree + * @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); + } + + /** + * @return the distinct artifacts of the subtree with their sizes, those of unknown size left out + */ + 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); + } + } + for (DependencyNode child : node.getChildren()) { + if (isIncluded(child)) { + subtree.putAll(annotate(child, fileSizes, false)); + } + } + + long total = 0; + for (Long size : subtree.values()) { + total += size; + } + node.setSizes(own, total); + + return subtree; + } + + private static boolean isIncluded(DependencyNode node) { + return node.getVerboseInfo() == null || node.getVerboseInfo().isIncluded(); + } + + /** + * @return the identity of an artifact for the purpose of counting it once + */ + static String key(Artifact artifact) { + return artifact.getDependencyConflictId() + ":" + artifact.getVersion(); + } + + /** + * 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. + */ + 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(); + } + + text.append(node.getSize() != null ? format(node.getSize()) : "size unknown"); + if (hasSizedChild) { + text.append(", total ").append(format(node.getTotalSize())); + } + return text.append(')').toString(); + } + + /** + * Formats a size with the units B, KB, MB, GB and TB, where 1 KB is 1024 bytes, rounded to one decimal that is + * left out when it is zero, such as <code>512 B</code>, <code>200 KB</code> or <code>1.5 MB</code>. + * + * @param bytes the size, not negative + * @return the formatted size + */ + static String format(long bytes) { + int unit = 0; + double value = bytes; + while (unit < UNITS.length - 1 && round(value) >= 1024) { + value /= 1024; + unit++; + } + String number = unit == 0 ? String.valueOf(bytes) : String.format(Locale.ROOT, "%.1f", value); + if (number.endsWith(".0")) { + number = number.substring(0, number.length() - 2); + } + return number + " " + UNITS[unit]; + } + + private static double round(double value) { + return Math.round(value * 10) / 10.0; + } +} 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 d39c667c..d25e5dce 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 @@ -132,6 +132,7 @@ 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); appendKeyValue(sb, indent, "groupId", artifact.getGroupId()); appendKeyValue(sb, indent, "artifactId", artifact.getArtifactId()); appendKeyValue(sb, indent, "version", artifact.getVersion()); @@ -177,6 +178,20 @@ public class JsonDependencyNodeVisitor extends AbstractSerializingVisitor implem 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/SerializingDependencyNodeVisitor.java b/src/main/java/org/apache/maven/plugins/dependency/tree/SerializingDependencyNodeVisitor.java index 448e89f9..4853b456 100644 --- a/src/main/java/org/apache/maven/plugins/dependency/tree/SerializingDependencyNodeVisitor.java +++ b/src/main/java/org/apache/maven/plugins/dependency/tree/SerializingDependencyNodeVisitor.java @@ -73,7 +73,7 @@ class SerializingDependencyNodeVisitor implements DependencyNodeVisitor { public boolean visit(DependencyNode node) { indent(node); - writer.println(node.toNodeString()); + writer.println(node.toNodeString() + DependencySizes.describe(node)); depth++; 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 d72d3d3b..7a80397f 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 @@ -26,10 +26,16 @@ import java.io.StringWriter; import java.io.Writer; 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.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; @@ -40,6 +46,7 @@ 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; @@ -47,6 +54,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.resolution.ArtifactResolutionException; +import org.eclipse.aether.resolution.ArtifactResult; /** * Displays the dependency tree for this project. Multiple formats are supported: text (by default), but also @@ -72,6 +81,8 @@ public class TreeMojo extends AbstractMojo { private final DependencyTreeBuilder dependencyTreeBuilder; + private final RepositorySystem repositorySystem; + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") private String outputEncoding; @@ -170,6 +181,24 @@ public class TreeMojo extends AbstractMojo { @Parameter(property = "excludes") 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. + * <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 + * <code>size</code> and <code>totalSize</code> in bytes. The other output types ignore this parameter with a + * warning and download nothing. + * + * @since 3.12.0 + */ + @Parameter(property = "showSizes", defaultValue = "false") + private boolean showSizes; + /** * The computed dependency tree root node of the Maven project. */ @@ -202,6 +231,7 @@ public class TreeMojo extends AbstractMojo { ProjectDependenciesResolver projectDependenciesResolver) { this.project = project; this.session = session; + this.repositorySystem = repositorySystem; this.dependencyTreeBuilder = new DependencyTreeBuilder(repositorySystem, projectDependenciesResolver); } @@ -317,6 +347,9 @@ public class TreeMojo extends AbstractMojo { DependencyNode displayed = theRootNode.filter(null, createExcludesDependencyNodeFilter(), createIncludesDependencyNodeFilter()); if (displayed != null) { + if (showSizes) { + annotateSizes(displayed); + } displayed.accept( dotGraphEnvelope ? getSerializingDependencyNodeVisitor(writer) @@ -326,6 +359,66 @@ public class TreeMojo extends AbstractMojo { return writer.toString(); } + /** + * 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. + */ + 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); + 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(); + if (file != null) { + if (file.isFile()) { + sizes.put(entry.getKey(), file.length()); + } + } else { + toResolve.put(entry.getKey(), RepositoryUtils.toArtifact(entry.getValue())); + } + } + + if (!toResolve.isEmpty()) { + List<String> keys = new ArrayList<>(toResolve.keySet()); + List<ArtifactResult> results; + try { + results = new ResolverUtil(repositorySystem, () -> session) + .resolveArtifacts(toResolve.values(), project.getRemoteProjectRepositories()); + } 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()); + } + } + } + + int unknown = artifacts.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); + } + + private boolean isSizesOutputType() { + return !("dot".equals(outputType) + || "graphml".equals(outputType) + || "tgf".equals(outputType) + || "mermaid".equals(outputType)); + } + /** * Adds the edges of a tree to the DOT graph in the file, so that the trees of the modules of a reactor build end * up in one graph. A file that does not hold a graph yet gets one, named after the root of this tree. diff --git a/src/site/markdown/examples/tree-mojo.md b/src/site/markdown/examples/tree-mojo.md index 73777f70..7c278669 100644 --- a/src/site/markdown/examples/tree-mojo.md +++ b/src/site/markdown/examples/tree-mojo.md @@ -65,6 +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`. - **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 bcb186ff..240ffa7a 100644 --- a/src/site/markdown/usage.md.vm +++ b/src/site/markdown/usage.md.vm @@ -581,6 +581,26 @@ Also, the `outputType` parameter can be used to generate different formats of ou mvn dependency:tree -DoutputFile=/path/to/file.graphml -DoutputType=graphml ``` +The `showSizes` parameter (since 3.12.0) shows how much each dependency weighs. By default `dependency:tree` only collects the dependency graph and downloads no artifacts. With `-DshowSizes` the goal also resolves the artifact of each node, which downloads those missing from the local repository, and shows its file size and, for an artifact with dependencies, the total: + +``` +mvn dependency:tree -DshowSizes +``` + +``` +org.example:app:jar:1.0-SNAPSHOT (total 1.5 MB) +\- org.foo:foo-all:jar:2.0:compile (200 KB, total 1.5 MB) + +- org.foo:foo-core:jar:2.0:compile (1.3 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. +- 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. +- 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 new file mode 100644 index 00000000..4f595542 --- /dev/null +++ b/src/test/java/org/apache/maven/plugins/dependency/tree/DependencySizesTest.java @@ -0,0 +1,186 @@ +/* + * 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.tree; + +import java.io.StringWriter; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DependencySizesTest { + // 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"); + + 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); + } + + @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()); + } + + @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); + + assertEquals(1000 + 100 + 10 + 2000, root.getTotalSize()); + assertNull(root.getSize()); + } + + @Test + void omittedNodeContributesNothingAndGetsNoSizes() { + DependencySizes.annotate(root, sizes); + + assertFalse(omitted.hasSizes()); + assertEquals("", DependencySizes.describe(omitted)); + assertFalse(DependencySizes.artifacts(root).containsKey(DependencySizes.key(omitted.getArtifact()))); + assertEquals(2100, b.getTotalSize()); + } + + @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)); + } + + @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)); + } + + @Test + void nodeWithoutSizesIsUnchanged() { + assertEquals("", DependencySizes.describe(a)); + assertEquals("", DependencySizes.describe(root)); + } + + @Test + void collectsDistinctArtifactsExceptRootAndOmitted() { + Map<String, Artifact> artifacts = DependencySizes.artifacts(root); + + assertEquals(4, artifacts.size()); + assertTrue(artifacts.containsKey(DependencySizes.key(aShared.getArtifact()))); + assertFalse(artifacts.containsKey(DependencySizes.key(root.getArtifact()))); + } + + @Test + void textOutputAppendsSizes() { + DependencySizes.annotate(root, sizes); + StringWriter writer = new StringWriter(); + root.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("+- 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)); + } + + @Test + void formatsUnits() { + assertEquals("0 B", DependencySizes.format(0)); + assertEquals("1023 B", DependencySizes.format(1023)); + assertEquals("1 KB", DependencySizes.format(1024)); + assertEquals("200 KB", DependencySizes.format(200 * 1024)); + assertEquals("1.5 KB", DependencySizes.format(1536)); + assertEquals("1.5 MB", DependencySizes.format(1536 * 1024)); + assertEquals("1 MB", DependencySizes.format(1024 * 1024 - 1)); + assertEquals("2.3 GB", DependencySizes.format(2469606195L)); + assertEquals("2048 TB", DependencySizes.format(2048L * 1024 * 1024 * 1024 * 1024)); + } + + @Test + void jsonHasNumericSizesOnlyWhenComputed() { + StringWriter plain = new StringWriter(); + root.accept(new JsonDependencyNodeVisitor(plain)); + assertFalse(plain.toString().contains("totalSize")); + assertFalse(plain.toString().contains("\"size\"")); + + // a2 has an unknown size: totalSize only + sizes.remove(DependencySizes.key(a2.getArtifact())); + DependencySizes.annotate(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\": 0")); + assertFalse(json.contains("\"size\": 10,")); + assertFalse(json.contains("\"size\": 10\n")); + } + + private static DependencyNode node(DependencyNode parent, String artifactId) { + Artifact artifact = new DefaultArtifact( + "g", artifactId, "1.0", Artifact.SCOPE_COMPILE, "jar", null, new DefaultArtifactHandler("jar")); + return new DependencyNode(parent, artifact, artifactId); + } +}
