TExcelTAD
Home › Cargo in Depth › cargo tree & cargo metadata

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

bash · try it yourself
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 Unpacking
app 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-dedupe to 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:

bash · try it yourself
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 -u
app 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:

bash · try it yourself
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 Unpacking
app 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:

bash · try it yourself
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"])
PY
package: 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-deps skips dependencies (much faster in big workspaces when you only need your own packages).
  • --filter-platform <triple> trims the resolve graph to one platform.

Note: for one quick value, cargo pkgid (the package's full id) and cargo locate-project (the path of the manifest, as JSON) are lighter than cargo metadata.

Test yourself

What does (*) after a crate in cargo tree output mean?

  1. The crate failed to build
  2. Its dependencies were already printed earlier in the tree
  3. It's optional
  4. It's a proc-macro

Which command answers 'which of my dependencies pulls in memchr?'

  1. cargo tree -d memchr
  2. cargo tree -i memchr
  3. cargo metadata memchr
  4. cargo search memchr

A tool needs the list of targets of every workspace package. What should it call?

  1. Parse every Cargo.toml with a TOML library
  2. cargo metadata --format-version 1
  3. cargo tree --prefix none
  4. cargo read-manifest