Alaa Nassef
Alaa Nassef

Reputation: 280

How to fetch a specific commit with JGit

I know from Retrieve specific commit from a remote Git repository that it's possible to fetch a specific commit from a remote git repository.

However, trying to do so from JGit, it's failing. For the same repository, when I run git fetch origin 57eab609d9efda3b8ee370582c3762c0e721033d:HEAD from terminal, the commit I want (with all its ancestors) is fetched from the remote repository. However, when I run the following using JGit, I get an exception:

RefSpec refSpec = new RefSpec()
    .setSourceDestination(commitId, HEAD)
    .setForceUpdate(true);
refs = Lists.newArrayList(refSpec);
git.fetch().setRemote(GIT_REMOTE_NAME)
    .setTimeout(REMOTE_FETCH_TIMEOUT)
    .setTransportConfigCallback(transportConfigurer)
    .setCredentialsProvider(gitCredentials)
    .setTagOpt(TagOpt.FETCH_TAGS)
    .setRefSpecs(refs)
    .call();

The exception is org.eclipse.jgit.errors.TransportException: Remote does not have 57eab609d9efda3b8ee370582c3762c0e721033d available for fetch.

Upvotes: 2

Views: 1762

Answers (1)

Rüdiger Herrmann
Rüdiger Herrmann

Reputation: 20985

With Git porcelain commands, you can only fetch refs, not specific commits. See also here: Fetch specific commit from remote git repo

The post you refer to only explains how to fetch a specific ref (refs/remotes/origin/branch in the given example) from a remote. I can't see where a specific commit (that is not referred to by a ref) is fetched.

The same applies to JGit: the FetchCommand need to be given a refspec (hence the name setRefSpecs()) to fetch from. With that information, JGit will fetch the commit to which the refspec points to and all its ancestors.

Upvotes: 3

Related Questions