pack.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  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_END,
  71. )
  72. from dulwich.objects import (
  73. ShaFile,
  74. hex_to_sha,
  75. sha_to_hex,
  76. object_header,
  77. )
  78. supports_mmap_offset = (sys.version_info[0] >= 3 or
  79. (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
  80. OFS_DELTA = 6
  81. REF_DELTA = 7
  82. DELTA_TYPES = (OFS_DELTA, REF_DELTA)
  83. def take_msb_bytes(read, crc32=None):
  84. """Read bytes marked with most significant bit.
  85. :param read: Read function
  86. """
  87. ret = []
  88. while len(ret) == 0 or ret[-1] & 0x80:
  89. b = read(1)
  90. if crc32 is not None:
  91. crc32 = binascii.crc32(b, crc32)
  92. ret.append(ord(b))
  93. return ret, crc32
  94. def read_zlib_chunks(read_some, dec_size, buffer_size=4096, crc32=None):
  95. """Read zlib data from a buffer.
  96. This function requires that the buffer have additional data following the
  97. compressed data, which is guaranteed to be the case for git pack files.
  98. :param read_some: Read function that returns at least one byte, but may
  99. return less than the requested size
  100. :param dec_size: Expected size of the decompressed buffer
  101. :param buffer_size: Size of the read buffer
  102. :param crc32: If not None, the CRC32 of the compressed bytes will be
  103. computed using this starting CRC32. If False, CRC32 computations will
  104. not be done, and the returned CRC32 will be None.
  105. :return: Tuple of (
  106. list of uncompressed chunks,
  107. length of compressed data,
  108. crc32 of compressed data,
  109. unused read data,
  110. ).
  111. :raise zlib.error: if a decompression error occurred.
  112. """
  113. if dec_size <= -1:
  114. raise ValueError('non-negative zlib data stream size expected')
  115. obj = zlib.decompressobj()
  116. ret = []
  117. size = 0
  118. comp_size = 0
  119. while True:
  120. add = read_some(buffer_size)
  121. if not add:
  122. raise zlib.error('EOF before end of zlib stream')
  123. comp_size += len(add)
  124. decomp = obj.decompress(add)
  125. size += len(decomp)
  126. ret.append(decomp)
  127. unused = obj.unused_data
  128. if unused:
  129. left = len(unused)
  130. comp_size -= left
  131. if crc32 is not None:
  132. crc32 = binascii.crc32(add[:-left], crc32)
  133. break
  134. elif crc32 is not None:
  135. crc32 = binascii.crc32(add, crc32)
  136. if size != dec_size:
  137. raise zlib.error('decompressed data does not match expected size')
  138. return ret, comp_size, crc32, unused
  139. def iter_sha1(iter):
  140. """Return the hexdigest of the SHA1 over a set of names.
  141. :param iter: Iterator over string objects
  142. :return: 40-byte hex sha1 digest
  143. """
  144. sha1 = make_sha()
  145. for name in iter:
  146. sha1.update(name)
  147. return sha1.hexdigest()
  148. def load_pack_index(path):
  149. """Load an index file by path.
  150. :param filename: Path to the index file
  151. :return: A PackIndex loaded from the given path
  152. """
  153. f = GitFile(path, 'rb')
  154. try:
  155. return load_pack_index_file(path, f)
  156. finally:
  157. f.close()
  158. def _load_file_contents(f, size=None):
  159. fileno = getattr(f, 'fileno', None)
  160. # Attempt to use mmap if possible
  161. if fileno is not None:
  162. fd = f.fileno()
  163. if size is None:
  164. size = os.fstat(fd).st_size
  165. if has_mmap:
  166. try:
  167. contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
  168. except mmap.error:
  169. # Perhaps a socket?
  170. pass
  171. else:
  172. return contents, size
  173. contents = f.read()
  174. size = len(contents)
  175. return contents, size
  176. def load_pack_index_file(path, f):
  177. """Load an index file from a file-like object.
  178. :param path: Path for the index file
  179. :param f: File-like object
  180. :return: A PackIndex loaded from the given file
  181. """
  182. contents, size = _load_file_contents(f)
  183. if contents[:4] == '\377tOc':
  184. version = struct.unpack('>L', contents[4:8])[0]
  185. if version == 2:
  186. return PackIndex2(path, file=f, contents=contents,
  187. size=size)
  188. else:
  189. raise KeyError('Unknown pack index format %d' % version)
  190. else:
  191. return PackIndex1(path, file=f, contents=contents, size=size)
  192. def bisect_find_sha(start, end, sha, unpack_name):
  193. """Find a SHA in a data blob with sorted SHAs.
  194. :param start: Start index of range to search
  195. :param end: End index of range to search
  196. :param sha: Sha to find
  197. :param unpack_name: Callback to retrieve SHA by index
  198. :return: Index of the SHA, or None if it wasn't found
  199. """
  200. assert start <= end
  201. while start <= end:
  202. i = (start + end)/2
  203. file_sha = unpack_name(i)
  204. x = cmp(file_sha, sha)
  205. if x < 0:
  206. start = i + 1
  207. elif x > 0:
  208. end = i - 1
  209. else:
  210. return i
  211. return None
  212. class PackIndex(object):
  213. """An index in to a packfile.
  214. Given a sha id of an object a pack index can tell you the location in the
  215. packfile of that object if it has it.
  216. """
  217. def __eq__(self, other):
  218. if not isinstance(other, PackIndex):
  219. return False
  220. for (name1, _, _), (name2, _, _) in izip(self.iterentries(),
  221. other.iterentries()):
  222. if name1 != name2:
  223. return False
  224. return True
  225. def __ne__(self, other):
  226. return not self.__eq__(other)
  227. def __len__(self):
  228. """Return the number of entries in this pack index."""
  229. raise NotImplementedError(self.__len__)
  230. def __iter__(self):
  231. """Iterate over the SHAs in this pack."""
  232. return imap(sha_to_hex, self._itersha())
  233. def iterentries(self):
  234. """Iterate over the entries in this pack index.
  235. :return: iterator over tuples with object name, offset in packfile and
  236. crc32 checksum.
  237. """
  238. raise NotImplementedError(self.iterentries)
  239. def get_pack_checksum(self):
  240. """Return the SHA1 checksum stored for the corresponding packfile.
  241. :return: 20-byte binary digest
  242. """
  243. raise NotImplementedError(self.get_pack_checksum)
  244. def object_index(self, sha):
  245. """Return the index in to the corresponding packfile for the object.
  246. Given the name of an object it will return the offset that object
  247. lives at within the corresponding pack file. If the pack file doesn't
  248. have the object then None will be returned.
  249. """
  250. if len(sha) == 40:
  251. sha = hex_to_sha(sha)
  252. return self._object_index(sha)
  253. def _object_index(self, sha):
  254. """See object_index.
  255. :param sha: A *binary* SHA string. (20 characters long)_
  256. """
  257. raise NotImplementedError(self._object_index)
  258. def objects_sha1(self):
  259. """Return the hex SHA1 over all the shas of all objects in this pack.
  260. :note: This is used for the filename of the pack.
  261. """
  262. return iter_sha1(self._itersha())
  263. def _itersha(self):
  264. """Yield all the SHA1's of the objects in the index, sorted."""
  265. raise NotImplementedError(self._itersha)
  266. class MemoryPackIndex(PackIndex):
  267. """Pack index that is stored entirely in memory."""
  268. def __init__(self, entries, pack_checksum=None):
  269. """Create a new MemoryPackIndex.
  270. :param entries: Sequence of name, idx, crc32 (sorted)
  271. :param pack_checksum: Optional pack checksum
  272. """
  273. self._by_sha = {}
  274. for name, idx, crc32 in entries:
  275. self._by_sha[name] = idx
  276. self._entries = entries
  277. self._pack_checksum = pack_checksum
  278. def get_pack_checksum(self):
  279. return self._pack_checksum
  280. def __len__(self):
  281. return len(self._entries)
  282. def _object_index(self, sha):
  283. return self._by_sha[sha][0]
  284. def _itersha(self):
  285. return iter(self._by_sha)
  286. def iterentries(self):
  287. return iter(self._entries)
  288. class FilePackIndex(PackIndex):
  289. """Pack index that is based on a file.
  290. To do the loop it opens the file, and indexes first 256 4 byte groups
  291. with the first byte of the sha id. The value in the four byte group indexed
  292. is the end of the group that shares the same starting byte. Subtract one
  293. from the starting byte and index again to find the start of the group.
  294. The values are sorted by sha id within the group, so do the math to find
  295. the start and end offset and then bisect in to find if the value is present.
  296. """
  297. def __init__(self, filename, file=None, contents=None, size=None):
  298. """Create a pack index object.
  299. Provide it with the name of the index file to consider, and it will map
  300. it whenever required.
  301. """
  302. self._filename = filename
  303. # Take the size now, so it can be checked each time we map the file to
  304. # ensure that it hasn't changed.
  305. if file is None:
  306. self._file = GitFile(filename, 'rb')
  307. else:
  308. self._file = file
  309. if contents is None:
  310. self._contents, self._size = _load_file_contents(self._file, size)
  311. else:
  312. self._contents, self._size = (contents, size)
  313. def __eq__(self, other):
  314. # Quick optimization:
  315. if (isinstance(other, FilePackIndex) and
  316. self._fan_out_table != other._fan_out_table):
  317. return False
  318. return super(FilePackIndex, self).__eq__(other)
  319. def close(self):
  320. self._file.close()
  321. if getattr(self._contents, "close", None) is not None:
  322. self._contents.close()
  323. def __len__(self):
  324. """Return the number of entries in this pack index."""
  325. return self._fan_out_table[-1]
  326. def _unpack_entry(self, i):
  327. """Unpack the i-th entry in the index file.
  328. :return: Tuple with object name (SHA), offset in pack file and CRC32
  329. checksum (if known).
  330. """
  331. raise NotImplementedError(self._unpack_entry)
  332. def _unpack_name(self, i):
  333. """Unpack the i-th name from the index file."""
  334. raise NotImplementedError(self._unpack_name)
  335. def _unpack_offset(self, i):
  336. """Unpack the i-th object offset from the index file."""
  337. raise NotImplementedError(self._unpack_offset)
  338. def _unpack_crc32_checksum(self, i):
  339. """Unpack the crc32 checksum for the i-th object from the index file."""
  340. raise NotImplementedError(self._unpack_crc32_checksum)
  341. def _itersha(self):
  342. for i in range(len(self)):
  343. yield self._unpack_name(i)
  344. def iterentries(self):
  345. """Iterate over the entries in this pack index.
  346. :return: iterator over tuples with object name, offset in packfile and
  347. crc32 checksum.
  348. """
  349. for i in range(len(self)):
  350. yield self._unpack_entry(i)
  351. def _read_fan_out_table(self, start_offset):
  352. ret = []
  353. for i in range(0x100):
  354. fanout_entry = self._contents[start_offset+i*4:start_offset+(i+1)*4]
  355. ret.append(struct.unpack('>L', fanout_entry)[0])
  356. return ret
  357. def check(self):
  358. """Check that the stored checksum matches the actual checksum."""
  359. actual = self.calculate_checksum()
  360. stored = self.get_stored_checksum()
  361. if actual != stored:
  362. raise ChecksumMismatch(stored, actual)
  363. def calculate_checksum(self):
  364. """Calculate the SHA1 checksum over this pack index.
  365. :return: This is a 20-byte binary digest
  366. """
  367. return make_sha(self._contents[:-20]).digest()
  368. def get_pack_checksum(self):
  369. """Return the SHA1 checksum stored for the corresponding packfile.
  370. :return: 20-byte binary digest
  371. """
  372. return str(self._contents[-40:-20])
  373. def get_stored_checksum(self):
  374. """Return the SHA1 checksum stored for this index.
  375. :return: 20-byte binary digest
  376. """
  377. return str(self._contents[-20:])
  378. def _object_index(self, sha):
  379. """See object_index.
  380. :param sha: A *binary* SHA string. (20 characters long)_
  381. """
  382. assert len(sha) == 20
  383. idx = ord(sha[0])
  384. if idx == 0:
  385. start = 0
  386. else:
  387. start = self._fan_out_table[idx-1]
  388. end = self._fan_out_table[idx]
  389. i = bisect_find_sha(start, end, sha, self._unpack_name)
  390. if i is None:
  391. raise KeyError(sha)
  392. return self._unpack_offset(i)
  393. class PackIndex1(FilePackIndex):
  394. """Version 1 Pack Index file."""
  395. def __init__(self, filename, file=None, contents=None, size=None):
  396. super(PackIndex1, self).__init__(filename, file, contents, size)
  397. self.version = 1
  398. self._fan_out_table = self._read_fan_out_table(0)
  399. def _unpack_entry(self, i):
  400. (offset, name) = unpack_from('>L20s', self._contents,
  401. (0x100 * 4) + (i * 24))
  402. return (name, offset, None)
  403. def _unpack_name(self, i):
  404. offset = (0x100 * 4) + (i * 24) + 4
  405. return self._contents[offset:offset+20]
  406. def _unpack_offset(self, i):
  407. offset = (0x100 * 4) + (i * 24)
  408. return unpack_from('>L', self._contents, offset)[0]
  409. def _unpack_crc32_checksum(self, i):
  410. # Not stored in v1 index files
  411. return None
  412. class PackIndex2(FilePackIndex):
  413. """Version 2 Pack Index file."""
  414. def __init__(self, filename, file=None, contents=None, size=None):
  415. super(PackIndex2, self).__init__(filename, file, contents, size)
  416. assert self._contents[:4] == '\377tOc', 'Not a v2 pack index file'
  417. (self.version, ) = unpack_from('>L', self._contents, 4)
  418. assert self.version == 2, 'Version was %d' % self.version
  419. self._fan_out_table = self._read_fan_out_table(8)
  420. self._name_table_offset = 8 + 0x100 * 4
  421. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  422. self._pack_offset_table_offset = (self._crc32_table_offset +
  423. 4 * len(self))
  424. def _unpack_entry(self, i):
  425. return (self._unpack_name(i), self._unpack_offset(i),
  426. self._unpack_crc32_checksum(i))
  427. def _unpack_name(self, i):
  428. offset = self._name_table_offset + i * 20
  429. return self._contents[offset:offset+20]
  430. def _unpack_offset(self, i):
  431. offset = self._pack_offset_table_offset + i * 4
  432. return unpack_from('>L', self._contents, offset)[0]
  433. def _unpack_crc32_checksum(self, i):
  434. return unpack_from('>L', self._contents,
  435. self._crc32_table_offset + i * 4)[0]
  436. def read_pack_header(read):
  437. """Read the header of a pack file.
  438. :param read: Read function
  439. :return: Tuple with pack version and number of objects
  440. """
  441. header = read(12)
  442. assert header[:4] == 'PACK'
  443. (version,) = unpack_from('>L', header, 4)
  444. assert version in (2, 3), 'Version was %d' % version
  445. (num_objects,) = unpack_from('>L', header, 8)
  446. return (version, num_objects)
  447. def chunks_length(chunks):
  448. return sum(imap(len, chunks))
  449. def unpack_object(read_all, read_some=None, compute_crc32=False):
  450. """Unpack a Git object.
  451. :param read_all: Read function that blocks until the number of requested
  452. bytes are read.
  453. :param read_some: Read function that returns at least one byte, but may not
  454. return the number of bytes requested.
  455. :param compute_crc32: If True, compute the CRC32 of the compressed data. If
  456. False, the returned CRC32 will be None.
  457. :return: A tuple of (
  458. type number,
  459. uncompressed data,
  460. length of compressed data,
  461. CRC32 of compressed data,
  462. unused read data,
  463. ).
  464. For delta types, the uncompressed data is a tuple of
  465. (base, uncompressed chunks).
  466. """
  467. if read_some is None:
  468. read_some = read_all
  469. if compute_crc32:
  470. crc32 = 0
  471. else:
  472. crc32 = None
  473. bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
  474. type_num = (bytes[0] >> 4) & 0x07
  475. size = bytes[0] & 0x0f
  476. for i, byte in enumerate(bytes[1:]):
  477. size += (byte & 0x7f) << ((i * 7) + 4)
  478. raw_base = len(bytes)
  479. if type_num == OFS_DELTA:
  480. bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
  481. raw_base += len(bytes)
  482. assert not (bytes[-1] & 0x80)
  483. delta_base_offset = bytes[0] & 0x7f
  484. for byte in bytes[1:]:
  485. delta_base_offset += 1
  486. delta_base_offset <<= 7
  487. delta_base_offset += (byte & 0x7f)
  488. base = delta_base_offset
  489. elif type_num == REF_DELTA:
  490. base = read_all(20)
  491. if compute_crc32:
  492. crc32 = binascii.crc32(base, crc32)
  493. raw_base += 20
  494. else:
  495. base = None
  496. uncomp, comp_len, crc32, unused = read_zlib_chunks(read_some, size,
  497. crc32=crc32)
  498. if compute_crc32:
  499. crc32 &= 0xffffffff
  500. comp_len += raw_base
  501. if base is None:
  502. return type_num, uncomp, comp_len, crc32, unused
  503. else:
  504. return type_num, (base, uncomp), comp_len, crc32, unused
  505. def _compute_object_size((num, obj)):
  506. """Compute the size of a unresolved object for use with LRUSizeCache."""
  507. if num in DELTA_TYPES:
  508. return chunks_length(obj[1])
  509. return chunks_length(obj)
  510. class PackStreamReader(object):
  511. """Class to read a pack stream.
  512. The pack is read from a ReceivableProtocol using read() or recv() as
  513. appropriate.
  514. """
  515. def __init__(self, read_all, read_some=None):
  516. self.read_all = read_all
  517. if read_some is None:
  518. self.read_some = read_all
  519. else:
  520. self.read_some = read_some
  521. self.sha = make_sha()
  522. self._offset = 0
  523. self._rbuf = StringIO()
  524. # trailer is a deque to avoid memory allocation on small reads
  525. self._trailer = deque()
  526. def _read(self, read, size):
  527. """Read up to size bytes using the given callback.
  528. As a side effect, update the verifier's hash (excluding the last 20
  529. bytes read).
  530. :param read: The read callback to read from.
  531. :param size: The maximum number of bytes to read; the particular
  532. behavior is callback-specific.
  533. """
  534. data = read(size)
  535. # maintain a trailer of the last 20 bytes we've read
  536. n = len(data)
  537. self._offset += n
  538. tn = len(self._trailer)
  539. if n >= 20:
  540. to_pop = tn
  541. to_add = 20
  542. else:
  543. to_pop = max(n + tn - 20, 0)
  544. to_add = n
  545. for _ in xrange(to_pop):
  546. self.sha.update(self._trailer.popleft())
  547. self._trailer.extend(data[-to_add:])
  548. # hash everything but the trailer
  549. self.sha.update(data[:-to_add])
  550. return data
  551. def _buf_len(self):
  552. buf = self._rbuf
  553. start = buf.tell()
  554. buf.seek(0, SEEK_END)
  555. end = buf.tell()
  556. buf.seek(start)
  557. return end - start
  558. @property
  559. def offset(self):
  560. return self._offset - self._buf_len()
  561. def read(self, size):
  562. """Read, blocking until size bytes are read."""
  563. buf_len = self._buf_len()
  564. if buf_len >= size:
  565. return self._rbuf.read(size)
  566. buf_data = self._rbuf.read()
  567. self._rbuf = StringIO()
  568. return buf_data + self._read(self.read_all, size - buf_len)
  569. def recv(self, size):
  570. """Read up to size bytes, blocking until one byte is read."""
  571. buf_len = self._buf_len()
  572. if buf_len:
  573. data = self._rbuf.read(size)
  574. if size >= buf_len:
  575. self._rbuf = StringIO()
  576. return data
  577. return self._read(self.read_some, size)
  578. def __len__(self):
  579. return self._num_objects
  580. def read_objects(self, compute_crc32=False):
  581. """Read the objects in this pack file.
  582. :param compute_crc32: If True, compute the CRC32 of the compressed
  583. data. If False, the returned CRC32 will be None.
  584. :return: Iterator over tuples of (
  585. offset,
  586. type number,
  587. list of uncompressed chunks,
  588. length of compressed data,
  589. crc32 of compressed data,
  590. ).
  591. :raise AssertionError: if there is an error in the pack format.
  592. :raise ChecksumMismatch: if the checksum of the pack contents does not
  593. match the checksum in the pack trailer.
  594. :raise zlib.error: if an error occurred during zlib decompression.
  595. :raise IOError: if an error occurred writing to the output file.
  596. """
  597. pack_version, self._num_objects = read_pack_header(self.read)
  598. for i in xrange(self._num_objects):
  599. offset = self.offset
  600. type_num, uncomp, comp_len, crc32, unused = unpack_object(
  601. self.read, read_some=self.recv, compute_crc32=compute_crc32)
  602. yield offset, type_num, uncomp, comp_len, crc32
  603. # prepend any unused data to current read buffer
  604. buf = StringIO()
  605. buf.write(unused)
  606. buf.write(self._rbuf.read())
  607. buf.seek(0)
  608. self._rbuf = buf
  609. pack_sha = ''.join(self._trailer)
  610. if pack_sha != self.sha.digest():
  611. raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest())
  612. def obj_sha(type, chunks):
  613. """Compute the SHA for a numeric type and object chunks."""
  614. sha = make_sha()
  615. sha.update(object_header(type, chunks_length(chunks)))
  616. for chunk in chunks:
  617. sha.update(chunk)
  618. return sha.digest()
  619. class PackData(object):
  620. """The data contained in a packfile.
  621. Pack files can be accessed both sequentially for exploding a pack, and
  622. directly with the help of an index to retrieve a specific object.
  623. The objects within are either complete or a delta aginst another.
  624. The header is variable length. If the MSB of each byte is set then it
  625. indicates that the subsequent byte is still part of the header.
  626. For the first byte the next MS bits are the type, which tells you the type
  627. of object, and whether it is a delta. The LS byte is the lowest bits of the
  628. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  629. size, i.e. the last byte of the header contains the MS bits of the size.
  630. For the complete objects the data is stored as zlib deflated data.
  631. The size in the header is the uncompressed object size, so to uncompress
  632. you need to just keep feeding data to zlib until you get an object back,
  633. or it errors on bad data. This is done here by just giving the complete
  634. buffer from the start of the deflated object on. This is bad, but until I
  635. get mmap sorted out it will have to do.
  636. Currently there are no integrity checks done. Also no attempt is made to
  637. try and detect the delta case, or a request for an object at the wrong
  638. position. It will all just throw a zlib or KeyError.
  639. """
  640. def __init__(self, filename, file=None, size=None):
  641. """Create a PackData object representing the pack in the given filename.
  642. The file must exist and stay readable until the object is disposed of. It
  643. must also stay the same size. It will be mapped whenever needed.
  644. Currently there is a restriction on the size of the pack as the python
  645. mmap implementation is flawed.
  646. """
  647. self._filename = filename
  648. self._size = size
  649. self._header_size = 12
  650. if file is None:
  651. self._file = GitFile(self._filename, 'rb')
  652. else:
  653. self._file = file
  654. (version, self._num_objects) = read_pack_header(self._file.read)
  655. self._offset_cache = LRUSizeCache(1024*1024*20,
  656. compute_size=_compute_object_size)
  657. self.pack = None
  658. @classmethod
  659. def from_file(cls, file, size):
  660. return cls(str(file), file=file, size=size)
  661. @classmethod
  662. def from_path(cls, path):
  663. return cls(filename=path)
  664. def close(self):
  665. self._file.close()
  666. def _get_size(self):
  667. if self._size is not None:
  668. return self._size
  669. self._size = os.path.getsize(self._filename)
  670. if self._size < self._header_size:
  671. errmsg = ('%s is too small for a packfile (%d < %d)' %
  672. (self._filename, self._size, self._header_size))
  673. raise AssertionError(errmsg)
  674. return self._size
  675. def __len__(self):
  676. """Returns the number of objects in this pack."""
  677. return self._num_objects
  678. def calculate_checksum(self):
  679. """Calculate the checksum for this pack.
  680. :return: 20-byte binary SHA1 digest
  681. """
  682. s = make_sha()
  683. self._file.seek(0)
  684. todo = self._get_size() - 20
  685. while todo > 0:
  686. x = self._file.read(min(todo, 1<<16))
  687. s.update(x)
  688. todo -= len(x)
  689. return s.digest()
  690. def get_ref(self, sha):
  691. """Get the object for a ref SHA, only looking in this pack."""
  692. # TODO: cache these results
  693. if self.pack is None:
  694. raise KeyError(sha)
  695. offset = self.pack.index.object_index(sha)
  696. if not offset:
  697. raise KeyError(sha)
  698. type, obj = self.get_object_at(offset)
  699. return offset, type, obj
  700. def resolve_object(self, offset, type, obj, get_ref=None):
  701. """Resolve an object, possibly resolving deltas when necessary.
  702. :return: Tuple with object type and contents.
  703. """
  704. if type not in DELTA_TYPES:
  705. return type, obj
  706. if get_ref is None:
  707. get_ref = self.get_ref
  708. if type == OFS_DELTA:
  709. (delta_offset, delta) = obj
  710. # TODO: clean up asserts and replace with nicer error messages
  711. assert isinstance(offset, int)
  712. assert isinstance(delta_offset, int)
  713. base_offset = offset-delta_offset
  714. type, base_obj = self.get_object_at(base_offset)
  715. assert isinstance(type, int)
  716. elif type == REF_DELTA:
  717. (basename, delta) = obj
  718. assert isinstance(basename, str) and len(basename) == 20
  719. base_offset, type, base_obj = get_ref(basename)
  720. assert isinstance(type, int)
  721. type, base_chunks = self.resolve_object(base_offset, type, base_obj)
  722. chunks = apply_delta(base_chunks, delta)
  723. # TODO(dborowitz): This can result in poor performance if large base
  724. # objects are separated from deltas in the pack. We should reorganize
  725. # so that we apply deltas to all objects in a chain one after the other
  726. # to optimize cache performance.
  727. if offset is not None:
  728. self._offset_cache[offset] = type, chunks
  729. return type, chunks
  730. def iterobjects(self, progress=None, compute_crc32=True):
  731. offset = self._header_size
  732. for i in xrange(1, self._num_objects + 1):
  733. self._file.seek(offset) # Back up over unused data.
  734. type_num, obj, total_size, crc32, unused = unpack_object(
  735. self._file.read, compute_crc32=compute_crc32)
  736. if progress is not None:
  737. progress(i, self._num_objects)
  738. yield offset, type_num, obj, crc32
  739. offset += total_size
  740. def iterentries(self, progress=None):
  741. """Yield entries summarizing the contents of this pack.
  742. :param progress: Progress function, called with current and total
  743. object count.
  744. :return: iterator of tuples with (sha, offset, crc32)
  745. """
  746. num_objects = self._num_objects
  747. for i, result in enumerate(PackIndexer.for_pack_data(self)):
  748. if progress is not None:
  749. progress(i, num_objects)
  750. yield result
  751. def sorted_entries(self, progress=None):
  752. """Return entries in this pack, sorted by SHA.
  753. :param progress: Progress function, called with current and total
  754. object count
  755. :return: List of tuples with (sha, offset, crc32)
  756. """
  757. ret = list(self.iterentries(progress=progress))
  758. ret.sort()
  759. return ret
  760. def create_index_v1(self, filename, progress=None):
  761. """Create a version 1 file for this data file.
  762. :param filename: Index filename.
  763. :param progress: Progress report function
  764. :return: Checksum of index file
  765. """
  766. entries = self.sorted_entries(progress=progress)
  767. f = GitFile(filename, 'wb')
  768. try:
  769. return write_pack_index_v1(f, entries, self.calculate_checksum())
  770. finally:
  771. f.close()
  772. def create_index_v2(self, filename, progress=None):
  773. """Create a version 2 index file for this data file.
  774. :param filename: Index filename.
  775. :param progress: Progress report function
  776. :return: Checksum of index file
  777. """
  778. entries = self.sorted_entries(progress=progress)
  779. f = GitFile(filename, 'wb')
  780. try:
  781. return write_pack_index_v2(f, entries, self.calculate_checksum())
  782. finally:
  783. f.close()
  784. def create_index(self, filename, progress=None,
  785. version=2):
  786. """Create an index file for this data file.
  787. :param filename: Index filename.
  788. :param progress: Progress report function
  789. :return: Checksum of index file
  790. """
  791. if version == 1:
  792. return self.create_index_v1(filename, progress)
  793. elif version == 2:
  794. return self.create_index_v2(filename, progress)
  795. else:
  796. raise ValueError('unknown index format %d' % version)
  797. def get_stored_checksum(self):
  798. """Return the expected checksum stored in this pack."""
  799. self._file.seek(self._get_size()-20)
  800. return self._file.read(20)
  801. def check(self):
  802. """Check the consistency of this pack."""
  803. actual = self.calculate_checksum()
  804. stored = self.get_stored_checksum()
  805. if actual != stored:
  806. raise ChecksumMismatch(stored, actual)
  807. def get_object_at(self, offset):
  808. """Given an offset in to the packfile return the object that is there.
  809. Using the associated index the location of an object can be looked up,
  810. and then the packfile can be asked directly for that object using this
  811. function.
  812. """
  813. if offset in self._offset_cache:
  814. return self._offset_cache[offset]
  815. assert isinstance(offset, long) or isinstance(offset, int),\
  816. 'offset was %r' % offset
  817. assert offset >= self._header_size
  818. self._file.seek(offset)
  819. return unpack_object(self._file.read)[:2]
  820. class ThinPackData(PackData):
  821. """PackData for thin packs, which require an ObjectStore for resolving."""
  822. def __init__(self, resolve_ext_ref, *args, **kwargs):
  823. super(ThinPackData, self).__init__(*args, **kwargs)
  824. self.resolve_ext_ref = resolve_ext_ref
  825. @classmethod
  826. def from_file(cls, resolve_ext_ref, file, size):
  827. return cls(resolve_ext_ref, str(file), file=file, size=size)
  828. def get_ref(self, sha):
  829. """Resolve a reference looking in both this pack and the store."""
  830. try:
  831. # As part of completing a pack we create a Pack object with a
  832. # ThinPackData and a full PackIndex, so check in the index first if
  833. # possible.
  834. # TODO(dborowitz): reevaluate this when the pack completion code is
  835. # rewritten.
  836. return super(ThinPackData, self).get_ref(sha)
  837. except KeyError:
  838. type, obj = self.resolve_ext_ref(sha)
  839. return None, type, obj
  840. def iterentries(self, progress=None):
  841. """Yield entries summarizing the contents of this pack.
  842. :param progress: Progress function, called with current and
  843. total object count.
  844. This will yield tuples with (sha, offset, crc32)
  845. """
  846. found = {}
  847. postponed = defaultdict(list)
  848. class Postpone(Exception):
  849. """Raised to postpone delta resolving."""
  850. def __init__(self, sha):
  851. self.sha = sha
  852. def get_ref_text(sha):
  853. assert len(sha) == 20
  854. if sha in found:
  855. offset = found[sha]
  856. type, obj = self.get_object_at(offset)
  857. return offset, type, obj
  858. try:
  859. return self.get_ref(sha)
  860. except KeyError:
  861. raise Postpone(sha)
  862. extra = []
  863. todo = chain(self.iterobjects(progress=progress), extra)
  864. for (offset, type, obj, crc32) in todo:
  865. assert isinstance(offset, int)
  866. if obj is None:
  867. # Inflate postponed delta
  868. obj, type = self.get_object_at(offset)
  869. assert isinstance(type, int)
  870. assert isinstance(obj, list) or isinstance(obj, tuple)
  871. try:
  872. type, obj = self.resolve_object(offset, type, obj, get_ref_text)
  873. except Postpone, e:
  874. # Save memory by not storing the inflated obj in postponed
  875. postponed[e.sha].append((offset, type, None, crc32))
  876. else:
  877. sha = obj_sha(type, obj)
  878. found[sha] = offset
  879. yield sha, offset, crc32
  880. extra.extend(postponed.pop(sha, []))
  881. if postponed:
  882. raise KeyError([sha_to_hex(h) for h in postponed.keys()])
  883. class DeltaChainIterator(object):
  884. """Abstract iterator over pack data based on delta chains.
  885. Each object in the pack is guaranteed to be inflated exactly once,
  886. regardless of how many objects reference it as a delta base. As a result,
  887. memory usage is proportional to the length of the longest delta chain.
  888. Subclasses override _result to define the result type of the iterator.
  889. """
  890. _compute_crc32 = False
  891. def __init__(self, file_obj, resolve_ext_ref=None):
  892. self._file = file_obj
  893. self._resolve_ext_ref = resolve_ext_ref
  894. self._pending_ofs = defaultdict(list)
  895. self._pending_ref = defaultdict(list)
  896. self._full_ofs = []
  897. self._shas = {}
  898. self._ext_refs = []
  899. @classmethod
  900. def for_pack_data(cls, pack_data):
  901. walker = cls(None)
  902. walker.set_pack_data(pack_data)
  903. for offset, type_num, obj, _ in pack_data.iterobjects():
  904. walker.record(offset, type_num, obj)
  905. return walker
  906. def record(self, offset, type_num, uncomp):
  907. if type_num == OFS_DELTA:
  908. delta_offset, _ = uncomp
  909. base_offset = offset - delta_offset
  910. self._pending_ofs[base_offset].append(offset)
  911. elif type_num == REF_DELTA:
  912. base_sha, _ = uncomp
  913. self._pending_ref[base_sha].append(offset)
  914. else:
  915. self._full_ofs.append((offset, type_num))
  916. def set_pack_data(self, pack_data):
  917. self._file = pack_data._file
  918. if isinstance(pack_data, ThinPackData):
  919. self._resolve_ext_ref = pack_data.resolve_ext_ref
  920. def _walk_all_chains(self):
  921. for offset, type_num in self._full_ofs:
  922. for result in self._follow_chain(offset, type_num, None):
  923. yield result
  924. for result in self._walk_ref_chains():
  925. yield result
  926. assert not self._pending_ofs
  927. def _ensure_no_pending(self):
  928. if self._pending_ref:
  929. raise KeyError([sha_to_hex(s) for s in self._pending_ref])
  930. def _walk_ref_chains(self):
  931. if not self._resolve_ext_ref:
  932. self._ensure_no_pending()
  933. return
  934. for base_sha, pending in sorted(self._pending_ref.iteritems()):
  935. try:
  936. type_num, chunks = self._resolve_ext_ref(base_sha)
  937. except KeyError:
  938. # Not an external ref, but may depend on one. Either it will get
  939. # popped via a _follow_chain call, or we will raise an error
  940. # below.
  941. continue
  942. self._ext_refs.append(base_sha)
  943. self._pending_ref.pop(base_sha)
  944. for new_offset in pending:
  945. for result in self._follow_chain(new_offset, type_num, chunks):
  946. yield result
  947. self._ensure_no_pending()
  948. def _result(self, offset, type_num, chunks, sha, crc32):
  949. raise NotImplementedError
  950. def _resolve_object(self, offset, base_type_num, base_chunks):
  951. self._file.seek(offset)
  952. type_num, obj, _, crc32, _ = unpack_object(
  953. self._file.read, compute_crc32=self._compute_crc32)
  954. if base_chunks is None:
  955. assert type_num == base_type_num
  956. chunks = obj
  957. else:
  958. assert type_num in DELTA_TYPES
  959. _, delta_chunks = obj
  960. chunks = apply_delta(base_chunks, delta_chunks)
  961. sha = obj_sha(base_type_num, chunks)
  962. return chunks, sha, crc32
  963. def _follow_chain(self, offset, base_type_num, base_chunks):
  964. # Unlike PackData.get_object_at, there is no need to cache offsets as
  965. # this approach by design inflates each object exactly once.
  966. chunks, sha, crc32 = self._resolve_object(offset, base_type_num,
  967. base_chunks)
  968. yield self._result(offset, base_type_num, chunks, sha, crc32)
  969. pending = chain(self._pending_ofs.pop(offset, []),
  970. self._pending_ref.pop(sha, []))
  971. for new_offset in pending:
  972. for result in self._follow_chain(new_offset, base_type_num, chunks):
  973. yield result
  974. def __iter__(self):
  975. return self._walk_all_chains()
  976. def ext_refs(self):
  977. return self._ext_refs
  978. class PackIndexer(DeltaChainIterator):
  979. """Delta chain iterator that yields index entries."""
  980. _compute_crc32 = True
  981. def _result(self, offset, unused_type_num, unused_chunks, sha, crc32):
  982. return sha, offset, crc32
  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. assert len(self.index) == len(self._data)
  1360. idx_stored_checksum = self.index.get_pack_checksum()
  1361. data_stored_checksum = self._data.get_stored_checksum()
  1362. if idx_stored_checksum != data_stored_checksum:
  1363. raise ChecksumMismatch(sha_to_hex(idx_stored_checksum),
  1364. sha_to_hex(data_stored_checksum))
  1365. return self._data
  1366. @property
  1367. def index(self):
  1368. """The index being used.
  1369. :note: This may be an in-memory index
  1370. """
  1371. if self._idx is None:
  1372. self._idx = self._idx_load()
  1373. return self._idx
  1374. def close(self):
  1375. if self._data is not None:
  1376. self._data.close()
  1377. self.index.close()
  1378. def __eq__(self, other):
  1379. return type(self) == type(other) and self.index == other.index
  1380. def __len__(self):
  1381. """Number of entries in this pack."""
  1382. return len(self.index)
  1383. def __repr__(self):
  1384. return '%s(%r)' % (self.__class__.__name__, self._basename)
  1385. def __iter__(self):
  1386. """Iterate over all the sha1s of the objects in this pack."""
  1387. return iter(self.index)
  1388. def check(self):
  1389. """Check the integrity of this pack.
  1390. :raise ChecksumMismatch: if a checksum for the index or data is wrong
  1391. """
  1392. self.index.check()
  1393. self.data.check()
  1394. for obj in self.iterobjects():
  1395. obj.check()
  1396. # TODO: object connectivity checks
  1397. def get_stored_checksum(self):
  1398. return self.data.get_stored_checksum()
  1399. def __contains__(self, sha1):
  1400. """Check whether this pack contains a particular SHA1."""
  1401. try:
  1402. self.index.object_index(sha1)
  1403. return True
  1404. except KeyError:
  1405. return False
  1406. def get_raw(self, sha1):
  1407. offset = self.index.object_index(sha1)
  1408. obj_type, obj = self.data.get_object_at(offset)
  1409. if type(offset) is long:
  1410. offset = int(offset)
  1411. type_num, chunks = self.data.resolve_object(offset, obj_type, obj)
  1412. return type_num, ''.join(chunks)
  1413. def __getitem__(self, sha1):
  1414. """Retrieve the specified SHA1."""
  1415. type, uncomp = self.get_raw(sha1)
  1416. return ShaFile.from_raw_string(type, uncomp)
  1417. def iterobjects(self):
  1418. """Iterate over the objects in this pack."""
  1419. for offset, type, obj, crc32 in self.data.iterobjects():
  1420. assert isinstance(offset, int)
  1421. yield ShaFile.from_raw_chunks(
  1422. *self.data.resolve_object(offset, type, obj))
  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