test_object_store.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. # test_object_store.py -- tests for object_store.py
  2. # Copyright (C) 2008 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. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for the object store interface."""
  22. import os
  23. import shutil
  24. import stat
  25. import sys
  26. import tempfile
  27. from contextlib import closing
  28. from io import BytesIO
  29. from dulwich.errors import NotTreeError
  30. from dulwich.index import commit_tree
  31. from dulwich.object_format import DEFAULT_OBJECT_FORMAT
  32. from dulwich.object_store import (
  33. DiskObjectStore,
  34. MemoryObjectStore,
  35. ObjectStoreGraphWalker,
  36. OverlayObjectStore,
  37. commit_tree_changes,
  38. read_packs_file,
  39. tree_lookup_path,
  40. )
  41. from dulwich.objects import (
  42. S_IFGITLINK,
  43. Blob,
  44. EmptyFileException,
  45. SubmoduleEncountered,
  46. Tree,
  47. TreeEntry,
  48. sha_to_hex,
  49. )
  50. from dulwich.pack import REF_DELTA, write_pack_objects
  51. from dulwich.tests.test_object_store import ObjectStoreTests, PackBasedObjectStoreTests
  52. from dulwich.tests.utils import build_pack, make_object
  53. from . import TestCase
  54. testobject = make_object(Blob, data=b"yummy data")
  55. class OverlayObjectStoreTests(ObjectStoreTests, TestCase):
  56. def setUp(self) -> None:
  57. TestCase.setUp(self)
  58. self.bases = [MemoryObjectStore(), MemoryObjectStore()]
  59. self.store = OverlayObjectStore(self.bases, self.bases[0])
  60. class MemoryObjectStoreTests(ObjectStoreTests, TestCase):
  61. def setUp(self) -> None:
  62. TestCase.setUp(self)
  63. self.store = MemoryObjectStore()
  64. def test_add_pack(self) -> None:
  65. o = MemoryObjectStore()
  66. f, commit, abort = o.add_pack()
  67. try:
  68. b = make_object(Blob, data=b"more yummy data")
  69. write_pack_objects(
  70. f.write, [(b, None)], object_format=DEFAULT_OBJECT_FORMAT
  71. )
  72. except BaseException:
  73. abort()
  74. raise
  75. else:
  76. commit()
  77. def test_add_pack_emtpy(self) -> None:
  78. o = MemoryObjectStore()
  79. _f, commit, _abort = o.add_pack()
  80. commit()
  81. def test_add_thin_pack(self) -> None:
  82. o = MemoryObjectStore()
  83. blob = make_object(Blob, data=b"yummy data")
  84. o.add_object(blob)
  85. f = BytesIO()
  86. entries = build_pack(
  87. f,
  88. [
  89. (REF_DELTA, (blob.id, b"more yummy data")),
  90. ],
  91. store=o,
  92. )
  93. o.add_thin_pack(f.read, None)
  94. packed_blob_sha = sha_to_hex(entries[0][3])
  95. self.assertEqual(
  96. (Blob.type_num, b"more yummy data"), o.get_raw(packed_blob_sha)
  97. )
  98. def test_add_thin_pack_empty(self) -> None:
  99. o = MemoryObjectStore()
  100. f = BytesIO()
  101. entries = build_pack(f, [], store=o)
  102. self.assertEqual([], entries)
  103. o.add_thin_pack(f.read, None)
  104. def test_add_pack_data_with_deltas(self) -> None:
  105. """Test that add_pack_data properly handles delta objects.
  106. This test verifies that MemoryObjectStore.add_pack_data can handle
  107. pack data containing delta objects. Before the fix for issue #1179,
  108. this would fail with AssertionError when trying to call sha_file()
  109. on unresolved delta objects.
  110. The fix routes through add_pack() which properly resolves deltas.
  111. """
  112. o1 = MemoryObjectStore()
  113. o2 = MemoryObjectStore()
  114. base_blob = make_object(Blob, data=b"base data")
  115. o1.add_object(base_blob)
  116. # Create a pack with a delta object
  117. f = BytesIO()
  118. entries = build_pack(
  119. f,
  120. [
  121. (REF_DELTA, (base_blob.id, b"more data")),
  122. ],
  123. store=o1,
  124. )
  125. # Use add_thin_pack which internally calls add_pack_data
  126. # This demonstrates the scenario where delta resolution is needed
  127. f.seek(0)
  128. o2.add_object(base_blob) # Need base object for thin pack
  129. o2.add_thin_pack(f.read, None)
  130. # Verify the delta object was properly resolved and added
  131. packed_blob_sha = sha_to_hex(entries[0][3])
  132. self.assertIn(packed_blob_sha, o2)
  133. self.assertEqual((Blob.type_num, b"more data"), o2.get_raw(packed_blob_sha))
  134. class DiskObjectStoreTests(PackBasedObjectStoreTests, TestCase):
  135. def setUp(self) -> None:
  136. TestCase.setUp(self)
  137. self.store_dir = tempfile.mkdtemp()
  138. self.addCleanup(shutil.rmtree, self.store_dir)
  139. self.store = DiskObjectStore.init(self.store_dir)
  140. def tearDown(self) -> None:
  141. TestCase.tearDown(self)
  142. PackBasedObjectStoreTests.tearDown(self)
  143. def test_loose_compression_level(self) -> None:
  144. alternate_dir = tempfile.mkdtemp()
  145. self.addCleanup(shutil.rmtree, alternate_dir)
  146. alternate_store = DiskObjectStore(alternate_dir, loose_compression_level=6)
  147. b2 = make_object(Blob, data=b"yummy data")
  148. alternate_store.add_object(b2)
  149. def test_alternates(self) -> None:
  150. alternate_dir = tempfile.mkdtemp()
  151. self.addCleanup(shutil.rmtree, alternate_dir)
  152. alternate_store = DiskObjectStore(alternate_dir)
  153. b2 = make_object(Blob, data=b"yummy data")
  154. alternate_store.add_object(b2)
  155. store = DiskObjectStore(self.store_dir)
  156. self.assertRaises(KeyError, store.__getitem__, b2.id)
  157. store.add_alternate_path(alternate_dir)
  158. self.assertIn(b2.id, store)
  159. self.assertEqual(b2, store[b2.id])
  160. def test_read_alternate_paths(self) -> None:
  161. store = DiskObjectStore(self.store_dir)
  162. abs_path = os.path.abspath(os.path.normpath("/abspath"))
  163. # ensures in particular existence of the alternates file
  164. store.add_alternate_path(abs_path)
  165. self.assertEqual(set(store._read_alternate_paths()), {abs_path})
  166. store.add_alternate_path("relative-path")
  167. self.assertIn(
  168. os.path.join(store.path, "relative-path"),
  169. set(store._read_alternate_paths()),
  170. )
  171. # arguably, add_alternate_path() could strip comments.
  172. # Meanwhile it's more convenient to use it than to import INFODIR
  173. store.add_alternate_path("# comment")
  174. for alt_path in store._read_alternate_paths():
  175. self.assertNotIn("#", alt_path)
  176. def test_file_modes(self) -> None:
  177. self.store.add_object(testobject)
  178. path = self.store._get_shafile_path(testobject.id)
  179. mode = os.stat(path).st_mode
  180. packmode = "0o100444" if sys.platform != "win32" else "0o100666"
  181. self.assertEqual(oct(mode), packmode)
  182. def test_corrupted_object_raise_exception(self) -> None:
  183. """Corrupted sha1 disk file should raise specific exception."""
  184. self.store.add_object(testobject)
  185. self.assertEqual(
  186. (Blob.type_num, b"yummy data"), self.store.get_raw(testobject.id)
  187. )
  188. self.assertTrue(self.store.contains_loose(testobject.id))
  189. self.assertIsNotNone(self.store._get_loose_object(testobject.id))
  190. path = self.store._get_shafile_path(testobject.id)
  191. old_mode = os.stat(path).st_mode
  192. os.chmod(path, 0o600)
  193. with open(path, "wb") as f: # corrupt the file
  194. f.write(b"")
  195. os.chmod(path, old_mode)
  196. expected_error_msg = "Corrupted empty file detected"
  197. try:
  198. self.store.contains_loose(testobject.id)
  199. except EmptyFileException as e:
  200. self.assertEqual(str(e), expected_error_msg)
  201. try:
  202. self.store._get_loose_object(testobject.id)
  203. except EmptyFileException as e:
  204. self.assertEqual(str(e), expected_error_msg)
  205. # this does not change iteration on loose objects though
  206. self.assertEqual([testobject.id], list(self.store._iter_loose_objects()))
  207. def test_tempfile_in_loose_store(self) -> None:
  208. self.store.add_object(testobject)
  209. self.assertEqual([testobject.id], list(self.store._iter_loose_objects()))
  210. # add temporary files to the loose store
  211. for i in range(256):
  212. dirname = os.path.join(self.store_dir, f"{i:02x}")
  213. if not os.path.isdir(dirname):
  214. os.makedirs(dirname)
  215. fd, _n = tempfile.mkstemp(prefix="tmp_obj_", dir=dirname)
  216. os.close(fd)
  217. self.assertEqual([testobject.id], list(self.store._iter_loose_objects()))
  218. def test_add_alternate_path(self) -> None:
  219. store = DiskObjectStore(self.store_dir)
  220. self.assertEqual([], list(store._read_alternate_paths()))
  221. store.add_alternate_path(os.path.abspath("/foo/path"))
  222. self.assertEqual(
  223. [os.path.abspath("/foo/path")], list(store._read_alternate_paths())
  224. )
  225. if sys.platform == "win32":
  226. store.add_alternate_path("D:\\bar\\path")
  227. else:
  228. store.add_alternate_path("/bar/path")
  229. if sys.platform == "win32":
  230. self.assertEqual(
  231. [os.path.abspath("/foo/path"), "D:\\bar\\path"],
  232. list(store._read_alternate_paths()),
  233. )
  234. else:
  235. self.assertEqual(
  236. [os.path.abspath("/foo/path"), "/bar/path"],
  237. list(store._read_alternate_paths()),
  238. )
  239. def test_rel_alternative_path(self) -> None:
  240. alternate_dir = tempfile.mkdtemp()
  241. self.addCleanup(shutil.rmtree, alternate_dir)
  242. alternate_store = DiskObjectStore(alternate_dir)
  243. b2 = make_object(Blob, data=b"yummy data")
  244. alternate_store.add_object(b2)
  245. store = DiskObjectStore(self.store_dir)
  246. self.assertRaises(KeyError, store.__getitem__, b2.id)
  247. store.add_alternate_path(os.path.relpath(alternate_dir, self.store_dir))
  248. self.assertEqual(list(alternate_store), list(store.alternates[0]))
  249. self.assertIn(b2.id, store)
  250. self.assertEqual(b2, store[b2.id])
  251. def test_pack_dir(self) -> None:
  252. o = DiskObjectStore(self.store_dir)
  253. self.assertEqual(os.path.join(self.store_dir, "pack"), o.pack_dir)
  254. def test_add_pack(self) -> None:
  255. o = DiskObjectStore(self.store_dir)
  256. self.addCleanup(o.close)
  257. f, commit, abort = o.add_pack()
  258. try:
  259. b = make_object(Blob, data=b"more yummy data")
  260. write_pack_objects(
  261. f.write, [(b, None)], object_format=DEFAULT_OBJECT_FORMAT
  262. )
  263. except BaseException:
  264. abort()
  265. raise
  266. else:
  267. commit()
  268. def test_add_thin_pack(self) -> None:
  269. o = DiskObjectStore(self.store_dir)
  270. self.addCleanup(o.close)
  271. blob = make_object(Blob, data=b"yummy data")
  272. o.add_object(blob)
  273. f = BytesIO()
  274. entries = build_pack(
  275. f,
  276. [
  277. (REF_DELTA, (blob.id, b"more yummy data")),
  278. ],
  279. store=o,
  280. )
  281. with o.add_thin_pack(f.read, None) as pack:
  282. packed_blob_sha = sha_to_hex(entries[0][3])
  283. pack.check_length_and_checksum()
  284. self.assertEqual(sorted([blob.id, packed_blob_sha]), list(pack))
  285. self.assertTrue(o.contains_packed(packed_blob_sha))
  286. self.assertTrue(o.contains_packed(blob.id))
  287. self.assertEqual(
  288. (Blob.type_num, b"more yummy data"),
  289. o.get_raw(packed_blob_sha),
  290. )
  291. def test_add_thin_pack_empty(self) -> None:
  292. with closing(DiskObjectStore(self.store_dir)) as o:
  293. f = BytesIO()
  294. entries = build_pack(f, [], store=o)
  295. self.assertEqual([], entries)
  296. o.add_thin_pack(f.read, None)
  297. def test_pack_index_version_config(self) -> None:
  298. # Test that pack.indexVersion configuration is respected
  299. from dulwich.config import ConfigDict
  300. from dulwich.pack import load_pack_index
  301. # Create config with pack.indexVersion = 1
  302. config = ConfigDict()
  303. config[(b"pack",)] = {b"indexVersion": b"1"}
  304. # Create object store with config
  305. store_dir = tempfile.mkdtemp()
  306. self.addCleanup(shutil.rmtree, store_dir)
  307. os.makedirs(os.path.join(store_dir, "pack"))
  308. store = DiskObjectStore.from_config(store_dir, config)
  309. self.addCleanup(store.close)
  310. # Create some objects to pack
  311. b1 = make_object(Blob, data=b"blob1")
  312. b2 = make_object(Blob, data=b"blob2")
  313. store.add_objects([(b1, None), (b2, None)])
  314. # Add a pack
  315. f, commit, abort = store.add_pack()
  316. try:
  317. # build_pack expects (type_num, data) tuples
  318. objects_spec = [
  319. (b1.type_num, b1.as_raw_string()),
  320. (b2.type_num, b2.as_raw_string()),
  321. ]
  322. build_pack(f, objects_spec, store=store)
  323. commit()
  324. except:
  325. abort()
  326. raise
  327. # Find the created pack index
  328. pack_dir = os.path.join(store_dir, "pack")
  329. idx_files = [f for f in os.listdir(pack_dir) if f.endswith(".idx")]
  330. self.assertEqual(1, len(idx_files))
  331. # Load and verify it's version 1
  332. idx_path = os.path.join(pack_dir, idx_files[0])
  333. idx = load_pack_index(idx_path)
  334. self.assertEqual(1, idx.version)
  335. # Test version 3
  336. config[(b"pack",)] = {b"indexVersion": b"3"}
  337. store_dir2 = tempfile.mkdtemp()
  338. self.addCleanup(shutil.rmtree, store_dir2)
  339. os.makedirs(os.path.join(store_dir2, "pack"))
  340. store2 = DiskObjectStore.from_config(store_dir2, config)
  341. self.addCleanup(store2.close)
  342. b3 = make_object(Blob, data=b"blob3")
  343. store2.add_objects([(b3, None)])
  344. f2, commit2, abort2 = store2.add_pack()
  345. try:
  346. objects_spec2 = [(b3.type_num, b3.as_raw_string())]
  347. build_pack(f2, objects_spec2, store=store2)
  348. commit2()
  349. except:
  350. abort2()
  351. raise
  352. # Find and verify version 3 index
  353. pack_dir2 = os.path.join(store_dir2, "pack")
  354. idx_files2 = [f for f in os.listdir(pack_dir2) if f.endswith(".idx")]
  355. self.assertEqual(1, len(idx_files2))
  356. idx_path2 = os.path.join(pack_dir2, idx_files2[0])
  357. idx2 = load_pack_index(idx_path2)
  358. self.assertEqual(3, idx2.version)
  359. def test_prune_orphaned_tempfiles(self) -> None:
  360. import time
  361. # Create an orphaned temporary pack file in the repository directory
  362. tmp_pack_path = os.path.join(self.store_dir, "tmp_pack_test123")
  363. with open(tmp_pack_path, "wb") as f:
  364. f.write(b"temporary pack data")
  365. # Create an orphaned .pack file without .idx in pack directory
  366. pack_dir = os.path.join(self.store_dir, "pack")
  367. orphaned_pack_path = os.path.join(pack_dir, "pack-orphaned.pack")
  368. with open(orphaned_pack_path, "wb") as f:
  369. f.write(b"orphaned pack data")
  370. # Make files appear old by modifying mtime (older than grace period)
  371. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  372. old_time = time.time() - (
  373. DEFAULT_TEMPFILE_GRACE_PERIOD + 3600
  374. ) # grace period + 1 hour
  375. os.utime(tmp_pack_path, (old_time, old_time))
  376. os.utime(orphaned_pack_path, (old_time, old_time))
  377. # Create a recent temporary file that should NOT be cleaned
  378. recent_tmp_path = os.path.join(self.store_dir, "tmp_pack_recent")
  379. with open(recent_tmp_path, "wb") as f:
  380. f.write(b"recent temp data")
  381. # Run prune
  382. self.store.prune()
  383. # Check that old orphaned files were removed
  384. self.assertFalse(os.path.exists(tmp_pack_path))
  385. self.assertFalse(os.path.exists(orphaned_pack_path))
  386. # Check that recent file was NOT removed
  387. self.assertTrue(os.path.exists(recent_tmp_path))
  388. # Cleanup the recent file
  389. os.remove(recent_tmp_path)
  390. def test_prune_with_custom_grace_period(self) -> None:
  391. """Test that prune respects custom grace period."""
  392. import time
  393. # Create a temporary file that's 1 hour old
  394. tmp_pack_path = os.path.join(self.store_dir, "tmp_pack_1hour")
  395. with open(tmp_pack_path, "wb") as f:
  396. f.write(b"1 hour old data")
  397. # Make it 1 hour old
  398. old_time = time.time() - 3600 # 1 hour ago
  399. os.utime(tmp_pack_path, (old_time, old_time))
  400. # Prune with default grace period (2 weeks) - should NOT remove
  401. self.store.prune()
  402. self.assertTrue(os.path.exists(tmp_pack_path))
  403. # Prune with 30 minute grace period - should remove
  404. self.store.prune(grace_period=1800) # 30 minutes
  405. self.assertFalse(os.path.exists(tmp_pack_path))
  406. def test_gc_prunes_tempfiles(self) -> None:
  407. """Test that garbage collection prunes temporary files."""
  408. import time
  409. from dulwich.gc import garbage_collect
  410. from dulwich.repo import Repo
  411. # Create a repository with the store
  412. repo = Repo.init(self.store_dir)
  413. # Create an old orphaned temporary file in the objects directory
  414. tmp_pack_path = os.path.join(repo.object_store.path, "tmp_pack_old")
  415. with open(tmp_pack_path, "wb") as f:
  416. f.write(b"old temporary data")
  417. # Make it old (older than grace period)
  418. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  419. old_time = time.time() - (
  420. DEFAULT_TEMPFILE_GRACE_PERIOD + 3600
  421. ) # grace period + 1 hour
  422. os.utime(tmp_pack_path, (old_time, old_time))
  423. # Run garbage collection
  424. garbage_collect(repo)
  425. # Verify the orphaned file was cleaned up
  426. self.assertFalse(os.path.exists(tmp_pack_path))
  427. def test_commit_graph_enabled_by_default(self) -> None:
  428. """Test that commit graph is enabled by default."""
  429. from dulwich.config import ConfigDict
  430. config = ConfigDict()
  431. store = DiskObjectStore.from_config(self.store_dir, config)
  432. self.addCleanup(store.close)
  433. # Should be enabled by default
  434. self.assertTrue(store._use_commit_graph)
  435. def test_commit_graph_disabled_by_config(self) -> None:
  436. """Test that commit graph can be disabled via config."""
  437. from dulwich.config import ConfigDict
  438. config = ConfigDict()
  439. config[(b"core",)] = {b"commitGraph": b"false"}
  440. store = DiskObjectStore.from_config(self.store_dir, config)
  441. self.addCleanup(store.close)
  442. # Should be disabled
  443. self.assertFalse(store._use_commit_graph)
  444. # get_commit_graph should return None when disabled
  445. self.assertIsNone(store.get_commit_graph())
  446. def test_commit_graph_enabled_by_config(self) -> None:
  447. """Test that commit graph can be explicitly enabled via config."""
  448. from dulwich.config import ConfigDict
  449. config = ConfigDict()
  450. config[(b"core",)] = {b"commitGraph": b"true"}
  451. store = DiskObjectStore.from_config(self.store_dir, config)
  452. self.addCleanup(store.close)
  453. # Should be enabled
  454. self.assertTrue(store._use_commit_graph)
  455. def test_commit_graph_usage_in_find_shallow(self) -> None:
  456. """Test that find_shallow uses commit graph when available."""
  457. import time
  458. from dulwich.object_store import find_shallow
  459. from dulwich.objects import Commit
  460. # Create a simple commit chain: c1 -> c2 -> c3
  461. ts = int(time.time())
  462. c1 = make_object(
  463. Commit,
  464. message=b"commit 1",
  465. tree=b"1" * 40,
  466. parents=[],
  467. author=b"Test Author <test@example.com>",
  468. committer=b"Test Committer <test@example.com>",
  469. commit_time=ts,
  470. commit_timezone=0,
  471. author_time=ts,
  472. author_timezone=0,
  473. )
  474. c2 = make_object(
  475. Commit,
  476. message=b"commit 2",
  477. tree=b"2" * 40,
  478. parents=[c1.id],
  479. author=b"Test Author <test@example.com>",
  480. committer=b"Test Committer <test@example.com>",
  481. commit_time=ts + 1,
  482. commit_timezone=0,
  483. author_time=ts + 1,
  484. author_timezone=0,
  485. )
  486. c3 = make_object(
  487. Commit,
  488. message=b"commit 3",
  489. tree=b"3" * 40,
  490. parents=[c2.id],
  491. author=b"Test Author <test@example.com>",
  492. committer=b"Test Committer <test@example.com>",
  493. commit_time=ts + 2,
  494. commit_timezone=0,
  495. author_time=ts + 2,
  496. author_timezone=0,
  497. )
  498. self.store.add_objects([(c1, None), (c2, None), (c3, None)])
  499. # Write a commit graph
  500. self.store.write_commit_graph([c1.id, c2.id, c3.id])
  501. # Verify commit graph was written
  502. commit_graph = self.store.get_commit_graph()
  503. self.assertIsNotNone(commit_graph)
  504. self.assertEqual(3, len(commit_graph))
  505. # Test find_shallow with depth
  506. # With depth 2 starting from c3:
  507. # - depth 1 includes c3 itself (not shallow)
  508. # - depth 2 includes c3 and c2 (not shallow)
  509. # - c1 is at depth 3, so it's marked as shallow
  510. shallow, not_shallow = find_shallow(self.store, [c3.id], 2)
  511. # c2 should be marked as shallow since it's at the depth boundary
  512. self.assertEqual({c2.id}, shallow)
  513. self.assertEqual({c3.id}, not_shallow)
  514. def test_commit_graph_end_to_end(self) -> None:
  515. """Test end-to-end commit graph generation and usage."""
  516. import os
  517. import time
  518. from dulwich.object_store import get_depth
  519. from dulwich.objects import Blob, Commit, Tree
  520. # Create a more complex commit history:
  521. # c1 -- c2 -- c4
  522. # \ /
  523. # \-- c3 -/
  524. ts = int(time.time())
  525. # Create some blobs and trees for the commits
  526. blob1 = make_object(Blob, data=b"content 1")
  527. blob2 = make_object(Blob, data=b"content 2")
  528. blob3 = make_object(Blob, data=b"content 3")
  529. blob4 = make_object(Blob, data=b"content 4")
  530. tree1 = make_object(Tree)
  531. tree1[b"file1.txt"] = (0o100644, blob1.id)
  532. tree2 = make_object(Tree)
  533. tree2[b"file1.txt"] = (0o100644, blob1.id)
  534. tree2[b"file2.txt"] = (0o100644, blob2.id)
  535. tree3 = make_object(Tree)
  536. tree3[b"file1.txt"] = (0o100644, blob1.id)
  537. tree3[b"file3.txt"] = (0o100644, blob3.id)
  538. tree4 = make_object(Tree)
  539. tree4[b"file1.txt"] = (0o100644, blob1.id)
  540. tree4[b"file2.txt"] = (0o100644, blob2.id)
  541. tree4[b"file3.txt"] = (0o100644, blob3.id)
  542. tree4[b"file4.txt"] = (0o100644, blob4.id)
  543. # Add all objects to store
  544. self.store.add_objects(
  545. [
  546. (blob1, None),
  547. (blob2, None),
  548. (blob3, None),
  549. (blob4, None),
  550. (tree1, None),
  551. (tree2, None),
  552. (tree3, None),
  553. (tree4, None),
  554. ]
  555. )
  556. # Create commits
  557. c1 = make_object(
  558. Commit,
  559. message=b"Initial commit",
  560. tree=tree1.id,
  561. parents=[],
  562. author=b"Test Author <test@example.com>",
  563. committer=b"Test Committer <test@example.com>",
  564. commit_time=ts,
  565. commit_timezone=0,
  566. author_time=ts,
  567. author_timezone=0,
  568. )
  569. c2 = make_object(
  570. Commit,
  571. message=b"Second commit",
  572. tree=tree2.id,
  573. parents=[c1.id],
  574. author=b"Test Author <test@example.com>",
  575. committer=b"Test Committer <test@example.com>",
  576. commit_time=ts + 10,
  577. commit_timezone=0,
  578. author_time=ts + 10,
  579. author_timezone=0,
  580. )
  581. c3 = make_object(
  582. Commit,
  583. message=b"Branch commit",
  584. tree=tree3.id,
  585. parents=[c1.id],
  586. author=b"Test Author <test@example.com>",
  587. committer=b"Test Committer <test@example.com>",
  588. commit_time=ts + 20,
  589. commit_timezone=0,
  590. author_time=ts + 20,
  591. author_timezone=0,
  592. )
  593. c4 = make_object(
  594. Commit,
  595. message=b"Merge commit",
  596. tree=tree4.id,
  597. parents=[c2.id, c3.id],
  598. author=b"Test Author <test@example.com>",
  599. committer=b"Test Committer <test@example.com>",
  600. commit_time=ts + 30,
  601. commit_timezone=0,
  602. author_time=ts + 30,
  603. author_timezone=0,
  604. )
  605. self.store.add_objects([(c1, None), (c2, None), (c3, None), (c4, None)])
  606. # First, verify operations work without commit graph
  607. # Check depth calculation
  608. depth_before = get_depth(self.store, c4.id)
  609. self.assertEqual(3, depth_before) # c4 -> c2/c3 -> c1
  610. # Generate commit graph
  611. self.store.write_commit_graph([c1.id, c2.id, c3.id, c4.id])
  612. # Verify commit graph file was created
  613. graph_path = os.path.join(self.store.path, "info", "commit-graph")
  614. self.assertTrue(os.path.exists(graph_path))
  615. # Load and verify commit graph
  616. commit_graph = self.store.get_commit_graph()
  617. self.assertIsNotNone(commit_graph)
  618. self.assertEqual(4, len(commit_graph))
  619. # Verify commit graph contains correct parent information
  620. c1_entry = commit_graph.get_entry_by_oid(c1.id)
  621. self.assertIsNotNone(c1_entry)
  622. self.assertEqual([], c1_entry.parents)
  623. c2_entry = commit_graph.get_entry_by_oid(c2.id)
  624. self.assertIsNotNone(c2_entry)
  625. self.assertEqual([c1.id], c2_entry.parents)
  626. c3_entry = commit_graph.get_entry_by_oid(c3.id)
  627. self.assertIsNotNone(c3_entry)
  628. self.assertEqual([c1.id], c3_entry.parents)
  629. c4_entry = commit_graph.get_entry_by_oid(c4.id)
  630. self.assertIsNotNone(c4_entry)
  631. self.assertEqual([c2.id, c3.id], c4_entry.parents)
  632. # Test that operations now use the commit graph
  633. # Check depth calculation again - should use commit graph
  634. depth_after = get_depth(self.store, c4.id)
  635. self.assertEqual(3, depth_after)
  636. # Test with commit graph disabled
  637. self.store._use_commit_graph = False
  638. self.assertIsNone(self.store.get_commit_graph())
  639. # Operations should still work without commit graph
  640. depth_disabled = get_depth(self.store, c4.id)
  641. self.assertEqual(3, depth_disabled)
  642. def test_fsync_object_files_disabled_by_default(self) -> None:
  643. """Test that fsync is disabled by default for object files."""
  644. from dulwich.config import ConfigDict
  645. config = ConfigDict()
  646. store = DiskObjectStore.from_config(self.store_dir, config)
  647. self.addCleanup(store.close)
  648. # Should be disabled by default
  649. self.assertFalse(store.fsync_object_files)
  650. def test_fsync_object_files_enabled_by_config(self) -> None:
  651. """Test that fsync can be enabled via core.fsyncObjectFiles config."""
  652. from unittest.mock import patch
  653. from dulwich.config import ConfigDict
  654. config = ConfigDict()
  655. config[(b"core",)] = {b"fsyncObjectFiles": b"true"}
  656. store = DiskObjectStore.from_config(self.store_dir, config)
  657. self.addCleanup(store.close)
  658. # Should be enabled
  659. self.assertTrue(store.fsync_object_files)
  660. # Test that fsync is actually called when adding objects
  661. blob = make_object(Blob, data=b"test fsync data")
  662. with patch("os.fsync") as mock_fsync:
  663. store.add_object(blob)
  664. # fsync should have been called
  665. mock_fsync.assert_called_once()
  666. def test_fsync_object_files_disabled_by_config(self) -> None:
  667. """Test that fsync can be explicitly disabled via config."""
  668. from unittest.mock import patch
  669. from dulwich.config import ConfigDict
  670. config = ConfigDict()
  671. config[(b"core",)] = {b"fsyncObjectFiles": b"false"}
  672. store = DiskObjectStore.from_config(self.store_dir, config)
  673. self.addCleanup(store.close)
  674. # Should be disabled
  675. self.assertFalse(store.fsync_object_files)
  676. # Test that fsync is NOT called when adding objects
  677. blob = make_object(Blob, data=b"test no fsync data")
  678. with patch("os.fsync") as mock_fsync:
  679. store.add_object(blob)
  680. # fsync should NOT have been called
  681. mock_fsync.assert_not_called()
  682. def test_fsync_object_files_for_pack_files(self) -> None:
  683. """Test that fsync config applies to pack files."""
  684. from unittest.mock import patch
  685. from dulwich.config import ConfigDict
  686. from dulwich.pack import write_pack_objects
  687. # Test with fsync enabled
  688. config = ConfigDict()
  689. config[(b"core",)] = {b"fsyncObjectFiles": b"true"}
  690. store = DiskObjectStore.from_config(self.store_dir, config)
  691. self.addCleanup(store.close)
  692. self.assertTrue(store.fsync_object_files)
  693. # Add some objects via pack
  694. blob = make_object(Blob, data=b"pack test data")
  695. with patch("os.fsync") as mock_fsync:
  696. f, commit, abort = store.add_pack()
  697. try:
  698. write_pack_objects(
  699. f.write, [(blob, None)], object_format=DEFAULT_OBJECT_FORMAT
  700. )
  701. except BaseException:
  702. abort()
  703. raise
  704. else:
  705. commit()
  706. # fsync should have been called at least once (for pack file and index)
  707. self.assertGreater(mock_fsync.call_count, 0)
  708. class TreeLookupPathTests(TestCase):
  709. def setUp(self) -> None:
  710. TestCase.setUp(self)
  711. self.store = MemoryObjectStore()
  712. blob_a = make_object(Blob, data=b"a")
  713. blob_b = make_object(Blob, data=b"b")
  714. blob_c = make_object(Blob, data=b"c")
  715. for blob in [blob_a, blob_b, blob_c]:
  716. self.store.add_object(blob)
  717. blobs = [
  718. (b"a", blob_a.id, 0o100644),
  719. (b"ad/b", blob_b.id, 0o100644),
  720. (b"ad/bd/c", blob_c.id, 0o100755),
  721. (b"ad/c", blob_c.id, 0o100644),
  722. (b"c", blob_c.id, 0o100644),
  723. (b"d", blob_c.id, S_IFGITLINK),
  724. ]
  725. self.tree_id = commit_tree(self.store, blobs)
  726. def get_object(self, sha):
  727. return self.store[sha]
  728. def test_lookup_blob(self) -> None:
  729. o_id = tree_lookup_path(self.get_object, self.tree_id, b"a")[1]
  730. self.assertIsInstance(self.store[o_id], Blob)
  731. def test_lookup_tree(self) -> None:
  732. o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad")[1]
  733. self.assertIsInstance(self.store[o_id], Tree)
  734. o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad/bd")[1]
  735. self.assertIsInstance(self.store[o_id], Tree)
  736. o_id = tree_lookup_path(self.get_object, self.tree_id, b"ad/bd/")[1]
  737. self.assertIsInstance(self.store[o_id], Tree)
  738. def test_lookup_submodule(self) -> None:
  739. tree_lookup_path(self.get_object, self.tree_id, b"d")[1]
  740. self.assertRaises(
  741. SubmoduleEncountered,
  742. tree_lookup_path,
  743. self.get_object,
  744. self.tree_id,
  745. b"d/a",
  746. )
  747. def test_lookup_nonexistent(self) -> None:
  748. self.assertRaises(
  749. KeyError, tree_lookup_path, self.get_object, self.tree_id, b"j"
  750. )
  751. def test_lookup_not_tree(self) -> None:
  752. self.assertRaises(
  753. NotTreeError,
  754. tree_lookup_path,
  755. self.get_object,
  756. self.tree_id,
  757. b"ad/b/j",
  758. )
  759. def test_lookup_empty_path(self) -> None:
  760. # Empty path should return the tree itself
  761. mode, sha = tree_lookup_path(self.get_object, self.tree_id, b"")
  762. self.assertEqual(sha, self.tree_id)
  763. self.assertEqual(mode, stat.S_IFDIR)
  764. class ObjectStoreGraphWalkerTests(TestCase):
  765. def get_walker(self, heads, parent_map):
  766. new_parent_map = {
  767. k * 40: [(p * 40) for p in ps] for (k, ps) in parent_map.items()
  768. }
  769. return ObjectStoreGraphWalker(
  770. [x * 40 for x in heads], new_parent_map.__getitem__
  771. )
  772. def test_ack_invalid_value(self) -> None:
  773. gw = self.get_walker([], {})
  774. self.assertRaises(ValueError, gw.ack, "tooshort")
  775. def test_empty(self) -> None:
  776. gw = self.get_walker([], {})
  777. self.assertIs(None, next(gw))
  778. gw.ack(b"a" * 40)
  779. self.assertIs(None, next(gw))
  780. def test_descends(self) -> None:
  781. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []})
  782. self.assertEqual(b"a" * 40, next(gw))
  783. self.assertEqual(b"b" * 40, next(gw))
  784. def test_present(self) -> None:
  785. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []})
  786. gw.ack(b"a" * 40)
  787. self.assertIs(None, next(gw))
  788. def test_parent_present(self) -> None:
  789. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": []})
  790. self.assertEqual(b"a" * 40, next(gw))
  791. gw.ack(b"a" * 40)
  792. self.assertIs(None, next(gw))
  793. def test_child_ack_later(self) -> None:
  794. gw = self.get_walker([b"a"], {b"a": [b"b"], b"b": [b"c"], b"c": []})
  795. self.assertEqual(b"a" * 40, next(gw))
  796. self.assertEqual(b"b" * 40, next(gw))
  797. gw.ack(b"a" * 40)
  798. self.assertIs(None, next(gw))
  799. def test_only_once(self) -> None:
  800. # a b
  801. # | |
  802. # c d
  803. # \ /
  804. # e
  805. gw = self.get_walker(
  806. [b"a", b"b"],
  807. {
  808. b"a": [b"c"],
  809. b"b": [b"d"],
  810. b"c": [b"e"],
  811. b"d": [b"e"],
  812. b"e": [],
  813. },
  814. )
  815. walk = []
  816. acked = False
  817. walk.append(next(gw))
  818. walk.append(next(gw))
  819. # A branch (a, c) or (b, d) may be done after 2 steps or 3 depending on
  820. # the order walked: 3-step walks include (a, b, c) and (b, a, d), etc.
  821. if walk == [b"a" * 40, b"c" * 40] or walk == [b"b" * 40, b"d" * 40]:
  822. gw.ack(walk[0])
  823. acked = True
  824. walk.append(next(gw))
  825. if not acked and walk[2] == b"c" * 40:
  826. gw.ack(b"a" * 40)
  827. elif not acked and walk[2] == b"d" * 40:
  828. gw.ack(b"b" * 40)
  829. walk.append(next(gw))
  830. self.assertIs(None, next(gw))
  831. self.assertEqual([b"a" * 40, b"b" * 40, b"c" * 40, b"d" * 40], sorted(walk))
  832. self.assertLess(walk.index(b"a" * 40), walk.index(b"c" * 40))
  833. self.assertLess(walk.index(b"b" * 40), walk.index(b"d" * 40))
  834. class CommitTreeChangesTests(TestCase):
  835. def setUp(self) -> None:
  836. super().setUp()
  837. self.store = MemoryObjectStore()
  838. self.blob_a = make_object(Blob, data=b"a")
  839. self.blob_b = make_object(Blob, data=b"b")
  840. self.blob_c = make_object(Blob, data=b"c")
  841. for blob in [self.blob_a, self.blob_b, self.blob_c]:
  842. self.store.add_object(blob)
  843. blobs = [
  844. (b"a", self.blob_a.id, 0o100644),
  845. (b"ad/b", self.blob_b.id, 0o100644),
  846. (b"ad/bd/c", self.blob_c.id, 0o100755),
  847. (b"ad/c", self.blob_c.id, 0o100644),
  848. (b"c", self.blob_c.id, 0o100644),
  849. ]
  850. self.tree_id = commit_tree(self.store, blobs)
  851. def test_no_changes(self) -> None:
  852. # When no changes, should return the same tree SHA
  853. self.assertEqual(
  854. self.tree_id,
  855. commit_tree_changes(self.store, self.store[self.tree_id], []),
  856. )
  857. def test_add_blob(self) -> None:
  858. blob_d = make_object(Blob, data=b"d")
  859. new_tree_id = commit_tree_changes(
  860. self.store, self.store[self.tree_id], [(b"d", 0o100644, blob_d.id)]
  861. )
  862. new_tree = self.store[new_tree_id]
  863. self.assertEqual(
  864. new_tree[b"d"],
  865. (33188, b"c59d9b6344f1af00e504ba698129f07a34bbed8d"),
  866. )
  867. def test_add_blob_in_dir(self) -> None:
  868. blob_d = make_object(Blob, data=b"d")
  869. new_tree_id = commit_tree_changes(
  870. self.store,
  871. self.store[self.tree_id],
  872. [(b"e/f/d", 0o100644, blob_d.id)],
  873. )
  874. new_tree = self.store[new_tree_id]
  875. self.assertEqual(
  876. new_tree.items(),
  877. [
  878. TreeEntry(path=b"a", mode=stat.S_IFREG | 0o100644, sha=self.blob_a.id),
  879. TreeEntry(
  880. path=b"ad",
  881. mode=stat.S_IFDIR,
  882. sha=b"0e2ce2cd7725ff4817791be31ccd6e627e801f4a",
  883. ),
  884. TreeEntry(path=b"c", mode=stat.S_IFREG | 0o100644, sha=self.blob_c.id),
  885. TreeEntry(
  886. path=b"e",
  887. mode=stat.S_IFDIR,
  888. sha=b"6ab344e288724ac2fb38704728b8896e367ed108",
  889. ),
  890. ],
  891. )
  892. e_tree = self.store[new_tree[b"e"][1]]
  893. self.assertEqual(
  894. e_tree.items(),
  895. [
  896. TreeEntry(
  897. path=b"f",
  898. mode=stat.S_IFDIR,
  899. sha=b"24d2c94d8af232b15a0978c006bf61ef4479a0a5",
  900. )
  901. ],
  902. )
  903. f_tree = self.store[e_tree[b"f"][1]]
  904. self.assertEqual(
  905. f_tree.items(),
  906. [TreeEntry(path=b"d", mode=stat.S_IFREG | 0o100644, sha=blob_d.id)],
  907. )
  908. def test_delete_blob(self) -> None:
  909. new_tree_id = commit_tree_changes(
  910. self.store, self.store[self.tree_id], [(b"ad/bd/c", None, None)]
  911. )
  912. new_tree = self.store[new_tree_id]
  913. self.assertEqual(set(new_tree), {b"a", b"ad", b"c"})
  914. ad_tree = self.store[new_tree[b"ad"][1]]
  915. self.assertEqual(set(ad_tree), {b"b", b"c"})
  916. class TestReadPacksFile(TestCase):
  917. def test_read_packs(self) -> None:
  918. self.assertEqual(
  919. ["pack-1.pack"],
  920. list(
  921. read_packs_file(
  922. BytesIO(
  923. b"""P pack-1.pack
  924. """
  925. )
  926. )
  927. ),
  928. )