Bazel query how-to

This is a quick tutorial to get you started using Bazel's query language to
trace dependencies in your code.

For a language details and --output flag details, please see the reference
manuals, Bazel query reference and Bazel cquery reference.
You can get help by typing bazel help query or bazel help cquery on the command line.

To execute a query while ignoring errors such as missing targets, use the
--keep_going flag.

Finding the Dependencies of a Rule

To see the dependencies of //foo, use the
deps function in bazel query:

$ bazel query "deps(//foo)"
//foo:foo
//foo:foo-dep
...

This is the set of all targets required to build //foo.

Tracing the Dependency Chain between Two Packages

The library //third_party/zlib:zlibonly isn't in the BUILD file for
//foo, but it is an indirect dependency. How can
we trace this dependency path? There are two useful functions here:
allpaths and somepath

Aside: implicit dependencies

The BUILD file for //foo never references
//translations/tools:aggregator. So, where's the direct dependency?

Certain rules include implicit dependencies on additional libraries or tools.
For example, to build a genproto rule, you need first to build the Protocol
Compiler, so every genproto rule carries an implicit dependency on the
protocol compiler. These dependencies are not mentioned in the build file,
but added in by the build tool. The full set of implicit dependencies is
currently undocumented. Using --noimplicit_deps allows you to filter out
these deps from your query results.

Reverse Dependencies

You might want to know the set of targets that depends on some target. e.g.,
if you're going to change some code, you might want to know what other code
you're about to break. You can use rdeps(u, x) to find the reverse
dependencies of the targets in x within the transitive closure of u.

Bazel's Sky Query
supports the allrdeps function which allows you to query rdeps in the entire
universe of the build.

What C++ libraries do the foo tests depend on that the //foo production binary does not depend on?

Why does this dependency exist ...

Why does bar depend on groups2?

bazel query 'somepath(bar/...,groups2/...:*)'

Once you have the results of this query, you will often find that a single
target stands out as being an unexpected or egregious and undesirable
dependency of bar. The query can then be further refined to:

Show me a path from docker/updater:updater_systest (a py_test) to some cc_library that it depends upon:

How do I break a dependency ...

What dependency paths do I have to break to make bar no longer depend on X?

Misc ...

How many sequential steps are there in the //foo-tests build?

Unfortunately, the query language can't currently give you the longest path
from x to y, but it can find the (or rather a) most distant node from the
starting point, or show you the lengths of the longest path from x to every
y that it depends on. Use maxrank: