JGit: Checkout a remote branch

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?


You have to use setCreateBranch to create a branch:

Ref ref = git.checkout().
        setStartPoint("origin/" + branchName).

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)

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

public void testCreateBranchOnCheckout() throws Exception {

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

git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch).call();

you also can just like this

                logger.info("Checkout to remote branch:" + remoteBranch);
                logger.info("create new locale branch:" + branchName + "set_upstream with:" + remoteBranch);
                logger.info("Checkout to locale branch:" + branchName);

Need Your Help

Wrong requestCode in onActivityResult

android android-fragments onactivityresult

I'm starting a new Activity from my Fragment with

Bootstrap carousel not sliding

jquery html twitter-bootstrap

I have been trying to use the Bootstrap Carousel and have been successful to some extent. I can click and change the images too. But I have got one problem. Its just not sliding! Where am I doing w...