5

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 ?

Flexo
  • 87,323
  • 22
  • 191
  • 272
Muthu
  • 1,550
  • 10
  • 36
  • 62

3 Answers3

5

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(); 
Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • @kaleeswaran14 not sure. Maybe the `.setForce(true)` is important here? – VonC Sep 27 '12 at 13:57
  • @kaleeswaran14 I have edited the answer to include a more precise example. – VonC Sep 27 '12 at 14:04
  • @kaleeswaran14 You can checkout a remote branch, provided you create a local one based on that checkout (otherwise you are in a DETACHED HEAD mode, which is your case here). – VonC Oct 08 '12 at 10:22
2

I met this question when I want to create a branch with an empty repository, there is no commit in this repository.

It's resolved when I commit something to the repository. Hope it's helpful for you :)

Linsama
  • 149
  • 1
  • 6
1

Muthu your code is working you only need to add origin/branch like this to the branch call

Ref call = checkout.setName("origin/kalees").call();
Rob
  • 26,989
  • 16
  • 82
  • 98
takumi3t9
  • 21
  • 1