3

How to tell JGit to checkout its parent? For example, if I have a situation like the one below on the master branch:

c815b27 newestCommit (HEAD -> master, origin/master, master)
e46dcaf previousCommit
b2d6867 previousPreviousCommit

I would like to call a command from JGit that would look something like:

git.checkout().setName("c815b27~").call();

and would result in the state where HEAD would be moved to commit e46dcaf:

c815b27 newestCommit (origin/master, master)
e46dcaf previousCommit (HEAD)
b2d6867 previousPreviousCommit

However, when I call the above checkout statement nothing happens. I have also come across the following statement, which also does not move HEAD:

git.checkout().setStartPoint("c815b27~").call();

Any ideas how to achieve moving to the previous commit based on tilde (~) or caret (^) symbols, and whether is even possible with the JGit API?

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
chao
  • 1,893
  • 2
  • 23
  • 27

1 Answers1

3

First, you need to resolve the expression that points to the previous commit. Then you can checkout the resulting commit id.

For example:

ObjectId previousCommitId = git.getRepository().resolve( "HEAD^" );
git.checkout().setName( previousCommitId ).call();

Note that checking out a commit detaches HEAD.

Community
  • 1
  • 1
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79