pack.py 61 KB

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