2
0

pack.py 32 KB

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