Rust : 无法通过 Cargo 拉取私有代码仓库解决方式 failed to load source for dependency

问题描述

在使用rust 的过程中,有时候会依赖一些公司内部,或者私有的代码仓库,这时候,通常需要使用ssh认证,才能正常拉取仓库代码,但是有时候会遇到 Cargo 无法拉取代码的情况,看起来像是 ssh 认证失败导致的无法拉取代码,报错如下:

rust 复制代码
Updating git repository `ssh://git@git.yourcompany.com/your-team/your-repo`
error: failed to get `private-crate` as a dependency of package `your-project v0.1.0 (/path/to/your-project)`

Caused by:
  failed to load source for dependency `private-crate`

Caused by:
  Unable to update ssh://git@git.yourcompany.com/your-team/your-repo

Caused by:
  failed to fetch into: /Users/yourusername/.cargo/git/db/your-repo-xxxxxx

Caused by:
  failed to authenticate when downloading repository

  * attempted ssh-agent authentication, but no usernames succeeded: `git`

  if the git CLI succeeds then `net.git-fetch-with-cli` may help here
  https://doc.rust-lang.org/cargo/reference/config.html#netgit-fetch-with-cli

Caused by:
  no authentication methods succeeded

问题原因

默认新情况下,cargo使用内置的 libgit2 来拉取 git 依赖,而非系统自带的 git 命令行工具进行依赖拉取,libgit2 对 SSH 认证幼体套独立的实现,所以可能无法直接复用本地对ssh的配置,ssh-agent 环境变量 以及 SSH 密钥设置。

这就可能导致一个现象:正常使用 git clone 可以拉取到项目代码,但是 rust-analyzer 却总是报错无法拉取依赖,ssh 认证失败等问题。

解决方案

在你的项目中,添加 .cargo 文件夹,并在文件夹中创建 config.toml 文件,

bash 复制代码
your-project/
├─ .cargo/
│  └─ config.toml
└─ Cargo.toml

在config.toml 文件中添加以下配置

toml 复制代码
[net]
git-fetch-with-cli = true

就可以让 cargo 使用本机已安装的 git 命令行工具拉取配置,从而与手动拉取配置一样,正常获取到依赖。

验证

最后重启代码编辑器vscode,或者运行cargo b 进行验证,会发现问题已解决。Pomelo_刘金,转载请注明链接,感谢!

相关推荐
techdashen2 小时前
深入 Rust enum 的内存世界
开发语言·后端·rust
techdashen4 小时前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust
Arman_6 小时前
02 rusty-cat 实战:MeowClient 配置、任务参数、进度回调与暂停恢复
http·https·rust·tokio·文件分片上传·文件分片下载
wzhao1016 小时前
Relink 0.15.1:一个 no_std 的 ELF 加载器/链接器
linux·rust·gnu
yzwlord8 小时前
【无标题】
linux·运维·rust·ssh
Arman_8 小时前
Rust 客户端安全上传下载阿里云 OSS:rusty-cat 预签名 URL 实战
安全·阿里云·rust·oss断点续传
灵机一物8 小时前
灵机一物AI原生电商小程序、PC端(已上线)-【技术深度解析】Bun 6 天 AI 重写 96 万行代码:从 Zig 迁移 Rust 全流程与行业影响
开发语言·人工智能·rust
Arman_8 小时前
03 rusty-cat 进阶解析:架构设计、云存储接入、安全模型与长期维护评估
css·安全·rust·文件分片上传·文件分片下载
techdashen9 小时前
半小时读懂 Rust:从语法符号到所有权思维
开发语言·rust
星栈9 小时前
Rust 全栈 SSR 用了一年,我踩过的 5 个坑和 3 个真香瞬间
rust·开源·全栈