From 3347c00137e45a8b8b512afab242703892a1a1d2 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 15:57:22 +0100 Subject: change ordereddict guard, add type: ignore --- git/config.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'git') diff --git a/git/config.py b/git/config.py index c4b26ba6..77fa3045 100644 --- a/git/config.py +++ b/git/config.py @@ -41,12 +41,17 @@ if TYPE_CHECKING: T_ConfigParser = TypeVar('T_ConfigParser', bound='GitConfigParser') -if sys.version_info[:2] < (3, 7): +if sys.version_info[:2] < (3, 7, 2): + # typing.Ordereddict not added until py 3.7.2 from collections import OrderedDict OrderedDict_OMD = OrderedDict +elif sys.version_info[:2] >= (3, 10): + # then deprecated from 3.10 as collections.OrderedDict was made generic + from collections import OrderedDict + OrderedDict_OMD = OrderedDict[str, List[_T]] else: from typing import OrderedDict - OrderedDict_OMD = OrderedDict[str, List[_T]] + OrderedDict_OMD = OrderedDict[str, List[_T]] # type: ignore[assignment, misc] # ------------------------------------------------------------- -- cgit v1.2.1 From 28fdd30a579362a1121fa7e81d8051098b31f2d1 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 16:26:35 +0100 Subject: Fix SymbolicReference reference typing --- git/refs/head.py | 2 +- git/refs/symbolic.py | 6 ++++-- git/repo/base.py | 5 ++--- 3 files changed, 7 insertions(+), 6 deletions(-) (limited to 'git') diff --git a/git/refs/head.py b/git/refs/head.py index 338efce9..4b9bf33c 100644 --- a/git/refs/head.py +++ b/git/refs/head.py @@ -142,7 +142,7 @@ class Head(Reference): flag = "-D" repo.git.branch(flag, *heads) - def set_tracking_branch(self, remote_reference: 'RemoteReference') -> 'Head': + def set_tracking_branch(self, remote_reference: Union['RemoteReference', None]) -> 'Head': """ Configure this branch to track the given remote reference. This will alter this branch's configuration accordingly. diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 0e9dad5c..9a5a4479 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -28,6 +28,7 @@ from git.types import Commit_ish, PathLike, TBD, Literal if TYPE_CHECKING: from git.repo import Repo + from git.refs import Reference T_References = TypeVar('T_References', bound='SymbolicReference') @@ -356,8 +357,9 @@ class SymbolicReference(object): return self # aliased reference - reference = property(_get_reference, set_reference, doc="Returns the Reference we point to") - ref: Union[Commit_ish] = reference # type: ignore # Union[str, Commit_ish, SymbolicReference] + reference: Union[Commit_ish, 'Reference'] = property( # type: ignore + _get_reference, set_reference, doc="Returns the Reference we point to") + ref = reference def is_valid(self): """ diff --git a/git/repo/base.py b/git/repo/base.py index f8a1689a..74f27b2e 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -422,7 +422,7 @@ class Repo(object): def create_head(self, path: PathLike, commit: str = 'HEAD', force: bool = False, logmsg: Optional[str] = None - ) -> 'SymbolicReference': + ) -> 'Head': """Create a new head within the repository. For more documentation, please see the Head.create method. @@ -788,9 +788,8 @@ class Repo(object): return proc.replace("\\\\", "\\").replace('"', "").split("\n") @property - def active_branch(self) -> 'SymbolicReference': + def active_branch(self) -> 'HEAD': """The name of the currently active branch. - :return: Head to the active branch""" return self.head.reference -- cgit v1.2.1 From 3abc837c7c1f3241524d788933c287ec1a804b7e Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 16:35:38 +0100 Subject: Add another type ignore for Ordereddict --- git/config.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'git') diff --git a/git/config.py b/git/config.py index 77fa3045..def8ab8c 100644 --- a/git/config.py +++ b/git/config.py @@ -41,7 +41,7 @@ if TYPE_CHECKING: T_ConfigParser = TypeVar('T_ConfigParser', bound='GitConfigParser') -if sys.version_info[:2] < (3, 7, 2): +if sys.version_info[:3] < (3, 7, 2): # typing.Ordereddict not added until py 3.7.2 from collections import OrderedDict OrderedDict_OMD = OrderedDict @@ -50,7 +50,7 @@ elif sys.version_info[:2] >= (3, 10): from collections import OrderedDict OrderedDict_OMD = OrderedDict[str, List[_T]] else: - from typing import OrderedDict + from typing import OrderedDict # type: ignore # until 3.6 dropped OrderedDict_OMD = OrderedDict[str, List[_T]] # type: ignore[assignment, misc] # ------------------------------------------------------------- -- cgit v1.2.1 From 679142481d94c779d46f1e347604ec9ab24b05f3 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 16:41:14 +0100 Subject: Rmv py 3.10 check for typing.Ordereddict - its deprecated then, but will still work until 3.12 --- git/config.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'git') diff --git a/git/config.py b/git/config.py index def8ab8c..ad02b437 100644 --- a/git/config.py +++ b/git/config.py @@ -43,12 +43,8 @@ T_ConfigParser = TypeVar('T_ConfigParser', bound='GitConfigParser') if sys.version_info[:3] < (3, 7, 2): # typing.Ordereddict not added until py 3.7.2 - from collections import OrderedDict - OrderedDict_OMD = OrderedDict -elif sys.version_info[:2] >= (3, 10): - # then deprecated from 3.10 as collections.OrderedDict was made generic - from collections import OrderedDict - OrderedDict_OMD = OrderedDict[str, List[_T]] + from collections import OrderedDict # type: ignore # until 3.6 dropped + OrderedDict_OMD = OrderedDict # type: ignore # until 3.6 dropped else: from typing import OrderedDict # type: ignore # until 3.6 dropped OrderedDict_OMD = OrderedDict[str, List[_T]] # type: ignore[assignment, misc] -- cgit v1.2.1 From c464e33793d0839666233883212018dbbcdf1e09 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 17:19:10 +0100 Subject: Fix some SymbolicReference types --- git/refs/symbolic.py | 80 +++++++++++++++++++++++++--------------------------- git/refs/tag.py | 2 +- git/repo/base.py | 2 +- 3 files changed, 41 insertions(+), 43 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 9a5a4479..86dc04e1 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -1,4 +1,3 @@ -from git.types import PathLike import os from git.compat import defenc @@ -17,13 +16,11 @@ from gitdb.exc import ( BadName ) -import os.path as osp - from .log import RefLog # typing ------------------------------------------------------------------ -from typing import Any, Iterator, List, Match, Optional, Tuple, Type, TypeVar, Union, TYPE_CHECKING # NOQA +from typing import Any, Iterator, List, Match, Optional, Tuple, Type, TypeVar, Union, TYPE_CHECKING, cast # NOQA from git.types import Commit_ish, PathLike, TBD, Literal # NOQA if TYPE_CHECKING: @@ -38,9 +35,9 @@ T_References = TypeVar('T_References', bound='SymbolicReference') __all__ = ["SymbolicReference"] -def _git_dir(repo, path): +def _git_dir(repo: 'Repo', path: PathLike) -> PathLike: """ Find the git dir that's appropriate for the path""" - name = "%s" % (path,) + name = f"{path}" if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']: return repo.git_dir return repo.common_dir @@ -60,46 +57,46 @@ class SymbolicReference(object): _remote_common_path_default = "refs/remotes" _id_attribute_ = "name" - def __init__(self, repo: 'Repo', path: PathLike, check_path: bool = False): + def __init__(self, repo: 'Repo', path: PathLike, check_path: bool = False) -> None: self.repo = repo self.path = str(path) def __str__(self) -> str: return self.path - def __repr__(self): + def __repr__(self) -> str: return '' % (self.__class__.__name__, self.path) - def __eq__(self, other): + def __eq__(self, other) -> bool: if hasattr(other, 'path'): return self.path == other.path return False - def __ne__(self, other): + def __ne__(self, other) -> bool: return not (self == other) def __hash__(self): return hash(self.path) @property - def name(self): + def name(self) -> str: """ :return: In case of symbolic references, the shortest assumable name is the path itself.""" - return self.path + return str(self.path) @property - def abspath(self): + def abspath(self) -> PathLike: return join_path_native(_git_dir(self.repo, self.path), self.path) @classmethod - def _get_packed_refs_path(cls, repo): - return osp.join(repo.common_dir, 'packed-refs') + def _get_packed_refs_path(cls, repo: 'Repo') -> str: + return os.path.join(repo.common_dir, 'packed-refs') @classmethod - def _iter_packed_refs(cls, repo): - """Returns an iterator yielding pairs of sha1/path pairs (as bytes) for the corresponding refs. + def _iter_packed_refs(cls, repo: 'Repo') -> Iterator[Tuple[str, str]]: + """Returns an iterator yielding pairs of sha1/path pairs for the corresponding refs. :note: The packed refs file will be kept open as long as we iterate""" try: with open(cls._get_packed_refs_path(repo), 'rt', encoding='UTF-8') as fp: @@ -127,7 +124,7 @@ class SymbolicReference(object): if line[0] == '^': continue - yield tuple(line.split(' ', 1)) + yield cast(Tuple[str, str], tuple(line.split(' ', 1))) # END for each line except OSError: return None @@ -138,7 +135,7 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo, ref_path): + def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required @@ -150,14 +147,14 @@ class SymbolicReference(object): # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo, ref_path): + def _get_ref_info_helper(cls, repo: Repo, ref_path: PathLike): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" - tokens = None + tokens: Union[List[str], Tuple[str, str], None] = None repodir = _git_dir(repo, ref_path) try: - with open(osp.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: + with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: value = fp.read().rstrip() # Don't only split on spaces, but on whitespace, which allows to parse lines like # 60b64ef992065e2600bfef6187a97f92398a9144 branch 'master' of git-server:/path/to/repo @@ -189,7 +186,7 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) @classmethod - def _get_ref_info(cls, repo, ref_path): + def _get_ref_info(cls, repo: 'Repo', ref_path: PathLike): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" @@ -424,21 +421,22 @@ class SymbolicReference(object): return RefLog.entry_at(RefLog.path(self), index) @classmethod - def to_full_path(cls, path) -> PathLike: + def to_full_path(cls, path: Union[PathLike, 'SymbolicReference']) -> str: """ :return: string with a full repository-relative path which can be used to initialize a Reference instance, for instance by using ``Reference.from_path``""" if isinstance(path, SymbolicReference): path = path.path - full_ref_path = path + full_ref_path = str(path) if not cls._common_path_default: return full_ref_path - if not path.startswith(cls._common_path_default + "/"): + + if not str(path).startswith(cls._common_path_default + "/"): full_ref_path = '%s/%s' % (cls._common_path_default, path) return full_ref_path @classmethod - def delete(cls, repo, path): + def delete(cls, repo: 'Repo', path: PathLike) -> None: """Delete the reference at the given path :param repo: @@ -449,8 +447,8 @@ class SymbolicReference(object): or just "myreference", hence 'refs/' is implied. Alternatively the symbolic reference to be deleted""" full_ref_path = cls.to_full_path(path) - abs_path = osp.join(repo.common_dir, full_ref_path) - if osp.exists(abs_path): + abs_path = os.path.join(repo.common_dir, full_ref_path) + if os.path.exists(abs_path): os.remove(abs_path) else: # check packed refs @@ -460,8 +458,8 @@ class SymbolicReference(object): new_lines = [] made_change = False dropped_last_line = False - for line in reader: - line = line.decode(defenc) + for line_bytes in reader: + line = line_bytes.decode(defenc) _, _, line_ref = line.partition(' ') line_ref = line_ref.strip() # keep line if it is a comment or if the ref to delete is not @@ -491,7 +489,7 @@ class SymbolicReference(object): # delete the reflog reflog_path = RefLog.path(cls(repo, full_ref_path)) - if osp.isfile(reflog_path): + if os.path.isfile(reflog_path): os.remove(reflog_path) # END remove reflog @@ -504,14 +502,14 @@ class SymbolicReference(object): instead""" git_dir = _git_dir(repo, path) full_ref_path = cls.to_full_path(path) - abs_ref_path = osp.join(git_dir, full_ref_path) + abs_ref_path = os.path.join(git_dir, full_ref_path) # figure out target data target = reference if resolve: target = repo.rev_parse(str(reference)) - if not force and osp.isfile(abs_ref_path): + if not force and os.path.isfile(abs_ref_path): target_data = str(target) if isinstance(target, SymbolicReference): target_data = target.path @@ -561,7 +559,7 @@ class SymbolicReference(object): :note: This does not alter the current HEAD, index or Working Tree""" return cls._create(repo, path, cls._resolve_ref_on_create, reference, force, logmsg) - def rename(self, new_path, force=False): + def rename(self, new_path: str, force: bool = False) -> 'SymbolicReference': """Rename self to a new path :param new_path: @@ -579,9 +577,9 @@ class SymbolicReference(object): if self.path == new_path: return self - new_abs_path = osp.join(_git_dir(self.repo, new_path), new_path) - cur_abs_path = osp.join(_git_dir(self.repo, self.path), self.path) - if osp.isfile(new_abs_path): + new_abs_path = os.path.join(_git_dir(self.repo, new_path), new_path) + cur_abs_path = os.path.join(_git_dir(self.repo, self.path), self.path) + if os.path.isfile(new_abs_path): if not force: # if they point to the same file, its not an error with open(new_abs_path, 'rb') as fd1: @@ -596,8 +594,8 @@ class SymbolicReference(object): os.remove(new_abs_path) # END handle existing target file - dname = osp.dirname(new_abs_path) - if not osp.isdir(dname): + dname = os.path.dirname(new_abs_path) + if not os.path.isdir(dname): os.makedirs(dname) # END create directory @@ -632,7 +630,7 @@ class SymbolicReference(object): # read packed refs for _sha, rela_path in cls._iter_packed_refs(repo): - if rela_path.startswith(common_path): + if rela_path.startswith(str(common_path)): rela_paths.add(rela_path) # END relative path matches common path # END packed refs reading diff --git a/git/refs/tag.py b/git/refs/tag.py index 281ce09a..3aec99fe 100644 --- a/git/refs/tag.py +++ b/git/refs/tag.py @@ -111,7 +111,7 @@ class TagReference(Reference): return TagReference(repo, "%s/%s" % (cls._common_path_default, path)) @classmethod - def delete(cls, repo: 'Repo', *tags: 'TagReference') -> None: + def delete(cls, repo: 'Repo', *tags: 'TagReference') -> None: # type: ignore[override] """Delete the given existing tag or tags""" repo.git.tag("-d", *tags) diff --git a/git/repo/base.py b/git/repo/base.py index 74f27b2e..12efe9c6 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -429,7 +429,7 @@ class Repo(object): :return: newly created Head Reference""" return Head.create(self, path, commit, logmsg, force) - def delete_head(self, *heads: 'SymbolicReference', **kwargs: Any) -> None: + def delete_head(self, *heads: 'Head', **kwargs: Any) -> None: """Delete the given heads :param kwargs: Additional keyword arguments to be passed to git-branch""" -- cgit v1.2.1 From 7cf30c1cf4a6494916a162983bdb439388d59ff3 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 17:22:09 +0100 Subject: Fix forwardref --- git/refs/symbolic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 86dc04e1..4919ea83 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -147,7 +147,7 @@ class SymbolicReference(object): # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo: Repo, ref_path: PathLike): + def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" -- cgit v1.2.1 From 5b880c0e98e41276de9fc498b25727c149cfcc40 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 17:39:01 +0100 Subject: Fix more missing types in Symbolic.py --- git/refs/symbolic.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 4919ea83..2e8544d3 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -25,7 +25,7 @@ from git.types import Commit_ish, PathLike, TBD, Literal if TYPE_CHECKING: from git.repo import Repo - from git.refs import Reference + from git.refs import Reference, Head, HEAD, TagReference, RemoteReference T_References = TypeVar('T_References', bound='SymbolicReference') @@ -141,13 +141,13 @@ class SymbolicReference(object): intermediate references as required :param repo: the repository containing the reference at ref_path""" while True: - hexsha, ref_path = cls._get_ref_info(repo, ref_path) + hexsha, _ref_path_out = cls._get_ref_info(repo, ref_path) if hexsha is not None: return hexsha # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike): + def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, PathLike]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" @@ -186,13 +186,14 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) @classmethod - def _get_ref_info(cls, repo: 'Repo', ref_path: PathLike): + def _get_ref_info(cls, repo: 'Repo', ref_path: PathLike + ) -> Union[Tuple[str, None], Tuple[None, PathLike]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" return cls._get_ref_info_helper(repo, ref_path) - def _get_object(self): + def _get_object(self) -> Commit_ish: """ :return: The object our ref currently refers to. Refs can be cached, they will @@ -201,7 +202,7 @@ class SymbolicReference(object): # Our path will be resolved to the hexsha which will be used accordingly return Object.new_from_sha(self.repo, hex_to_bin(self.dereference_recursive(self.repo, self.path))) - def _get_commit(self): + def _get_commit(self) -> 'Commit': """ :return: Commit object we point to, works for detached and non-detached @@ -216,7 +217,8 @@ class SymbolicReference(object): # END handle type return obj - def set_commit(self, commit: Union[Commit, 'SymbolicReference', str], logmsg=None): + def set_commit(self, commit: Union[Commit, 'SymbolicReference', str], + logmsg: Union[str, None] = None) -> None: """As set_object, but restricts the type of object to be a Commit :raise ValueError: If commit is not a Commit object or doesn't point to @@ -243,7 +245,8 @@ class SymbolicReference(object): # we leave strings to the rev-parse method below self.set_object(commit, logmsg) - return self + # return self + return None def set_object(self, object, logmsg=None): # @ReservedAssignment """Set the object we point to, possibly dereference our symbolic reference first. @@ -275,7 +278,8 @@ class SymbolicReference(object): commit = property(_get_commit, set_commit, doc="Query or set commits directly") object = property(_get_object, set_object, doc="Return the object our ref currently refers to") - def _get_reference(self): + def _get_reference(self + ) -> Union['HEAD', 'Head', 'RemoteReference', 'TagReference', 'Reference', 'SymbolicReference']: """:return: Reference Object we point to :raise TypeError: If this symbolic reference is detached, hence it doesn't point to a reference, but to a commit""" -- cgit v1.2.1 From 07d71e57c422e8df943fe14f5e2a1b4856d5077c Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 17:58:23 +0100 Subject: Fix more missing types in Symbolic.py --- git/refs/symbolic.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 2e8544d3..d5dc87c6 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -358,11 +358,11 @@ class SymbolicReference(object): return self # aliased reference - reference: Union[Commit_ish, 'Reference'] = property( # type: ignore + reference: Union[Commit_ish, 'Head', 'Reference'] = property( # type: ignore _get_reference, set_reference, doc="Returns the Reference we point to") ref = reference - def is_valid(self): + def is_valid(self) -> bool: """ :return: True if the reference is valid, hence it can be read and points to @@ -531,7 +531,7 @@ class SymbolicReference(object): return ref @classmethod - def create(cls, repo: 'Repo', path: PathLike, reference: Union[Commit_ish, str] = 'HEAD', + def create(cls, repo: 'Repo', path: PathLike, reference: Union[Commit_ish, str] = 'SymbolicReference', logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any): """Create a new symbolic reference, hence a reference pointing , to another reference. -- cgit v1.2.1 From b8b07b9ff5fe478b872d3da767e549841da02205 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 18:03:29 +0100 Subject: Fix more missing types in Symbolic.py. --- git/refs/tag.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'git') diff --git a/git/refs/tag.py b/git/refs/tag.py index 3aec99fe..4cbea5ea 100644 --- a/git/refs/tag.py +++ b/git/refs/tag.py @@ -98,7 +98,9 @@ class TagReference(Reference): Additional keyword arguments to be passed to git-tag :return: A new TagReference""" - args = (path, reference) + if 'ref' in kwargs and kwargs['ref']: + reference = kwargs['ref'] + if logmsg: kwargs['m'] = logmsg elif 'message' in kwargs and kwargs['message']: @@ -107,6 +109,8 @@ class TagReference(Reference): if force: kwargs['f'] = True + args = (path, reference) + repo.git.tag(*args, **kwargs) return TagReference(repo, "%s/%s" % (cls._common_path_default, path)) -- cgit v1.2.1 From 390efbf521d62d9cb188c7688288878ef1b1b45d Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 20:40:29 +0100 Subject: Fix more missing types in Symbolic.py, cos GuthubActions pytest stuck --- git/objects/submodule/base.py | 8 +++++--- git/refs/symbolic.py | 41 +++++++++++++++++++++++++---------------- git/refs/tag.py | 6 ++++-- git/repo/base.py | 3 ++- 4 files changed, 36 insertions(+), 22 deletions(-) (limited to 'git') diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 29212167..14351190 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -563,6 +563,7 @@ class Submodule(IndexObject, TraversableIterableObj): progress.update(op, i, len_rmts, prefix + "Done fetching remote of submodule %r" % self.name) # END fetch new data except InvalidGitRepositoryError: + mrepo = None if not init: return self # END early abort if init is not allowed @@ -603,7 +604,7 @@ class Submodule(IndexObject, TraversableIterableObj): # make sure HEAD is not detached mrepo.head.set_reference(local_branch, logmsg="submodule: attaching head to %s" % local_branch) - mrepo.head.ref.set_tracking_branch(remote_branch) + mrepo.head.reference.set_tracking_branch(remote_branch) except (IndexError, InvalidGitRepositoryError): log.warning("Failed to checkout tracking branch %s", self.branch_path) # END handle tracking branch @@ -629,13 +630,14 @@ class Submodule(IndexObject, TraversableIterableObj): if mrepo is not None and to_latest_revision: msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir if not is_detached: - rref = mrepo.head.ref.tracking_branch() + rref = mrepo.head.reference.tracking_branch() if rref is not None: rcommit = rref.commit binsha = rcommit.binsha hexsha = rcommit.hexsha else: - log.error("%s a tracking branch was not set for local branch '%s'", msg_base, mrepo.head.ref) + log.error("%s a tracking branch was not set for local branch '%s'", + msg_base, mrepo.head.reference) # END handle remote ref else: log.error("%s there was no local tracking branch", msg_base) diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index d5dc87c6..4ae7a9d1 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -25,7 +25,7 @@ from git.types import Commit_ish, PathLike, TBD, Literal if TYPE_CHECKING: from git.repo import Repo - from git.refs import Reference, Head, HEAD, TagReference, RemoteReference + from git.refs import Reference, Head, TagReference, RemoteReference T_References = TypeVar('T_References', bound='SymbolicReference') @@ -60,6 +60,7 @@ class SymbolicReference(object): def __init__(self, repo: 'Repo', path: PathLike, check_path: bool = False) -> None: self.repo = repo self.path = str(path) + self.ref = self._get_reference() def __str__(self) -> str: return self.path @@ -279,7 +280,7 @@ class SymbolicReference(object): object = property(_get_object, set_object, doc="Return the object our ref currently refers to") def _get_reference(self - ) -> Union['HEAD', 'Head', 'RemoteReference', 'TagReference', 'Reference', 'SymbolicReference']: + ) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: """:return: Reference Object we point to :raise TypeError: If this symbolic reference is detached, hence it doesn't point to a reference, but to a commit""" @@ -288,7 +289,8 @@ class SymbolicReference(object): raise TypeError("%s is a detached symbolic reference as it points to %r" % (self, sha)) return self.from_path(self.repo, target_ref_path) - def set_reference(self, ref, logmsg=None): + def set_reference(self, ref: Union[str, Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None + ) -> None: """Set ourselves to the given ref. It will stay a symbol if the ref is a Reference. Otherwise an Object, given as Object instance or refspec, is assumed and if valid, will be set which effectively detaches the refererence if it was a purely @@ -355,12 +357,16 @@ class SymbolicReference(object): if logmsg is not None: self.log_append(oldbinsha, logmsg) - return self + return None - # aliased reference - reference: Union[Commit_ish, 'Head', 'Reference'] = property( # type: ignore - _get_reference, set_reference, doc="Returns the Reference we point to") - ref = reference + @ property + def reference(self) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: + return self._get_reference() + + @ reference.setter + def reference(self, ref: Union[str, Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None + ) -> None: + return self.set_reference(ref=ref, logmsg=logmsg) def is_valid(self) -> bool: """ @@ -374,7 +380,7 @@ class SymbolicReference(object): else: return True - @property + @ property def is_detached(self): """ :return: @@ -424,7 +430,7 @@ class SymbolicReference(object): In that case, it will be faster than the ``log()`` method""" return RefLog.entry_at(RefLog.path(self), index) - @classmethod + @ classmethod def to_full_path(cls, path: Union[PathLike, 'SymbolicReference']) -> str: """ :return: string with a full repository-relative path which can be used to initialize @@ -439,7 +445,7 @@ class SymbolicReference(object): full_ref_path = '%s/%s' % (cls._common_path_default, path) return full_ref_path - @classmethod + @ classmethod def delete(cls, repo: 'Repo', path: PathLike) -> None: """Delete the reference at the given path @@ -497,8 +503,10 @@ class SymbolicReference(object): os.remove(reflog_path) # END remove reflog - @classmethod - def _create(cls, repo, path, resolve, reference, force, logmsg=None): + @ classmethod + def _create(cls: Type[T_References], repo: 'Repo', path: PathLike, resolve: bool, + reference: Union[str, 'SymbolicReference'], + force: bool, logmsg: Union[str, None] = None) -> T_References: """internal method used to create a new symbolic reference. If resolve is False, the reference will be taken as is, creating a proper symbolic reference. Otherwise it will be resolved to the @@ -531,8 +539,9 @@ class SymbolicReference(object): return ref @classmethod - def create(cls, repo: 'Repo', path: PathLike, reference: Union[Commit_ish, str] = 'SymbolicReference', - logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any): + def create(cls: Type[T_References], repo: 'Repo', path: PathLike, + reference: Union[Commit_ish, str, 'SymbolicReference'] = 'SymbolicReference', + logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any) -> T_References: """Create a new symbolic reference, hence a reference pointing , to another reference. :param repo: @@ -669,7 +678,7 @@ class SymbolicReference(object): return (r for r in cls._iter_items(repo, common_path) if r.__class__ == SymbolicReference or not r.is_detached) @classmethod - def from_path(cls, repo, path): + def from_path(cls, repo: 'Repo', path: PathLike) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: """ :param path: full .git-directory-relative path name to the Reference to instantiate :note: use to_full_path() if you only have a partial path of a known Reference Type diff --git a/git/refs/tag.py b/git/refs/tag.py index 4cbea5ea..ce2a58a0 100644 --- a/git/refs/tag.py +++ b/git/refs/tag.py @@ -4,13 +4,14 @@ __all__ = ["TagReference", "Tag"] # typing ------------------------------------------------------------------ -from typing import Any, Union, TYPE_CHECKING +from typing import Any, Type, Union, TYPE_CHECKING from git.types import Commit_ish, PathLike if TYPE_CHECKING: from git.repo import Repo from git.objects import Commit from git.objects import TagObject + from git.refs import SymbolicReference # ------------------------------------------------------------------------------ @@ -68,7 +69,8 @@ class TagReference(Reference): return Reference._get_object(self) @classmethod - def create(cls, repo: 'Repo', path: PathLike, reference: Union[Commit_ish, str] = 'HEAD', + def create(cls: Type['TagReference'], repo: 'Repo', path: PathLike, + reference: Union[Commit_ish, str, 'SymbolicReference'] = 'HEAD', logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any) -> 'TagReference': """Create a new tag reference. diff --git a/git/repo/base.py b/git/repo/base.py index 12efe9c6..355f9399 100644 --- a/git/repo/base.py +++ b/git/repo/base.py @@ -788,9 +788,10 @@ class Repo(object): return proc.replace("\\\\", "\\").replace('"', "").split("\n") @property - def active_branch(self) -> 'HEAD': + def active_branch(self) -> Head: """The name of the currently active branch. :return: Head to the active branch""" + # reveal_type(self.head.reference) # => Reference return self.head.reference def blame_incremental(self, rev: TBD, file: TBD, **kwargs: Any) -> Optional[Iterator['BlameEntry']]: -- cgit v1.2.1 From adc00dd1773ee1b532803b2272cc989f11e09f8a Mon Sep 17 00:00:00 2001 From: Yobmod Date: Wed, 28 Jul 2021 21:50:49 +0100 Subject: Fix more missing types in Symbolic.py, cos GuthubActions pytest stuck --- git/objects/commit.py | 1 + git/objects/util.py | 5 +++++ git/refs/head.py | 13 +++++++------ git/refs/reference.py | 4 +++- git/refs/symbolic.py | 47 +++++++++++++++++++++++++++++------------------ git/refs/tag.py | 4 ++-- 6 files changed, 47 insertions(+), 27 deletions(-) (limited to 'git') diff --git a/git/objects/commit.py b/git/objects/commit.py index 884f6522..9d709656 100644 --- a/git/objects/commit.py +++ b/git/objects/commit.py @@ -128,6 +128,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): as what time.altzone returns. The sign is inverted compared to git's UTC timezone.""" super(Commit, self).__init__(repo, binsha) + self.binsha = binsha if tree is not None: assert isinstance(tree, Tree), "Tree needs to be a Tree instance, was %s" % type(tree) if tree is not None: diff --git a/git/objects/util.py b/git/objects/util.py index ef1ae77b..db7807c2 100644 --- a/git/objects/util.py +++ b/git/objects/util.py @@ -493,6 +493,11 @@ class TraversableIterableObj(IterableObj, Traversable): return super(TraversableIterableObj, self)._list_traverse(* args, **kwargs) @ overload # type: ignore + def traverse(self: T_TIobj + ) -> Iterator[T_TIobj]: + ... + + @ overload def traverse(self: T_TIobj, predicate: Callable[[Union[T_TIobj, Tuple[Union[T_TIobj, None], T_TIobj]], int], bool], prune: Callable[[Union[T_TIobj, Tuple[Union[T_TIobj, None], T_TIobj]], int], bool], diff --git a/git/refs/head.py b/git/refs/head.py index 4b9bf33c..260bf5e7 100644 --- a/git/refs/head.py +++ b/git/refs/head.py @@ -1,4 +1,4 @@ -from git.config import SectionConstraint +from git.config import GitConfigParser, SectionConstraint from git.util import join_path from git.exc import GitCommandError @@ -203,7 +203,7 @@ class Head(Reference): self.path = "%s/%s" % (self._common_path_default, new_path) return self - def checkout(self, force: bool = False, **kwargs: Any): + def checkout(self, force: bool = False, **kwargs: Any) -> Union['HEAD', 'Head']: """Checkout this head by setting the HEAD to this reference, by updating the index to reflect the tree we point to and by updating the working tree to reflect the latest index. @@ -235,10 +235,11 @@ class Head(Reference): self.repo.git.checkout(self, **kwargs) if self.repo.head.is_detached: return self.repo.head - return self.repo.active_branch + else: + return self.repo.active_branch #{ Configuration - def _config_parser(self, read_only: bool) -> SectionConstraint: + def _config_parser(self, read_only: bool) -> SectionConstraint[GitConfigParser]: if read_only: parser = self.repo.config_reader() else: @@ -247,13 +248,13 @@ class Head(Reference): return SectionConstraint(parser, 'branch "%s"' % self.name) - def config_reader(self) -> SectionConstraint: + def config_reader(self) -> SectionConstraint[GitConfigParser]: """ :return: A configuration parser instance constrained to only read this instance's values""" return self._config_parser(read_only=True) - def config_writer(self) -> SectionConstraint: + def config_writer(self) -> SectionConstraint[GitConfigParser]: """ :return: A configuration writer instance with read-and write access to options of this head""" diff --git a/git/refs/reference.py b/git/refs/reference.py index 64662281..bc2c6e80 100644 --- a/git/refs/reference.py +++ b/git/refs/reference.py @@ -62,7 +62,9 @@ class Reference(SymbolicReference, LazyMixin, IterableObj): #{ Interface - def set_object(self, object: Commit_ish, logmsg: Union[str, None] = None) -> 'Reference': # @ReservedAssignment + # @ReservedAssignment + def set_object(self, object: Union[Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None + ) -> 'SymbolicReference': """Special version which checks if the head-log needs an update as well :return: self""" oldbinsha = None diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 4ae7a9d1..4171fe23 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -16,7 +16,7 @@ from gitdb.exc import ( BadName ) -from .log import RefLog +from .log import RefLog, RefLogEntry # typing ------------------------------------------------------------------ @@ -26,6 +26,8 @@ from git.types import Commit_ish, PathLike, TBD, Literal if TYPE_CHECKING: from git.repo import Repo from git.refs import Reference, Head, TagReference, RemoteReference + from git.config import GitConfigParser + from git.objects.commit import Actor T_References = TypeVar('T_References', bound='SymbolicReference') @@ -229,11 +231,13 @@ class SymbolicReference(object): invalid_type = False if isinstance(commit, Object): invalid_type = commit.type != Commit.type + commit = cast('Commit', commit) elif isinstance(commit, SymbolicReference): invalid_type = commit.object.type != Commit.type else: try: - invalid_type = self.repo.rev_parse(commit).type != Commit.type + commit = self.repo.rev_parse(commit) + invalid_type = commit.type != Commit.type except (BadObject, BadName) as e: raise ValueError("Invalid object: %s" % commit) from e # END handle exception @@ -249,7 +253,9 @@ class SymbolicReference(object): # return self return None - def set_object(self, object, logmsg=None): # @ReservedAssignment + def set_object(self, object: Union[Commit_ish, 'SymbolicReference'], + logmsg: Union[str, None] = None + ) -> 'SymbolicReference': # @ReservedAssignment """Set the object we point to, possibly dereference our symbolic reference first. If the reference does not exist, it will be created @@ -276,8 +282,8 @@ class SymbolicReference(object): # set the commit on our reference return self._get_reference().set_object(object, logmsg) - commit = property(_get_commit, set_commit, doc="Query or set commits directly") - object = property(_get_object, set_object, doc="Return the object our ref currently refers to") + commit = cast('Commit', property(_get_commit, set_commit, doc="Query or set commits directly")) + object = property(_get_object, set_object, doc="Return the object our ref currently refers to") # type: ignore def _get_reference(self ) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: @@ -290,7 +296,7 @@ class SymbolicReference(object): return self.from_path(self.repo, target_ref_path) def set_reference(self, ref: Union[str, Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None - ) -> None: + ) -> 'SymbolicReference': """Set ourselves to the given ref. It will stay a symbol if the ref is a Reference. Otherwise an Object, given as Object instance or refspec, is assumed and if valid, will be set which effectively detaches the refererence if it was a purely @@ -331,7 +337,7 @@ class SymbolicReference(object): raise TypeError("Require commit, got %r" % obj) # END verify type - oldbinsha = None + oldbinsha: bytes = b'' if logmsg is not None: try: oldbinsha = self.commit.binsha @@ -357,7 +363,7 @@ class SymbolicReference(object): if logmsg is not None: self.log_append(oldbinsha, logmsg) - return None + return self @ property def reference(self) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: @@ -365,7 +371,7 @@ class SymbolicReference(object): @ reference.setter def reference(self, ref: Union[str, Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None - ) -> None: + ) -> 'SymbolicReference': return self.set_reference(ref=ref, logmsg=logmsg) def is_valid(self) -> bool: @@ -392,7 +398,7 @@ class SymbolicReference(object): except TypeError: return True - def log(self): + def log(self) -> 'RefLog': """ :return: RefLog for this reference. Its last entry reflects the latest change applied to this reference @@ -401,7 +407,8 @@ class SymbolicReference(object): instead of calling this method repeatedly. It should be considered read-only.""" return RefLog.from_file(RefLog.path(self)) - def log_append(self, oldbinsha, message, newbinsha=None): + def log_append(self, oldbinsha: bytes, message: Union[str, None], + newbinsha: Union[bytes, None] = None) -> 'RefLogEntry': """Append a logentry to the logfile of this ref :param oldbinsha: binary sha this ref used to point to @@ -413,15 +420,19 @@ class SymbolicReference(object): # correct to allow overriding the committer on a per-commit level. # See https://github.com/gitpython-developers/GitPython/pull/146 try: - committer_or_reader = self.commit.committer + committer_or_reader: Union['Actor', 'GitConfigParser'] = self.commit.committer except ValueError: committer_or_reader = self.repo.config_reader() # end handle newly cloned repositories - return RefLog.append_entry(committer_or_reader, RefLog.path(self), oldbinsha, - (newbinsha is None and self.commit.binsha) or newbinsha, - message) + if newbinsha is None: + newbinsha = self.commit.binsha + + if message is None: + message = '' + + return RefLog.append_entry(committer_or_reader, RefLog.path(self), oldbinsha, newbinsha, message) - def log_entry(self, index): + def log_entry(self, index: int) -> RefLogEntry: """:return: RefLogEntry at the given index :param index: python list compatible positive or negative index @@ -540,7 +551,7 @@ class SymbolicReference(object): @classmethod def create(cls: Type[T_References], repo: 'Repo', path: PathLike, - reference: Union[Commit_ish, str, 'SymbolicReference'] = 'SymbolicReference', + reference: Union[str, 'SymbolicReference'] = 'SymbolicReference', logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any) -> T_References: """Create a new symbolic reference, hence a reference pointing , to another reference. @@ -553,7 +564,7 @@ class SymbolicReference(object): :param reference: The reference to which the new symbolic reference should point to. - If it is a commit'ish, the symbolic ref will be detached. + If it is a ref to a commit'ish, the symbolic ref will be detached. :param force: if True, force creation even if a symbolic reference with that name already exists. diff --git a/git/refs/tag.py b/git/refs/tag.py index ce2a58a0..edfab33d 100644 --- a/git/refs/tag.py +++ b/git/refs/tag.py @@ -70,7 +70,7 @@ class TagReference(Reference): @classmethod def create(cls: Type['TagReference'], repo: 'Repo', path: PathLike, - reference: Union[Commit_ish, str, 'SymbolicReference'] = 'HEAD', + reference: Union[str, 'SymbolicReference'] = 'HEAD', logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any) -> 'TagReference': """Create a new tag reference. @@ -80,7 +80,7 @@ class TagReference(Reference): The prefix refs/tags is implied :param ref: - A reference to the object you want to tag. It can be a commit, tree or + A reference to the Object you want to tag. The Object can be a commit, tree or blob. :param logmsg: -- cgit v1.2.1 From 15d1c01c132bc6fbdb21146578df35a8f7e2195e Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 15:51:34 +0100 Subject: Add type to symbolicreference.name() --- git/refs/remote.py | 4 +- git/refs/symbolic.py | 134 +++++++++++++++++++++------------------------------ 2 files changed, 56 insertions(+), 82 deletions(-) (limited to 'git') diff --git a/git/refs/remote.py b/git/refs/remote.py index 8a680a4a..9b74d87f 100644 --- a/git/refs/remote.py +++ b/git/refs/remote.py @@ -9,7 +9,7 @@ __all__ = ["RemoteReference"] # typing ------------------------------------------------------------------ -from typing import Any, NoReturn, Union, TYPE_CHECKING +from typing import Any, Iterator, NoReturn, Union, TYPE_CHECKING from git.types import PathLike @@ -28,7 +28,7 @@ class RemoteReference(Head): @classmethod def iter_items(cls, repo: 'Repo', common_path: Union[PathLike, None] = None, remote: Union['Remote', None] = None, *args: Any, **kwargs: Any - ) -> 'RemoteReference': + ) -> Iterator['RemoteReference']: """Iterate remote references, and if given, constrain them to the given remote""" common_path = common_path or cls._common_path_default if remote is not None: diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 4171fe23..779fe5a5 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -1,3 +1,4 @@ +from git.types import PathLike import os from git.compat import defenc @@ -16,7 +17,7 @@ from gitdb.exc import ( BadName ) -from .log import RefLog, RefLogEntry +from .log import RefLog # typing ------------------------------------------------------------------ @@ -25,9 +26,6 @@ from git.types import Commit_ish, PathLike, TBD, Literal if TYPE_CHECKING: from git.repo import Repo - from git.refs import Reference, Head, TagReference, RemoteReference - from git.config import GitConfigParser - from git.objects.commit import Actor T_References = TypeVar('T_References', bound='SymbolicReference') @@ -37,9 +35,9 @@ T_References = TypeVar('T_References', bound='SymbolicReference') __all__ = ["SymbolicReference"] -def _git_dir(repo: 'Repo', path: PathLike) -> PathLike: +def _git_dir(repo, path): """ Find the git dir that's appropriate for the path""" - name = f"{path}" + name = "%s" % (path,) if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']: return repo.git_dir return repo.common_dir @@ -59,23 +57,22 @@ class SymbolicReference(object): _remote_common_path_default = "refs/remotes" _id_attribute_ = "name" - def __init__(self, repo: 'Repo', path: PathLike, check_path: bool = False) -> None: + def __init__(self, repo: 'Repo', path: PathLike, check_path: bool = False): self.repo = repo self.path = str(path) - self.ref = self._get_reference() def __str__(self) -> str: return self.path - def __repr__(self) -> str: + def __repr__(self): return '' % (self.__class__.__name__, self.path) - def __eq__(self, other) -> bool: + def __eq__(self, other): if hasattr(other, 'path'): return self.path == other.path return False - def __ne__(self, other) -> bool: + def __ne__(self, other): return not (self == other) def __hash__(self): @@ -87,7 +84,7 @@ class SymbolicReference(object): :return: In case of symbolic references, the shortest assumable name is the path itself.""" - return str(self.path) + return self.path @property def abspath(self) -> PathLike: @@ -99,7 +96,7 @@ class SymbolicReference(object): @classmethod def _iter_packed_refs(cls, repo: 'Repo') -> Iterator[Tuple[str, str]]: - """Returns an iterator yielding pairs of sha1/path pairs for the corresponding refs. + """Returns an iterator yielding pairs of sha1/path pairs (as strings) for the corresponding refs. :note: The packed refs file will be kept open as long as we iterate""" try: with open(cls._get_packed_refs_path(repo), 'rt', encoding='UTF-8') as fp: @@ -138,23 +135,23 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: + def dereference_recursive(cls, repo, ref_path): """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required :param repo: the repository containing the reference at ref_path""" while True: - hexsha, _ref_path_out = cls._get_ref_info(repo, ref_path) + hexsha, ref_path = cls._get_ref_info(repo, ref_path) if hexsha is not None: return hexsha # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, PathLike]]: + def _get_ref_info_helper(cls, repo, ref_path): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" - tokens: Union[List[str], Tuple[str, str], None] = None + tokens = None repodir = _git_dir(repo, ref_path) try: with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: @@ -189,14 +186,13 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) @classmethod - def _get_ref_info(cls, repo: 'Repo', ref_path: PathLike - ) -> Union[Tuple[str, None], Tuple[None, PathLike]]: + def _get_ref_info(cls, repo, ref_path): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" return cls._get_ref_info_helper(repo, ref_path) - def _get_object(self) -> Commit_ish: + def _get_object(self): """ :return: The object our ref currently refers to. Refs can be cached, they will @@ -205,7 +201,7 @@ class SymbolicReference(object): # Our path will be resolved to the hexsha which will be used accordingly return Object.new_from_sha(self.repo, hex_to_bin(self.dereference_recursive(self.repo, self.path))) - def _get_commit(self) -> 'Commit': + def _get_commit(self): """ :return: Commit object we point to, works for detached and non-detached @@ -220,8 +216,7 @@ class SymbolicReference(object): # END handle type return obj - def set_commit(self, commit: Union[Commit, 'SymbolicReference', str], - logmsg: Union[str, None] = None) -> None: + def set_commit(self, commit: Union[Commit, 'SymbolicReference', str], logmsg=None): """As set_object, but restricts the type of object to be a Commit :raise ValueError: If commit is not a Commit object or doesn't point to @@ -231,13 +226,11 @@ class SymbolicReference(object): invalid_type = False if isinstance(commit, Object): invalid_type = commit.type != Commit.type - commit = cast('Commit', commit) elif isinstance(commit, SymbolicReference): invalid_type = commit.object.type != Commit.type else: try: - commit = self.repo.rev_parse(commit) - invalid_type = commit.type != Commit.type + invalid_type = self.repo.rev_parse(commit).type != Commit.type except (BadObject, BadName) as e: raise ValueError("Invalid object: %s" % commit) from e # END handle exception @@ -250,12 +243,9 @@ class SymbolicReference(object): # we leave strings to the rev-parse method below self.set_object(commit, logmsg) - # return self - return None + return self - def set_object(self, object: Union[Commit_ish, 'SymbolicReference'], - logmsg: Union[str, None] = None - ) -> 'SymbolicReference': # @ReservedAssignment + def set_object(self, object, logmsg=None): # @ReservedAssignment """Set the object we point to, possibly dereference our symbolic reference first. If the reference does not exist, it will be created @@ -282,11 +272,10 @@ class SymbolicReference(object): # set the commit on our reference return self._get_reference().set_object(object, logmsg) - commit = cast('Commit', property(_get_commit, set_commit, doc="Query or set commits directly")) - object = property(_get_object, set_object, doc="Return the object our ref currently refers to") # type: ignore + commit = property(_get_commit, set_commit, doc="Query or set commits directly") + object = property(_get_object, set_object, doc="Return the object our ref currently refers to") - def _get_reference(self - ) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: + def _get_reference(self): """:return: Reference Object we point to :raise TypeError: If this symbolic reference is detached, hence it doesn't point to a reference, but to a commit""" @@ -295,8 +284,7 @@ class SymbolicReference(object): raise TypeError("%s is a detached symbolic reference as it points to %r" % (self, sha)) return self.from_path(self.repo, target_ref_path) - def set_reference(self, ref: Union[str, Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None - ) -> 'SymbolicReference': + def set_reference(self, ref, logmsg=None): """Set ourselves to the given ref. It will stay a symbol if the ref is a Reference. Otherwise an Object, given as Object instance or refspec, is assumed and if valid, will be set which effectively detaches the refererence if it was a purely @@ -337,7 +325,7 @@ class SymbolicReference(object): raise TypeError("Require commit, got %r" % obj) # END verify type - oldbinsha: bytes = b'' + oldbinsha = None if logmsg is not None: try: oldbinsha = self.commit.binsha @@ -365,16 +353,11 @@ class SymbolicReference(object): return self - @ property - def reference(self) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: - return self._get_reference() - - @ reference.setter - def reference(self, ref: Union[str, Commit_ish, 'SymbolicReference'], logmsg: Union[str, None] = None - ) -> 'SymbolicReference': - return self.set_reference(ref=ref, logmsg=logmsg) + # aliased reference + reference = property(_get_reference, set_reference, doc="Returns the Reference we point to") + ref: Union[Commit_ish] = reference # type: ignore # Union[str, Commit_ish, SymbolicReference] - def is_valid(self) -> bool: + def is_valid(self): """ :return: True if the reference is valid, hence it can be read and points to @@ -386,7 +369,7 @@ class SymbolicReference(object): else: return True - @ property + @property def is_detached(self): """ :return: @@ -398,7 +381,7 @@ class SymbolicReference(object): except TypeError: return True - def log(self) -> 'RefLog': + def log(self): """ :return: RefLog for this reference. Its last entry reflects the latest change applied to this reference @@ -407,8 +390,7 @@ class SymbolicReference(object): instead of calling this method repeatedly. It should be considered read-only.""" return RefLog.from_file(RefLog.path(self)) - def log_append(self, oldbinsha: bytes, message: Union[str, None], - newbinsha: Union[bytes, None] = None) -> 'RefLogEntry': + def log_append(self, oldbinsha, message, newbinsha=None): """Append a logentry to the logfile of this ref :param oldbinsha: binary sha this ref used to point to @@ -420,19 +402,15 @@ class SymbolicReference(object): # correct to allow overriding the committer on a per-commit level. # See https://github.com/gitpython-developers/GitPython/pull/146 try: - committer_or_reader: Union['Actor', 'GitConfigParser'] = self.commit.committer + committer_or_reader = self.commit.committer except ValueError: committer_or_reader = self.repo.config_reader() # end handle newly cloned repositories - if newbinsha is None: - newbinsha = self.commit.binsha - - if message is None: - message = '' + return RefLog.append_entry(committer_or_reader, RefLog.path(self), oldbinsha, + (newbinsha is None and self.commit.binsha) or newbinsha, + message) - return RefLog.append_entry(committer_or_reader, RefLog.path(self), oldbinsha, newbinsha, message) - - def log_entry(self, index: int) -> RefLogEntry: + def log_entry(self, index): """:return: RefLogEntry at the given index :param index: python list compatible positive or negative index @@ -441,23 +419,22 @@ class SymbolicReference(object): In that case, it will be faster than the ``log()`` method""" return RefLog.entry_at(RefLog.path(self), index) - @ classmethod - def to_full_path(cls, path: Union[PathLike, 'SymbolicReference']) -> str: + @classmethod + 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``""" if isinstance(path, SymbolicReference): path = path.path - full_ref_path = str(path) + full_ref_path = path if not cls._common_path_default: return full_ref_path - - if not str(path).startswith(cls._common_path_default + "/"): + if not path.startswith(cls._common_path_default + "/"): full_ref_path = '%s/%s' % (cls._common_path_default, path) return full_ref_path - @ classmethod - def delete(cls, repo: 'Repo', path: PathLike) -> None: + @classmethod + def delete(cls, repo, path): """Delete the reference at the given path :param repo: @@ -479,8 +456,8 @@ class SymbolicReference(object): new_lines = [] made_change = False dropped_last_line = False - for line_bytes in reader: - line = line_bytes.decode(defenc) + for line in reader: + line = line.decode(defenc) _, _, line_ref = line.partition(' ') line_ref = line_ref.strip() # keep line if it is a comment or if the ref to delete is not @@ -514,10 +491,8 @@ class SymbolicReference(object): os.remove(reflog_path) # END remove reflog - @ classmethod - def _create(cls: Type[T_References], repo: 'Repo', path: PathLike, resolve: bool, - reference: Union[str, 'SymbolicReference'], - force: bool, logmsg: Union[str, None] = None) -> T_References: + @classmethod + def _create(cls, repo, path, resolve, reference, force, logmsg=None): """internal method used to create a new symbolic reference. If resolve is False, the reference will be taken as is, creating a proper symbolic reference. Otherwise it will be resolved to the @@ -550,9 +525,8 @@ class SymbolicReference(object): return ref @classmethod - def create(cls: Type[T_References], repo: 'Repo', path: PathLike, - reference: Union[str, 'SymbolicReference'] = 'SymbolicReference', - logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any) -> T_References: + def create(cls, repo: 'Repo', path: PathLike, reference: Union[Commit_ish, str] = 'HEAD', + logmsg: Union[str, None] = None, force: bool = False, **kwargs: Any): """Create a new symbolic reference, hence a reference pointing , to another reference. :param repo: @@ -564,7 +538,7 @@ class SymbolicReference(object): :param reference: The reference to which the new symbolic reference should point to. - If it is a ref to a commit'ish, the symbolic ref will be detached. + If it is a commit'ish, the symbolic ref will be detached. :param force: if True, force creation even if a symbolic reference with that name already exists. @@ -583,7 +557,7 @@ class SymbolicReference(object): :note: This does not alter the current HEAD, index or Working Tree""" return cls._create(repo, path, cls._resolve_ref_on_create, reference, force, logmsg) - def rename(self, new_path: str, force: bool = False) -> 'SymbolicReference': + def rename(self, new_path, force=False): """Rename self to a new path :param new_path: @@ -603,7 +577,7 @@ class SymbolicReference(object): new_abs_path = os.path.join(_git_dir(self.repo, new_path), new_path) cur_abs_path = os.path.join(_git_dir(self.repo, self.path), self.path) - if os.path.isfile(new_abs_path): + if os.path.path.isfile(new_abs_path): if not force: # if they point to the same file, its not an error with open(new_abs_path, 'rb') as fd1: @@ -689,7 +663,7 @@ class SymbolicReference(object): return (r for r in cls._iter_items(repo, common_path) if r.__class__ == SymbolicReference or not r.is_detached) @classmethod - def from_path(cls, repo: 'Repo', path: PathLike) -> Union['Head', 'RemoteReference', 'TagReference', 'Reference']: + def from_path(cls, repo, path): """ :param path: full .git-directory-relative path name to the Reference to instantiate :note: use to_full_path() if you only have a partial path of a known Reference Type -- cgit v1.2.1 From 34e9850989e9748e94609925a754de4b2ba38216 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 15:56:42 +0100 Subject: Add type to symbolicreference.iter_items() --- git/refs/symbolic.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 779fe5a5..081cd74d 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -642,8 +642,8 @@ class SymbolicReference(object): # END for each sorted relative refpath @classmethod - # type: ignore[override] - def iter_items(cls, repo: 'Repo', common_path: Union[PathLike, None] = None, *args, **kwargs): + def iter_items(cls: Type[T_References], repo: 'Repo', common_path: Union[PathLike, None] = None, + *args: Any, **kwargs: Any) -> Iterator[T_References]: """Find all refs in the repository :param repo: is the Repo -- cgit v1.2.1 From 265d40be3cf0e6f16d7ffd22f5fbd4a503f09219 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:03:23 +0100 Subject: Add type to symbolicreference.rename() --- git/refs/symbolic.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 081cd74d..80b4fef6 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -26,6 +26,7 @@ from git.types import Commit_ish, PathLike, TBD, Literal if TYPE_CHECKING: from git.repo import Repo + from git.refs import Head, TagReference, Reference T_References = TypeVar('T_References', bound='SymbolicReference') @@ -59,10 +60,10 @@ class SymbolicReference(object): def __init__(self, repo: 'Repo', path: PathLike, check_path: bool = False): self.repo = repo - self.path = str(path) + self.path = path def __str__(self) -> str: - return self.path + return str(self.path) def __repr__(self): return '' % (self.__class__.__name__, self.path) @@ -84,7 +85,7 @@ class SymbolicReference(object): :return: In case of symbolic references, the shortest assumable name is the path itself.""" - return self.path + return str(self.path) @property def abspath(self) -> PathLike: @@ -557,7 +558,7 @@ class SymbolicReference(object): :note: This does not alter the current HEAD, index or Working Tree""" return cls._create(repo, path, cls._resolve_ref_on_create, reference, force, logmsg) - def rename(self, new_path, force=False): + def rename(self, new_path: PathLike, force: bool = False) -> 'SymbolicReference': """Rename self to a new path :param new_path: @@ -577,7 +578,7 @@ class SymbolicReference(object): new_abs_path = os.path.join(_git_dir(self.repo, new_path), new_path) cur_abs_path = os.path.join(_git_dir(self.repo, self.path), self.path) - if os.path.path.isfile(new_abs_path): + if os.path.isfile(new_abs_path): if not force: # if they point to the same file, its not an error with open(new_abs_path, 'rb') as fd1: @@ -663,7 +664,7 @@ class SymbolicReference(object): return (r for r in cls._iter_items(repo, common_path) if r.__class__ == SymbolicReference or not r.is_detached) @classmethod - def from_path(cls, repo, path): + def from_path(cls, repo: 'Repo', path: PathLike) -> Union['Head', 'TagReference', 'Reference']: """ :param path: full .git-directory-relative path name to the Reference to instantiate :note: use to_full_path() if you only have a partial path of a known Reference Type -- cgit v1.2.1 From bdd6a4345f224c7a208fec7dd42014b3ff13defa Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:09:22 +0100 Subject: Add type to symbolicreference.__repr__() --- git/refs/symbolic.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 80b4fef6..74bc0a39 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -36,9 +36,9 @@ T_References = TypeVar('T_References', bound='SymbolicReference') __all__ = ["SymbolicReference"] -def _git_dir(repo, path): +def _git_dir(repo: 'Repo', path: PathLike) -> PathLike: """ Find the git dir that's appropriate for the path""" - name = "%s" % (path,) + name = f"{path}" if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']: return repo.git_dir return repo.common_dir @@ -65,18 +65,18 @@ class SymbolicReference(object): def __str__(self) -> str: return str(self.path) - def __repr__(self): + def __repr__(self) -> str: return '' % (self.__class__.__name__, self.path) - def __eq__(self, other): + def __eq__(self, other: Any) -> bool: if hasattr(other, 'path'): return self.path == other.path return False - def __ne__(self, other): + def __ne__(self, other: Any) -> bool: return not (self == other) - def __hash__(self): + def __hash__(self) -> int: return hash(self.path) @property -- cgit v1.2.1 From 1f922671be65261538314f8759e473084c5ed865 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:19:28 +0100 Subject: Add type to symbolicreference._get_ref_info() --- git/refs/symbolic.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 74bc0a39..4b04add5 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -136,23 +136,23 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo, ref_path): + def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required :param repo: the repository containing the reference at ref_path""" while True: - hexsha, ref_path = cls._get_ref_info(repo, ref_path) + hexsha, _ref_path = cls._get_ref_info(repo, ref_path) if hexsha is not None: return hexsha # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo, ref_path): + def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, str]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" - tokens = None + tokens: Union[Tuple[str, str], List[str], None] = None repodir = _git_dir(repo, ref_path) try: with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: @@ -169,7 +169,7 @@ class SymbolicReference(object): if path != ref_path: continue # sha will be used - tokens = sha, path + tokens = (sha, path) break # END for each packed ref # END handle packed refs @@ -186,8 +186,8 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) - @classmethod - def _get_ref_info(cls, repo, ref_path): + @ classmethod + def _get_ref_info(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, str]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" @@ -370,7 +370,7 @@ class SymbolicReference(object): else: return True - @property + @ property def is_detached(self): """ :return: @@ -420,7 +420,7 @@ class SymbolicReference(object): In that case, it will be faster than the ``log()`` method""" return RefLog.entry_at(RefLog.path(self), index) - @classmethod + @ classmethod def to_full_path(cls, path) -> PathLike: """ :return: string with a full repository-relative path which can be used to initialize @@ -434,7 +434,7 @@ class SymbolicReference(object): full_ref_path = '%s/%s' % (cls._common_path_default, path) return full_ref_path - @classmethod + @ classmethod def delete(cls, repo, path): """Delete the reference at the given path @@ -492,7 +492,7 @@ class SymbolicReference(object): os.remove(reflog_path) # END remove reflog - @classmethod + @ classmethod def _create(cls, repo, path, resolve, reference, force, logmsg=None): """internal method used to create a new symbolic reference. If resolve is False, the reference will be taken as is, creating -- cgit v1.2.1 From ad4517ff7c6bb629097a1adae204c27a7af4ba4b Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:23:11 +0100 Subject: Add type to symbolicreference._get_packed_refs_path() --- git/refs/symbolic.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 4b04add5..74bc0a39 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -136,23 +136,23 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: + def dereference_recursive(cls, repo, ref_path): """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required :param repo: the repository containing the reference at ref_path""" while True: - hexsha, _ref_path = cls._get_ref_info(repo, ref_path) + hexsha, ref_path = cls._get_ref_info(repo, ref_path) if hexsha is not None: return hexsha # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, str]]: + def _get_ref_info_helper(cls, repo, ref_path): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" - tokens: Union[Tuple[str, str], List[str], None] = None + tokens = None repodir = _git_dir(repo, ref_path) try: with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: @@ -169,7 +169,7 @@ class SymbolicReference(object): if path != ref_path: continue # sha will be used - tokens = (sha, path) + tokens = sha, path break # END for each packed ref # END handle packed refs @@ -186,8 +186,8 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) - @ classmethod - def _get_ref_info(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, str]]: + @classmethod + def _get_ref_info(cls, repo, ref_path): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" @@ -370,7 +370,7 @@ class SymbolicReference(object): else: return True - @ property + @property def is_detached(self): """ :return: @@ -420,7 +420,7 @@ class SymbolicReference(object): In that case, it will be faster than the ``log()`` method""" return RefLog.entry_at(RefLog.path(self), index) - @ classmethod + @classmethod def to_full_path(cls, path) -> PathLike: """ :return: string with a full repository-relative path which can be used to initialize @@ -434,7 +434,7 @@ class SymbolicReference(object): full_ref_path = '%s/%s' % (cls._common_path_default, path) return full_ref_path - @ classmethod + @classmethod def delete(cls, repo, path): """Delete the reference at the given path @@ -492,7 +492,7 @@ class SymbolicReference(object): os.remove(reflog_path) # END remove reflog - @ classmethod + @classmethod def _create(cls, repo, path, resolve, reference, force, logmsg=None): """internal method used to create a new symbolic reference. If resolve is False, the reference will be taken as is, creating -- cgit v1.2.1 From 6b0faba783d8f93bdd23ef52f50619a61b0ed815 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:25:23 +0100 Subject: Add type to symbolicreference.dereference_recursive() --- git/refs/symbolic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 74bc0a39..30a23e66 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -136,7 +136,7 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo, ref_path): + def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required -- cgit v1.2.1 From 7e972b982cea094b84df27a7b0be5a4dd13b8469 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:28:10 +0100 Subject: Add type to symbolicreference.dereference_recursive() --- git/refs/symbolic.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 30a23e66..d712e5a2 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -148,11 +148,11 @@ class SymbolicReference(object): # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo, ref_path): + def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, str]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" - tokens = None + tokens: Union[None, List[str], Tuple[str, str]] = None repodir = _git_dir(repo, ref_path) try: with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: -- cgit v1.2.1 From 24c124208a870c6c041a304a12a7b91968225ac7 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:37:56 +0100 Subject: Add type to symbolicreference() --- git/refs/symbolic.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index d712e5a2..7da10cb2 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -36,7 +36,7 @@ T_References = TypeVar('T_References', bound='SymbolicReference') __all__ = ["SymbolicReference"] -def _git_dir(repo: 'Repo', path: PathLike) -> PathLike: +def _git_dir(repo: 'Repo', path: Union[PathLike, None]) -> PathLike: """ Find the git dir that's appropriate for the path""" name = f"{path}" if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']: @@ -136,26 +136,27 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: + def dereference_recursive(cls, repo: 'Repo', ref_path: Union[None, PathLike]) -> str: """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required :param repo: the repository containing the reference at ref_path""" - while True: + while True: # loop that overwrites ref_path each loop hexsha, ref_path = cls._get_ref_info(repo, ref_path) if hexsha is not None: return hexsha # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike) -> Union[Tuple[str, None], Tuple[None, str]]: + def _get_ref_info_helper(cls, repo: 'Repo', ref_path: Union[PathLike, None] + ) -> Union[Tuple[str, None], Tuple[None, str]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" tokens: Union[None, List[str], Tuple[str, str]] = None repodir = _git_dir(repo, ref_path) try: - with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: + with open(os.path.join(repodir, cast(str, ref_path)), 'rt', encoding='UTF-8') as fp: value = fp.read().rstrip() # Don't only split on spaces, but on whitespace, which allows to parse lines like # 60b64ef992065e2600bfef6187a97f92398a9144 branch 'master' of git-server:/path/to/repo @@ -187,7 +188,7 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) @classmethod - def _get_ref_info(cls, repo, ref_path): + def _get_ref_info(cls, repo: 'Repo', ref_path: Union[PathLike, None]) -> Union[Tuple[str, None], Tuple[None, str]]: """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" -- cgit v1.2.1 From 8eedc9d002da9bb085be4a82ffb5372f8f8ff7a2 Mon Sep 17 00:00:00 2001 From: Yobmod Date: Sat, 31 Jul 2021 16:43:19 +0100 Subject: Add type to symbolicreference.get_() --- git/refs/symbolic.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) (limited to 'git') diff --git a/git/refs/symbolic.py b/git/refs/symbolic.py index 7da10cb2..bffcfea5 100644 --- a/git/refs/symbolic.py +++ b/git/refs/symbolic.py @@ -36,7 +36,7 @@ T_References = TypeVar('T_References', bound='SymbolicReference') __all__ = ["SymbolicReference"] -def _git_dir(repo: 'Repo', path: Union[PathLike, None]) -> PathLike: +def _git_dir(repo: 'Repo', path: PathLike) -> PathLike: """ Find the git dir that's appropriate for the path""" name = f"{path}" if name in ['HEAD', 'ORIG_HEAD', 'FETCH_HEAD', 'index', 'logs']: @@ -136,27 +136,26 @@ class SymbolicReference(object): # alright. @classmethod - def dereference_recursive(cls, repo: 'Repo', ref_path: Union[None, PathLike]) -> str: + def dereference_recursive(cls, repo: 'Repo', ref_path: PathLike) -> str: """ :return: hexsha stored in the reference at the given ref_path, recursively dereferencing all intermediate references as required :param repo: the repository containing the reference at ref_path""" - while True: # loop that overwrites ref_path each loop + while True: hexsha, ref_path = cls._get_ref_info(repo, ref_path) if hexsha is not None: return hexsha # END recursive dereferencing @classmethod - def _get_ref_info_helper(cls, repo: 'Repo', ref_path: Union[PathLike, None] - ) -> Union[Tuple[str, None], Tuple[None, str]]: + def _get_ref_info_helper(cls, repo: 'Repo', ref_path: PathLike): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" tokens: Union[None, List[str], Tuple[str, str]] = None repodir = _git_dir(repo, ref_path) try: - with open(os.path.join(repodir, cast(str, ref_path)), 'rt', encoding='UTF-8') as fp: + with open(os.path.join(repodir, ref_path), 'rt', encoding='UTF-8') as fp: value = fp.read().rstrip() # Don't only split on spaces, but on whitespace, which allows to parse lines like # 60b64ef992065e2600bfef6187a97f92398a9144 branch 'master' of git-server:/path/to/repo @@ -188,7 +187,7 @@ class SymbolicReference(object): raise ValueError("Failed to parse reference information from %r" % ref_path) @classmethod - def _get_ref_info(cls, repo: 'Repo', ref_path: Union[PathLike, None]) -> Union[Tuple[str, None], Tuple[None, str]]: + def _get_ref_info(cls, repo, ref_path): """Return: (str(sha), str(target_ref_path)) if available, the sha the file at rela_path points to, or None. target_ref_path is the reference we point to, or None""" -- cgit v1.2.1