如何使用git2-rs从分支克隆存储库?

huangapple go评论79阅读模式
英文:

How to clone repository from branch using git2-rs?

问题

I can provide a translation of the non-code parts of your text:

"最近我想从一个仓库中复制文件,在Rust中使用Repository::clone,但是这个函数不支持分支。我想问一下如何从一个分支中复制文件。

我目前正在使用git2版本0.17.1和Rust版本1.69.0 (84c898d65 2023-04-16)。"

Please note that the code you provided is already in English, so there's no need for translation. If you have any further questions or need assistance with the code itself, feel free to ask.

英文:

recently I wanted to copy files from a repo, in rust using Repository::clone, but this function does not support branches. I wanted to ask how to copy files from a branch.

I am currently using git2 version 0.17.1, and rust version 1.69.0 (84c898d65 2023-04-16).

    let repo = match Repository::clone(repo_url, temp_dir.path()) {
        Ok(repo) => repo,
        Err(e) => panic!("failed to clone: {}", e),
    };

    println!("Cloned {} to {}", repo_url, temp_dir.path().display());
    repo.remote_anonymous(repo_url)?
        .fetch(&[branch_name], None, None)?;

    let head = repo.head().unwrap();
    let oid = head.target().unwrap();
    let commit = repo.find_commit(oid).unwrap();
    let branch = repo
        .branch(branch_name, &commit, false)
        .expect("Faild to find branch");

    let obj = repo
        .revparse_single(&("refs/heads/".to_owned() + branch_name))
        .unwrap();

    repo.set_head(&("refs/heads/".to_owned() + branch_name));

    repo.checkout_tree(&obj, None);

This is the code I tried. The branch has been changed. But I don't know how to swap the files from that branch with the ones that have already been copied.

答案1

得分: 2

Here is the translated content:

如果您阅读 clone 的文档,它会告诉您:

有关更多信息,请参阅 RepoBuilder 结构体。

然后,如果您转到 RepoBuilder,会有一个 branch 方法。

git2::build::RepoBuilder::new()
    .branch(branch_name)
    .clone(repo_url, temp_dir.path())
英文:

If you read the documentation for clone, it tells you this:

> See the RepoBuilder struct for more information.

Then if you go to RepoBuilder, there's a branch method.

git2::build::RepoBuilder::new()
    .branch(branch_name)
    .clone(repo_url, temp_dir.path())

huangapple
  • 本文由 发表于 2023年5月7日 19:18:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定