使用LibGit2Sharp克隆给定的分支

4

我想使用LibGit2Sharp将给定分支克隆到本地存储库。

 var repoPath = LibGit2Sharp.Repository.Clone("https://something", localpath, cloneOptions);

 using (var repo = new LibGit2Sharp.Repository(repoPath))
 {
     var branches = repo.Branches.GetEnumerator();
 }

使用repo.Branches.GetEnumerator()可以查看每个远程分支,但是使用Clone命令时,我只能从GitHub克隆主分支吗?如何克隆“testBranch”或其他分支?

实际上,默认情况下,Clone()会负责本地检索所有分支的所有提交。默认情况下,只有远程HEAD分支(通常是origin/master)会自动创建一个本地分支副本,然后将其检出。

因此,一旦克隆完成,您只需要从要使用的远程分支创建一个本地分支,并将其检出即可。

例如,假设您对分支my-feature-branch感兴趣,并且您的远程命名为origin

Branch remoteBranch = repo.Branches["origin/my-feature-branch"];

Branch newLocalBranch = repo.CreateBranch("my-feature-branch");

// Make the local branch track the upstream one
repo.Branches.Update(newLocalBranch ,
     b => b.TrackedBranch = remoteBranch.CanonicalName);

Branch trackingBranch = repo.Branches["my-feature-branch"];

repo.Checkout(trackingBranch);

值得一提的是,目前有一个未决的拉取请求,允许用户明确指定要检出的分支。

编辑

我根据您的建议更新了代码,但仍然不能很好地工作。我的本地存储库的内容与跟踪分支不相等,仍代表主分支的内容。

var remoteBranch = repo.Branches["origin/" + branchName];

var newLocalBranch = repo.Branches.Add(branchName, commit, true);

repo.Branches.Update(newLocalBranch, 
      b => b.TrackedBranch = remoteBranch.CanonicalName);

var trackingBranch = repo.Branches[branchName];

repo.Checkout(trackingBranch, new LibGit2Sharp.CheckoutOptions(), author);

repo.Branches.Add(branchName, commit, true); -> commit 是从哪里来的?我建议使用 IRepository.CreateBranch() 扩展方法或 repo.Branches.Add(branchName, remoteBranch.Tip); - nulltoken
1个回答

5
实际上,默认情况下,Clone() 会负责本地检索所有分支的所有提交。默认情况下,只有远程 HEAD 分支(通常是 origin/master)会自动创建一个本地分支对应项,然后被检出。
因此,一旦克隆完成,你所要做的就是从你想要操作的远程分支创建一个本地分支,并检出这个新创建的本地分支。
例如,假设你对分支 my-feature-branch 感兴趣,而你的远程名称为 origin:
Branch remoteBranch = repo.Branches["origin/my-feature-branch"];

Branch newLocalBranch = repo.CreateBranch("my-feature-branch", remoteBranch.Tip);

// Make the local branch track the upstream one
repo.Branches.Update(newLocalBranch ,
     b => b.TrackedBranch = remoteBranch.CanonicalName);

Branch trackingBranch = repo.Branches["my-feature-branch"];

repo.Checkout(trackingBranch);

值得一提的是,目前有一个未决的拉取请求允许用户明确指定要查看的分支。

更新

拉取请求已经合并。现在可以更轻松地通过以下方法在Clone()调用成功后检出已知分支:

string clonedRepoPath = Repository.Clone(
    url, targetPath,
    new CloneOptions { BranchName = branchName });

是的,我看到建议使用repo.CreateBranch()方法来解决这个问题。我的项目中添加了版本为0.20.0.0的LibGit2Sharp NuGet包。有趣的是,我的Repository对象没有CrateBranch()方法。我可能做错了什么吗? - Gábor Domonkos
CreateBranch()IRepository 接口的扩展方法。任何 Repository 类型的实例都应该公开它。 - nulltoken
是的,那就是问题所在。我没有在 usings 中使用 LibGit2Sharp; ,如果你只写 var repo = new LibGit2Sharp.Repository(path) ,那么你不能使用 repo.CreateBranch() 方法。 - Gábor Domonkos
看起来在这个答案中提到的拉取请求已经合并到产品中了。我还没有测试过使用情况,但是现在似乎允许您在传递给Repository.Clone命令的CloneOptions对象中指定一个分支。 - phil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接