-
Notifications
You must be signed in to change notification settings - Fork 10
/
oscar.pyx
1757 lines (1509 loc) · 62.7 KB
/
oscar.pyx
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
# cython: language_level=3str, wraparound=False, boundscheck=False, nonecheck=False
import binascii
from cpython.version cimport PY_MAJOR_VERSION
from datetime import datetime, timedelta, tzinfo
import difflib
from functools import wraps
import glob
import hashlib
from libc.stdint cimport uint8_t, uint32_t, uint64_t
from libc.stdlib cimport free
from math import log
import os
import re
from threading import Lock
import time
from typing import Dict, Tuple
import warnings
# if throws "module 'lzf' has no attribute 'decompress'",
# `pip uninstall lzf && pip install python-lzf`
import lzf
__version__ = '2.2.2'
__author__ = 'marat@cmu.edu'
__license__ = 'GPL v3'
if PY_MAJOR_VERSION < 3:
str_type = unicode
bytes_type = str
else:
str_type = str
bytes_type = bytes
try:
with open('/etc/hostname') as fh:
HOSTNAME = fh.read().strip()
except IOError:
raise ImportError('Oscar only support Linux hosts so far')
HOST = HOSTNAME.split('.', 1)[0]
DOMAIN = HOSTNAME[len(HOST):]
IS_TEST_ENV = 'OSCAR_TEST' in os.environ
# test environment has 'OSCAR_TEST' environment variable set
if not IS_TEST_ENV:
if not DOMAIN.endswith(r'.eecs.utk.edu'):
raise ImportError('Oscar is only available on certain servers at UTK, '
'please modify to match your cluster configuration')
if HOST not in ('da4', 'da5'):
warnings.warn('Commit and tree direct content is only available on da4.'
' Some functions might not work as expected.\n\n')
# Cython is generally smart enough to convert data[i] to int, but
# pyximport in Py2 fails to do so, requires to use ord explicitly
# TODO: get rid of this shame once Py2 support is dropped
cdef uint8_t nth_byte(bytes data, uint32_t i):
if PY_MAJOR_VERSION < 3:
return ord(data[i])
return data[i]
def _latest_version(path_template):
if '{ver}' not in path_template:
return ''
# Using * to allow for two-character versions
glob_pattern = path_template.format(key=0, ver='*')
filenames = glob.glob(glob_pattern)
prefix, postfix = glob_pattern.split('*', 1)
versions = [fname[len(prefix):-len(postfix)] for fname in filenames]
return max(versions or [''], key=lambda ver: (len(ver), ver))
def _key_length(str path_template):
# type: (str) -> int
if '{key}' not in path_template:
return 0
glob_pattern = path_template.format(key='*', ver='*')
filenames = glob.glob(glob_pattern)
# check emptiness of filenames otherwise we can't use filenames[0]
if not filenames:
# warnings.warn("No files found for %s" % (glob_pattern))
return 0
# key always comes the last, so rsplit is enough to account for two stars
prefix, postfix = glob_pattern.rsplit('*', 1)
# quirk for multi-char versions: match the last digit of the prefix
_prefix_len = len(prefix)
while _prefix_len < len(filenames[0]) - 2:
if filenames[0][_prefix_len - 1] == prefix[len(prefix) - 1]:
break
_prefix_len += 1
# note that with wraparound=False we can't use negative indexes.
# this caused hard to catch bugs before
str_keys = [fname[_prefix_len:len(fname)-len(postfix)] for fname in filenames]
keys = [int(key) for key in str_keys if key]
# Py2/3 compatible version
return int(log(max(keys or [0]) + 1, 2))
# re_pattern = path_template.format(key='(\d+)', ver='([A-Za-z0-9]+)')
# _matched = re.match(re_pattern, 'c2cFull{ver}.0.tch')
VERSIONS = {} # type: Dict[str, str]
def _get_paths(dict raw_paths):
# type: (Dict[str, Tuple[str, Dict[str, str]]]) -> Dict[str, Tuple[bytes, int]]
"""
Compose path from
Args:
raw_paths (Dict[str, Tuple[str, Dict[str, str]]]): see example below
Returns:
(Dict[str, Tuple[str, int]]: map data type to a path template and a key
length, e.g.:
'author_commits' -> ('/da0_data/basemaps/a2cFullR.{key}.tch', 5)
"""
paths = {} # type: Dict[str, Tuple[bytes, int]]
local_data_prefix = '/' + HOST + '_data'
for category, (path_prefix, filenames) in raw_paths.items():
cat_path_prefix = os.environ.get(category, path_prefix)
cat_version = os.environ.get(category + '_VER') or _latest_version(
os.path.join(cat_path_prefix, list(filenames.values())[0]))
if cat_path_prefix.startswith(local_data_prefix):
cat_path_prefix = '/data' + cat_path_prefix[len(local_data_prefix):]
for ptype, fname in filenames.items():
ppath = os.environ.get(
'_'.join(['OSCAR', ptype.upper()]), cat_path_prefix)
for replace_from, replace_to in [
('da5', 'da4'),
('da4', 'da3'),
('da3_fast', 'da7_data/basemaps'),
('da7', 'da0'),
('da0', 'da5'),
('da5', 'da8'),
('da8', 'never_gonna_happen'),
]:
# get the latest version for the current mapping
path_template = os.path.join(ppath, fname)
pver = os.environ.get(
'_'.join(['OSCAR', ptype.upper(), 'VER']),
_latest_version(path_template) or cat_version)
path_template = os.path.join(ppath, fname)
key_length = _key_length(path_template)
# match
if key_length:
if ptype in VERSIONS and VERSIONS[ptype] > pver:
warnings.warn(
"Skipping older version of %s: %s > %s" % (
ptype, VERSIONS[ptype], pver))
continue
VERSIONS[ptype] = pver
paths[ptype] = (
path_template.format(ver=pver, key='{key}'), key_length)
break
# mismatch
ppath = ppath.replace(replace_from, replace_to)
else:
warnings.warn("No keys found for path_template %s:\n%s" % (
ptype, path_template))
# # TODO: .format with pver and check keys only
# # this will allow to handle 2-char versions
# key_length = _key_length(path_template)
# if not key_length and not IS_TEST_ENV:
# ppath = ppath .replace('da5','da4')
# path_template = os.path.join(ppath, fname)
# key_length = _key_length(path_template)
# if not key_length:
# ppath = ppath .replace('da4','da3')
# path_template = os.path.join(ppath, fname)
# key_length = _key_length(path_template)
# if not key_length:
# ppath = ppath .replace('da3_fast','da7_data/basemaps')
# path_template = os.path.join(ppath, fname)
# key_length = _key_length(path_template)
# if not key_length:
# ppath = ppath .replace('da7','da0')
# path_template = os.path.join(ppath, fname)
# key_length = _key_length(path_template)
# if not key_length:
# ppath = ppath .replace('da0','da5')
# path_template = os.path.join(ppath, fname)
# key_length = _key_length(path_template)
# if not key_length:
# ppath = ppath .replace('da5','da8')
# path_template = os.path.join(ppath, fname)
# key_length = _key_length(path_template)
# if not key_length:
# warnings.warn("No keys found for path_template %s:\n%s" % (
# ptype, path_template))
# VERSIONS[ptype] = pver
# paths[ptype] = (
# path_template.format(ver=pver, key='{key}'), key_length)
return paths
# note to future self: Python2 uses str (bytes) for os.environ,
# Python3 uses str (unicode). Don't add Py2/3 compatibility prefixes here
PATHS = _get_paths({
'OSCAR_ALL_BLOBS': ('/da5_data/All.blobs/', {
'commit_sequential_idx': 'commit_{key}.idx',
'commit_sequential_bin': 'commit_{key}.bin',
'tree_sequential_idx': 'tree_{key}.idx',
'tree_sequential_bin': 'tree_{key}.bin',
'blob_sequential_idx': 'blob_{key}.idx',
'blob_sequential_bin': 'blob_{key}.bin',
'blob_data': 'blob_{key}.bin',
}),
'OSCAR_ALL_SHA1C': ('/da5_fast/All.sha1c', {
# critical - random access to trees and commits: only on da4 and da5
# - performance is best when /fast is on SSD raid
'commit_random': 'commit_{key}.tch',
'tree_random': 'tree_{key}.tch',
}),
# all three are available on da[3-5]
'OSCAR_ALL_SHA1O': ('/da4_fast/All.sha1o', {
'blob_offset': 'sha1.blob_{key}.tch',
# Speed is a bit lower since the content is read from HDD raid
}),
'OSCAR_BASEMAPS': ('/da5_fast', {
# relations - good to have but not critical
'commit_projects': 'c2pFull{ver}.{key}.tch',
'commit_children': 'c2ccFull{ver}.{key}.tch',
'commit_data': 'c2datFull{ver}.{key}.tch',
'commit_root': 'c2rFull{ver}.{key}.tch',
'commit_head': 'c2hFull{ver}.{key}.tch',
'commit_parent': 'c2pcFull{ver}.{key}.tch',
'author_commits': 'a2cFull{ver}.{key}.tch',
'author_projects': 'a2pFull{ver}.{key}.tch',
'author_files': 'a2fFull{ver}.{key}.tch',
'project_authors': 'p2aFull{ver}.{key}.tch',
'commit_blobs': 'c2bFull{ver}.{key}.tch',
'commit_files': 'c2fFull{ver}.{key}.tch',
'project_commits': 'p2cFull{ver}.{key}.tch',
'blob_commits': 'b2cFull{ver}.{key}.tch',
# this points to the first time/author/commit
'blob_first_author': 'b2faFull{ver}.{key}.tch',
'file_authors': 'f2aFull{ver}.{key}.tch',
'file_commits': 'f2cFull{ver}.{key}.tch',
'file_blobs': 'f2bFull{ver}.{key}.tch',
'blob_files': 'b2fFull{ver}.{key}.tch',
}),
})
# prefixes used by World of Code to identify source project platforms
# See Project.to_url() for more details
# Prefixes have been deprecated by replacing them with the string resembling
# actual URL
URL_PREFIXES = {
b'bitbucket.org': b'bitbucket.org',
b'gitlab.com': b'gitlab.com',
b'android.googlesource.com': b'android.googlesource.com',
b'bioconductor.org': b'bioconductor.org',
b'drupal.com': b'git.drupal.org',
b'git.eclipse.org': b'git.eclipse.org',
b'git.kernel.org': b'git.kernel.org',
b'git.postgresql.org': b'git.postgresql.org',
b'git.savannah.gnu.org': b'git.savannah.gnu.org',
b'git.zx2c4.com': b'git.zx2c4.com',
b'gitlab.gnome.org': b'gitlab.gnome.org',
b'kde.org': b'anongit.kde.org',
b'repo.or.cz': b'repo.or.cz',
b'salsa.debian.org': b'salsa.debian.org',
b'sourceforge.net': b'git.code.sf.net/p'
}
IGNORED_AUTHORS = (
b'GitHub Merge Button <merge-button@github.com>'
)
class ObjectNotFound(KeyError):
pass
cdef unber(bytes buf):
r""" Perl BER unpacking.
BER is a way to pack several variable-length ints into one
binary string. Here we do the reverse.
Format definition: from http://perldoc.perl.org/functions/pack.html
(see "w" template description)
Args:
buf (bytes): a binary string with packed values
Returns:
str: a list of unpacked values
>>> unber(b'\x00\x83M')
[0, 461]
>>> unber(b'\x83M\x96\x14')
[461, 2836]
>>> unber(b'\x99a\x89\x12')
[3297, 1170]
"""
# PY: 262ns, Cy: 78ns
cdef:
list res = []
# blob_offset sizes are getting close to 32-bit integer max
uint64_t acc = 0
uint8_t b
for b in buf:
acc = (acc << 7) + (b & 0x7f)
if not b & 0x80:
res.append(acc)
acc = 0
return res
cdef (int, int) lzf_length(bytes raw_data):
# type: (bytes) -> (int, int)
r""" Get length of uncompressed data from a header of Compress::LZF
output. Check Compress::LZF sources for the definition of this bit magic
(namely, LZF.xs, decompress_sv)
https://metacpan.org/source/MLEHMANN/Compress-LZF-3.8/LZF.xs
Args:
raw_data (bytes): data compressed with Perl Compress::LZF
Returns:
Tuple[int, int]: (header_size, uncompressed_content_length) in bytes
>>> lzf_length(b'\xc4\x9b')
(2, 283)
>>> lzf_length(b'\xc3\xa4')
(2, 228)
>>> lzf_length(b'\xc3\x8a')
(2, 202)
>>> lzf_length(b'\xca\x87')
(2, 647)
>>> lzf_length(b'\xe1\xaf\xa9')
(3, 7145)
>>> lzf_length(b'\xe0\xa7\x9c')
(3, 2524)
"""
# PY:725us, Cy:194usec
cdef:
# compressed size, header length, uncompressed size
uint32_t csize=len(raw_data), start=1, usize
# first byte, mask, buffer iterator placeholder
uint8_t lower=nth_byte(raw_data, 0), mask=0x80, b
while mask and csize > start and (lower & mask):
mask >>= 1 + (mask == 0x80)
start += 1
if not mask or csize < start:
raise ValueError('LZF compressed data header is corrupted')
usize = lower & (mask - 1)
for b in raw_data[1:start]:
usize = (usize << 6) + (b & 0x3f)
if not usize:
raise ValueError('LZF compressed data header is corrupted')
return start, usize
def decomp(bytes raw_data):
# type: (bytes) -> bytes
""" lzf wrapper to handle perl tweaks in Compress::LZF
This function extracts uncompressed size header
and then does usual lzf decompression.
Args:
raw_data (bytes): data compressed with Perl Compress::LZF
Returns:
str: unpacked data
"""
if not raw_data:
return b''
if nth_byte(raw_data, 0) == 0:
return raw_data[1:]
start, usize = lzf_length(raw_data)
# while it is tempting to include liblzf and link statically, there is
# zero advantage comparing to just using python-lzf
return lzf.decompress(raw_data[start:], usize)
cdef uint32_t fnvhash(bytes data):
"""
Returns the 32 bit FNV-1a hash value for the given data.
>>> hex(fnvhash('foo'))
'0xa9f37ed7'
"""
# PY: 5.8usec Cy: 66.8ns
cdef:
uint32_t hval = 0x811c9dc5
uint8_t b
for b in data:
hval ^= b
hval *= 0x01000193
return hval
def cached_property(func):
""" Classic memoize with @property on top"""
@wraps(func)
def wrapper(self):
key = '_' + func.__name__
if not hasattr(self, key):
setattr(self, key, func(self))
return getattr(self, key)
return property(wrapper)
def slice20(bytes raw_data):
""" Slice raw_data into 20-byte chunks and hex encode each of them
It returns tuple in order to be cacheable
"""
if raw_data is None:
return ()
return tuple(raw_data[i:i + 20] for i in range(0, len(raw_data), 20))
class CommitTimezone(tzinfo):
# TODO: replace with datetime.timezone once Py2 support is ended
# a lightweight version of pytz._FixedOffset
def __init__(self, hours, minutes):
self.offset = timedelta(hours=hours, minutes=minutes)
def utcoffset(self, dt):
return self.offset
def tzname(self, dt):
return 'fixed'
def dst(self, dt):
# daylight saving time - no info
return timedelta(0)
def __repr__(self):
h, m = divmod(self.offset.seconds // 60, 60)
return "<Timezone: %02d:%02d>" % (h, m)
DAY_Z = datetime.fromtimestamp(0, CommitTimezone(0, 0))
def parse_commit_date(bytes timestamp, bytes tz):
""" Parse date string of authored_at/commited_at
git log time is in the original timezone
gitpython - same as git log (also, it has the correct timezone)
unix timestamps (used internally by commit objects) are in UTC
datetime.fromtimestamp without a timezone will convert it to host tz
github api is in UTC (this is what trailing 'Z' means)
Args:
timestamp (str): Commit.authored_at or Commit.commited_at,
e.g. '1337145807 +1100'
tz (str): timezone
Returns:
Optional[datetime.datetime]: UTC datetime
>>> parse_commit_date(b'1337145807', b'+1130')
datetime.datetime(2012, 5, 16, 16, 23, 27, tzinfo=<Timezone: 11:30>)
>>> parse_commit_date(b'3337145807', b'+1100') is None
True
"""
cdef:
int sign = -1 if tz.startswith(b'-') else 1
uint32_t ts
int hours, minutes
uint8_t tz_len = len(tz)
try:
ts = int(timestamp)
hours = sign * int(tz[tz_len-4:tz_len-2])
minutes = sign * int(tz[tz_len-2:])
dt = datetime.fromtimestamp(ts, CommitTimezone(hours, minutes))
except (ValueError, OverflowError):
# i.e. if timestamp or timezone is invalid
return None
# timestamp is in the future
if ts > time.time():
return None
return dt
cdef extern from 'Python.h':
object PyBytes_FromStringAndSize(char *s, Py_ssize_t len)
cdef extern from 'tchdb.h':
ctypedef struct TCHDB: # type of structure for a hash database
pass
cdef enum: # enumeration for open modes
HDBOREADER = 1 << 0, # open as a reader
HDBONOLCK = 1 << 4, # open without locking
const char *tchdberrmsg(int ecode)
TCHDB *tchdbnew()
int tchdbecode(TCHDB *hdb)
bint tchdbopen(TCHDB *hdb, const char *path, int omode)
bint tchdbclose(TCHDB *hdb)
void *tchdbget(TCHDB *hdb, const void *kbuf, int ksiz, int *sp)
bint tchdbiterinit(TCHDB *hdb)
void *tchdbiternext(TCHDB *hdb, int *sp)
cdef class Hash:
"""Object representing a Tokyocabinet Hash table"""
cdef TCHDB* _db
cdef bytes filename
def __cinit__(self, char *path, nolock=True):
cdef int mode = HDBOREADER
if nolock:
mode |= HDBONOLCK
self._db = tchdbnew()
self.filename = path
if self._db is NULL:
raise MemoryError()
cdef bint result = tchdbopen(self._db, path, mode)
if not result:
raise IOError('Failed to open .tch file "%s": ' % self.filename
+ self._error())
def _error(self):
cdef int code = tchdbecode(self._db)
cdef bytes msg = tchdberrmsg(code)
return msg.decode('ascii')
def __iter__(self):
cdef:
bint result = tchdbiterinit(self._db)
char *buf
int sp
bytes key
if not result:
raise IOError('Failed to iterate .tch file "%s": ' % self.filename
+ self._error())
while True:
buf = <char *>tchdbiternext(self._db, &sp)
if buf is NULL:
break
key = PyBytes_FromStringAndSize(buf, sp)
free(buf)
yield key
cdef bytes read(self, bytes key):
cdef:
char *k = key
char *buf
int sp
int ksize=len(key)
buf = <char *>tchdbget(self._db, k, ksize, &sp)
if buf is NULL:
raise ObjectNotFound()
cdef bytes value = PyBytes_FromStringAndSize(buf, sp)
free(buf)
return value
def __getitem__(self, bytes key):
return self.read(key)
def __del__(self):
cdef bint result = tchdbclose(self._db)
if not result:
raise IOError('Failed to close .tch "%s": ' % self.filename
+ self._error())
def __dealloc__(self):
free(self._db)
# Pool of open TokyoCabinet databases to save few milliseconds on opening
cdef dict _TCH_POOL = {} # type: Dict[str, Hash]
TCH_LOCK = Lock()
def _get_tch(char *path):
""" Cache Hash() objects """
if path in _TCH_POOL:
return _TCH_POOL[path]
try:
TCH_LOCK.acquire()
# in multithreading environment this can cause race condition,
# so we need a lock
if path not in _TCH_POOL:
_TCH_POOL[path] = Hash(path)
finally:
TCH_LOCK.release()
return _TCH_POOL[path]
class _Base(object):
type = 'oscar_base' # type: str
key = None # type: bytes
# fnv keys are used for non-git objects, such as files, projects and authors
use_fnv_keys = True # type: bool
_keys_registry_dtype = None # type: str
def __init__(self, key):
self.key = key
def __repr__(self):
return '<%s: %s>' % (self.type.capitalize(), self)
def __hash__(self):
return hash(self.key)
def __eq__(self, other):
return isinstance(other, type(self)) \
and self.type == other.type \
and self.key == other.key
def __ne__(self, other):
return not self == other
def __str__(self):
return (binascii.hexlify(self.key).decode('ascii')
if isinstance(self.key, bytes_type) else self.key)
def resolve_path(self, dtype):
""" Get path to a file using data type and object key (for sharding)
"""
path, prefix_length = PATHS[dtype]
cdef uint8_t p
if self.use_fnv_keys:
p = fnvhash(self.key)
else:
p = nth_byte(self.key, 0)
cdef uint8_t prefix = p & (2**prefix_length - 1)
return path.format(key=prefix)
def read_tch(self, dtype):
""" Resolve the path and read .tch"""
path = self.resolve_path(dtype).encode('ascii')
try:
return _get_tch(path)[self.key]
except KeyError:
return None
@classmethod
def all_keys(cls):
""" Iterate keys of all objects of the given type
This might be useful to get a list of all projects, or a list of
all file names.
Yields:
bytes: objects key
"""
if not cls._keys_registry_dtype:
raise NotImplemented
base_path, prefix_length = PATHS[cls._keys_registry_dtype]
for file_prefix in range(2 ** prefix_length):
for key in _get_tch(base_path.format(key=file_prefix).encode('ascii')):
yield key
@classmethod
def all(cls):
for key in cls.all_keys():
yield cls(key)
class GitObject(_Base):
use_fnv_keys = False
@classmethod
def all(cls):
""" Iterate ALL objects of this type (all projects, all times) """
base_idx_path, prefix_length = PATHS[cls.type + '_sequential_idx']
base_bin_path, prefix_length = PATHS[cls.type + '_sequential_bin']
for key in range(2**prefix_length):
idx_path = base_idx_path.format(key=key)
bin_path = base_bin_path.format(key=key)
datafile = open(bin_path, "rb")
for line in open(idx_path):
chunks = line.strip().split(";")
offset, comp_length, sha = chunks[1:4]
if len(chunks) > 4: # cls.type == "blob":
# usually, it's true for blobs;
# however, some blobs follow common pattern
sha = chunks[4]
obj = cls(sha)
# obj.data = decomp(datafile.read(int(comp_length)))
yield obj
datafile.close()
def __init__(self, sha):
if isinstance(sha, str_type) and len(sha) == 40:
self.sha = sha
self.bin_sha = binascii.unhexlify(sha)
elif isinstance(sha, bytes_type) and len(sha) == 20:
self.bin_sha = sha
self.sha = binascii.hexlify(sha).decode('ascii')
else:
raise ValueError('Invalid SHA1 hash: %s' % sha)
super(GitObject, self).__init__(self.bin_sha)
@cached_property
def data(self):
# type: () -> bytes
if self.type not in ('commit', 'tree'):
raise NotImplementedError
# default implementation will only work for commits and trees
return decomp(self.read_tch(self.type + '_random'))
@classmethod
def string_sha(cls, data):
# type: (bytes) -> str
"""Manually compute blob sha from its content passed as `data`.
The main use case for this method is to identify source of a file.
Blob SHA is computed from a string:
"blob <file content length as str><null byte><file content>"
# https://gist.github.com/masak/2415865
Commit SHAs are computed in a similar way
"commit <commit length as str><null byte><commit content>"
note that commit content includes committed/authored date
Args:
data (bytes): content of the GitObject to get hash for
Returns:
str: 40-byte hex SHA1 hash
"""
sha1 = hashlib.sha1()
sha1.update(b'%s %d\x00' % (cls.type.encode('ascii'), len(data)))
sha1.update(data)
return sha1.hexdigest()
@classmethod
def file_sha(cls, path):
buffsize = 1024 ** 2
size = os.stat(path).st_size
with open(path, 'rb') as fh:
sha1 = hashlib.sha1()
sha1.update(b'%s %d\x00' % (cls.type.encode('ascii'), size))
while True:
data = fh.read(min(size, buffsize))
if not data:
return sha1.hexdigest()
sha1.update(data)
class Blob(GitObject):
type = 'blob'
def __len__(self):
_, length = self.position
return length
@cached_property
def position(self):
# type: () -> (int, int)
""" Get offset and length of the blob data in the storage """
value = self.read_tch('blob_offset')
if value is None: # empty read -> value not found
raise ObjectNotFound('Blob data not found (bad sha?)')
return unber(value)
@cached_property
def data(self):
""" Content of the blob """
offset, length = self.position
# no caching here to stay thread-safe
with open(self.resolve_path('blob_data'), 'rb') as fh:
fh.seek(offset)
return decomp(fh.read(length))
@cached_property
def commit_shas(self):
""" SHAs of Commits in which this blob have been
introduced or modified.
**NOTE: commits removing this blob are not included**
"""
return slice20(self.read_tch('blob_commits'))
@property
def commits(self):
""" Commits where this blob has been added or changed
**NOTE: commits removing this blob are not included**
"""
return (Commit(bin_sha) for bin_sha in self.commit_shas)
@cached_property
def first_author(self):
""" get time, first author and first commit for the blob
"""
buf = self .read_tch ('blob_first_author')
buf0 = buf [0:len(buf)-21]
cmt_sha = buf [(len(buf)-20):len(buf)]
(Time, Author) = buf0 .decode('ascii') .split(";")
return (Time, Author, cmt_sha .hex())
class Tree(GitObject):
""" A representation of git tree object, basically - a directory.
Trees are iterable. Each element of the iteration is a 3-tuple:
`(mode, filename, sha)`
- `mode` is an ASCII decimal **string** similar to file mode
in Unix systems. Subtrees always have mode "40000"
- `filename` is a string filename, not including directories
- `sha` is a 40 bytes hex string representing file content Blob SHA
.. Note:: iteration is not recursive.
For a recursive walk, use Tree.traverse() or Tree.files
Both files and blobs can be checked for membership,
either by their id (filename or SHA) or a corresponding object:
>>> tree = Tree("d4ddbae978c9ec2dc3b7b3497c2086ecf7be7d9d")
>>> '.gitignore' in tree
True
>>> File('.keep') in tree
False
>>> '83d22195edc1473673f1bf35307aea6edf3c37e3' in tree
True
>>> Blob('83d22195edc1473673f1bf35307aea6edf3c37e3') in tree
True
`len(tree)` returns the number of files under the tree, including files in
subtrees but not the subtrees themselves:
>>> len(Tree("d4ddbae978c9ec2dc3b7b3497c2086ecf7be7d9d"))
16
"""
type = 'tree'
def __iter__(self):
""" Unpack binary tree structures, yielding 3-tuples of
(mode (ASCII decimal), filename, sha (40 bytes hex))
Format description: https://stackoverflow.com/questions/14790681/
mode (ASCII encoded decimal)
SPACE (\0x20)
filename
NULL (\x00)
20-byte binary hash
>>> len(list(Tree("d4ddbae978c9ec2dc3b7b3497c2086ecf7be7d9d")))
6
>>> all(len(line) == 3
... for line in Tree("954829887af5d9071aa92c427133ca2cdd0813cc"))
True
"""
# unfortunately, Py2 cython doesn't know how to instantiate bytes from
# memoryviews. TODO: reuse libgit2 git_tree__parse_raw
data = self.data
i = 0
while i < len(data):
# mode
start = i
while i < len(data) and nth_byte(data, i) != 32: # 32 is space
i += 1
mode = data[start:i]
i += 1
# file name
start = i
while i < len(data) and <char> nth_byte(data, i) != 0:
i += 1
fname = data[start:i]
# sha
start = i + 1
i += 21
yield mode, fname, data[start:i]
def __len__(self):
return len(self.files)
def __contains__(self, item):
if isinstance(item, File):
return item.key in self.files
elif isinstance(item, Blob):
return item.bin_sha in self.blob_shas
elif isinstance(item, str_type) and len(item) == 40:
item = binascii.unhexlify(item)
elif not isinstance(item, bytes_type):
return False
return item in self.blob_shas or item in self.files
def traverse(self):
""" Recursively traverse the tree
This will generate 3-tuples of the same format as direct tree
iteration, but will recursively include subtrees content.
Yields:
Tuple[bytes, bytes, bytes]: (mode, filename, blob/tree sha)
>>> c = Commit(u'1e971a073f40d74a1e72e07c682e1cba0bae159b')
>>> len(list(c.tree.traverse()))
8
>>> c = Commit(u'e38126dbca6572912013621d2aa9e6f7c50f36bc')
>>> len(list(c.tree.traverse()))
36
"""
for mode, fname, sha in self:
yield mode, fname, sha
# trees are always 40000:
# https://stackoverflow.com/questions/1071241
if mode == b'40000':
for mode2, fname2, sha2 in Tree(sha).traverse():
yield mode2, fname + b'/' + fname2, sha2
@cached_property
def str(self):
"""
>>> print(Tree('954829887af5d9071aa92c427133ca2cdd0813cc'))
100644 __init__.py ff1f7925b77129b31938e76b5661f0a2c4500556
100644 admin.py d05d461b48a8a5b5a9d1ea62b3815e089f3eb79b
100644 models.py d1d952ee766d616eae5bfbd040c684007a424364
40000 templates 7ff5e4c9bd3ce6ab500b754831d231022b58f689
40000 templatetags e5e994b0be2c9ce6af6f753275e7d8c29ccf75ce
100644 urls.py e9cb0c23a7f6683911305efff91dcabadb938794
100644 utils.py 2cfbd298f18a75d1f0f51c2f6a1f2fcdf41a9559
100644 views.py 973a78a1fe9e69d4d3b25c92b3889f7e91142439
"""
return b'\n'.join(b' '.join((mode, fname, binascii.hexlify(sha)))
for mode, fname, sha in self).decode('ascii')
@cached_property
def files(self):
""" A dict of all files and their content/blob sha under this tree.
It includes recursive files (i.e. files in subdirectories).
It does NOT include subdirectories themselves.
"""
return {fname: sha for mode, fname, sha in self if mode != b'40000'}
@property
def blob_shas(self):
"""A tuple of all file content shas, including files in subdirectories
"""
return tuple(self.files.values())
@property
def blobs(self):
""" A generator of Blob objects with file content.
It does include files in subdirectories.
>>> tuple(Tree('d20520ef8c1537a42628b72d481b8174c0a1de84').blobs
... ) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
(<Blob: 2bdf5d686c6cd488b706be5c99c3bb1e166cf2f6>, ...,
<Blob: c006bef767d08b41633b380058a171b7786b71ab>)
"""
return (Blob(sha) for sha in self.blob_shas)
class Commit(GitObject):
""" A git commit object.
Commits have some special properties.
Most of object properties provided by this project are lazy, i.e. they are
computed when you access them for the first time.
The following `Commit` properties will be instantiated all at once on the
first access to *any* of them.
- :data:`tree`: root `Tree` of the commit
- :data:`parent_shas`: tuple of parent commit sha hashes
- :data:`message`: str, first line of the commit message
- :data:`full_message`: str, full commit message
- :data:`author`: str, Name <email>
- :data:`authored_at`: str, unix_epoch+timezone
- :data:`committer`: str, Name <email>
- :data:`committed_at`: str, unix_epoch+timezone
"""
type = 'commit'
encoding = 'utf8'
def __getattr__(self, attr):
""" Mimic special properties:
tree: root Tree of the commit
parent_shas: tuple of parent commit sha hashes
message: str, first line of the commit message
full_message: str, full commit message
author: str, Name <email>
authored_at: timezone-aware datetime or None (if invalid)
committer: str, Name <email>
committed_at: timezone-aware datetime or None (if invalid)
signature: str or None, PGP signature
Commit: https://github.com/user2589/minicms/commit/e38126db
>>> c = Commit('e38126dbca6572912013621d2aa9e6f7c50f36bc')
>>> c.author.startswith(b'Marat')
True
>>> c.authored_at
datetime.datetime(2012, 5, 19, 1, 14, 8, tzinfo=<Timezone: 11:00>)
>>> c.tree.sha
'6845f55f47ddfdbe4628a83fdaba35fa4ae3c894'
>>> len(c.parent_shas)