我有一个通过 git2-rs 维护的本地 git 存储库,围绕 C 库的几乎一对一的 Rust 包装器 libgit2 .我已经设法使用该库进行并提交更改。但是,我无法设法将更改推送到远程存储库。当我尝试连接到 Remote 时,出现以下错误消息:
request failed with status code: 401
这是我的代码:
let repo: Repository = /* get repository */;
let mut remote = repo.find_remote("origin").unwrap();
// connect returns Err, and so this panics.
remote.connect(Direction::Push).unwrap();
我也尝试过传递各种凭据,但出现同样的错误:
let mut callbacks = RemoteCallbacks::new();
callbacks.credentials(|str, str_opt, cred_type| {
Ok(Cred::userpass_plaintext("natanfudge", env!("GITHUB_PASSWORD")).unwrap())
});
remote
.connect_auth(Direction::Push, Some(callbacks), None)
.unwrap();
let mut callbacks = RemoteCallbacks::new();
callbacks.credentials(|str, str_opt, cred_type| {
// This line does not panic, only the connect_auth!
Ok(Cred::ssh_key_from_agent("natanfudge").expect("Could not get ssh key from ssh agent"))
});
remote
.connect_auth(Direction::Push, Some(callbacks), None)
.unwrap();
我错过了什么?
最佳答案
好的,我解决了这个问题。需要完成 3 件事情才能使其正常工作:
使用
connect_auth
和credentials
是正确的。您还需要使用
remote.push
指定相同的凭据。您必须在
remote.push
中指定与在remote_add_push
中所做的相同的 refspec 字符串。
所以这段代码有效:
fn create_callbacks<'a>() -> RemoteCallbacks<'a>{
let mut callbacks = RemoteCallbacks::new();
&callbacks.credentials(|str, str_opt, cred_type| {
Cred::userpass_plaintext("your-username",env!("GITHUB_PASSWORD"))
});
callbacks
}
fn main() {
let repo = /* get repository */
let mut remote = repo.find_remote("origin").unwrap();
remote.connect_auth(Direction::Push, Some(create_callbacks()), None).unwrap();
repo.remote_add_push("origin", "refs/heads/<branch-name>:refs/heads/<branch-name>").unwrap();
let mut push_options = PushOptions::default();
let mut callbacks = create_callbacks();
push_options.remote_callbacks(callbacks);
remote.push(&["refs/heads/<branch-name>:refs/heads/<branch-name>"], Some(&mut push_options)).unwrap();
std::mem::drop(remote);
Ok(())
}
对于调试,使用 push_update_reference
回调很有用。如果推送有问题,它会说。
let mut push_options = PushOptions::default();
let mut callbacks = create_callbacks();
callbacks.push_update_reference(|ref,error|{
println!("ref = {}, error = {:?}", ref, error);
Ok(())
});
remote.push(&["refs/heads/<branch-name>:refs/heads/<branch-name>"], Some(&mut
push_options)).unwrap();
关于git - 尝试使用 git2-rs/libgit2 推送到远程时出现 "request failed with status code: 401"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58201849/