pack.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  1. # pack.py -- For dealing with packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public 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. """Classes for dealing with packed git objects.
  22. A pack is a compact representation of a bunch of objects, stored
  23. using deltas where possible.
  24. They have two parts, the pack file, which stores the data, and an index
  25. that tells you where the data is.
  26. To find an object you look in all of the index files 'til you find a
  27. match for the object name. You then use the pointer got from this as
  28. a pointer in to the corresponding packfile.
  29. """
  30. from collections import defaultdict
  31. import binascii
  32. from io import BytesIO, UnsupportedOperation
  33. from collections import (
  34. deque,
  35. )
  36. import difflib
  37. import struct
  38. from itertools import chain
  39. try:
  40. from itertools import imap, izip
  41. except ImportError:
  42. # Python3
  43. imap = map
  44. izip = zip
  45. import os
  46. import sys
  47. from hashlib import sha1
  48. from os import (
  49. SEEK_CUR,
  50. SEEK_END,
  51. )
  52. from struct import unpack_from
  53. import zlib
  54. try:
  55. import mmap
  56. except ImportError:
  57. has_mmap = False
  58. else:
  59. has_mmap = True
  60. # For some reason the above try, except fails to set has_mmap = False for plan9
  61. if sys.platform == 'Plan9':
  62. has_mmap = False
  63. from dulwich.errors import ( # noqa: E402
  64. ApplyDeltaError,
  65. ChecksumMismatch,
  66. )
  67. from dulwich.file import GitFile # noqa: E402
  68. from dulwich.lru_cache import ( # noqa: E402
  69. LRUSizeCache,
  70. )
  71. from dulwich.objects import ( # noqa: E402
  72. ShaFile,
  73. hex_to_sha,
  74. sha_to_hex,
  75. object_header,
  76. )
  77. OFS_DELTA = 6
  78. REF_DELTA = 7
  79. DELTA_TYPES = (OFS_DELTA, REF_DELTA)
  80. DEFAULT_PACK_DELTA_WINDOW_SIZE = 10
  81. def take_msb_bytes(read, crc32=None):
  82. """Read bytes marked with most significant bit.
  83. :param read: Read function
  84. """
  85. ret = []
  86. while len(ret) == 0 or ret[-1] & 0x80:
  87. b = read(1)
  88. if crc32 is not None:
  89. crc32 = binascii.crc32(b, crc32)
  90. ret.append(ord(b[:1]))
  91. return ret, crc32
  92. class UnpackedObject(object):
  93. """Class encapsulating an object unpacked from a pack file.
  94. These objects should only be created from within unpack_object. Most
  95. members start out as empty and are filled in at various points by
  96. read_zlib_chunks, unpack_object, DeltaChainIterator, etc.
  97. End users of this object should take care that the function they're getting
  98. this object from is guaranteed to set the members they need.
  99. """
  100. __slots__ = [
  101. 'offset', # Offset in its pack.
  102. '_sha', # Cached binary SHA.
  103. 'obj_type_num', # Type of this object.
  104. 'obj_chunks', # Decompressed and delta-resolved chunks.
  105. 'pack_type_num', # Type of this object in the pack (may be a delta).
  106. 'delta_base', # Delta base offset or SHA.
  107. 'comp_chunks', # Compressed object chunks.
  108. 'decomp_chunks', # Decompressed object chunks.
  109. 'decomp_len', # Decompressed length of this object.
  110. 'crc32', # CRC32.
  111. ]
  112. # TODO(dborowitz): read_zlib_chunks and unpack_object could very well be
  113. # methods of this object.
  114. def __init__(self, pack_type_num, delta_base, decomp_len, crc32):
  115. self.offset = None
  116. self._sha = None
  117. self.pack_type_num = pack_type_num
  118. self.delta_base = delta_base
  119. self.comp_chunks = None
  120. self.decomp_chunks = []
  121. self.decomp_len = decomp_len
  122. self.crc32 = crc32
  123. if pack_type_num in DELTA_TYPES:
  124. self.obj_type_num = None
  125. self.obj_chunks = None
  126. else:
  127. self.obj_type_num = pack_type_num
  128. self.obj_chunks = self.decomp_chunks
  129. self.delta_base = delta_base
  130. def sha(self):
  131. """Return the binary SHA of this object."""
  132. if self._sha is None:
  133. self._sha = obj_sha(self.obj_type_num, self.obj_chunks)
  134. return self._sha
  135. def sha_file(self):
  136. """Return a ShaFile from this object."""
  137. return ShaFile.from_raw_chunks(self.obj_type_num, self.obj_chunks)
  138. # Only provided for backwards compatibility with code that expects either
  139. # chunks or a delta tuple.
  140. def _obj(self):
  141. """Return the decompressed chunks, or (delta base, delta chunks)."""
  142. if self.pack_type_num in DELTA_TYPES:
  143. return (self.delta_base, self.decomp_chunks)
  144. else:
  145. return self.decomp_chunks
  146. def __eq__(self, other):
  147. if not isinstance(other, UnpackedObject):
  148. return False
  149. for slot in self.__slots__:
  150. if getattr(self, slot) != getattr(other, slot):
  151. return False
  152. return True
  153. def __ne__(self, other):
  154. return not (self == other)
  155. def __repr__(self):
  156. data = ['%s=%r' % (s, getattr(self, s)) for s in self.__slots__]
  157. return '%s(%s)' % (self.__class__.__name__, ', '.join(data))
  158. _ZLIB_BUFSIZE = 4096
  159. def read_zlib_chunks(read_some, unpacked, include_comp=False,
  160. buffer_size=_ZLIB_BUFSIZE):
  161. """Read zlib data from a buffer.
  162. This function requires that the buffer have additional data following the
  163. compressed data, which is guaranteed to be the case for git pack files.
  164. :param read_some: Read function that returns at least one byte, but may
  165. return less than the requested size.
  166. :param unpacked: An UnpackedObject to write result data to. If its crc32
  167. attr is not None, the CRC32 of the compressed bytes will be computed
  168. using this starting CRC32.
  169. After this function, will have the following attrs set:
  170. * comp_chunks (if include_comp is True)
  171. * decomp_chunks
  172. * decomp_len
  173. * crc32
  174. :param include_comp: If True, include compressed data in the result.
  175. :param buffer_size: Size of the read buffer.
  176. :return: Leftover unused data from the decompression.
  177. :raise zlib.error: if a decompression error occurred.
  178. """
  179. if unpacked.decomp_len <= -1:
  180. raise ValueError('non-negative zlib data stream size expected')
  181. decomp_obj = zlib.decompressobj()
  182. comp_chunks = []
  183. decomp_chunks = unpacked.decomp_chunks
  184. decomp_len = 0
  185. crc32 = unpacked.crc32
  186. while True:
  187. add = read_some(buffer_size)
  188. if not add:
  189. raise zlib.error('EOF before end of zlib stream')
  190. comp_chunks.append(add)
  191. decomp = decomp_obj.decompress(add)
  192. decomp_len += len(decomp)
  193. decomp_chunks.append(decomp)
  194. unused = decomp_obj.unused_data
  195. if unused:
  196. left = len(unused)
  197. if crc32 is not None:
  198. crc32 = binascii.crc32(add[:-left], crc32)
  199. if include_comp:
  200. comp_chunks[-1] = add[:-left]
  201. break
  202. elif crc32 is not None:
  203. crc32 = binascii.crc32(add, crc32)
  204. if crc32 is not None:
  205. crc32 &= 0xffffffff
  206. if decomp_len != unpacked.decomp_len:
  207. raise zlib.error('decompressed data does not match expected size')
  208. unpacked.crc32 = crc32
  209. if include_comp:
  210. unpacked.comp_chunks = comp_chunks
  211. return unused
  212. def iter_sha1(iter):
  213. """Return the hexdigest of the SHA1 over a set of names.
  214. :param iter: Iterator over string objects
  215. :return: 40-byte hex sha1 digest
  216. """
  217. sha = sha1()
  218. for name in iter:
  219. sha.update(name)
  220. return sha.hexdigest().encode('ascii')
  221. def load_pack_index(path):
  222. """Load an index file by path.
  223. :param filename: Path to the index file
  224. :return: A PackIndex loaded from the given path
  225. """
  226. with GitFile(path, 'rb') as f:
  227. return load_pack_index_file(path, f)
  228. def _load_file_contents(f, size=None):
  229. try:
  230. fd = f.fileno()
  231. except (UnsupportedOperation, AttributeError):
  232. fd = None
  233. # Attempt to use mmap if possible
  234. if fd is not None:
  235. if size is None:
  236. size = os.fstat(fd).st_size
  237. if has_mmap:
  238. try:
  239. contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
  240. except mmap.error:
  241. # Perhaps a socket?
  242. pass
  243. else:
  244. return contents, size
  245. contents = f.read()
  246. size = len(contents)
  247. return contents, size
  248. def load_pack_index_file(path, f):
  249. """Load an index file from a file-like object.
  250. :param path: Path for the index file
  251. :param f: File-like object
  252. :return: A PackIndex loaded from the given file
  253. """
  254. contents, size = _load_file_contents(f)
  255. if contents[:4] == b'\377tOc':
  256. version = struct.unpack(b'>L', contents[4:8])[0]
  257. if version == 2:
  258. return PackIndex2(
  259. path, file=f, contents=contents, size=size)
  260. else:
  261. raise KeyError('Unknown pack index format %d' % version)
  262. else:
  263. return PackIndex1(path, file=f, contents=contents, size=size)
  264. def bisect_find_sha(start, end, sha, unpack_name):
  265. """Find a SHA in a data blob with sorted SHAs.
  266. :param start: Start index of range to search
  267. :param end: End index of range to search
  268. :param sha: Sha to find
  269. :param unpack_name: Callback to retrieve SHA by index
  270. :return: Index of the SHA, or None if it wasn't found
  271. """
  272. assert start <= end
  273. while start <= end:
  274. i = (start + end) // 2
  275. file_sha = unpack_name(i)
  276. if file_sha < sha:
  277. start = i + 1
  278. elif file_sha > sha:
  279. end = i - 1
  280. else:
  281. return i
  282. return None
  283. class PackIndex(object):
  284. """An index in to a packfile.
  285. Given a sha id of an object a pack index can tell you the location in the
  286. packfile of that object if it has it.
  287. """
  288. def __eq__(self, other):
  289. if not isinstance(other, PackIndex):
  290. return False
  291. for (name1, _, _), (name2, _, _) in izip(self.iterentries(),
  292. other.iterentries()):
  293. if name1 != name2:
  294. return False
  295. return True
  296. def __ne__(self, other):
  297. return not self.__eq__(other)
  298. def __len__(self):
  299. """Return the number of entries in this pack index."""
  300. raise NotImplementedError(self.__len__)
  301. def __iter__(self):
  302. """Iterate over the SHAs in this pack."""
  303. return imap(sha_to_hex, self._itersha())
  304. def iterentries(self):
  305. """Iterate over the entries in this pack index.
  306. :return: iterator over tuples with object name, offset in packfile and
  307. crc32 checksum.
  308. """
  309. raise NotImplementedError(self.iterentries)
  310. def get_pack_checksum(self):
  311. """Return the SHA1 checksum stored for the corresponding packfile.
  312. :return: 20-byte binary digest
  313. """
  314. raise NotImplementedError(self.get_pack_checksum)
  315. def object_index(self, sha):
  316. """Return the index in to the corresponding packfile for the object.
  317. Given the name of an object it will return the offset that object
  318. lives at within the corresponding pack file. If the pack file doesn't
  319. have the object then None will be returned.
  320. """
  321. if len(sha) == 40:
  322. sha = hex_to_sha(sha)
  323. return self._object_index(sha)
  324. def _object_index(self, sha):
  325. """See object_index.
  326. :param sha: A *binary* SHA string. (20 characters long)_
  327. """
  328. raise NotImplementedError(self._object_index)
  329. def objects_sha1(self):
  330. """Return the hex SHA1 over all the shas of all objects in this pack.
  331. :note: This is used for the filename of the pack.
  332. """
  333. return iter_sha1(self._itersha())
  334. def _itersha(self):
  335. """Yield all the SHA1's of the objects in the index, sorted."""
  336. raise NotImplementedError(self._itersha)
  337. class MemoryPackIndex(PackIndex):
  338. """Pack index that is stored entirely in memory."""
  339. def __init__(self, entries, pack_checksum=None):
  340. """Create a new MemoryPackIndex.
  341. :param entries: Sequence of name, idx, crc32 (sorted)
  342. :param pack_checksum: Optional pack checksum
  343. """
  344. self._by_sha = {}
  345. for name, idx, crc32 in entries:
  346. self._by_sha[name] = idx
  347. self._entries = entries
  348. self._pack_checksum = pack_checksum
  349. def get_pack_checksum(self):
  350. return self._pack_checksum
  351. def __len__(self):
  352. return len(self._entries)
  353. def _object_index(self, sha):
  354. return self._by_sha[sha][0]
  355. def _itersha(self):
  356. return iter(self._by_sha)
  357. def iterentries(self):
  358. return iter(self._entries)
  359. class FilePackIndex(PackIndex):
  360. """Pack index that is based on a file.
  361. To do the loop it opens the file, and indexes first 256 4 byte groups
  362. with the first byte of the sha id. The value in the four byte group indexed
  363. is the end of the group that shares the same starting byte. Subtract one
  364. from the starting byte and index again to find the start of the group.
  365. The values are sorted by sha id within the group, so do the math to find
  366. the start and end offset and then bisect in to find if the value is
  367. present.
  368. """
  369. def __init__(self, filename, file=None, contents=None, size=None):
  370. """Create a pack index object.
  371. Provide it with the name of the index file to consider, and it will map
  372. it whenever required.
  373. """
  374. self._filename = filename
  375. # Take the size now, so it can be checked each time we map the file to
  376. # ensure that it hasn't changed.
  377. if file is None:
  378. self._file = GitFile(filename, 'rb')
  379. else:
  380. self._file = file
  381. if contents is None:
  382. self._contents, self._size = _load_file_contents(self._file, size)
  383. else:
  384. self._contents, self._size = (contents, size)
  385. @property
  386. def path(self):
  387. return self._filename
  388. def __eq__(self, other):
  389. # Quick optimization:
  390. if (isinstance(other, FilePackIndex) and
  391. self._fan_out_table != other._fan_out_table):
  392. return False
  393. return super(FilePackIndex, self).__eq__(other)
  394. def close(self):
  395. self._file.close()
  396. if getattr(self._contents, "close", None) is not None:
  397. self._contents.close()
  398. def __len__(self):
  399. """Return the number of entries in this pack index."""
  400. return self._fan_out_table[-1]
  401. def _unpack_entry(self, i):
  402. """Unpack the i-th entry in the index file.
  403. :return: Tuple with object name (SHA), offset in pack file and CRC32
  404. checksum (if known).
  405. """
  406. raise NotImplementedError(self._unpack_entry)
  407. def _unpack_name(self, i):
  408. """Unpack the i-th name from the index file."""
  409. raise NotImplementedError(self._unpack_name)
  410. def _unpack_offset(self, i):
  411. """Unpack the i-th object offset from the index file."""
  412. raise NotImplementedError(self._unpack_offset)
  413. def _unpack_crc32_checksum(self, i):
  414. """Unpack the crc32 checksum for the ith object from the index file.
  415. """
  416. raise NotImplementedError(self._unpack_crc32_checksum)
  417. def _itersha(self):
  418. for i in range(len(self)):
  419. yield self._unpack_name(i)
  420. def iterentries(self):
  421. """Iterate over the entries in this pack index.
  422. :return: iterator over tuples with object name, offset in packfile and
  423. crc32 checksum.
  424. """
  425. for i in range(len(self)):
  426. yield self._unpack_entry(i)
  427. def _read_fan_out_table(self, start_offset):
  428. ret = []
  429. for i in range(0x100):
  430. fanout_entry = self._contents[
  431. start_offset+i*4:start_offset+(i+1)*4]
  432. ret.append(struct.unpack('>L', fanout_entry)[0])
  433. return ret
  434. def check(self):
  435. """Check that the stored checksum matches the actual checksum."""
  436. actual = self.calculate_checksum()
  437. stored = self.get_stored_checksum()
  438. if actual != stored:
  439. raise ChecksumMismatch(stored, actual)
  440. def calculate_checksum(self):
  441. """Calculate the SHA1 checksum over this pack index.
  442. :return: This is a 20-byte binary digest
  443. """
  444. return sha1(self._contents[:-20]).digest()
  445. def get_pack_checksum(self):
  446. """Return the SHA1 checksum stored for the corresponding packfile.
  447. :return: 20-byte binary digest
  448. """
  449. return bytes(self._contents[-40:-20])
  450. def get_stored_checksum(self):
  451. """Return the SHA1 checksum stored for this index.
  452. :return: 20-byte binary digest
  453. """
  454. return bytes(self._contents[-20:])
  455. def _object_index(self, sha):
  456. """See object_index.
  457. :param sha: A *binary* SHA string. (20 characters long)_
  458. """
  459. assert len(sha) == 20
  460. idx = ord(sha[:1])
  461. if idx == 0:
  462. start = 0
  463. else:
  464. start = self._fan_out_table[idx-1]
  465. end = self._fan_out_table[idx]
  466. i = bisect_find_sha(start, end, sha, self._unpack_name)
  467. if i is None:
  468. raise KeyError(sha)
  469. return self._unpack_offset(i)
  470. class PackIndex1(FilePackIndex):
  471. """Version 1 Pack Index file."""
  472. def __init__(self, filename, file=None, contents=None, size=None):
  473. super(PackIndex1, self).__init__(filename, file, contents, size)
  474. self.version = 1
  475. self._fan_out_table = self._read_fan_out_table(0)
  476. def _unpack_entry(self, i):
  477. (offset, name) = unpack_from('>L20s', self._contents,
  478. (0x100 * 4) + (i * 24))
  479. return (name, offset, None)
  480. def _unpack_name(self, i):
  481. offset = (0x100 * 4) + (i * 24) + 4
  482. return self._contents[offset:offset+20]
  483. def _unpack_offset(self, i):
  484. offset = (0x100 * 4) + (i * 24)
  485. return unpack_from('>L', self._contents, offset)[0]
  486. def _unpack_crc32_checksum(self, i):
  487. # Not stored in v1 index files
  488. return None
  489. class PackIndex2(FilePackIndex):
  490. """Version 2 Pack Index file."""
  491. def __init__(self, filename, file=None, contents=None, size=None):
  492. super(PackIndex2, self).__init__(filename, file, contents, size)
  493. if self._contents[:4] != b'\377tOc':
  494. raise AssertionError('Not a v2 pack index file')
  495. (self.version, ) = unpack_from(b'>L', self._contents, 4)
  496. if self.version != 2:
  497. raise AssertionError('Version was %d' % self.version)
  498. self._fan_out_table = self._read_fan_out_table(8)
  499. self._name_table_offset = 8 + 0x100 * 4
  500. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  501. self._pack_offset_table_offset = (self._crc32_table_offset +
  502. 4 * len(self))
  503. self._pack_offset_largetable_offset = (
  504. self._pack_offset_table_offset + 4 * len(self))
  505. def _unpack_entry(self, i):
  506. return (self._unpack_name(i), self._unpack_offset(i),
  507. self._unpack_crc32_checksum(i))
  508. def _unpack_name(self, i):
  509. offset = self._name_table_offset + i * 20
  510. return self._contents[offset:offset+20]
  511. def _unpack_offset(self, i):
  512. offset = self._pack_offset_table_offset + i * 4
  513. offset = unpack_from('>L', self._contents, offset)[0]
  514. if offset & (2**31):
  515. offset = (
  516. self._pack_offset_largetable_offset +
  517. (offset & (2 ** 31 - 1)) * 8)
  518. offset = unpack_from('>Q', self._contents, offset)[0]
  519. return offset
  520. def _unpack_crc32_checksum(self, i):
  521. return unpack_from('>L', self._contents,
  522. self._crc32_table_offset + i * 4)[0]
  523. def read_pack_header(read):
  524. """Read the header of a pack file.
  525. :param read: Read function
  526. :return: Tuple of (pack version, number of objects). If no data is
  527. available to read, returns (None, None).
  528. """
  529. header = read(12)
  530. if not header:
  531. return None, None
  532. if header[:4] != b'PACK':
  533. raise AssertionError('Invalid pack header %r' % header)
  534. (version,) = unpack_from(b'>L', header, 4)
  535. if version not in (2, 3):
  536. raise AssertionError('Version was %d' % version)
  537. (num_objects,) = unpack_from(b'>L', header, 8)
  538. return (version, num_objects)
  539. def chunks_length(chunks):
  540. if isinstance(chunks, bytes):
  541. return len(chunks)
  542. else:
  543. return sum(imap(len, chunks))
  544. def unpack_object(read_all, read_some=None, compute_crc32=False,
  545. include_comp=False, zlib_bufsize=_ZLIB_BUFSIZE):
  546. """Unpack a Git object.
  547. :param read_all: Read function that blocks until the number of requested
  548. bytes are read.
  549. :param read_some: Read function that returns at least one byte, but may not
  550. return the number of bytes requested.
  551. :param compute_crc32: If True, compute the CRC32 of the compressed data. If
  552. False, the returned CRC32 will be None.
  553. :param include_comp: If True, include compressed data in the result.
  554. :param zlib_bufsize: An optional buffer size for zlib operations.
  555. :return: A tuple of (unpacked, unused), where unused is the unused data
  556. leftover from decompression, and unpacked in an UnpackedObject with
  557. the following attrs set:
  558. * obj_chunks (for non-delta types)
  559. * pack_type_num
  560. * delta_base (for delta types)
  561. * comp_chunks (if include_comp is True)
  562. * decomp_chunks
  563. * decomp_len
  564. * crc32 (if compute_crc32 is True)
  565. """
  566. if read_some is None:
  567. read_some = read_all
  568. if compute_crc32:
  569. crc32 = 0
  570. else:
  571. crc32 = None
  572. bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
  573. type_num = (bytes[0] >> 4) & 0x07
  574. size = bytes[0] & 0x0f
  575. for i, byte in enumerate(bytes[1:]):
  576. size += (byte & 0x7f) << ((i * 7) + 4)
  577. raw_base = len(bytes)
  578. if type_num == OFS_DELTA:
  579. bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
  580. raw_base += len(bytes)
  581. if bytes[-1] & 0x80:
  582. raise AssertionError
  583. delta_base_offset = bytes[0] & 0x7f
  584. for byte in bytes[1:]:
  585. delta_base_offset += 1
  586. delta_base_offset <<= 7
  587. delta_base_offset += (byte & 0x7f)
  588. delta_base = delta_base_offset
  589. elif type_num == REF_DELTA:
  590. delta_base = read_all(20)
  591. if compute_crc32:
  592. crc32 = binascii.crc32(delta_base, crc32)
  593. raw_base += 20
  594. else:
  595. delta_base = None
  596. unpacked = UnpackedObject(type_num, delta_base, size, crc32)
  597. unused = read_zlib_chunks(read_some, unpacked, buffer_size=zlib_bufsize,
  598. include_comp=include_comp)
  599. return unpacked, unused
  600. def _compute_object_size(value):
  601. """Compute the size of a unresolved object for use with LRUSizeCache."""
  602. (num, obj) = value
  603. if num in DELTA_TYPES:
  604. return chunks_length(obj[1])
  605. return chunks_length(obj)
  606. class PackStreamReader(object):
  607. """Class to read a pack stream.
  608. The pack is read from a ReceivableProtocol using read() or recv() as
  609. appropriate.
  610. """
  611. def __init__(self, read_all, read_some=None, zlib_bufsize=_ZLIB_BUFSIZE):
  612. self.read_all = read_all
  613. if read_some is None:
  614. self.read_some = read_all
  615. else:
  616. self.read_some = read_some
  617. self.sha = sha1()
  618. self._offset = 0
  619. self._rbuf = BytesIO()
  620. # trailer is a deque to avoid memory allocation on small reads
  621. self._trailer = deque()
  622. self._zlib_bufsize = zlib_bufsize
  623. def _read(self, read, size):
  624. """Read up to size bytes using the given callback.
  625. As a side effect, update the verifier's hash (excluding the last 20
  626. bytes read).
  627. :param read: The read callback to read from.
  628. :param size: The maximum number of bytes to read; the particular
  629. behavior is callback-specific.
  630. """
  631. data = read(size)
  632. # maintain a trailer of the last 20 bytes we've read
  633. n = len(data)
  634. self._offset += n
  635. tn = len(self._trailer)
  636. if n >= 20:
  637. to_pop = tn
  638. to_add = 20
  639. else:
  640. to_pop = max(n + tn - 20, 0)
  641. to_add = n
  642. self.sha.update(
  643. bytes(bytearray([self._trailer.popleft() for _ in range(to_pop)])))
  644. self._trailer.extend(data[-to_add:])
  645. # hash everything but the trailer
  646. self.sha.update(data[:-to_add])
  647. return data
  648. def _buf_len(self):
  649. buf = self._rbuf
  650. start = buf.tell()
  651. buf.seek(0, SEEK_END)
  652. end = buf.tell()
  653. buf.seek(start)
  654. return end - start
  655. @property
  656. def offset(self):
  657. return self._offset - self._buf_len()
  658. def read(self, size):
  659. """Read, blocking until size bytes are read."""
  660. buf_len = self._buf_len()
  661. if buf_len >= size:
  662. return self._rbuf.read(size)
  663. buf_data = self._rbuf.read()
  664. self._rbuf = BytesIO()
  665. return buf_data + self._read(self.read_all, size - buf_len)
  666. def recv(self, size):
  667. """Read up to size bytes, blocking until one byte is read."""
  668. buf_len = self._buf_len()
  669. if buf_len:
  670. data = self._rbuf.read(size)
  671. if size >= buf_len:
  672. self._rbuf = BytesIO()
  673. return data
  674. return self._read(self.read_some, size)
  675. def __len__(self):
  676. return self._num_objects
  677. def read_objects(self, compute_crc32=False):
  678. """Read the objects in this pack file.
  679. :param compute_crc32: If True, compute the CRC32 of the compressed
  680. data. If False, the returned CRC32 will be None.
  681. :return: Iterator over UnpackedObjects with the following members set:
  682. offset
  683. obj_type_num
  684. obj_chunks (for non-delta types)
  685. delta_base (for delta types)
  686. decomp_chunks
  687. decomp_len
  688. crc32 (if compute_crc32 is True)
  689. :raise ChecksumMismatch: if the checksum of the pack contents does not
  690. match the checksum in the pack trailer.
  691. :raise zlib.error: if an error occurred during zlib decompression.
  692. :raise IOError: if an error occurred writing to the output file.
  693. """
  694. pack_version, self._num_objects = read_pack_header(self.read)
  695. if pack_version is None:
  696. return
  697. for i in range(self._num_objects):
  698. offset = self.offset
  699. unpacked, unused = unpack_object(
  700. self.read, read_some=self.recv, compute_crc32=compute_crc32,
  701. zlib_bufsize=self._zlib_bufsize)
  702. unpacked.offset = offset
  703. # prepend any unused data to current read buffer
  704. buf = BytesIO()
  705. buf.write(unused)
  706. buf.write(self._rbuf.read())
  707. buf.seek(0)
  708. self._rbuf = buf
  709. yield unpacked
  710. if self._buf_len() < 20:
  711. # If the read buffer is full, then the last read() got the whole
  712. # trailer off the wire. If not, it means there is still some of the
  713. # trailer to read. We need to read() all 20 bytes; N come from the
  714. # read buffer and (20 - N) come from the wire.
  715. self.read(20)
  716. pack_sha = bytearray(self._trailer)
  717. if pack_sha != self.sha.digest():
  718. raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest())
  719. class PackStreamCopier(PackStreamReader):
  720. """Class to verify a pack stream as it is being read.
  721. The pack is read from a ReceivableProtocol using read() or recv() as
  722. appropriate and written out to the given file-like object.
  723. """
  724. def __init__(self, read_all, read_some, outfile, delta_iter=None):
  725. """Initialize the copier.
  726. :param read_all: Read function that blocks until the number of
  727. requested bytes are read.
  728. :param read_some: Read function that returns at least one byte, but may
  729. not return the number of bytes requested.
  730. :param outfile: File-like object to write output through.
  731. :param delta_iter: Optional DeltaChainIterator to record deltas as we
  732. read them.
  733. """
  734. super(PackStreamCopier, self).__init__(read_all, read_some=read_some)
  735. self.outfile = outfile
  736. self._delta_iter = delta_iter
  737. def _read(self, read, size):
  738. """Read data from the read callback and write it to the file."""
  739. data = super(PackStreamCopier, self)._read(read, size)
  740. self.outfile.write(data)
  741. return data
  742. def verify(self):
  743. """Verify a pack stream and write it to the output file.
  744. See PackStreamReader.iterobjects for a list of exceptions this may
  745. throw.
  746. """
  747. if self._delta_iter:
  748. for unpacked in self.read_objects():
  749. self._delta_iter.record(unpacked)
  750. else:
  751. for _ in self.read_objects():
  752. pass
  753. def obj_sha(type, chunks):
  754. """Compute the SHA for a numeric type and object chunks."""
  755. sha = sha1()
  756. sha.update(object_header(type, chunks_length(chunks)))
  757. if isinstance(chunks, bytes):
  758. sha.update(chunks)
  759. else:
  760. for chunk in chunks:
  761. sha.update(chunk)
  762. return sha.digest()
  763. def compute_file_sha(f, start_ofs=0, end_ofs=0, buffer_size=1 << 16):
  764. """Hash a portion of a file into a new SHA.
  765. :param f: A file-like object to read from that supports seek().
  766. :param start_ofs: The offset in the file to start reading at.
  767. :param end_ofs: The offset in the file to end reading at, relative to the
  768. end of the file.
  769. :param buffer_size: A buffer size for reading.
  770. :return: A new SHA object updated with data read from the file.
  771. """
  772. sha = sha1()
  773. f.seek(0, SEEK_END)
  774. length = f.tell()
  775. if (end_ofs < 0 and length + end_ofs < start_ofs) or end_ofs > length:
  776. raise AssertionError(
  777. "Attempt to read beyond file length. "
  778. "start_ofs: %d, end_ofs: %d, file length: %d" % (
  779. start_ofs, end_ofs, length))
  780. todo = length + end_ofs - start_ofs
  781. f.seek(start_ofs)
  782. while todo:
  783. data = f.read(min(todo, buffer_size))
  784. sha.update(data)
  785. todo -= len(data)
  786. return sha
  787. class PackData(object):
  788. """The data contained in a packfile.
  789. Pack files can be accessed both sequentially for exploding a pack, and
  790. directly with the help of an index to retrieve a specific object.
  791. The objects within are either complete or a delta against another.
  792. The header is variable length. If the MSB of each byte is set then it
  793. indicates that the subsequent byte is still part of the header.
  794. For the first byte the next MS bits are the type, which tells you the type
  795. of object, and whether it is a delta. The LS byte is the lowest bits of the
  796. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  797. size, i.e. the last byte of the header contains the MS bits of the size.
  798. For the complete objects the data is stored as zlib deflated data.
  799. The size in the header is the uncompressed object size, so to uncompress
  800. you need to just keep feeding data to zlib until you get an object back,
  801. or it errors on bad data. This is done here by just giving the complete
  802. buffer from the start of the deflated object on. This is bad, but until I
  803. get mmap sorted out it will have to do.
  804. Currently there are no integrity checks done. Also no attempt is made to
  805. try and detect the delta case, or a request for an object at the wrong
  806. position. It will all just throw a zlib or KeyError.
  807. """
  808. def __init__(self, filename, file=None, size=None):
  809. """Create a PackData object representing the pack in the given filename.
  810. The file must exist and stay readable until the object is disposed of.
  811. It must also stay the same size. It will be mapped whenever needed.
  812. Currently there is a restriction on the size of the pack as the python
  813. mmap implementation is flawed.
  814. """
  815. self._filename = filename
  816. self._size = size
  817. self._header_size = 12
  818. if file is None:
  819. self._file = GitFile(self._filename, 'rb')
  820. else:
  821. self._file = file
  822. (version, self._num_objects) = read_pack_header(self._file.read)
  823. self._offset_cache = LRUSizeCache(
  824. 1024*1024*20, compute_size=_compute_object_size)
  825. self.pack = None
  826. @property
  827. def filename(self):
  828. return os.path.basename(self._filename)
  829. @property
  830. def path(self):
  831. return self._filename
  832. @classmethod
  833. def from_file(cls, file, size):
  834. return cls(str(file), file=file, size=size)
  835. @classmethod
  836. def from_path(cls, path):
  837. return cls(filename=path)
  838. def close(self):
  839. self._file.close()
  840. def __enter__(self):
  841. return self
  842. def __exit__(self, exc_type, exc_val, exc_tb):
  843. self.close()
  844. def _get_size(self):
  845. if self._size is not None:
  846. return self._size
  847. self._size = os.path.getsize(self._filename)
  848. if self._size < self._header_size:
  849. errmsg = ('%s is too small for a packfile (%d < %d)' %
  850. (self._filename, self._size, self._header_size))
  851. raise AssertionError(errmsg)
  852. return self._size
  853. def __len__(self):
  854. """Returns the number of objects in this pack."""
  855. return self._num_objects
  856. def calculate_checksum(self):
  857. """Calculate the checksum for this pack.
  858. :return: 20-byte binary SHA1 digest
  859. """
  860. return compute_file_sha(self._file, end_ofs=-20).digest()
  861. def get_ref(self, sha):
  862. """Get the object for a ref SHA, only looking in this pack."""
  863. # TODO: cache these results
  864. if self.pack is None:
  865. raise KeyError(sha)
  866. try:
  867. offset = self.pack.index.object_index(sha)
  868. except KeyError:
  869. offset = None
  870. if offset:
  871. type, obj = self.get_object_at(offset)
  872. elif self.pack is not None and self.pack.resolve_ext_ref:
  873. type, obj = self.pack.resolve_ext_ref(sha)
  874. else:
  875. raise KeyError(sha)
  876. return offset, type, obj
  877. def resolve_object(self, offset, type, obj, get_ref=None):
  878. """Resolve an object, possibly resolving deltas when necessary.
  879. :return: Tuple with object type and contents.
  880. """
  881. # Walk down the delta chain, building a stack of deltas to reach
  882. # the requested object.
  883. base_offset = offset
  884. base_type = type
  885. base_obj = obj
  886. delta_stack = []
  887. while base_type in DELTA_TYPES:
  888. prev_offset = base_offset
  889. if get_ref is None:
  890. get_ref = self.get_ref
  891. if base_type == OFS_DELTA:
  892. (delta_offset, delta) = base_obj
  893. # TODO: clean up asserts and replace with nicer error messages
  894. base_offset = base_offset - delta_offset
  895. base_type, base_obj = self.get_object_at(base_offset)
  896. assert isinstance(base_type, int)
  897. elif base_type == REF_DELTA:
  898. (basename, delta) = base_obj
  899. assert isinstance(basename, bytes) and len(basename) == 20
  900. base_offset, base_type, base_obj = get_ref(basename)
  901. assert isinstance(base_type, int)
  902. delta_stack.append((prev_offset, base_type, delta))
  903. # Now grab the base object (mustn't be a delta) and apply the
  904. # deltas all the way up the stack.
  905. chunks = base_obj
  906. for prev_offset, delta_type, delta in reversed(delta_stack):
  907. chunks = apply_delta(chunks, delta)
  908. # TODO(dborowitz): This can result in poor performance if
  909. # large base objects are separated from deltas in the pack.
  910. # We should reorganize so that we apply deltas to all
  911. # objects in a chain one after the other to optimize cache
  912. # performance.
  913. if prev_offset is not None:
  914. self._offset_cache[prev_offset] = base_type, chunks
  915. return base_type, chunks
  916. def iterobjects(self, progress=None, compute_crc32=True):
  917. self._file.seek(self._header_size)
  918. for i in range(1, self._num_objects + 1):
  919. offset = self._file.tell()
  920. unpacked, unused = unpack_object(
  921. self._file.read, compute_crc32=compute_crc32)
  922. if progress is not None:
  923. progress(i, self._num_objects)
  924. yield (offset, unpacked.pack_type_num, unpacked._obj(),
  925. unpacked.crc32)
  926. # Back up over unused data.
  927. self._file.seek(-len(unused), SEEK_CUR)
  928. def _iter_unpacked(self):
  929. # TODO(dborowitz): Merge this with iterobjects, if we can change its
  930. # return type.
  931. self._file.seek(self._header_size)
  932. if self._num_objects is None:
  933. return
  934. for _ in range(self._num_objects):
  935. offset = self._file.tell()
  936. unpacked, unused = unpack_object(
  937. self._file.read, compute_crc32=False)
  938. unpacked.offset = offset
  939. yield unpacked
  940. # Back up over unused data.
  941. self._file.seek(-len(unused), SEEK_CUR)
  942. def iterentries(self, progress=None):
  943. """Yield entries summarizing the contents of this pack.
  944. :param progress: Progress function, called with current and total
  945. object count.
  946. :return: iterator of tuples with (sha, offset, crc32)
  947. """
  948. num_objects = self._num_objects
  949. resolve_ext_ref = (
  950. self.pack.resolve_ext_ref if self.pack is not None else None)
  951. indexer = PackIndexer.for_pack_data(
  952. self, resolve_ext_ref=resolve_ext_ref)
  953. for i, result in enumerate(indexer):
  954. if progress is not None:
  955. progress(i, num_objects)
  956. yield result
  957. def sorted_entries(self, progress=None):
  958. """Return entries in this pack, sorted by SHA.
  959. :param progress: Progress function, called with current and total
  960. object count
  961. :return: List of tuples with (sha, offset, crc32)
  962. """
  963. ret = sorted(self.iterentries(progress=progress))
  964. return ret
  965. def create_index_v1(self, filename, progress=None):
  966. """Create a version 1 file for this data file.
  967. :param filename: Index filename.
  968. :param progress: Progress report function
  969. :return: Checksum of index file
  970. """
  971. entries = self.sorted_entries(progress=progress)
  972. with GitFile(filename, 'wb') as f:
  973. return write_pack_index_v1(f, entries, self.calculate_checksum())
  974. def create_index_v2(self, filename, progress=None):
  975. """Create a version 2 index file for this data file.
  976. :param filename: Index filename.
  977. :param progress: Progress report function
  978. :return: Checksum of index file
  979. """
  980. entries = self.sorted_entries(progress=progress)
  981. with GitFile(filename, 'wb') as f:
  982. return write_pack_index_v2(f, entries, self.calculate_checksum())
  983. def create_index(self, filename, progress=None,
  984. version=2):
  985. """Create an index file for this data file.
  986. :param filename: Index filename.
  987. :param progress: Progress report function
  988. :return: Checksum of index file
  989. """
  990. if version == 1:
  991. return self.create_index_v1(filename, progress)
  992. elif version == 2:
  993. return self.create_index_v2(filename, progress)
  994. else:
  995. raise ValueError('unknown index format %d' % version)
  996. def get_stored_checksum(self):
  997. """Return the expected checksum stored in this pack."""
  998. self._file.seek(-20, SEEK_END)
  999. return self._file.read(20)
  1000. def check(self):
  1001. """Check the consistency of this pack."""
  1002. actual = self.calculate_checksum()
  1003. stored = self.get_stored_checksum()
  1004. if actual != stored:
  1005. raise ChecksumMismatch(stored, actual)
  1006. def get_object_at(self, offset):
  1007. """Given an offset in to the packfile return the object that is there.
  1008. Using the associated index the location of an object can be looked up,
  1009. and then the packfile can be asked directly for that object using this
  1010. function.
  1011. """
  1012. try:
  1013. return self._offset_cache[offset]
  1014. except KeyError:
  1015. pass
  1016. assert offset >= self._header_size
  1017. self._file.seek(offset)
  1018. unpacked, _ = unpack_object(self._file.read)
  1019. return (unpacked.pack_type_num, unpacked._obj())
  1020. class DeltaChainIterator(object):
  1021. """Abstract iterator over pack data based on delta chains.
  1022. Each object in the pack is guaranteed to be inflated exactly once,
  1023. regardless of how many objects reference it as a delta base. As a result,
  1024. memory usage is proportional to the length of the longest delta chain.
  1025. Subclasses can override _result to define the result type of the iterator.
  1026. By default, results are UnpackedObjects with the following members set:
  1027. * offset
  1028. * obj_type_num
  1029. * obj_chunks
  1030. * pack_type_num
  1031. * delta_base (for delta types)
  1032. * comp_chunks (if _include_comp is True)
  1033. * decomp_chunks
  1034. * decomp_len
  1035. * crc32 (if _compute_crc32 is True)
  1036. """
  1037. _compute_crc32 = False
  1038. _include_comp = False
  1039. def __init__(self, file_obj, resolve_ext_ref=None):
  1040. self._file = file_obj
  1041. self._resolve_ext_ref = resolve_ext_ref
  1042. self._pending_ofs = defaultdict(list)
  1043. self._pending_ref = defaultdict(list)
  1044. self._full_ofs = []
  1045. self._shas = {}
  1046. self._ext_refs = []
  1047. @classmethod
  1048. def for_pack_data(cls, pack_data, resolve_ext_ref=None):
  1049. walker = cls(None, resolve_ext_ref=resolve_ext_ref)
  1050. walker.set_pack_data(pack_data)
  1051. for unpacked in pack_data._iter_unpacked():
  1052. walker.record(unpacked)
  1053. return walker
  1054. def record(self, unpacked):
  1055. type_num = unpacked.pack_type_num
  1056. offset = unpacked.offset
  1057. if type_num == OFS_DELTA:
  1058. base_offset = offset - unpacked.delta_base
  1059. self._pending_ofs[base_offset].append(offset)
  1060. elif type_num == REF_DELTA:
  1061. self._pending_ref[unpacked.delta_base].append(offset)
  1062. else:
  1063. self._full_ofs.append((offset, type_num))
  1064. def set_pack_data(self, pack_data):
  1065. self._file = pack_data._file
  1066. def _walk_all_chains(self):
  1067. for offset, type_num in self._full_ofs:
  1068. for result in self._follow_chain(offset, type_num, None):
  1069. yield result
  1070. for result in self._walk_ref_chains():
  1071. yield result
  1072. assert not self._pending_ofs
  1073. def _ensure_no_pending(self):
  1074. if self._pending_ref:
  1075. raise KeyError([sha_to_hex(s) for s in self._pending_ref])
  1076. def _walk_ref_chains(self):
  1077. if not self._resolve_ext_ref:
  1078. self._ensure_no_pending()
  1079. return
  1080. for base_sha, pending in sorted(self._pending_ref.items()):
  1081. if base_sha not in self._pending_ref:
  1082. continue
  1083. try:
  1084. type_num, chunks = self._resolve_ext_ref(base_sha)
  1085. except KeyError:
  1086. # Not an external ref, but may depend on one. Either it will
  1087. # get popped via a _follow_chain call, or we will raise an
  1088. # error below.
  1089. continue
  1090. self._ext_refs.append(base_sha)
  1091. self._pending_ref.pop(base_sha)
  1092. for new_offset in pending:
  1093. for result in self._follow_chain(new_offset, type_num, chunks):
  1094. yield result
  1095. self._ensure_no_pending()
  1096. def _result(self, unpacked):
  1097. return unpacked
  1098. def _resolve_object(self, offset, obj_type_num, base_chunks):
  1099. self._file.seek(offset)
  1100. unpacked, _ = unpack_object(
  1101. self._file.read, include_comp=self._include_comp,
  1102. compute_crc32=self._compute_crc32)
  1103. unpacked.offset = offset
  1104. if base_chunks is None:
  1105. assert unpacked.pack_type_num == obj_type_num
  1106. else:
  1107. assert unpacked.pack_type_num in DELTA_TYPES
  1108. unpacked.obj_type_num = obj_type_num
  1109. unpacked.obj_chunks = apply_delta(base_chunks,
  1110. unpacked.decomp_chunks)
  1111. return unpacked
  1112. def _follow_chain(self, offset, obj_type_num, base_chunks):
  1113. # Unlike PackData.get_object_at, there is no need to cache offsets as
  1114. # this approach by design inflates each object exactly once.
  1115. todo = [(offset, obj_type_num, base_chunks)]
  1116. for offset, obj_type_num, base_chunks in todo:
  1117. unpacked = self._resolve_object(offset, obj_type_num, base_chunks)
  1118. yield self._result(unpacked)
  1119. unblocked = chain(self._pending_ofs.pop(unpacked.offset, []),
  1120. self._pending_ref.pop(unpacked.sha(), []))
  1121. todo.extend(
  1122. (new_offset, unpacked.obj_type_num, unpacked.obj_chunks)
  1123. for new_offset in unblocked)
  1124. def __iter__(self):
  1125. return self._walk_all_chains()
  1126. def ext_refs(self):
  1127. return self._ext_refs
  1128. class PackIndexer(DeltaChainIterator):
  1129. """Delta chain iterator that yields index entries."""
  1130. _compute_crc32 = True
  1131. def _result(self, unpacked):
  1132. return unpacked.sha(), unpacked.offset, unpacked.crc32
  1133. class PackInflater(DeltaChainIterator):
  1134. """Delta chain iterator that yields ShaFile objects."""
  1135. def _result(self, unpacked):
  1136. return unpacked.sha_file()
  1137. class SHA1Reader(object):
  1138. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1139. def __init__(self, f):
  1140. self.f = f
  1141. self.sha1 = sha1(b'')
  1142. def read(self, num=None):
  1143. data = self.f.read(num)
  1144. self.sha1.update(data)
  1145. return data
  1146. def check_sha(self):
  1147. stored = self.f.read(20)
  1148. if stored != self.sha1.digest():
  1149. raise ChecksumMismatch(self.sha1.hexdigest(), sha_to_hex(stored))
  1150. def close(self):
  1151. return self.f.close()
  1152. def tell(self):
  1153. return self.f.tell()
  1154. class SHA1Writer(object):
  1155. """Wrapper for file-like object that remembers the SHA1 of its data."""
  1156. def __init__(self, f):
  1157. self.f = f
  1158. self.length = 0
  1159. self.sha1 = sha1(b'')
  1160. def write(self, data):
  1161. self.sha1.update(data)
  1162. self.f.write(data)
  1163. self.length += len(data)
  1164. def write_sha(self):
  1165. sha = self.sha1.digest()
  1166. assert len(sha) == 20
  1167. self.f.write(sha)
  1168. self.length += len(sha)
  1169. return sha
  1170. def close(self):
  1171. sha = self.write_sha()
  1172. self.f.close()
  1173. return sha
  1174. def offset(self):
  1175. return self.length
  1176. def tell(self):
  1177. return self.f.tell()
  1178. def pack_object_header(type_num, delta_base, size):
  1179. """Create a pack object header for the given object info.
  1180. :param type_num: Numeric type of the object.
  1181. :param delta_base: Delta base offset or ref, or None for whole objects.
  1182. :param size: Uncompressed object size.
  1183. :return: A header for a packed object.
  1184. """
  1185. header = []
  1186. c = (type_num << 4) | (size & 15)
  1187. size >>= 4
  1188. while size:
  1189. header.append(c | 0x80)
  1190. c = size & 0x7f
  1191. size >>= 7
  1192. header.append(c)
  1193. if type_num == OFS_DELTA:
  1194. ret = [delta_base & 0x7f]
  1195. delta_base >>= 7
  1196. while delta_base:
  1197. delta_base -= 1
  1198. ret.insert(0, 0x80 | (delta_base & 0x7f))
  1199. delta_base >>= 7
  1200. header.extend(ret)
  1201. elif type_num == REF_DELTA:
  1202. assert len(delta_base) == 20
  1203. header += delta_base
  1204. return bytearray(header)
  1205. def write_pack_object(f, type, object, sha=None):
  1206. """Write pack object to a file.
  1207. :param f: File to write to
  1208. :param type: Numeric type of the object
  1209. :param object: Object to write
  1210. :return: Tuple with offset at which the object was written, and crc32
  1211. """
  1212. if type in DELTA_TYPES:
  1213. delta_base, object = object
  1214. else:
  1215. delta_base = None
  1216. header = bytes(pack_object_header(type, delta_base, len(object)))
  1217. comp_data = zlib.compress(object)
  1218. crc32 = 0
  1219. for data in (header, comp_data):
  1220. f.write(data)
  1221. if sha is not None:
  1222. sha.update(data)
  1223. crc32 = binascii.crc32(data, crc32)
  1224. return crc32 & 0xffffffff
  1225. def write_pack(filename, objects, deltify=None, delta_window_size=None):
  1226. """Write a new pack data file.
  1227. :param filename: Path to the new pack file (without .pack extension)
  1228. :param objects: Iterable of (object, path) tuples to write.
  1229. Should provide __len__
  1230. :param window_size: Delta window size
  1231. :param deltify: Whether to deltify pack objects
  1232. :return: Tuple with checksum of pack file and index file
  1233. """
  1234. with GitFile(filename + '.pack', 'wb') as f:
  1235. entries, data_sum = write_pack_objects(
  1236. f, objects, delta_window_size=delta_window_size, deltify=deltify)
  1237. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  1238. with GitFile(filename + '.idx', 'wb') as f:
  1239. return data_sum, write_pack_index_v2(f, entries, data_sum)
  1240. def write_pack_header(f, num_objects):
  1241. """Write a pack header for the given number of objects."""
  1242. f.write(b'PACK') # Pack header
  1243. f.write(struct.pack(b'>L', 2)) # Pack version
  1244. f.write(struct.pack(b'>L', num_objects)) # Number of objects in pack
  1245. def deltify_pack_objects(objects, window_size=None):
  1246. """Generate deltas for pack objects.
  1247. :param objects: An iterable of (object, path) tuples to deltify.
  1248. :param window_size: Window size; None for default
  1249. :return: Iterator over type_num, object id, delta_base, content
  1250. delta_base is None for full text entries
  1251. """
  1252. if window_size is None:
  1253. window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE
  1254. # Build a list of objects ordered by the magic Linus heuristic
  1255. # This helps us find good objects to diff against us
  1256. magic = []
  1257. for obj, path in objects:
  1258. magic.append((obj.type_num, path, -obj.raw_length(), obj))
  1259. magic.sort()
  1260. possible_bases = deque()
  1261. for type_num, path, neg_length, o in magic:
  1262. raw = o.as_raw_string()
  1263. winner = raw
  1264. winner_base = None
  1265. for base in possible_bases:
  1266. if base.type_num != type_num:
  1267. continue
  1268. delta = create_delta(base.as_raw_string(), raw)
  1269. if len(delta) < len(winner):
  1270. winner_base = base.sha().digest()
  1271. winner = delta
  1272. yield type_num, o.sha().digest(), winner_base, winner
  1273. possible_bases.appendleft(o)
  1274. while len(possible_bases) > window_size:
  1275. possible_bases.pop()
  1276. def write_pack_objects(f, objects, delta_window_size=None, deltify=False):
  1277. """Write a new pack data file.
  1278. :param f: File to write to
  1279. :param objects: Iterable of (object, path) tuples to write.
  1280. Should provide __len__
  1281. :param window_size: Sliding window size for searching for deltas;
  1282. Set to None for default window size.
  1283. :param deltify: Whether to deltify objects
  1284. :return: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1285. """
  1286. if deltify:
  1287. pack_contents = deltify_pack_objects(objects, delta_window_size)
  1288. else:
  1289. pack_contents = (
  1290. (o.type_num, o.sha().digest(), None, o.as_raw_string())
  1291. for (o, path) in objects)
  1292. return write_pack_data(f, len(objects), pack_contents)
  1293. def write_pack_data(f, num_records, records):
  1294. """Write a new pack data file.
  1295. :param f: File to write to
  1296. :param num_records: Number of records
  1297. :param records: Iterator over type_num, object_id, delta_base, raw
  1298. :return: Dict mapping id -> (offset, crc32 checksum), pack checksum
  1299. """
  1300. # Write the pack
  1301. entries = {}
  1302. f = SHA1Writer(f)
  1303. write_pack_header(f, num_records)
  1304. for type_num, object_id, delta_base, raw in records:
  1305. offset = f.offset()
  1306. if delta_base is not None:
  1307. try:
  1308. base_offset, base_crc32 = entries[delta_base]
  1309. except KeyError:
  1310. type_num = REF_DELTA
  1311. raw = (delta_base, raw)
  1312. else:
  1313. type_num = OFS_DELTA
  1314. raw = (offset - base_offset, raw)
  1315. crc32 = write_pack_object(f, type_num, raw)
  1316. entries[object_id] = (offset, crc32)
  1317. return entries, f.write_sha()
  1318. def write_pack_index_v1(f, entries, pack_checksum):
  1319. """Write a new pack index file.
  1320. :param f: A file-like object to write to
  1321. :param entries: List of tuples with object name (sha), offset_in_pack,
  1322. and crc32_checksum.
  1323. :param pack_checksum: Checksum of the pack file.
  1324. :return: The SHA of the written index file
  1325. """
  1326. f = SHA1Writer(f)
  1327. fan_out_table = defaultdict(lambda: 0)
  1328. for (name, offset, entry_checksum) in entries:
  1329. fan_out_table[ord(name[:1])] += 1
  1330. # Fan-out table
  1331. for i in range(0x100):
  1332. f.write(struct.pack('>L', fan_out_table[i]))
  1333. fan_out_table[i+1] += fan_out_table[i]
  1334. for (name, offset, entry_checksum) in entries:
  1335. if not (offset <= 0xffffffff):
  1336. raise TypeError("pack format 1 only supports offsets < 2Gb")
  1337. f.write(struct.pack('>L20s', offset, name))
  1338. assert len(pack_checksum) == 20
  1339. f.write(pack_checksum)
  1340. return f.write_sha()
  1341. def _delta_encode_size(size):
  1342. ret = bytearray()
  1343. c = size & 0x7f
  1344. size >>= 7
  1345. while size:
  1346. ret.append(c | 0x80)
  1347. c = size & 0x7f
  1348. size >>= 7
  1349. ret.append(c)
  1350. return ret
  1351. # The length of delta compression copy operations in version 2 packs is limited
  1352. # to 64K. To copy more, we use several copy operations. Version 3 packs allow
  1353. # 24-bit lengths in copy operations, but we always make version 2 packs.
  1354. _MAX_COPY_LEN = 0xffff
  1355. def _encode_copy_operation(start, length):
  1356. scratch = []
  1357. op = 0x80
  1358. for i in range(4):
  1359. if start & 0xff << i*8:
  1360. scratch.append((start >> i*8) & 0xff)
  1361. op |= 1 << i
  1362. for i in range(2):
  1363. if length & 0xff << i*8:
  1364. scratch.append((length >> i*8) & 0xff)
  1365. op |= 1 << (4+i)
  1366. return bytearray([op] + scratch)
  1367. def create_delta(base_buf, target_buf):
  1368. """Use python difflib to work out how to transform base_buf to target_buf.
  1369. :param base_buf: Base buffer
  1370. :param target_buf: Target buffer
  1371. """
  1372. assert isinstance(base_buf, bytes)
  1373. assert isinstance(target_buf, bytes)
  1374. out_buf = bytearray()
  1375. # write delta header
  1376. out_buf += _delta_encode_size(len(base_buf))
  1377. out_buf += _delta_encode_size(len(target_buf))
  1378. # write out delta opcodes
  1379. seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
  1380. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  1381. # Git patch opcodes don't care about deletes!
  1382. # if opcode == 'replace' or opcode == 'delete':
  1383. # pass
  1384. if opcode == 'equal':
  1385. # If they are equal, unpacker will use data from base_buf
  1386. # Write out an opcode that says what range to use
  1387. copy_start = i1
  1388. copy_len = i2 - i1
  1389. while copy_len > 0:
  1390. to_copy = min(copy_len, _MAX_COPY_LEN)
  1391. out_buf += _encode_copy_operation(copy_start, to_copy)
  1392. copy_start += to_copy
  1393. copy_len -= to_copy
  1394. if opcode == 'replace' or opcode == 'insert':
  1395. # If we are replacing a range or adding one, then we just
  1396. # output it to the stream (prefixed by its size)
  1397. s = j2 - j1
  1398. o = j1
  1399. while s > 127:
  1400. out_buf.append(127)
  1401. out_buf += bytearray(target_buf[o:o+127])
  1402. s -= 127
  1403. o += 127
  1404. out_buf.append(s)
  1405. out_buf += bytearray(target_buf[o:o+s])
  1406. return bytes(out_buf)
  1407. def apply_delta(src_buf, delta):
  1408. """Based on the similar function in git's patch-delta.c.
  1409. :param src_buf: Source buffer
  1410. :param delta: Delta instructions
  1411. """
  1412. if not isinstance(src_buf, bytes):
  1413. src_buf = b''.join(src_buf)
  1414. if not isinstance(delta, bytes):
  1415. delta = b''.join(delta)
  1416. out = []
  1417. index = 0
  1418. delta_length = len(delta)
  1419. def get_delta_header_size(delta, index):
  1420. size = 0
  1421. i = 0
  1422. while delta:
  1423. cmd = ord(delta[index:index+1])
  1424. index += 1
  1425. size |= (cmd & ~0x80) << i
  1426. i += 7
  1427. if not cmd & 0x80:
  1428. break
  1429. return size, index
  1430. src_size, index = get_delta_header_size(delta, index)
  1431. dest_size, index = get_delta_header_size(delta, index)
  1432. assert src_size == len(src_buf), '%d vs %d' % (src_size, len(src_buf))
  1433. while index < delta_length:
  1434. cmd = ord(delta[index:index+1])
  1435. index += 1
  1436. if cmd & 0x80:
  1437. cp_off = 0
  1438. for i in range(4):
  1439. if cmd & (1 << i):
  1440. x = ord(delta[index:index+1])
  1441. index += 1
  1442. cp_off |= x << (i * 8)
  1443. cp_size = 0
  1444. # Version 3 packs can contain copy sizes larger than 64K.
  1445. for i in range(3):
  1446. if cmd & (1 << (4+i)):
  1447. x = ord(delta[index:index+1])
  1448. index += 1
  1449. cp_size |= x << (i * 8)
  1450. if cp_size == 0:
  1451. cp_size = 0x10000
  1452. if (cp_off + cp_size < cp_size or
  1453. cp_off + cp_size > src_size or
  1454. cp_size > dest_size):
  1455. break
  1456. out.append(src_buf[cp_off:cp_off+cp_size])
  1457. elif cmd != 0:
  1458. out.append(delta[index:index+cmd])
  1459. index += cmd
  1460. else:
  1461. raise ApplyDeltaError('Invalid opcode 0')
  1462. if index != delta_length:
  1463. raise ApplyDeltaError('delta not empty: %r' % delta[index:])
  1464. if dest_size != chunks_length(out):
  1465. raise ApplyDeltaError('dest size incorrect')
  1466. return out
  1467. def write_pack_index_v2(f, entries, pack_checksum):
  1468. """Write a new pack index file.
  1469. :param f: File-like object to write to
  1470. :param entries: List of tuples with object name (sha), offset_in_pack, and
  1471. crc32_checksum.
  1472. :param pack_checksum: Checksum of the pack file.
  1473. :return: The SHA of the index file written
  1474. """
  1475. f = SHA1Writer(f)
  1476. f.write(b'\377tOc') # Magic!
  1477. f.write(struct.pack('>L', 2))
  1478. fan_out_table = defaultdict(lambda: 0)
  1479. for (name, offset, entry_checksum) in entries:
  1480. fan_out_table[ord(name[:1])] += 1
  1481. # Fan-out table
  1482. largetable = []
  1483. for i in range(0x100):
  1484. f.write(struct.pack(b'>L', fan_out_table[i]))
  1485. fan_out_table[i+1] += fan_out_table[i]
  1486. for (name, offset, entry_checksum) in entries:
  1487. f.write(name)
  1488. for (name, offset, entry_checksum) in entries:
  1489. f.write(struct.pack(b'>L', entry_checksum))
  1490. for (name, offset, entry_checksum) in entries:
  1491. if offset < 2**31:
  1492. f.write(struct.pack(b'>L', offset))
  1493. else:
  1494. f.write(struct.pack(b'>L', 2**31 + len(largetable)))
  1495. largetable.append(offset)
  1496. for offset in largetable:
  1497. f.write(struct.pack(b'>Q', offset))
  1498. assert len(pack_checksum) == 20
  1499. f.write(pack_checksum)
  1500. return f.write_sha()
  1501. write_pack_index = write_pack_index_v2
  1502. class Pack(object):
  1503. """A Git pack object."""
  1504. def __init__(self, basename, resolve_ext_ref=None):
  1505. self._basename = basename
  1506. self._data = None
  1507. self._idx = None
  1508. self._idx_path = self._basename + '.idx'
  1509. self._data_path = self._basename + '.pack'
  1510. self._data_load = lambda: PackData(self._data_path)
  1511. self._idx_load = lambda: load_pack_index(self._idx_path)
  1512. self.resolve_ext_ref = resolve_ext_ref
  1513. @classmethod
  1514. def from_lazy_objects(self, data_fn, idx_fn):
  1515. """Create a new pack object from callables to load pack data and
  1516. index objects."""
  1517. ret = Pack('')
  1518. ret._data_load = data_fn
  1519. ret._idx_load = idx_fn
  1520. return ret
  1521. @classmethod
  1522. def from_objects(self, data, idx):
  1523. """Create a new pack object from pack data and index objects."""
  1524. ret = Pack('')
  1525. ret._data_load = lambda: data
  1526. ret._idx_load = lambda: idx
  1527. return ret
  1528. def name(self):
  1529. """The SHA over the SHAs of the objects in this pack."""
  1530. return self.index.objects_sha1()
  1531. @property
  1532. def data(self):
  1533. """The pack data object being used."""
  1534. if self._data is None:
  1535. self._data = self._data_load()
  1536. self._data.pack = self
  1537. self.check_length_and_checksum()
  1538. return self._data
  1539. @property
  1540. def index(self):
  1541. """The index being used.
  1542. :note: This may be an in-memory index
  1543. """
  1544. if self._idx is None:
  1545. self._idx = self._idx_load()
  1546. return self._idx
  1547. def close(self):
  1548. if self._data is not None:
  1549. self._data.close()
  1550. if self._idx is not None:
  1551. self._idx.close()
  1552. def __enter__(self):
  1553. return self
  1554. def __exit__(self, exc_type, exc_val, exc_tb):
  1555. self.close()
  1556. def __eq__(self, other):
  1557. return isinstance(self, type(other)) and self.index == other.index
  1558. def __len__(self):
  1559. """Number of entries in this pack."""
  1560. return len(self.index)
  1561. def __repr__(self):
  1562. return '%s(%r)' % (self.__class__.__name__, self._basename)
  1563. def __iter__(self):
  1564. """Iterate over all the sha1s of the objects in this pack."""
  1565. return iter(self.index)
  1566. def check_length_and_checksum(self):
  1567. """Sanity check the length and checksum of the pack index and data."""
  1568. assert len(self.index) == len(self.data)
  1569. idx_stored_checksum = self.index.get_pack_checksum()
  1570. data_stored_checksum = self.data.get_stored_checksum()
  1571. if idx_stored_checksum != data_stored_checksum:
  1572. raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
  1573. sha_to_hex(data_stored_checksum))
  1574. def check(self):
  1575. """Check the integrity of this pack.
  1576. :raise ChecksumMismatch: if a checksum for the index or data is wrong
  1577. """
  1578. self.index.check()
  1579. self.data.check()
  1580. for obj in self.iterobjects():
  1581. obj.check()
  1582. # TODO: object connectivity checks
  1583. def get_stored_checksum(self):
  1584. return self.data.get_stored_checksum()
  1585. def __contains__(self, sha1):
  1586. """Check whether this pack contains a particular SHA1."""
  1587. try:
  1588. self.index.object_index(sha1)
  1589. return True
  1590. except KeyError:
  1591. return False
  1592. def get_raw(self, sha1):
  1593. offset = self.index.object_index(sha1)
  1594. obj_type, obj = self.data.get_object_at(offset)
  1595. type_num, chunks = self.data.resolve_object(offset, obj_type, obj)
  1596. return type_num, b''.join(chunks)
  1597. def __getitem__(self, sha1):
  1598. """Retrieve the specified SHA1."""
  1599. type, uncomp = self.get_raw(sha1)
  1600. return ShaFile.from_raw_string(type, uncomp, sha=sha1)
  1601. def iterobjects(self):
  1602. """Iterate over the objects in this pack."""
  1603. return iter(PackInflater.for_pack_data(
  1604. self.data, resolve_ext_ref=self.resolve_ext_ref))
  1605. def pack_tuples(self):
  1606. """Provide an iterable for use with write_pack_objects.
  1607. :return: Object that can iterate over (object, path) tuples
  1608. and provides __len__
  1609. """
  1610. class PackTupleIterable(object):
  1611. def __init__(self, pack):
  1612. self.pack = pack
  1613. def __len__(self):
  1614. return len(self.pack)
  1615. def __iter__(self):
  1616. return ((o, None) for o in self.pack.iterobjects())
  1617. return PackTupleIterable(self)
  1618. def keep(self, msg=None):
  1619. """Add a .keep file for the pack, preventing git from garbage collecting it.
  1620. :param msg: A message written inside the .keep file; can be used later
  1621. to determine whether or not a .keep file is obsolete.
  1622. :return: The path of the .keep file, as a string.
  1623. """
  1624. keepfile_name = '%s.keep' % self._basename
  1625. with GitFile(keepfile_name, 'wb') as keepfile:
  1626. if msg:
  1627. keepfile.write(msg)
  1628. keepfile.write(b'\n')
  1629. return keepfile_name
  1630. try:
  1631. from dulwich._pack import apply_delta, bisect_find_sha # noqa: F811
  1632. except ImportError:
  1633. pass