test_object_store.py 38 KB

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