cargo tree & cargo metadata
Two commands answer almost every "why is this in my build?" question. cargo tree is for humans: it draws the resolved dependency graph. cargo metadata is for programs: it prints the same graph, plus every target and feature, as JSON. Both read Cargo.lock (creating it if needed) and never compile anything.
Reading cargo tree
cargo new app --vcs none -q
cd app
cargo add regex -q
cargo add anyhow -q
cargo add --dev serde_json -q
cargo add --build cc -q
cargo tree 2>&1 | grep -v Unpackingapp v0.1.0 (/home/learner/app)
├── anyhow v1.0.104
└── regex v1.13.1
├── aho-corasick v1.1.5
│ └── memchr v2.8.3
├── memchr v2.8.3
├── regex-automata v0.4.18
│ ├── aho-corasick v1.1.5 (*)
│ ├── memchr v2.8.3
│ └── regex-syntax v0.8.11
└── regex-syntax v0.8.11
[build-dependencies]
└── cc v1.10.0
├── find-msvc-tools v0.1.15
└── shlex v2.0.1
[dev-dependencies]
└── serde_json v1.0.154
├── itoa v1.0.18
├── memchr v2.8.3
├── serde_core v1.0.229
└── zmij v1.0.23
- Normal, build and dev dependencies get their own sections.
(*)means "already shown above": the subtree is not repeated. Pass--no-dedupeto repeat it anyway.(proc-macro)marks crates that run inside the compiler.
The flags you'll actually use
| Flag | Answers |
|---|---|
-i <spec> / --invert |
Who depends on this crate? |
-d / --duplicates |
Which crates exist in several versions? (lesson) |
--depth N |
Only the top N levels (--depth 1 = direct dependencies) |
-e normal / -e no-dev / -e build |
Only some edge kinds |
-e features |
Which features are on, and who turned them on? (lesson) |
--target <triple> / --target all |
The graph for another platform (default: the host) |
-p <pkg> |
One workspace member |
--prefix none, -f '{p} {l}' |
Machine-friendly output: no tree lines, custom format ({p} package, {l} license, {r} repository, {f} features) |
A few of them on the same project:
cargo new app --vcs none -q
cd app
cargo add regex anyhow -q
cargo add --dev serde_json -q
cargo fetch -q
cargo tree -q --depth 1 -e normal 2>&1 | grep -v Unpacking
echo "--- who pulls in memchr?"
cargo tree -i memchr
echo "--- licenses of everything that ships in the binary"
cargo tree -e normal --prefix none --no-dedupe -f '{p} {l}' | sort -uapp v0.1.0 (/home/learner/app)
├── anyhow v1.0.104
└── regex v1.13.1
--- who pulls in memchr?
memchr v2.8.3
├── aho-corasick v1.1.5
│ ├── regex v1.13.1
│ │ └── app v0.1.0 (/home/learner/app)
│ └── regex-automata v0.4.18
│ └── regex v1.13.1 (*)
├── regex v1.13.1 (*)
├── regex-automata v0.4.18 (*)
└── serde_json v1.0.154
[dev-dependencies]
└── app v0.1.0 (/home/learner/app)
--- licenses of everything that ships in the binary
aho-corasick v1.1.5 Unlicense OR MIT
anyhow v1.0.104 MIT OR Apache-2.0
app v0.1.0 (/home/learner/app)
memchr v2.8.3 Unlicense OR MIT
regex v1.13.1 MIT OR Apache-2.0
regex-automata v0.4.18 MIT OR Apache-2.0
regex-syntax v0.8.11 MIT OR Apache-2.0
The last command is a two-second license audit. (cargo-deny does the same job properly, with an allow-list.)
Platform-specific dependencies
cargo tree shows the graph for the host platform by default, so Windows-only dependencies are hidden on Linux. Ask for another target, or for all of them:
cargo new app --vcs none -q
cd app
cargo add anyhow -q
cargo add --target 'cfg(windows)' itoa -q 2>&1
cargo tree --depth 1 2>&1 | grep -v Unpacking
echo "--- the same project, all targets"
cargo tree --depth 1 --target all 2>&1 | grep -v Unpackingapp v0.1.0 (/home/learner/app)
└── anyhow v1.0.104
--- the same project, all targets
app v0.1.0 (/home/learner/app)
├── anyhow v1.0.104
└── itoa v1.0.18
cargo metadata: the graph as JSON
Scripts, IDEs (rust-analyzer) and tools like cargo-deny don't parse Cargo.toml themselves; they call cargo metadata. The output has packages (every package with its targets, features and dependency requirements), resolve (the locked graph) and workspace_members. Here a few lines of Python list the targets of a package and its resolved dependencies:
cargo new --lib stats --vcs none -q
cd stats
mkdir -p examples src/bin
echo 'fn main() {}' > examples/demo.rs
echo 'fn main() {}' > src/bin/stats-cli.rs
cargo add anyhow -q
cargo fetch -q
cargo metadata --format-version 1 > meta.json
python3 - <<'PY'
import json
m = json.load(open("meta.json"))
me = next(p for p in m["packages"] if p["id"] in m["workspace_members"])
print("package:", me["name"], me["version"])
for t in sorted(me["targets"], key=lambda t: t["name"]):
print(f" target {t['name']:10} kinds={t['kind']} src={t['src_path'].split('/stats/')[1]}")
print("resolved:", sorted(f"{p['name']} {p['version']}" for p in m["packages"] if p is not me))
print("target dir:", m["target_directory"])
PYpackage: stats 0.1.0
target demo kinds=['example'] src=examples/demo.rs
target stats kinds=['lib'] src=src/lib.rs
target stats-cli kinds=['bin'] src=src/bin/stats-cli.rs
resolved: ['anyhow 1.0.104']
target dir: /home/learner/stats/target
- Always pass
--format-version 1; it's the only format, and Cargo warns if you leave it out. --no-depsskips dependencies (much faster in big workspaces when you only need your own packages).--filter-platform <triple>trims theresolvegraph to one platform.
Note: for one quick value,
cargo pkgid(the package's full id) andcargo locate-project(the path of the manifest, as JSON) are lighter thancargo metadata.
Test yourself
What does (*) after a crate in cargo tree output mean?
- The crate failed to build
- Its dependencies were already printed earlier in the tree
- It's optional
- It's a proc-macro
Which command answers 'which of my dependencies pulls in memchr?'
- cargo tree -d memchr
- cargo tree -i memchr
- cargo metadata memchr
- cargo search memchr
A tool needs the list of targets of every workspace package. What should it call?
- Parse every Cargo.toml with a TOML library
cargo metadata --format-version 1cargo tree --prefix nonecargo read-manifest