2
0

pack.py 28 KB

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