pack.py 32 KB

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