JGit:检出远程分支

28

我正在使用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状态输出:git status
$ git status
# Not currently on any branch.
nothing to commit (working directory clean)

同样的操作也可以在git命令行中轻松完成,并且它是有效的。

git checkout -t origin/mybranch

如何使用 JGit 进行操作?

4个回答

45

您需要使用 setCreateBranch 创建一个分支:

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

你的第一个命令相当于 git checkout origin/mybranch

(编辑:我提交了一个关于CheckoutCommand的文档改进补丁给JGit:https://git.eclipse.org/r/8259


@AdamSiemion:你是什么意思?setStartPoint 应该能够使用标签名称,否则这就是 JGit 的一个 bug(请报告它)。 - robinst
@robinst 为了使其与git标签名称配合使用,必须删除“origin/”,否则将会发生此情况(https://issues.jboss.org/browse/FORGE-2033)。 - Adam Siemion
@AdamSiemion:是的,但这与命令行上的情况相同,标签不像分支那样有命名空间。 - robinst
在命令行中,@robinst使用git checkout <branch/tag> 命令可以切换分支或标签:例如 git checkout 2.1.2.Final 或者 git checkout master - Adam Siemion
setCreateBranch 一直是 true 吗?参考:https://dev59.com/nVcO5IYBdhLWcg3wkif2 - Mr.Raindrop
显示剩余3条评论

5

由于某种原因,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();

1
这应该是被接受的答案。另外两个解决方案不起作用。 - PC.

4
CheckoutCommand 代码所示,你需要将布尔值 createBranch 设置为 true 以创建本地分支。
你可以在 CheckoutCommandTest - testCreateBranchOnCheckout() 中看到一个例子。
@Test
public void testCreateBranchOnCheckout() throws Exception {
  git.checkout().setCreateBranch(true).setName("test2").call();
  assertNotNull(db.getRef("test2"));
}

好主意将测试用例链接起来,加一分 :) - robinst

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);

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