libgit2sharp中的孤儿分支

时间:2013-10-09 14:25:17

标签: version-control libgit2sharp

如何在libgit2sharp中创建孤立分支?

我能找到的只是创建指向提交的分支的方法 我正在寻找类似命令的效果:

git checkout --orphan BRANCH_NAME  

1 个答案:

答案 0 :(得分:3)

git checkout --orphan BRANCH_NAME实际上将HEAD移动到未出生的分支BRANCH_NAME,而不改变工作目录和索引。

您可以使用HEAD方法更新repo.Refs.UpdateTarget()引用的目标,从而对LibGit2Sharp执行类似的操作。

以下测试演示了这个

[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", "me@there.com", 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);
    }
}