2012-10-17 121 views
15

我正在使用JGit簽出遠程跟蹤分支。JGit:簽出遠程分支

Git binrepository = cloneCmd.call() 

CheckoutCommand checkoutCmd = binrepository.checkout(); 
checkoutCmd.setName("origin/" + branchName); 
checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK); 
checkoutCmd.setStartPoint("origin/" + branchName); 

Ref ref = checkoutCmd.call(); 

文件已簽出,但HEAD未指向分支。 以下是git status輸出,

$ git status 
# Not currently on any branch. 
nothing to commit (working directory clean) 

同樣的操作可以在git的命令行中執行,很容易和它的作品,

git checkout -t origin/mybranch 

如何做到這一點JGit?

回答

19

你必須使用setCreateBranch去創建一個分支:

Ref ref = git.checkout(). 
     setCreateBranch(true). 
     setName("branchName"). 
     setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK). 
     setStartPoint("origin/" + branchName). 
     call(); 

你的第一個命令是的git checkout origin/mybranch相當。

(編輯:我提交了一個補丁來JGit改善CheckoutCommand的文檔:https://git.eclipse.org/r/8259

+0

我試過了。有用。其簡單的解決方案。我需要做出改變,承諾並推動遠程。我會測試並更新線程。 – Nambi

+0

比我的完整答案。 +1 – VonC

+0

上面的代碼不會與git標籤一起使用,權限? –

4

如代碼CheckoutCommand所示,您需要將布爾createBranch設置爲true以創建本地分支。

你可以看到一個例子,CheckoutCommandTest - testCreateBranchOnCheckout()

@Test 
public void testCreateBranchOnCheckout() throws Exception { 
    git.checkout().setCreateBranch(true).setName("test2").call(); 
    assertNotNull(db.getRef("test2")); 
} 
+0

好主意鏈接到測試用例,+1 :) – robinst

3

無論出於何種原因,robinst張貼我沒有工作的代碼。特別是,創建的本地分支沒有跟蹤遠程分支。這是我使用的爲我工作(使用jgit 2.0.0.201206130900-R):

git.pull().setCredentialsProvider(user).call() 
git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch).call(); 
git.checkout().setName(branch).call() 
+0

這應該是接受的答案。其他兩種解決方案不起作用。 –

1

你也可以就這樣

git.checkout().setName(remoteBranch).setForce(true).call(); 
       logger.info("Checkout to remote branch:" + remoteBranch); 
       git.branchCreate() 
        .setName(branchName) 
        .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) 
        .setStartPoint(remoteBranch) 
        .setForce(true) 
        .call(); 
       logger.info("create new locale branch:" + branchName + "set_upstream with:" + remoteBranch); 
       git.checkout().setName(branchName).setForce(true).call(); 
       logger.info("Checkout to locale branch:" + branchName);