Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Orphan branch in libgit2sharp

How do you create an orphan branch in libgit2sharp?

All i could find are methods which create a branch which points to a commit.
I'm looking for an effect similar to the command:

git checkout --orphan BRANCH_NAME  
like image 330
SWilly22 Avatar asked Oct 09 '13 14:10

SWilly22


1 Answers

git checkout --orphan BRANCH_NAME actually moves the HEAD to an unborn branch BRANCH_NAME without altering the working directory nor the index.

You can perform a similar operation with LibGit2Sharp by updating the target of the HEAD reference with repo.Refs.UpdateTarget() method.

The following test demonstrates this

[Fact]
public void CanCreateAnUnbornBranch()
{
    string path = CloneStandardTestRepo();
    using (var repo = new Repository(path))
    {
        // No branch named orphan
        Assert.Null(repo.Branches["orphan"]);

        // HEAD doesn't point to an unborn branch
        Assert.False(repo.Info.IsHeadUnborn);

        // Let's move the HEAD to this branch to be created
        repo.Refs.UpdateTarget("HEAD", "refs/heads/orphan");
        Assert.True(repo.Info.IsHeadUnborn);

        // The branch still doesn't exist
        Assert.Null(repo.Branches["orphan"]);

        // Create a commit against HEAD
        var signature = new Signature("Me", "[email protected]", DateTimeOffset.Now);
        Commit c = repo.Commit("New initial root commit", signature, signature);

        // Ensure this commit has no parent
        Assert.Equal(0, c.Parents.Count());

        // The branch now exists...
        Branch orphan = repo.Branches["orphan"];
        Assert.NotNull(orphan);

        // ...and points to that newly created commit
        Assert.Equal(c, orphan.Tip);
    }
}
like image 160
nulltoken Avatar answered Sep 30 '22 03:09

nulltoken