5

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

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

git checkout --orphan BRANCH_NAME  
4

1 回答 1

6

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

HEAD您可以通过使用方法更新引用的目标来使用 LibGit2Sharp 执行类似的操作repo.Refs.UpdateTarget()

下面的测试证明了这一点

[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);
    }
}
于 2013-10-09T15:39:28.397 回答