Sub topic 12
Git, path and renamed dependencies
Most dependencies come from crates.io, but Cargo can also read a crate from a directory on disk or from a Git repository. It can also import a crate under a different name. This chapter covers all three. It builds on the [dependencies] table, version requirements and Cargo.lock from earlier chapters.
You should already know how to run cargo add, read an entry such as serde = { version = "1" }, and explain what Cargo.lock records.
Where a dependency can come from
Each entry in [dependencies] names a package and tells Cargo where to find it. The keys you give decide the source.
| Keys in the entry | Source | Pinned by |
|---|---|---|
| `version` only | crates.io | version requirement, then `Cargo.lock` |
| `path` | a directory on your machine | nothing, the files are read as they are |
| `git` | a Git repository | commit hash in `Cargo.lock` |
| `package` | any of the above, imported under another name | same as the underlying source |
Path dependencies
A path dependency points at a crate in another directory. This is how you develop two crates side by side without publishing either one. The path is relative to the Cargo.toml that contains it.
Create a library and an application next to each other:
mkdir demo && cd demo
cargo new --lib greeter
cargo new app
cd app
cargo add --path ../greetercargo add --path writes this line into app/Cargo.toml:
[dependencies]
greeter = { path = "../greeter" }Put a public function in greeter/src/lib.rs:
pub fn greet(name: &str) -> String {
format!("Hello, {name}!")
}Then call it from app/src/main.rs:
use greeter::greet;
fn main() {
println!("{}", greet("Ferris"));
}Running cargo run inside app prints Hello, Ferris!. If you edit greeter and run again, Cargo rebuilds it. A path dependency has no version to resolve and no download. The dependencies of greeter still go into the same Cargo.lock as everything else.
Git dependencies
A Git dependency points at a repository URL. It is useful when a fix is merged upstream but not yet released, or when you depend on a private repository.
cargo add my_fork --git https://github.com/example/my_forkWithout further keys, Cargo follows the repository's default branch. You can narrow that down with one of three keys:
[dependencies]
# Follow a branch
my_fork = { git = "https://github.com/example/my_fork", branch = "main" }
# Use a release tag
my_tool = { git = "https://github.com/example/my_tool", tag = "v0.4.1" }
# Use one exact commit
my_lib = { git = "https://github.com/example/my_lib", rev = "9f3c2a1" }cargo add accepts --branch, --tag and --rev for the same purpose. Use only one of the three keys per dependency.
What Cargo.lock records
For a Git dependency, Cargo.lock stores the full commit hash that Cargo checked out:
[[package]]
name = "my_fork"
version = "0.1.0"
source = "git+https://github.com/example/my_fork?branch=main#3f2a9c0d41b7e85a6c1d0f92b4e7a8135c6d9e20"This is the reproducibility mechanism for Git sources. A branch moves, but the lock file keeps building the same commit until you ask for a change. To move forward, run:
cargo update -p my_forkThat fetches the newest commit on the branch and rewrites the hash. A tag or rev does not move, so there is nothing to update.
Details that cause surprises
- The repository can hold several crates, for example a workspace. Cargo searches it for a package whose name matches the key you wrote.
- Cargo caches clones under
CARGO_HOME(usually~/.cargo/git). A clean machine needs network access to the repository on the first build. - For private repositories, Cargo uses your Git credentials. If your credentials come from an SSH agent or a credential helper that Cargo's built-in Git client does not handle, set
net.git-fetch-with-cli = truein.cargo/config.tomlso Cargo calls thegitcommand instead. - Prefer
tagorrevoverbranchin anything you ship. A branch makes the build depend on whoever last rancargo update.
Combining a source with a version
An entry can have both a local source and a version:
[dependencies]
util = { path = "../util", version = "0.3" }
my_fork = { git = "https://github.com/example/my_fork", version = "0.2" }During local development Cargo uses the path or Git source. When you publish the package, Cargo drops the path or git key and keeps the version, so users get the crate from crates.io.
Renamed dependencies
The package key separates two names: the key on the left is the name you use in your code, and package is the real name of the crate.
[dependencies]
rand = "0.8"
rand07 = { package = "rand", version = "0.7" }This is the standard way to use two incompatible versions of the same crate. Under SemVer, 0.7 and 0.8 are different compatible ranges, so Cargo builds both. Without the rename, the two entries would collide on the key rand.
use rand::Rng as _;
use rand07::Rng as _;
fn main() {
let new_roll: u32 = rand::thread_rng().gen_range(1..7);
let old_roll: u32 = rand07::thread_rng().gen_range(1, 7);
println!("rand 0.8 rolled {new_roll}, rand 0.7 rolled {old_roll}");
}The two gen_range calls differ because the API changed between versions. The as _ imports bring each trait's methods into scope without giving the traits names that clash.
cargo add can write the rename for you:
cargo add [email protected] --rename rand07You can rename path and Git dependencies too. Going back to the earlier example, this entry imports greeter as hello:
[dependencies]
hello = { package = "greeter", path = "../greeter" }Your code then says use hello::greet;. The package key is the real name. If you are unsure which name to use in code, use the key on the left of the entry.
Hyphens and underscores
Crate names may contain hyphens, as in serde-json-style names, but Rust identifiers cannot. In code, Cargo maps each hyphen in the dependency key to an underscore. A dependency my-crate = "1" is imported as my_crate. Renaming gives you a way out if the mapped name is awkward.
Overriding a crate across the whole tree
Sometimes you need to replace a dependency that another crate pulls in, not one you declared. The [patch] table in the top-level Cargo.toml does this:
[dependencies]
serde = "1"
[patch.crates-io]
serde = { git = "https://github.com/example/serde-fix", branch = "fix-bug" }Everywhere in the dependency graph that asks for serde from crates.io, Cargo now uses the patched source. Remember that [patch] is read only in the top-level package of a build, so a library cannot force a patch on its users. It is also a temporary measure. Remove the patch once the fix is released.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `failed to read ../greeter/Cargo.toml` | The path is wrong or relative to the wrong file | Count `..` from the `Cargo.toml` that holds the entry |
| `unresolved import` for a renamed crate | You used the `package` name in code | Use the key on the left, such as `rand07` |
| `cargo publish` rejects a dependency | A path or Git entry has no `version` | Add `version = "..."` |
| Build changes with no edit to `Cargo.toml` | A `branch` dependency was updated by `cargo update` | Switch to `rev` or `tag` |
| `failed to authenticate` on a private repository | Cargo's Git client cannot use your credentials | Set `net.git-fetch-with-cli = true` |
Exercise
A library crate depends on util = { path = "../util" } and you run cargo publish. What happens, and what is the smallest change that fixes it?
Show answer
The publish fails because crates.io requires every dependency to come from the registry, and this entry has no version. Change it to util = { path = "../util", version = "0.3" }, using a version of util that is already published. Cargo keeps using the path locally and uses the version on crates.io.
Exercise
Your Cargo.toml has rand = "0.8" and you need rand 0.7 in the same crate as well. Write the second entry and show how you call thread_rng from it.
Show answer
Add rand07 = { package = "rand", version = "0.7" } under [dependencies]. In code, call rand07::thread_rng(). The name before = is the import name, and package is the real crate name.