JGit: Checkout a remote branch

我只是一个虾纸丫 提交于 2019-12-29 05:43:35

问题


I'm using JGit to checkout a remote tracking branch.

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

The files are checked out, but the HEAD is not pointing to the branch. Following is the git status output,

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

The same operation can be performed in git command line, easily and it works,

git checkout -t origin/mybranch

How to do this JGit?


回答1:


You have to use setCreateBranch to create a branch:

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

Your first command was the equivalent of git checkout origin/mybranch.

(Edit: I submitted a patch to JGit to improve the documentation of CheckoutCommand: https://git.eclipse.org/r/8259)




回答2:


For whatever reason, the code that robinst posted did not work for me. In particular, the local branch that was created did not track the remote branch. This is what I used that worked for me (using 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();



回答3:


As shown in the code of CheckoutCommand, you need to set the boolean createBranch to true in order to create a local branch.

You can see an example in CheckoutCommandTest - testCreateBranchOnCheckout()

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



回答4:


you also can just like this

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


来源:https://stackoverflow.com/questions/12927163/jgit-checkout-a-remote-branch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!