如何使用 JGit 将文件重置为特定提交?

How to reset a file to a particular commit with JGit?

请考虑我的本地存储库包含多个文件,在对某个文件的特定提交进行检出时,存储库中的其他文件已被删除。

我正在使用以下 API(git 是 git 存储库的实例)

git.checkout().setName(commitId).call()

这是检查特定文件的特定提交的正确方法吗?

您的调用重置了索引(并且可以删除您签出的新提交中不再存在的文件)

您可以在 jgit/porcelain/RevertChanges.java

中查找更精确的示例
 // revert the changes
 git.checkout().addPath(fileName).call();

你的情况:

git.checkout().setname(commitId).addPath(fileName).call()

setName() 的 JavaDoc 说

When only checking out paths and not switching branches, use setStartPoint(} to specify from which branch or commit to check out files.

对于 addPath(),它指出:

If this option is set, neither the setCreateBranch() nor setName() option is considered. In other words, these options are exclusive.

因此我认为你应该使用

git.checkout().addPath( ... ).setStartPoint( ... ).call();