簡體   English   中英

使用LibGit2Sharp克隆給定分支

[英]Clone a given branch with LibGit2Sharp

我想使用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);

FWIW,有一個待處理的Pull Request ,允許用戶明確指定想要查看的分支。

編輯

我用你的建議更新了我的代碼,但它仍然不能正常工作。 我的本地存儲庫的內容與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);

實際上,默認情況下, 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);

FWIW,有一個待處理的Pull Request ,允許用戶明確指定想要查看的分支。

更新

Pull請求已合並。 克隆()調用成功后檢出已知分支現在可以通過以下方式更輕松地完成:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM