pack.py 28 KB

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