Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork966
Expand file tree
/
Copy pathutil.py
More file actions
700 lines (559 loc) · 23.3 KB
/
util.py
File metadata and controls
700 lines (559 loc) · 23.3 KB
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
# Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
#
# This module is part of GitPython and is released under the
# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
"""Utility functions for working with git objects."""
__all__= [
"get_object_type_by_name",
"parse_date",
"parse_actor_and_date",
"ProcessStreamAdapter",
"Traversable",
"altz_to_utctz_str",
"utctz_to_altz",
"verify_utctz",
"Actor",
"tzoffset",
"utc",
]
fromabcimportABC,abstractmethod
importcalendar
fromcollectionsimportdeque
fromdatetimeimportdatetime,timedelta,tzinfo
importre
fromstringimportdigits
importtime
importwarnings
fromgit.utilimportActor,IterableList,IterableObj
# typing ------------------------------------------------------------
fromtypingimport (
Any,
Callable,
Deque,
Iterator,
NamedTuple,
Sequence,
TYPE_CHECKING,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
)
fromgit.typesimportHas_id_attribute,Literal
ifTYPE_CHECKING:
fromioimportBytesIO,StringIO
fromsubprocessimportPopen
fromgit.typesimportProtocol,runtime_checkable
from .blobimportBlob
from .commitimportCommit
from .submodule.baseimportSubmodule
from .tagimportTagObject
from .treeimportTraversedTreeTup,Tree
else:
Protocol=ABC
defruntime_checkable(f):
returnf
classTraverseNT(NamedTuple):
depth:int
item:Union["Traversable","Blob"]
src:Union["Traversable",None]
T_TIobj=TypeVar("T_TIobj",bound="TraversableIterableObj")# For TraversableIterableObj.traverse()
TraversedTup=Union[
Tuple[Union["Traversable",None],"Traversable"],# For Commit, Submodule.
"TraversedTreeTup",# For Tree.traverse().
]
# --------------------------------------------------------------------
ZERO=timedelta(0)
# { Functions
defmode_str_to_int(modestr:Union[bytes,str])->int:
"""Convert mode bits from an octal mode string to an integer mode for git.
:param modestr:
String like ``755`` or ``644`` or ``100644`` - only the last 6 chars will be
used.
:return:
String identifying a mode compatible to the mode methods ids of the :mod:`stat`
module regarding the rwx permissions for user, group and other, special flags
and file system flags, such as whether it is a symlink.
"""
mode=0
foriteration,charinenumerate(reversed(modestr[-6:])):
char=cast(Union[str,int],char)
mode+=int(char)<<iteration*3
# END for each char
returnmode
defget_object_type_by_name(
object_type_name:bytes,
)->Union[Type["Commit"],Type["TagObject"],Type["Tree"],Type["Blob"]]:
"""Retrieve the Python class GitPython uses to represent a kind of Git object.
:return:
A type suitable to handle the given as `object_type_name`.
This type can be called create new instances.
:param object_type_name:
Member of :attr:`Object.TYPES <git.objects.base.Object.TYPES>`.
:raise ValueError:
If `object_type_name` is unknown.
"""
ifobject_type_name==b"commit":
from .importcommit
returncommit.Commit
elifobject_type_name==b"tag":
from .importtag
returntag.TagObject
elifobject_type_name==b"blob":
from .importblob
returnblob.Blob
elifobject_type_name==b"tree":
from .importtree
returntree.Tree
else:
raiseValueError("Cannot handle unknown object type: %s"%object_type_name.decode())
defutctz_to_altz(utctz:str)->int:
"""Convert a git timezone offset into a timezone offset west of UTC in seconds
(compatible with :attr:`time.altzone`).
:param utctz:
git utc timezone string, e.g. +0200
"""
int_utctz=int(utctz)
seconds= (abs(int_utctz)//100)*3600+ (abs(int_utctz)%100)*60
returnsecondsifint_utctz<0else-seconds
defaltz_to_utctz_str(altz:float)->str:
"""Convert a timezone offset west of UTC in seconds into a Git timezone offset
string.
:param altz:
Timezone offset in seconds west of UTC.
"""
hours=abs(altz)//3600
minutes= (abs(altz)%3600)//60
sign="-"ifaltz>=60else"+"
return"{}{:02}{:02}".format(sign,hours,minutes)
defverify_utctz(offset:str)->str:
"""
:raise ValueError:
If `offset` is incorrect.
:return:
`offset`
"""
fmt_exc=ValueError("Invalid timezone offset format: %s"%offset)
iflen(offset)!=5:
raisefmt_exc
ifoffset[0]notin"+-":
raisefmt_exc
ifoffset[1]notindigitsoroffset[2]notindigitsoroffset[3]notindigitsoroffset[4]notindigits:
raisefmt_exc
# END for each char
returnoffset
classtzoffset(tzinfo):
def__init__(self,secs_west_of_utc:float,name:Union[None,str]=None)->None:
self._offset=timedelta(seconds=-secs_west_of_utc)
self._name=nameor"fixed"
def__reduce__(self)->Tuple[Type["tzoffset"],Tuple[float,str]]:
returntzoffset, (-self._offset.total_seconds(),self._name)
defutcoffset(self,dt:Union[datetime,None])->timedelta:
returnself._offset
deftzname(self,dt:Union[datetime,None])->str:
returnself._name
defdst(self,dt:Union[datetime,None])->timedelta:
returnZERO
utc=tzoffset(0,"UTC")
deffrom_timestamp(timestamp:float,tz_offset:float)->datetime:
"""Convert a `timestamp` + `tz_offset` into an aware :class:`~datetime.datetime`
instance."""
utc_dt=datetime.fromtimestamp(timestamp,utc)
try:
local_dt=utc_dt.astimezone(tzoffset(tz_offset))
returnlocal_dt
exceptValueError:
returnutc_dt
defparse_date(string_date:Union[str,datetime])->Tuple[int,int]:
"""Parse the given date as one of the following:
* Aware datetime instance
* Git internal format: timestamp offset
* :rfc:`2822`: ``Thu, 07 Apr 2005 22:13:13 +0200``
* ISO 8601: ``2005-04-07T22:13:13`` - The ``T`` can be a space as well.
:return:
Tuple(int(timestamp_UTC), int(offset)), both in seconds since epoch
:raise ValueError:
If the format could not be understood.
:note:
Date can also be ``YYYY.MM.DD``, ``MM/DD/YYYY`` and ``DD.MM.YYYY``.
"""
ifisinstance(string_date,datetime):
ifstring_date.tzinfo:
utcoffset=cast(timedelta,string_date.utcoffset())# typeguard, if tzinfoand is not None
offset=-int(utcoffset.total_seconds())
returnint(string_date.astimezone(utc).timestamp()),offset
else:
raiseValueError(f"string_date datetime object without tzinfo,{string_date}")
# Git time
try:
ifstring_date.count(" ")==1andstring_date.rfind(":")==-1:
timestamp,offset_str=string_date.split()
iftimestamp.startswith("@"):
timestamp=timestamp[1:]
timestamp_int=int(timestamp)
returntimestamp_int,utctz_to_altz(verify_utctz(offset_str))
else:
offset_str="+0000"# Local time by default.
ifstring_date[-5]in"-+":
offset_str=verify_utctz(string_date[-5:])
string_date=string_date[:-6]# skip space as well
# END split timezone info
offset=utctz_to_altz(offset_str)
# Now figure out the date and time portion - split time.
date_formats= []
splitter=-1
if","instring_date:
date_formats.append("%a, %d %b %Y")
splitter=string_date.rfind(" ")
else:
# ISO plus additional
date_formats.append("%Y-%m-%d")
date_formats.append("%Y.%m.%d")
date_formats.append("%m/%d/%Y")
date_formats.append("%d.%m.%Y")
splitter=string_date.rfind("T")
ifsplitter==-1:
splitter=string_date.rfind(" ")
# END handle 'T' and ' '
# END handle RFC or ISO
assertsplitter>-1
# Split date and time.
time_part=string_date[splitter+1 :]# Skip space.
date_part=string_date[:splitter]
# Parse time.
tstruct=time.strptime(time_part,"%H:%M:%S")
forfmtindate_formats:
try:
dtstruct=time.strptime(date_part,fmt)
utctime=calendar.timegm(
(
dtstruct.tm_year,
dtstruct.tm_mon,
dtstruct.tm_mday,
tstruct.tm_hour,
tstruct.tm_min,
tstruct.tm_sec,
dtstruct.tm_wday,
dtstruct.tm_yday,
tstruct.tm_isdst,
)
)
returnint(utctime),offset
exceptValueError:
continue
# END exception handling
# END for each fmt
# Still here ? fail.
raiseValueError("no format matched")
# END handle format
exceptExceptionase:
raiseValueError(f"Unsupported date format or type:{string_date}, type={type(string_date)}")frome
# END handle exceptions
# Precompiled regexes
_re_actor_epoch=re.compile(r"^.+? (.*) (\d+) ([+-]\d+).*$")
_re_only_actor=re.compile(r"^.+? (.*)$")
defparse_actor_and_date(line:str)->Tuple[Actor,int,int]:
"""Parse out the actor (author or committer) info from a line like::
author Tom Preston-Werner <tom@mojombo.com> 1191999972 -0700
:return:
[Actor, int_seconds_since_epoch, int_timezone_offset]
"""
actor,epoch,offset="","0","0"
m=_re_actor_epoch.search(line)
ifm:
actor,epoch,offset=m.groups()
else:
m=_re_only_actor.search(line)
actor=m.group(1)ifmelselineor""
return (Actor._from_string(actor),int(epoch),utctz_to_altz(offset))
# } END functions
# { Classes
classProcessStreamAdapter:
"""Class wiring all calls to the contained Process instance.
Use this type to hide the underlying process to provide access only to a specified
stream. The process is usually wrapped into an :class:`~git.cmd.Git.AutoInterrupt`
class to kill it if the instance goes out of scope.
"""
__slots__= ("_proc","_stream")
def__init__(self,process:"Popen",stream_name:str)->None:
self._proc=process
self._stream:StringIO=getattr(process,stream_name)# guessed type
def__getattr__(self,attr:str)->Any:
returngetattr(self._stream,attr)
@runtime_checkable
classTraversable(Protocol):
"""Simple interface to perform depth-first or breadth-first traversals in one
direction.
Subclasses only need to implement one function.
Instances of the subclass must be hashable.
Defined subclasses:
* :class:`Commit <git.objects.Commit>`
* :class:`Tree <git.objects.tree.Tree>`
* :class:`Submodule <git.objects.submodule.base.Submodule>`
"""
__slots__= ()
@classmethod
@abstractmethod
def_get_intermediate_items(cls,item:Any)->Sequence["Traversable"]:
"""
:return:
Tuple of items connected to the given item.
Must be implemented in subclass.
class Commit:: (cls, Commit) -> Tuple[Commit, ...]
class Submodule:: (cls, Submodule) -> Iterablelist[Submodule]
class Tree:: (cls, Tree) -> Tuple[Tree, ...]
"""
raiseNotImplementedError("To be implemented in subclass")
@abstractmethod
deflist_traverse(self,*args:Any,**kwargs:Any)->Any:
"""Traverse self and collect all items found.
Calling this directly on the abstract base class, including via a ``super()``
proxy, is deprecated. Only overridden implementations should be called.
"""
warnings.warn(
"list_traverse() method should only be called from subclasses."
" Calling from Traversable abstract class will raise NotImplementedError in 4.0.0."
" The concrete subclasses in GitPython itself are 'Commit', 'RootModule', 'Submodule', and 'Tree'.",
DeprecationWarning,
stacklevel=2,
)
returnself._list_traverse(*args,**kwargs)
def_list_traverse(
self,as_edge:bool=False,*args:Any,**kwargs:Any
)->IterableList[Union["Commit","Submodule","Tree","Blob"]]:
"""Traverse self and collect all items found.
:return:
:class:`~git.util.IterableList` with the results of the traversal as
produced by :meth:`traverse`::
Commit -> IterableList[Commit]
Submodule -> IterableList[Submodule]
Tree -> IterableList[Union[Submodule, Tree, Blob]]
"""
# Commit and Submodule have id.__attribute__ as IterableObj.
# Tree has id.__attribute__ inherited from IndexObject.
ifisinstance(self,Has_id_attribute):
id=self._id_attribute_
else:
# Shouldn't reach here, unless Traversable subclass created with no
# _id_attribute_.
id=""
# Could add _id_attribute_ to Traversable, or make all Traversable also
# Iterable?
ifnotas_edge:
out:IterableList[Union["Commit","Submodule","Tree","Blob"]]=IterableList(id)
out.extend(self.traverse(as_edge=as_edge,*args,**kwargs))# noqa: B026
returnout
# Overloads in subclasses (mypy doesn't allow typing self: subclass).
# Union[IterableList['Commit'], IterableList['Submodule'], IterableList[Union['Submodule', 'Tree', 'Blob']]]
else:
# Raise DeprecationWarning, it doesn't make sense to use this.
out_list:IterableList=IterableList(self.traverse(*args,**kwargs))
returnout_list
@abstractmethod
deftraverse(self,*args:Any,**kwargs:Any)->Any:
"""Iterator yielding items found when traversing self.
Calling this directly on the abstract base class, including via a ``super()``
proxy, is deprecated. Only overridden implementations should be called.
"""
warnings.warn(
"traverse() method should only be called from subclasses."
" Calling from Traversable abstract class will raise NotImplementedError in 4.0.0."
" The concrete subclasses in GitPython itself are 'Commit', 'RootModule', 'Submodule', and 'Tree'.",
DeprecationWarning,
stacklevel=2,
)
returnself._traverse(*args,**kwargs)
def_traverse(
self,
predicate:Callable[[Union["Traversable","Blob",TraversedTup],int],bool]=lambdai,d:True,
prune:Callable[[Union["Traversable","Blob",TraversedTup],int],bool]=lambdai,d:False,
depth:int=-1,
branch_first:bool=True,
visit_once:bool=True,
ignore_self:int=1,
as_edge:bool=False,
)->Union[Iterator[Union["Traversable","Blob"]],Iterator[TraversedTup]]:
"""Iterator yielding items found when traversing `self`.
:param predicate:
A function ``f(i,d)`` that returns ``False`` if item i at depth ``d`` should
not be included in the result.
:param prune:
A function ``f(i,d)`` that returns ``True`` if the search should stop at
item ``i`` at depth ``d``. Item ``i`` will not be returned.
:param depth:
Defines at which level the iteration should not go deeper if -1. There is no
limit if 0, you would effectively only get `self`, the root of the
iteration. If 1, you would only get the first level of
predecessors/successors.
:param branch_first:
If ``True``, items will be returned branch first, otherwise depth first.
:param visit_once:
If ``True``, items will only be returned once, although they might be
encountered several times. Loops are prevented that way.
:param ignore_self:
If ``True``, `self` will be ignored and automatically pruned from the
result. Otherwise it will be the first item to be returned. If `as_edge` is
``True``, the source of the first edge is ``None``.
:param as_edge:
If ``True``, return a pair of items, first being the source, second the
destination, i.e. tuple(src, dest) with the edge spanning from source to
destination.
:return:
Iterator yielding items found when traversing `self`::
Commit -> Iterator[Union[Commit, Tuple[Commit, Commit]] Submodule ->
Iterator[Submodule, Tuple[Submodule, Submodule]] Tree ->
Iterator[Union[Blob, Tree, Submodule,
Tuple[Union[Submodule, Tree], Union[Blob, Tree,
Submodule]]]
ignore_self=True is_edge=True -> Iterator[item] ignore_self=True
is_edge=False --> Iterator[item] ignore_self=False is_edge=True ->
Iterator[item] | Iterator[Tuple[src, item]] ignore_self=False
is_edge=False -> Iterator[Tuple[src, item]]
"""
visited=set()
stack:Deque[TraverseNT]=deque()
stack.append(TraverseNT(0,self,None))# self is always depth level 0.
defaddToStack(
stack:Deque[TraverseNT],
src_item:"Traversable",
branch_first:bool,
depth:int,
)->None:
lst=self._get_intermediate_items(item)
ifnotlst:# Empty list
return
ifbranch_first:
stack.extendleft(TraverseNT(depth,i,src_item)foriinlst)
else:
reviter= (TraverseNT(depth,lst[i],src_item)foriinrange(len(lst)-1,-1,-1))
stack.extend(reviter)
# END addToStack local method
whilestack:
d,item,src=stack.pop()# Depth of item, item, item_source
ifvisit_onceanditeminvisited:
continue
ifvisit_once:
visited.add(item)
rval:Union[TraversedTup,"Traversable","Blob"]
ifas_edge:
# If as_edge return (src, item) unless rrc is None
# (e.g. for first item).
rval= (src,item)
else:
rval=item
ifprune(rval,d):
continue
skipStartItem=ignore_selfand (itemisself)
ifnotskipStartItemandpredicate(rval,d):
yieldrval
# Only continue to next level if this is appropriate!
next_d=d+1
ifdepth>-1andnext_d>depth:
continue
addToStack(stack,item,branch_first,next_d)
# END for each item on work stack
@runtime_checkable
classSerializable(Protocol):
"""Defines methods to serialize and deserialize objects from and into a data
stream."""
__slots__= ()
# @abstractmethod
def_serialize(self,stream:"BytesIO")->"Serializable":
"""Serialize the data of this object into the given data stream.
:note:
A serialized object would :meth:`_deserialize` into the same object.
:param stream:
A file-like object.
:return:
self
"""
raiseNotImplementedError("To be implemented in subclass")
# @abstractmethod
def_deserialize(self,stream:"BytesIO")->"Serializable":
"""Deserialize all information regarding this object from the stream.
:param stream:
A file-like object.
:return:
self
"""
raiseNotImplementedError("To be implemented in subclass")
classTraversableIterableObj(IterableObj,Traversable):
__slots__= ()
TIobj_tuple=Tuple[Union[T_TIobj,None],T_TIobj]
deflist_traverse(self:T_TIobj,*args:Any,**kwargs:Any)->IterableList[T_TIobj]:
returnsuper()._list_traverse(*args,**kwargs)
@overload
deftraverse(self:T_TIobj)->Iterator[T_TIobj]: ...
@overload
deftraverse(
self:T_TIobj,
predicate:Callable[[Union[T_TIobj,Tuple[Union[T_TIobj,None],T_TIobj]],int],bool],
prune:Callable[[Union[T_TIobj,Tuple[Union[T_TIobj,None],T_TIobj]],int],bool],
depth:int,
branch_first:bool,
visit_once:bool,
ignore_self:Literal[True],
as_edge:Literal[False],
)->Iterator[T_TIobj]: ...
@overload
deftraverse(
self:T_TIobj,
predicate:Callable[[Union[T_TIobj,Tuple[Union[T_TIobj,None],T_TIobj]],int],bool],
prune:Callable[[Union[T_TIobj,Tuple[Union[T_TIobj,None],T_TIobj]],int],bool],
depth:int,
branch_first:bool,
visit_once:bool,
ignore_self:Literal[False],
as_edge:Literal[True],
)->Iterator[Tuple[Union[T_TIobj,None],T_TIobj]]: ...
@overload
deftraverse(
self:T_TIobj,
predicate:Callable[[Union[T_TIobj,TIobj_tuple],int],bool],
prune:Callable[[Union[T_TIobj,TIobj_tuple],int],bool],
depth:int,
branch_first:bool,
visit_once:bool,
ignore_self:Literal[True],
as_edge:Literal[True],
)->Iterator[Tuple[T_TIobj,T_TIobj]]: ...
deftraverse(
self:T_TIobj,
predicate:Callable[[Union[T_TIobj,TIobj_tuple],int],bool]=lambdai,d:True,
prune:Callable[[Union[T_TIobj,TIobj_tuple],int],bool]=lambdai,d:False,
depth:int=-1,
branch_first:bool=True,
visit_once:bool=True,
ignore_self:int=1,
as_edge:bool=False,
)->Union[Iterator[T_TIobj],Iterator[Tuple[T_TIobj,T_TIobj]],Iterator[TIobj_tuple]]:
"""For documentation, see :meth:`Traversable._traverse`."""
## To typecheck instead of using cast:
#
# import itertools
# from git.types import TypeGuard
# def is_commit_traversed(inp: Tuple) -> TypeGuard[Tuple[Iterator[Tuple['Commit', 'Commit']]]]:
# for x in inp[1]:
# if not isinstance(x, tuple) and len(x) != 2:
# if all(isinstance(inner, Commit) for inner in x):
# continue
# return True
#
# ret = super(Commit, self).traverse(predicate, prune, depth, branch_first, visit_once, ignore_self, as_edge)
# ret_tup = itertools.tee(ret, 2)
# assert is_commit_traversed(ret_tup), f"{[type(x) for x in list(ret_tup[0])]}"
# return ret_tup[0]
returncast(
Union[Iterator[T_TIobj],Iterator[Tuple[Union[None,T_TIobj],T_TIobj]]],
super()._traverse(
predicate,# type: ignore[arg-type]
prune,# type: ignore[arg-type]
depth,
branch_first,
visit_once,
ignore_self,
as_edge,
),
)