假设我们在git存储库中有两个文件,path / to / file1.txt和path / to / file2.txt。 file1.txt首先提交,然后是file2.txt,因此它们属于具有不同SHA1的提交。我想使用jGit检索与每个文件对应的SHA1。这是我到目前为止的代码:
String localPath = "/path/to/repo";
Repository localRepo = new FileRepository(localPath + "/.git");
Ref headRef = localRepo.getRef("refs/heads/master");
RevWalk revWalk = new RevWalk(localRepo);
RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
TreeWalk tw = new TreeWalk(localRepo);
tw.addTree(headCommit.getTree());
tw.setRecursive(true);
HashMap<String, String> fileShas = new HashMap<String, String>();
RevWalk commitFinder = new RevWalk(localRepo);
while (tw.next()) {
ArrayList<PathFilter> filters = new ArrayList<PathFilter>();
filters.add(PathFilter.create(tw.getPathString()));
commitFinder.reset();
RevCommit iterHead = commitFinder.lookupCommit(headRef.getObjectId());
commitFinder.markStart(iterHead);
commitFinder.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(filters), TreeFilter.ANY_DIFF));
commitFinder.setRevFilter(MaxCountRevFilter.create(1));
RevCommit commit = commitFinder.next();
fileShas.put(tw.getPathString(), commit.getId().getName());
}
不幸的是,这不起作用。我得到第一个文件的正确SHA1,但不是第二个文件。看来commitFinder.reset();
没有做好自己的工作。如果我在每次迭代时创建一个新的RevWalk
,它可以工作,但速度非常慢。有什么想法reset()
无效?
答案 0 :(得分:0)
虽然这并没有回答这个问题,但我把调查结果放在这里是为了提高可读性。下面显示的测试中的getLatestModification
方法返回上次修改给定文件的提交的id。
虽然代码比原始代码段短,但问题仍然是reset
显然无法正常工作。
public class RevWalkResetLearningTest {
@Rule
public final TemporaryFolder tempFolder = new TemporaryFolder();
private Repository repository;
@Test
public void testReset() throws Exception {
RevWalk revWalk = new RevWalk( repository );
RevCommit beerCommit = getLastModification( revWalk, "plugins/emoji/public/images/beer.png" );
// RevCommit discourseCommit = getLastModification( new RevWalk( repository ), "images/discourse.png" );
RevCommit discourseCommit = getLastModification( revWalk, "images/discourse.png" );
assertEquals( "8278fdb9ddbc61eea9f6e6045b705106678ce532", beerCommit.name() );
assertEquals( "50cd44df2dec27c0834be4a2975fe175c3fac64f", discourseCommit.name() );
}
private RevCommit getLastModification( RevWalk revWalk, String path ) throws IOException {
revWalk.reset();
revWalk.markStart( revWalk.parseCommit( repository.resolve( "refs/heads/master" ) ) );
revWalk.setTreeFilter( AndTreeFilter.create( PathFilter.create( path ), TreeFilter.ANY_DIFF ) );
return revWalk.next();
}
@Before
public void setUp() throws Exception {
// Git git = Git.cloneRepository().setURI( "https://github.com/discourse/discourse.git" ).setDirectory( tempFolder.getRoot() ).call();
// repository = git.getRepository();
repository = new FileRepositoryBuilder().setMustExist( true ).setGitDir( new File( "/path/to/discourse/.git" ) ).build();
}
@After
public void tearDown() {
repository.close();
}
}
测试失败,因为discourseCommit
的commit-id与beerCommit
相同。如果我更改代码以便每次调用getLastModification
获得RevWalk
的新实例(请参阅注释行),则测试成功。
我建议打开bug report或向JGit mailing list寻求帮助。