Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
16f0607
Improve typing of config_levels, add assert_never()
Yobmod Jul 5, 2021
9400246
Fix IndexFile forwardref
Yobmod Jul 5, 2021
e4caa80
put typing_extensions.get_types() behind python version guard
Yobmod Jul 5, 2021
0939e38
fix is_config_level for < 3.8
Yobmod Jul 5, 2021
0fc93b5
Rmv is_config_level() and get_args(), not worth the trouble
Yobmod Jul 5, 2021
53f1195
Add Literal_config_levels.__args__
Yobmod Jul 5, 2021
41e9781
Improve BlameEntry.commit typing
Yobmod Jul 5, 2021
23b5d6b
Add types to submodule.util.py
Yobmod Jul 5, 2021
c2317a7
Make bytesIO forwardref
Yobmod Jul 5, 2021
a935134
Add types to submodule.root.py
Yobmod Jul 5, 2021
3ce319f
Add types to submodule.update()
Yobmod Jul 6, 2021
6471018
Improve types of @unbare_repo and @git_working_dir decorators
Yobmod Jul 6, 2021
fb09bfa
Improve types of diff.py
Yobmod Jul 6, 2021
2a6a2e2
Improve types of diff.py
Yobmod Jul 6, 2021
3578355
Add cast(Repo, mrepo) in try block
Yobmod Jul 6, 2021
1bcccd5
Fix Literal Typeguards
Yobmod Jul 6, 2021
278a371
Fix for mrepo
Yobmod Jul 6, 2021
deafa6a
Fix for mrepo2
Yobmod Jul 6, 2021
e6f340c
Rmv runtime_checkable < py3.8
Yobmod Jul 6, 2021
ed58e2f
Rmv runtime_checkable < py3.8 pt2
Yobmod Jul 6, 2021
eecf148
Rmv root.py types
Yobmod Jul 6, 2021
a857b97
Merge branch 'gitpython-developers:main' into main
Yobmod Jul 6, 2021
b78cca1
Rmv base.py types
Yobmod Jul 6, 2021
8ef1adb
Merge branch 'main' of https://github.com/Yobmod/gitpython
Yobmod Jul 6, 2021
6aebb73
Rmv submodule types
Yobmod Jul 6, 2021
c0ab23e
Rmv submodule types2
Yobmod Jul 6, 2021
8d2a770
Rmv diff typeguard
Yobmod Jul 6, 2021
1fd9e8c
Re-add submodule.util.py types
Yobmod Jul 6, 2021
1eceb89
Fix submodule.util.py types
Yobmod Jul 6, 2021
215abfd
Readd typeguard to Diff.py
Yobmod Jul 6, 2021
94c2ae4
Readd submodule.base.py types
Yobmod Jul 6, 2021
06eca0b
Make subodule a forward ref in Index.base
Yobmod Jul 6, 2021
33ffd0b
Make subodule a forward ref in Index.base2
Yobmod Jul 6, 2021
af7cee5
Make Repo a forward ref in Submodule.base
Yobmod Jul 6, 2021
f372187
Make subodule a forward ref in Index.base3
Yobmod Jul 6, 2021
de36cb6
UnMake subodule a forward ref in Index.base
Yobmod Jul 6, 2021
3cc0edc
UnMake subodule a forward ref in Index.base2
Yobmod Jul 6, 2021
28bde39
Type index _items_to_rela_paths()
Yobmod Jul 6, 2021
1d0e666
Check change_levels (should fail)
Yobmod Jul 6, 2021
e985851
Add 'U' to change_levels (should pass)
Yobmod Jul 6, 2021
873ebe6
Make diff.DiffIndex generic List['Diff']
Yobmod Jul 6, 2021
2e2fe18
Increase mypy strictness (no_implicit_optional & warn_redundant_casts…
Yobmod Jul 8, 2021
5d3818e
Finish initial typing of index folder
Yobmod Jul 8, 2021
9f88796
Mak GitCmdObjectDB a froward ref
Yobmod Jul 8, 2021
1533596
Mak EntryTup a froward ref
Yobmod Jul 8, 2021
4333dcb
Mmmmm
Yobmod Jul 8, 2021
fe5fef9
Mmmmmm
Yobmod Jul 8, 2021
d344abf
Fix traverse_trees_recursive()
Yobmod Jul 8, 2021
dfbc0f4
Fix traverse_trees_recursive() again
Yobmod Jul 8, 2021
c27d2b0
Use Tuple not tuple
Yobmod Jul 8, 2021
4f13b4e
fix base,ours,theirs typing
Yobmod Jul 8, 2021
627deff
Change List to MutableSequence in fun.py _find_by_name()
Yobmod Jul 8, 2021
f271c58
tests TraversableIterableObj typeguard
Yobmod Jul 8, 2021
4802a36
improve TraversableIterableObj typeguard
Yobmod Jul 8, 2021
1faa25f
Rmv typeguard from list_traverse(), was wrong
Yobmod Jul 8, 2021
f4cb7db
Change type of list_traverse() again.
Yobmod Jul 9, 2021
030b1fd
Add list_traverse() to Tree and TraversableIterableObj.
Yobmod Jul 9, 2021
3710e24
Rmv circular import, create Has_id_attribute Protocol instead
Yobmod Jul 9, 2021
5eea891
Fix list_traverse() docstring for Autodoc
Yobmod Jul 9, 2021
9377462
Make has_repo protocol runtime checkable and use in Diffable
Yobmod Jul 9, 2021
3c6deb0
Flatten list_traverse()
Yobmod Jul 9, 2021
a024bdd
Move TraverseNT to global, cos mypy complained on testing
Yobmod Jul 9, 2021
6271660
Rmv submodule.base Repo assert
Yobmod Jul 9, 2021
7c6ae2b
Try to distinguation git.diff module from diff.Diff.diff and diff.Daf…
Yobmod Jul 9, 2021
f916c14
Improve Diffable method typing
Yobmod Jul 9, 2021
e7b685d
Rmv Diffable assert, add Remoote.url property
Yobmod Jul 9, 2021
9bb630f
Add remote.url type
Yobmod Jul 9, 2021
b03af05
Remove defsult_index decorator from diff() and do check within functi…
Yobmod Jul 9, 2021
797e962
Make IndexFile and Diffable .diff() types agree
Yobmod Jul 9, 2021
09053c5
Improve IndexFile_process_diff_args() to get checks to rerun
Yobmod Jul 9, 2021
2ea528e
Fix typing of index.fun.write_tree_from_cache()
Yobmod Jul 9, 2021
e6a27ad
Use TreeCacheTup type alias throughout
Yobmod Jul 9, 2021
94c6652
Make TreeCacheTup forward ref
Yobmod Jul 9, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Improve typing of config_levels, add assert_never()
  • Loading branch information
Yobmod committed Jul 5, 2021
commit 16f0607ed29f20c09e89f2cacc0e28e982309d60
31 changes: 16 additions & 15 deletions git/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@

# typing-------------------------------------------------------

from typing import Any, Callable, IO, List, Dict, Sequence, TYPE_CHECKING, Tuple, Union, cast, overload
from typing import (Any, Callable, IO, List, Dict, Sequence,
TYPE_CHECKING, Tuple, Union, cast, overload)

from git.types import Literal, Lit_config_levels, PathLike, TBD
from git.types import Lit_config_levels, ConfigLevels_Tup, ConfigLevels_NT, PathLike, TBD, assert_never

if TYPE_CHECKING:
from git.repo.base import Repo
Expand All @@ -48,8 +49,9 @@

# invariants
# represents the configuration level of a configuration file
CONFIG_LEVELS = ("system", "user", "global", "repository"
) # type: Tuple[Literal['system'], Literal['user'], Literal['global'], Literal['repository']]


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

# Section pattern to detect conditional includes.
# https://git-scm.com/docs/git-config#_conditional_includes
Expand Down Expand Up @@ -229,8 +231,9 @@ def get_config_path(config_level: Lit_config_levels) -> str:
return osp.normpath(osp.expanduser("~/.gitconfig"))
elif config_level == "repository":
raise ValueError("No repo to get repository configuration from. Use Repo._get_config_path")

raise ValueError("Invalid configuration level: %r" % config_level)
else:
# Should not reach here. Will raise ValueError if does. Static typing will warn about extra and missing elifs
assert_never(config_level, ValueError("Invalid configuration level: %r" % config_level))


class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, object)): # type: ignore ## mypy does not understand dynamic class creation # noqa: E501
Expand Down Expand Up @@ -300,12 +303,12 @@ def __init__(self, file_or_files: Union[None, PathLike, IO, Sequence[Union[PathL
self._proxies = self._dict()

if file_or_files is not None:
self._file_or_files = file_or_files # type: Union[PathLike, IO, Sequence[Union[PathLike, IO]]]
self._file_or_files: Union[PathLike, IO, Sequence[Union[PathLike, IO]]] = file_or_files
else:
if config_level is None:
if read_only:
self._file_or_files = [get_config_path(f) # type: ignore
for f in CONFIG_LEVELS # Can type f properly when 3.5 dropped
self._file_or_files = [get_config_path(f)
for f in CONFIG_LEVELS
if f != 'repository']
else:
raise ValueError("No configuration level or configuration files specified")
Expand All @@ -323,15 +326,13 @@ def __init__(self, file_or_files: Union[None, PathLike, IO, Sequence[Union[PathL
def _acquire_lock(self) -> None:
if not self._read_only:
if not self._lock:
if isinstance(self._file_or_files, (tuple, list)):
raise ValueError(
"Write-ConfigParsers can operate on a single file only, multiple files have been passed")
# END single file check

if isinstance(self._file_or_files, (str, os.PathLike)):
file_or_files = self._file_or_files
elif isinstance(self._file_or_files, (tuple, list, Sequence)):
raise ValueError(
"Write-ConfigParsers can operate on a single file only, multiple files have been passed")
else:
file_or_files = cast(IO, self._file_or_files).name
file_or_files = self._file_or_files.name

# END get filename from handle/stream
# initialize lock base - we want to write
Expand Down
27 changes: 15 additions & 12 deletions git/objects/submodule/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from unittest import SkipTest
import uuid

from git import IndexFile

import git
from git.cmd import Git
from git.compat import (
Expand Down Expand Up @@ -49,7 +51,7 @@


# typing ----------------------------------------------------------------------
from typing import Dict, TYPE_CHECKING
from typing import Callable, Dict, TYPE_CHECKING
from typing import Any, Iterator, Union

from git.types import Commit_ish, PathLike
Expand Down Expand Up @@ -131,14 +133,14 @@ def __init__(self, repo: 'Repo', binsha: bytes,
if url is not None:
self._url = url
if branch_path is not None:
assert isinstance(branch_path, str)
# assert isinstance(branch_path, str)
self._branch_path = branch_path
if name is not None:
self._name = name

def _set_cache_(self, attr: str) -> None:
if attr in ('path', '_url', '_branch_path'):
reader = self.config_reader()
reader: SectionConstraint = self.config_reader()
# default submodule values
try:
self.path = reader.get('path')
Expand Down Expand Up @@ -807,7 +809,8 @@ def move(self, module_path, configuration=True, module=True):
return self

@unbare_repo
def remove(self, module=True, force=False, configuration=True, dry_run=False):
def remove(self, module: bool = True, force: bool = False,
configuration: bool = True, dry_run: bool = False) -> 'Submodule':
"""Remove this submodule from the repository. This will remove our entry
from the .gitmodules file and the entry in the .git / config file.

Expand Down Expand Up @@ -861,7 +864,7 @@ def remove(self, module=True, force=False, configuration=True, dry_run=False):
# TODO: If we run into permission problems, we have a highly inconsistent
# state. Delete the .git folders last, start with the submodules first
mp = self.abspath
method = None
method: Union[None, Callable[[PathLike], None]] = None
if osp.islink(mp):
method = os.remove
elif osp.isdir(mp):
Expand Down Expand Up @@ -928,7 +931,7 @@ def remove(self, module=True, force=False, configuration=True, dry_run=False):
rmtree(git_dir)
except Exception as ex:
if HIDE_WINDOWS_KNOWN_ERRORS:
raise SkipTest("FIXME: fails with: PermissionError\n %s", ex) from ex
raise SkipTest(f"FIXME: fails with: PermissionError\n {ex}") from ex
else:
raise
# end handle separate bare repository
Expand Down Expand Up @@ -961,7 +964,7 @@ def remove(self, module=True, force=False, configuration=True, dry_run=False):

return self

def set_parent_commit(self, commit: Union[Commit_ish, None], check=True):
def set_parent_commit(self, commit: Union[Commit_ish, None], check: bool = True) -> 'Submodule':
"""Set this instance to use the given commit whose tree is supposed to
contain the .gitmodules blob.

Expand Down Expand Up @@ -1009,7 +1012,7 @@ def set_parent_commit(self, commit: Union[Commit_ish, None], check=True):
return self

@unbare_repo
def config_writer(self, index=None, write=True):
def config_writer(self, index: Union[IndexFile, None] = None, write: bool = True) -> SectionConstraint:
""":return: a config writer instance allowing you to read and write the data
belonging to this submodule into the .gitmodules file.

Expand All @@ -1030,7 +1033,7 @@ def config_writer(self, index=None, write=True):
return writer

@unbare_repo
def rename(self, new_name):
def rename(self, new_name: str) -> 'Submodule':
"""Rename this submodule
:note: This method takes care of renaming the submodule in various places, such as

Expand Down Expand Up @@ -1081,7 +1084,7 @@ def rename(self, new_name):
#{ Query Interface

@unbare_repo
def module(self):
def module(self) -> 'Repo':
""":return: Repo instance initialized from the repository at our submodule path
:raise InvalidGitRepositoryError: if a repository was not available. This could
also mean that it was not yet initialized"""
Expand All @@ -1098,7 +1101,7 @@ def module(self):
raise InvalidGitRepositoryError("Repository at %r was not yet checked out" % module_checkout_abspath)
# END handle exceptions

def module_exists(self):
def module_exists(self) -> bool:
""":return: True if our module exists and is a valid git repository. See module() method"""
try:
self.module()
Expand All @@ -1107,7 +1110,7 @@ def module_exists(self):
return False
# END handle exception

def exists(self):
def exists(self) -> bool:
"""
:return: True if the submodule exists, False otherwise. Please note that
a submodule may exist ( in the .gitmodules file) even though its module
Expand Down
9 changes: 8 additions & 1 deletion git/objects/submodule/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,18 @@
import weakref


# typing -----------------------------------------------------------------------

from typing import Any, TYPE_CHECKING, Union

from git.types import PathLike

if TYPE_CHECKING:
from .base import Submodule
from weakref import ReferenceType
from git.repo import Repo
from git.refs import Head


__all__ = ('sm_section', 'sm_name', 'mkhead', 'find_first_remote_branch',
'SubmoduleConfigParser')
Expand All @@ -28,7 +35,7 @@ def sm_name(section):
return section[11:-1]


def mkhead(repo, path):
def mkhead(repo: 'Repo', path: PathLike) -> 'Head':
""":return: New branch/head instance"""
return git.Head(repo, git.Head.to_full_path(path))

Expand Down
3 changes: 2 additions & 1 deletion git/refs/symbolic.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from git.types import PathLike
import os

from git.compat import defenc
Expand Down Expand Up @@ -408,7 +409,7 @@ def log_entry(self, index):
return RefLog.entry_at(RefLog.path(self), index)

@classmethod
def to_full_path(cls, path):
def to_full_path(cls, path) -> PathLike:
"""
:return: string with a full repository-relative path which can be used to initialize
a Reference instance, for instance by using ``Reference.from_path``"""
Expand Down
19 changes: 10 additions & 9 deletions git/repo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@

# typing ------------------------------------------------------

from git.types import TBD, PathLike, Lit_config_levels, Commit_ish, Tree_ish
from git.types import ConfigLevels_NT, TBD, PathLike, Lit_config_levels, Commit_ish, Tree_ish
from typing import (Any, BinaryIO, Callable, Dict,
Iterator, List, Mapping, Optional, Sequence,
TextIO, Tuple, Type, Union,
NamedTuple, cast, TYPE_CHECKING)

if TYPE_CHECKING: # only needed for types
from git.types import ConfigLevels_Tup

if TYPE_CHECKING:
from git.util import IterableList
from git.refs.symbolic import SymbolicReference
from git.objects import Tree
Expand All @@ -55,12 +57,11 @@
__all__ = ('Repo',)


BlameEntry = NamedTuple('BlameEntry', [
('commit', Dict[str, TBD]),
('linenos', range),
('orig_path', Optional[str]),
('orig_linenos', range)]
)
class BlameEntry(NamedTuple):
commit: Dict[str, TBD]
linenos: range
orig_path: Optional[str]
orig_linenos: range


class Repo(object):
Expand Down Expand Up @@ -95,7 +96,7 @@ class Repo(object):

# invariants
# represents the configuration level of a configuration file
config_level = ("system", "user", "global", "repository") # type: Tuple[Lit_config_levels, ...]
config_level: ConfigLevels_Tup = ConfigLevels_NT("system", "user", "global", "repository")

# Subclass configuration
# Subclasses may easily bring in their own custom types by placing a constructor or type here
Expand Down
29 changes: 28 additions & 1 deletion git/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

import os
import sys
from typing import Dict, Union, Any, TYPE_CHECKING
from typing import (Callable, Dict, NoReturn, Tuple, Union, Any, Iterator, # noqa: F401
NamedTuple, TYPE_CHECKING, get_args, TypeVar) # noqa: F401


if sys.version_info[:2] >= (3, 8):
Expand Down Expand Up @@ -35,6 +36,32 @@

Lit_config_levels = Literal['system', 'global', 'user', 'repository']

T = TypeVar('T', bound=Literal['system', 'global', 'user', 'repository'], covariant=True)


class ConfigLevels_NT(NamedTuple):
"""NamedTuple of allowed CONFIG_LEVELS"""
# works for pylance, but not mypy
system: Literal['system']
user: Literal['user']
global_: Literal['global']
repository: Literal['repository']


ConfigLevels_Tup = Tuple[Lit_config_levels, Lit_config_levels, Lit_config_levels, Lit_config_levels]
# Typing this as specific literals breaks for mypy


def is_config_level(inp: str) -> TypeGuard[Lit_config_levels]:
return inp in get_args(Lit_config_levels)


def assert_never(inp: NoReturn, exc: Union[Exception, None] = None) -> NoReturn:
if exc is None:
assert False, f"An unhandled Literal ({inp}) in an if else chain was found"
else:
raise exc


class Files_TD(TypedDict):
insertions: int
Expand Down
Loading