如何通过VSCode或rust-analyzer配置解决Rust crate认证缺失问题
解决VSCode中rust-analyzer因SSH认证失败无法加载Cargo工作区的问题
问题场景
使用VSCode的rust-analyzer插件时,出现Cargo元数据加载失败的错误,核心原因是拉取Git依赖时SSH认证失败,具体错误日志如下:
[ERROR rust_analyzer::lsp_utils] rust-analyzer failed to load workspace: Failed to read Cargo metadata from Cargo.toml file /Users/calvin/tiflash/raft-engine/Cargo.toml, Some(Version { major: 1, minor: 64, patch: 0, pre: Prerelease("nightly") }): Failed to run `"cargo" "metadata" "--format-version" "1" "--manifest-path" "/Users/calvin/tiflash/raft-engine/Cargo.toml" "--filter-platform" "x86_64-apple-darwin"`: `cargo metadata` exited with an error: Updating git repository `https://github.com/pingcap/rust-protobuf` Updating git repository `https://github.com/tikv/raft-rs` error: failed to load source for dependency `raft-proto` Caused by: Unable to update https://github.com/tikv/raft-rs?branch=master Caused by: failed to fetch into: /Users/calvin/.cargo/git/db/raft-rs-42b8049ef2e3af07 Caused by: failed to authenticate when downloading repository: git@github.com:tikv/raft-rs * 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 available
临时解决办法
在终端执行以下命令启动SSH代理并添加密钥后,从命令行启动VSCode可临时解决问题:
eval `ssh-agent -s` ssh-add # 执行 code . 启动VSCode
更简洁的配置解决方案
无需每次从命令行启动VSCode,可通过以下两种方式永久解决:
1. 修改Cargo配置,使用Git CLI拉取依赖
在全局Cargo配置文件~/.cargo/config.toml,或项目级配置文件项目根目录下的.cargo/config.toml中添加以下内容:
[net] git-fetch-with-cli = true
该配置会让Cargo调用系统Git CLI拉取依赖,而非内置Git实现,自动继承当前环境的SSH认证信息。
2. 配置VSCode让rust-analyzer继承SSH Agent环境变量
如果上述方法无效,可在VSCode的settings.json中添加环境变量配置,确保rust-analyzer运行时能获取到SSH认证所需的环境变量:
{ "rust-analyzer.cargo.extraEnv": { "SSH_AUTH_SOCK": "${env:SSH_AUTH_SOCK}" } }
注意:需确保系统已自动启动SSH代理(可在~/.zshrc或~/.bashrc中配置自动启动ssh-agent的脚本),否则VSCode无法读取到有效的SSH_AUTH_SOCK变量。
内容的提问来源于stack exchange,提问作者calvin
相关产品推荐
相关产品推荐

