pack.py 63 KB

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