Skip to content

Commit

Permalink
ModqueryExecutor output logic
Browse files Browse the repository at this point in the history
- `show` implementation added (mostly uses `Query`'s `TargetOutputter` which is now publicly exposed instead of package-private).

- `text`, `json` and `graphviz dot` outputters added

- Unit testing for `ModqueryExecutor`output logic

#15365

PiperOrigin-RevId: 542325901
Change-Id: I155a326465355432fbb4436b28aecc0697c3ffab
  • Loading branch information
andyrinne12 authored and Wyverald committed Jul 12, 2023
1 parent f0bd906 commit 1169a56
Show file tree
Hide file tree
Showing 19 changed files with 1,352 additions and 338 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ package(

filegroup(
name = "srcs",
srcs = glob(["*"]),
srcs = glob(["*"]) + [
"//src/main/java/com/google/devtools/build/lib/bazel/bzlmod/modquery:srcs",
],
visibility = ["//src:__subpackages__"],
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,17 +196,27 @@ public AugmentedModule.Builder addDepReason(String repoName, ResolutionReason re
/** The reason why a final dependency of a module was resolved the way it was. */
public enum ResolutionReason {
/** The dependency is the original dependency defined in the MODULE.bazel file. */
ORIGINAL,
ORIGINAL(""),
/** The dependency was replaced by the Minimal-Version Selection algorithm. */
MINIMAL_VERSION_SELECTION,
MINIMAL_VERSION_SELECTION("MVS"),
/** The dependency was replaced by a {@code single_version_override} rule. */
SINGLE_VERSION_OVERRIDE,
SINGLE_VERSION_OVERRIDE("SVO"),
/** The dependency was replaced by a {@code multiple_version_override} rule. */
MULTIPLE_VERSION_OVERRIDE,
MULTIPLE_VERSION_OVERRIDE("MVO"),
/** The dependency was replaced by one of the {@link NonRegistryOverride} rules. */
ARCHIVE_OVERRIDE,
GIT_OVERRIDE,
LOCAL_PATH_OVERRIDE,
ARCHIVE_OVERRIDE("archive"),
GIT_OVERRIDE("git"),
LOCAL_PATH_OVERRIDE("local");

private final String label;

ResolutionReason(String label) {
this.label = label;
}

public String getLabel() {
return label;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
load("@rules_java//java:defs.bzl", "java_library")

package(
default_applicable_licenses = ["//:license"],
default_visibility = ["//src:__subpackages__"],
)

filegroup(
name = "srcs",
srcs = glob(["*"]),
visibility = ["//src:__subpackages__"],
)

java_library(
name = "modquery",
srcs = glob(["*.java"]),
deps = [
"//src/main/java/com/google/devtools/build/lib/bazel/bzlmod:common",
"//src/main/java/com/google/devtools/build/lib/bazel/bzlmod:inspection",
"//src/main/java/com/google/devtools/build/lib/bazel/bzlmod:repo_rule_value",
"//src/main/java/com/google/devtools/build/lib/packages",
"//src/main/java/com/google/devtools/build/lib/query2/query/output",
"//src/main/java/com/google/devtools/common/options",
"//third_party:auto_value",
"//third_party:gson",
"//third_party:guava",
"//third_party:jsr305",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.bazel.bzlmod.modquery;

import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleInspectorValue.AugmentedModule;
import com.google.devtools.build.lib.bazel.bzlmod.ModuleKey;
import com.google.devtools.build.lib.bazel.bzlmod.Version;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode.IsIndirect;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode.NodeMetadata;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.OutputFormatters.OutputFormatter;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;

/**
* Outputs graph-based results of {@link ModqueryExecutor} in the Graphviz <i>dot</i> format which
* can be further pipelined to create an image graph visualization.
*/
public class GraphvizOutputFormatter extends OutputFormatter {

@Override
public void output() {
StringBuilder str = new StringBuilder();
str.append("digraph mygraph {\n")
.append(" ")
.append("node [ shape=box ]\n")
.append(" ")
.append("edge [ fontsize=8 ]\n");
Set<ModuleKey> seen = new HashSet<>();
Deque<ModuleKey> toVisit = new ArrayDeque<>();
seen.add(ModuleKey.ROOT);
toVisit.add(ModuleKey.ROOT);

while (!toVisit.isEmpty()) {
ModuleKey key = toVisit.pop();
AugmentedModule module = depGraph.get(key);
ResultNode node = result.get(key);
Preconditions.checkNotNull(module);
Preconditions.checkNotNull(node);
String sourceId = toId(key);

if (key.equals(ModuleKey.ROOT)) {
String rootLabel = String.format("root (%s@%s)", module.getName(), module.getVersion());
str.append(String.format(" root [ label=\"%s\" ]\n", rootLabel));
} else if (node.isTarget() || !module.isUsed()) {
String shapeString = node.isTarget() ? "diamond" : "box";
String styleString = module.isUsed() ? "solid" : "dotted";
str.append(
String.format(" %s [ shape=%s style=%s ]\n", toId(key), shapeString, styleString));
}

for (Entry<ModuleKey, NodeMetadata> e : node.getChildrenSortedByKey()) {
ModuleKey childKey = e.getKey();
IsIndirect childIndirect = e.getValue().isIndirect();
String childId = toId(childKey);
if (childIndirect == IsIndirect.FALSE) {
String reasonLabel = getReasonLabel(childKey, key);
str.append(String.format(" %s -> %s [ %s ]\n", sourceId, childId, reasonLabel));
} else {
str.append(String.format(" %s -> %s [ style=dashed ]\n", sourceId, childId));
}
if (seen.add(childKey)) {
toVisit.add(childKey);
}
}
}
str.append("}");
printer.println(str);
printer.flush();
}

private String toId(ModuleKey key) {
if (key.equals(ModuleKey.ROOT)) {
return "root";
}
return String.format(
"\"%s@%s\"",
key.getName(), key.getVersion().equals(Version.EMPTY) ? "_" : key.getVersion());
}

private String getReasonLabel(ModuleKey key, ModuleKey parent) {
if (!options.extra) {
return "";
}
Explanation explanation = getExtraResolutionExplanation(key, parent);
if (explanation == null) {
return "";
}
String label = explanation.getResolutionReason().getLabel();
if (!label.isEmpty()) {
return String.format("label=%s", label);
}
return "";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2022 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.bazel.bzlmod.modquery;

import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleInspectorValue.AugmentedModule;
import com.google.devtools.build.lib.bazel.bzlmod.ModuleKey;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode.IsCycle;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode.IsExpanded;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode.IsIndirect;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.ModqueryExecutor.ResultNode.NodeMetadata;
import com.google.devtools.build.lib.bazel.bzlmod.modquery.OutputFormatters.OutputFormatter;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.Map.Entry;

/** Outputs graph-based results of {@link ModqueryExecutor} in JSON format. */
public class JsonOutputFormatter extends OutputFormatter {
@Override
public void output() {
JsonObject root = printTree(ModuleKey.ROOT, null, IsExpanded.TRUE, IsIndirect.FALSE);
root.addProperty("root", true);
printer.println(new GsonBuilder().setPrettyPrinting().create().toJson(root));
}

public String printKey(ModuleKey key) {
if (key.equals(ModuleKey.ROOT)) {
return "root";
}
return key.toString();
}

JsonObject printTree(ModuleKey key, ModuleKey parent, IsExpanded expanded, IsIndirect indirect) {
ResultNode node = result.get(key);
AugmentedModule module = depGraph.get(key);
JsonObject json = new JsonObject();
json.addProperty("key", printKey(key));
if (!key.getName().equals(module.getName())) {
json.addProperty("name", module.getName());
}
if (!key.getVersion().equals(module.getVersion())) {
json.addProperty("version", module.getVersion().toString());
}

if (indirect == IsIndirect.FALSE && options.extra && parent != null) {
Explanation explanation = getExtraResolutionExplanation(key, parent);
if (explanation != null) {
if (!module.isUsed()) {
json.addProperty("unused", true);
json.addProperty("resolvedVersion", explanation.getChangedVersion().toString());
} else {
json.addProperty("originalVersion", explanation.getChangedVersion().toString());
}
json.addProperty("resolutionReason", explanation.getChangedVersion().toString());
if (explanation.getRequestedByModules() != null) {
JsonArray requestedBy = new JsonArray();
explanation.getRequestedByModules().forEach(k -> requestedBy.add(printKey(k)));
json.add("resolvedRequestedBy", requestedBy);
}
}
}

if (expanded == IsExpanded.FALSE) {
json.addProperty("unexpanded", true);
return json;
}

JsonArray deps = new JsonArray();
JsonArray indirectDeps = new JsonArray();
JsonArray cycles = new JsonArray();
for (Entry<ModuleKey, NodeMetadata> e : node.getChildrenSortedByEdgeType()) {
ModuleKey childKey = e.getKey();
IsExpanded childExpanded = e.getValue().isExpanded();
IsIndirect childIndirect = e.getValue().isIndirect();
IsCycle childCycles = e.getValue().isCycle();
if (childCycles == IsCycle.TRUE) {
cycles.add(printTree(childKey, key, IsExpanded.FALSE, IsIndirect.FALSE));
} else if (childIndirect == IsIndirect.TRUE) {
indirectDeps.add(printTree(childKey, key, childExpanded, IsIndirect.TRUE));
} else {
deps.add(printTree(childKey, key, childExpanded, IsIndirect.FALSE));
}
}
json.add("dependencies", deps);
json.add("indirectDependencies", indirectDeps);
json.add("cycles", cycles);
return json;
}
}
Loading

0 comments on commit 1169a56

Please sign in to comment.