pack.py 64 KB

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