willkil
willkil

Reputation: 1669

How do I point git HEAD to a particular ref using the jgit library?

I want to update HEAD programmatically without performing a checkout or rebase on a non-bare repo.

I want the working tree and index to be unchanged after the operation.

EDIT

I need to update the symbolic target of HEAD, not the commit ID of the current target of HEAD. This is more like a checkout than anything else, except I can't use org.eclipse.jgit.api.CheckoutCommand because it requires that I update paths, but I don't want to touch the working tree. org.eclipse.jgit.api.CreateBranchCommand is also inappropriate because it expects a particular starting point, which doesn't exist because I'm creating an orphan branch.

Upvotes: 3

Views: 1743

Answers (2)

Matthias Sohn
Matthias Sohn

Reputation: 272

Try org.eclipse.jgit.api.ResetCommand and set its mode to SOFT.

Upvotes: 0

willkil
willkil

Reputation: 1669

This worked for me: RefUpdate.link().

Example:

Result updateHead(
    Repository repo, String newHead, boolean force, boolean detach
) throws IOException {
    RefUpdate refUpdate = repo.getRefDatabase().newUpdate(Constants.HEAD, detach);
    refUpdate.setForceUpdate(force);
    return refUpdate.link(newHead);
}

The answer is buried in about 5 places in the jgit source code.

Three api commands in jgit v2.0.0.201206130900-r update HEAD for you: clone, checkout, and rebase. Use one of those if it applies.

None of those apply: checkout and rebase would change the working tree and index.

Hopefully posting this question and answer will save others the time I had to spend on it.

Upvotes: 6

Related Questions