Sub topic 10
Inspecting the dependency tree with cargo tree
Adding one crate often pulls in many others. cargo tree prints the full graph Cargo resolved for your project. It shows which crates you depend on directly, which ones arrive indirectly, which versions were chosen, and which features are on.
This chapter assumes you can run cargo add, you know what Cargo.toml and Cargo.lock are, and you understand SemVer requirements and crate features at the level of the earlier chapters. The examples use the json_demo project from the start of this tutorial.
What cargo tree reads
cargo tree is a built-in Cargo subcommand. It needs no installation. It reads Cargo.toml and Cargo.lock, resolving the graph if no lockfile exists yet. It does not compile anything, and it does not need to be told which crates are "yours".
Run it in the project root:
cargo treeThe output for json_demo looks like the following. Version numbers and the exact set of crates depend on when your Cargo.lock was generated, so treat this as the shape of the output, not literal text.
json_demo v0.1.0 (/home/you/json_demo)
├── serde v1.0.x
│ └── serde_derive v1.0.x (proc-macro)
│ ├── proc-macro2 v1.0.x
│ │ └── unicode-ident v1.0.x
│ ├── quote v1.0.x
│ │ └── proc-macro2 v1.0.x (*)
│ └── syn v2.0.x
│ ├── proc-macro2 v1.0.x (*)
│ ├── quote v1.0.x (*)
│ └── unicode-ident v1.0.x
└── serde_json v1.0.x
├── itoa v1.0.x
├── memchr v2.x.x
└── ryu v1.0.xThe root is your package. Its direct children are the entries in [dependencies]. Each deeper level is a dependency of the crate above it.
Reading the output
Three markers matter:
| Marker | Meaning |
|---|---|
| `(*)` | This crate's subtree was already printed earlier, so Cargo omits it here to keep the output short. |
| `(proc-macro)` | The crate is a procedural macro. It runs at compile time inside the compiler, not in your final program. |
| `(/path)` or `(https://...)` | The crate comes from a path or git source instead of crates.io. |
A crate appearing in several places is not a problem. proc-macro2 appears under both quote and syn, but Cargo builds it once. The graph is a directed acyclic graph, and the tree view is only a way to print it. Each (*) is a second edge pointing to a node you have already seen.
If you want the printed tree without the (*) shortcut, pass --no-dedupe. The output grows quickly, so use it mainly with a small --depth.
Limiting what you see
Large projects produce trees with hundreds of lines. Three options keep the output manageable.
cargo tree --depth 1
cargo tree -p serde_json
cargo tree --prefix none--depth Nstops printing below level N.--depth 1lists only your direct dependencies, which is a quick way to check whatcargo addactually wrote.-p NAME(--package) roots the tree at one package from the graph. This works for a dependency and for a workspace member.--prefix noneremoves the drawing characters and prints a flat list.--prefix depthprints each line with its depth number. Both are easier to pipe intosort,uniqorgrep.
In a workspace, cargo tree shows the package in the current directory. Add --workspace to show every member, or -p member_name to pick one.
Finding why a crate is there: inverted trees
The most useful question cargo tree answers is "why is this in my build?". The -i flag (--invert) flips the tree. It takes a package and prints everything that depends on it, up to the root.
cargo tree -i serdeserde v1.0.x
└── json_demo v0.1.0 (/home/you/json_demo)Here the answer is short, because json_demo asks for serde directly. For a transitive dependency the chain is longer:
cargo tree -i proc-macro2proc-macro2 v1.0.x
├── quote v1.0.x
│ └── serde_derive v1.0.x (proc-macro)
│ └── serde v1.0.x
│ └── json_demo v0.1.0 (/home/you/json_demo)
└── syn v2.0.x
├── serde_derive v1.0.x (proc-macro) (*)
└── ...Read it from the top down as "proc-macro2 is needed by quote and syn, which are needed by serde_derive, which is needed by serde, which you asked for". To remove proc-macro2 from your build, you would have to remove or change serde's derive feature. Removing quote alone would do nothing.
When a crate name matches several versions in the graph, give a version with the package ID form name@version, for example cargo tree -i [email protected].
Finding duplicate versions
Cargo allows more than one version of a crate in the same build when the versions are incompatible under SemVer. For example, rand 0.7 and rand 0.8 can coexist, because 0.7 and 0.8 are different compatibility lines. This works, but it increases compile time and binary size. It can also cause type mismatches if two crates pass each other a type from different versions.
cargo tree -d (--duplicates) lists only the crates that appear at more than one version, inverted so you can see who pulls in each:
cargo tree -drand v0.7.3
└── old_dep v0.4.1
└── json_demo v0.1.0 (/home/you/json_demo)
rand v0.8.5
└── json_demo v0.1.0 (/home/you/json_demo)This output is illustrative. It shows old_dep holding back the older rand. Possible fixes are to update old_dep, to look for an alternative crate, or to accept the duplicate when it is harmless. Running cargo update -p old_dep first costs little and sometimes resolves it.
Not every duplicate is a bug. Two versions of a small, internal crate such as syn 1.x and syn 2.x are common during ecosystem transitions. Duplicates matter most when the type crosses a crate boundary, or when the crate is large.
Choosing which edges to show
Cargo has several kinds of dependency edges: normal, build, dev and target-specific. By default cargo tree shows normal, build and dev edges for the current package, and it labels each group.
The -e flag (--edges) selects edge types:
cargo tree -e normal
cargo tree -e no-dev
cargo tree -e build
cargo tree -e features| Value | Shows |
|---|---|
| `normal` | Only `[dependencies]` edges. |
| `build` | Only `[build-dependencies]` edges. |
| `dev` | Only `[dev-dependencies]` edges. |
| `no-dev` | Normal and build edges, without dev. |
| `no-build` | Normal and dev edges, without build. |
| `no-proc-macro` | Everything except proc-macro dependencies. |
| `features` | Feature edges, covered below. |
| `all` | Every kind of edge. |
-e normal is the right choice when you want to know what ends up in your shipped binary. Dev dependencies such as pretty_assertions and build dependencies such as cc are not part of that. You can combine values with commas, for example -e normal,build.
Target-specific dependencies, such as those under [target.'cfg(windows)'.dependencies], appear only if they apply to the platform being inspected. By default that is your host platform. Use --target x86_64-pc-windows-msvc to see another platform, or --target all to see every platform.
Seeing features in the tree
Chapter material on features told you that features can turn on optional dependencies. cargo tree -e features makes those decisions visible. Feature names appear as nodes under their crate:
cargo tree -e featuresjson_demo v0.1.0 (/home/you/json_demo)
├── serde feature "default"
│ ├── serde v1.0.x
│ │ └── serde_derive feature "default"
│ │ └── serde_derive v1.0.x (proc-macro)
│ └── serde feature "std"
│ └── serde v1.0.x (*)
├── serde feature "derive"
│ ├── serde v1.0.x (*)
│ └── serde feature "serde_derive"
│ └── serde v1.0.x (*)
└── serde_json feature "default"
├── serde_json v1.0.x
└── serde_json feature "std"
└── ...The exact names change between crate versions. The pattern to look for is a line like serde feature "derive" directly under json_demo. That is the feature you asked for in Cargo.toml. Lines nested below it are the features and crates it enabled in turn.
To find out why one feature is on, combine -e features with -i:
cargo tree -e features -i serdeThis prints the features of serde that are active and which crate requested each one. Cargo unifies features across the whole graph. If any crate in your tree turns on a feature, it is on for everyone. A dependency's feature can therefore be on even though you never asked for it. This is the usual reason a default-features = false setting seems to have no effect. A different crate in the tree enabled the defaults. The inverted feature tree names that crate.
You can also ask what the tree looks like with other features of your own package: cargo tree -F feature_name enables a feature of the package, and --all-features or --no-default-features change the whole set.
Custom formats
The -f flag (--format) controls how each node prints. The default is {p}, which prints the package name, version and source. Other placeholders include {l} for the license and {r} for the repository URL, and {f} for the enabled features.
cargo tree --prefix none -f "{p} {l}"
cargo tree --prefix none -f "{p} [{f}]"The first command is a quick license audit. It lists every crate with its license string. The second shows which features of each crate are active. Combined with --prefix none, you can pipe either one into sort -u or grep.
Putting it to use
These are common questions and the command that answers each.
- What did
cargo addjust write?cargo tree --depth 1. - Why is this crate in my build?
cargo tree -i crate_name. - Do I have duplicate versions?
cargo tree -d. - What will ship in my release binary?
cargo tree -e normal. - Who turned this feature on?
cargo tree -e features -i crate_name. - What are my dependencies' licenses?
cargo tree --prefix none -f "{p} {l}".
Common mistakes
- Reading
(*)as an error. It only means the subtree was shown earlier. - Using
cargo tree -iwith a name that has several versions. Cargo will complain about an ambiguous spec. Usename@version. - Expecting dev dependencies in release builds. Use
-e normalor-e no-devto see the real set. - Assuming a duplicate is always harmful. Check whether the duplicated types cross a crate boundary before spending time on it.
- Blaming your own
Cargo.tomlfor an enabled feature. Feature unification means another crate may be responsible. Use-e features -i.
Exercise
In jsondemo you run cargo tree -i syn and see that syn is reached only through `serdederive. You then run cargo tree -e normal and still see syn. A teammate suggests removing serde_derive from Cargo.toml to drop syn` from the build. Why will that not work, and what would you change instead?
Show answer
serde_derive is not listed in jsondemo's Cargo.toml. It comes in through serde because the derive feature is enabled, so there is nothing named `serdederive to remove. To drop syn, you would stop using the derive feature, for example by removing features = ["derive"] from the serde entry. You would then implement Serialize and Deserialize by hand. You can confirm the effect with cargo tree -i syn`, which should report that the package ID is not found in the graph.
Exercise
Which command lists only the crates that appear at more than one version, and which flag would you add to see only what ships in a release binary?
Show answer
cargo tree -d (or --duplicates) lists duplicated crates. Adding -e normal restricts the edges to normal [dependencies] entries, which leaves out dev and build dependencies, so you get cargo tree -d -e normal.