pack.py 57 KB

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