test_commit_graph.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. # test_commit_graph.py -- Tests for commit graph functionality
  2. # Copyright (C) 2024 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. """Tests for Git commit graph functionality."""
  10. import io
  11. import os
  12. import struct
  13. import tempfile
  14. import unittest
  15. from dulwich.commit_graph import (
  16. CHUNK_COMMIT_DATA,
  17. CHUNK_OID_FANOUT,
  18. CHUNK_OID_LOOKUP,
  19. COMMIT_GRAPH_SIGNATURE,
  20. COMMIT_GRAPH_VERSION,
  21. HASH_VERSION_SHA1,
  22. CommitGraph,
  23. CommitGraphChunk,
  24. CommitGraphEntry,
  25. find_commit_graph_file,
  26. generate_commit_graph,
  27. get_reachable_commits,
  28. read_commit_graph,
  29. )
  30. class CommitGraphEntryTests(unittest.TestCase):
  31. """Tests for CommitGraphEntry."""
  32. def test_init(self) -> None:
  33. commit_id = b"a" * 40
  34. tree_id = b"b" * 40
  35. parents = [b"c" * 40, b"d" * 40]
  36. generation = 42
  37. commit_time = 1234567890
  38. entry = CommitGraphEntry(commit_id, tree_id, parents, generation, commit_time)
  39. self.assertEqual(entry.commit_id, commit_id)
  40. self.assertEqual(entry.tree_id, tree_id)
  41. self.assertEqual(entry.parents, parents)
  42. self.assertEqual(entry.generation, generation)
  43. self.assertEqual(entry.commit_time, commit_time)
  44. def test_repr(self) -> None:
  45. entry = CommitGraphEntry(b"a" * 40, b"b" * 40, [], 1, 1000)
  46. repr_str = repr(entry)
  47. self.assertIn("CommitGraphEntry", repr_str)
  48. self.assertIn("generation=1", repr_str)
  49. class CommitGraphChunkTests(unittest.TestCase):
  50. """Tests for CommitGraphChunk."""
  51. def test_init(self) -> None:
  52. chunk = CommitGraphChunk(b"TEST", b"test data")
  53. self.assertEqual(chunk.chunk_id, b"TEST")
  54. self.assertEqual(chunk.data, b"test data")
  55. def test_repr(self) -> None:
  56. chunk = CommitGraphChunk(b"TEST", b"x" * 100)
  57. repr_str = repr(chunk)
  58. self.assertIn("CommitGraphChunk", repr_str)
  59. self.assertIn("size=100", repr_str)
  60. class CommitGraphTests(unittest.TestCase):
  61. """Tests for CommitGraph."""
  62. def test_init(self) -> None:
  63. graph = CommitGraph()
  64. self.assertEqual(graph.hash_version, HASH_VERSION_SHA1)
  65. self.assertEqual(len(graph.entries), 0)
  66. self.assertEqual(len(graph.chunks), 0)
  67. def test_len(self) -> None:
  68. graph = CommitGraph()
  69. self.assertEqual(len(graph), 0)
  70. # Add a dummy entry
  71. entry = CommitGraphEntry(b"a" * 40, b"b" * 40, [], 1, 1000)
  72. graph.entries.append(entry)
  73. self.assertEqual(len(graph), 1)
  74. def test_iter(self) -> None:
  75. graph = CommitGraph()
  76. entry1 = CommitGraphEntry(b"a" * 40, b"b" * 40, [], 1, 1000)
  77. entry2 = CommitGraphEntry(b"c" * 40, b"d" * 40, [], 2, 2000)
  78. graph.entries.extend([entry1, entry2])
  79. entries = list(graph)
  80. self.assertEqual(len(entries), 2)
  81. self.assertEqual(entries[0], entry1)
  82. self.assertEqual(entries[1], entry2)
  83. def test_get_entry_by_oid_missing(self) -> None:
  84. graph = CommitGraph()
  85. result = graph.get_entry_by_oid(b"f" * 40)
  86. self.assertIsNone(result)
  87. def test_get_generation_number_missing(self) -> None:
  88. graph = CommitGraph()
  89. result = graph.get_generation_number(b"f" * 40)
  90. self.assertIsNone(result)
  91. def test_get_parents_missing(self) -> None:
  92. graph = CommitGraph()
  93. result = graph.get_parents(b"f" * 40)
  94. self.assertIsNone(result)
  95. def test_from_invalid_signature(self) -> None:
  96. data = b"XXXX" + b"\\x00" * 100
  97. f = io.BytesIO(data)
  98. try:
  99. with self.assertRaises(ValueError) as cm:
  100. CommitGraph.from_file(f)
  101. self.assertIn("Invalid commit graph signature", str(cm.exception))
  102. finally:
  103. f.close()
  104. def test_from_invalid_version(self) -> None:
  105. data = COMMIT_GRAPH_SIGNATURE + struct.pack(">B", 99) + b"\\x00" * 100
  106. f = io.BytesIO(data)
  107. try:
  108. with self.assertRaises(ValueError) as cm:
  109. CommitGraph.from_file(f)
  110. self.assertIn("Unsupported commit graph version", str(cm.exception))
  111. finally:
  112. f.close()
  113. def test_from_invalid_hash_version(self) -> None:
  114. data = (
  115. COMMIT_GRAPH_SIGNATURE
  116. + struct.pack(">B", COMMIT_GRAPH_VERSION)
  117. + struct.pack(">B", 99) # Invalid hash version
  118. + b"\\x00" * 100
  119. )
  120. f = io.BytesIO(data)
  121. try:
  122. with self.assertRaises(ValueError) as cm:
  123. CommitGraph.from_file(f)
  124. self.assertIn("Unsupported hash version", str(cm.exception))
  125. finally:
  126. f.close()
  127. def create_minimal_commit_graph_data(self) -> bytes:
  128. """Create minimal valid commit graph data for testing."""
  129. # Create the data in order and calculate offsets properly
  130. # Header: signature + version + hash_version + num_chunks + base_graph_count
  131. header = (
  132. COMMIT_GRAPH_SIGNATURE
  133. + struct.pack(">B", COMMIT_GRAPH_VERSION)
  134. + struct.pack(">B", HASH_VERSION_SHA1)
  135. + struct.pack(">B", 3) # 3 chunks
  136. + struct.pack(">B", 0)
  137. ) # 0 base graphs
  138. # Table of contents: 4 entries (3 chunks + terminator) = 4 * 12 = 48 bytes
  139. toc_size = 4 * 12
  140. # Calculate chunk offsets from start of file
  141. header_size = 8
  142. chunk1_offset = header_size + toc_size # OID Fanout
  143. chunk2_offset = chunk1_offset + 256 * 4 # OID Lookup (after fanout)
  144. chunk3_offset = chunk2_offset + 20 # Commit Data (after 1 commit * 20 bytes)
  145. terminator_offset = (
  146. chunk3_offset + 36
  147. ) # After commit data (1 commit * 36 bytes)
  148. # Build table of contents
  149. toc = (
  150. CHUNK_OID_FANOUT
  151. + struct.pack(">Q", chunk1_offset)
  152. + CHUNK_OID_LOOKUP
  153. + struct.pack(">Q", chunk2_offset)
  154. + CHUNK_COMMIT_DATA
  155. + struct.pack(">Q", chunk3_offset)
  156. + b"\x00\x00\x00\x00"
  157. + struct.pack(">Q", terminator_offset)
  158. )
  159. # OID Fanout chunk (256 * 4 bytes)
  160. fanout = b""
  161. for i in range(256):
  162. if i < 0xAA: # Our test commit starts with 0xaa
  163. fanout += struct.pack(">L", 0)
  164. else:
  165. fanout += struct.pack(">L", 1) # 1 commit total
  166. # OID Lookup chunk (1 commit = 20 bytes)
  167. commit_oid = b"\xaa" + b"\x00" * 19
  168. oid_lookup = commit_oid
  169. # Commit Data chunk (1 commit = 20 + 16 = 36 bytes)
  170. tree_oid = b"\xbb" + b"\x00" * 19
  171. parent1_pos = 0x70000000 # GRAPH_PARENT_MISSING
  172. parent2_pos = 0x70000000 # GRAPH_PARENT_MISSING
  173. generation = 1
  174. commit_time = 1234567890
  175. gen_and_time = (generation << 2) | (commit_time >> 32)
  176. commit_data = (
  177. tree_oid
  178. + struct.pack(">LL", parent1_pos, parent2_pos)
  179. + struct.pack(">LL", gen_and_time, commit_time & 0xFFFFFFFF)
  180. )
  181. return header + toc + fanout + oid_lookup + commit_data
  182. def test_from_minimal_valid_file(self) -> None:
  183. """Test parsing a minimal but valid commit graph file."""
  184. data = self.create_minimal_commit_graph_data()
  185. f = io.BytesIO(data)
  186. graph = CommitGraph.from_file(f)
  187. self.assertEqual(graph.hash_version, HASH_VERSION_SHA1)
  188. self.assertEqual(len(graph), 1)
  189. # Check the parsed entry
  190. entry = graph.entries[0]
  191. self.assertEqual(entry.commit_id, b"aa" + b"00" * 19)
  192. self.assertEqual(entry.tree_id, b"bb" + b"00" * 19)
  193. self.assertEqual(entry.parents, []) # No parents
  194. self.assertEqual(entry.generation, 1)
  195. self.assertEqual(entry.commit_time, 1234567890)
  196. # Test lookup methods
  197. commit_oid = b"aa" + b"00" * 19
  198. self.assertEqual(graph.get_generation_number(commit_oid), 1)
  199. self.assertEqual(graph.get_parents(commit_oid), [])
  200. self.assertIsNotNone(graph.get_entry_by_oid(commit_oid))
  201. def test_missing_required_chunks(self) -> None:
  202. """Test error handling for missing required chunks."""
  203. # Create data with header but no chunks
  204. header = (
  205. COMMIT_GRAPH_SIGNATURE
  206. + struct.pack(">B", COMMIT_GRAPH_VERSION)
  207. + struct.pack(">B", HASH_VERSION_SHA1)
  208. + struct.pack(">B", 0) # 0 chunks
  209. + struct.pack(">B", 0)
  210. )
  211. # TOC with just terminator
  212. toc = b"\\x00\\x00\\x00\\x00" + struct.pack(">Q", 12)
  213. data = header + toc
  214. f = io.BytesIO(data)
  215. with self.assertRaises(ValueError) as cm:
  216. CommitGraph.from_file(f)
  217. self.assertIn("Missing required OID lookup chunk", str(cm.exception))
  218. def test_write_empty_graph_raises(self) -> None:
  219. """Test that writing empty graph raises ValueError."""
  220. graph = CommitGraph()
  221. f = io.BytesIO()
  222. with self.assertRaises(ValueError):
  223. graph.write_to_file(f)
  224. def test_write_and_read_round_trip(self) -> None:
  225. """Test writing and reading a commit graph."""
  226. # Create a simple commit graph
  227. graph = CommitGraph()
  228. entry = CommitGraphEntry(
  229. commit_id=b"aa" + b"00" * 19,
  230. tree_id=b"bb" + b"00" * 19,
  231. parents=[],
  232. generation=1,
  233. commit_time=1234567890,
  234. )
  235. graph.entries.append(entry)
  236. graph._oid_to_index = {bytes.fromhex(entry.commit_id.decode()): 0}
  237. # Write to bytes
  238. f = io.BytesIO()
  239. graph.write_to_file(f)
  240. # Read back
  241. f.seek(0)
  242. read_graph = CommitGraph.from_file(f)
  243. # Verify
  244. self.assertEqual(len(read_graph), 1)
  245. read_entry = read_graph.entries[0]
  246. self.assertEqual(read_entry.commit_id, entry.commit_id)
  247. self.assertEqual(read_entry.tree_id, entry.tree_id)
  248. self.assertEqual(read_entry.parents, entry.parents)
  249. self.assertEqual(read_entry.generation, entry.generation)
  250. self.assertEqual(read_entry.commit_time, entry.commit_time)
  251. class CommitGraphFileOperationsTests(unittest.TestCase):
  252. """Tests for commit graph file operations."""
  253. def setUp(self) -> None:
  254. self.tempdir = tempfile.mkdtemp()
  255. def tearDown(self) -> None:
  256. import shutil
  257. shutil.rmtree(self.tempdir, ignore_errors=True)
  258. def test_read_commit_graph_missing_file(self) -> None:
  259. """Test reading from non-existent file."""
  260. missing_path = os.path.join(self.tempdir, "missing.graph")
  261. result = read_commit_graph(missing_path)
  262. self.assertIsNone(result)
  263. def test_read_commit_graph_invalid_file(self) -> None:
  264. """Test reading from invalid file."""
  265. invalid_path = os.path.join(self.tempdir, "invalid.graph")
  266. with open(invalid_path, "wb") as f:
  267. f.write(b"invalid data")
  268. with self.assertRaises(ValueError):
  269. read_commit_graph(invalid_path)
  270. def test_find_commit_graph_file_missing(self) -> None:
  271. """Test finding commit graph file when it doesn't exist."""
  272. result = find_commit_graph_file(self.tempdir)
  273. self.assertIsNone(result)
  274. def test_find_commit_graph_file_standard_location(self) -> None:
  275. """Test finding commit graph file in standard location."""
  276. # Create .git/objects/info/commit-graph
  277. objects_dir = os.path.join(self.tempdir, "objects")
  278. info_dir = os.path.join(objects_dir, "info")
  279. os.makedirs(info_dir)
  280. graph_path = os.path.join(info_dir, "commit-graph")
  281. with open(graph_path, "wb") as f:
  282. f.write(b"dummy")
  283. result = find_commit_graph_file(self.tempdir)
  284. self.assertEqual(result, graph_path.encode())
  285. def test_find_commit_graph_file_chain_location(self) -> None:
  286. """Test finding commit graph file in chain location."""
  287. # Create .git/objects/info/commit-graphs/graph-{hash}.graph
  288. objects_dir = os.path.join(self.tempdir, "objects")
  289. info_dir = os.path.join(objects_dir, "info")
  290. graphs_dir = os.path.join(info_dir, "commit-graphs")
  291. os.makedirs(graphs_dir)
  292. graph_path = os.path.join(graphs_dir, "graph-abc123.graph")
  293. with open(graph_path, "wb") as f:
  294. f.write(b"dummy")
  295. result = find_commit_graph_file(self.tempdir)
  296. self.assertEqual(result, graph_path.encode())
  297. def test_find_commit_graph_file_prefers_standard(self) -> None:
  298. """Test that standard location is preferred over chain location."""
  299. # Create both locations
  300. objects_dir = os.path.join(self.tempdir, "objects")
  301. info_dir = os.path.join(objects_dir, "info")
  302. graphs_dir = os.path.join(info_dir, "commit-graphs")
  303. os.makedirs(info_dir)
  304. os.makedirs(graphs_dir)
  305. # Standard location
  306. standard_path = os.path.join(info_dir, "commit-graph")
  307. with open(standard_path, "wb") as f:
  308. f.write(b"standard")
  309. # Chain location
  310. chain_path = os.path.join(graphs_dir, "graph-abc123.graph")
  311. with open(chain_path, "wb") as f:
  312. f.write(b"chain")
  313. result = find_commit_graph_file(self.tempdir)
  314. self.assertEqual(result, standard_path.encode())
  315. class CommitGraphGenerationTests(unittest.TestCase):
  316. """Tests for commit graph generation functionality."""
  317. def setUp(self) -> None:
  318. self.tempdir = tempfile.mkdtemp()
  319. def tearDown(self) -> None:
  320. import shutil
  321. shutil.rmtree(self.tempdir, ignore_errors=True)
  322. def test_generate_commit_graph_empty(self) -> None:
  323. """Test generating commit graph with no commits."""
  324. from dulwich.object_store import MemoryObjectStore
  325. object_store = MemoryObjectStore()
  326. graph = generate_commit_graph(object_store, [])
  327. self.assertEqual(len(graph), 0)
  328. def test_generate_commit_graph_single_commit(self) -> None:
  329. """Test generating commit graph with single commit."""
  330. from dulwich.object_store import MemoryObjectStore
  331. from dulwich.objects import Commit, Tree
  332. object_store = MemoryObjectStore()
  333. # Create a tree and commit
  334. tree = Tree()
  335. object_store.add_object(tree)
  336. commit = Commit()
  337. commit.tree = tree.id
  338. commit.author = b"Test Author <test@example.com>"
  339. commit.committer = b"Test Author <test@example.com>"
  340. commit.commit_time = commit.author_time = 1234567890
  341. commit.commit_timezone = commit.author_timezone = 0
  342. commit.message = b"Test commit"
  343. object_store.add_object(commit)
  344. # Generate graph
  345. graph = generate_commit_graph(object_store, [commit.id])
  346. self.assertEqual(len(graph), 1)
  347. entry = graph.entries[0]
  348. self.assertEqual(entry.commit_id, commit.id)
  349. self.assertEqual(entry.tree_id, commit.tree)
  350. self.assertEqual(entry.parents, [])
  351. self.assertEqual(entry.generation, 1)
  352. self.assertEqual(entry.commit_time, 1234567890)
  353. def test_get_reachable_commits(self) -> None:
  354. """Test getting reachable commits."""
  355. from dulwich.object_store import MemoryObjectStore
  356. from dulwich.objects import Commit, Tree
  357. object_store = MemoryObjectStore()
  358. # Create tree
  359. tree = Tree()
  360. object_store.add_object(tree)
  361. # Create commit chain: commit1 -> commit2
  362. commit1 = Commit()
  363. commit1.tree = tree.id
  364. commit1.author = commit1.committer = b"Test <test@example.com>"
  365. commit1.commit_time = commit1.author_time = 1234567890
  366. commit1.commit_timezone = commit1.author_timezone = 0
  367. commit1.message = b"First commit"
  368. object_store.add_object(commit1)
  369. commit2 = Commit()
  370. commit2.tree = tree.id
  371. commit2.parents = [commit1.id]
  372. commit2.author = commit2.committer = b"Test <test@example.com>"
  373. commit2.commit_time = commit2.author_time = 1234567891
  374. commit2.commit_timezone = commit2.author_timezone = 0
  375. commit2.message = b"Second commit"
  376. object_store.add_object(commit2)
  377. # Get reachable commits from commit2
  378. reachable = get_reachable_commits(object_store, [commit2.id])
  379. # Should include both commits
  380. self.assertEqual(len(reachable), 2)
  381. self.assertIn(commit1.id, reachable)
  382. self.assertIn(commit2.id, reachable)
  383. def test_write_commit_graph_to_file(self) -> None:
  384. """Test writing commit graph to file."""
  385. from dulwich.object_store import DiskObjectStore
  386. from dulwich.objects import Commit, Tree
  387. # Create a disk object store
  388. object_store_path = os.path.join(self.tempdir, "objects")
  389. os.makedirs(object_store_path, exist_ok=True)
  390. object_store = DiskObjectStore(object_store_path)
  391. # Create a tree and commit
  392. tree = Tree()
  393. object_store.add_object(tree)
  394. commit = Commit()
  395. commit.tree = tree.id
  396. commit.author = b"Test Author <test@example.com>"
  397. commit.committer = b"Test Author <test@example.com>"
  398. commit.commit_time = commit.author_time = 1234567890
  399. commit.commit_timezone = commit.author_timezone = 0
  400. commit.message = b"Test commit"
  401. object_store.add_object(commit)
  402. # Write commit graph using ObjectStore method
  403. object_store.write_commit_graph([commit.id], reachable=False)
  404. # Verify file was created
  405. graph_path = os.path.join(object_store_path, "info", "commit-graph")
  406. self.assertTrue(os.path.exists(graph_path))
  407. # Read back and verify
  408. graph = read_commit_graph(graph_path)
  409. self.assertIsNotNone(graph)
  410. assert graph is not None # For mypy
  411. self.assertEqual(len(graph), 1)
  412. entry = graph.entries[0]
  413. self.assertEqual(entry.commit_id, commit.id)
  414. self.assertEqual(entry.tree_id, commit.tree)
  415. def test_object_store_commit_graph_methods(self) -> None:
  416. """Test ObjectStore commit graph methods."""
  417. from dulwich.object_store import DiskObjectStore
  418. from dulwich.objects import Commit, Tree
  419. # Create a disk object store
  420. object_store_path = os.path.join(self.tempdir, "objects")
  421. os.makedirs(object_store_path, exist_ok=True)
  422. object_store = DiskObjectStore(object_store_path)
  423. # Initially no commit graph
  424. self.assertIsNone(object_store.get_commit_graph()) # type: ignore[no-untyped-call]
  425. # Create a tree and commit
  426. tree = Tree()
  427. object_store.add_object(tree)
  428. commit = Commit()
  429. commit.tree = tree.id
  430. commit.author = b"Test Author <test@example.com>"
  431. commit.committer = b"Test Author <test@example.com>"
  432. commit.commit_time = commit.author_time = 1234567890
  433. commit.commit_timezone = commit.author_timezone = 0
  434. commit.message = b"Test commit"
  435. object_store.add_object(commit)
  436. # Write commit graph (disable reachable to avoid traversal issue)
  437. object_store.write_commit_graph([commit.id], reachable=False)
  438. # Now should have commit graph
  439. self.assertIsNotNone(object_store.get_commit_graph()) # type: ignore[no-untyped-call]
  440. # Test update (should still have commit graph)
  441. object_store.write_commit_graph()
  442. self.assertIsNot(None, object_store.get_commit_graph()) # type: ignore[no-untyped-call]
  443. def test_parents_provider_commit_graph_integration(self) -> None:
  444. """Test that ParentsProvider uses commit graph when available."""
  445. from dulwich.object_store import DiskObjectStore
  446. from dulwich.objects import Commit, Tree
  447. from dulwich.repo import ParentsProvider
  448. # Create a disk object store
  449. object_store_path = os.path.join(self.tempdir, "objects")
  450. os.makedirs(object_store_path, exist_ok=True)
  451. object_store = DiskObjectStore(object_store_path)
  452. # Create a tree and two commits
  453. tree = Tree()
  454. object_store.add_object(tree)
  455. # First commit (no parents)
  456. commit1 = Commit()
  457. commit1.tree = tree.id
  458. commit1.author = commit1.committer = b"Test <test@example.com>"
  459. commit1.commit_time = commit1.author_time = 1234567890
  460. commit1.commit_timezone = commit1.author_timezone = 0
  461. commit1.message = b"First commit"
  462. object_store.add_object(commit1)
  463. # Second commit (child of first)
  464. commit2 = Commit()
  465. commit2.tree = tree.id
  466. commit2.parents = [commit1.id]
  467. commit2.author = commit2.committer = b"Test <test@example.com>"
  468. commit2.commit_time = commit2.author_time = 1234567891
  469. commit2.commit_timezone = commit2.author_timezone = 0
  470. commit2.message = b"Second commit"
  471. object_store.add_object(commit2)
  472. # Write commit graph
  473. object_store.write_commit_graph([commit1.id, commit2.id], reachable=False)
  474. # Test ParentsProvider with commit graph
  475. provider = ParentsProvider(object_store)
  476. # Verify commit graph is loaded
  477. self.assertIsNotNone(provider.commit_graph)
  478. # Test parent lookups
  479. parents1 = provider.get_parents(commit1.id) # type: ignore[no-untyped-call]
  480. self.assertEqual(parents1, [])
  481. parents2 = provider.get_parents(commit2.id) # type: ignore[no-untyped-call]
  482. self.assertEqual(parents2, [commit1.id])
  483. # Test fallback behavior by creating provider without commit graph
  484. object_store_no_graph_path = os.path.join(self.tempdir, "objects2")
  485. os.makedirs(object_store_no_graph_path, exist_ok=True)
  486. object_store_no_graph = DiskObjectStore(object_store_no_graph_path)
  487. object_store_no_graph.add_object(tree)
  488. object_store_no_graph.add_object(commit1)
  489. object_store_no_graph.add_object(commit2)
  490. provider_no_graph = ParentsProvider(object_store_no_graph)
  491. self.assertIsNone(provider_no_graph.commit_graph)
  492. # Should still work via commit object fallback
  493. parents1_fallback = provider_no_graph.get_parents(commit1.id) # type: ignore[no-untyped-call]
  494. self.assertEqual(parents1_fallback, [])
  495. parents2_fallback = provider_no_graph.get_parents(commit2.id) # type: ignore[no-untyped-call]
  496. self.assertEqual(parents2_fallback, [commit1.id])
  497. def test_graph_operations_use_commit_graph(self) -> None:
  498. """Test that graph operations use commit graph when available."""
  499. from dulwich.graph import can_fast_forward, find_merge_base
  500. from dulwich.object_store import DiskObjectStore
  501. from dulwich.objects import Commit, Tree
  502. from dulwich.repo import Repo
  503. # Create a disk object store
  504. object_store_path = os.path.join(self.tempdir, "objects")
  505. os.makedirs(object_store_path, exist_ok=True)
  506. object_store = DiskObjectStore(object_store_path)
  507. # Create a tree and a more complex commit graph for testing
  508. tree = Tree()
  509. object_store.add_object(tree)
  510. # Create commit chain: commit1 -> commit2 -> commit3
  511. # \-> commit4 -> commit5 (merge)
  512. commit1 = Commit()
  513. commit1.tree = tree.id
  514. commit1.author = commit1.committer = b"Test <test@example.com>"
  515. commit1.commit_time = commit1.author_time = 1234567890
  516. commit1.commit_timezone = commit1.author_timezone = 0
  517. commit1.message = b"First commit"
  518. object_store.add_object(commit1)
  519. commit2 = Commit()
  520. commit2.tree = tree.id
  521. commit2.parents = [commit1.id]
  522. commit2.author = commit2.committer = b"Test <test@example.com>"
  523. commit2.commit_time = commit2.author_time = 1234567891
  524. commit2.commit_timezone = commit2.author_timezone = 0
  525. commit2.message = b"Second commit"
  526. object_store.add_object(commit2)
  527. commit3 = Commit()
  528. commit3.tree = tree.id
  529. commit3.parents = [commit2.id]
  530. commit3.author = commit3.committer = b"Test <test@example.com>"
  531. commit3.commit_time = commit3.author_time = 1234567892
  532. commit3.commit_timezone = commit3.author_timezone = 0
  533. commit3.message = b"Third commit"
  534. object_store.add_object(commit3)
  535. # Branch from commit2
  536. commit4 = Commit()
  537. commit4.tree = tree.id
  538. commit4.parents = [commit2.id]
  539. commit4.author = commit4.committer = b"Test <test@example.com>"
  540. commit4.commit_time = commit4.author_time = 1234567893
  541. commit4.commit_timezone = commit4.author_timezone = 0
  542. commit4.message = b"Fourth commit (branch)"
  543. object_store.add_object(commit4)
  544. # Merge commit
  545. commit5 = Commit()
  546. commit5.tree = tree.id
  547. commit5.parents = [commit3.id, commit4.id]
  548. commit5.author = commit5.committer = b"Test <test@example.com>"
  549. commit5.commit_time = commit5.author_time = 1234567894
  550. commit5.commit_timezone = commit5.author_timezone = 0
  551. commit5.message = b"Merge commit"
  552. object_store.add_object(commit5)
  553. # Create refs
  554. refs_path = os.path.join(self.tempdir, "refs")
  555. os.makedirs(refs_path, exist_ok=True)
  556. repo_path = self.tempdir
  557. repo = Repo.init(repo_path)
  558. repo.object_store = object_store
  559. # Test graph operations WITHOUT commit graph first
  560. merge_base_no_graph = find_merge_base(repo, [commit3.id, commit4.id])
  561. can_ff_no_graph = can_fast_forward(repo, commit1.id, commit3.id)
  562. # Now write commit graph
  563. object_store.write_commit_graph(
  564. [commit1.id, commit2.id, commit3.id, commit4.id, commit5.id],
  565. reachable=False,
  566. )
  567. # Verify commit graph is loaded by creating new repo instance
  568. repo2 = Repo(repo_path)
  569. self.addCleanup(repo2.close)
  570. repo2.object_store = object_store
  571. # Verify commit graph is available
  572. commit_graph = repo2.object_store.get_commit_graph() # type: ignore[no-untyped-call]
  573. self.assertIsNotNone(commit_graph)
  574. # Test graph operations WITH commit graph
  575. merge_base_with_graph = find_merge_base(repo2, [commit3.id, commit4.id])
  576. can_ff_with_graph = can_fast_forward(repo2, commit1.id, commit3.id)
  577. # Results should be identical
  578. self.assertEqual(
  579. merge_base_no_graph,
  580. merge_base_with_graph,
  581. "Merge base should be same with and without commit graph",
  582. )
  583. self.assertEqual(
  584. can_ff_no_graph,
  585. can_ff_with_graph,
  586. "Fast-forward detection should be same with and without commit graph",
  587. )
  588. # Expected results
  589. self.assertEqual(
  590. merge_base_with_graph,
  591. [commit2.id],
  592. "Merge base of commit3 and commit4 should be commit2",
  593. )
  594. self.assertTrue(
  595. can_ff_with_graph, "Should be able to fast-forward from commit1 to commit3"
  596. )
  597. # Test that ParentsProvider in the repo uses commit graph
  598. parents_provider = repo2.parents_provider()
  599. self.assertIsNotNone(
  600. parents_provider.commit_graph,
  601. "Repository's parents provider should have commit graph",
  602. )
  603. # Verify parent lookups work through the provider
  604. self.assertEqual(parents_provider.get_parents(commit1.id), []) # type: ignore[no-untyped-call]
  605. self.assertEqual(parents_provider.get_parents(commit2.id), [commit1.id]) # type: ignore[no-untyped-call]
  606. self.assertEqual(
  607. parents_provider.get_parents(commit5.id),
  608. [commit3.id, commit4.id], # type: ignore[no-untyped-call]
  609. )
  610. def test_performance_with_commit_graph(self) -> None:
  611. """Test that using commit graph provides performance benefits."""
  612. from dulwich.graph import find_merge_base
  613. from dulwich.object_store import DiskObjectStore
  614. from dulwich.objects import Commit, Tree
  615. from dulwich.repo import Repo
  616. # Create a larger commit history to better measure performance
  617. object_store_path = os.path.join(self.tempdir, "objects")
  618. os.makedirs(object_store_path, exist_ok=True)
  619. object_store = DiskObjectStore(object_store_path)
  620. tree = Tree()
  621. object_store.add_object(tree)
  622. # Create a chain of 20 commits
  623. commits: list[Commit] = []
  624. for i in range(20):
  625. commit = Commit()
  626. commit.tree = tree.id
  627. if i > 0:
  628. commit.parents = [commits[i - 1].id]
  629. commit.author = commit.committer = b"Test <test@example.com>"
  630. commit.commit_time = commit.author_time = 1234567890 + i
  631. commit.commit_timezone = commit.author_timezone = 0
  632. commit.message = f"Commit {i}".encode()
  633. object_store.add_object(commit)
  634. commits.append(commit)
  635. # Create repository
  636. repo_path = self.tempdir
  637. repo = Repo.init(repo_path)
  638. repo.object_store = object_store
  639. # Time operations without commit graph
  640. for _ in range(10): # Run multiple times for better measurement
  641. find_merge_base(repo, [commits[0].id, commits[-1].id])
  642. # Write commit graph
  643. object_store.write_commit_graph([c.id for c in commits], reachable=False)
  644. # Create new repo instance to pick up commit graph
  645. repo2 = Repo(repo_path)
  646. self.addCleanup(repo2.close)
  647. repo2.object_store = object_store
  648. # Verify commit graph is loaded
  649. self.assertIsNotNone(repo2.object_store.get_commit_graph()) # type: ignore[no-untyped-call]
  650. # Time operations with commit graph
  651. for _ in range(10): # Run multiple times for better measurement
  652. find_merge_base(repo2, [commits[0].id, commits[-1].id])
  653. # With commit graph should be at least as fast (usually faster)
  654. # We don't assert a specific speedup since it depends on the machine
  655. # But we verify both approaches give the same result
  656. result_no_graph = find_merge_base(repo, [commits[0].id, commits[-1].id])
  657. result_with_graph = find_merge_base(repo2, [commits[0].id, commits[-1].id])
  658. self.assertEqual(
  659. result_no_graph,
  660. result_with_graph,
  661. "Results should be identical with and without commit graph",
  662. )
  663. self.assertEqual(
  664. result_with_graph, [commits[0].id], "Merge base should be the first commit"
  665. )
  666. if __name__ == "__main__":
  667. unittest.main()