summaryrefslogtreecommitdiff
path: root/git
diff options
context:
space:
mode:
authorYobmod <yobmod@gmail.com>2021-07-19 16:55:03 +0100
committerYobmod <yobmod@gmail.com>2021-07-19 16:55:03 +0100
commitac39679ce170c5eb21f98ac23ac0358850e8974f (patch)
tree0a552c49d9358dffcb2272c42fa4c8d50acda2fe /git
parent8fc25c63d9282ddc6b3162c2d92679a89e934ec5 (diff)
downloadgitpython-ac39679ce170c5eb21f98ac23ac0358850e8974f.tar.gz
Make types in refs compatible with previous
Diffstat (limited to 'git')
-rw-r--r--git/cmd.py12
-rw-r--r--git/config.py2
-rw-r--r--git/db.py2
-rw-r--r--git/diff.py2
-rw-r--r--git/remote.py57
-rw-r--r--git/util.py29
6 files changed, 59 insertions, 45 deletions
diff --git a/git/cmd.py b/git/cmd.py
index dd887a18..11c02afe 100644
--- a/git/cmd.py
+++ b/git/cmd.py
@@ -15,7 +15,6 @@ from subprocess import (
PIPE
)
import subprocess
-import sys
import threading
from textwrap import dedent
@@ -539,7 +538,7 @@ class Git(LazyMixin):
return self
def __next__(self) -> bytes:
- return self.next()
+ return next(self)
def next(self) -> bytes:
line = self.readline()
@@ -799,10 +798,7 @@ class Git(LazyMixin):
if kill_after_timeout:
raise GitCommandError(redacted_command, '"kill_after_timeout" feature is not supported on Windows.')
else:
- if sys.version_info[0] > 2:
- cmd_not_found_exception = FileNotFoundError # NOQA # exists, flake8 unknown @UndefinedVariable
- else:
- cmd_not_found_exception = OSError
+ cmd_not_found_exception = FileNotFoundError # NOQA # exists, flake8 unknown @UndefinedVariable
# end handle
stdout_sink = (PIPE
@@ -1070,8 +1066,8 @@ class Git(LazyMixin):
It contains key-values for the following:
- the :meth:`execute()` kwds, as listed in :var:`execute_kwargs`;
- "command options" to be converted by :meth:`transform_kwargs()`;
- - the `'insert_kwargs_after'` key which its value must match one of ``*args``,
- and any cmd-options will be appended after the matched arg.
+ - the `'insert_kwargs_after'` key which its value must match one of ``*args``
+ and any cmd-options will be appended after the matched arg.
Examples::
diff --git a/git/config.py b/git/config.py
index 2c863f93..e0a18ec8 100644
--- a/git/config.py
+++ b/git/config.py
@@ -238,7 +238,7 @@ def get_config_path(config_level: Lit_config_levels) -> str:
assert_never(config_level, ValueError(f"Invalid configuration level: {config_level!r}"))
-class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser, object)): # type: ignore ## mypy does not understand dynamic class creation # noqa: E501
+class GitConfigParser(with_metaclass(MetaParserBuilder, cp.RawConfigParser)): # type: ignore ## mypy does not understand dynamic class creation # noqa: E501
"""Implements specifics required to read git style configuration files.
diff --git a/git/db.py b/git/db.py
index 47cccda8..3a7adc7d 100644
--- a/git/db.py
+++ b/git/db.py
@@ -17,7 +17,7 @@ from git.types import PathLike
if TYPE_CHECKING:
from git.cmd import Git
-
+
# --------------------------------------------------------
diff --git a/git/diff.py b/git/diff.py
index 51dac390..f8c0c25f 100644
--- a/git/diff.py
+++ b/git/diff.py
@@ -143,7 +143,7 @@ class Diffable(object):
paths = [paths]
if hasattr(self, 'Has_Repo'):
- self.repo: Repo = self.repo
+ self.repo: 'Repo' = self.repo
diff_cmd = self.repo.git.diff
if other is self.Index:
diff --git a/git/remote.py b/git/remote.py
index f59b3245..0fcd49b5 100644
--- a/git/remote.py
+++ b/git/remote.py
@@ -36,9 +36,10 @@ from .refs import (
# typing-------------------------------------------------------
-from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union, overload
+from typing import (Any, Callable, Dict, Iterator, List, NoReturn, Optional, Sequence, # NOQA[TC002]
+ TYPE_CHECKING, Type, Union, overload)
-from git.types import PathLike, Literal, TBD, TypeGuard, Commit_ish
+from git.types import PathLike, Literal, TBD, TypeGuard, Commit_ish # NOQA[TC002]
if TYPE_CHECKING:
from git.repo.base import Repo
@@ -83,17 +84,17 @@ def add_progress(kwargs: Any, git: Git,
#} END utilities
-@overload
+@ overload
def to_progress_instance(progress: None) -> RemoteProgress:
...
-@overload
+@ overload
def to_progress_instance(progress: Callable[..., Any]) -> CallableRemoteProgress:
...
-@overload
+@ overload
def to_progress_instance(progress: RemoteProgress) -> RemoteProgress:
...
@@ -155,11 +156,11 @@ class PushInfo(IterableObj, object):
self._old_commit_sha = old_commit
self.summary = summary
- @property
- def old_commit(self) -> Union[str, SymbolicReference, 'Commit_ish', None]:
+ @ property
+ def old_commit(self) -> Union[str, SymbolicReference, Commit_ish, None]:
return self._old_commit_sha and self._remote.repo.commit(self._old_commit_sha) or None
- @property
+ @ property
def remote_ref(self) -> Union[RemoteReference, TagReference]:
"""
:return:
@@ -175,7 +176,7 @@ class PushInfo(IterableObj, object):
raise ValueError("Could not handle remote ref: %r" % self.remote_ref_string)
# END
- @classmethod
+ @ classmethod
def _from_line(cls, remote: 'Remote', line: str) -> 'PushInfo':
"""Create a new PushInfo instance as parsed from line which is expected to be like
refs/heads/master:refs/heads/master 05d2687..1d0568e as bytes"""
@@ -228,6 +229,11 @@ class PushInfo(IterableObj, object):
return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary)
+ @ classmethod
+ def iter_items(cls, repo: 'Repo', *args: Any, **kwargs: Any
+ ) -> NoReturn: # -> Iterator['PushInfo']:
+ raise NotImplementedError
+
class FetchInfo(IterableObj, object):
@@ -262,7 +268,7 @@ class FetchInfo(IterableObj, object):
'-': TAG_UPDATE,
} # type: Dict[flagKeyLiteral, int]
- @classmethod
+ @ classmethod
def refresh(cls) -> Literal[True]:
"""This gets called by the refresh function (see the top level
__init__).
@@ -301,25 +307,25 @@ class FetchInfo(IterableObj, object):
def __str__(self) -> str:
return self.name
- @property
+ @ property
def name(self) -> str:
""":return: Name of our remote ref"""
return self.ref.name
- @property
+ @ property
def commit(self) -> Commit_ish:
""":return: Commit of our remote ref"""
return self.ref.commit
- @classmethod
+ @ classmethod
def _from_line(cls, repo: 'Repo', line: str, fetch_line: str) -> 'FetchInfo':
"""Parse information from the given line as returned by git-fetch -v
and return a new FetchInfo object representing this information.
- We can handle a line as follows
- "%c %-*s %-*s -> %s%s"
+ We can handle a line as follows:
+ "%c %-\\*s %-\\*s -> %s%s"
- Where c is either ' ', !, +, -, *, or =
+ Where c is either ' ', !, +, -, \\*, or =
! means error
+ means success forcing update
- means a tag was updated
@@ -334,6 +340,7 @@ class FetchInfo(IterableObj, object):
raise ValueError("Failed to parse line: %r" % line)
# parse lines
+ remote_local_ref_str: str
control_character, operation, local_remote_ref, remote_local_ref_str, note = match.groups()
assert is_flagKeyLiteral(control_character), f"{control_character}"
@@ -375,7 +382,7 @@ class FetchInfo(IterableObj, object):
# If we do not specify a target branch like master:refs/remotes/origin/master,
# the fetch result is stored in FETCH_HEAD which destroys the rule we usually
# have. In that case we use a symbolic reference which is detached
- ref_type = None
+ ref_type: Optional[Type[SymbolicReference]] = None
if remote_local_ref_str == "FETCH_HEAD":
ref_type = SymbolicReference
elif ref_type_name == "tag" or is_tag_operation:
@@ -404,14 +411,15 @@ class FetchInfo(IterableObj, object):
# by the 'ref/' prefix. Otherwise even a tag could be in refs/remotes, which is when it will have the
# 'tags/' subdirectory in its path.
# We don't want to test for actual existence, but try to figure everything out analytically.
- ref_path = None # type: Optional[PathLike]
+ ref_path: Optional[PathLike] = None
remote_local_ref_str = remote_local_ref_str.strip()
+
if remote_local_ref_str.startswith(Reference._common_path_default + "/"):
# always use actual type if we get absolute paths
# Will always be the case if something is fetched outside of refs/remotes (if its not a tag)
ref_path = remote_local_ref_str
if ref_type is not TagReference and not \
- remote_local_ref_str.startswith(RemoteReference._common_path_default + "/"):
+ remote_local_ref_str.startswith(RemoteReference._common_path_default + "/"):
ref_type = Reference
# END downgrade remote reference
elif ref_type is TagReference and 'tags/' in remote_local_ref_str:
@@ -430,6 +438,11 @@ class FetchInfo(IterableObj, object):
return cls(remote_local_ref, flags, note, old_commit, local_remote_ref)
+ @ classmethod
+ def iter_items(cls, repo: 'Repo', *args: Any, **kwargs: Any
+ ) -> NoReturn: # -> Iterator['FetchInfo']:
+ raise NotImplementedError
+
class Remote(LazyMixin, IterableObj):
@@ -507,7 +520,7 @@ class Remote(LazyMixin, IterableObj):
return False
# end
- @classmethod
+ @ classmethod
def iter_items(cls, repo: 'Repo', *args: Any, **kwargs: Any) -> Iterator['Remote']:
""":return: Iterator yielding Remote objects of the given repository"""
for section in repo.config_reader("repository").sections():
@@ -897,7 +910,7 @@ class Remote(LazyMixin, IterableObj):
universal_newlines=True, **kwargs)
return self._get_push_info(proc, progress)
- @property
+ @ property
def config_reader(self) -> SectionConstraint:
"""
:return:
@@ -912,7 +925,7 @@ class Remote(LazyMixin, IterableObj):
pass
# END handle exception
- @property
+ @ property
def config_writer(self) -> SectionConstraint:
"""
:return: GitConfigParser compatible object able to write options for this remote.
diff --git a/git/util.py b/git/util.py
index 571e261e..c04e2927 100644
--- a/git/util.py
+++ b/git/util.py
@@ -4,6 +4,7 @@
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
+from abc import abstractmethod
from .exc import InvalidGitRepositoryError
import os.path as osp
from .compat import is_win
@@ -28,7 +29,8 @@ import warnings
# typing ---------------------------------------------------------
from typing import (Any, AnyStr, BinaryIO, Callable, Dict, Generator, IO, Iterator, List,
- Optional, Pattern, Sequence, Tuple, TypeVar, Union, cast, TYPE_CHECKING, overload)
+ Optional, Pattern, Sequence, Tuple, TypeVar, Union, cast,
+ TYPE_CHECKING, overload, )
import pathlib
@@ -39,8 +41,8 @@ if TYPE_CHECKING:
# from git.objects.base import IndexObject
-from .types import (Literal, SupportsIndex, # because behind py version guards
- PathLike, HSH_TD, Total_TD, Files_TD, # aliases
+from .types import (Literal, SupportsIndex, Protocol, runtime_checkable, # because behind py version guards
+ PathLike, HSH_TD, Total_TD, Files_TD, # aliases
Has_id_attribute)
T_IterableObj = TypeVar('T_IterableObj', bound=Union['IterableObj', 'Has_id_attribute'], covariant=True)
@@ -471,7 +473,7 @@ class RemoteProgress(object):
- Lines that do not contain progress info are stored in :attr:`other_lines`.
- Lines that seem to contain an error (i.e. start with error: or fatal:) are stored
- in :attr:`error_lines`."""
+ in :attr:`error_lines`."""
# handle
# Counting objects: 4, done.
# Compressing objects: 50% (1/2)
@@ -993,7 +995,7 @@ class IterableList(List[T_IterableObj]):
# END for each item
return list.__getattribute__(self, attr)
- def __getitem__(self, index: Union[SupportsIndex, int, slice, str]) -> 'T_IterableObj': # type: ignore
+ def __getitem__(self, index: Union[SupportsIndex, int, slice, str]) -> T_IterableObj: # type: ignore
assert isinstance(index, (int, str, slice)), "Index of IterableList should be an int or str"
@@ -1030,23 +1032,24 @@ class IterableList(List[T_IterableObj]):
class IterableClassWatcher(type):
+ """ Metaclass that watches """
def __init__(cls, name, bases, clsdict):
for base in bases:
if type(base) == IterableClassWatcher:
warnings.warn(f"GitPython Iterable subclassed by {name}. "
- "Iterable is deprecated due to naming clash, "
+ "Iterable is deprecated due to naming clash since v3.1.18"
+ " and will be removed in 3.1.20, "
"Use IterableObj instead \n",
DeprecationWarning,
stacklevel=2)
-class Iterable(object):
+class Iterable(metaclass=IterableClassWatcher):
"""Defines an interface for iterable items which is to assure a uniform
way to retrieve and iterate items within the git repository"""
__slots__ = ()
_id_attribute_ = "attribute that most suitably identifies your instance"
- __metaclass__ = IterableClassWatcher
@classmethod
def list_items(cls, repo, *args, **kwargs):
@@ -1064,14 +1067,15 @@ class Iterable(object):
return out_list
@classmethod
- def iter_items(cls, repo: 'Repo', *args: Any, **kwargs: Any):
+ def iter_items(cls, repo: 'Repo', *args: Any, **kwargs: Any) -> Any:
# return typed to be compatible with subtypes e.g. Remote
"""For more information about the arguments, see list_items
:return: iterator yielding Items"""
raise NotImplementedError("To be implemented by Subclass")
-class IterableObj():
+@runtime_checkable
+class IterableObj(Protocol):
"""Defines an interface for iterable items which is to assure a uniform
way to retrieve and iterate items within the git repository
@@ -1095,11 +1099,12 @@ class IterableObj():
return out_list
@classmethod
+ @abstractmethod
def iter_items(cls, repo: 'Repo', *args: Any, **kwargs: Any
- ) -> Iterator[T_IterableObj]:
+ ) -> Iterator[T_IterableObj]: # Iterator[T_IterableObj]:
# return typed to be compatible with subtypes e.g. Remote
"""For more information about the arguments, see list_items
- :return: iterator yielding Items"""
+ :return: iterator yielding Items"""
raise NotImplementedError("To be implemented by Subclass")
# } END classes