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
425 lines (354 loc) · 13.5 KB
/
fun.py
File metadata and controls
425 lines (354 loc) · 13.5 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
# This module is part of GitPython and is released under the
# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
"""General repository-related functions."""
from __future__importannotations
__all__= [
"rev_parse",
"is_git_dir",
"touch",
"find_submodule_git_dir",
"name_to_object",
"short_to_long",
"deref_tag",
"to_commit",
"find_worktree_git_dir",
]
importos
importos.pathasosp
frompathlibimportPath
importstat
fromstringimportdigits
fromgitdb.excimportBadName,BadObject
fromgit.cmdimportGit
fromgit.excimportWorkTreeRepositoryUnsupported
fromgit.objectsimportObject
fromgit.refsimportSymbolicReference
fromgit.utilimportcygpath,bin_to_hex,hex_to_bin
# Typing ----------------------------------------------------------------------
fromtypingimportOptional,TYPE_CHECKING,Union,cast,overload
fromgit.typesimportAnyGitObject,Literal,PathLike
ifTYPE_CHECKING:
fromgit.dbimportGitCmdObjectDB
fromgit.objectsimportCommit,TagObject
fromgit.refs.referenceimportReference
fromgit.refs.tagimportTag
from .baseimportRepo
# ----------------------------------------------------------------------------
deftouch(filename:str)->str:
withopen(filename,"ab"):
pass
returnfilename
defis_git_dir(d:PathLike)->bool:
"""This is taken from the git setup.c:is_git_directory function.
:raise git.exc.WorkTreeRepositoryUnsupported:
If it sees a worktree directory. It's quite hacky to do that here, but at least
clearly indicates that we don't support it. There is the unlikely danger to
throw if we see directories which just look like a worktree dir, but are none.
"""
ifosp.isdir(d):
if (osp.isdir(osp.join(d,"objects"))or"GIT_OBJECT_DIRECTORY"inos.environ)andosp.isdir(
osp.join(d,"refs")
):
headref=osp.join(d,"HEAD")
returnosp.isfile(headref)or (osp.islink(headref)andos.readlink(headref).startswith("refs"))
elif (
osp.isfile(osp.join(d,"gitdir"))
andosp.isfile(osp.join(d,"commondir"))
andosp.isfile(osp.join(d,"gitfile"))
):
raiseWorkTreeRepositoryUnsupported(d)
returnFalse
deffind_worktree_git_dir(dotgit:PathLike)->Optional[str]:
"""Search for a gitdir for this worktree."""
try:
statbuf=os.stat(dotgit)
exceptOSError:
returnNone
ifnotstat.S_ISREG(statbuf.st_mode):
returnNone
try:
lines=Path(dotgit).read_text().splitlines()
forkey,valuein [line.strip().split(": ")forlineinlines]:
ifkey=="gitdir":
returnvalue
exceptValueError:
pass
returnNone
deffind_submodule_git_dir(d:PathLike)->Optional[PathLike]:
"""Search for a submodule repo."""
ifis_git_dir(d):
returnd
try:
withopen(d)asfp:
content=fp.read().rstrip()
exceptIOError:
# It's probably not a file.
pass
else:
ifcontent.startswith("gitdir: "):
path=content[8:]
ifGit.is_cygwin():
# Cygwin creates submodules prefixed with `/cygdrive/...`.
# Cygwin git understands Cygwin paths much better than Windows ones.
# Also the Cygwin tests are assuming Cygwin paths.
path=cygpath(path)
ifnotosp.isabs(path):
path=osp.normpath(osp.join(osp.dirname(d),path))
returnfind_submodule_git_dir(path)
# END handle exception
returnNone
defshort_to_long(odb:"GitCmdObjectDB",hexsha:str)->Optional[bytes]:
"""
:return:
Long hexadecimal sha1 from the given less than 40 byte hexsha, or ``None`` if no
candidate could be found.
:param hexsha:
hexsha with less than 40 bytes.
"""
try:
returnbin_to_hex(odb.partial_to_complete_sha_hex(hexsha))
exceptBadObject:
returnNone
# END exception handling
@overload
defname_to_object(repo:"Repo",name:str,return_ref:Literal[False]= ...)->AnyGitObject: ...
@overload
defname_to_object(repo:"Repo",name:str,return_ref:Literal[True])->Union[AnyGitObject,SymbolicReference]: ...
defname_to_object(repo:"Repo",name:str,return_ref:bool=False)->Union[AnyGitObject,SymbolicReference]:
"""
:return:
Object specified by the given name - hexshas (short and long) as well as
references are supported.
:param return_ref:
If ``True``, and name specifies a reference, we will return the reference
instead of the object. Otherwise it will raise :exc:`~gitdb.exc.BadObject` or
:exc:`~gitdb.exc.BadName`.
"""
hexsha:Union[None,str,bytes]=None
# Is it a hexsha? Try the most common ones, which is 7 to 40.
ifrepo.re_hexsha_shortened.match(name):
iflen(name)!=40:
# Find long sha for short sha.
hexsha=short_to_long(repo.odb,name)
else:
hexsha=name
# END handle short shas
# END find sha if it matches
# If we couldn't find an object for what seemed to be a short hexsha, try to find it
# as reference anyway, it could be named 'aaa' for instance.
ifhexshaisNone:
forbasein (
"%s",
"refs/%s",
"refs/tags/%s",
"refs/heads/%s",
"refs/remotes/%s",
"refs/remotes/%s/HEAD",
):
try:
hexsha=SymbolicReference.dereference_recursive(repo,base%name)
ifreturn_ref:
returnSymbolicReference(repo,base%name)
# END handle symbolic ref
break
exceptValueError:
pass
# END for each base
# END handle hexsha
# Didn't find any ref, this is an error.
ifreturn_ref:
raiseBadObject("Couldn't find reference named %r"%name)
# END handle return ref
# Tried everything ? fail.
ifhexshaisNone:
raiseBadName(name)
# END assert hexsha was found
returnObject.new_from_sha(repo,hex_to_bin(hexsha))
defderef_tag(tag:"Tag")->AnyGitObject:
"""Recursively dereference a tag and return the resulting object."""
whileTrue:
try:
tag=tag.object
exceptAttributeError:
break
# END dereference tag
returntag
defto_commit(obj:Object)->"Commit":
"""Convert the given object to a commit if possible and return it."""
ifobj.type=="tag":
obj=deref_tag(obj)
ifobj.type!="commit":
raiseValueError("Cannot convert object %r to type commit"%obj)
# END verify type
returnobj
defrev_parse(repo:"Repo",rev:str)->AnyGitObject:
"""Parse a revision string. Like :manpage:`git-rev-parse(1)`.
:return:
`~git.objects.base.Object` at the given revision.
This may be any type of git object:
* :class:`Commit <git.objects.commit.Commit>`
* :class:`TagObject <git.objects.tag.TagObject>`
* :class:`Tree <git.objects.tree.Tree>`
* :class:`Blob <git.objects.blob.Blob>`
:param rev:
:manpage:`git-rev-parse(1)`-compatible revision specification as string.
Please see :manpage:`git-rev-parse(1)` for details.
:raise gitdb.exc.BadObject:
If the given revision could not be found.
:raise ValueError:
If `rev` couldn't be parsed.
:raise IndexError:
If an invalid reflog index is specified.
"""
# Are we in colon search mode?
ifrev.startswith(":/"):
# Colon search mode
raiseNotImplementedError("commit by message search (regex)")
# END handle search
obj:Optional[AnyGitObject]=None
ref=None
output_type="commit"
start=0
parsed_to=0
lr=len(rev)
whilestart<lr:
ifrev[start]notin"^~:@":
start+=1
continue
# END handle start
token=rev[start]
ifobjisNone:
# token is a rev name.
ifstart==0:
ref=repo.head.ref
else:
iftoken=="@":
ref=cast("Reference",name_to_object(repo,rev[:start],return_ref=True))
else:
obj=name_to_object(repo,rev[:start])
# END handle token
# END handle refname
else:
ifrefisnotNone:
obj=ref.commit
# END handle ref
# END initialize obj on first token
start+=1
# Try to parse {type}.
ifstart<lrandrev[start]=="{":
end=rev.find("}",start)
ifend==-1:
raiseValueError("Missing closing brace to define type in %s"%rev)
output_type=rev[start+1 :end]# Exclude brace.
# Handle type.
ifoutput_type=="commit":
obj=cast("TagObject",obj)
ifobjandobj.type=="tag":
obj=deref_tag(obj)
else:
# Cannot do anything for non-tags.
pass
# END handle tag
elifoutput_type=="tree":
try:
obj=cast(AnyGitObject,obj)
obj=to_commit(obj).tree
except (AttributeError,ValueError):
pass# Error raised later.
# END exception handling
elifoutput_typein ("","blob"):
obj=cast("TagObject",obj)
ifobjandobj.type=="tag":
obj=deref_tag(obj)
else:
# Cannot do anything for non-tags.
pass
# END handle tag
eliftoken=="@":
# try single int
assertrefisnotNone,"Require Reference to access reflog"
revlog_index=None
try:
# Transform reversed index into the format of our revlog.
revlog_index=-(int(output_type)+1)
exceptValueErrorase:
# TODO: Try to parse the other date options, using parse_date maybe.
raiseNotImplementedError("Support for additional @{...} modes not implemented")frome
# END handle revlog index
try:
entry=ref.log_entry(revlog_index)
exceptIndexErrorase:
raiseIndexError("Invalid revlog index: %i"%revlog_index)frome
# END handle index out of bound
obj=Object.new_from_sha(repo,hex_to_bin(entry.newhexsha))
# Make it pass the following checks.
output_type=""
else:
raiseValueError("Invalid output type: %s ( in %s )"% (output_type,rev))
# END handle output type
# Empty output types don't require any specific type, its just about
# dereferencing tags.
ifoutput_typeandobjandobj.type!=output_type:
raiseValueError("Could not accommodate requested object type %r, got %s"% (output_type,obj.type))
# END verify output type
start=end+1# Skip brace.
parsed_to=start
continue
# END parse type
# Try to parse a number.
num=0
iftoken!=":":
found_digit=False
whilestart<lr:
ifrev[start]indigits:
num=num*10+int(rev[start])
start+=1
found_digit=True
else:
break
# END handle number
# END number parse loop
# No explicit number given, 1 is the default. It could be 0 though.
ifnotfound_digit:
num=1
# END set default num
# END number parsing only if non-blob mode
parsed_to=start
# Handle hierarchy walk.
try:
obj=cast(AnyGitObject,obj)
iftoken=="~":
obj=to_commit(obj)
for_inrange(num):
obj=obj.parents[0]
# END for each history item to walk
eliftoken=="^":
obj=to_commit(obj)
# Must be n'th parent.
ifnum:
obj=obj.parents[num-1]
eliftoken==":":
ifobj.type!="tree":
obj=obj.tree
# END get tree type
obj=obj[rev[start:]]
parsed_to=lr
else:
raiseValueError("Invalid token: %r"%token)
# END end handle tag
except (IndexError,AttributeError)ase:
raiseBadName(
f"Invalid revision spec '{rev}' - not enough parent commits to reach '{token}{int(num)}'"
)frome
# END exception handling
# END parse loop
# Still no obj? It's probably a simple name.
ifobjisNone:
obj=name_to_object(repo,rev)
parsed_to=lr
# END handle simple name
ifobjisNone:
raiseValueError("Revision specifier could not be parsed: %s"%rev)
ifparsed_to!=lr:
raiseValueError("Didn't consume complete rev spec %s, consumed part: %s"% (rev,rev[:parsed_to]))
returnobj