Skip to content

Commit 5232c89

Browse files
committed
add types to git.__init__, compat, db, diff, exc, util
1 parent 9562ae2 commit 5232c89

File tree

11 files changed

+321
-215
lines changed

11 files changed

+321
-215
lines changed

‎git/__init__.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,20 @@
55
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
66
# flake8: noqa
77
#@PydevCodeAnalysisIgnore
8+
from git.exc import * # @NoMove @IgnorePep8
89
import inspect
910
import os
1011
import sys
11-
1212
import os.path as osp
1313

14+
from typing import Optional
15+
from git.types import PathLike
1416

1517
__version__ = 'git'
1618

1719

1820
#{ Initialization
19-
def _init_externals():
21+
def _init_externals() -> None:
2022
"""Initialize external projects by putting them into the path"""
2123
if __version__ == 'git' and 'PYOXIDIZER' not in os.environ:
2224
sys.path.insert(1, osp.join(osp.dirname(__file__), 'ext', 'gitdb'))
@@ -29,13 +31,13 @@ def _init_externals():
2931

3032
#} END initialization
3133

34+
3235
#################
3336
_init_externals()
3437
#################
3538

3639
#{ Imports
3740

38-
from git.exc import * # @NoMove @IgnorePep8
3941
try:
4042
from git.config import GitConfigParser # @NoMove @IgnorePep8
4143
from git.objects import * # @NoMove @IgnorePep8
@@ -65,7 +67,8 @@ def _init_externals():
6567
#{ Initialize git executable path
6668
GIT_OK = None
6769

68-
def refresh(path=None):
70+
71+
def refresh(path: Optional[PathLike] = None) -> None:
6972
"""Convenience method for setting the git executable path."""
7073
global GIT_OK
7174
GIT_OK = False
@@ -78,6 +81,7 @@ def refresh(path=None):
7881
GIT_OK = True
7982
#} END initialize git executable path
8083

84+
8185
#################
8286
try:
8387
refresh()

‎git/cmd.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def refresh(cls, path=None):
210210
# - a GitCommandNotFound error is spawned by ourselves
211211
# - a PermissionError is spawned if the git executable provided
212212
# cannot be executed for whatever reason
213-
213+
214214
has_git = False
215215
try:
216216
cls().version()
@@ -498,7 +498,7 @@ def readlines(self, size=-1):
498498
# skipcq: PYL-E0301
499499
def __iter__(self):
500500
return self
501-
501+
502502
def __next__(self):
503503
return self.next()
504504

