Skip to content

Instantly share code, notes, and snippets.

@asins
Created July 25, 2024 12:47
Show Gist options
  • Save asins/c18a4bfa2648215f283bc7b2fae0cb57 to your computer and use it in GitHub Desktop.
Save asins/c18a4bfa2648215f283bc7b2fae0cb57 to your computer and use it in GitHub Desktop.
使用git2-rs库克隆指定的单个分支的内容
use git2::build::RepoBuilder;
use git2::{Cred, FetchOptions, RemoteCallbacks};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct SshKey {
pub public_key: PathBuf,
pub private_key: PathBuf,
}
pub fn single_git_clone(git_url: &str, git_path: &Path, git_branch: &str, ssh_key: &SshKey) -> Result<(), git2::Error> {
let mut cb = RemoteCallbacks::new();
cb.transfer_progress(|stats| {
let network_pct = (100 * stats.received_objects()) / stats.total_objects();
println!("[git clone] {network_pct}% {}/{}", stats.received_objects(), stats.total_objects());
true
});
cb.credentials(|_, username, _| Cred::ssh_key(username.unwrap_or("git"), Some(&ssh_key.public_key), &ssh_key.private_key, None));
let mut fo = FetchOptions::new();
fo.remote_callbacks(cb);
RepoBuilder::new()
.branch(git_branch) // 指定分支
.fetch_options(fo)
.remote_create(|repo, name, url| { // 只克隆指定的分支 --single-branch
let refspec = format!("+refs/heads/{0:}:refs/remotes/origin/{0:}", &git_branch);
repo.remote_with_fetch(name, url, &refspec)
})
.clone(git_url, git_path)?;
Ok(())
}
mod git;
use std::path::{Path, PathBuf};
use create::git::{single_git_clone, SshKey};
fn main() {
let ssh_key = SshKey {
public_key: PathBuf::from("./git_ssh_key/user_rsa.pub"),
private_key: PathBuf::from("./git_ssh_key/user_rsa"),
};
let local_path = Path::new("./test");
match single_git_clone("[email protected]:a/b.git", &local_path, "release/1.2.3", &ssh_key) {
Ok(()) => {}
Err(e) => println!("error: {}", e),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment