Skip to content

Commit 8314626

Browse files
#213 Handle files with missing Git objects
1 parent 78bae44 commit 8314626

2 files changed

Lines changed: 252 additions & 14 deletions

File tree

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

Lines changed: 66 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,78 @@ 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());
138+
139+
if (stats.commitCount == 0 && stats.truncatedByMissingObjects) {
140+
// Shallow or partial clone: the path-filtered history is unreadable, but a
141+
// pathless walk only needs commit objects, so fall back to the total commit
142+
// history as a degraded change-proneness signal.
143+
log.warn(
144+
"No commits could be read for {} due to missing Git objects; "
145+
+ "falling back to the total repository commit count",
146+
path);
147+
stats = walkCommits(git.log().add(branchId).call());
148+
}
135149

136-
int commitCount = 0;
137-
int earliestCommit = Integer.MAX_VALUE;
138-
int mostRecentCommit = 0;
150+
if (stats.commitCount == 0) {
151+
return new ScmLogInfo(path, null, stats.earliestCommit, stats.earliestCommit, stats.commitCount);
152+
}
139153

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

151-
if (commitCount == 0) {
152-
return new ScmLogInfo(path, null, earliestCommit, earliestCommit, commitCount);
190+
return stats;
191+
}
192+
193+
private static boolean isCausedByMissingObject(Throwable throwable) {
194+
while (throwable != null) {
195+
if (throwable instanceof MissingObjectException) {
196+
return true;
197+
}
198+
throwable = throwable.getCause();
153199
}
200+
return false;
201+
}
154202

155-
return new ScmLogInfo(path, null, earliestCommit, mostRecentCommit, commitCount);
203+
private static class CommitWalkStats {
204+
int commitCount = 0;
205+
int earliestCommit = Integer.MAX_VALUE;
206+
int mostRecentCommit = 0;
207+
boolean truncatedByMissingObjects = false;
156208
}
157209

