JGit branch checkout Issue

Muthu picture Muthu · Sep 27, 2012 · Viewed 12.8k times · Source

I am checking out a repository from github using the following code .

private String url = "https://github.com/organization/project.git";
    Git repo = Git.cloneRepository().setURI(url).setDirectory(directory).setCloneAllBranches(true).call();
    for (Ref b : repo.branchList().call()) {
        System.out.println("(standard): cloned branch " + b.getName());
    }

i am using the code

Git git = Git.open(checkout); //checkout is the folder with .git
git.pull().call(); //succeeds

If i chekout a branch

Git git = Git.open(new File(checkout)); //checkout is the folder with .git
System.out.println(git.getRepository().getFullBranch());
CheckoutCommand checkout = git.checkout();
Ref call = checkout.setName("kalees").call();

It throws org.eclipse.jgit.api.errors.RefNotFoundException: Ref kalees can not be resolved.

What is the issue here, if i specify "master" instead of "kalees", it works fine. what change should i do to checkout a specific branch?

if i use the code

git.checkout().setCreateBranch(true).setName("refs/remotes/origin/kalees");

It checkout the kalees branch. but when i do pull operation

git.pull().call(); 

it throws org.eclipse.jgit.api.errors.DetachedHeadException: HEAD is detached. What could be the , whether this is a checkout issue or pull issue ?

Answer

VonC picture VonC · Sep 27, 2012

It should only happen if:

  • kalees isn't an existing branch (or is incorrectly written, bad case)
  • kalees is a remote branch you haven tracked yet a a local branch

If so you might need to create it first (a bit like in this example)

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

Following "JGit: Cannot find a tutorial or simple example", I would rather use:

git.branchCreate() 
       .setName("kalees")
       .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
       .setStartPoint("origin/kalees")
       .setForce(true)
       .call();