JGit: Checkout a remote branch

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

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)


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

Tags:

Git

Jgit