pack.py 27 KB

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