2
0

test_pack.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. # test_pack.py -- Tests for the handling of git packs.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008 Jelmer Vernooij <jelmer@jelmer.uk>
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as public by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Tests for Dulwich packs."""
  23. import os
  24. import shutil
  25. import sys
  26. import tempfile
  27. import zlib
  28. from hashlib import sha1
  29. from io import BytesIO
  30. from typing import NoReturn
  31. from dulwich.errors import ApplyDeltaError, ChecksumMismatch
  32. from dulwich.file import GitFile
  33. from dulwich.object_store import MemoryObjectStore
  34. from dulwich.objects import Blob, Commit, Tree, hex_to_sha, sha_to_hex
  35. from dulwich.pack import (
  36. OFS_DELTA,
  37. REF_DELTA,
  38. DeltaChainIterator,
  39. MemoryPackIndex,
  40. Pack,
  41. PackData,
  42. PackStreamReader,
  43. UnpackedObject,
  44. UnresolvedDeltas,
  45. _delta_encode_size,
  46. _encode_copy_operation,
  47. apply_delta,
  48. compute_file_sha,
  49. create_delta,
  50. deltify_pack_objects,
  51. load_pack_index,
  52. read_zlib_chunks,
  53. unpack_object,
  54. write_pack,
  55. write_pack_header,
  56. write_pack_index_v1,
  57. write_pack_index_v2,
  58. write_pack_object,
  59. )
  60. from dulwich.tests.utils import build_pack, make_object
  61. from . import TestCase
  62. pack1_sha = b"bc63ddad95e7321ee734ea11a7a62d314e0d7481"
  63. a_sha = b"6f670c0fb53f9463760b7295fbb814e965fb20c8"
  64. tree_sha = b"b2a2766a2879c209ab1176e7e778b81ae422eeaa"
  65. commit_sha = b"f18faa16531ac570a3fdc8c7ca16682548dafd12"
  66. indexmode = "0o100644" if sys.platform != "win32" else "0o100666"
  67. class PackTests(TestCase):
  68. """Base class for testing packs."""
  69. def setUp(self) -> None:
  70. super().setUp()
  71. self.tempdir = tempfile.mkdtemp()
  72. self.addCleanup(shutil.rmtree, self.tempdir)
  73. datadir = os.path.abspath(
  74. os.path.join(os.path.dirname(__file__), "../testdata/packs")
  75. )
  76. def get_pack_index(self, sha):
  77. """Returns a PackIndex from the datadir with the given sha."""
  78. return load_pack_index(
  79. os.path.join(self.datadir, "pack-{}.idx".format(sha.decode("ascii")))
  80. )
  81. def get_pack_data(self, sha):
  82. """Returns a PackData object from the datadir with the given sha."""
  83. return PackData(
  84. os.path.join(self.datadir, "pack-{}.pack".format(sha.decode("ascii")))
  85. )
  86. def get_pack(self, sha):
  87. return Pack(os.path.join(self.datadir, "pack-{}".format(sha.decode("ascii"))))
  88. def assertSucceeds(self, func, *args, **kwargs) -> None:
  89. try:
  90. func(*args, **kwargs)
  91. except ChecksumMismatch as e:
  92. self.fail(e)
  93. class PackIndexTests(PackTests):
  94. """Class that tests the index of packfiles."""
  95. def test_object_offset(self) -> None:
  96. """Tests that the correct object offset is returned from the index."""
  97. p = self.get_pack_index(pack1_sha)
  98. self.assertRaises(KeyError, p.object_offset, pack1_sha)
  99. self.assertEqual(p.object_offset(a_sha), 178)
  100. self.assertEqual(p.object_offset(tree_sha), 138)
  101. self.assertEqual(p.object_offset(commit_sha), 12)
  102. def test_object_sha1(self) -> None:
  103. """Tests that the correct object offset is returned from the index."""
  104. p = self.get_pack_index(pack1_sha)
  105. self.assertRaises(KeyError, p.object_sha1, 876)
  106. self.assertEqual(p.object_sha1(178), hex_to_sha(a_sha))
  107. self.assertEqual(p.object_sha1(138), hex_to_sha(tree_sha))
  108. self.assertEqual(p.object_sha1(12), hex_to_sha(commit_sha))
  109. def test_iter_prefix(self) -> None:
  110. p = self.get_pack_index(pack1_sha)
  111. self.assertEqual([p.object_sha1(178)], list(p.iter_prefix(hex_to_sha(a_sha))))
  112. self.assertEqual(
  113. [p.object_sha1(178)], list(p.iter_prefix(hex_to_sha(a_sha)[:5]))
  114. )
  115. self.assertEqual(
  116. [p.object_sha1(178)], list(p.iter_prefix(hex_to_sha(a_sha)[:2]))
  117. )
  118. def test_index_len(self) -> None:
  119. p = self.get_pack_index(pack1_sha)
  120. self.assertEqual(3, len(p))
  121. def test_get_stored_checksum(self) -> None:
  122. p = self.get_pack_index(pack1_sha)
  123. self.assertEqual(
  124. b"f2848e2ad16f329ae1c92e3b95e91888daa5bd01",
  125. sha_to_hex(p.get_stored_checksum()),
  126. )
  127. self.assertEqual(
  128. b"721980e866af9a5f93ad674144e1459b8ba3e7b7",
  129. sha_to_hex(p.get_pack_checksum()),
  130. )
  131. def test_index_check(self) -> None:
  132. p = self.get_pack_index(pack1_sha)
  133. self.assertSucceeds(p.check)
  134. def test_iterentries(self) -> None:
  135. p = self.get_pack_index(pack1_sha)
  136. entries = [(sha_to_hex(s), o, c) for s, o, c in p.iterentries()]
  137. self.assertEqual(
  138. [
  139. (b"6f670c0fb53f9463760b7295fbb814e965fb20c8", 178, None),
  140. (b"b2a2766a2879c209ab1176e7e778b81ae422eeaa", 138, None),
  141. (b"f18faa16531ac570a3fdc8c7ca16682548dafd12", 12, None),
  142. ],
  143. entries,
  144. )
  145. def test_iter(self) -> None:
  146. p = self.get_pack_index(pack1_sha)
  147. self.assertEqual({tree_sha, commit_sha, a_sha}, set(p))
  148. class TestPackDeltas(TestCase):
  149. test_string1 = b"The answer was flailing in the wind"
  150. test_string2 = b"The answer was falling down the pipe"
  151. test_string3 = b"zzzzz"
  152. test_string_empty = b""
  153. test_string_big = b"Z" * 8192
  154. test_string_huge = b"Z" * 100000
  155. def _test_roundtrip(self, base, target) -> None:
  156. self.assertEqual(
  157. target, b"".join(apply_delta(base, list(create_delta(base, target))))
  158. )
  159. def test_nochange(self) -> None:
  160. self._test_roundtrip(self.test_string1, self.test_string1)
  161. def test_nochange_huge(self) -> None:
  162. self._test_roundtrip(self.test_string_huge, self.test_string_huge)
  163. def test_change(self) -> None:
  164. self._test_roundtrip(self.test_string1, self.test_string2)
  165. def test_rewrite(self) -> None:
  166. self._test_roundtrip(self.test_string1, self.test_string3)
  167. def test_empty_to_big(self) -> None:
  168. self._test_roundtrip(self.test_string_empty, self.test_string_big)
  169. def test_empty_to_huge(self) -> None:
  170. self._test_roundtrip(self.test_string_empty, self.test_string_huge)
  171. def test_huge_copy(self) -> None:
  172. self._test_roundtrip(
  173. self.test_string_huge + self.test_string1,
  174. self.test_string_huge + self.test_string2,
  175. )
  176. def test_dest_overflow(self) -> None:
  177. self.assertRaises(
  178. ApplyDeltaError,
  179. apply_delta,
  180. b"a" * 0x10000,
  181. b"\x80\x80\x04\x80\x80\x04\x80" + b"a" * 0x10000,
  182. )
  183. self.assertRaises(
  184. ApplyDeltaError, apply_delta, b"", b"\x00\x80\x02\xb0\x11\x11"
  185. )
  186. def test_pypy_issue(self) -> None:
  187. # Test for https://github.com/jelmer/dulwich/issues/509 /
  188. # https://bitbucket.org/pypy/pypy/issues/2499/cpyext-pystring_asstring-doesnt-work
  189. chunks = [
  190. b"tree 03207ccf58880a748188836155ceed72f03d65d6\n"
  191. b"parent 408fbab530fd4abe49249a636a10f10f44d07a21\n"
  192. b"author Victor Stinner <victor.stinner@gmail.com> "
  193. b"1421355207 +0100\n"
  194. b"committer Victor Stinner <victor.stinner@gmail.com> "
  195. b"1421355207 +0100\n"
  196. b"\n"
  197. b"Backout changeset 3a06020af8cf\n"
  198. b"\nStreamWriter: close() now clears the reference to the "
  199. b"transport\n"
  200. b"\nStreamWriter now raises an exception if it is closed: "
  201. b"write(), writelines(),\n"
  202. b"write_eof(), can_write_eof(), get_extra_info(), drain().\n"
  203. ]
  204. delta = [
  205. b"\xcd\x03\xad\x03]tree ff3c181a393d5a7270cddc01ea863818a8621ca8\n"
  206. b"parent 20a103cc90135494162e819f98d0edfc1f1fba6b\x91]7\x0510738"
  207. b"\x91\x99@\x0b10738 +0100\x93\x04\x01\xc9"
  208. ]
  209. res = apply_delta(chunks, delta)
  210. expected = [
  211. b"tree ff3c181a393d5a7270cddc01ea863818a8621ca8\n"
  212. b"parent 20a103cc90135494162e819f98d0edfc1f1fba6b",
  213. b"\nauthor Victor Stinner <victor.stinner@gmail.com> 14213",
  214. b"10738",
  215. b" +0100\ncommitter Victor Stinner <victor.stinner@gmail.com> " b"14213",
  216. b"10738 +0100",
  217. b"\n\nStreamWriter: close() now clears the reference to the "
  218. b"transport\n\n"
  219. b"StreamWriter now raises an exception if it is closed: "
  220. b"write(), writelines(),\n"
  221. b"write_eof(), can_write_eof(), get_extra_info(), drain().\n",
  222. ]
  223. self.assertEqual(b"".join(expected), b"".join(res))
  224. class TestPackData(PackTests):
  225. """Tests getting the data from the packfile."""
  226. def test_create_pack(self) -> None:
  227. self.get_pack_data(pack1_sha).close()
  228. def test_from_file(self) -> None:
  229. path = os.path.join(
  230. self.datadir, "pack-{}.pack".format(pack1_sha.decode("ascii"))
  231. )
  232. with open(path, "rb") as f:
  233. PackData.from_file(f, os.path.getsize(path))
  234. def test_pack_len(self) -> None:
  235. with self.get_pack_data(pack1_sha) as p:
  236. self.assertEqual(3, len(p))
  237. def test_index_check(self) -> None:
  238. with self.get_pack_data(pack1_sha) as p:
  239. self.assertSucceeds(p.check)
  240. def test_iter_unpacked(self) -> None:
  241. with self.get_pack_data(pack1_sha) as p:
  242. commit_data = (
  243. b"tree b2a2766a2879c209ab1176e7e778b81ae422eeaa\n"
  244. b"author James Westby <jw+debian@jameswestby.net> "
  245. b"1174945067 +0100\n"
  246. b"committer James Westby <jw+debian@jameswestby.net> "
  247. b"1174945067 +0100\n"
  248. b"\n"
  249. b"Test commit\n"
  250. )
  251. blob_sha = b"6f670c0fb53f9463760b7295fbb814e965fb20c8"
  252. tree_data = b"100644 a\0" + hex_to_sha(blob_sha)
  253. actual = list(p.iter_unpacked())
  254. self.assertEqual(
  255. [
  256. UnpackedObject(
  257. offset=12,
  258. pack_type_num=1,
  259. decomp_chunks=[commit_data],
  260. crc32=None,
  261. ),
  262. UnpackedObject(
  263. offset=138,
  264. pack_type_num=2,
  265. decomp_chunks=[tree_data],
  266. crc32=None,
  267. ),
  268. UnpackedObject(
  269. offset=178,
  270. pack_type_num=3,
  271. decomp_chunks=[b"test 1\n"],
  272. crc32=None,
  273. ),
  274. ],
  275. actual,
  276. )
  277. def test_iterentries(self) -> None:
  278. with self.get_pack_data(pack1_sha) as p:
  279. entries = {(sha_to_hex(s), o, c) for s, o, c in p.iterentries()}
  280. self.assertEqual(
  281. {
  282. (
  283. b"6f670c0fb53f9463760b7295fbb814e965fb20c8",
  284. 178,
  285. 1373561701,
  286. ),
  287. (
  288. b"b2a2766a2879c209ab1176e7e778b81ae422eeaa",
  289. 138,
  290. 912998690,
  291. ),
  292. (
  293. b"f18faa16531ac570a3fdc8c7ca16682548dafd12",
  294. 12,
  295. 3775879613,
  296. ),
  297. },
  298. entries,
  299. )
  300. def test_create_index_v1(self) -> None:
  301. with self.get_pack_data(pack1_sha) as p:
  302. filename = os.path.join(self.tempdir, "v1test.idx")
  303. p.create_index_v1(filename)
  304. idx1 = load_pack_index(filename)
  305. idx2 = self.get_pack_index(pack1_sha)
  306. self.assertEqual(oct(os.stat(filename).st_mode), indexmode)
  307. self.assertEqual(idx1, idx2)
  308. def test_create_index_v2(self) -> None:
  309. with self.get_pack_data(pack1_sha) as p:
  310. filename = os.path.join(self.tempdir, "v2test.idx")
  311. p.create_index_v2(filename)
  312. idx1 = load_pack_index(filename)
  313. idx2 = self.get_pack_index(pack1_sha)
  314. self.assertEqual(oct(os.stat(filename).st_mode), indexmode)
  315. self.assertEqual(idx1, idx2)
  316. def test_compute_file_sha(self) -> None:
  317. f = BytesIO(b"abcd1234wxyz")
  318. self.assertEqual(
  319. sha1(b"abcd1234wxyz").hexdigest(), compute_file_sha(f).hexdigest()
  320. )
  321. self.assertEqual(
  322. sha1(b"abcd1234wxyz").hexdigest(),
  323. compute_file_sha(f, buffer_size=5).hexdigest(),
  324. )
  325. self.assertEqual(
  326. sha1(b"abcd1234").hexdigest(),
  327. compute_file_sha(f, end_ofs=-4).hexdigest(),
  328. )
  329. self.assertEqual(
  330. sha1(b"1234wxyz").hexdigest(),
  331. compute_file_sha(f, start_ofs=4).hexdigest(),
  332. )
  333. self.assertEqual(
  334. sha1(b"1234").hexdigest(),
  335. compute_file_sha(f, start_ofs=4, end_ofs=-4).hexdigest(),
  336. )
  337. def test_compute_file_sha_short_file(self) -> None:
  338. f = BytesIO(b"abcd1234wxyz")
  339. self.assertRaises(AssertionError, compute_file_sha, f, end_ofs=-20)
  340. self.assertRaises(AssertionError, compute_file_sha, f, end_ofs=20)
  341. self.assertRaises(
  342. AssertionError, compute_file_sha, f, start_ofs=10, end_ofs=-12
  343. )
  344. class TestPack(PackTests):
  345. def test_len(self) -> None:
  346. with self.get_pack(pack1_sha) as p:
  347. self.assertEqual(3, len(p))
  348. def test_contains(self) -> None:
  349. with self.get_pack(pack1_sha) as p:
  350. self.assertIn(tree_sha, p)
  351. def test_get(self) -> None:
  352. with self.get_pack(pack1_sha) as p:
  353. self.assertEqual(type(p[tree_sha]), Tree)
  354. def test_iter(self) -> None:
  355. with self.get_pack(pack1_sha) as p:
  356. self.assertEqual({tree_sha, commit_sha, a_sha}, set(p))
  357. def test_iterobjects(self) -> None:
  358. with self.get_pack(pack1_sha) as p:
  359. expected = {p[s] for s in [commit_sha, tree_sha, a_sha]}
  360. self.assertEqual(expected, set(list(p.iterobjects())))
  361. def test_pack_tuples(self) -> None:
  362. with self.get_pack(pack1_sha) as p:
  363. tuples = p.pack_tuples()
  364. expected = {(p[s], None) for s in [commit_sha, tree_sha, a_sha]}
  365. self.assertEqual(expected, set(list(tuples)))
  366. self.assertEqual(expected, set(list(tuples)))
  367. self.assertEqual(3, len(tuples))
  368. def test_get_object_at(self) -> None:
  369. """Tests random access for non-delta objects."""
  370. with self.get_pack(pack1_sha) as p:
  371. obj = p[a_sha]
  372. self.assertEqual(obj.type_name, b"blob")
  373. self.assertEqual(obj.sha().hexdigest().encode("ascii"), a_sha)
  374. obj = p[tree_sha]
  375. self.assertEqual(obj.type_name, b"tree")
  376. self.assertEqual(obj.sha().hexdigest().encode("ascii"), tree_sha)
  377. obj = p[commit_sha]
  378. self.assertEqual(obj.type_name, b"commit")
  379. self.assertEqual(obj.sha().hexdigest().encode("ascii"), commit_sha)
  380. def test_copy(self) -> None:
  381. with self.get_pack(pack1_sha) as origpack:
  382. self.assertSucceeds(origpack.index.check)
  383. basename = os.path.join(self.tempdir, "Elch")
  384. write_pack(basename, origpack.pack_tuples())
  385. with Pack(basename) as newpack:
  386. self.assertEqual(origpack, newpack)
  387. self.assertSucceeds(newpack.index.check)
  388. self.assertEqual(origpack.name(), newpack.name())
  389. self.assertEqual(
  390. origpack.index.get_pack_checksum(),
  391. newpack.index.get_pack_checksum(),
  392. )
  393. wrong_version = origpack.index.version != newpack.index.version
  394. orig_checksum = origpack.index.get_stored_checksum()
  395. new_checksum = newpack.index.get_stored_checksum()
  396. self.assertTrue(wrong_version or orig_checksum == new_checksum)
  397. def test_commit_obj(self) -> None:
  398. with self.get_pack(pack1_sha) as p:
  399. commit = p[commit_sha]
  400. self.assertEqual(b"James Westby <jw+debian@jameswestby.net>", commit.author)
  401. self.assertEqual([], commit.parents)
  402. def _copy_pack(self, origpack):
  403. basename = os.path.join(self.tempdir, "somepack")
  404. write_pack(basename, origpack.pack_tuples())
  405. return Pack(basename)
  406. def test_keep_no_message(self) -> None:
  407. with self.get_pack(pack1_sha) as p:
  408. p = self._copy_pack(p)
  409. with p:
  410. keepfile_name = p.keep()
  411. # file should exist
  412. self.assertTrue(os.path.exists(keepfile_name))
  413. with open(keepfile_name) as f:
  414. buf = f.read()
  415. self.assertEqual("", buf)
  416. def test_keep_message(self) -> None:
  417. with self.get_pack(pack1_sha) as p:
  418. p = self._copy_pack(p)
  419. msg = b"some message"
  420. with p:
  421. keepfile_name = p.keep(msg)
  422. # file should exist
  423. self.assertTrue(os.path.exists(keepfile_name))
  424. # and contain the right message, with a linefeed
  425. with open(keepfile_name, "rb") as f:
  426. buf = f.read()
  427. self.assertEqual(msg + b"\n", buf)
  428. def test_name(self) -> None:
  429. with self.get_pack(pack1_sha) as p:
  430. self.assertEqual(pack1_sha, p.name())
  431. def test_length_mismatch(self) -> None:
  432. with self.get_pack_data(pack1_sha) as data:
  433. index = self.get_pack_index(pack1_sha)
  434. Pack.from_objects(data, index).check_length_and_checksum()
  435. data._file.seek(12)
  436. bad_file = BytesIO()
  437. write_pack_header(bad_file.write, 9999)
  438. bad_file.write(data._file.read())
  439. bad_file = BytesIO(bad_file.getvalue())
  440. bad_data = PackData("", file=bad_file)
  441. bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index)
  442. self.assertRaises(AssertionError, lambda: bad_pack.data)
  443. self.assertRaises(AssertionError, bad_pack.check_length_and_checksum)
  444. def test_checksum_mismatch(self) -> None:
  445. with self.get_pack_data(pack1_sha) as data:
  446. index = self.get_pack_index(pack1_sha)
  447. Pack.from_objects(data, index).check_length_and_checksum()
  448. data._file.seek(0)
  449. bad_file = BytesIO(data._file.read()[:-20] + (b"\xff" * 20))
  450. bad_data = PackData("", file=bad_file)
  451. bad_pack = Pack.from_lazy_objects(lambda: bad_data, lambda: index)
  452. self.assertRaises(ChecksumMismatch, lambda: bad_pack.data)
  453. self.assertRaises(ChecksumMismatch, bad_pack.check_length_and_checksum)
  454. def test_iterobjects_2(self) -> None:
  455. with self.get_pack(pack1_sha) as p:
  456. objs = {o.id: o for o in p.iterobjects()}
  457. self.assertEqual(3, len(objs))
  458. self.assertEqual(sorted(objs), sorted(p.index))
  459. self.assertIsInstance(objs[a_sha], Blob)
  460. self.assertIsInstance(objs[tree_sha], Tree)
  461. self.assertIsInstance(objs[commit_sha], Commit)
  462. def test_iterobjects_subset(self) -> None:
  463. with self.get_pack(pack1_sha) as p:
  464. objs = {o.id: o for o in p.iterobjects_subset([commit_sha])}
  465. self.assertEqual(1, len(objs))
  466. self.assertIsInstance(objs[commit_sha], Commit)
  467. class TestThinPack(PackTests):
  468. def setUp(self) -> None:
  469. super().setUp()
  470. self.store = MemoryObjectStore()
  471. self.blobs = {}
  472. for blob in (b"foo", b"bar", b"foo1234", b"bar2468"):
  473. self.blobs[blob] = make_object(Blob, data=blob)
  474. self.store.add_object(self.blobs[b"foo"])
  475. self.store.add_object(self.blobs[b"bar"])
  476. # Build a thin pack. 'foo' is as an external reference, 'bar' an
  477. # internal reference.
  478. self.pack_dir = tempfile.mkdtemp()
  479. self.addCleanup(shutil.rmtree, self.pack_dir)
  480. self.pack_prefix = os.path.join(self.pack_dir, "pack")
  481. with open(self.pack_prefix + ".pack", "wb") as f:
  482. build_pack(
  483. f,
  484. [
  485. (REF_DELTA, (self.blobs[b"foo"].id, b"foo1234")),
  486. (Blob.type_num, b"bar"),
  487. (REF_DELTA, (self.blobs[b"bar"].id, b"bar2468")),
  488. ],
  489. store=self.store,
  490. )
  491. # Index the new pack.
  492. with self.make_pack(True) as pack:
  493. with PackData(pack._data_path) as data:
  494. data.create_index(
  495. self.pack_prefix + ".idx", resolve_ext_ref=pack.resolve_ext_ref
  496. )
  497. del self.store[self.blobs[b"bar"].id]
  498. def make_pack(self, resolve_ext_ref):
  499. return Pack(
  500. self.pack_prefix,
  501. resolve_ext_ref=self.store.get_raw if resolve_ext_ref else None,
  502. )
  503. def test_get_raw(self) -> None:
  504. with self.make_pack(False) as p:
  505. self.assertRaises(KeyError, p.get_raw, self.blobs[b"foo1234"].id)
  506. with self.make_pack(True) as p:
  507. self.assertEqual((3, b"foo1234"), p.get_raw(self.blobs[b"foo1234"].id))
  508. def test_get_unpacked_object(self) -> None:
  509. self.maxDiff = None
  510. with self.make_pack(False) as p:
  511. expected = UnpackedObject(
  512. 7,
  513. delta_base=b"\x19\x10(\x15f=#\xf8\xb7ZG\xe7\xa0\x19e\xdc\xdc\x96F\x8c",
  514. decomp_chunks=[b"\x03\x07\x90\x03\x041234"],
  515. )
  516. expected.offset = 12
  517. got = p.get_unpacked_object(self.blobs[b"foo1234"].id)
  518. self.assertEqual(expected, got)
  519. with self.make_pack(True) as p:
  520. expected = UnpackedObject(
  521. 7,
  522. delta_base=b"\x19\x10(\x15f=#\xf8\xb7ZG\xe7\xa0\x19e\xdc\xdc\x96F\x8c",
  523. decomp_chunks=[b"\x03\x07\x90\x03\x041234"],
  524. )
  525. expected.offset = 12
  526. got = p.get_unpacked_object(self.blobs[b"foo1234"].id)
  527. self.assertEqual(
  528. expected,
  529. got,
  530. )
  531. def test_iterobjects(self) -> None:
  532. with self.make_pack(False) as p:
  533. self.assertRaises(UnresolvedDeltas, list, p.iterobjects())
  534. with self.make_pack(True) as p:
  535. self.assertEqual(
  536. sorted(
  537. [
  538. self.blobs[b"foo1234"].id,
  539. self.blobs[b"bar"].id,
  540. self.blobs[b"bar2468"].id,
  541. ]
  542. ),
  543. sorted(o.id for o in p.iterobjects()),
  544. )
  545. class WritePackTests(TestCase):
  546. def test_write_pack_header(self) -> None:
  547. f = BytesIO()
  548. write_pack_header(f.write, 42)
  549. self.assertEqual(b"PACK\x00\x00\x00\x02\x00\x00\x00*", f.getvalue())
  550. def test_write_pack_object(self) -> None:
  551. f = BytesIO()
  552. f.write(b"header")
  553. offset = f.tell()
  554. crc32 = write_pack_object(f.write, Blob.type_num, b"blob")
  555. self.assertEqual(crc32, zlib.crc32(f.getvalue()[6:]) & 0xFFFFFFFF)
  556. f.write(b"x") # unpack_object needs extra trailing data.
  557. f.seek(offset)
  558. unpacked, unused = unpack_object(f.read, compute_crc32=True)
  559. self.assertEqual(Blob.type_num, unpacked.pack_type_num)
  560. self.assertEqual(Blob.type_num, unpacked.obj_type_num)
  561. self.assertEqual([b"blob"], unpacked.decomp_chunks)
  562. self.assertEqual(crc32, unpacked.crc32)
  563. self.assertEqual(b"x", unused)
  564. def test_write_pack_object_sha(self) -> None:
  565. f = BytesIO()
  566. f.write(b"header")
  567. offset = f.tell()
  568. sha_a = sha1(b"foo")
  569. sha_b = sha_a.copy()
  570. write_pack_object(f.write, Blob.type_num, b"blob", sha=sha_a)
  571. self.assertNotEqual(sha_a.digest(), sha_b.digest())
  572. sha_b.update(f.getvalue()[offset:])
  573. self.assertEqual(sha_a.digest(), sha_b.digest())
  574. def test_write_pack_object_compression_level(self) -> None:
  575. f = BytesIO()
  576. f.write(b"header")
  577. offset = f.tell()
  578. sha_a = sha1(b"foo")
  579. sha_b = sha_a.copy()
  580. write_pack_object(
  581. f.write, Blob.type_num, b"blob", sha=sha_a, compression_level=6
  582. )
  583. self.assertNotEqual(sha_a.digest(), sha_b.digest())
  584. sha_b.update(f.getvalue()[offset:])
  585. self.assertEqual(sha_a.digest(), sha_b.digest())
  586. pack_checksum = hex_to_sha("721980e866af9a5f93ad674144e1459b8ba3e7b7")
  587. class BaseTestPackIndexWriting:
  588. def assertSucceeds(self, func, *args, **kwargs) -> None:
  589. try:
  590. func(*args, **kwargs)
  591. except ChecksumMismatch as e:
  592. self.fail(e)
  593. def index(self, filename, entries, pack_checksum) -> NoReturn:
  594. raise NotImplementedError(self.index)
  595. def test_empty(self) -> None:
  596. idx = self.index("empty.idx", [], pack_checksum)
  597. self.assertEqual(idx.get_pack_checksum(), pack_checksum)
  598. self.assertEqual(0, len(idx))
  599. def test_large(self) -> None:
  600. entry1_sha = hex_to_sha("4e6388232ec39792661e2e75db8fb117fc869ce6")
  601. entry2_sha = hex_to_sha("e98f071751bd77f59967bfa671cd2caebdccc9a2")
  602. entries = [
  603. (entry1_sha, 0xF2972D0830529B87, 24),
  604. (entry2_sha, (~0xF2972D0830529B87) & (2**64 - 1), 92),
  605. ]
  606. if not self._supports_large:
  607. self.assertRaises(
  608. TypeError, self.index, "single.idx", entries, pack_checksum
  609. )
  610. return
  611. idx = self.index("single.idx", entries, pack_checksum)
  612. self.assertEqual(idx.get_pack_checksum(), pack_checksum)
  613. self.assertEqual(2, len(idx))
  614. actual_entries = list(idx.iterentries())
  615. self.assertEqual(len(entries), len(actual_entries))
  616. for mine, actual in zip(entries, actual_entries):
  617. my_sha, my_offset, my_crc = mine
  618. actual_sha, actual_offset, actual_crc = actual
  619. self.assertEqual(my_sha, actual_sha)
  620. self.assertEqual(my_offset, actual_offset)
  621. if self._has_crc32_checksum:
  622. self.assertEqual(my_crc, actual_crc)
  623. else:
  624. self.assertIsNone(actual_crc)
  625. def test_single(self) -> None:
  626. entry_sha = hex_to_sha("6f670c0fb53f9463760b7295fbb814e965fb20c8")
  627. my_entries = [(entry_sha, 178, 42)]
  628. idx = self.index("single.idx", my_entries, pack_checksum)
  629. self.assertEqual(idx.get_pack_checksum(), pack_checksum)
  630. self.assertEqual(1, len(idx))
  631. actual_entries = list(idx.iterentries())
  632. self.assertEqual(len(my_entries), len(actual_entries))
  633. for mine, actual in zip(my_entries, actual_entries):
  634. my_sha, my_offset, my_crc = mine
  635. actual_sha, actual_offset, actual_crc = actual
  636. self.assertEqual(my_sha, actual_sha)
  637. self.assertEqual(my_offset, actual_offset)
  638. if self._has_crc32_checksum:
  639. self.assertEqual(my_crc, actual_crc)
  640. else:
  641. self.assertIsNone(actual_crc)
  642. class BaseTestFilePackIndexWriting(BaseTestPackIndexWriting):
  643. def setUp(self) -> None:
  644. self.tempdir = tempfile.mkdtemp()
  645. def tearDown(self) -> None:
  646. shutil.rmtree(self.tempdir)
  647. def index(self, filename, entries, pack_checksum):
  648. path = os.path.join(self.tempdir, filename)
  649. self.writeIndex(path, entries, pack_checksum)
  650. idx = load_pack_index(path)
  651. self.assertSucceeds(idx.check)
  652. self.assertEqual(idx.version, self._expected_version)
  653. return idx
  654. def writeIndex(self, filename, entries, pack_checksum) -> None:
  655. # FIXME: Write to BytesIO instead rather than hitting disk ?
  656. with GitFile(filename, "wb") as f:
  657. self._write_fn(f, entries, pack_checksum)
  658. class TestMemoryIndexWriting(TestCase, BaseTestPackIndexWriting):
  659. def setUp(self) -> None:
  660. TestCase.setUp(self)
  661. self._has_crc32_checksum = True
  662. self._supports_large = True
  663. def index(self, filename, entries, pack_checksum):
  664. return MemoryPackIndex(entries, pack_checksum)
  665. def tearDown(self) -> None:
  666. TestCase.tearDown(self)
  667. class TestPackIndexWritingv1(TestCase, BaseTestFilePackIndexWriting):
  668. def setUp(self) -> None:
  669. TestCase.setUp(self)
  670. BaseTestFilePackIndexWriting.setUp(self)
  671. self._has_crc32_checksum = False
  672. self._expected_version = 1
  673. self._supports_large = False
  674. self._write_fn = write_pack_index_v1
  675. def tearDown(self) -> None:
  676. TestCase.tearDown(self)
  677. BaseTestFilePackIndexWriting.tearDown(self)
  678. class TestPackIndexWritingv2(TestCase, BaseTestFilePackIndexWriting):
  679. def setUp(self) -> None:
  680. TestCase.setUp(self)
  681. BaseTestFilePackIndexWriting.setUp(self)
  682. self._has_crc32_checksum = True
  683. self._supports_large = True
  684. self._expected_version = 2
  685. self._write_fn = write_pack_index_v2
  686. def tearDown(self) -> None:
  687. TestCase.tearDown(self)
  688. BaseTestFilePackIndexWriting.tearDown(self)
  689. class ReadZlibTests(TestCase):
  690. decomp = (
  691. b"tree 4ada885c9196b6b6fa08744b5862bf92896fc002\n"
  692. b"parent None\n"
  693. b"author Jelmer Vernooij <jelmer@samba.org> 1228980214 +0000\n"
  694. b"committer Jelmer Vernooij <jelmer@samba.org> 1228980214 +0000\n"
  695. b"\n"
  696. b"Provide replacement for mmap()'s offset argument."
  697. )
  698. comp = zlib.compress(decomp)
  699. extra = b"nextobject"
  700. def setUp(self) -> None:
  701. super().setUp()
  702. self.read = BytesIO(self.comp + self.extra).read
  703. self.unpacked = UnpackedObject(
  704. Tree.type_num, decomp_len=len(self.decomp), crc32=0
  705. )
  706. def test_decompress_size(self) -> None:
  707. good_decomp_len = len(self.decomp)
  708. self.unpacked.decomp_len = -1
  709. self.assertRaises(ValueError, read_zlib_chunks, self.read, self.unpacked)
  710. self.unpacked.decomp_len = good_decomp_len - 1
  711. self.assertRaises(zlib.error, read_zlib_chunks, self.read, self.unpacked)
  712. self.unpacked.decomp_len = good_decomp_len + 1
  713. self.assertRaises(zlib.error, read_zlib_chunks, self.read, self.unpacked)
  714. def test_decompress_truncated(self) -> None:
  715. read = BytesIO(self.comp[:10]).read
  716. self.assertRaises(zlib.error, read_zlib_chunks, read, self.unpacked)
  717. read = BytesIO(self.comp).read
  718. self.assertRaises(zlib.error, read_zlib_chunks, read, self.unpacked)
  719. def test_decompress_empty(self) -> None:
  720. unpacked = UnpackedObject(Tree.type_num, decomp_len=0)
  721. comp = zlib.compress(b"")
  722. read = BytesIO(comp + self.extra).read
  723. unused = read_zlib_chunks(read, unpacked)
  724. self.assertEqual(b"", b"".join(unpacked.decomp_chunks))
  725. self.assertNotEqual(b"", unused)
  726. self.assertEqual(self.extra, unused + read())
  727. def test_decompress_no_crc32(self) -> None:
  728. self.unpacked.crc32 = None
  729. read_zlib_chunks(self.read, self.unpacked)
  730. self.assertEqual(None, self.unpacked.crc32)
  731. def _do_decompress_test(self, buffer_size, **kwargs) -> None:
  732. unused = read_zlib_chunks(
  733. self.read, self.unpacked, buffer_size=buffer_size, **kwargs
  734. )
  735. self.assertEqual(self.decomp, b"".join(self.unpacked.decomp_chunks))
  736. self.assertEqual(zlib.crc32(self.comp), self.unpacked.crc32)
  737. self.assertNotEqual(b"", unused)
  738. self.assertEqual(self.extra, unused + self.read())
  739. def test_simple_decompress(self) -> None:
  740. self._do_decompress_test(4096)
  741. self.assertEqual(None, self.unpacked.comp_chunks)
  742. # These buffer sizes are not intended to be realistic, but rather simulate
  743. # larger buffer sizes that may end at various places.
  744. def test_decompress_buffer_size_1(self) -> None:
  745. self._do_decompress_test(1)
  746. def test_decompress_buffer_size_2(self) -> None:
  747. self._do_decompress_test(2)
  748. def test_decompress_buffer_size_3(self) -> None:
  749. self._do_decompress_test(3)
  750. def test_decompress_buffer_size_4(self) -> None:
  751. self._do_decompress_test(4)
  752. def test_decompress_include_comp(self) -> None:
  753. self._do_decompress_test(4096, include_comp=True)
  754. self.assertEqual(self.comp, b"".join(self.unpacked.comp_chunks))
  755. class DeltifyTests(TestCase):
  756. def test_empty(self) -> None:
  757. self.assertEqual([], list(deltify_pack_objects([])))
  758. def test_single(self) -> None:
  759. b = Blob.from_string(b"foo")
  760. self.assertEqual(
  761. [
  762. UnpackedObject(
  763. b.type_num,
  764. sha=b.sha().digest(),
  765. delta_base=None,
  766. decomp_chunks=b.as_raw_chunks(),
  767. )
  768. ],
  769. list(deltify_pack_objects([(b, b"")])),
  770. )
  771. def test_simple_delta(self) -> None:
  772. b1 = Blob.from_string(b"a" * 101)
  773. b2 = Blob.from_string(b"a" * 100)
  774. delta = list(create_delta(b1.as_raw_chunks(), b2.as_raw_chunks()))
  775. self.assertEqual(
  776. [
  777. UnpackedObject(
  778. b1.type_num,
  779. sha=b1.sha().digest(),
  780. delta_base=None,
  781. decomp_chunks=b1.as_raw_chunks(),
  782. ),
  783. UnpackedObject(
  784. b2.type_num,
  785. sha=b2.sha().digest(),
  786. delta_base=b1.sha().digest(),
  787. decomp_chunks=delta,
  788. ),
  789. ],
  790. list(deltify_pack_objects([(b1, b""), (b2, b"")])),
  791. )
  792. class TestPackStreamReader(TestCase):
  793. def test_read_objects_emtpy(self) -> None:
  794. f = BytesIO()
  795. build_pack(f, [])
  796. reader = PackStreamReader(f.read)
  797. self.assertEqual(0, len(list(reader.read_objects())))
  798. def test_read_objects(self) -> None:
  799. f = BytesIO()
  800. entries = build_pack(
  801. f,
  802. [
  803. (Blob.type_num, b"blob"),
  804. (OFS_DELTA, (0, b"blob1")),
  805. ],
  806. )
  807. reader = PackStreamReader(f.read)
  808. objects = list(reader.read_objects(compute_crc32=True))
  809. self.assertEqual(2, len(objects))
  810. unpacked_blob, unpacked_delta = objects
  811. self.assertEqual(entries[0][0], unpacked_blob.offset)
  812. self.assertEqual(Blob.type_num, unpacked_blob.pack_type_num)
  813. self.assertEqual(Blob.type_num, unpacked_blob.obj_type_num)
  814. self.assertEqual(None, unpacked_blob.delta_base)
  815. self.assertEqual(b"blob", b"".join(unpacked_blob.decomp_chunks))
  816. self.assertEqual(entries[0][4], unpacked_blob.crc32)
  817. self.assertEqual(entries[1][0], unpacked_delta.offset)
  818. self.assertEqual(OFS_DELTA, unpacked_delta.pack_type_num)
  819. self.assertEqual(None, unpacked_delta.obj_type_num)
  820. self.assertEqual(
  821. unpacked_delta.offset - unpacked_blob.offset,
  822. unpacked_delta.delta_base,
  823. )
  824. delta = create_delta(b"blob", b"blob1")
  825. self.assertEqual(b"".join(delta), b"".join(unpacked_delta.decomp_chunks))
  826. self.assertEqual(entries[1][4], unpacked_delta.crc32)
  827. def test_read_objects_buffered(self) -> None:
  828. f = BytesIO()
  829. build_pack(
  830. f,
  831. [
  832. (Blob.type_num, b"blob"),
  833. (OFS_DELTA, (0, b"blob1")),
  834. ],
  835. )
  836. reader = PackStreamReader(f.read, zlib_bufsize=4)
  837. self.assertEqual(2, len(list(reader.read_objects())))
  838. def test_read_objects_empty(self) -> None:
  839. reader = PackStreamReader(BytesIO().read)
  840. self.assertRaises(AssertionError, list, reader.read_objects())
  841. class TestPackIterator(DeltaChainIterator):
  842. _compute_crc32 = True
  843. def __init__(self, *args, **kwargs) -> None:
  844. super().__init__(*args, **kwargs)
  845. self._unpacked_offsets: set[int] = set()
  846. def _result(self, unpacked):
  847. """Return entries in the same format as build_pack."""
  848. return (
  849. unpacked.offset,
  850. unpacked.obj_type_num,
  851. b"".join(unpacked.obj_chunks),
  852. unpacked.sha(),
  853. unpacked.crc32,
  854. )
  855. def _resolve_object(self, offset, pack_type_num, base_chunks):
  856. assert offset not in self._unpacked_offsets, (
  857. "Attempted to re-inflate offset %i" % offset
  858. )
  859. self._unpacked_offsets.add(offset)
  860. return super()._resolve_object(offset, pack_type_num, base_chunks)
  861. class DeltaChainIteratorTests(TestCase):
  862. def setUp(self) -> None:
  863. super().setUp()
  864. self.store = MemoryObjectStore()
  865. self.fetched = set()
  866. def store_blobs(self, blobs_data):
  867. blobs = []
  868. for data in blobs_data:
  869. blob = make_object(Blob, data=data)
  870. blobs.append(blob)
  871. self.store.add_object(blob)
  872. return blobs
  873. def get_raw_no_repeat(self, bin_sha):
  874. """Wrapper around store.get_raw that doesn't allow repeat lookups."""
  875. hex_sha = sha_to_hex(bin_sha)
  876. self.assertNotIn(
  877. hex_sha, self.fetched, f"Attempted to re-fetch object {hex_sha}"
  878. )
  879. self.fetched.add(hex_sha)
  880. return self.store.get_raw(hex_sha)
  881. def make_pack_iter(self, f, thin=None):
  882. if thin is None:
  883. thin = bool(list(self.store))
  884. resolve_ext_ref = thin and self.get_raw_no_repeat or None
  885. data = PackData("test.pack", file=f)
  886. return TestPackIterator.for_pack_data(data, resolve_ext_ref=resolve_ext_ref)
  887. def make_pack_iter_subset(self, f, subset, thin=None):
  888. if thin is None:
  889. thin = bool(list(self.store))
  890. resolve_ext_ref = thin and self.get_raw_no_repeat or None
  891. data = PackData("test.pack", file=f)
  892. assert data
  893. index = MemoryPackIndex.for_pack(data)
  894. pack = Pack.from_objects(data, index)
  895. return TestPackIterator.for_pack_subset(
  896. pack, subset, resolve_ext_ref=resolve_ext_ref
  897. )
  898. def assertEntriesMatch(self, expected_indexes, entries, pack_iter) -> None:
  899. expected = [entries[i] for i in expected_indexes]
  900. self.assertEqual(expected, list(pack_iter._walk_all_chains()))
  901. def test_no_deltas(self) -> None:
  902. f = BytesIO()
  903. entries = build_pack(
  904. f,
  905. [
  906. (Commit.type_num, b"commit"),
  907. (Blob.type_num, b"blob"),
  908. (Tree.type_num, b"tree"),
  909. ],
  910. )
  911. self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f))
  912. f.seek(0)
  913. self.assertEntriesMatch([], entries, self.make_pack_iter_subset(f, []))
  914. f.seek(0)
  915. self.assertEntriesMatch(
  916. [1, 0],
  917. entries,
  918. self.make_pack_iter_subset(f, [entries[0][3], entries[1][3]]),
  919. )
  920. f.seek(0)
  921. self.assertEntriesMatch(
  922. [1, 0],
  923. entries,
  924. self.make_pack_iter_subset(
  925. f, [sha_to_hex(entries[0][3]), sha_to_hex(entries[1][3])]
  926. ),
  927. )
  928. def test_ofs_deltas(self) -> None:
  929. f = BytesIO()
  930. entries = build_pack(
  931. f,
  932. [
  933. (Blob.type_num, b"blob"),
  934. (OFS_DELTA, (0, b"blob1")),
  935. (OFS_DELTA, (0, b"blob2")),
  936. ],
  937. )
  938. # Delta resolution changed to DFS
  939. self.assertEntriesMatch([0, 2, 1], entries, self.make_pack_iter(f))
  940. f.seek(0)
  941. self.assertEntriesMatch(
  942. [0, 2, 1],
  943. entries,
  944. self.make_pack_iter_subset(f, [entries[1][3], entries[2][3]]),
  945. )
  946. def test_ofs_deltas_chain(self) -> None:
  947. f = BytesIO()
  948. entries = build_pack(
  949. f,
  950. [
  951. (Blob.type_num, b"blob"),
  952. (OFS_DELTA, (0, b"blob1")),
  953. (OFS_DELTA, (1, b"blob2")),
  954. ],
  955. )
  956. self.assertEntriesMatch([0, 1, 2], entries, self.make_pack_iter(f))
  957. def test_ref_deltas(self) -> None:
  958. f = BytesIO()
  959. entries = build_pack(
  960. f,
  961. [
  962. (REF_DELTA, (1, b"blob1")),
  963. (Blob.type_num, (b"blob")),
  964. (REF_DELTA, (1, b"blob2")),
  965. ],
  966. )
  967. # Delta resolution changed to DFS
  968. self.assertEntriesMatch([1, 2, 0], entries, self.make_pack_iter(f))
  969. def test_ref_deltas_chain(self) -> None:
  970. f = BytesIO()
  971. entries = build_pack(
  972. f,
  973. [
  974. (REF_DELTA, (2, b"blob1")),
  975. (Blob.type_num, (b"blob")),
  976. (REF_DELTA, (1, b"blob2")),
  977. ],
  978. )
  979. self.assertEntriesMatch([1, 2, 0], entries, self.make_pack_iter(f))
  980. def test_ofs_and_ref_deltas(self) -> None:
  981. # Deltas pending on this offset are popped before deltas depending on
  982. # this ref.
  983. f = BytesIO()
  984. entries = build_pack(
  985. f,
  986. [
  987. (REF_DELTA, (1, b"blob1")),
  988. (Blob.type_num, (b"blob")),
  989. (OFS_DELTA, (1, b"blob2")),
  990. ],
  991. )
  992. # Delta resolution changed to DFS
  993. self.assertEntriesMatch([1, 0, 2], entries, self.make_pack_iter(f))
  994. def test_mixed_chain(self) -> None:
  995. f = BytesIO()
  996. entries = build_pack(
  997. f,
  998. [
  999. (Blob.type_num, b"blob"),
  1000. (REF_DELTA, (2, b"blob2")),
  1001. (OFS_DELTA, (0, b"blob1")),
  1002. (OFS_DELTA, (1, b"blob3")),
  1003. (OFS_DELTA, (0, b"bob")),
  1004. ],
  1005. )
  1006. # Delta resolution changed to DFS
  1007. self.assertEntriesMatch([0, 4, 2, 1, 3], entries, self.make_pack_iter(f))
  1008. def test_long_chain(self) -> None:
  1009. n = 100
  1010. objects_spec = [(Blob.type_num, b"blob")]
  1011. for i in range(n):
  1012. objects_spec.append((OFS_DELTA, (i, b"blob" + str(i).encode("ascii"))))
  1013. f = BytesIO()
  1014. entries = build_pack(f, objects_spec)
  1015. self.assertEntriesMatch(range(n + 1), entries, self.make_pack_iter(f))
  1016. def test_branchy_chain(self) -> None:
  1017. n = 100
  1018. objects_spec = [(Blob.type_num, b"blob")]
  1019. for i in range(n):
  1020. objects_spec.append((OFS_DELTA, (0, b"blob" + str(i).encode("ascii"))))
  1021. f = BytesIO()
  1022. entries = build_pack(f, objects_spec)
  1023. # Delta resolution changed to DFS
  1024. indices = [0, *list(range(100, 0, -1))]
  1025. self.assertEntriesMatch(indices, entries, self.make_pack_iter(f))
  1026. def test_ext_ref(self) -> None:
  1027. (blob,) = self.store_blobs([b"blob"])
  1028. f = BytesIO()
  1029. entries = build_pack(f, [(REF_DELTA, (blob.id, b"blob1"))], store=self.store)
  1030. pack_iter = self.make_pack_iter(f)
  1031. self.assertEntriesMatch([0], entries, pack_iter)
  1032. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  1033. def test_ext_ref_chain(self) -> None:
  1034. (blob,) = self.store_blobs([b"blob"])
  1035. f = BytesIO()
  1036. entries = build_pack(
  1037. f,
  1038. [
  1039. (REF_DELTA, (1, b"blob2")),
  1040. (REF_DELTA, (blob.id, b"blob1")),
  1041. ],
  1042. store=self.store,
  1043. )
  1044. pack_iter = self.make_pack_iter(f)
  1045. self.assertEntriesMatch([1, 0], entries, pack_iter)
  1046. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  1047. def test_ext_ref_chain_degenerate(self) -> None:
  1048. # Test a degenerate case where the sender is sending a REF_DELTA
  1049. # object that expands to an object already in the repository.
  1050. (blob,) = self.store_blobs([b"blob"])
  1051. (blob2,) = self.store_blobs([b"blob2"])
  1052. assert blob.id < blob2.id
  1053. f = BytesIO()
  1054. entries = build_pack(
  1055. f,
  1056. [
  1057. (REF_DELTA, (blob.id, b"blob2")),
  1058. (REF_DELTA, (0, b"blob3")),
  1059. ],
  1060. store=self.store,
  1061. )
  1062. pack_iter = self.make_pack_iter(f)
  1063. self.assertEntriesMatch([0, 1], entries, pack_iter)
  1064. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  1065. def test_ext_ref_multiple_times(self) -> None:
  1066. (blob,) = self.store_blobs([b"blob"])
  1067. f = BytesIO()
  1068. entries = build_pack(
  1069. f,
  1070. [
  1071. (REF_DELTA, (blob.id, b"blob1")),
  1072. (REF_DELTA, (blob.id, b"blob2")),
  1073. ],
  1074. store=self.store,
  1075. )
  1076. pack_iter = self.make_pack_iter(f)
  1077. self.assertEntriesMatch([0, 1], entries, pack_iter)
  1078. self.assertEqual([hex_to_sha(blob.id)], pack_iter.ext_refs())
  1079. def test_multiple_ext_refs(self) -> None:
  1080. b1, b2 = self.store_blobs([b"foo", b"bar"])
  1081. f = BytesIO()
  1082. entries = build_pack(
  1083. f,
  1084. [
  1085. (REF_DELTA, (b1.id, b"foo1")),
  1086. (REF_DELTA, (b2.id, b"bar2")),
  1087. ],
  1088. store=self.store,
  1089. )
  1090. pack_iter = self.make_pack_iter(f)
  1091. self.assertEntriesMatch([0, 1], entries, pack_iter)
  1092. self.assertEqual([hex_to_sha(b1.id), hex_to_sha(b2.id)], pack_iter.ext_refs())
  1093. def test_bad_ext_ref_non_thin_pack(self) -> None:
  1094. (blob,) = self.store_blobs([b"blob"])
  1095. f = BytesIO()
  1096. build_pack(f, [(REF_DELTA, (blob.id, b"blob1"))], store=self.store)
  1097. pack_iter = self.make_pack_iter(f, thin=False)
  1098. try:
  1099. list(pack_iter._walk_all_chains())
  1100. self.fail()
  1101. except UnresolvedDeltas as e:
  1102. self.assertEqual([blob.id], e.shas)
  1103. def test_bad_ext_ref_thin_pack(self) -> None:
  1104. b1, b2, b3 = self.store_blobs([b"foo", b"bar", b"baz"])
  1105. f = BytesIO()
  1106. build_pack(
  1107. f,
  1108. [
  1109. (REF_DELTA, (1, b"foo99")),
  1110. (REF_DELTA, (b1.id, b"foo1")),
  1111. (REF_DELTA, (b2.id, b"bar2")),
  1112. (REF_DELTA, (b3.id, b"baz3")),
  1113. ],
  1114. store=self.store,
  1115. )
  1116. del self.store[b2.id]
  1117. del self.store[b3.id]
  1118. pack_iter = self.make_pack_iter(f)
  1119. try:
  1120. list(pack_iter._walk_all_chains())
  1121. self.fail()
  1122. except UnresolvedDeltas as e:
  1123. self.assertEqual((sorted([b2.id, b3.id]),), (sorted(e.shas),))
  1124. def test_ext_ref_deltified_object_based_on_itself(self) -> None:
  1125. b1_content = b"foo"
  1126. (b1,) = self.store_blobs([b1_content])
  1127. f = BytesIO()
  1128. build_pack(
  1129. f,
  1130. [
  1131. # b1's content refers to bl1's object ID as delta base
  1132. (REF_DELTA, (b1.id, b1_content)),
  1133. ],
  1134. store=self.store,
  1135. )
  1136. fsize = f.tell()
  1137. f.seek(0)
  1138. packdata = PackData.from_file(f, fsize)
  1139. td = tempfile.mkdtemp()
  1140. idx_path = os.path.join(td, "test.idx")
  1141. self.addCleanup(shutil.rmtree, td)
  1142. packdata.create_index(
  1143. idx_path,
  1144. version=2,
  1145. resolve_ext_ref=self.get_raw_no_repeat,
  1146. )
  1147. packindex = load_pack_index(idx_path)
  1148. pack = Pack.from_objects(packdata, packindex)
  1149. try:
  1150. # Attempting to open this REF_DELTA object would loop forever
  1151. pack[b1.id]
  1152. except UnresolvedDeltas as e:
  1153. self.assertEqual((b1.id), e.shas)
  1154. class DeltaEncodeSizeTests(TestCase):
  1155. def test_basic(self) -> None:
  1156. self.assertEqual(b"\x00", _delta_encode_size(0))
  1157. self.assertEqual(b"\x01", _delta_encode_size(1))
  1158. self.assertEqual(b"\xfa\x01", _delta_encode_size(250))
  1159. self.assertEqual(b"\xe8\x07", _delta_encode_size(1000))
  1160. self.assertEqual(b"\xa0\x8d\x06", _delta_encode_size(100000))
  1161. class EncodeCopyOperationTests(TestCase):
  1162. def test_basic(self) -> None:
  1163. self.assertEqual(b"\x80", _encode_copy_operation(0, 0))
  1164. self.assertEqual(b"\x91\x01\x0a", _encode_copy_operation(1, 10))
  1165. self.assertEqual(b"\xb1\x64\xe8\x03", _encode_copy_operation(100, 1000))
  1166. self.assertEqual(b"\x93\xe8\x03\x01", _encode_copy_operation(1000, 1))