我正在使用Rust git2 crate 克隆Git存储库,就像这样

use git2::Repository;

fn main() {
    let repo = Repository::clone(
        "https://github.com/rossmacarthur/dotfiles",
        "dotfiles"
     ).expect("failed to clone repository");

     repo.checkout("mybranch");  // need something like this.
}

我希望能够签出分支、提交或标记.

我看过以下文档,但仍然不确定使用哪种方法

我可以做以下操作,但它只会更改文件

let object = repo
    .revparse_single("mybranch")
    .expect("failed to find identifier");
repo.checkout_tree(&object, None)
    .expect(&format!("failed to checkout '{:?}'", object));

如果我重置,它会改变头部,但不会改变当前分支

repo.reset(&object, git2::ResetType::Soft, None)
    .expect(&format!("failed to checkout '{:?}'", object));

推荐答案

使用git2(v0.13.18)的最新版本:

use git2::Repository;

fn main() {
    let repo = Repository::clone("https://github.com/rossmacarthur/dotfiles", "/tmp/dots")
        .expect("Failed to clone repo");

    let refname = "master"; // or a tag (v0.1.1) or a commit (8e8128)
    let (object, reference) = repo.revparse_ext(refname).expect("Object not found");
    
    repo.checkout_tree(&object, None)
        .expect("Failed to checkout");

    match reference {
        // gref is an actual reference like branches or tags
        Some(gref) => repo.set_head(gref.name().unwrap()),
        // this is a commit, not a reference
        None => repo.set_head_detached(object.id()),
    }
    .expect("Failed to set HEAD");
}

注意,checkout_tree只设置工作树的内容,set_head只设置HEAD.只运行其中一个将使目录处于脏状态.

Rust相关问答推荐

WebDriver等待三十四?(Rust Se)

使用InlineTables序列化toml ArrayOfTables

如何在Tauri中将变量从后端传递到前端

捕获FnMut闭包的时间不够长

如何在递归数据 struct 中移动所有权时变异引用?

我如何使用AWS SDK for Rust获取我承担的角色的凭据?

在铁 rust 中,如何一次只引用几件事中的一件?

为什么RefCell没有与常规引用相同的作用域?

如何在 `connect_activate()` 之外创建一个 `glib::MainContext::channel()` 并将其传入?

如何在 Rust 中编写一个通用方法,它可以接受任何可以转换为另一个值的值?

通过写入 std::io::stdout() 输出不可见

Rust typestate 模式:实现多个状态?

如何使用泛型满足 tokio 异步任务中的生命周期界限

从 Axum IntoResponse 获取请求标头

使用 `clap` 在 Rust CLI 工具中设置布尔标志

如何创建递归borrow 其父/创建者的 struct ?

将一片字节复制到一个大小不匹配的数组中

BigUint 二进制补码

HashMap entry() 方法使borrow 的时间比预期的长

为什么 Rust 标准库同时为 Thing 和 &Thing 实现特征?