CommitGraphLoader: control CPF reading with an int

The commit graph loader follows the deprecated "readChangedPaths" flag
(boolean) to control the loading of the changed path filters
(CPF). Now there is a "changedPathsVersions" flag [1] with more values
to control this behavior (0 to ignore, -1 to load any version, n to
load version N).

Update the CommitGraphLoader.load() parameter from boolean to int and
follow the changedPathsVersion semantics. We translate callers from
"false" to 0 and "true" to -1, so this should be a no-op.

JGit has been writing CPF with version 2 in files tagged as version 1
(fixed in [2]). At reading time we cannot know if the v1 file has been
written from cgit (real v1) or jgit (mislabelled v2). To avoid
confusion, asking for v1 is not supported and disables the reading.

[1] https://git-scm.com/docs/git-commit-graph/2.55.0#Documentation/git-commit-graph.txt-commitGraphreadChangedPaths
[2] https://gerrithub.io/c/eclipse-jgit/jgit/+/1248257

Change-Id: I818f2bef78417d0b3c4bc7c399a527dc6a6a6964
diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphTest.java
index 4d05360..fd4838e 100644
--- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphTest.java
+++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphTest.java
@@ -15,6 +15,8 @@
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
@@ -225,6 +227,57 @@ public void testGraphComputeChangedPaths() throws Exception {
 		assertTrue(ccpf.maybeContains("d/f".getBytes(UTF_8)));
 	}
 
