2
0

pack.py 61 KB

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