pack.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. # pack.py -- For dealing wih packed git objects.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copryight (C) 2008 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 misc import defaultdict
  32. from itertools import imap, izip
  33. import mmap
  34. import os
  35. import struct
  36. try:
  37. from struct import unpack_from
  38. except ImportError:
  39. from dulwich.misc import unpack_from
  40. import sys
  41. import zlib
  42. import difflib
  43. from dulwich.objects import (
  44. ShaFile,
  45. hex_to_sha,
  46. sha_to_hex,
  47. )
  48. from dulwich.errors import ApplyDeltaError
  49. from dulwich.misc import make_sha
  50. supports_mmap_offset = (sys.version_info[0] >= 3 or
  51. (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
  52. def take_msb_bytes(map, offset):
  53. ret = []
  54. while len(ret) == 0 or ret[-1] & 0x80:
  55. ret.append(ord(map[offset]))
  56. offset += 1
  57. return ret
  58. def read_zlib(data, offset, dec_size):
  59. obj = zlib.decompressobj()
  60. x = ""
  61. fed = 0
  62. while obj.unused_data == "":
  63. base = offset+fed
  64. add = data[base:base+1024]
  65. if len(add) < 1024:
  66. add += "Z"
  67. fed += len(add)
  68. x += obj.decompress(add)
  69. assert len(x) == dec_size
  70. comp_len = fed-len(obj.unused_data)
  71. return x, comp_len
  72. def iter_sha1(iter):
  73. sha1 = make_sha()
  74. for name in iter:
  75. sha1.update(name)
  76. return sha1.hexdigest()
  77. MAX_MMAP_SIZE = 256 * 1024 * 1024
  78. def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
  79. """Simple wrapper for mmap() which always supports the offset parameter.
  80. :param f: File object.
  81. :param offset: Offset in the file, from the beginning of the file.
  82. :param size: Size of the mmap'ed area
  83. :param access: Access mechanism.
  84. :return: MMAP'd area.
  85. """
  86. if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
  87. raise AssertionError("%s is larger than 256 meg, and this version "
  88. "of Python does not support the offset argument to mmap().")
  89. if supports_mmap_offset:
  90. return mmap.mmap(f.fileno(), size, access=access, offset=offset)
  91. else:
  92. class ArraySkipper(object):
  93. def __init__(self, array, offset):
  94. self.array = array
  95. self.offset = offset
  96. def __getslice__(self, i, j):
  97. return self.array[i+self.offset:j+self.offset]
  98. def __getitem__(self, i):
  99. return self.array[i+self.offset]
  100. def __len__(self):
  101. return len(self.array) - self.offset
  102. def __str__(self):
  103. return str(self.array[self.offset:])
  104. mem = mmap.mmap(f.fileno(), size+offset, access=access)
  105. if offset == 0:
  106. return mem
  107. return ArraySkipper(mem, offset)
  108. def resolve_object(offset, type, obj, get_ref, get_offset):
  109. """Resolve an object, possibly resolving deltas when necessary."""
  110. if not type in (6, 7): # Not a delta
  111. return type, obj
  112. if type == 6: # offset delta
  113. (delta_offset, delta) = obj
  114. assert isinstance(delta_offset, int)
  115. assert isinstance(delta, str)
  116. offset = offset-delta_offset
  117. type, base_obj = get_offset(offset)
  118. assert isinstance(type, int)
  119. elif type == 7: # ref delta
  120. (basename, delta) = obj
  121. assert isinstance(basename, str) and len(basename) == 20
  122. assert isinstance(delta, str)
  123. type, base_obj = get_ref(basename)
  124. assert isinstance(type, int)
  125. type, base_text = resolve_object(offset, type, base_obj, get_ref, get_offset)
  126. return type, apply_delta(base_text, delta)
  127. class PackIndex(object):
  128. """An index in to a packfile.
  129. Given a sha id of an object a pack index can tell you the location in the
  130. packfile of that object if it has it.
  131. To do the loop it opens the file, and indexes first 256 4 byte groups
  132. with the first byte of the sha id. The value in the four byte group indexed
  133. is the end of the group that shares the same starting byte. Subtract one
  134. from the starting byte and index again to find the start of the group.
  135. The values are sorted by sha id within the group, so do the math to find
  136. the start and end offset and then bisect in to find if the value is present.
  137. """
  138. def __init__(self, filename):
  139. """Create a pack index object.
  140. Provide it with the name of the index file to consider, and it will map
  141. it whenever required.
  142. """
  143. self._filename = filename
  144. # Take the size now, so it can be checked each time we map the file to
  145. # ensure that it hasn't changed.
  146. self._size = os.path.getsize(filename)
  147. self._file = open(filename, 'r')
  148. self._contents = simple_mmap(self._file, 0, self._size)
  149. if self._contents[:4] != '\377tOc':
  150. self.version = 1
  151. self._fan_out_table = self._read_fan_out_table(0)
  152. else:
  153. (self.version, ) = unpack_from(">L", self._contents, 4)
  154. assert self.version in (2,), "Version was %d" % self.version
  155. self._fan_out_table = self._read_fan_out_table(8)
  156. self._name_table_offset = 8 + 0x100 * 4
  157. self._crc32_table_offset = self._name_table_offset + 20 * len(self)
  158. self._pack_offset_table_offset = self._crc32_table_offset + 4 * len(self)
  159. def __eq__(self, other):
  160. if type(self) != type(other):
  161. return False
  162. if self._fan_out_table != other._fan_out_table:
  163. return False
  164. for (name1, _, _), (name2, _, _) in izip(self.iterentries(), other.iterentries()):
  165. if name1 != name2:
  166. return False
  167. return True
  168. def close(self):
  169. self._file.close()
  170. def __len__(self):
  171. """Return the number of entries in this pack index."""
  172. return self._fan_out_table[-1]
  173. def _unpack_entry(self, i):
  174. """Unpack the i-th entry in the index file.
  175. :return: Tuple with object name (SHA), offset in pack file and
  176. CRC32 checksum (if known)."""
  177. if self.version == 1:
  178. (offset, name) = unpack_from(">L20s", self._contents,
  179. (0x100 * 4) + (i * 24))
  180. return (name, offset, None)
  181. else:
  182. return (self._unpack_name(i), self._unpack_offset(i),
  183. self._unpack_crc32_checksum(i))
  184. def _unpack_name(self, i):
  185. if self.version == 1:
  186. return self._unpack_entry(i)[0]
  187. else:
  188. return unpack_from("20s", self._contents,
  189. self._name_table_offset + i * 20)[0]
  190. def _unpack_offset(self, i):
  191. if self.version == 1:
  192. return self._unpack_entry(i)[1]
  193. else:
  194. return unpack_from(">L", self._contents,
  195. self._pack_offset_table_offset + i * 4)[0]
  196. def _unpack_crc32_checksum(self, i):
  197. if self.version == 1:
  198. return None
  199. else:
  200. return unpack_from(">L", self._contents,
  201. self._crc32_table_offset + i * 4)[0]
  202. def __iter__(self):
  203. return imap(sha_to_hex, self._itersha())
  204. def _itersha(self):
  205. for i in range(len(self)):
  206. yield self._unpack_name(i)
  207. def objects_sha1(self):
  208. return iter_sha1(self._itersha())
  209. def iterentries(self):
  210. """Iterate over the entries in this pack index.
  211. Will yield tuples with object name, offset in packfile and crc32 checksum.
  212. """
  213. for i in range(len(self)):
  214. yield self._unpack_entry(i)
  215. def _read_fan_out_table(self, start_offset):
  216. ret = []
  217. for i in range(0x100):
  218. ret.append(struct.unpack(">L", self._contents[start_offset+i*4:start_offset+(i+1)*4])[0])
  219. return ret
  220. def check(self):
  221. """Check that the stored checksum matches the actual checksum."""
  222. return self.calculate_checksum() == self.get_stored_checksums()[1]
  223. def calculate_checksum(self):
  224. f = open(self._filename, 'r')
  225. try:
  226. return make_sha(self._contents[:-20]).digest()
  227. finally:
  228. f.close()
  229. def get_stored_checksums(self):
  230. """Return the SHA1 checksums stored for the corresponding packfile and
  231. this header file itself."""
  232. return str(self._contents[-40:-20]), str(self._contents[-20:])
  233. def object_index(self, sha):
  234. """Return the index in to the corresponding packfile for the object.
  235. Given the name of an object it will return the offset that object lives
  236. at within the corresponding pack file. If the pack file doesn't have the
  237. object then None will be returned.
  238. """
  239. size = os.path.getsize(self._filename)
  240. assert size == self._size, "Pack index %s has changed size, I don't " \
  241. "like that" % self._filename
  242. if len(sha) == 40:
  243. sha = hex_to_sha(sha)
  244. return self._object_index(sha)
  245. def _object_index(self, sha):
  246. """See object_index"""
  247. idx = ord(sha[0])
  248. if idx == 0:
  249. start = 0
  250. else:
  251. start = self._fan_out_table[idx-1]
  252. end = self._fan_out_table[idx]
  253. assert start <= end
  254. while start <= end:
  255. i = (start + end)/2
  256. file_sha = self._unpack_name(i)
  257. if file_sha < sha:
  258. start = i + 1
  259. elif file_sha > sha:
  260. end = i - 1
  261. else:
  262. return self._unpack_offset(i)
  263. return None
  264. def read_pack_header(f):
  265. header = f.read(12)
  266. assert header[:4] == "PACK"
  267. (version,) = unpack_from(">L", header, 4)
  268. assert version in (2, 3), "Version was %d" % version
  269. (num_objects,) = unpack_from(">L", header, 8)
  270. return (version, num_objects)
  271. def read_pack_tail(f):
  272. return (f.read(20),)
  273. def unpack_object(map):
  274. bytes = take_msb_bytes(map, 0)
  275. type = (bytes[0] >> 4) & 0x07
  276. size = bytes[0] & 0x0f
  277. for i, byte in enumerate(bytes[1:]):
  278. size += (byte & 0x7f) << ((i * 7) + 4)
  279. raw_base = len(bytes)
  280. if type == 6: # offset delta
  281. bytes = take_msb_bytes(map, raw_base)
  282. assert not (bytes[-1] & 0x80)
  283. delta_base_offset = bytes[0] & 0x7f
  284. for byte in bytes[1:]:
  285. delta_base_offset += 1
  286. delta_base_offset <<= 7
  287. delta_base_offset += (byte & 0x7f)
  288. raw_base+=len(bytes)
  289. uncomp, comp_len = read_zlib(map, raw_base, size)
  290. assert size == len(uncomp)
  291. return type, (delta_base_offset, uncomp), comp_len+raw_base
  292. elif type == 7: # ref delta
  293. basename = map[raw_base:raw_base+20]
  294. uncomp, comp_len = read_zlib(map, raw_base+20, size)
  295. assert size == len(uncomp)
  296. return type, (basename, uncomp), comp_len+raw_base+20
  297. else:
  298. uncomp, comp_len = read_zlib(map, raw_base, size)
  299. assert len(uncomp) == size
  300. return type, uncomp, comp_len+raw_base
  301. class PackData(object):
  302. """The data contained in a packfile.
  303. Pack files can be accessed both sequentially for exploding a pack, and
  304. directly with the help of an index to retrieve a specific object.
  305. The objects within are either complete or a delta aginst another.
  306. The header is variable length. If the MSB of each byte is set then it
  307. indicates that the subsequent byte is still part of the header.
  308. For the first byte the next MS bits are the type, which tells you the type
  309. of object, and whether it is a delta. The LS byte is the lowest bits of the
  310. size. For each subsequent byte the LS 7 bits are the next MS bits of the
  311. size, i.e. the last byte of the header contains the MS bits of the size.
  312. For the complete objects the data is stored as zlib deflated data.
  313. The size in the header is the uncompressed object size, so to uncompress
  314. you need to just keep feeding data to zlib until you get an object back,
  315. or it errors on bad data. This is done here by just giving the complete
  316. buffer from the start of the deflated object on. This is bad, but until I
  317. get mmap sorted out it will have to do.
  318. Currently there are no integrity checks done. Also no attempt is made to try
  319. and detect the delta case, or a request for an object at the wrong position.
  320. It will all just throw a zlib or KeyError.
  321. """
  322. def __init__(self, filename):
  323. """Create a PackData object that represents the pack in the given filename.
  324. The file must exist and stay readable until the object is disposed of. It
  325. must also stay the same size. It will be mapped whenever needed.
  326. Currently there is a restriction on the size of the pack as the python
  327. mmap implementation is flawed.
  328. """
  329. self._filename = filename
  330. assert os.path.exists(filename), "%s is not a packfile" % filename
  331. self._size = os.path.getsize(filename)
  332. self._header_size = 12
  333. assert self._size >= self._header_size, "%s is too small for a packfile (%d < %d)" % (filename, self._size, self._header_size)
  334. self._read_header()
  335. def _read_header(self):
  336. f = open(self._filename, 'rb')
  337. try:
  338. (version, self._num_objects) = \
  339. read_pack_header(f)
  340. f.seek(self._size-20)
  341. (self._stored_checksum,) = read_pack_tail(f)
  342. finally:
  343. f.close()
  344. def __len__(self):
  345. """Returns the number of objects in this pack."""
  346. return self._num_objects
  347. def calculate_checksum(self):
  348. """Calculate the checksum for this pack."""
  349. f = open(self._filename, 'rb')
  350. try:
  351. map = simple_mmap(f, 0, self._size)
  352. return make_sha(map[:-20]).digest()
  353. finally:
  354. f.close()
  355. def iterobjects(self):
  356. offset = self._header_size
  357. f = open(self._filename, 'rb')
  358. for i in range(len(self)):
  359. map = simple_mmap(f, offset, self._size-offset)
  360. (type, obj, total_size) = unpack_object(map)
  361. yield offset, type, obj
  362. offset += total_size
  363. f.close()
  364. def iterentries(self, ext_resolve_ref=None):
  365. found = {}
  366. at = {}
  367. postponed = defaultdict(list)
  368. class Postpone(Exception):
  369. """Raised to postpone delta resolving."""
  370. def get_ref_text(sha):
  371. if sha in found:
  372. return found[sha]
  373. if ext_resolve_ref:
  374. try:
  375. return ext_resolve_ref(sha)
  376. except KeyError:
  377. pass
  378. raise Postpone, (sha, )
  379. todo = list(self.iterobjects())
  380. while todo:
  381. (offset, type, obj) = todo.pop(0)
  382. at[offset] = (type, obj)
  383. assert isinstance(offset, int)
  384. assert isinstance(type, int)
  385. assert isinstance(obj, tuple) or isinstance(obj, str)
  386. try:
  387. type, obj = resolve_object(offset, type, obj, get_ref_text,
  388. at.__getitem__)
  389. except Postpone, (sha, ):
  390. postponed[sha].append((offset, type, obj))
  391. else:
  392. shafile = ShaFile.from_raw_string(type, obj)
  393. sha = shafile.sha().digest()
  394. found[sha] = (type, obj)
  395. yield sha, offset, shafile.crc32()
  396. todo += postponed.get(sha, [])
  397. if postponed:
  398. raise KeyError([sha_to_hex(h) for h in postponed.keys()])
  399. def sorted_entries(self, resolve_ext_ref=None):
  400. ret = list(self.iterentries(resolve_ext_ref))
  401. ret.sort()
  402. return ret
  403. def create_index_v1(self, filename, resolve_ext_ref=None):
  404. entries = self.sorted_entries(resolve_ext_ref)
  405. write_pack_index_v1(filename, entries, self.calculate_checksum())
  406. def create_index_v2(self, filename, resolve_ext_ref=None):
  407. entries = self.sorted_entries(resolve_ext_ref)
  408. write_pack_index_v2(filename, entries, self.calculate_checksum())
  409. def get_stored_checksum(self):
  410. return self._stored_checksum
  411. def check(self):
  412. return (self.calculate_checksum() == self.get_stored_checksum())
  413. def get_object_at(self, offset):
  414. """Given an offset in to the packfile return the object that is there.
  415. Using the associated index the location of an object can be looked up, and
  416. then the packfile can be asked directly for that object using this
  417. function.
  418. """
  419. assert isinstance(offset, long) or isinstance(offset, int),\
  420. "offset was %r" % offset
  421. assert offset >= self._header_size
  422. size = os.path.getsize(self._filename)
  423. assert size == self._size, "Pack data %s has changed size, I don't " \
  424. "like that" % self._filename
  425. f = open(self._filename, 'rb')
  426. try:
  427. map = simple_mmap(f, offset, size-offset)
  428. return unpack_object(map)[:2]
  429. finally:
  430. f.close()
  431. class SHA1Writer(object):
  432. def __init__(self, f):
  433. self.f = f
  434. self.sha1 = make_sha("")
  435. def write(self, data):
  436. self.sha1.update(data)
  437. self.f.write(data)
  438. def write_sha(self):
  439. sha = self.sha1.digest()
  440. assert len(sha) == 20
  441. self.f.write(sha)
  442. return sha
  443. def close(self):
  444. sha = self.write_sha()
  445. self.f.close()
  446. return sha
  447. def tell(self):
  448. return self.f.tell()
  449. def write_pack_object(f, type, object):
  450. """Write pack object to a file.
  451. :param f: File to write to
  452. :param o: Object to write
  453. """
  454. ret = f.tell()
  455. if type == 6: # ref delta
  456. (delta_base_offset, object) = object
  457. elif type == 7: # offset delta
  458. (basename, object) = object
  459. size = len(object)
  460. c = (type << 4) | (size & 15)
  461. size >>= 4
  462. while size:
  463. f.write(chr(c | 0x80))
  464. c = size & 0x7f
  465. size >>= 7
  466. f.write(chr(c))
  467. if type == 6: # offset delta
  468. ret = [delta_base_offset & 0x7f]
  469. delta_base_offset >>= 7
  470. while delta_base_offset:
  471. delta_base_offset -= 1
  472. ret.insert(0, 0x80 | (delta_base_offset & 0x7f))
  473. delta_base_offset >>= 7
  474. f.write("".join([chr(x) for x in ret]))
  475. elif type == 7: # ref delta
  476. assert len(basename) == 20
  477. f.write(basename)
  478. f.write(zlib.compress(object))
  479. return f.tell()
  480. def write_pack(filename, objects, num_objects):
  481. f = open(filename + ".pack", 'w')
  482. try:
  483. entries, data_sum = write_pack_data(f, objects, num_objects)
  484. finally:
  485. f.close()
  486. entries.sort()
  487. write_pack_index_v2(filename + ".idx", entries, data_sum)
  488. def write_pack_data(f, objects, num_objects, window=10):
  489. """Write a new pack file.
  490. :param filename: The filename of the new pack file.
  491. :param objects: List of objects to write (tuples with object and path)
  492. :return: List with (name, offset, crc32 checksum) entries, pack checksum
  493. """
  494. recency = list(objects)
  495. # FIXME: Somehow limit delta depth
  496. # FIXME: Make thin-pack optional (its not used when cloning a pack)
  497. # Build a list of objects ordered by the magic Linus heuristic
  498. # This helps us find good objects to diff against us
  499. magic = []
  500. for obj, path in recency:
  501. magic.append( (obj.type, path, 1, -len(obj.as_raw_string()[1]), obj) )
  502. magic.sort()
  503. # Build a map of objects and their index in magic - so we can find preceeding objects
  504. # to diff against
  505. offs = {}
  506. for i in range(len(magic)):
  507. offs[magic[i][4]] = i
  508. # Write the pack
  509. entries = []
  510. f = SHA1Writer(f)
  511. f.write("PACK") # Pack header
  512. f.write(struct.pack(">L", 2)) # Pack version
  513. f.write(struct.pack(">L", num_objects)) # Number of objects in pack
  514. for o, path in recency:
  515. sha1 = o.sha().digest()
  516. crc32 = o.crc32()
  517. orig_t, raw = o.as_raw_string()
  518. winner = raw
  519. t = orig_t
  520. #for i in range(offs[o]-window, window):
  521. # if i < 0 or i >= len(offs): continue
  522. # b = magic[i][4]
  523. # if b.type != orig_t: continue
  524. # _, base = b.as_raw_string()
  525. # delta = create_delta(base, raw)
  526. # if len(delta) < len(winner):
  527. # winner = delta
  528. # t = 6 if magic[i][2] == 1 else 7
  529. offset = write_pack_object(f, t, winner)
  530. entries.append((sha1, offset, crc32))
  531. return entries, f.write_sha()
  532. def write_pack_index_v1(filename, entries, pack_checksum):
  533. """Write a new pack index file.
  534. :param filename: The filename of the new pack index file.
  535. :param entries: List of tuples with object name (sha), offset_in_pack, and
  536. crc32_checksum.
  537. :param pack_checksum: Checksum of the pack file.
  538. """
  539. f = open(filename, 'w')
  540. f = SHA1Writer(f)
  541. fan_out_table = defaultdict(lambda: 0)
  542. for (name, offset, entry_checksum) in entries:
  543. fan_out_table[ord(name[0])] += 1
  544. # Fan-out table
  545. for i in range(0x100):
  546. f.write(struct.pack(">L", fan_out_table[i]))
  547. fan_out_table[i+1] += fan_out_table[i]
  548. for (name, offset, entry_checksum) in entries:
  549. f.write(struct.pack(">L20s", offset, name))
  550. assert len(pack_checksum) == 20
  551. f.write(pack_checksum)
  552. f.close()
  553. def create_delta(base_buf, target_buf):
  554. """Use python difflib to work out how to transform base_buf to target_buf"""
  555. assert isinstance(base_buf, str)
  556. assert isinstance(target_buf, str)
  557. out_buf = ""
  558. # write delta header
  559. def encode_size(size):
  560. ret = ""
  561. c = size & 0x7f
  562. size >>= 7
  563. while size:
  564. ret += chr(c | 0x80)
  565. c = size & 0x7f
  566. size >>= 7
  567. ret += chr(c)
  568. return ret
  569. out_buf += encode_size(len(base_buf))
  570. out_buf += encode_size(len(target_buf))
  571. # write out delta opcodes
  572. seq = difflib.SequenceMatcher(a=base_buf, b=target_buf)
  573. for opcode, i1, i2, j1, j2 in seq.get_opcodes():
  574. # Git patch opcodes don't care about deletes!
  575. #if opcode == "replace" or opcode == "delete":
  576. # pass
  577. if opcode == "equal":
  578. # If they are equal, unpacker will use data from base_buf
  579. # Write out an opcode that says what range to use
  580. scratch = ""
  581. op = 0x80
  582. o = i1
  583. for i in range(4):
  584. if o & 0xff << i*8:
  585. scratch += chr(o >> i)
  586. op |= 1 << i
  587. s = i2 - i1
  588. for i in range(2):
  589. if s & 0xff << i*8:
  590. scratch += chr(s >> i)
  591. op |= 1 << (4+i)
  592. out_buf += chr(op)
  593. out_buf += scratch
  594. if opcode == "replace" or opcode == "insert":
  595. # If we are replacing a range or adding one, then we just
  596. # output it to the stream (prefixed by its size)
  597. s = j2 - j1
  598. o = j1
  599. while s > 127:
  600. out_buf += chr(127)
  601. out_buf += target_buf[o:o+127]
  602. s -= 127
  603. o += 127
  604. out_buf += chr(s)
  605. out_buf += target_buf[o:o+s]
  606. return out_buf
  607. def apply_delta(src_buf, delta):
  608. """Based on the similar function in git's patch-delta.c."""
  609. assert isinstance(src_buf, str), "was %r" % (src_buf,)
  610. assert isinstance(delta, str)
  611. out = []
  612. index = 0
  613. delta_length = len(delta)
  614. def pop(delta, index):
  615. ret = delta[index]
  616. index += 1
  617. return ord(ret), index
  618. def get_delta_header_size(delta, index):
  619. size = 0
  620. i = 0
  621. while delta:
  622. cmd, index = pop(delta, index)
  623. size |= (cmd & ~0x80) << i
  624. i += 7
  625. if not cmd & 0x80:
  626. break
  627. return size, index
  628. src_size, index = get_delta_header_size(delta, index)
  629. dest_size, index = get_delta_header_size(delta, index)
  630. assert src_size == len(src_buf), "%d vs %d" % (src_size, len(src_buf))
  631. while index < delta_length:
  632. cmd, index = pop(delta, index)
  633. if cmd & 0x80:
  634. cp_off = 0
  635. for i in range(4):
  636. if cmd & (1 << i):
  637. x, index = pop(delta, index)
  638. cp_off |= x << (i * 8)
  639. cp_size = 0
  640. for i in range(3):
  641. if cmd & (1 << (4+i)):
  642. x, index = pop(delta, index)
  643. cp_size |= x << (i * 8)
  644. if cp_size == 0:
  645. cp_size = 0x10000
  646. if (cp_off + cp_size < cp_size or
  647. cp_off + cp_size > src_size or
  648. cp_size > dest_size):
  649. break
  650. out.append(src_buf[cp_off:cp_off+cp_size])
  651. elif cmd != 0:
  652. out.append(delta[index:index+cmd])
  653. index += cmd
  654. else:
  655. raise ApplyDeltaError("Invalid opcode 0")
  656. if index != delta_length:
  657. raise ApplyDeltaError("delta not empty: %r" % delta[index:])
  658. out = ''.join(out)
  659. if dest_size != len(out):
  660. raise ApplyDeltaError("dest size incorrect")
  661. return out
  662. def write_pack_index_v2(filename, entries, pack_checksum):
  663. """Write a new pack index file.
  664. :param filename: The filename of the new pack index file.
  665. :param entries: List of tuples with object name (sha), offset_in_pack, and
  666. crc32_checksum.
  667. :param pack_checksum: Checksum of the pack file.
  668. """
  669. f = open(filename, 'w')
  670. f = SHA1Writer(f)
  671. f.write('\377tOc') # Magic!
  672. f.write(struct.pack(">L", 2))
  673. fan_out_table = defaultdict(lambda: 0)
  674. for (name, offset, entry_checksum) in entries:
  675. fan_out_table[ord(name[0])] += 1
  676. # Fan-out table
  677. for i in range(0x100):
  678. f.write(struct.pack(">L", fan_out_table[i]))
  679. fan_out_table[i+1] += fan_out_table[i]
  680. for (name, offset, entry_checksum) in entries:
  681. f.write(name)
  682. for (name, offset, entry_checksum) in entries:
  683. f.write(struct.pack(">L", entry_checksum))
  684. for (name, offset, entry_checksum) in entries:
  685. # FIXME: handle if MSBit is set in offset
  686. f.write(struct.pack(">L", offset))
  687. # FIXME: handle table for pack files > 8 Gb
  688. assert len(pack_checksum) == 20
  689. f.write(pack_checksum)
  690. f.close()
  691. class Pack(object):
  692. def __init__(self, basename):
  693. self._basename = basename
  694. self._data_path = self._basename + ".pack"
  695. self._idx_path = self._basename + ".idx"
  696. self._data = None
  697. self._idx = None
  698. def name(self):
  699. return self.idx.objects_sha1()
  700. @property
  701. def data(self):
  702. if self._data is None:
  703. self._data = PackData(self._data_path)
  704. assert len(self.idx) == len(self._data)
  705. idx_stored_checksum = self.idx.get_stored_checksums()[0]
  706. data_stored_checksum = self._data.get_stored_checksum()
  707. if idx_stored_checksum != data_stored_checksum:
  708. raise AssertionError("Checksum for index does not match checksum for pack: %s != %s" % (sha_to_hex(idx_stored_checksum), sha_to_hex(data_stored_checksum)))
  709. return self._data
  710. @property
  711. def idx(self):
  712. if self._idx is None:
  713. self._idx = PackIndex(self._idx_path)
  714. return self._idx
  715. def close(self):
  716. if self._data is not None:
  717. self._data.close()
  718. self.idx.close()
  719. def __eq__(self, other):
  720. return type(self) == type(other) and self.idx == other.idx
  721. def __len__(self):
  722. """Number of entries in this pack."""
  723. return len(self.idx)
  724. def __repr__(self):
  725. return "Pack(%r)" % self._basename
  726. def __iter__(self):
  727. """Iterate over all the sha1s of the objects in this pack."""
  728. return iter(self.idx)
  729. def check(self):
  730. return self.idx.check() and self.data.check()
  731. def get_stored_checksum(self):
  732. return self.data.get_stored_checksum()
  733. def __contains__(self, sha1):
  734. """Check whether this pack contains a particular SHA1."""
  735. return (self.idx.object_index(sha1) is not None)
  736. def get_raw(self, sha1, resolve_ref=None):
  737. offset = self.idx.object_index(sha1)
  738. if offset is None:
  739. raise KeyError(sha1)
  740. type, obj = self.data.get_object_at(offset)
  741. if isinstance(offset, long):
  742. offset = int(offset)
  743. assert isinstance(offset, int)
  744. return resolve_object(offset, type, obj, resolve_ref,
  745. self.data.get_object_at)
  746. def __getitem__(self, sha1):
  747. """Retrieve the specified SHA1."""
  748. type, uncomp = self.get_raw(sha1)
  749. return ShaFile.from_raw_string(type, uncomp)
  750. def iterobjects(self, get_raw=None):
  751. if get_raw is None:
  752. def get_raw(x):
  753. raise KeyError(x)
  754. for offset, type, obj in self.data.iterobjects():
  755. assert isinstance(offset, int)
  756. yield ShaFile.from_raw_string(
  757. *resolve_object(offset, type, obj,
  758. get_raw,
  759. self.data.get_object_at))
  760. def load_packs(path):
  761. if not os.path.exists(path):
  762. return
  763. for name in os.listdir(path):
  764. if name.startswith("pack-") and name.endswith(".pack"):
  765. yield Pack(os.path.join(path, name[:-len(".pack")]))