Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit05825dc

Browse files
authored
Merge pull request#1308 from Yobmod/main
Add remaining types to symbolic.py
2 parents300330d +2a350b5 commit05825dc

File tree

15 files changed

+138
-100
lines changed

15 files changed

+138
-100
lines changed

‎git/cmd.py

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,10 @@
3939

4040
# typing ---------------------------------------------------------------------------
4141

42-
fromtypingimport (Any,AnyStr,BinaryIO,Callable,Dict,IO,List,Mapping,
42+
fromtypingimport (Any,AnyStr,BinaryIO,Callable,Dict,IO,Iterator,List,Mapping,
4343
Sequence,TYPE_CHECKING,TextIO,Tuple,Union,cast,overload)
4444

45-
fromgit.typesimportPathLike,Literal,TBD
45+
fromgit.typesimportPathLike,Literal
4646

4747
ifTYPE_CHECKING:
4848
fromgit.repo.baseimportRepo
@@ -146,11 +146,11 @@ def dashify(string: str) -> str:
146146
returnstring.replace('_','-')
147147

148148

149-
defslots_to_dict(self,exclude:Sequence[str]= ())->Dict[str,Any]:
149+
defslots_to_dict(self:object,exclude:Sequence[str]= ())->Dict[str,Any]:
150150
return {s:getattr(self,s)forsinself.__slots__ifsnotinexclude}
151151

152152

153-
defdict_to_slots_and__excluded_are_none(self,d:Mapping[str,Any],excluded:Sequence[str]= ())->None:
153+
defdict_to_slots_and__excluded_are_none(self:object,d:Mapping[str,Any],excluded:Sequence[str]= ())->None:
154154
fork,vind.items():
155155
setattr(self,k,v)
156156
forkinexcluded:
@@ -192,7 +192,7 @@ class Git(LazyMixin):
192192
def__getstate__(self)->Dict[str,Any]:
193193
returnslots_to_dict(self,exclude=self._excluded_)
194194

195-
def__setstate__(self,d)->None:
195+
def__setstate__(self,d:Dict[str,Any])->None:
196196
dict_to_slots_and__excluded_are_none(self,d,excluded=self._excluded_)
197197

198198
# CONFIGURATION
@@ -434,10 +434,13 @@ def wait(self, stderr: Union[None, bytes] = b'') -> int:
434434
ifself.procisnotNone:
435435
status=self.proc.wait()
436436

437-
defread_all_from_possibly_closed_stream(stream):
438-
try:
439-
returnstderr+force_bytes(stream.read())
440-
exceptValueError:
437+
defread_all_from_possibly_closed_stream(stream:Union[IO[bytes],None])->bytes:
438+
ifstream:
439+
try:
440+
returnstderr+force_bytes(stream.read())
441+
exceptValueError:
442+
returnstderrorb''
443+
else:
441444
returnstderrorb''
442445

443446
ifstatus!=0:
@@ -907,7 +910,7 @@ def _kill_process(pid: int) -> None:
907910
ifself.GIT_PYTHON_TRACE=='full':
908911
cmdstr=" ".join(redacted_command)
909912

910-
defas_text(stdout_value):
913+
defas_text(stdout_value:Union[bytes,str])->str:
911914
returnnotoutput_streamandsafe_decode(stdout_value)or'<OUTPUT_STREAM>'
912915
# end
913916

@@ -932,10 +935,10 @@ def as_text(stdout_value):
932935
else:
933936
returnstdout_value
934937

935-
defenvironment(self):
938+
defenvironment(self)->Dict[str,str]:
936939
returnself._environment
937940

938-
defupdate_environment(self,**kwargs):
941+
defupdate_environment(self,**kwargs:Any)->Dict[str,Union[str,None]]:
939942
"""
940943
Set environment variables for future git invocations. Return all changed
941944
values in a format that can be passed back into this function to revert
@@ -962,7 +965,7 @@ def update_environment(self, **kwargs):
962965
returnold_env
963966

964967
@contextmanager
965-
defcustom_environment(self,**kwargs):
968+
defcustom_environment(self,**kwargs:Any)->Iterator[None]:
966969
"""
967970
A context manager around the above ``update_environment`` method to restore the
968971
environment back to its previous state after operation.
@@ -1043,6 +1046,13 @@ def _call_process(self, method: str, *args: None, **kwargs: None
10431046
)->str:
10441047
...# if no args given, execute called with all defaults
10451048

1049+
@overload
1050+
def_call_process(self,method:str,
1051+
istream:int,
1052+
as_process:Literal[True],
1053+
*args:Any,**kwargs:Any
1054+
)->'Git.AutoInterrupt': ...
1055+
10461056
@overload
10471057
def_call_process(self,method:str,*args:Any,**kwargs:Any
10481058
)->Union[str,bytes,Tuple[int,Union[str,bytes],str],'Git.AutoInterrupt']:
@@ -1156,7 +1166,7 @@ def _prepare_ref(self, ref: AnyStr) -> bytes:
11561166
returnrefstr.encode(defenc)
11571167

11581168
def_get_persistent_cmd(self,attr_name:str,cmd_name:str,*args:Any,**kwargs:Any
1159-
)->Union['Git.AutoInterrupt',TBD]:
1169+
)->'Git.AutoInterrupt':
11601170
cur_val=getattr(self,attr_name)
11611171
ifcur_valisnotNone:
11621172
returncur_val
@@ -1166,12 +1176,16 @@ def _get_persistent_cmd(self, attr_name: str, cmd_name: str, *args: Any, **kwarg
11661176

11671177
cmd=self._call_process(cmd_name,*args,**options)
11681178
setattr(self,attr_name,cmd)
1179+
cmd=cast('Git.AutoInterrupt',cmd)
11691180
returncmd
11701181

1171-
def__get_object_header(self,cmd,ref:AnyStr)->Tuple[str,str,int]:
1172-
cmd.stdin.write(self._prepare_ref(ref))
1173-
cmd.stdin.flush()
1174-
returnself._parse_object_header(cmd.stdout.readline())
1182+
def__get_object_header(self,cmd:'Git.AutoInterrupt',ref:AnyStr)->Tuple[str,str,int]:
1183+
ifcmd.stdinandcmd.stdout:
1184+
cmd.stdin.write(self._prepare_ref(ref))
1185+
cmd.stdin.flush()
1186+
returnself._parse_object_header(cmd.stdout.readline())
1187+
else:
1188+
raiseValueError("cmd stdin was empty")
11751189

11761190
defget_object_header(self,ref:str)->Tuple[str,str,int]:
11771191
""" Use this method to quickly examine the type and size of the object behind
@@ -1200,7 +1214,8 @@ def stream_object_data(self, ref: str) -> Tuple[str, str, int, 'Git.CatFileConte
12001214
:note: This method is not threadsafe, you need one independent Command instance per thread to be safe !"""
12011215
cmd=self._get_persistent_cmd("cat_file_all","cat_file",batch=True)
12021216
hexsha,typename,size=self.__get_object_header(cmd,ref)
1203-
return (hexsha,typename,size,self.CatFileContentStream(size,cmd.stdout))
1217+
cmd_stdout=cmd.stdoutifcmd.stdoutisnotNoneelseio.BytesIO()
1218+
return (hexsha,typename,size,self.CatFileContentStream(size,cmd_stdout))
12041219

12051220
defclear_cache(self)->'Git':
12061221
"""Clear all kinds of internal caches to release resources.

‎git/config.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,15 @@
4040
fromioimportBytesIO
4141

4242
T_ConfigParser=TypeVar('T_ConfigParser',bound='GitConfigParser')
43+
T_OMD_value=TypeVar('T_OMD_value',str,bytes,int,float,bool)
4344

4445
ifsys.version_info[:3]< (3,7,2):
4546
# typing.Ordereddict not added until py 3.7.2
4647
fromcollectionsimportOrderedDict# type: ignore # until 3.6 dropped
4748
OrderedDict_OMD=OrderedDict# type: ignore # until 3.6 dropped
4849
else:
4950
fromtypingimportOrderedDict# type: ignore # until 3.6 dropped
50-
OrderedDict_OMD=OrderedDict[str,List[_T]]# type: ignore[assignment, misc]
51+
OrderedDict_OMD=OrderedDict[str,List[T_OMD_value]]# type: ignore[assignment, misc]
5152

5253
# -------------------------------------------------------------
5354

@@ -97,23 +98,23 @@ def __new__(cls, name: str, bases: TBD, clsdict: Dict[str, Any]) -> TBD:
9798
returnnew_type
9899

99100

100-
defneeds_values(func:Callable)->Callable:
101+
defneeds_values(func:Callable[...,_T])->Callable[...,_T]:
101102
"""Returns method assuring we read values (on demand) before we try to access them"""
102103

103104
@wraps(func)
104-
defassure_data_present(self,*args:Any,**kwargs:Any)->Any:
105+
defassure_data_present(self:'GitConfigParser',*args:Any,**kwargs:Any)->_T:
105106
self.read()
106107
returnfunc(self,*args,**kwargs)
107108
# END wrapper method
108109
returnassure_data_present
109110

110111

111-
defset_dirty_and_flush_changes(non_const_func:Callable)->Callable:
112+
defset_dirty_and_flush_changes(non_const_func:Callable[...,_T])->Callable[...,_T]:
112113
"""Return method that checks whether given non constant function may be called.
113114
If so, the instance will be set dirty.
114115
Additionally, we flush the changes right to disk"""
115116

116-
defflush_changes(self,*args:Any,**kwargs:Any)->Any:
117+
defflush_changes(self:'GitConfigParser',*args:Any,**kwargs:Any)->_T:
117118
rval=non_const_func(self,*args,**kwargs)
118119
self._dirty=True
119120
self.write()
@@ -356,7 +357,7 @@ def __enter__(self) -> 'GitConfigParser':
356357
self._acquire_lock()
357358
returnself
358359

359-
def__exit__(self,exception_type,exception_value,traceback)->None:
360+
def__exit__(self,*args:Any)->None:
360361
self.release()
361362

362363
defrelease(self)->None:
@@ -613,12 +614,15 @@ def read(self) -> None: # type: ignore[override]
613614
def_write(self,fp:IO)->None:
614615
"""Write an .ini-format representation of the configuration state in
615616
git compatible format"""
616-
defwrite_section(name,section_dict):
617+
defwrite_section(name:str,section_dict:_OMD)->None:
617618
fp.write(("[%s]\n"%name).encode(defenc))
619+
620+
values:Sequence[Union[str,bytes,int,float,bool]]
618621
for (key,values)insection_dict.items_all():
619622
ifkey=="__name__":
620623
continue
621624

625+
v:Union[str,bytes,int,float,bool]
622626
forvinvalues:
623627
fp.write(("\t%s = %s\n"% (key,self._value_to_string(v).replace('\n','\n\t'))).encode(defenc))
624628
# END if key is not __name__

‎git/index/fun.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ def read_cache(stream: IO[bytes]) -> Tuple[int, Dict[Tuple[PathLike, int], 'Inde
251251
return (version,entries,extension_data,content_sha)
252252

253253

254-
defwrite_tree_from_cache(entries:List[IndexEntry],odb,sl:slice,si:int=0
254+
defwrite_tree_from_cache(entries:List[IndexEntry],odb:'GitCmdObjectDB',sl:slice,si:int=0
255255
)->Tuple[bytes,List['TreeCacheTup']]:
256256
"""Create a tree from the given sorted list of entries and put the respective
257257
trees into the given object database

‎git/objects/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from .treeimportTree
2626
from .blobimportBlob
2727
from .submodule.baseimportSubmodule
28+
fromgit.refs.referenceimportReference
2829

2930
IndexObjUnion=Union['Tree','Blob','Submodule']
3031

@@ -59,7 +60,7 @@ def __init__(self, repo: 'Repo', binsha: bytes):
5960
assertlen(binsha)==20,"Require 20 byte binary sha, got %r, len = %i"% (binsha,len(binsha))
6061

6162
@classmethod
62-
defnew(cls,repo:'Repo',id):# @ReservedAssignment
63+
defnew(cls,repo:'Repo',id:Union[str,'Reference'])->Commit_ish:
6364
"""
6465
:return: New Object instance of a type appropriate to the object type behind
6566
id. The id of the newly created object will be a binsha even though

‎git/objects/commit.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def iter_items(cls, repo: 'Repo', rev: Union[str, 'Commit', 'SymbolicReference']
282282
proc=repo.git.rev_list(rev,args_list,as_process=True,**kwargs)
283283
returncls._iter_from_process_or_stream(repo,proc)
284284

285-
defiter_parents(self,paths:Union[PathLike,Sequence[PathLike]]='',**kwargs)->Iterator['Commit']:
285+
defiter_parents(self,paths:Union[PathLike,Sequence[PathLike]]='',**kwargs:Any)->Iterator['Commit']:
286286
"""Iterate _all_ parents of this commit.
287287
288288
:param paths:
@@ -362,7 +362,7 @@ def _iter_from_process_or_stream(cls, repo: 'Repo', proc_or_stream: Union[Popen,
362362
defcreate_from_tree(cls,repo:'Repo',tree:Union[Tree,str],message:str,
363363
parent_commits:Union[None,List['Commit']]=None,head:bool=False,
364364
author:Union[None,Actor]=None,committer:Union[None,Actor]=None,
365-
author_date:Union[None,str]=None,commit_date:Union[None,str]=None):
365+
author_date:Union[None,str]=None,commit_date:Union[None,str]=None)->'Commit':
366366
"""Commit the given tree, creating a commit object.
367367
368368
:param repo: Repo object the commit should be part of
@@ -403,7 +403,7 @@ def create_from_tree(cls, repo: 'Repo', tree: Union[Tree, str], message: str,
403403
else:
404404
forpinparent_commits:
405405
ifnotisinstance(p,cls):
406-
raiseValueError("Parent commit '%r' must be of type%s"% (p,cls))
406+
raiseValueError(f"Parent commit '{p!r}' must be of type{cls}")
407407
# end check parent commit types
408408
# END if parent commits are unset
409409

‎git/objects/submodule/base.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
ifTYPE_CHECKING:
5858
fromgit.indeximportIndexFile
5959
fromgit.repoimportRepo
60+
fromgit.refsimportHead
6061

6162

6263
# -----------------------------------------------------------------------------
@@ -265,7 +266,7 @@ def _module_abspath(cls, parent_repo: 'Repo', path: PathLike, name: str) -> Path
265266
# end
266267

267268
@classmethod
268-
def_clone_repo(cls,repo,url,path,name,**kwargs):
269+
def_clone_repo(cls,repo:'Repo',url:str,path:PathLike,name:str,**kwargs:Any)->'Repo':
269270
""":return: Repo instance of newly cloned repository
270271
:param repo: our parent repository
271272
:param url: url to clone from
@@ -279,7 +280,7 @@ def _clone_repo(cls, repo, url, path, name, **kwargs):
279280
module_abspath_dir=osp.dirname(module_abspath)
280281
ifnotosp.isdir(module_abspath_dir):
281282
os.makedirs(module_abspath_dir)
282-
module_checkout_path=osp.join(repo.working_tree_dir,path)
283+
module_checkout_path=osp.join(str(repo.working_tree_dir),path)
283284
# end
284285

285286
clone=git.Repo.clone_from(url,module_checkout_path,**kwargs)
@@ -484,7 +485,7 @@ def add(cls, repo: 'Repo', name: str, path: PathLike, url: Union[str, None] = No
484485
defupdate(self,recursive:bool=False,init:bool=True,to_latest_revision:bool=False,
485486
progress:Union['UpdateProgress',None]=None,dry_run:bool=False,
486487
force:bool=False,keep_going:bool=False,env:Union[Mapping[str,str],None]=None,
487-
clone_multi_options:Union[Sequence[TBD],None]=None):
488+
clone_multi_options:Union[Sequence[TBD],None]=None)->'Submodule':
488489
"""Update the repository of this submodule to point to the checkout
489490
we point at with the binsha of this instance.
490491
@@ -712,7 +713,7 @@ def update(self, recursive: bool = False, init: bool = True, to_latest_revision:
712713
returnself
713714

714715
@unbare_repo
715-
defmove(self,module_path,configuration=True,module=True):
716+
defmove(self,module_path:PathLike,configuration:bool=True,module:bool=True)->'Submodule':
716717
"""Move the submodule to a another module path. This involves physically moving
717718
the repository at our current path, changing the configuration, as well as
718719
adjusting our index entry accordingly.
@@ -742,7 +743,7 @@ def move(self, module_path, configuration=True, module=True):
742743
returnself
743744
# END handle no change
744745

745-
module_checkout_abspath=join_path_native(self.repo.working_tree_dir,module_checkout_path)
746+
module_checkout_abspath=join_path_native(str(self.repo.working_tree_dir),module_checkout_path)
746747
ifosp.isfile(module_checkout_abspath):
747748
raiseValueError("Cannot move repository onto a file: %s"%module_checkout_abspath)
748749
# END handle target files
@@ -1160,7 +1161,7 @@ def exists(self) -> bool:
11601161
# END handle object state consistency
11611162

11621163
@property
1163-
defbranch(self):
1164+
defbranch(self)->'Head':
11641165
""":return: The branch instance that we are to checkout
11651166
:raise InvalidGitRepositoryError: if our module is not yet checked out"""
11661167
returnmkhead(self.module(),self._branch_path)

‎git/objects/tree.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -375,8 +375,8 @@ def __contains__(self, item: Union[IndexObjUnion, PathLike]) -> bool:
375375
# END for each item
376376
returnFalse
377377

378-
def__reversed__(self):
379-
returnreversed(self._iter_convert_to_object(self._cache))
378+
def__reversed__(self)->Iterator[IndexObjUnion]:
379+
returnreversed(self._iter_convert_to_object(self._cache))# type: ignore
380380

381381
def_serialize(self,stream:'BytesIO')->'Tree':
382382
"""Serialize this tree into the stream. Please note that we will assume

‎git/objects/util.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -144,20 +144,20 @@ def __init__(self, secs_west_of_utc: float, name: Union[None, str] = None) -> No
144144
def__reduce__(self)->Tuple[Type['tzoffset'],Tuple[float,str]]:
145145
returntzoffset, (-self._offset.total_seconds(),self._name)
146146

147-
defutcoffset(self,dt)->timedelta:
147+
defutcoffset(self,dt:Union[datetime,None])->timedelta:
148148
returnself._offset
149149

150-
deftzname(self,dt)->str:
150+
deftzname(self,dt:Union[datetime,None])->str:
151151
returnself._name
152152

153-
defdst(self,dt)->timedelta:
153+
defdst(self,dt:Union[datetime,None])->timedelta:
154154
returnZERO
155155

156156

157157
utc=tzoffset(0,'UTC')
158158

159159

160-
deffrom_timestamp(timestamp,tz_offset:float)->datetime:
160+
deffrom_timestamp(timestamp:float,tz_offset:float)->datetime:
161161
"""Converts a timestamp + tz_offset into an aware datetime instance."""
162162
utc_dt=datetime.fromtimestamp(timestamp,utc)
163163
try:
@@ -305,7 +305,7 @@ class Traversable(Protocol):
305305

306306
@classmethod
307307
@abstractmethod
308-
def_get_intermediate_items(cls,item)->Sequence['Traversable']:
308+
def_get_intermediate_items(cls,item:Any)->Sequence['Traversable']:
309309
"""
310310
Returns:
311311
Tuple of items connected to the given item.
@@ -327,7 +327,7 @@ def list_traverse(self, *args: Any, **kwargs: Any) -> Any:
327327
stacklevel=2)
328328
returnself._list_traverse(*args,**kwargs)
329329

330-
def_list_traverse(self,as_edge=False,*args:Any,**kwargs:Any
330+
def_list_traverse(self,as_edge:bool=False,*args:Any,**kwargs:Any
331331
)->IterableList[Union['Commit','Submodule','Tree','Blob']]:
332332
"""
333333
:return: IterableList with the results of the traversal as produced by

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp