pack.py 62 KB

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