如何使用 JGit 获取特定的提交

How to fetch a specific commit with JGit

我从 Retrieve specific commit from a remote Git repository 得知可以从远程 git 存储库获取特定提交。

但是,尝试从 JGit 这样做时失败了。对于同一个存储库,当我从终端 运行 git fetch origin 57eab609d9efda3b8ee370582c3762c0e721033d:HEAD 时,我想要的提交(及其所有祖先)是从远程存储库中获取的。但是,当我 运行 使用 JGit 执行以下操作时,出现异常:

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();

例外是org.eclipse.jgit.errors.TransportException: Remote does not have 57eab609d9efda3b8ee370582c3762c0e721033d available for fetch.

使用 Git 瓷器命令,您只能获取引用,而不是特定的提交。另见此处:Fetch specific commit from remote git repo

您提到的 post 仅解释了如何从远程获取特定引用(给定示例中的 refs/remotes/origin/branch)。我看不到特定提交(未被引用引用)的提取位置。

这同样适用于 JGit:需要为 FetchCommand 提供一个 refspec(因此得名 setRefSpecs())以从中获取。有了这些信息,JGit 将获取 refspec 指向的提交及其所有祖先。