Cargo 依赖下载排查:索引、crate 与 Git 依赖
三层拆解 cargo build 卡住或拉取失败的原因。
Rust 项目第一次 cargo build 卡在 “Updating crates.io index”,或者 Git 依赖拉取失败,是很多人入门时碰到的第一道坎。这篇按“索引 → crate 下载 → Git 依赖“三层拆开排查。
1. 先确认 Cargo 版本和索引协议
Cargo 1.70 起默认使用 sparse 协议,只按需下载索引文件,比旧的 Git 索引快得多:
cargo --version
如果版本较老,可以在 ~/.cargo/config.toml 里显式打开:
[registries.crates-io]
protocol = "sparse"
2. 索引请求超时:看网络层
Cargo 会读取 http.proxy 配置和 HTTPS_PROXY 环境变量。排查时先用 curl 模拟同一个请求:
curl -I https://index.crates.io/config.json
curl 通、Cargo 不通,多半是 Cargo 没读到代理。在 config.toml 里写明:
[http]
proxy = "http://127.0.0.1:7890"
timeout = 60
3. crate 下载失败:校验和与缓存
报 checksum mismatch 时,不要手改 Cargo.lock。先清掉对应缓存再重试:
rm -rf ~/.cargo/registry/cache/*/有问题的crate-*
cargo fetch
4. Git 依赖:libgit2 与系统 git
Cargo 默认用内置的 libgit2,它不认识你在 ~/.gitconfig 里配的部分选项(比如某些 SSH 设置)。最省事的做法是让 Cargo 调用系统 git:
[net]
git-fetch-with-cli = true
这样 SSH key、core.sshCommand、凭据助手都会按系统 git 的方式生效。
5. 一份最小检查表
cargo --version≥ 1.70,确认 sparse 协议- curl 能访问 index.crates.io
- config.toml 中
[http] proxy与实际端口一致 - Git 依赖失败时开启
git-fetch-with-cli - 用
CARGO_LOG=cargo::sources=debug cargo fetch看详细日志
更完整的分场景说明可以参考这篇 Cargo:索引、crate 与 Git 依赖。
由 Roxi 背后的小团队撰写。
Write a comment