清理 Cargo 缓存和构建产物
TL;DR: 使用 cargo clean 清理项目构建产物,删除 ~/.cargo/registry 清理全局缓存,或使用 cargo-cache/cargo-sweep 工具进行更精细的管理。
快速清理命令
清理当前项目
1 2 3 4 5
| cargo clean
cargo clean --release
|
清理全局缓存
1 2 3 4 5 6 7 8
| rm -rf ~/.cargo/registry
rm -rf ~/.cargo/git
rm -rf ~/.cargo
|
推荐工具
cargo-cache
功能强大的缓存管理工具。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| cargo install cargo-cache
cargo cache
cargo cache --remove-dir all
cargo cache clean-unref
cargo cache --remove-if-older-than 30
|
cargo-sweep
清理旧构建产物,支持按时间和工具链过滤。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| cargo install cargo-sweep
cargo sweep --dry-run --time 30
cargo sweep --time 30
cargo sweep --installed
cargo sweep --time 30 /path/to/project
|
批量清理多个项目
1 2 3 4 5
| find /path/to/projects -type d -name target -exec rm -rf {} +
find . -name "target" -type d -exec rm -rf {} + 2>/dev/null
|
Rust 工具链管理
1 2 3 4 5 6 7 8
| rustup show
rustup uninstall nightly
rustup self update
|
清理未使用依赖
1 2 3 4 5 6
| cargo install cargo-machete cargo-udeps
cargo machete cargo udeps --all-targets
|
完全卸载 Rust
1 2 3 4 5 6
| rustup self uninstall
rm -rf ~/.rustup rm -rf ~/.cargo
|
环境变量配置
1 2 3 4 5
| export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup export CARGO_HOME="$HOME/.cargo" export PATH="$CARGO_HOME/bin:$PATH"
|
清理策略对比
| 方法 |
清理范围 |
推荐场景 |
风险等级 |
cargo clean |
当前项目构建产物 |
快速释放项目空间 |
低 |
rm -rf ~/.cargo/registry |
全局 crate 缓存 |
急需释放大量空间 |
中 |
cargo-cache |
可定制缓存清理 |
精细化管理 |
低 |
cargo-sweep |
旧构建产物 |
多项目开发环境 |
中 |
rustup uninstall |
工具链 |
切换版本后清理 |
低 |
最佳实践
- 日常开发:使用
cargo sweep --time 7 每周清理一次
- CI/CD 环境:每次构建前执行
cargo clean
- 磁盘空间紧张:优先清理
~/.cargo/registry 和 ~/.rustup
- 安全第一:执行删除前使用
--dry-run 预览效果
Tags: #rust #cargo #cleanup #disk-space #development-tools