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 pathfun.py
More file actions
423 lines (359 loc) · 16 KB
/
fun.py
File metadata and controls
423 lines (359 loc) · 16 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
# Contains standalone functions to accompany the index implementation and make it
# more versatile
# NOTE: Autodoc hates it if this is a docstring
fromioimportBytesIO
frompathlibimportPath
importos
fromstatimport (
S_IFDIR,
S_IFLNK,
S_ISLNK,
S_ISDIR,
S_IFMT,
S_IFREG,
S_IXUSR,
)
importsubprocess
fromgit.cmdimportPROC_CREATIONFLAGS,handle_process_output
fromgit.compatimport (
defenc,
force_text,
force_bytes,
is_posix,
is_win,
safe_decode,
)
fromgit.excimport (
UnmergedEntriesError,
HookExecutionError
)
fromgit.objects.funimport (
tree_to_stream,
traverse_tree_recursive,
traverse_trees_recursive
)
fromgit.utilimportIndexFileSHA1Writer,finalize_process
fromgitdb.baseimportIStream
fromgitdb.typimportstr_tree_type
importos.pathasosp
from .typimport (
BaseIndexEntry,
IndexEntry,
CE_NAMEMASK,
CE_STAGESHIFT
)
from .utilimport (
pack,
unpack
)
# typing -----------------------------------------------------------------------------
fromtypingimport (Dict,IO,List,Sequence,TYPE_CHECKING,Tuple,Type,Union,cast)
fromgit.typesimportPathLike
ifTYPE_CHECKING:
from .baseimportIndexFile
fromgit.dbimportGitCmdObjectDB
fromgit.objects.treeimportTreeCacheTup
# from git.objects.fun import EntryTupOrNone
# ------------------------------------------------------------------------------------
S_IFGITLINK=S_IFLNK|S_IFDIR# a submodule
CE_NAMEMASK_INV=~CE_NAMEMASK
__all__= ('write_cache','read_cache','write_tree_from_cache','entry_key',
'stat_mode_to_index_mode','S_IFGITLINK','run_commit_hook','hook_path')
defhook_path(name:str,git_dir:PathLike)->str:
""":return: path to the given named hook in the given git repository directory"""
returnosp.join(git_dir,'hooks',name)
def_has_file_extension(path):
returnosp.splitext(path)[1]
defrun_commit_hook(name:str,index:'IndexFile',*args:str)->None:
"""Run the commit hook of the given name. Silently ignores hooks that do not exist.
:param name: name of hook, like 'pre-commit'
:param index: IndexFile instance
:param args: arguments passed to hook file
:raises HookExecutionError: """
hp=hook_path(name,index.repo.git_dir)
ifnotos.access(hp,os.X_OK):
returnNone
env=os.environ.copy()
env['GIT_INDEX_FILE']=safe_decode(str(index.path))
env['GIT_EDITOR']=':'
cmd= [hp]
try:
ifis_winandnot_has_file_extension(hp):
# Windows only uses extensions to determine how to open files
# (doesn't understand shebangs). Try using bash to run the hook.
relative_hp=Path(hp).relative_to(index.repo.working_dir).as_posix()
cmd= ["bash.exe",relative_hp]
cmd=subprocess.Popen(cmd+list(args),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=index.repo.working_dir,
close_fds=is_posix,
creationflags=PROC_CREATIONFLAGS,)
exceptExceptionasex:
raiseHookExecutionError(hp,ex)fromex
else:
stdout_list:List[str]= []
stderr_list:List[str]= []
handle_process_output(cmd,stdout_list.append,stderr_list.append,finalize_process)
stdout=''.join(stdout_list)
stderr=''.join(stderr_list)
ifcmd.returncode!=0:
stdout=force_text(stdout,defenc)
stderr=force_text(stderr,defenc)
raiseHookExecutionError(hp,cmd.returncode,stderr,stdout)
# end handle return code
defstat_mode_to_index_mode(mode:int)->int:
"""Convert the given mode from a stat call to the corresponding index mode
and return it"""
ifS_ISLNK(mode):# symlinks
returnS_IFLNK
ifS_ISDIR(mode)orS_IFMT(mode)==S_IFGITLINK:# submodules
returnS_IFGITLINK
returnS_IFREG| (mode&S_IXUSRand0o755or0o644)# blobs with or without executable bit
defwrite_cache(entries:Sequence[Union[BaseIndexEntry,'IndexEntry']],stream:IO[bytes],
extension_data:Union[None,bytes]=None,
ShaStreamCls:Type[IndexFileSHA1Writer]=IndexFileSHA1Writer)->None:
"""Write the cache represented by entries to a stream
:param entries: **sorted** list of entries
:param stream: stream to wrap into the AdapterStreamCls - it is used for
final output.
:param ShaStreamCls: Type to use when writing to the stream. It produces a sha
while writing to it, before the data is passed on to the wrapped stream
:param extension_data: any kind of data to write as a trailer, it must begin
a 4 byte identifier, followed by its size ( 4 bytes )"""
# wrap the stream into a compatible writer
stream_sha=ShaStreamCls(stream)
tell=stream_sha.tell
write=stream_sha.write
# header
version=2
write(b"DIRC")
write(pack(">LL",version,len(entries)))
# body
forentryinentries:
beginoffset=tell()
write(entry.ctime_bytes)# ctime
write(entry.mtime_bytes)# mtime
path_str=str(entry.path)
path:bytes=force_bytes(path_str,encoding=defenc)
plen=len(path)&CE_NAMEMASK# path length
assertplen==len(path),"Path %s too long to fit into index"%entry.path
flags=plen| (entry.flags&CE_NAMEMASK_INV)# clear possible previous values
write(pack(">LLLLLL20sH",entry.dev,entry.inode,entry.mode,
entry.uid,entry.gid,entry.size,entry.binsha,flags))
write(path)
real_size= ((tell()-beginoffset+8)&~7)
write(b"\0"* ((beginoffset+real_size)-tell()))
# END for each entry
# write previously cached extensions data
ifextension_dataisnotNone:
stream_sha.write(extension_data)
# write the sha over the content
stream_sha.write_sha()
defread_header(stream:IO[bytes])->Tuple[int,int]:
"""Return tuple(version_long, num_entries) from the given stream"""
type_id=stream.read(4)
iftype_id!=b"DIRC":
raiseAssertionError("Invalid index file header: %r"%type_id)
unpacked=cast(Tuple[int,int],unpack(">LL",stream.read(4*2)))
version,num_entries=unpacked
# TODO: handle version 3: extended data, see read-cache.c
assertversionin (1,2)
returnversion,num_entries
defentry_key(*entry:Union[BaseIndexEntry,PathLike,int])->Tuple[PathLike,int]:
""":return: Key suitable to be used for the index.entries dictionary
:param entry: One instance of type BaseIndexEntry or the path and the stage"""
# def is_entry_key_tup(entry_key: Tuple) -> TypeGuard[Tuple[PathLike, int]]:
# return isinstance(entry_key, tuple) and len(entry_key) == 2
iflen(entry)==1:
entry_first=entry[0]
assertisinstance(entry_first,BaseIndexEntry)
return (entry_first.path,entry_first.stage)
else:
# assert is_entry_key_tup(entry)
entry=cast(Tuple[PathLike,int],entry)
returnentry
# END handle entry
defread_cache(stream:IO[bytes])->Tuple[int,Dict[Tuple[PathLike,int],'IndexEntry'],bytes,bytes]:
"""Read a cache file from the given stream
:return: tuple(version, entries_dict, extension_data, content_sha)
* version is the integer version number
* entries dict is a dictionary which maps IndexEntry instances to a path at a stage
* extension_data is '' or 4 bytes of type + 4 bytes of size + size bytes
* content_sha is a 20 byte sha on all cache file contents"""
version,num_entries=read_header(stream)
count=0
entries:Dict[Tuple[PathLike,int],'IndexEntry']= {}
read=stream.read
tell=stream.tell
whilecount<num_entries:
beginoffset=tell()
ctime=unpack(">8s",read(8))[0]
mtime=unpack(">8s",read(8))[0]
(dev,ino,mode,uid,gid,size,sha,flags)= \
unpack(">LLLLLL20sH",read(20+4*6+2))
path_size=flags&CE_NAMEMASK
path=read(path_size).decode(defenc)
real_size= ((tell()-beginoffset+8)&~7)
read((beginoffset+real_size)-tell())
entry=IndexEntry((mode,sha,flags,path,ctime,mtime,dev,ino,uid,gid,size))
# entry_key would be the method to use, but we safe the effort
entries[(path,entry.stage)]=entry
count+=1
# END for each entry
# the footer contains extension data and a sha on the content so far
# Keep the extension footer,and verify we have a sha in the end
# Extension data format is:
# 4 bytes ID
# 4 bytes length of chunk
# repeated 0 - N times
extension_data=stream.read(~0)
assertlen(extension_data)>19,"Index Footer was not at least a sha on content as it was only %i bytes in size"\
%len(extension_data)
content_sha=extension_data[-20:]
# truncate the sha in the end as we will dynamically create it anyway
extension_data=extension_data[:-20]
return (version,entries,extension_data,content_sha)
defwrite_tree_from_cache(entries:List[IndexEntry],odb:'GitCmdObjectDB',sl:slice,si:int=0
)->Tuple[bytes,List['TreeCacheTup']]:
"""Create a tree from the given sorted list of entries and put the respective
trees into the given object database
:param entries: **sorted** list of IndexEntries
:param odb: object database to store the trees in
:param si: start index at which we should start creating subtrees
:param sl: slice indicating the range we should process on the entries list
:return: tuple(binsha, list(tree_entry, ...)) a tuple of a sha and a list of
tree entries being a tuple of hexsha, mode, name"""
tree_items:List['TreeCacheTup']= []
ci=sl.start
end=sl.stop
whileci<end:
entry=entries[ci]
ifentry.stage!=0:
raiseUnmergedEntriesError(entry)
# END abort on unmerged
ci+=1
rbound=entry.path.find('/',si)
ifrbound==-1:
# its not a tree
tree_items.append((entry.binsha,entry.mode,entry.path[si:]))
else:
# find common base range
base=entry.path[si:rbound]
xi=ci
whilexi<end:
oentry=entries[xi]
orbound=oentry.path.find('/',si)
iforbound==-1oroentry.path[si:orbound]!=base:
break
# END abort on base mismatch
xi+=1
# END find common base
# enter recursion
# ci - 1 as we want to count our current item as well
sha,_tree_entry_list=write_tree_from_cache(entries,odb,slice(ci-1,xi),rbound+1)
tree_items.append((sha,S_IFDIR,base))
# skip ahead
ci=xi
# END handle bounds
# END for each entry
# finally create the tree
sio=BytesIO()
tree_to_stream(tree_items,sio.write)# writes to stream as bytes, but doesnt change tree_items
sio.seek(0)
istream=odb.store(IStream(str_tree_type,len(sio.getvalue()),sio))
return (istream.binsha,tree_items)
def_tree_entry_to_baseindexentry(tree_entry:'TreeCacheTup',stage:int)->BaseIndexEntry:
returnBaseIndexEntry((tree_entry[1],tree_entry[0],stage<<CE_STAGESHIFT,tree_entry[2]))
defaggressive_tree_merge(odb:'GitCmdObjectDB',tree_shas:Sequence[bytes])->List[BaseIndexEntry]:
"""
:return: list of BaseIndexEntries representing the aggressive merge of the given
trees. All valid entries are on stage 0, whereas the conflicting ones are left
on stage 1, 2 or 3, whereas stage 1 corresponds to the common ancestor tree,
2 to our tree and 3 to 'their' tree.
:param tree_shas: 1, 2 or 3 trees as identified by their binary 20 byte shas
If 1 or two, the entries will effectively correspond to the last given tree
If 3 are given, a 3 way merge is performed"""
out:List[BaseIndexEntry]= []
# one and two way is the same for us, as we don't have to handle an existing
# index, instrea
iflen(tree_shas)in (1,2):
forentryintraverse_tree_recursive(odb,tree_shas[-1],''):
out.append(_tree_entry_to_baseindexentry(entry,0))
# END for each entry
returnout
# END handle single tree
iflen(tree_shas)>3:
raiseValueError("Cannot handle %i trees at once"%len(tree_shas))
# three trees
forbase,ours,theirsintraverse_trees_recursive(odb,tree_shas,''):
ifbaseisnotNone:
# base version exists
ifoursisnotNone:
# ours exists
iftheirsisnotNone:
# it exists in all branches, if it was changed in both
# its a conflict, otherwise we take the changed version
# This should be the most common branch, so it comes first
if(base[0]!=ours[0]andbase[0]!=theirs[0]andours[0]!=theirs[0])or \
(base[1]!=ours[1]andbase[1]!=theirs[1]andours[1]!=theirs[1]):
# changed by both
out.append(_tree_entry_to_baseindexentry(base,1))
out.append(_tree_entry_to_baseindexentry(ours,2))
out.append(_tree_entry_to_baseindexentry(theirs,3))
elifbase[0]!=ours[0]orbase[1]!=ours[1]:
# only we changed it
out.append(_tree_entry_to_baseindexentry(ours,0))
else:
# either nobody changed it, or they did. In either
# case, use theirs
out.append(_tree_entry_to_baseindexentry(theirs,0))
# END handle modification
else:
ifours[0]!=base[0]orours[1]!=base[1]:
# they deleted it, we changed it, conflict
out.append(_tree_entry_to_baseindexentry(base,1))
out.append(_tree_entry_to_baseindexentry(ours,2))
# else:
# we didn't change it, ignore
# pass
# END handle our change
# END handle theirs
else:
iftheirsisNone:
# deleted in both, its fine - its out
pass
else:
iftheirs[0]!=base[0]ortheirs[1]!=base[1]:
# deleted in ours, changed theirs, conflict
out.append(_tree_entry_to_baseindexentry(base,1))
out.append(_tree_entry_to_baseindexentry(theirs,3))
# END theirs changed
# else:
# theirs didn't change
# pass
# END handle theirs
# END handle ours
else:
# all three can't be None
ifoursisNone:
# added in their branch
asserttheirsisnotNone
out.append(_tree_entry_to_baseindexentry(theirs,0))
eliftheirsisNone:
# added in our branch
out.append(_tree_entry_to_baseindexentry(ours,0))
else:
# both have it, except for the base, see whether it changed
ifours[0]!=theirs[0]orours[1]!=theirs[1]:
out.append(_tree_entry_to_baseindexentry(ours,2))
out.append(_tree_entry_to_baseindexentry(theirs,3))
else:
# it was added the same in both
out.append(_tree_entry_to_baseindexentry(ours,0))
# END handle two items
# END handle heads
# END handle base exists
# END for each entries tuple
returnout