以下示例使用的是Rust v1.34和git2 v0.8。
要检出一个分支:
use git2::*;
fn main() {
let repo = Repository::clone(
"https://github.com/rossmacarthur/dotfiles",
"dotfiles"
).expect("failed to clone repository");
let branch_name = "my_branch";
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,
);
let obj = repo.revparse_single(&("refs/heads/".to_owned() +
branch_name)).unwrap();
repo.checkout_tree(
&obj,
None
);
repo.set_head(&("refs/heads/".to_owned() + branch_name));
}
要检出一个提交:
use git2::*;
fn main() {
let repo = Repository::clone(
"https://github.com/rossmacarthur/dotfiles",
"dotfiles"
).expect("failed to clone repository");
let my_oid_str = "9411953f92d100f767e6de6325b17afae5231779";
let oid = Oid::from_str(my_oid_str).unwrap();
let commit = repo.find_commit(oid).unwrap();
let branch = repo.branch(
my_oid_str,
&commit,
false,
);
let obj = repo.revparse_single(&("refs/heads/".to_owned() + my_oid_str)).unwrap();
repo.checkout_tree(
&obj,
None,
);
repo.set_head(&("refs/heads/".to_owned() + my_oid_str));
}
要检出一个标签,请尝试以下方法:
use git2::*;
fn main() {
let repo = Repository::clone(
"https://github.com/narke/colorForth.git",
"colorforth"
).expect("failed to clone repository");
let tag_name = "v2012";
let references = repo.references().unwrap();
for reference in references {
let _reference = reference.unwrap();
if _reference.is_tag() == true {
let tag = _reference.peel_to_tag().unwrap();
if tag.name().unwrap() == tag_name {
let target_oid = tag.target().unwrap().id();
let commit = repo.find_commit(target_oid).unwrap();
let branch = repo.branch(
tag_name,
&commit,
false,
);
let obj = repo.revparse_single(&("refs/heads/".to_owned() + tag_name)).unwrap();
repo.checkout_tree(
&obj,
None,
);
repo.set_head(&("refs/heads/".to_owned() + tag_name));
}
}
}
}
我敢打赌通常有更好的方法,但这个问题已经无人回答几个月了,这就是我刚刚想到的解决方法。
set_head_detached()
-set_head()
期望一个引用名称,如refs/heads/master
或HEAD
(但提交哈希不是引用)。因此,正确的方式是repo.set_head_detached(oid);
。 - sudormrfbin