rust-lang / git2-rs

libgit2 bindings for Rust
https://docs.rs/git2
Apache License 2.0
1.69k stars 387 forks source link

How to create a orphan branch? #1089

Open dvaerum opened 5 hours ago

dvaerum commented 5 hours ago

If you run the command git switch --orphan <BRANCH_NAME> you get a new branch without any previous history.

Note: You, of course, need to make at least one commit to make the branch stay.

How do I do this with git2-rs?

I really don't seem to be able to find anything in the docs at https://docs.rs/git2/0.19.0/git2/index.html 😭

ehuss commented 2 hours ago

I believe orphans are created by setting HEAD to a non-existent branch:

let repo = Repository::open("repo")?;
repo.set_head("refs/heads/newbranch")?;
std::fs::write("repo/test", "This is a test")?;
let mut index = repo.index()?;
index.clear()?; // Only if you want to remove any existing files.
index.add_path(Path::new("test"))?;
index.write()?;
let tree_id = index.write_tree()?;
let tree = repo.find_tree(tree_id)?;
let sig = repo.signature()?;
repo.commit(
    Some("HEAD"),
    &sig,
    &sig,
    "Add on orphan",
    &tree,
    &[] // no parents
)?;