TExcelTAD

bazel query

In a repository with 50,000 targets, you can't answer "what depends on this library?" by grepping BUILD files. bazel query answers questions about the target graph after the loading phase: it reads BUILD files, but doesn't analyze or build anything, so it's fast and safe to run anywhere.

The query language

A query is an expression over sets of targets. Target patterns (//app/...) are sets; functions combine them:

Expression Result
deps(X) / deps(X, 1) X and everything it depends on (transitively / one level)
rdeps(U, X) / rdeps(U, X, 1) everything in universe U that depends on X
allrdeps(X) reverse dependencies in everything loaded so far
somepath(A, B) / allpaths(A, B) one path / all paths from A to B in the graph
kind("cc_.*", S) the targets in S whose rule kind matches a regex ("source file", "generated file" work too)
attr(name, regex, S) targets in S whose attribute matches, e.g. attr(tags, "manual", //...)
filter(regex, S) targets in S whose label matches
tests(S) the test targets in S (expands test_suites)
labels(attr, S) the labels in attribute attr of the targets in S
buildfiles(S), rbuildfiles(file) the BUILD/.bzl files that define S / packages affected by a file
S1 + S2, S1 - S2, S1 ^ S2 union, difference, intersection (union, except, intersect work too)
let v = E in … name a subexpression

Output formats: --output=label (default), label_kind, build (the target as it would look in a BUILD file, after macro expansion), graph (Graphviz text), package, location, xml, proto, streamed_jsonproto.

A graph to query

All the commands in this lesson run on the same small repository:

text
//app:server ──► //lib/http ──► //lib/strings
     │                          ▲
     └──► //lib/log ────────────┘
//tools:lint ──► //lib/strings
bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p app lib/http lib/log lib/strings tools
lib() { printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "%s", srcs = ["%s.cc"], hdrs = ["%s.h"], deps = [%s], visibility = ["//visibility:public"])\n' "$2" "$2" "$2" "$3" > $1/BUILD.bazel; touch $1/$2.cc $1/$2.h; }
lib lib/strings strings ''
lib lib/http http '"//lib/strings"'
lib lib/log log '"//lib/strings"'
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "server", srcs = ["main.cc"], deps = ["//lib/http", "//lib/log"])\n' > app/BUILD.bazel
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "lint", srcs = ["lint.cc"], deps = ["//lib/strings"], tags = ["tool"])\n' > tools/BUILD.bazel
touch app/main.cc tools/lint.cc
q() { echo "== $*"; bazel query "$@" 2>/dev/null; }
q 'deps(//app:server, 1)'
q 'kind(rule, deps(//app:server)) intersect //...'
q 'rdeps(//..., //lib/strings)'
q 'rdeps(//..., //lib/strings, 1) - //lib/strings'
q 'somepath(//app:server, //lib/strings:strings.h)'
q 'allpaths(//app:server, //lib/strings)'
q 'attr(tags, "tool", //...)'
q --output=label_kind 'filter("^//", kind("source file", deps(//app:server)))'
q --output=package 'deps(//app:server) intersect //...'
== deps(//app:server, 1)
//app:main.cc
//app:server
//lib/http:http
//lib/log:log
@bazel_tools//tools/cpp:cc_runtimes_toolchain_type
@bazel_tools//tools/cpp:link_extra_lib
@bazel_tools//tools/cpp:malloc
@bazel_tools//tools/cpp:toolchain_type
@bazel_tools//tools/def_parser:def_parser
@rules_cc//:link_extra_lib
@rules_cc//cc/private/rules_impl/wrappers:cc_binary_impl_wrapper
== kind(rule, deps(//app:server)) intersect //...
//app:server
//lib/http:http
//lib/log:log
//lib/strings:strings
== rdeps(//..., //lib/strings)
//app:server
//lib/http:http
//lib/log:log
//lib/strings:strings
//tools:lint
== rdeps(//..., //lib/strings, 1) - //lib/strings
//lib/http:http
//lib/log:log
//tools:lint
== somepath(//app:server, //lib/strings:strings.h)
//app:server
//lib/http:http
//lib/strings:strings
//lib/strings:strings.h
== allpaths(//app:server, //lib/strings)
//app:server
//lib/http:http
//lib/log:log
//lib/strings:strings
== attr(tags, "tool", //...)
//tools:lint
== --output=label_kind filter("^//", kind("source file", deps(//app:server)))
source file //app:main.cc
source file //lib/http:http.cc
source file //lib/http:http.h
source file //lib/log:log.cc
source file //lib/log:log.h
source file //lib/strings:strings.cc
source file //lib/strings:strings.h
== --output=package deps(//app:server) intersect //...
app
lib/http
lib/log
lib/strings

Reading the answers:

  • deps(X) includes files and rule-internal dependencies (the C++ toolchain, @rules_cc helpers): that's why the second query intersects with //... and keeps only rules. deps(X, 1) shows the direct dependencies, including the implicit @rules_cc//:link_extra_lib every cc_binary gets.
  • rdeps(//..., X) is the question you ask before changing a library: "who is affected?". The universe (//...) matters: Bazel only searches the targets you give it.
  • somepath explains why something is in your build, a very common question when a binary unexpectedly links a huge library. allpaths shows every route.
  • attr finds targets by any attribute, here a tag.

Graph output and scripting

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p app lib/http lib/strings
printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "strings", hdrs = ["strings.h"], visibility = ["//visibility:public"])\n' > lib/strings/BUILD.bazel
printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "http", hdrs = ["http.h"], deps = ["//lib/strings"], visibility = ["//visibility:public"])\n' > lib/http/BUILD.bazel
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "server", srcs = ["main.cc"], deps = ["//lib/http", "//lib/strings"])\n' > app/BUILD.bazel
touch lib/strings/strings.h lib/http/http.h app/main.cc
bazel query --noimplicit_deps 'kind(rule, deps(//app:server)) intersect //...' --output=graph 2>/dev/null
echo "== the target after macro expansion"
bazel query --output=build //lib/http 2>/dev/null | grep -v -E '^#|generator_'
echo "== which packages would a change to strings.h affect?"
bazel query 'rdeps(//..., //lib/strings:strings.h)' --output=package 2>/dev/null
digraph mygraph {
  node [shape=box];
  "//app:server"
  "//app:server" -> "//lib/http:http"
  "//app:server" -> "//lib/strings:strings"
  "//lib/http:http"
  "//lib/http:http" -> "//lib/strings:strings"
  "//lib/strings:strings"
}
== the target after macro expansion
cc_library(
  name = "http",
  visibility = ["//visibility:public"],
  hdrs = ["//lib/http:http.h"],
  deps = ["//lib/strings:strings"],
)

== which packages would a change to strings.h affect?
app
lib/http
lib/strings

--output=graph prints a digraph you can render with Graphviz; --noimplicit_deps drops the toolchain edges. --output=build is the best way to see what a macro really generated (the generator_* attributes, filtered out here, record which macro created the target). And --output=package turns a target list into the list of packages, the input a CI script needs for "which teams own the affected code".

query vs cquery vs aquery

Command Works on Knows about select() and flags? Typical question
bazel query the target graph after loading no: follows all branches of every select() "what could depend on X?", "why is X in the graph?"
bazel cquery the configured target graph after analysis yes: follows only the branch the current flags select "what is actually built for --platforms=…?"
bazel aquery the action graph yes "what exact command line compiles this file?"

Because query follows every possible edge, it also loads every implicit dependency of every rule, such as the coverage tools attached to each test rule and the Java tools behind py_binary's internals. In this course image those tools aren't in the offline repository cache, so a plain query whose transitive closure includes a test or Python rule fails with a download error. On a normal machine Bazel would simply download them. That's why the sessions above use C++ targets only, and why the polyglot lesson used cquery, which only loads what the current configuration needs.

Test yourself

Which query lists every target in the workspace that depends on //lib/strings?

  1. deps(//lib/strings)
  2. rdeps(//..., //lib/strings)
  3. somepath(//..., //lib/strings)
  4. kind(rdeps, //lib/strings)

Why might bazel query 'deps(//app)' list targets that a build of //app never uses?

  1. It is buggy
  2. query ignores configuration and follows every branch of every select()
  3. It includes test targets
  4. It queries the remote cache

Which output format shows a target the way a macro actually expanded it?

  1. --output=label
  2. --output=build
  3. --output=package
  4. --output=graph