158210
// 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: 186 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,183 @@ 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 successive log commands return the given iterables; the underlying
129+
* repository is real so that HEAD resolution works.
130+
*/
131+
@SafeVarargs
132+
private final Git gitWithLogs(Iterable<RevCommit>... iterables) throws IOException, GitAPIException {
133+
Git mockGit = mock(Git.class);
134+
when(mockGit.getRepository()).thenReturn(repository);
135+
List<LogCommand> logCommands = new ArrayList<>();
136+
for (Iterable<RevCommit> revCommits : iterables) {
137+
LogCommand logCommand = mock(LogCommand.class);
138+
when(logCommand.add(any(ObjectId.class))).thenReturn(logCommand);
139+
when(logCommand.addPath(anyString())).thenReturn(logCommand);
140+
when(logCommand.call()).thenReturn(revCommits);
141+
logCommands.add(logCommand);
142+
}
143+
when(mockGit.log())
144+
.thenReturn(
145+
logCommands.get(0),
146+
logCommands.subList(1, logCommands.size()).toArray(new LogCommand[0]));
147+
return mockGit;
148+
}
149+
150+
/** An iterable that yields the given commits and then fails, mimicking a truncated walk. */
151+
private static Iterable<RevCommit> walkYieldingThenThrowing(List<RevCommit> commits, RuntimeException failure) {
152+
return () -> new Iterator<RevCommit>() {
153+
private final Iterator<RevCommit> delegate = commits.iterator();
154+
155+
@Override
156+
public boolean hasNext() {
157+
return true;
158+
}
159+
160+
@Override
161+
public RevCommit next() {
162+
if (delegate.hasNext()) {
163+
return delegate.next();
164+
}
165+
throw failure;
166+
}
167+
};
168+
}
169+
170+
private ObjectId headId() throws IOException {
171+
ObjectId head = repository.resolve("HEAD");
172+
return head == null ? ObjectId.fromString("1111111111111111111111111111111111111111") : head;
173+
}
174+
175+
@Test
176+
void testFileLogFallsBackToTotalCommitCountWhenFilteredWalkYieldsNothingDueToMissingObjects() throws Exception {
177+
String attributeHandler = "AttributeHandler.java";
178+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
179+
writeFile(attributeHandler, convertInputStreamToString(resourceAsStream));
180+
git.add().addFilepattern(".").call();
181+
RevCommit onlyCommit = git.commit().setMessage("message").call();
182+
183+
Iterable<RevCommit> failingFilteredWalk = walkYieldingThenThrowing(
184+
Collections.emptyList(),
185+
new RevWalkException(new MissingObjectException(headId(), Constants.OBJ_TREE)));
186+
Iterable<RevCommit> pathlessWalk = Collections.singletonList(onlyCommit);
187+
188+
GitLogReader gitLogReader = new GitLogReader(gitWithLogs(failingFilteredWalk, pathlessWalk));
189+
190+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog(attributeHandler));
191+
192+
Assertions.assertEquals(1, scmLogInfo.getCommitCount());
193+
Assertions.assertEquals(onlyCommit.getCommitTime(), scmLogInfo.getEarliestCommit());
194+
Assertions.assertEquals(onlyCommit.getCommitTime(), scmLogInfo.getMostRecentCommit());
195+
}
196+
197+
@Test
198+
void testFileLogWithMissingTreeFallsBackToTotalCommitCount() throws Exception {
199+
// Simulates a shallow clone whose tree objects are missing: the filtered walk
200+
// yields nothing, so fileLog falls back to the total (tree-independent) history.
201+
GitLogReader gitLogReader = new GitLogReader(git);
202+
203+
String attributeHandler = "AttributeHandler.java";
204+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
205+
String contents = convertInputStreamToString(resourceAsStream);
206+
207+
writeFile(attributeHandler, contents);
208+
git.add().addFilepattern(".").call();
209+
RevCommit firstCommit = git.commit().setMessage("message").call();
210+
211+
Thread.sleep(1000);
212+
213+
writeFile(attributeHandler, contents + "\n// second revision\n");
214+
git.add().addFilepattern(".").call();
215+
RevCommit secondCommit = git.commit().setMessage("message").call();
216+
217+
deleteLooseObject(secondCommit.getTree());
218+
219+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog(attributeHandler));
220+
221+
Assertions.assertEquals(2, scmLogInfo.getCommitCount());
222+
Assertions.assertEquals(firstCommit.getCommitTime(), scmLogInfo.getEarliestCommit());
223+
Assertions.assertEquals(secondCommit.getCommitTime(), scmLogInfo.getMostRecentCommit());
224+
}
225+
226+
@Test
227+
void testFileLogDoesNotFabricateHistoryForFileNeverCommitted() throws Exception {
228+
// An empty filtered walk with NO missing objects means the file simply has no
229+
// history: the total commit count must NOT be substituted.
230+
GitLogReader gitLogReader = new GitLogReader(git);
231+
232+
String attributeHandler = "AttributeHandler.java";
233+
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(attributeHandler);
234+
writeFile(attributeHandler, convertInputStreamToString(resourceAsStream));
235+
git.add().addFilepattern(".").call();
236+
git.commit().setMessage("message").call();
237+
238+
ScmLogInfo scmLogInfo = Assertions.assertDoesNotThrow(() -> gitLogReader.fileLog("NeverCommitted.java"));
239+
240+
Assertions.assertEquals(0, scmLogInfo.getCommitCount());
241+
}
242+
243+
private void deleteLooseObject(ObjectId objectId) throws IOException {
244+
String objectName = objectId.getName();
245+
File looseObject = new File(
246+
new File(repository.getDirectory(), "objects"),
247+
objectName.substring(0, 2) + '/' + objectName.substring(2));
248+
org.junit.jupiter.api.Assumptions.assumeTrue(
249+
looseObject.exists(), "loose object " + objectName + " should exist in a fresh repository");
250+
if (!looseObject.delete()) {
251+
throw new IOException("Unable to delete loose object " + looseObject);
252+
}
253+
}
254+
69255
@Test
70256
void testWalkFirstCommit() throws IOException, GitAPIException {
71257
GitLogReader gitLogReader = new GitLogReader(git);

0 commit comments

Comments
 (0)