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 pathtree.py
More file actions
418 lines (333 loc) · 13.6 KB
/
tree.py
File metadata and controls
418 lines (333 loc) · 13.6 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
# 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/
__all__= ["TreeModifier","Tree"]
importos
importsys
importgit.diffasgit_diff
fromgit.utilimportIterableList,join_path,to_bin_sha
from .importutil
from .baseimportIndexObjUnion,IndexObject
from .blobimportBlob
from .funimporttree_entries_from_data,tree_to_stream
from .submodule.baseimportSubmodule
# typing -------------------------------------------------
fromtypingimport (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Tuple,
TYPE_CHECKING,
Type,
Union,
cast,
)
ifsys.version_info>= (3,8):
fromtypingimportLiteral
else:
fromtyping_extensionsimportLiteral
fromgit.typesimportPathLike
ifTYPE_CHECKING:
fromioimportBytesIO
fromgit.repoimportRepo
TreeCacheTup=Tuple[bytes,int,str]
TraversedTreeTup=Union[Tuple[Union["Tree",None],IndexObjUnion,Tuple["Submodule","Submodule"]]]
# --------------------------------------------------------
defcmp(a:str,b:str)->int:
return (a>b)- (a<b)
classTreeModifier:
"""A utility class providing methods to alter the underlying cache in a list-like
fashion.
Once all adjustments are complete, the :attr:`_cache`, which really is a reference
to the cache of a tree, will be sorted. This ensures it will be in a serializable
state.
"""
__slots__= ("_cache",)
def__init__(self,cache:List[TreeCacheTup])->None:
self._cache=cache
def_index_by_name(self,name:str)->int:
""":return: index of an item with name, or -1 if not found"""
fori,tinenumerate(self._cache):
ift[2]==name:
returni
# END found item
# END for each item in cache
return-1
# { Interface
defset_done(self)->"TreeModifier":
"""Call this method once you are done modifying the tree information.
This may be called several times, but be aware that each call will cause a sort
operation.
:return:
self
"""
self._cache.sort(key=lambdax: (x[2]+"/")ifx[1]==Tree.tree_id<<12elsex[2])
returnself
# } END interface
# { Mutators
defadd(self,sha:bytes,mode:int,name:str,force:bool=False)->"TreeModifier":
"""Add the given item to the tree.
If an item with the given name already exists, nothing will be done, but a
:exc:`ValueError` will be raised if the sha and mode of the existing item do not
match the one you add, unless `force` is ``True``.
:param sha:
The 20 or 40 byte sha of the item to add.
:param mode:
:class:`int` representing the stat-compatible mode of the item.
:param force:
If ``True``, an item with your name and information will overwrite any
existing item with the same name, no matter which information it has.
:return:
self
"""
if"/"inname:
raiseValueError("Name must not contain '/' characters")
if (mode>>12)notinTree._map_id_to_type:
raiseValueError("Invalid object type according to mode %o"%mode)
sha=to_bin_sha(sha)
index=self._index_by_name(name)
item= (sha,mode,name)
ifindex==-1:
self._cache.append(item)
else:
ifforce:
self._cache[index]=item
else:
ex_item=self._cache[index]
ifex_item[0]!=shaorex_item[1]!=mode:
raiseValueError("Item %r existed with different properties"%name)
# END handle mismatch
# END handle force
# END handle name exists
returnself
defadd_unchecked(self,binsha:bytes,mode:int,name:str)->None:
"""Add the given item to the tree. Its correctness is assumed, so it is the
caller's responsibility to ensure that the input is correct.
For more information on the parameters, see :meth:`add`.
:param binsha:
20 byte binary sha.
"""
assertisinstance(binsha,bytes)andisinstance(mode,int)andisinstance(name,str)
tree_cache= (binsha,mode,name)
self._cache.append(tree_cache)
def__delitem__(self,name:str)->None:
"""Delete an item with the given name if it exists."""
index=self._index_by_name(name)
ifindex>-1:
delself._cache[index]
# } END mutators
classTree(IndexObject,git_diff.Diffable,util.Traversable,util.Serializable):
R"""Tree objects represent an ordered list of :class:`~git.objects.blob.Blob`\s and
other :class:`Tree`\s.
See :manpage:`gitglossary(7)` on "tree object":
https://git-scm.com/docs/gitglossary#def_tree_object
Subscripting is supported, as with a list or dict:
* Access a specific blob using the ``tree["filename"]`` notation.
* You may likewise access by index, like ``blob = tree[0]``.
"""
type:Literal["tree"]="tree"
__slots__= ("_cache",)
# Actual integer IDs for comparison.
commit_id=0o16# Equals stat.S_IFDIR | stat.S_IFLNK - a directory link.
blob_id=0o10
symlink_id=0o12
tree_id=0o04
_map_id_to_type:Dict[int,Type[IndexObjUnion]]= {
commit_id:Submodule,
blob_id:Blob,
symlink_id:Blob,
# Tree ID added once Tree is defined.
}
def__init__(
self,
repo:"Repo",
binsha:bytes,
mode:int=tree_id<<12,
path:Union[PathLike,None]=None,
):
super().__init__(repo,binsha,mode,path)
@classmethod
def_get_intermediate_items(
cls,
index_object:IndexObjUnion,
)->Union[Tuple["Tree", ...],Tuple[()]]:
ifindex_object.type=="tree":
returntuple(index_object._iter_convert_to_object(index_object._cache))
return ()
def_set_cache_(self,attr:str)->None:
ifattr=="_cache":
# Set the data when we need it.
ostream=self.repo.odb.stream(self.binsha)
self._cache:List[TreeCacheTup]=tree_entries_from_data(ostream.read())
else:
super()._set_cache_(attr)
# END handle attribute
def_iter_convert_to_object(self,iterable:Iterable[TreeCacheTup])->Iterator[IndexObjUnion]:
"""Iterable yields tuples of (binsha, mode, name), which will be converted to
the respective object representation.
"""
forbinsha,mode,nameiniterable:
path=join_path(self.path,name)
try:
yieldself._map_id_to_type[mode>>12](self.repo,binsha,mode,path)
exceptKeyErrorase:
raiseTypeError("Unknown mode %o found in tree data for path '%s'"% (mode,path))frome
# END for each item
defjoin(self,file:PathLike)->IndexObjUnion:
"""Find the named object in this tree's contents.
:return:
:class:`~git.objects.blob.Blob`, :class:`Tree`, or
:class:`~git.objects.submodule.base.Submodule`
:raise KeyError:
If the given file or tree does not exist in this tree.
"""
msg="Blob or Tree named %r not found"
file=os.fspath(file)
if"/"infile:
tree=self
item=self
tokens=file.split("/")
fori,tokeninenumerate(tokens):
item=tree[token]
ifitem.type=="tree":
tree=item
else:
# Safety assertion - blobs are at the end of the path.
ifi!=len(tokens)-1:
raiseKeyError(msg%file)
returnitem
# END handle item type
# END for each token of split path
ifitem==self:
raiseKeyError(msg%file)
returnitem
else:
forinfoinself._cache:
ifinfo[2]==file:# [2] == name
returnself._map_id_to_type[info[1]>>12](
self.repo,info[0],info[1],join_path(self.path,info[2])
)
# END for each obj
raiseKeyError(msg%file)
# END handle long paths
def__truediv__(self,file:PathLike)->IndexObjUnion:
"""The ``/`` operator is another syntax for joining.
See :meth:`join` for details.
"""
returnself.join(file)
@property
deftrees(self)->List["Tree"]:
""":return: list(Tree, ...) List of trees directly below this tree"""
return [iforiinselfifi.type=="tree"]
@property
defblobs(self)->List[Blob]:
""":return: list(Blob, ...) List of blobs directly below this tree"""
return [iforiinselfifi.type=="blob"]
@property
defcache(self)->TreeModifier:
"""
:return:
An object allowing modification of the internal cache. This can be used to
change the tree's contents. When done, make sure you call
:meth:`~TreeModifier.set_done` on the tree modifier, or serialization
behaviour will be incorrect.
:note:
See :class:`TreeModifier` for more information on how to alter the cache.
"""
returnTreeModifier(self._cache)
deftraverse(
self,
predicate:Callable[[Union[IndexObjUnion,TraversedTreeTup],int],bool]=lambdai,d:True,
prune:Callable[[Union[IndexObjUnion,TraversedTreeTup],int],bool]=lambdai,d:False,
depth:int=-1,
branch_first:bool=True,
visit_once:bool=False,
ignore_self:int=1,
as_edge:bool=False,
)->Union[Iterator[IndexObjUnion],Iterator[TraversedTreeTup]]:
"""For documentation, see
`Traversable._traverse() <git.objects.util.Traversable._traverse>`.
Trees are set to ``visit_once = False`` to gain more performance in the
traversal.
"""
# # To typecheck instead of using cast.
# import itertools
# def is_tree_traversed(inp: Tuple) -> TypeGuard[Tuple[Iterator[Union['Tree', 'Blob', 'Submodule']]]]:
# return all(isinstance(x, (Blob, Tree, Submodule)) for x in inp[1])
# ret = super().traverse(predicate, prune, depth, branch_first, visit_once, ignore_self)
# ret_tup = itertools.tee(ret, 2)
# assert is_tree_traversed(ret_tup), f"Type is {[type(x) for x in list(ret_tup[0])]}"
# return ret_tup[0]
returncast(
Union[Iterator[IndexObjUnion],Iterator[TraversedTreeTup]],
super()._traverse(
predicate,# type: ignore[arg-type]
prune,# type: ignore[arg-type]
depth,
branch_first,
visit_once,
ignore_self,
),
)
deflist_traverse(self,*args:Any,**kwargs:Any)->IterableList[IndexObjUnion]:
"""
:return:
:class:`~git.util.IterableList` with the results of the traversal as
produced by :meth:`traverse`
Tree -> IterableList[Union[Submodule, Tree, Blob]]
"""
returnsuper()._list_traverse(*args,**kwargs)
# List protocol
def__getslice__(self,i:int,j:int)->List[IndexObjUnion]:
returnlist(self._iter_convert_to_object(self._cache[i:j]))
def__iter__(self)->Iterator[IndexObjUnion]:
returnself._iter_convert_to_object(self._cache)
def__len__(self)->int:
returnlen(self._cache)
def__getitem__(self,item:Union[str,int,slice])->IndexObjUnion:
ifisinstance(item,int):
info=self._cache[item]
returnself._map_id_to_type[info[1]>>12](self.repo,info[0],info[1],join_path(self.path,info[2]))
ifisinstance(item,str):
# compatibility
returnself.join(item)
# END index is basestring
raiseTypeError("Invalid index type: %r"%item)
def__contains__(self,item:Union[IndexObjUnion,PathLike])->bool:
ifisinstance(item,IndexObject):
forinfoinself._cache:
ifitem.binsha==info[0]:
returnTrue
# END compare sha
# END for each entry
# END handle item is index object
# compatibility
# Treat item as repo-relative path.
else:
path=self.path
forinfoinself._cache:
ifitem==join_path(path,info[2]):
returnTrue
# END for each item
returnFalse
def__reversed__(self)->Iterator[IndexObjUnion]:
returnreversed(self._iter_convert_to_object(self._cache))# type: ignore[call-overload]
def_serialize(self,stream:"BytesIO")->"Tree":
"""Serialize this tree into the stream. Assumes sorted tree data.
:note:
We will assume our tree data to be in a sorted state. If this is not the
case, serialization will not generate a correct tree representation as these
are assumed to be sorted by algorithms.
"""
tree_to_stream(self._cache,stream.write)
returnself
def_deserialize(self,stream:"BytesIO")->"Tree":
self._cache=tree_entries_from_data(stream.read())
returnself
# END tree
# Finalize map definition.
Tree._map_id_to_type[Tree.tree_id]=Tree