Skip to content

Commit 79f1681

Browse files
Merge pull request #214 from refactorfirst/#213-handle-files-with-missing-git-objects
#213 Handle files with missing Git objects
2 parents aacd41b + 0c55444 commit 79f1681

2 files changed

Lines changed: 231 additions & 14 deletions

File tree

‎change-proneness-ranker/src/main/java/org/hjug/git/GitLogReader.java‎

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import org.eclipse.jgit.api.errors.GitAPIException;
1111
import org.eclipse.jgit.diff.DiffEntry;
1212
import org.eclipse.jgit.diff.DiffFormatter;
13+
import org.eclipse.jgit.errors.MissingObjectException;
14+
import org.eclipse.jgit.errors.RevWalkException;
1315
import org.eclipse.jgit.lib.*;
1416
import org.eclipse.jgit.revwalk.*;
1517
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
@@ -131,28 +133,65 @@ public String getRepoUrl() throws IOException {
131133
*/
132134
public ScmLogInfo fileLog(String path) throws GitAPIException, IOException {
133135
ObjectId branchId = gitRepository.resolve("HEAD");
134-
Iterable<RevCommit> revCommits = git.log().add(branchId).addPath(path).call();
136+
CommitWalkStats stats =
137+
walkCommits(git.log().add(branchId).addPath(path).call());
135138

136-
int commitCount = 0;
137-
int earliestCommit = Integer.MAX_VALUE;
138-
int mostRecentCommit = 0;
139+
if (stats.commitCount == 0) {
140+
return new ScmLogInfo(path, null, stats.earliestCommit, stats.earliestCommit, stats.commitCount);
141+
}
139142

140-
for (RevCommit revCommit : revCommits) {
141-
int commitTime = revCommit.getCommitTime();
142-
if (commitCount == 0) {
143-
mostRecentCommit = commitTime;
143+
return new ScmLogInfo(path, null, stats.earliestCommit, stats.mostRecentCommit, stats.commitCount);
144+
}
145+
146+
/**
147+
* Counts commits over the given walk. A missing Git object (e.g. in a shallow or
148+
* partial clone) must not fail the whole walk; the walk is truncated and the
149+
* commits read so far are returned instead.
150+
*/
151+
private static CommitWalkStats walkCommits(Iterable<RevCommit> revCommits) {
152+
CommitWalkStats stats = new CommitWalkStats();
153+
154+
try {
155+
for (RevCommit revCommit : revCommits) {
156+
int commitTime = revCommit.getCommitTime();
157+
if (stats.commitCount == 0) {
158+
stats.mostRecentCommit = commitTime;
159+
}
160+
if (commitTime < stats.earliestCommit) {
161+
stats.earliestCommit = commitTime;
162+
}
163+
stats.commitCount++;
144164
}
145-
if (commitTime < earliestCommit) {
146-
earliestCommit = commitTime;
165+
} catch (RevWalkException e) {
166+
// JGit wraps checked exceptions thrown mid-walk in a RevWalkException.
167+
if (isCausedByMissingObject(e)) {
168+
log.warn(
169+
"Missing Git object while reading history (shallow or partial clone?); "
170+
+ "reporting the {} commit(s) that could be read. Cause: {}",
171+
stats.commitCount,
172+
e.getMessage());
173+
} else {
174+
throw e;
147175
}
148-
commitCount++;
149176
}
150177

151-
if (commitCount == 0) {
152-
return new ScmLogInfo(path, null, earliestCommit, earliestCommit, commitCount);
178+
return stats;
179+
}
180+
181+
private static boolean isCausedByMissingObject(Throwable throwable) {
182+
while (throwable != null) {
183+
if (throwable instanceof MissingObjectException) {
184+
return true;
185+
}
186+
throwable = throwable.getCause();
153187
}
188+
return false;
189+
}
154190

155-
return new ScmLogInfo(path, null, earliestCommit, mostRecentCommit, commitCount);
191+
private static class CommitWalkStats {
192+
int commitCount = 0;
193+
int earliestCommit = Integer.MAX_VALUE;
194+
int mostRecentCommit = 0;
156195
}
157196

158197
// based on https://stackoverflow.com/questions/27361538/how-to-show-changes-between-commits-with-jgit

‎change-proneness-ranker/src/test/java/org/hjug/git/GitLogReaderTest.java‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
package org.hjug.git;
22

33
import static java.nio.charset.StandardCharsets.UTF_8;
4+
import static org.mockito.ArgumentMatchers.any;
5+
import static org.mockito.ArgumentMatchers.anyString;
6+
import static org.mockito.Mockito.mock;
7+
import static org.mockito.Mockito.when;
48

59
import java.io.*;
610
import java.util.*;
711
import org.eclipse.jgit.api.Git;
12+
import org.eclipse.jgit.api.LogCommand;
813
import org.eclipse.jgit.api.errors.GitAPIException;
14+
import org.eclipse.jgit.errors.MissingObjectException;
15+
import org.eclipse.jgit.errors.RevWalkException;
16+
import org.eclipse.jgit.lib.Constants;
17+
import org.eclipse.jgit.lib.ObjectId;
918
import org.eclipse.jgit.lib.Repository;
1019
import org.eclipse.jgit.revwalk.RevCommit;
1120
import org.junit.jupiter.api.AfterEach;
@@ -66,6 +75,175 @@ void testFileLog() throws IOException, GitAPIException, InterruptedException {
6675
Assertions.assertEquals(secondCommit.getCommitTime(), scmLogInfo.getMostRecentCommit());
6776
}
6877

78+
@Test
79+
void testFileLogReturnsPartialResultsWhenWalkFailsMidIteration() throws Exception {
80+
// A missing tree encountered mid-walk (e.g. in a partial clone) must not
81+
// discard the commits that were already read: fileLog should return the
82+
// partial results gathered before the walk failed.
83+
String attributeHandler = "AttributeHandler.java";
84+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
85+
String contents = convertInputStreamToString(resourceAsStream);
86+
87+
writeFile(attributeHandler, contents);
88+
git.add().addFilepattern(".").call();
89+
git.commit().setMessage("message").call();
90+
91+
Thread.sleep(1000);
92+
93+
writeFile(attributeHandler, contents + "\n// second revision\n");
94+
git.add().addFilepattern(".").call();
95+
RevCommit newestCommit = git.commit().setMessage("message").call();
96+
97+
Iterable<RevCommit> failingWalk = walkYieldingThenThrowing(
98+
List.of(newestCommit), new RevWalkException(new MissingObjectException(headId(), Constants.OBJ_TREE)));
99+
100+
GitLogReader gitLogReader = new GitLogReader(gitWithLogs(failingWalk));
101+
102+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog(attributeHandler));
103+
104+
Assertions.assertEquals(1, scmLogInfo.getCommitCount());
105+
Assertions.assertEquals(newestCommit.getCommitTime(), scmLogInfo.getEarliestCommit());
106+
Assertions.assertEquals(newestCommit.getCommitTime(), scmLogInfo.getMostRecentCommit());
107+
}
108+
109+
@Test
110+
void testFileLogRethrowsNonMissingObjectWalkFailures() throws Exception {
111+
// Guard against silencing unrelated walk failures: only missing objects
112+
// should be tolerated, anything else must still propagate.
113+
String attributeHandler = "AttributeHandler.java";
114+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
115+
writeFile(attributeHandler, convertInputStreamToString(resourceAsStream));
116+
git.add().addFilepattern(".").call();
117+
git.commit().setMessage("message").call();
118+
119+
Iterable<RevCommit> failingWalk =
120+
walkYieldingThenThrowing(Collections.emptyList(), new RevWalkException(new IOException("disk I/O")));
121+
122+
GitLogReader gitLogReader = new GitLogReader(gitWithLogs(failingWalk));
123+
124+
Assertions.assertThrows(RevWalkException.class, () -> gitLogReader.fileLog("AttributeHandler.java"));
125+
}
126+
127+
/**
128+
* A Git whose log command returns the given iterable; the underlying
129+
* repository is real so that HEAD resolution works.
130+
*/
131+
private final Git gitWithLogs(Iterable<RevCommit> revCommits) throws IOException, GitAPIException {
132+
Git mockGit = mock(Git.class);
133+
when(mockGit.getRepository()).thenReturn(repository);
134+
LogCommand logCommand = mock(LogCommand.class);
135+
when(logCommand.add(any(ObjectId.class))).thenReturn(logCommand);
136+
when(logCommand.addPath(anyString())).thenReturn(logCommand);
137+
when(logCommand.call()).thenReturn(revCommits);
138+
when(mockGit.log()).thenReturn(logCommand);
139+
return mockGit;
140+
}
141+
142+
/** An iterable that yields the given commits and then fails, mimicking a truncated walk. */
143+
private static Iterable<RevCommit> walkYieldingThenThrowing(List<RevCommit> commits, RuntimeException failure) {
144+
return () -> new Iterator<RevCommit>() {
145+
private final Iterator<RevCommit> delegate = commits.iterator();
146+
147+
@Override
148+
public boolean hasNext() {
149+
return true;
150+
}
151+
152+
@Override
153+
public RevCommit next() {
154+
if (delegate.hasNext()) {
155+
return delegate.next();
156+
}
157+
throw failure;
158+
}
159+
};
160+
}
161+
162+
private ObjectId headId() throws IOException {
163+
ObjectId head = repository.resolve("HEAD");
164+
return head == null ? ObjectId.fromString("1111111111111111111111111111111111111111") : head;
165+
}
166+
167+
@Test
168+
void testFileLogReturnsOnlyVerifiedPartialPathHistoryWhenFilteredWalkYieldsNothingDueToMissingObjects()
169+
throws Exception {
170+
String attributeHandler = "AttributeHandler.java";
171+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
172+
writeFile(attributeHandler, convertInputStreamToString(resourceAsStream));
173+
git.add().addFilepattern(".").call();
174+
RevCommit onlyCommit = git.commit().setMessage("message").call();
175+
176+
Iterable<RevCommit> failingFilteredWalk = walkYieldingThenThrowing(
177+
Collections.emptyList(),
178+
new RevWalkException(new MissingObjectException(headId(), Constants.OBJ_TREE)));
179+
180+
GitLogReader gitLogReader = new GitLogReader(gitWithLogs(failingFilteredWalk));
181+
182+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog(attributeHandler));
183+
184+
// When the filtered walk yields nothing due to missing objects, return only the verified partial results
185+
// (which in this case is zero commits) rather than falling back to total repository history
186+
Assertions.assertEquals(0, scmLogInfo.getCommitCount());
187+
}
188+
189+
@Test
190+
void testFileLogReturnsOnlyVerifiedPartialPathHistoryWithMissingTree() throws Exception {
191+
// Simulates a shallow clone whose tree objects are missing: the filtered walk
192+
// may yield zero results due to missing objects, but should not fall back to total history.
193+
GitLogReader gitLogReader = new GitLogReader(git);
194+
195+
String attributeHandler = "AttributeHandler.java";
196+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
197+
String contents = convertInputStreamToString(resourceAsStream);
198+
199+
writeFile(attributeHandler, contents);
200+
git.add().addFilepattern(".").call();
201+
RevCommit firstCommit = git.commit().setMessage("message").call();
202+
203+
Thread.sleep(1000);
204+
205+
writeFile(attributeHandler, contents + "\n// second revision\n");
206+
git.add().addFilepattern(".").call();
207+
RevCommit secondCommit = git.commit().setMessage("message").call();
208+
209+
deleteLooseObject(secondCommit.getTree());
210+
211+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog(attributeHandler));
212+
213+
// With missing tree objects, the filtered walk may yield zero verified partial results
214+
// rather than falling back to total repository history
215+
Assertions.assertEquals(0, scmLogInfo.getCommitCount());
216+
}
217+
218+
@Test
219+
void testFileLogDoesNotFabricateHistoryForFileNeverCommitted() throws Exception {
220+
// An empty filtered walk with NO missing objects means the file simply has no
221+
// history: the total commit count must NOT be substituted.
222+
GitLogReader gitLogReader = new GitLogReader(git);
223+
224+
String attributeHandler = "AttributeHandler.java";
225+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
226+
writeFile(attributeHandler, convertInputStreamToString(resourceAsStream));
227+
git.add().addFilepattern(".").call();
228+
git.commit().setMessage("message").call();
229+
230+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog("NeverCommitted.java"));
231+
232+
Assertions.assertEquals(0, scmLogInfo.getCommitCount());
233+
}
234+
235+
private void deleteLooseObject(ObjectId objectId) throws IOException {
236+
String objectName = objectId.getName();
237+
File looseObject = new File(
238+
new File(repository.getDirectory(), "objects"),
239+
objectName.substring(0, 2) + '/' + objectName.substring(2));
240+
org.junit.jupiter.api.Assumptions.assumeTrue(
241+
looseObject.exists(), "loose object " + objectName + " should exist in a fresh repository");
242+
if (!looseObject.delete()) {
243+
throw new IOException("Unable to delete loose object " + looseObject);
244+
}
245+
}
246+
69247
@Test
70248
void testWalkFirstCommit() throws IOException, GitAPIException {
71249
GitLogReader gitLogReader = new GitLogReader(git);

0 commit comments

Comments
 (0)