@@ -639,7 +639,7 @@ def execute(self, command,
639639
640640
:param env:
641641
A dictionary of environment variables to be passed to `subprocess.Popen`.
642-
642+
643643
:param max_chunk_size:
644644
Maximum number of bytes in one chunk of data passed to the output_stream in
645645
one invocation of write() method. If the given number is not positive then

‎git/compat.py

+26-12
Original file line numberDiff line numberDiff line change
@@ -11,57 +11,71 @@
1111
import os
1212
import sys
1313

14-
1514
from gitdb.utils.encoding import (
1615
force_bytes, # @UnusedImport
1716
force_text # @UnusedImport
1817
)
1918

19+
# typing --------------------------------------------------------------------
20+
21+
from typing import Any, AnyStr, Dict, Optional, Type
22+
from git.types import TBD
23+
24+
# ---------------------------------------------------------------------------
2025

21-
is_win = (os.name == 'nt')
26+
27+
is_win = (os.name == 'nt') # type: bool
2228
is_posix = (os.name == 'posix')
2329
is_darwin = (os.name == 'darwin')
2430
defenc = sys.getfilesystemencoding()
2531

2632

27-
def safe_decode(s):
33+
def safe_decode(s: Optional[AnyStr]) -> Optional[str]:
2834
"""Safely decodes a binary string to unicode"""
2935
if isinstance(s, str):
3036
return s
3137
elif isinstance(s, bytes):
3238
return s.decode(defenc, 'surrogateescape')
33-
elif s is not None:
39+
elif s is None:
40+
return None
41+
else:
3442
raise TypeError('Expected bytes or text, but got %r' % (s,))
3543

3644

37-
def safe_encode(s):
38-
"""Safely decodes a binary string to unicode"""
45+
def safe_encode(s: Optional[AnyStr]) -> Optional[bytes]:
46+
"""Safely encodes a binary string to unicode"""
3947
if isinstance(s, str):
4048
return s.encode(defenc)
4149
elif isinstance(s, bytes):
4250
return s
43-
elif s is not None:
51+
elif s is None:
52+
return None
53+
else:
4454
raise TypeError('Expected bytes or text, but got %r' % (s,))
4555

4656

47-
def win_encode(s):
57+
def win_encode(s: Optional[AnyStr]) -> Optional[bytes]:
4858
"""Encode unicodes for process arguments on Windows."""
4959
if isinstance(s, str):
5060
return s.encode(locale.getpreferredencoding(False))
5161
elif isinstance(s, bytes):
5262
return s
5363
elif s is not None:
5464
raise TypeError('Expected bytes or text, but got %r' % (s,))
65+
return None
66+
5567

5668

57-
def with_metaclass(meta, *bases):
69+
def with_metaclass(meta: Type[Any], *bases: Any) -> 'metaclass': # type: ignore ## mypy cannot understand dynamic class creation
5870
"""copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15"""
59-
class metaclass(meta):
71+
72+
class metaclass(meta): # type: ignore
6073
__call__ = type.__call__
61-
__init__ = type.__init__
74+
__init__ = type.__init__ # type: ignore
6275

63-
def __new__(cls, name, nbases, d):
76+
def __new__(cls, name: str, nbases: Optional[int], d: Dict[str, Any]) -> TBD:
6477
if nbases is None:
6578
return type.__new__(cls, name, (), d)
6679
return meta(name, bases, d)
80+
6781
return metaclass(meta.__name__ + 'Helper', None, {})

‎git/config.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
import fnmatch
1717
from collections import OrderedDict
1818

19+
from typing_extensions import Literal
20+
1921
from git.compat import (
2022
defenc,
2123
force_text,
@@ -194,7 +196,7 @@ def items_all(self):
194196
return [(k, self.getall(k)) for k in self]
195197

196198

197-
def get_config_path(config_level):
199+
def get_config_path(config_level: Literal['system', 'global', 'user', 'repository']) -> str:
198200

199201
# we do not support an absolute path of the gitconfig on windows ,
200202
# use the global config instead

‎git/db.py

+16-8
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,19 @@
77
from gitdb.db import GitDB # @UnusedImport
88
from gitdb.db import LooseObjectDB
99

10-
from .exc import (
11-
GitCommandError,
12-
BadObject
13-
)
10+
from gitdb.exc import BadObject
11+
from git.exc import GitCommandError
12+
13+
# typing-------------------------------------------------
14+
15+
from typing import TYPE_CHECKING, AnyStr
16+
from git.types import PathLike
17+
18+
if TYPE_CHECKING:
19+
from git.cmd import Git
20+
1421

22+
# --------------------------------------------------------
1523

1624
__all__ = ('GitCmdObjectDB', 'GitDB')
1725

@@ -28,23 +36,23 @@ class GitCmdObjectDB(LooseObjectDB):
2836
have packs and the other implementations
2937
"""
3038

31-
def __init__(self, root_path, git):
39+
def __init__(self, root_path: PathLike, git: 'Git') -> None:
3240
"""Initialize this instance with the root and a git command"""
3341
super(GitCmdObjectDB, self).__init__(root_path)
3442
self._git = git
3543

36-
def info(self, sha):
44+
def info(self, sha: bytes) -> OInfo:
3745
hexsha, typename, size = self._git.get_object_header(bin_to_hex(sha))
3846
return OInfo(hex_to_bin(hexsha), typename, size)
3947

40-
def stream(self, sha):
48+
def stream(self, sha: bytes) -> OStream:
4149
"""For now, all lookup is done by git itself"""
4250
hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(sha))
4351
return OStream(hex_to_bin(hexsha), typename, size, stream)
4452

4553
# { Interface
4654

47-
def partial_to_complete_sha_hex(self, partial_hexsha):
55+
def partial_to_complete_sha_hex(self, partial_hexsha: AnyStr) -> bytes:
4856
""":return: Full binary 20 byte sha from the given partial hexsha
4957
:raise AmbiguousObjectName:
5058
:raise BadObject:

0 commit comments

Comments
 (0)