2012-10-17 471 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);