Skip to content

Commit 2e2fe18

Browse files
committed
Increase mypy strictness (no_implicit_optional & warn_redundant_casts) and fix errors
1 parent 873ebe6 commit 2e2fe18

File tree

9 files changed

+26
-28
lines changed

9 files changed

+26
-28
lines changed

‎git/cmd.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,7 @@ def execute(self,
831831
except cmd_not_found_exception as err:
832832
raise GitCommandNotFound(redacted_command, err) from err
833833
else:
834-
proc = cast(Popen, proc)
834+
# replace with a typeguard for Popen[bytes]?
835835
proc.stdout = cast(BinaryIO, proc.stdout)
836836
proc.stderr = cast(BinaryIO, proc.stderr)
837837

‎git/config.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from typing import (Any, Callable, IO, List, Dict, Sequence,
3535
TYPE_CHECKING, Tuple, Union, cast, overload)
3636

37-
from git.types import Lit_config_levels, ConfigLevels_Tup, PathLike, TBD, assert_never
37+
from git.types import Lit_config_levels, ConfigLevels_Tup, PathLike, TBD, assert_never, is_config_level
3838

3939
if TYPE_CHECKING:
4040
from git.repo.base import Repo
@@ -54,6 +54,7 @@
5454

5555
CONFIG_LEVELS: ConfigLevels_Tup = ("system", "user", "global", "repository")
5656

57+
5758
# Section pattern to detect conditional includes.
5859
# https://git-scm.com/docs/git-config#_conditional_includes
5960
CONDITIONAL_INCLUDE_REGEXP = re.compile(r"(?<=includeIf )\"(gitdir|gitdir/i|onbranch):(.+)\"")
@@ -310,7 +311,7 @@ def __init__(self, file_or_files: Union[None, PathLike, 'BytesIO', Sequence[Unio
310311
if read_only:
311312
self._file_or_files = [get_config_path(f)
312313
for f in CONFIG_LEVELS
313-
if f != 'repository']
314+
if is_config_level(f) and f != 'repository']
314315
else:
315316
raise ValueError("No configuration level or configuration files specified")
316317
else:

‎git/index/base.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ class IndexFile(LazyMixin, diff.Diffable, Serializable):
113113
_VERSION = 2 # latest version we support
114114
S_IFGITLINK = S_IFGITLINK # a submodule
115115

116-
def __init__(self, repo: 'Repo', file_path: PathLike = None) -> None:
116+
def __init__(self, repo: 'Repo', file_path: Union[PathLike, None] = None) -> None:
117117
"""Initialize this Index instance, optionally from the given ``file_path``.
118118
If no file_path is given, we will be created from the current index file.
119119
@@ -665,7 +665,7 @@ def _entries_for_paths(self, paths: List[str], path_rewriter: Callable, fprogres
665665
return entries_added
666666

667667
def add(self, items: Sequence[Union[PathLike, Blob, BaseIndexEntry, 'Submodule']], force: bool = True,
668-
fprogress: Callable = lambda *args: None, path_rewriter: Callable = None,
668+
fprogress: Callable = lambda *args: None, path_rewriter: Union[Callable[..., PathLike], None] = None,
669669
write: bool = True, write_extension_data: bool = False) -> List[BaseIndexEntry]:
670670
"""Add files from the working tree, specific blobs or BaseIndexEntries
671671
to the index.
@@ -970,7 +970,8 @@ def move(self, items: Sequence[Union[PathLike, Blob, BaseIndexEntry, 'Submodule'
970970
return out
971971

972972
def commit(self, message: str, parent_commits=None, head: bool = True, author: Union[None, 'Actor'] = None,
973-
committer: Union[None, 'Actor'] = None, author_date: str = None, commit_date: str = None,
973+
committer: Union[None, 'Actor'] = None, author_date: Union[str, None] = None,
974+
commit_date: Union[str, None] = None,
974975
skip_hooks: bool = False) -> Commit:
975976
"""Commit the current default index file, creating a commit object.
976977
For more information on the arguments, see tree.commit.
@@ -1265,7 +1266,8 @@ def reset(self, commit: Union[Commit, 'Reference', str] = 'HEAD', working_tree:
12651266

12661267
@ default_index
12671268
def diff(self, other: Union[diff.Diffable.Index, 'IndexFile.Index', Treeish, None, object] = diff.Diffable.Index,
1268-
paths: Union[str, List[PathLike], Tuple[PathLike, ...]] = None, create_patch: bool = False, **kwargs: Any
1269+
paths: Union[str, List[PathLike], Tuple[PathLike, ...], None] = None,
1270+
create_patch: bool = False, **kwargs: Any
12691271
) -> diff.DiffIndex:
12701272
"""Diff this index against the working copy or a Tree or Commit object
12711273

‎git/objects/commit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable):
8080
"message", "parents", "encoding", "gpgsig")
8181
_id_attribute_ = "hexsha"
8282

83-
def __init__(self, repo: 'Repo', binsha: bytes, tree: 'Tree' = None,
83+
def __init__(self, repo: 'Repo', binsha: bytes, tree: Union['Tree', None] = None,
8484
author: Union[Actor, None] = None,
8585
authored_date: Union[int, None] = None,
8686
author_tz_offset: Union[None, float] = None,

‎git/objects/submodule/base.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def __init__(self, repo: 'Repo', binsha: bytes,
115115
path: Union[PathLike, None] = None,
116116
name: Union[str, None] = None,
117117
parent_commit: Union[Commit_ish, None] = None,
118-
url: str = None,
118+
url: Union[str, None] = None,
119119
branch_path: Union[PathLike, None] = None
120120
) -> None:
121121
"""Initialize this instance with its attributes. We only document the ones
@@ -339,7 +339,7 @@ def _write_git_file_and_module_config(cls, working_tree_dir: PathLike, module_ab
339339
@classmethod
340340
def add(cls, repo: 'Repo', name: str, path: PathLike, url: Union[str, None] = None,
341341
branch: Union[str, None] = None, no_checkout: bool = False, depth: Union[int, None] = None,
342-
env: Mapping[str, str] = None, clone_multi_options: Union[Sequence[TBD], None] = None
342+
env: Union[Mapping[str, str], None] = None, clone_multi_options: Union[Sequence[TBD], None] = None
343343
) -> 'Submodule':
344344
"""Add a new submodule to the given repository. This will alter the index
345345
as well as the .gitmodules file, but will not create a new commit.
@@ -481,7 +481,7 @@ def add(cls, repo: 'Repo', name: str, path: PathLike, url: Union[str, None] = No
481481

482482
def update(self, recursive: bool = False, init: bool = True, to_latest_revision: bool = False,
483483
progress: Union['UpdateProgress', None] = None, dry_run: bool = False,
484-
force: bool = False, keep_going: bool = False, env: Mapping[str, str] = None,
484+
force: bool = False, keep_going: bool = False, env: Union[Mapping[str, str], None] = None,
485485
clone_multi_options: Union[Sequence[TBD], None] = None):
486486
"""Update the repository of this submodule to point to the checkout
487487
we point at with the binsha of this instance.

‎git/objects/tree.py

-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,6 @@ def __init__(self, repo: 'Repo', binsha: bytes, mode: int = tree_id << 12, path:
216216
def _get_intermediate_items(cls, index_object: 'Tree',
217217
) -> Union[Tuple['Tree', ...], Tuple[()]]:
218218
if index_object.type == "tree":
219-
index_object = cast('Tree', index_object)
220219
return tuple(index_object._iter_convert_to_object(index_object._cache))
221220
return ()
222221

‎git/repo/base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737
# typing ------------------------------------------------------
3838

39-
from git.types import TBD, PathLike, Lit_config_levels, Commit_ish, Tree_ish
39+
from git.types import TBD, PathLike, Lit_config_levels, Commit_ish, Tree_ish, is_config_level
4040
from typing import (Any, BinaryIO, Callable, Dict,
4141
Iterator, List, Mapping, Optional, Sequence,
4242
TextIO, Tuple, Type, Union,
@@ -498,7 +498,7 @@ def config_reader(self, config_level: Optional[Lit_config_levels] = None) -> Git
498498
unknown, instead the global path will be used."""
499499
files = None
500500
if config_level is None:
501-
files = [self._get_config_path(f) for f in self.config_level]
501+
files = [self._get_config_path(f) for f in self.config_level if is_config_level(f)]
502502
else:
503503
files = [self._get_config_path(config_level)]
504504
return GitConfigParser(files, read_only=True, repo=self)
@@ -623,7 +623,7 @@ def is_ancestor(self, ancestor_rev: 'Commit', rev: 'Commit') -> bool:
623623
raise
624624
return True
625625

626-
def is_valid_object(self, sha: str, object_type: str = None) -> bool:
626+
def is_valid_object(self, sha: str, object_type: Union[str, None] = None) -> bool:
627627
try:
628628
complete_sha = self.odb.partial_to_complete_sha_hex(sha)
629629
object_info = self.odb.info(complete_sha)
@@ -976,7 +976,7 @@ def blame(self, rev: TBD, file: TBD, incremental: bool = False, **kwargs: Any
976976
return blames
977977

978978
@classmethod
979-
def init(cls, path: PathLike = None, mkdir: bool = True, odbt: Type[GitCmdObjectDB] = GitCmdObjectDB,
979+
def init(cls, path: Union[PathLike, None] = None, mkdir: bool = True, odbt: Type[GitCmdObjectDB] = GitCmdObjectDB,
980980
expand_vars: bool = True, **kwargs: Any) -> 'Repo':
981981
"""Initialize a git repository at the given path if specified
982982

‎git/types.py

+3-12
Original file line numberDiff line numberDiff line change
@@ -39,20 +39,11 @@
3939

4040

4141
def is_config_level(inp: str) -> TypeGuard[Lit_config_levels]:
42-
return inp in ('system', 'global', 'user', 'repository')
42+
# return inp in get_args(Lit_config_level) # only py >= 3.8
43+
return inp in ("system", "user", "global", "repository")
4344

4445

45-
class ConfigLevels_NT(NamedTuple):
46-
"""NamedTuple of allowed CONFIG_LEVELS"""
47-
# works for pylance, but not mypy
48-
system: Literal['system']
49-
user: Literal['user']
50-
global_: Literal['global']
51-
repository: Literal['repository']
52-
53-
54-
ConfigLevels_Tup = Tuple[Lit_config_levels, Lit_config_levels, Lit_config_levels, Lit_config_levels]
55-
# Typing this as specific literals breaks for mypy
46+
ConfigLevels_Tup = Tuple[Literal['system'], Literal['user'], Literal['global'], Literal['repository']]
5647

5748

5849
def assert_never(inp: NoReturn, exc: Union[Exception, None] = None) -> NoReturn:

‎mypy.ini

+5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33

44
# TODO: enable when we've fully annotated everything
55
# disallow_untyped_defs = True
6+
no_implicit_optional = True
7+
warn_redundant_casts = True
8+
# warn_unused_ignores = True
9+
# warn_unreachable = True
10+
pretty = True
611

712
# TODO: remove when 'gitdb' is fully annotated
813
[mypy-gitdb.*]

0 commit comments

Comments
 (0)