Bazel Query Examples¶
This guide demonstrates how to use bazel query and bazel aquery to explore the build graph.
Basic Queries¶
List all targets in the workspace¶
Output:
//go_service:go_service_test
//go_service:server
//py_service:py_service_test
//py_service:server
//tests:test_go_service
//tests:test_py_service
List targets in a specific package¶
Find all test targets¶
Find all Python targets¶
Find all Go targets¶
Dependency Queries¶
Show all dependencies of a target¶
This shows everything the Go server depends on, including: - Source files - Toolchains - External dependencies
Show only direct dependencies¶
The 1 limits the depth to immediate dependencies only.
Find what depends on a target (reverse dependencies)¶
This shows all targets that depend on the Go server.
Show path between two targets¶
Visualization¶
Generate a dependency graph¶
Then convert to image (requires Graphviz):
Generate graph for entire workspace¶
Action Queries (Advanced)¶
aquery shows the actual actions (compile, link, etc.) that Bazel executes.
Show all actions for building a target¶
Show only compilation actions¶
Show linking actions¶
Show actions with inputs and outputs¶
Practical Examples¶
Find all binary targets (runnable services)¶
Output:
Find targets that changed since last commit¶
Check if target exists¶
Find unused dependencies (requires analysis)¶
# This is more complex and requires additional tooling
bazel query "rdeps(//..., //some:target, 1)" --output=label_kind
Filtering and Formatting¶
Output as a list¶
Output as JSON¶
Output with kind (target type)¶
Example output:
go_binary rule //go_service:server
py_binary rule //py_service:server
go_test rule //go_service:go_service_test
py_test rule //py_service:py_service_test
Query Functions Cheatsheet¶
| Function | Description | Example |
|---|---|---|
deps(target) |
All dependencies | deps(//go_service:server) |
rdeps(universe, target) |
Reverse dependencies | rdeps(//..., //py_service:server) |
allpaths(from, to) |
All paths between targets | allpaths(//go_service:server, @rules_go//:go) |
somepath(from, to) |
One path between targets | somepath(//go_service:server, @rules_go//:go) |
kind(pattern, input) |
Filter by target type | kind(test, //...) |
attr(name, pattern, input) |
Filter by attribute | attr(srcs, ".*\.py", //...) |
labels(attr, input) |
Extract label values | labels(srcs, //go_service:server) |
filter(pattern, input) |
Filter labels by regex | filter("test", //...) |
Performance Tips¶
Use --universe_scope for large queries¶
This limits the search space, making queries faster.