pack.py 64 KB

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