+	@Test
+	public void changedPathsVersion_hasCPF_disabled_returnNoCPF()
+			throws Exception {
+		RevCommit a = tr.commit(tr.tree(tr.file("d/f", tr.blob("a"))));
+		writeAndReadCommitGraph(Collections.singleton(a), true, 0);
+		assertNull(commitGraph
+				.getChangedPathFilter(commitGraph.findGraphPosition(a)));
+	}
+
+	@Test
+	public void changedPathsVersion_hasCPF_v2_returnCPF() throws Exception {
+		RevCommit a = tr.commit(tr.tree(tr.file("d/f", tr.blob("a"))));
+		writeAndReadCommitGraph(Collections.singleton(a), true, 2);
+		assertNotNull(commitGraph
+				.getChangedPathFilter(commitGraph.findGraphPosition(a)));
+	}
+
+	@Test
+	public void changedPathsVersion_noCPF_v2_returnNoCPF() throws Exception {
+		RevCommit a = tr.commit(tr.tree(tr.file("d/f", tr.blob("a"))));
+		writeAndReadCommitGraph(Collections.singleton(a), false, 2);
+		assertNull(commitGraph
+				.getChangedPathFilter(commitGraph.findGraphPosition(a)));
+	}
+
+	@Test
+	public void changedPathsVersion_v1_noCPF() throws Exception {
+		RevCommit a = tr.commit(tr.tree(tr.file("d/f", tr.blob("a"))));
+		// The generated commit-graph has bloom filter version 2, so version 1
+		// should not load it
+		writeAndReadCommitGraph(Collections.singleton(a), true, 1);
+		assertNull(commitGraph
+				.getChangedPathFilter(commitGraph.findGraphPosition(a)));
+	}
+
+	@Test
+	public void changedPathsVersion_hasCPF_any_returnCPF() throws Exception {
+		RevCommit a = tr.commit(tr.tree(tr.file("d/f", tr.blob("a"))));
+		writeAndReadCommitGraph(Collections.singleton(a), true, -1);
+		assertNotNull(commitGraph
+				.getChangedPathFilter(commitGraph.findGraphPosition(a)));
+	}
+
+	@Test
+	public void changedPathsVersion_noCPF_any_returnNoCPF() throws Exception {
+		RevCommit a = tr.commit(tr.tree(tr.file("d/f", tr.blob("a"))));
+		writeAndReadCommitGraph(Collections.singleton(a), false, -1);
+		assertNull(commitGraph
+				.getChangedPathFilter(commitGraph.findGraphPosition(a)));
+	}
+
 	void writeAndReadCommitGraph(Set<ObjectId> wants) throws Exception {
 		NullProgressMonitor m = NullProgressMonitor.INSTANCE;
 		try (RevWalk walk = new RevWalk(db)) {
@@ -238,6 +291,21 @@ void writeAndReadCommitGraph(Set<ObjectId> wants) throws Exception {
 		}
 	}
 
+	void writeAndReadCommitGraph(Set<ObjectId> wants, boolean write,
+			int changedPathsVersion) throws Exception {
+		NullProgressMonitor m = NullProgressMonitor.INSTANCE;
+		try (RevWalk walk = new RevWalk(db)) {
+			CommitGraphWriter writer = new CommitGraphWriter(
+					GraphCommits.fromWalk(m, wants, walk), write);
+			ByteArrayOutputStream os = new ByteArrayOutputStream();
+			writer.write(m, os);
+			InputStream inputStream = new ByteArrayInputStream(
+					os.toByteArray());
+			commitGraph = CommitGraphLoader.read(inputStream,
+					changedPathsVersion);
+		}
+	}
+
 	void verifyCommitGraph() throws Exception {
 		try (RevWalk walk = new RevWalk(db)) {
 			for (int i = 0; i < commitGraph.getCommitCnt(); i++) {
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphLoader.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphLoader.java
index 7e9220d..d05aaef 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphLoader.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/commitgraph/CommitGraphLoader.java
@@ -111,7 +111,7 @@ public static CommitGraph read(InputStream fd)
 			readChangedPathFilters = false;
 		}
 
-		return read(fd, readChangedPathFilters);
+		return read(fd, readChangedPathFilters ? -1 : 0);
 	}
 
 	/**
@@ -126,8 +126,9 @@ public static CommitGraph read(InputStream fd)
 	 *            buffered as some small IOs are performed against the stream.
 	 *            The caller is responsible for closing the stream.
 	 *
-	 * @param readChangedPathFilters
-	 *            enable reading bloom filter chunks.
+	 * @param changedPathsVersion
+	 *            the version of changed path bloom filters to read (-1 for any
+	 *            supported version, 0 to disable reading, 1 for v1, etc.).
 	 *
 	 * @return a copy of the commit-graph file in memory
 	 * @throws CommitGraphFormatException
@@ -135,8 +136,7 @@ public static CommitGraph read(InputStream fd)
 	 * @throws java.io.IOException
 	 *             the stream cannot be read.
 	 */
-	public static CommitGraph read(InputStream fd,
-			boolean readChangedPathFilters)
+	public static CommitGraph read(InputStream fd, int changedPathsVersion)
 			throws CommitGraphFormatException, IOException {
 		byte[] hdr = new byte[8];
 		IO.readFully(fd, hdr, 0, hdr.length);
@@ -183,6 +183,8 @@ public static CommitGraph read(InputStream fd,
 		}
 
 		CommitGraphBuilder builder = CommitGraphBuilder.builder();
+		byte[] bloomFilterIndex = null;
+		byte[] bloomFilterData = null;
 		for (int i = 0; i < numberOfChunks; i++) {
 			long chunkOffset = chunks.get(i).offset;
 			int chunkId = chunks.get(i).id;
@@ -193,7 +195,7 @@ public static CommitGraph read(InputStream fd,
 						JGitText.get().commitGraphFileIsTooLargeForJgit);
 			}
 
-			byte buffer[] = new byte[(int) len];
+			byte[] buffer = new byte[(int) len];
 			IO.readFully(fd, buffer, 0, buffer.length);
 
 			switch (chunkId) {
@@ -210,14 +212,20 @@ public static CommitGraph read(InputStream fd,
 				builder.addExtraList(buffer);
 				break;
 			case CHUNK_ID_BLOOM_FILTER_INDEX:
-				if (readChangedPathFilters) {
-					builder.addBloomFilterIndex(buffer);
+				if (bloomFilterIndex != null) {
+					throw new CommitGraphFormatException(MessageFormat.format(
+							JGitText.get().commitGraphChunkRepeated,
+							Integer.toHexString(chunkId)));
 				}
+				bloomFilterIndex = buffer;
 				break;
 			case CHUNK_ID_BLOOM_FILTER_DATA:
-				if (readChangedPathFilters) {
-					builder.addBloomFilterData(buffer);
+				if (bloomFilterData != null) {
+					throw new CommitGraphFormatException(MessageFormat.format(
+							JGitText.get().commitGraphChunkRepeated,
+							Integer.toHexString(chunkId)));
 				}
+				bloomFilterData = buffer;
 				break;
 			default:
 				LOG.warn(MessageFormat.format(
@@ -225,6 +233,25 @@ public static CommitGraph read(InputStream fd,
 						Integer.toHexString(chunkId)));
 			}
 		}
+
+		// A file with v1 could be v1 or v2 depending who created it (cgit or
+		// jgit). On top of that, JGit doesn't understand v1.
+		// If caller explicitly wants v1, act like there are no bloom filters.
+		if (changedPathsVersion == 0 || changedPathsVersion == 1) {
+			return builder.build();
+		}
+
+		if (bloomFilterIndex != null && bloomFilterData != null) {
+			if (bloomFilterData.length >= 4) {
+				int fileBloomVersion = (int) NB.decodeUInt32(bloomFilterData,
+						0);
+				if (changedPathsVersion == -1
+						|| changedPathsVersion == fileBloomVersion) {
+					builder.addBloomFilterIndex(bloomFilterIndex);
+					builder.addBloomFilterData(bloomFilterData);
+				}
+			}
+		}
 		return builder.build();
 	}
 
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
index dc7f320..530f3ed 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/dfs/DfsPackFile.java
@@ -1423,8 +1423,7 @@ private DfsBlockCache.Ref<CommitGraph> loadCommitGraph(DfsReader ctx,
 			long size;
 			CommitGraph cg;
 			try {
-				cg = CommitGraphLoader.read(alignTo8kBlocks(rc),
-						true);
+				cg = CommitGraphLoader.read(alignTo8kBlocks(rc), -1);
 			} finally {
 				size = rc.position();
 				ctx.stats.readCommitGraphBytes += size;