Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check out specific revision from Git repository with JGit

Tags:

java

jgit

I am trying to use jGit to clone a repository and checkout a particular commit.

Assuming the commit hash is: 1e9ae842ca94f326215358917c620ac407323c81.

My first step is:

// Cloning the repository
    Git.cloneRepository()
        .setURI(remotePath)
        .setDirectory(localPath)
        .call();

I then found another question which suggested this approach:

git.checkout().
                setCreateBranch(true).
                setName("branchName").
                setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
                setStartPoint("origin/" + branchName).
                call();

But I'm unsure how to link the two together?

Any thoughts?

like image 709
MrD Avatar asked Jul 22 '14 16:07

MrD


People also ask

What is JGit used for?

JGit is a pure Java implementation of the Git version control system. It powers many Git related Java projects like the Git support in Eclipse or the Gerrit reviewer server. JGit is available as Java library and can be integrated into your project with the usual methods.

How do I checkout and check in github?

This is accomplished by entering the command 'git branch' in the command line. After entering the command you will be presented with a list of all available branches in your repository. These are the branches that you can switch to using the checkout command.


1 Answers

You will have to clone the repository first, thus your first step was right:

Git.cloneRepository().setURI(remotePath).setDirectory(localPath).call();

To just checkout a commit by its id you can call checkout like this:

git.checkout().setName("<id-to-commit>").call();

But note that this will result in a detached HEAD. To avoid this, you can tell checkout to create a new branch first that points to the commit and then checkout this branch.

git.checkout().setCreateBranch(true).setName("new-branch").setStartPoint("<id-to-commit>").call();

The API isn't very intuitive, but it does what it should.

like image 52
Rüdiger Herrmann Avatar answered Oct 23 '22 11:10

Rüdiger Herrmann