forked from jelmer/dulwich
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pack.py
1934 lines (1603 loc) · 63.1 KB
/
pack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pack.py -- For dealing with packed git objects.
# Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
# Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License or (at your option) a later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
"""Classes for dealing with packed git objects.
A pack is a compact representation of a bunch of objects, stored
using deltas where possible.
They have two parts, the pack file, which stores the data, and an index
that tells you where the data is.
To find an object you look in all of the index files 'til you find a
match for the object name. You then use the pointer got from this as
a pointer in to the corresponding packfile.
"""
from collections import defaultdict
import binascii
from io import BytesIO
from collections import (
deque,
)
import difflib
from itertools import chain, imap, izip
try:
import mmap
except ImportError:
has_mmap = False
else:
has_mmap = True
from hashlib import sha1
import os
from os import (
SEEK_CUR,
SEEK_END,
)
import struct
from struct import unpack_from
import warnings
import zlib
from dulwich.errors import (
ApplyDeltaError,
ChecksumMismatch,
)
from dulwich.file import GitFile
from dulwich.lru_cache import (
LRUSizeCache,
)
from dulwich.objects import (
ShaFile,
hex_to_sha,
sha_to_hex,
object_header,
)
OFS_DELTA = 6
REF_DELTA = 7
DELTA_TYPES = (OFS_DELTA, REF_DELTA)
DEFAULT_PACK_DELTA_WINDOW_SIZE = 10
def take_msb_bytes(read, crc32=None):
"""Read bytes marked with most significant bit.
:param read: Read function
"""
ret = []
while len(ret) == 0 or ret[-1] & 0x80:
b = read(1)
if crc32 is not None:
crc32 = binascii.crc32(b, crc32)
ret.append(ord(b))
return ret, crc32
class UnpackedObject(object):
"""Class encapsulating an object unpacked from a pack file.
These objects should only be created from within unpack_object. Most
members start out as empty and are filled in at various points by
read_zlib_chunks, unpack_object, DeltaChainIterator, etc.
End users of this object should take care that the function they're getting
this object from is guaranteed to set the members they need.
"""
__slots__ = [
'offset', # Offset in its pack.
'_sha', # Cached binary SHA.
'obj_type_num', # Type of this object.
'obj_chunks', # Decompressed and delta-resolved chunks.
'pack_type_num', # Type of this object in the pack (may be a delta).
'delta_base', # Delta base offset or SHA.
'comp_chunks', # Compressed object chunks.
'decomp_chunks', # Decompressed object chunks.
'decomp_len', # Decompressed length of this object.
'crc32', # CRC32.
]
# TODO(dborowitz): read_zlib_chunks and unpack_object could very well be
# methods of this object.
def __init__(self, pack_type_num, delta_base, decomp_len, crc32):
self.offset = None
self._sha = None
self.pack_type_num = pack_type_num
self.delta_base = delta_base
self.comp_chunks = None
self.decomp_chunks = []
self.decomp_len = decomp_len
self.crc32 = crc32
if pack_type_num in DELTA_TYPES:
self.obj_type_num = None
self.obj_chunks = None
else:
self.obj_type_num = pack_type_num
self.obj_chunks = self.decomp_chunks
self.delta_base = delta_base
def sha(self):
"""Return the binary SHA of this object."""
if self._sha is None:
self._sha = obj_sha(self.obj_type_num, self.obj_chunks)
return self._sha
def sha_file(self):
"""Return a ShaFile from this object."""
return ShaFile.from_raw_chunks(self.obj_type_num, self.obj_chunks)
# Only provided for backwards compatibility with code that expects either
# chunks or a delta tuple.
def _obj(self):
"""Return the decompressed chunks, or (delta base, delta chunks)."""
if self.pack_type_num in DELTA_TYPES:
return (self.delta_base, self.decomp_chunks)
else:
return self.decomp_chunks
def __eq__(self, other):
if not isinstance(other, UnpackedObject):
return False
for slot in self.__slots__:
if getattr(self, slot) != getattr(other, slot):
return False
return True
def __ne__(self, other):
return not (self == other)
def __repr__(self):
data = ['%s=%r' % (s, getattr(self, s)) for s in self.__slots__]
return '%s(%s)' % (self.__class__.__name__, ', '.join(data))
_ZLIB_BUFSIZE = 4096
def read_zlib_chunks(read_some, unpacked, include_comp=False,
buffer_size=_ZLIB_BUFSIZE):
"""Read zlib data from a buffer.
This function requires that the buffer have additional data following the
compressed data, which is guaranteed to be the case for git pack files.
:param read_some: Read function that returns at least one byte, but may
return less than the requested size.
:param unpacked: An UnpackedObject to write result data to. If its crc32
attr is not None, the CRC32 of the compressed bytes will be computed
using this starting CRC32.
After this function, will have the following attrs set:
* comp_chunks (if include_comp is True)
* decomp_chunks
* decomp_len
* crc32
:param include_comp: If True, include compressed data in the result.
:param buffer_size: Size of the read buffer.
:return: Leftover unused data from the decompression.
:raise zlib.error: if a decompression error occurred.
"""
if unpacked.decomp_len <= -1:
raise ValueError('non-negative zlib data stream size expected')
decomp_obj = zlib.decompressobj()
comp_chunks = []
decomp_chunks = unpacked.decomp_chunks
decomp_len = 0
crc32 = unpacked.crc32
while True:
add = read_some(buffer_size)
if not add:
raise zlib.error('EOF before end of zlib stream')
comp_chunks.append(add)
decomp = decomp_obj.decompress(add)
decomp_len += len(decomp)
decomp_chunks.append(decomp)
unused = decomp_obj.unused_data
if unused:
left = len(unused)
if crc32 is not None:
crc32 = binascii.crc32(add[:-left], crc32)
if include_comp:
comp_chunks[-1] = add[:-left]
break
elif crc32 is not None:
crc32 = binascii.crc32(add, crc32)
if crc32 is not None:
crc32 &= 0xffffffff
if decomp_len != unpacked.decomp_len:
raise zlib.error('decompressed data does not match expected size')
unpacked.crc32 = crc32
if include_comp:
unpacked.comp_chunks = comp_chunks
return unused
def iter_sha1(iter):
"""Return the hexdigest of the SHA1 over a set of names.
:param iter: Iterator over string objects
:return: 40-byte hex sha1 digest
"""
sha = sha1()
for name in iter:
sha.update(name)
return sha.hexdigest()
def load_pack_index(path):
"""Load an index file by path.
:param filename: Path to the index file
:return: A PackIndex loaded from the given path
"""
f = GitFile(path, 'rb')
try:
return load_pack_index_file(path, f)
finally:
f.close()
def _load_file_contents(f, size=None):
fileno = getattr(f, 'fileno', None)
# Attempt to use mmap if possible
if fileno is not None:
fd = f.fileno()
if size is None:
size = os.fstat(fd).st_size
if has_mmap:
try:
contents = mmap.mmap(fd, size, access=mmap.ACCESS_READ)
except mmap.error:
# Perhaps a socket?
pass
else:
return contents, size
contents = f.read()
size = len(contents)
return contents, size
def load_pack_index_file(path, f):
"""Load an index file from a file-like object.
:param path: Path for the index file
:param f: File-like object
:return: A PackIndex loaded from the given file
"""
contents, size = _load_file_contents(f)
if contents[:4] == '\377tOc':
version = struct.unpack('>L', contents[4:8])[0]
if version == 2:
return PackIndex2(path, file=f, contents=contents,
size=size)
else:
raise KeyError('Unknown pack index format %d' % version)
else:
return PackIndex1(path, file=f, contents=contents, size=size)
def bisect_find_sha(start, end, sha, unpack_name):
"""Find a SHA in a data blob with sorted SHAs.
:param start: Start index of range to search
:param end: End index of range to search
:param sha: Sha to find
:param unpack_name: Callback to retrieve SHA by index
:return: Index of the SHA, or None if it wasn't found
"""
assert start <= end
while start <= end:
i = (start + end) // 2
file_sha = unpack_name(i)
x = cmp(file_sha, sha)
if x < 0:
start = i + 1
elif x > 0:
end = i - 1
else:
return i
return None
class PackIndex(object):
"""An index in to a packfile.
Given a sha id of an object a pack index can tell you the location in the
packfile of that object if it has it.
"""
def __eq__(self, other):
if not isinstance(other, PackIndex):
return False
for (name1, _, _), (name2, _, _) in izip(self.iterentries(),
other.iterentries()):
if name1 != name2:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __len__(self):
"""Return the number of entries in this pack index."""
raise NotImplementedError(self.__len__)
def __iter__(self):
"""Iterate over the SHAs in this pack."""
return imap(sha_to_hex, self._itersha())
def iterentries(self):
"""Iterate over the entries in this pack index.
:return: iterator over tuples with object name, offset in packfile and
crc32 checksum.
"""
raise NotImplementedError(self.iterentries)
def get_pack_checksum(self):
"""Return the SHA1 checksum stored for the corresponding packfile.
:return: 20-byte binary digest
"""
raise NotImplementedError(self.get_pack_checksum)
def object_index(self, sha):
"""Return the index in to the corresponding packfile for the object.
Given the name of an object it will return the offset that object
lives at within the corresponding pack file. If the pack file doesn't
have the object then None will be returned.
"""
if len(sha) == 40:
sha = hex_to_sha(sha)
return self._object_index(sha)
def _object_index(self, sha):
"""See object_index.
:param sha: A *binary* SHA string. (20 characters long)_
"""
raise NotImplementedError(self._object_index)
def objects_sha1(self):
"""Return the hex SHA1 over all the shas of all objects in this pack.
:note: This is used for the filename of the pack.
"""
return iter_sha1(self._itersha())
def _itersha(self):
"""Yield all the SHA1's of the objects in the index, sorted."""
raise NotImplementedError(self._itersha)
class MemoryPackIndex(PackIndex):
"""Pack index that is stored entirely in memory."""
def __init__(self, entries, pack_checksum=None):
"""Create a new MemoryPackIndex.
:param entries: Sequence of name, idx, crc32 (sorted)
:param pack_checksum: Optional pack checksum
"""
self._by_sha = {}
for name, idx, crc32 in entries:
self._by_sha[name] = idx
self._entries = entries
self._pack_checksum = pack_checksum
def get_pack_checksum(self):
return self._pack_checksum
def __len__(self):
return len(self._entries)
def _object_index(self, sha):
return self._by_sha[sha][0]
def _itersha(self):
return iter(self._by_sha)
def iterentries(self):
return iter(self._entries)
class FilePackIndex(PackIndex):
"""Pack index that is based on a file.
To do the loop it opens the file, and indexes first 256 4 byte groups
with the first byte of the sha id. The value in the four byte group indexed
is the end of the group that shares the same starting byte. Subtract one
from the starting byte and index again to find the start of the group.
The values are sorted by sha id within the group, so do the math to find
the start and end offset and then bisect in to find if the value is present.
"""
def __init__(self, filename, file=None, contents=None, size=None):
"""Create a pack index object.
Provide it with the name of the index file to consider, and it will map
it whenever required.
"""
self._filename = filename
# Take the size now, so it can be checked each time we map the file to
# ensure that it hasn't changed.
if file is None:
self._file = GitFile(filename, 'rb')
else:
self._file = file
if contents is None:
self._contents, self._size = _load_file_contents(self._file, size)
else:
self._contents, self._size = (contents, size)
def __eq__(self, other):
# Quick optimization:
if (isinstance(other, FilePackIndex) and
self._fan_out_table != other._fan_out_table):
return False
return super(FilePackIndex, self).__eq__(other)
def close(self):
self._file.close()
if getattr(self._contents, "close", None) is not None:
self._contents.close()
def __len__(self):
"""Return the number of entries in this pack index."""
return self._fan_out_table[-1]
def _unpack_entry(self, i):
"""Unpack the i-th entry in the index file.
:return: Tuple with object name (SHA), offset in pack file and CRC32
checksum (if known).
"""
raise NotImplementedError(self._unpack_entry)
def _unpack_name(self, i):
"""Unpack the i-th name from the index file."""
raise NotImplementedError(self._unpack_name)
def _unpack_offset(self, i):
"""Unpack the i-th object offset from the index file."""
raise NotImplementedError(self._unpack_offset)
def _unpack_crc32_checksum(self, i):
"""Unpack the crc32 checksum for the i-th object from the index file."""
raise NotImplementedError(self._unpack_crc32_checksum)
def _itersha(self):
for i in range(len(self)):
yield self._unpack_name(i)
def iterentries(self):
"""Iterate over the entries in this pack index.
:return: iterator over tuples with object name, offset in packfile and
crc32 checksum.
"""
for i in range(len(self)):
yield self._unpack_entry(i)
def _read_fan_out_table(self, start_offset):
ret = []
for i in range(0x100):
fanout_entry = self._contents[start_offset+i*4:start_offset+(i+1)*4]
ret.append(struct.unpack('>L', fanout_entry)[0])
return ret
def check(self):
"""Check that the stored checksum matches the actual checksum."""
actual = self.calculate_checksum()
stored = self.get_stored_checksum()
if actual != stored:
raise ChecksumMismatch(stored, actual)
def calculate_checksum(self):
"""Calculate the SHA1 checksum over this pack index.
:return: This is a 20-byte binary digest
"""
return sha1(self._contents[:-20]).digest()
def get_pack_checksum(self):
"""Return the SHA1 checksum stored for the corresponding packfile.
:return: 20-byte binary digest
"""
return str(self._contents[-40:-20])
def get_stored_checksum(self):
"""Return the SHA1 checksum stored for this index.
:return: 20-byte binary digest
"""
return str(self._contents[-20:])
def _object_index(self, sha):
"""See object_index.
:param sha: A *binary* SHA string. (20 characters long)_
"""
assert len(sha) == 20
idx = ord(sha[0])
if idx == 0:
start = 0
else:
start = self._fan_out_table[idx-1]
end = self._fan_out_table[idx]
i = bisect_find_sha(start, end, sha, self._unpack_name)
if i is None:
raise KeyError(sha)
return self._unpack_offset(i)
class PackIndex1(FilePackIndex):
"""Version 1 Pack Index file."""
def __init__(self, filename, file=None, contents=None, size=None):
super(PackIndex1, self).__init__(filename, file, contents, size)
self.version = 1
self._fan_out_table = self._read_fan_out_table(0)
def _unpack_entry(self, i):
(offset, name) = unpack_from('>L20s', self._contents,
(0x100 * 4) + (i * 24))
return (name, offset, None)
def _unpack_name(self, i):
offset = (0x100 * 4) + (i * 24) + 4
return self._contents[offset:offset+20]
def _unpack_offset(self, i):
offset = (0x100 * 4) + (i * 24)
return unpack_from('>L', self._contents, offset)[0]
def _unpack_crc32_checksum(self, i):
# Not stored in v1 index files
return None
class PackIndex2(FilePackIndex):
"""Version 2 Pack Index file."""
def __init__(self, filename, file=None, contents=None, size=None):
super(PackIndex2, self).__init__(filename, file, contents, size)
if self._contents[:4] != '\377tOc':
raise AssertionError('Not a v2 pack index file')
(self.version, ) = unpack_from('>L', self._contents, 4)
if self.version != 2:
raise AssertionError('Version was %d' % self.version)
self._fan_out_table = self._read_fan_out_table(8)
self._name_table_offset = 8 + 0x100 * 4
self._crc32_table_offset = self._name_table_offset + 20 * len(self)
self._pack_offset_table_offset = (self._crc32_table_offset +
4 * len(self))
self._pack_offset_largetable_offset = (self._pack_offset_table_offset +
4 * len(self))
def _unpack_entry(self, i):
return (self._unpack_name(i), self._unpack_offset(i),
self._unpack_crc32_checksum(i))
def _unpack_name(self, i):
offset = self._name_table_offset + i * 20
return self._contents[offset:offset+20]
def _unpack_offset(self, i):
offset = self._pack_offset_table_offset + i * 4
offset = unpack_from('>L', self._contents, offset)[0]
if offset & (2**31):
offset = self._pack_offset_largetable_offset + (offset&(2**31-1)) * 8
offset = unpack_from('>Q', self._contents, offset)[0]
return offset
def _unpack_crc32_checksum(self, i):
return unpack_from('>L', self._contents,
self._crc32_table_offset + i * 4)[0]
def read_pack_header(read):
"""Read the header of a pack file.
:param read: Read function
:return: Tuple of (pack version, number of objects). If no data is available
to read, returns (None, None).
"""
header = read(12)
if not header:
return None, None
if header[:4] != 'PACK':
raise AssertionError('Invalid pack header %r' % header)
(version,) = unpack_from('>L', header, 4)
if version not in (2, 3):
raise AssertionError('Version was %d' % version)
(num_objects,) = unpack_from('>L', header, 8)
return (version, num_objects)
def chunks_length(chunks):
return sum(imap(len, chunks))
def unpack_object(read_all, read_some=None, compute_crc32=False,
include_comp=False, zlib_bufsize=_ZLIB_BUFSIZE):
"""Unpack a Git object.
:param read_all: Read function that blocks until the number of requested
bytes are read.
:param read_some: Read function that returns at least one byte, but may not
return the number of bytes requested.
:param compute_crc32: If True, compute the CRC32 of the compressed data. If
False, the returned CRC32 will be None.
:param include_comp: If True, include compressed data in the result.
:param zlib_bufsize: An optional buffer size for zlib operations.
:return: A tuple of (unpacked, unused), where unused is the unused data
leftover from decompression, and unpacked in an UnpackedObject with
the following attrs set:
* obj_chunks (for non-delta types)
* pack_type_num
* delta_base (for delta types)
* comp_chunks (if include_comp is True)
* decomp_chunks
* decomp_len
* crc32 (if compute_crc32 is True)
"""
if read_some is None:
read_some = read_all
if compute_crc32:
crc32 = 0
else:
crc32 = None
bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
type_num = (bytes[0] >> 4) & 0x07
size = bytes[0] & 0x0f
for i, byte in enumerate(bytes[1:]):
size += (byte & 0x7f) << ((i * 7) + 4)
raw_base = len(bytes)
if type_num == OFS_DELTA:
bytes, crc32 = take_msb_bytes(read_all, crc32=crc32)
raw_base += len(bytes)
if bytes[-1] & 0x80:
raise AssertionError
delta_base_offset = bytes[0] & 0x7f
for byte in bytes[1:]:
delta_base_offset += 1
delta_base_offset <<= 7
delta_base_offset += (byte & 0x7f)
delta_base = delta_base_offset
elif type_num == REF_DELTA:
delta_base = read_all(20)
if compute_crc32:
crc32 = binascii.crc32(delta_base, crc32)
raw_base += 20
else:
delta_base = None
unpacked = UnpackedObject(type_num, delta_base, size, crc32)
unused = read_zlib_chunks(read_some, unpacked, buffer_size=zlib_bufsize,
include_comp=include_comp)
return unpacked, unused
def _compute_object_size(value):
"""Compute the size of a unresolved object for use with LRUSizeCache."""
(num, obj) = value
if num in DELTA_TYPES:
return chunks_length(obj[1])
return chunks_length(obj)
class PackStreamReader(object):
"""Class to read a pack stream.
The pack is read from a ReceivableProtocol using read() or recv() as
appropriate.
"""
def __init__(self, read_all, read_some=None, zlib_bufsize=_ZLIB_BUFSIZE):
self.read_all = read_all
if read_some is None:
self.read_some = read_all
else:
self.read_some = read_some
self.sha = sha1()
self._offset = 0
self._rbuf = BytesIO()
# trailer is a deque to avoid memory allocation on small reads
self._trailer = deque()
self._zlib_bufsize = zlib_bufsize
def _read(self, read, size):
"""Read up to size bytes using the given callback.
As a side effect, update the verifier's hash (excluding the last 20
bytes read).
:param read: The read callback to read from.
:param size: The maximum number of bytes to read; the particular
behavior is callback-specific.
"""
data = read(size)
# maintain a trailer of the last 20 bytes we've read
n = len(data)
self._offset += n
tn = len(self._trailer)
if n >= 20:
to_pop = tn
to_add = 20
else:
to_pop = max(n + tn - 20, 0)
to_add = n
for _ in xrange(to_pop):
self.sha.update(self._trailer.popleft())
self._trailer.extend(data[-to_add:])
# hash everything but the trailer
self.sha.update(data[:-to_add])
return data
def _buf_len(self):
buf = self._rbuf
start = buf.tell()
buf.seek(0, SEEK_END)
end = buf.tell()
buf.seek(start)
return end - start
@property
def offset(self):
return self._offset - self._buf_len()
def read(self, size):
"""Read, blocking until size bytes are read."""
buf_len = self._buf_len()
if buf_len >= size:
return self._rbuf.read(size)
buf_data = self._rbuf.read()
self._rbuf = BytesIO()
return buf_data + self._read(self.read_all, size - buf_len)
def recv(self, size):
"""Read up to size bytes, blocking until one byte is read."""
buf_len = self._buf_len()
if buf_len:
data = self._rbuf.read(size)
if size >= buf_len:
self._rbuf = BytesIO()
return data
return self._read(self.read_some, size)
def __len__(self):
return self._num_objects
def read_objects(self, compute_crc32=False):
"""Read the objects in this pack file.
:param compute_crc32: If True, compute the CRC32 of the compressed
data. If False, the returned CRC32 will be None.
:return: Iterator over UnpackedObjects with the following members set:
offset
obj_type_num
obj_chunks (for non-delta types)
delta_base (for delta types)
decomp_chunks
decomp_len
crc32 (if compute_crc32 is True)
:raise ChecksumMismatch: if the checksum of the pack contents does not
match the checksum in the pack trailer.
:raise zlib.error: if an error occurred during zlib decompression.
:raise IOError: if an error occurred writing to the output file.
"""
pack_version, self._num_objects = read_pack_header(self.read)
if pack_version is None:
return
for i in xrange(self._num_objects):
offset = self.offset
unpacked, unused = unpack_object(
self.read, read_some=self.recv, compute_crc32=compute_crc32,
zlib_bufsize=self._zlib_bufsize)
unpacked.offset = offset
# prepend any unused data to current read buffer
buf = BytesIO()
buf.write(unused)
buf.write(self._rbuf.read())
buf.seek(0)
self._rbuf = buf
yield unpacked
if self._buf_len() < 20:
# If the read buffer is full, then the last read() got the whole
# trailer off the wire. If not, it means there is still some of the
# trailer to read. We need to read() all 20 bytes; N come from the
# read buffer and (20 - N) come from the wire.
self.read(20)
pack_sha = ''.join(self._trailer)
if pack_sha != self.sha.digest():
raise ChecksumMismatch(sha_to_hex(pack_sha), self.sha.hexdigest())
class PackStreamCopier(PackStreamReader):
"""Class to verify a pack stream as it is being read.
The pack is read from a ReceivableProtocol using read() or recv() as
appropriate and written out to the given file-like object.
"""
def __init__(self, read_all, read_some, outfile, delta_iter=None):
"""Initialize the copier.
:param read_all: Read function that blocks until the number of requested
bytes are read.
:param read_some: Read function that returns at least one byte, but may
not return the number of bytes requested.
:param outfile: File-like object to write output through.
:param delta_iter: Optional DeltaChainIterator to record deltas as we
read them.
"""
super(PackStreamCopier, self).__init__(read_all, read_some=read_some)
self.outfile = outfile
self._delta_iter = delta_iter
def _read(self, read, size):
"""Read data from the read callback and write it to the file."""
data = super(PackStreamCopier, self)._read(read, size)
self.outfile.write(data)
return data
def verify(self):
"""Verify a pack stream and write it to the output file.
See PackStreamReader.iterobjects for a list of exceptions this may
throw.
"""
if self._delta_iter:
for unpacked in self.read_objects():
self._delta_iter.record(unpacked)
else:
for _ in self.read_objects():
pass
def obj_sha(type, chunks):
"""Compute the SHA for a numeric type and object chunks."""
sha = sha1()
sha.update(object_header(type, chunks_length(chunks)))
for chunk in chunks:
sha.update(chunk)
return sha.digest()
def compute_file_sha(f, start_ofs=0, end_ofs=0, buffer_size=1<<16):
"""Hash a portion of a file into a new SHA.
:param f: A file-like object to read from that supports seek().
:param start_ofs: The offset in the file to start reading at.
:param end_ofs: The offset in the file to end reading at, relative to the
end of the file.
:param buffer_size: A buffer size for reading.
:return: A new SHA object updated with data read from the file.
"""
sha = sha1()
f.seek(0, SEEK_END)
todo = f.tell() + end_ofs - start_ofs
f.seek(start_ofs)
while todo:
data = f.read(min(todo, buffer_size))
sha.update(data)
todo -= len(data)
return sha
class PackData(object):
"""The data contained in a packfile.
Pack files can be accessed both sequentially for exploding a pack, and
directly with the help of an index to retrieve a specific object.
The objects within are either complete or a delta aginst another.
The header is variable length. If the MSB of each byte is set then it
indicates that the subsequent byte is still part of the header.
For the first byte the next MS bits are the type, which tells you the type
of object, and whether it is a delta. The LS byte is the lowest bits of the
size. For each subsequent byte the LS 7 bits are the next MS bits of the
size, i.e. the last byte of the header contains the MS bits of the size.
For the complete objects the data is stored as zlib deflated data.
The size in the header is the uncompressed object size, so to uncompress
you need to just keep feeding data to zlib until you get an object back,
or it errors on bad data. This is done here by just giving the complete
buffer from the start of the deflated object on. This is bad, but until I
get mmap sorted out it will have to do.
Currently there are no integrity checks done. Also no attempt is made to
try and detect the delta case, or a request for an object at the wrong
position. It will all just throw a zlib or KeyError.
"""
def __init__(self, filename, file=None, size=None):
"""Create a PackData object representing the pack in the given filename.
The file must exist and stay readable until the object is disposed of. It
must also stay the same size. It will be mapped whenever needed.
Currently there is a restriction on the size of the pack as the python
mmap implementation is flawed.
"""
self._filename = filename
self._size = size
self._header_size = 12
if file is None:
self._file = GitFile(self._filename, 'rb')
else:
self._file = file
(version, self._num_objects) = read_pack_header(self._file.read)
self._offset_cache = LRUSizeCache(1024*1024*20,
compute_size=_compute_object_size)
self.pack = None
@property
def filename(self):
return os.path.basename(self._filename)
@classmethod
def from_file(cls, file, size):
return cls(str(file), file=file, size=size)
@classmethod
def from_path(cls, path):
return cls(filename=path)
def close(self):
self._file.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def _get_size(self):