diff options
author | Sebastian Thiel <sebastian.thiel@icloud.com> | 2022-05-18 08:01:38 +0800 |
---|---|---|
committer | Sebastian Thiel <sebastian.thiel@icloud.com> | 2022-05-18 08:01:38 +0800 |
commit | e530544546b2a4e5f00e8d9458bf1b895573ec41 (patch) | |
tree | 9b957bd812fe98664d3f1f75615dda8242663097 /git/objects | |
parent | f78fc42b90711c81e06699d1ebdbe69e6648b949 (diff) | |
download | gitpython-e530544546b2a4e5f00e8d9458bf1b895573ec41.tar.gz |
reformat according to 'black' configuration file.
Diffstat (limited to 'git/objects')
-rw-r--r-- | git/objects/__init__.py | 6 | ||||
-rw-r--r-- | git/objects/commit.py | 46 | ||||
-rw-r--r-- | git/objects/fun.py | 12 | ||||
-rw-r--r-- | git/objects/submodule/base.py | 190 | ||||
-rw-r--r-- | git/objects/submodule/root.py | 44 | ||||
-rw-r--r-- | git/objects/submodule/util.py | 8 | ||||
-rw-r--r-- | git/objects/tree.py | 38 | ||||
-rw-r--r-- | git/objects/util.py | 76 |
8 files changed, 101 insertions, 319 deletions
diff --git a/git/objects/__init__.py b/git/objects/__init__.py index d2e1e53a..5910ac58 100644 --- a/git/objects/__init__.py +++ b/git/objects/__init__.py @@ -21,8 +21,4 @@ del smutil # must come after submodule was made available -__all__ = [ - name - for name, obj in locals().items() - if not (name.startswith("_") or inspect.ismodule(obj)) -] +__all__ = [name for name, obj in locals().items() if not (name.startswith("_") or inspect.ismodule(obj))] diff --git a/git/objects/commit.py b/git/objects/commit.py index 137cc620..66cb9191 100644 --- a/git/objects/commit.py +++ b/git/objects/commit.py @@ -144,9 +144,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): 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) + assert isinstance(tree, Tree), "Tree needs to be a Tree instance, was %s" % type(tree) if tree is not None: self.tree = tree if author is not None: @@ -234,9 +232,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): else: return self.message.split(b"\n", 1)[0] - def count( - self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs: Any - ) -> int: + def count(self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs: Any) -> int: """Count the number of commits reachable from this commit :param paths: @@ -250,9 +246,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): # yes, it makes a difference whether empty paths are given or not in our case # as the empty paths version will ignore merge commits for some reason. if paths: - return len( - self.repo.git.rev_list(self.hexsha, "--", paths, **kwargs).splitlines() - ) + return len(self.repo.git.rev_list(self.hexsha, "--", paths, **kwargs).splitlines()) return len(self.repo.git.rev_list(self.hexsha, **kwargs).splitlines()) @property @@ -285,9 +279,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): ``since`` all commits since i.e. '1970-01-01' :return: iterator yielding Commit items""" if "pretty" in kwargs: - raise ValueError( - "--pretty cannot be used as parsing expects single sha's only" - ) + raise ValueError("--pretty cannot be used as parsing expects single sha's only") # END handle pretty # use -- in any case, to prevent possibility of ambiguous arguments @@ -308,9 +300,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): proc = repo.git.rev_list(rev, args_list, as_process=True, **kwargs) return cls._iter_from_process_or_stream(repo, proc) - def iter_parents( - self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs: Any - ) -> Iterator["Commit"]: + def iter_parents(self, paths: Union[PathLike, Sequence[PathLike]] = "", **kwargs: Any) -> Iterator["Commit"]: """Iterate _all_ parents of this commit. :param paths: @@ -340,9 +330,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): text2 += "%s\t%s\t%s\n" % (insertions, deletions, filename) text = text2 else: - text = self.repo.git.diff( - self.parents[0].hexsha, self.hexsha, "--", numstat=True - ) + text = self.repo.git.diff(self.parents[0].hexsha, self.hexsha, "--", numstat=True) return Stats._list_from_string(self.repo, text) @property @@ -394,9 +382,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): return d @classmethod - def _iter_from_process_or_stream( - cls, repo: "Repo", proc_or_stream: Union[Popen, IO] - ) -> Iterator["Commit"]: + def _iter_from_process_or_stream(cls, repo: "Repo", proc_or_stream: Union[Popen, IO]) -> Iterator["Commit"]: """Parse out commit information into a list of Commit objects We expect one-line per commit, and parse the actual commit information directly from our lighting fast object database @@ -577,9 +563,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): new_commit, logmsg="commit (initial): %s" % message, ) - repo.head.set_reference( - master, logmsg="commit: Switching to %s" % master - ) + repo.head.set_reference(master, logmsg="commit: Switching to %s" % master) # END handle empty repositories # END advance head handling @@ -652,9 +636,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): Otherwise it is assumed to be a plain data stream from our object """ readline = stream.readline - self.tree = Tree( - self.repo, hex_to_bin(readline().split()[1]), Tree.tree_id << 12, "" - ) + self.tree = Tree(self.repo, hex_to_bin(readline().split()[1]), Tree.tree_id << 12, "") self.parents = [] next_line = None @@ -664,11 +646,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): next_line = parent_line break # END abort reading parents - self.parents.append( - type(self)( - self.repo, hex_to_bin(parent_line.split()[-1].decode("ascii")) - ) - ) + self.parents.append(type(self)(self.repo, hex_to_bin(parent_line.split()[-1].decode("ascii")))) # END for each parent line self.parents = tuple(self.parents) @@ -694,9 +672,7 @@ class Commit(base.Object, TraversableIterableObj, Diffable, Serializable): buf = enc.strip() while buf: if buf[0:10] == b"encoding ": - self.encoding = buf[buf.find(b" ") + 1 :].decode( - self.encoding, "ignore" - ) + self.encoding = buf[buf.find(b" ") + 1 :].decode(self.encoding, "ignore") elif buf[0:7] == b"gpgsig ": sig = buf[buf.find(b" ") + 1 :] + b"\n" is_next_header = False diff --git a/git/objects/fun.py b/git/objects/fun.py index de065599..001e10e4 100644 --- a/git/objects/fun.py +++ b/git/objects/fun.py @@ -35,9 +35,7 @@ __all__ = ( ) -def tree_to_stream( - entries: Sequence[EntryTup], write: Callable[["ReadableBuffer"], Union[int, None]] -) -> None: +def tree_to_stream(entries: Sequence[EntryTup], write: Callable[["ReadableBuffer"], Union[int, None]]) -> None: """Write the give list of entries into a stream using its write method :param entries: **sorted** list of tuples with (binsha, mode, name) :param write: write method which takes a data string""" @@ -114,9 +112,7 @@ def tree_entries_from_data(data: bytes) -> List[EntryTup]: return out -def _find_by_name( - tree_data: MutableSequence[EntryTupOrNone], name: str, is_dir: bool, start_at: int -) -> EntryTupOrNone: +def _find_by_name(tree_data: MutableSequence[EntryTupOrNone], name: str, is_dir: bool, start_at: int) -> EntryTupOrNone: """return data entry matching the given name and tree mode or None. Before the item is returned, the respective data item is set @@ -234,9 +230,7 @@ def traverse_trees_recursive( return out -def traverse_tree_recursive( - odb: "GitCmdObjectDB", tree_sha: bytes, path_prefix: str -) -> List[EntryTup]: +def traverse_tree_recursive(odb: "GitCmdObjectDB", tree_sha: bytes, path_prefix: str) -> List[EntryTup]: """ :return: list of entries of the tree pointed to by the binary tree_sha. An entry has the following format: diff --git a/git/objects/submodule/base.py b/git/objects/submodule/base.py index 84a34206..bdcdf1ec 100644 --- a/git/objects/submodule/base.py +++ b/git/objects/submodule/base.py @@ -68,10 +68,7 @@ class UpdateProgress(RemoteProgress): """Class providing detailed progress information to the caller who should derive from it and implement the ``update(...)`` message""" - CLONE, FETCH, UPDWKTREE = [ - 1 << x - for x in range(RemoteProgress._num_op_codes, RemoteProgress._num_op_codes + 3) - ] + CLONE, FETCH, UPDWKTREE = [1 << x for x in range(RemoteProgress._num_op_codes, RemoteProgress._num_op_codes + 3)] _num_op_codes: int = RemoteProgress._num_op_codes + 3 __slots__ = () @@ -101,9 +98,7 @@ class Submodule(IndexObject, TraversableIterableObj): k_modules_file = ".gitmodules" k_head_option = "branch" k_head_default = "master" - k_default_mode = ( - stat.S_IFDIR | stat.S_IFLNK - ) # submodules are directories with link-status + k_default_mode = stat.S_IFDIR | stat.S_IFLNK # submodules are directories with link-status # this is a bogus type for base class compatibility type: Literal["submodule"] = "submodule" # type: ignore @@ -156,13 +151,9 @@ class Submodule(IndexObject, TraversableIterableObj): # end self._url = reader.get("url") # git-python extension values - optional - self._branch_path = reader.get_value( - self.k_head_option, git.Head.to_full_path(self.k_head_default) - ) + self._branch_path = reader.get_value(self.k_head_option, git.Head.to_full_path(self.k_head_default)) elif attr == "_name": - raise AttributeError( - "Cannot retrieve the name of a submodule if it was not set initially" - ) + raise AttributeError("Cannot retrieve the name of a submodule if it was not set initially") else: super(Submodule, self)._set_cache_(attr) # END handle attribute name @@ -227,23 +218,18 @@ class Submodule(IndexObject, TraversableIterableObj): if not repo.bare and parent_matches_head and repo.working_tree_dir: fp_module = osp.join(repo.working_tree_dir, cls.k_modules_file) else: - assert ( - parent_commit is not None - ), "need valid parent_commit in bare repositories" + assert parent_commit is not None, "need valid parent_commit in bare repositories" try: fp_module = cls._sio_modules(parent_commit) except KeyError as e: raise IOError( - "Could not find %s file in the tree of parent commit %s" - % (cls.k_modules_file, parent_commit) + "Could not find %s file in the tree of parent commit %s" % (cls.k_modules_file, parent_commit) ) from e # END handle exceptions # END handle non-bare working tree if not read_only and (repo.bare or not parent_matches_head): - raise ValueError( - "Cannot write blobs of 'historical' submodule configurations" - ) + raise ValueError("Cannot write blobs of 'historical' submodule configurations") # END handle writes of historical submodules return SubmoduleConfigParser(fp_module, read_only=read_only) @@ -277,9 +263,7 @@ class Submodule(IndexObject, TraversableIterableObj): return SectionConstraint(parser, sm_section(self.name)) @classmethod - def _module_abspath( - cls, parent_repo: "Repo", path: PathLike, name: str - ) -> PathLike: + def _module_abspath(cls, parent_repo: "Repo", path: PathLike, name: str) -> PathLike: if cls._need_gitfile_submodules(parent_repo.git): return osp.join(parent_repo.git_dir, "modules", name) if parent_repo.working_tree_dir: @@ -288,9 +272,7 @@ class Submodule(IndexObject, TraversableIterableObj): # end @classmethod - def _clone_repo( - cls, repo: "Repo", url: str, path: PathLike, name: str, **kwargs: Any - ) -> "Repo": + def _clone_repo(cls, repo: "Repo", url: str, path: PathLike, name: str, **kwargs: Any) -> "Repo": """:return: Repo instance of newly cloned repository :param repo: our parent repository :param url: url to clone from @@ -331,19 +313,14 @@ class Submodule(IndexObject, TraversableIterableObj): ) path = path[len(working_tree_linux.rstrip("/")) + 1 :] if not path: - raise ValueError( - "Absolute submodule path '%s' didn't yield a valid relative path" - % path - ) + raise ValueError("Absolute submodule path '%s' didn't yield a valid relative path" % path) # end verify converted relative path makes sense # end convert to a relative path return path @classmethod - def _write_git_file_and_module_config( - cls, working_tree_dir: PathLike, module_abspath: PathLike - ) -> None: + def _write_git_file_and_module_config(cls, working_tree_dir: PathLike, module_abspath: PathLike) -> None: """Writes a .git file containing a(preferably) relative path to the actual git module repository. It is an error if the module_abspath cannot be made into a relative path, relative to the working_tree_dir :note: will overwrite existing files ! @@ -361,15 +338,11 @@ class Submodule(IndexObject, TraversableIterableObj): with open(git_file, "wb") as fp: fp.write(("gitdir: %s" % rela_path).encode(defenc)) - with GitConfigParser( - osp.join(module_abspath, "config"), read_only=False, merge_includes=False - ) as writer: + with GitConfigParser(osp.join(module_abspath, "config"), read_only=False, merge_includes=False) as writer: writer.set_value( "core", "worktree", - to_native_path_linux( - osp.relpath(working_tree_dir, start=module_abspath) - ), + to_native_path_linux(osp.relpath(working_tree_dir, start=module_abspath)), ) # { Edit Interface @@ -426,9 +399,7 @@ class Submodule(IndexObject, TraversableIterableObj): update fails for instance""" if repo.bare: - raise InvalidGitRepositoryError( - "Cannot add submodules to bare repositories" - ) + raise InvalidGitRepositoryError("Cannot add submodules to bare repositories") # END handle bare repos path = cls._to_relative_path(repo, path) @@ -470,8 +441,7 @@ class Submodule(IndexObject, TraversableIterableObj): if has_module and url is not None: if url not in [r.url for r in sm.module().remotes]: raise ValueError( - "Specified URL '%s' does not match any remote url of the repository at '%s'" - % (url, sm.abspath) + "Specified URL '%s' does not match any remote url of the repository at '%s'" % (url, sm.abspath) ) # END check url # END verify urls match @@ -480,17 +450,13 @@ class Submodule(IndexObject, TraversableIterableObj): if url is None: if not has_module: - raise ValueError( - "A URL was not given and a repository did not exist at %s" % path - ) + raise ValueError("A URL was not given and a repository did not exist at %s" % path) # END check url mrepo = sm.module() # assert isinstance(mrepo, git.Repo) urls = [r.url for r in mrepo.remotes] if not urls: - raise ValueError( - "Didn't find any remote url in repository at %s" % sm.abspath - ) + raise ValueError("Didn't find any remote url in repository at %s" % sm.abspath) # END verify we have url url = urls[0] else: @@ -624,8 +590,7 @@ class Submodule(IndexObject, TraversableIterableObj): op, i, len_rmts, - prefix - + "Fetching remote %s of submodule %r" % (remote, self.name), + prefix + "Fetching remote %s of submodule %r" % (remote, self.name), ) # =============================== if not dry_run: @@ -655,8 +620,7 @@ class Submodule(IndexObject, TraversableIterableObj): os.rmdir(checkout_module_abspath) except OSError as e: raise OSError( - "Module directory at %r does already exist and is non-empty" - % checkout_module_abspath + "Module directory at %r does already exist and is non-empty" % checkout_module_abspath ) from e # END handle OSError # END handle directory removal @@ -668,8 +632,7 @@ class Submodule(IndexObject, TraversableIterableObj): 0, 1, prefix - + "Cloning url '%s' to '%s' in submodule %r" - % (self.url, checkout_module_abspath, self.name), + + "Cloning url '%s' to '%s' in submodule %r" % (self.url, checkout_module_abspath, self.name), ) if not dry_run: mrepo = self._clone_repo( @@ -694,9 +657,7 @@ class Submodule(IndexObject, TraversableIterableObj): try: mrepo = cast("Repo", mrepo) # find a remote which has our branch - we try to be flexible - remote_branch = find_first_remote_branch( - mrepo.remotes, self.branch_name - ) + remote_branch = find_first_remote_branch(mrepo.remotes, self.branch_name) local_branch = mkhead(mrepo, self.branch_path) # have a valid branch, but no checkout - make sure we can figure @@ -711,9 +672,7 @@ class Submodule(IndexObject, TraversableIterableObj): ) mrepo.head.reference.set_tracking_branch(remote_branch) except (IndexError, InvalidGitRepositoryError): - log.warning( - "Failed to checkout tracking branch %s", self.branch_path - ) + log.warning("Failed to checkout tracking branch %s", self.branch_path) # END handle tracking branch # NOTE: Have to write the repo config file as well, otherwise @@ -735,10 +694,7 @@ class Submodule(IndexObject, TraversableIterableObj): # END handle dry_run if mrepo is not None and to_latest_revision: - msg_base = ( - "Cannot update to latest revision in repository at %r as " - % mrepo.working_dir - ) + msg_base = "Cannot update to latest revision in repository at %r as " % mrepo.working_dir if not is_detached: rref = mrepo.head.reference.tracking_branch() if rref is not None: @@ -767,9 +723,7 @@ class Submodule(IndexObject, TraversableIterableObj): may_reset = True if mrepo.head.commit.binsha != self.NULL_BIN_SHA: base_commit = mrepo.merge_base(mrepo.head.commit, hexsha) - if len(base_commit) == 0 or ( - base_commit[0] is not None and base_commit[0].hexsha == hexsha - ): + if len(base_commit) == 0 or (base_commit[0] is not None and base_commit[0].hexsha == hexsha): if force: msg = "Will force checkout or reset on local branch that is possibly in the future of" msg += "the commit it will be checked out to, effectively 'forgetting' new commits" @@ -786,16 +740,8 @@ class Submodule(IndexObject, TraversableIterableObj): # end handle force # end handle if we are in the future - if ( - may_reset - and not force - and mrepo.is_dirty( - index=True, working_tree=True, untracked_files=True - ) - ): - raise RepositoryDirtyError( - mrepo, "Cannot reset a dirty repository" - ) + if may_reset and not force and mrepo.is_dirty(index=True, working_tree=True, untracked_files=True): + raise RepositoryDirtyError(mrepo, "Cannot reset a dirty repository") # end handle force and dirty state # end handle empty repo @@ -805,8 +751,7 @@ class Submodule(IndexObject, TraversableIterableObj): 0, 1, prefix - + "Updating working tree at %s for submodule %r to revision %s" - % (self.path, self.name, hexsha), + + "Updating working tree at %s for submodule %r to revision %s" % (self.path, self.name, hexsha), ) if not dry_run and may_reset: @@ -855,9 +800,7 @@ class Submodule(IndexObject, TraversableIterableObj): return self @unbare_repo - def move( - self, module_path: PathLike, configuration: bool = True, module: bool = True - ) -> "Submodule": + def move(self, module_path: PathLike, configuration: bool = True, module: bool = True) -> "Submodule": """Move the submodule to a another module path. This involves physically moving the repository at our current path, changing the configuration, as well as adjusting our index entry accordingly. @@ -877,9 +820,7 @@ class Submodule(IndexObject, TraversableIterableObj): in an inconsistent state if a sub - step fails for some reason """ if module + configuration < 1: - raise ValueError( - "You must specify to move at least the module or the configuration of the submodule" - ) + raise ValueError("You must specify to move at least the module or the configuration of the submodule") # END handle input module_checkout_path = self._to_relative_path(self.repo, module_path) @@ -889,13 +830,9 @@ class Submodule(IndexObject, TraversableIterableObj): return self # END handle no change - module_checkout_abspath = join_path_native( - str(self.repo.working_tree_dir), module_checkout_path - ) + module_checkout_abspath = join_path_native(str(self.repo.working_tree_dir), module_checkout_path) if osp.isfile(module_checkout_abspath): - raise ValueError( - "Cannot move repository onto a file: %s" % module_checkout_abspath - ) + raise ValueError("Cannot move repository onto a file: %s" % module_checkout_abspath) # END handle target files index = self.repo.index @@ -933,9 +870,7 @@ class Submodule(IndexObject, TraversableIterableObj): if osp.isfile(osp.join(module_checkout_abspath, ".git")): module_abspath = self._module_abspath(self.repo, self.path, self.name) - self._write_git_file_and_module_config( - module_checkout_abspath, module_abspath - ) + self._write_git_file_and_module_config(module_checkout_abspath, module_abspath) # end handle git file rewrite # END move physical module @@ -948,14 +883,10 @@ class Submodule(IndexObject, TraversableIterableObj): ekey = index.entry_key(self.path, 0) entry = index.entries[ekey] del index.entries[ekey] - nentry = git.IndexEntry( - entry[:3] + (module_checkout_path,) + entry[4:] - ) + nentry = git.IndexEntry(entry[:3] + (module_checkout_path,) + entry[4:]) index.entries[tekey] = nentry except KeyError as e: - raise InvalidGitRepositoryError( - "Submodule's entry at %r did not exist" % (self.path) - ) from e + raise InvalidGitRepositoryError("Submodule's entry at %r did not exist" % (self.path)) from e # END handle submodule doesn't exist # update configuration @@ -1012,9 +943,7 @@ class Submodule(IndexObject, TraversableIterableObj): :raise InvalidGitRepositoryError: thrown if the repository cannot be deleted :raise OSError: if directories or files could not be removed""" if not (module or configuration): - raise ValueError( - "Need to specify to delete at least the module, or the configuration" - ) + raise ValueError("Need to specify to delete at least the module, or the configuration") # END handle parameters # Recursively remove children of this submodule @@ -1027,9 +956,7 @@ class Submodule(IndexObject, TraversableIterableObj): if configuration and not dry_run and nc > 0: # Assure we don't leave the parent repository in a dirty state, and commit our changes # It's important for recursive, unforced, deletions to work as expected - self.module().index.commit( - "Removed at least one of child-modules of '%s'" % self.name - ) + self.module().index.commit("Removed at least one of child-modules of '%s'" % self.name) # end handle recursion # DELETE REPOSITORY WORKING TREE @@ -1048,9 +975,7 @@ class Submodule(IndexObject, TraversableIterableObj): elif osp.isdir(mp): method = rmtree elif osp.exists(mp): - raise AssertionError( - "Cannot forcibly delete repository as it was neither a link, nor a directory" - ) + raise AssertionError("Cannot forcibly delete repository as it was neither a link, nor a directory") # END handle brutal deletion if not dry_run: assert method @@ -1079,8 +1004,7 @@ class Submodule(IndexObject, TraversableIterableObj): # not a single remote branch contained all our commits if len(rrefs) and num_branches_with_new_commits == len(rrefs): raise InvalidGitRepositoryError( - "Cannot delete module at %s as there are new commits" - % mod.working_tree_dir + "Cannot delete module at %s as there are new commits" % mod.working_tree_dir ) # END handle new commits # have to manually delete references as python's scoping is @@ -1106,9 +1030,7 @@ class Submodule(IndexObject, TraversableIterableObj): if HIDE_WINDOWS_KNOWN_ERRORS: from unittest import SkipTest - raise SkipTest( - "FIXME: fails with: PermissionError\n {}".format(ex) - ) from ex + raise SkipTest("FIXME: fails with: PermissionError\n {}".format(ex)) from ex raise # END delete tree if possible # END handle force @@ -1121,9 +1043,7 @@ class Submodule(IndexObject, TraversableIterableObj): if HIDE_WINDOWS_KNOWN_ERRORS: from unittest import SkipTest - raise SkipTest( - f"FIXME: fails with: PermissionError\n {ex}" - ) from ex + raise SkipTest(f"FIXME: fails with: PermissionError\n {ex}") from ex else: raise # end handle separate bare repository @@ -1157,9 +1077,7 @@ class Submodule(IndexObject, TraversableIterableObj): return self - def set_parent_commit( - self, commit: Union[Commit_ish, None], check: bool = True - ) -> "Submodule": + 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. @@ -1180,10 +1098,7 @@ class Submodule(IndexObject, TraversableIterableObj): pcommit = self.repo.commit(commit) pctree = pcommit.tree if self.k_modules_file not in pctree: - raise ValueError( - "Tree of commit %s did not contain the %s file" - % (commit, self.k_modules_file) - ) + raise ValueError("Tree of commit %s did not contain the %s file" % (commit, self.k_modules_file)) # END handle exceptions prev_pc = self._parent_commit @@ -1193,10 +1108,7 @@ class Submodule(IndexObject, TraversableIterableObj): parser = self._config_parser(self.repo, self._parent_commit, read_only=True) if not parser.has_section(sm_section(self.name)): self._parent_commit = prev_pc - raise ValueError( - "Submodule at path %r did not exist in parent commit %s" - % (self.path, commit) - ) + raise ValueError("Submodule at path %r did not exist in parent commit %s" % (self.path, commit)) # END handle submodule did not exist # END handle checking mode @@ -1268,9 +1180,7 @@ class Submodule(IndexObject, TraversableIterableObj): # .git/modules mod = self.module() if mod.has_separate_working_tree(): - destination_module_abspath = self._module_abspath( - self.repo, self.path, new_name - ) + destination_module_abspath = self._module_abspath(self.repo, self.path, new_name) source_dir = mod.git_dir # Let's be sure the submodule name is not so obviously tied to a directory if str(destination_module_abspath).startswith(str(mod.git_dir)): @@ -1280,9 +1190,7 @@ class Submodule(IndexObject, TraversableIterableObj): # end handle self-containment os.renames(source_dir, destination_module_abspath) if mod.working_tree_dir: - self._write_git_file_and_module_config( - mod.working_tree_dir, destination_module_abspath - ) + self._write_git_file_and_module_config(mod.working_tree_dir, destination_module_abspath) # end move separate git repository return self @@ -1304,13 +1212,9 @@ class Submodule(IndexObject, TraversableIterableObj): return repo # END handle repo uninitialized except (InvalidGitRepositoryError, NoSuchPathError) as e: - raise InvalidGitRepositoryError( - "No valid repository at %s" % module_checkout_abspath - ) from e + raise InvalidGitRepositoryError("No valid repository at %s" % module_checkout_abspath) from e else: - raise InvalidGitRepositoryError( - "Repository at %r was not yet checked out" % module_checkout_abspath - ) + raise InvalidGitRepositoryError("Repository at %r was not yet checked out" % module_checkout_abspath) # END handle exceptions def module_exists(self) -> bool: diff --git a/git/objects/submodule/root.py b/git/objects/submodule/root.py index 16f0f91f..0cbc262c 100644 --- a/git/objects/submodule/root.py +++ b/git/objects/submodule/root.py @@ -27,8 +27,7 @@ class RootUpdateProgress(UpdateProgress): """Utility class which adds more opcodes to the UpdateProgress""" REMOVE, PATHCHANGE, BRANCHCHANGE, URLCHANGE = [ - 1 << x - for x in range(UpdateProgress._num_op_codes, UpdateProgress._num_op_codes + 4) + 1 << x for x in range(UpdateProgress._num_op_codes, UpdateProgress._num_op_codes + 4) ] _num_op_codes = UpdateProgress._num_op_codes + 4 @@ -116,9 +115,7 @@ class RootModule(Submodule): In conjunction with dry_run, it can be useful to anticipate all errors when updating submodules :return: self""" if self.repo.bare: - raise InvalidGitRepositoryError( - "Cannot update submodules in bare repositories" - ) + raise InvalidGitRepositoryError("Cannot update submodules in bare repositories") # END handle bare if progress is None: @@ -149,9 +146,7 @@ class RootModule(Submodule): previous_commit = repo.commit(previous_commit) # obtain commit object # END handle previous commit - psms: "IterableList[Submodule]" = self.list_items( - repo, parent_commit=previous_commit - ) + psms: "IterableList[Submodule]" = self.list_items(repo, parent_commit=previous_commit) sms: "IterableList[Submodule]" = self.list_items(repo) spsms = set(psms) ssms = set(sms) @@ -186,9 +181,7 @@ class RootModule(Submodule): if i == len_rrsm - 1: op |= END # END handle end - progress.update( - op, i, len_rrsm, prefix + "Done removing submodule %r" % rsm.name - ) + progress.update(op, i, len_rrsm, prefix + "Done removing submodule %r" % rsm.name) # END for each removed submodule # HANDLE PATH RENAMES @@ -207,9 +200,7 @@ class RootModule(Submodule): BEGIN | PATHCHANGE, i, len_csms, - prefix - + "Moving repository of submodule %r from %s to %s" - % (sm.name, psm.abspath, sm.abspath), + prefix + "Moving repository of submodule %r from %s to %s" % (sm.name, psm.abspath, sm.abspath), ) # move the module to the new path if not dry_run: @@ -240,9 +231,7 @@ class RootModule(Submodule): BEGIN | URLCHANGE, i, len_csms, - prefix - + "Changing url of submodule %r from %s to %s" - % (sm.name, psm.url, sm.url), + prefix + "Changing url of submodule %r from %s to %s" % (sm.name, psm.url, sm.url), ) if not dry_run: @@ -252,16 +241,7 @@ class RootModule(Submodule): # If we have a tracking branch, it should be available # in the new remote as well. - if ( - len( - [ - r - for r in smr.refs - if r.remote_head == sm.branch_name - ] - ) - == 0 - ): + if len([r for r in smr.refs if r.remote_head == sm.branch_name]) == 0: raise ValueError( "Submodule branch named %r was not available in new submodule remote at %r" % (sm.branch_name, sm.url) @@ -289,8 +269,7 @@ class RootModule(Submodule): # Alternatively we could just generate a unique name and leave all # existing ones in place raise InvalidGitRepositoryError( - "Couldn't find original remote-repo at url %r" - % psm.url + "Couldn't find original remote-repo at url %r" % psm.url ) # END handle one single remote # END handle check we found a remote @@ -340,8 +319,7 @@ class RootModule(Submodule): END | URLCHANGE, i, len_csms, - prefix - + "Done adjusting url of submodule %r" % (sm.name), + prefix + "Done adjusting url of submodule %r" % (sm.name), ) # END skip remote handling if new url already exists in module # END handle url @@ -378,9 +356,7 @@ class RootModule(Submodule): tbr = git.Head(smm, sm.branch_path) # END assure tracking branch exists - tbr.set_tracking_branch( - find_first_remote_branch(smmr, sm.branch_name) - ) + tbr.set_tracking_branch(find_first_remote_branch(smmr, sm.branch_name)) # NOTE: All head-resetting is done in the base implementation of update # but we will have to checkout the new branch here. As it still points to the currently # checkout out commit, we don't do any harm. diff --git a/git/objects/submodule/util.py b/git/objects/submodule/util.py index 456ae34b..56ce1489 100644 --- a/git/objects/submodule/util.py +++ b/git/objects/submodule/util.py @@ -47,9 +47,7 @@ def mkhead(repo: "Repo", path: PathLike) -> "Head": return git.Head(repo, git.Head.to_full_path(path)) -def find_first_remote_branch( - remotes: Sequence["Remote"], branch_name: str -) -> "RemoteReference": +def find_first_remote_branch(remotes: Sequence["Remote"], branch_name: str) -> "RemoteReference": """Find the remote branch matching the name of the given branch or raise InvalidGitRepositoryError""" for remote in remotes: try: @@ -58,9 +56,7 @@ def find_first_remote_branch( continue # END exception handling # END for remote - raise InvalidGitRepositoryError( - "Didn't find remote branch '%r' in any of the given remotes" % branch_name - ) + raise InvalidGitRepositoryError("Didn't find remote branch '%r' in any of the given remotes" % branch_name) # } END utilities diff --git a/git/objects/tree.py b/git/objects/tree.py index e1fcced7..b72e88c4 100644 --- a/git/objects/tree.py +++ b/git/objects/tree.py @@ -40,9 +40,7 @@ if TYPE_CHECKING: TreeCacheTup = Tuple[bytes, int, str] -TraversedTreeTup = Union[ - Tuple[Union["Tree", None], IndexObjUnion, Tuple["Submodule", "Submodule"]] -] +TraversedTreeTup = Union[Tuple[Union["Tree", None], IndexObjUnion, Tuple["Submodule", "Submodule"]]] # def is_tree_cache(inp: Tuple[bytes, int, str]) -> TypeGuard[TreeCacheTup]: @@ -69,9 +67,7 @@ def git_cmp(t1: TreeCacheTup, t2: TreeCacheTup) -> int: return len_a - len_b -def merge_sort( - a: List[TreeCacheTup], cmp: Callable[[TreeCacheTup, TreeCacheTup], int] -) -> None: +def merge_sort(a: List[TreeCacheTup], cmp: Callable[[TreeCacheTup, TreeCacheTup], int]) -> None: if len(a) < 2: return None @@ -139,9 +135,7 @@ class TreeModifier(object): # } END interface # { Mutators - def add( - self, sha: bytes, mode: int, name: str, force: bool = False - ) -> "TreeModifier": + def add(self, sha: bytes, mode: int, name: str, force: bool = False) -> "TreeModifier": """Add the given item to the tree. If an item with the given name already exists, nothing will be done, but a ValueError will be raised if the sha and mode of the existing item do not match the one you add, unless @@ -182,11 +176,7 @@ class TreeModifier(object): puts the caller into responsibility to assure the input is correct. For more information on the parameters, see ``add`` :param binsha: 20 byte binary sha""" - assert ( - isinstance(binsha, bytes) - and isinstance(mode, int) - and isinstance(name, str) - ) + assert isinstance(binsha, bytes) and isinstance(mode, int) and isinstance(name, str) tree_cache = (binsha, mode, name) self._cache.append(tree_cache) @@ -256,9 +246,7 @@ class Tree(IndexObject, git_diff.Diffable, util.Traversable, util.Serializable): super(Tree, self)._set_cache_(attr) # END handle attribute - def _iter_convert_to_object( - self, iterable: Iterable[TreeCacheTup] - ) -> Iterator[IndexObjUnion]: + def _iter_convert_to_object(self, iterable: Iterable[TreeCacheTup]) -> Iterator[IndexObjUnion]: """Iterable yields tuples of (binsha, mode, name), which will be converted to the respective object representation""" for binsha, mode, name in iterable: @@ -266,9 +254,7 @@ class Tree(IndexObject, git_diff.Diffable, util.Traversable, util.Serializable): try: yield self._map_id_to_type[mode >> 12](self.repo, binsha, mode, path) except KeyError as e: - raise TypeError( - "Unknown mode %o found in tree data for path '%s'" % (mode, path) - ) from e + raise TypeError("Unknown mode %o found in tree data for path '%s'" % (mode, path)) from e # END for each item def join(self, file: str) -> IndexObjUnion: @@ -330,12 +316,8 @@ class Tree(IndexObject, git_diff.Diffable, util.Traversable, util.Serializable): def traverse( self, # type: ignore[override] - predicate: Callable[ - [Union[IndexObjUnion, TraversedTreeTup], int], bool - ] = lambda i, d: True, - prune: Callable[ - [Union[IndexObjUnion, TraversedTreeTup], int], bool - ] = lambda i, d: False, + predicate: Callable[[Union[IndexObjUnion, TraversedTreeTup], int], bool] = lambda i, d: True, + prune: Callable[[Union[IndexObjUnion, TraversedTreeTup], int], bool] = lambda i, d: False, depth: int = -1, branch_first: bool = True, visit_once: bool = False, @@ -389,9 +371,7 @@ class Tree(IndexObject, git_diff.Diffable, util.Traversable, util.Serializable): def __getitem__(self, item: Union[str, int, slice]) -> IndexObjUnion: if isinstance(item, int): info = self._cache[item] - return self._map_id_to_type[info[1] >> 12]( - self.repo, info[0], info[1], join_path(self.path, info[2]) - ) + return self._map_id_to_type[info[1] >> 12](self.repo, info[0], info[1], join_path(self.path, info[2])) if isinstance(item, str): # compatibility diff --git a/git/objects/util.py b/git/objects/util.py index 4ba59c8a..fad00001 100644 --- a/git/objects/util.py +++ b/git/objects/util.py @@ -60,9 +60,7 @@ class TraverseNT(NamedTuple): src: Union["Traversable", None] -T_TIobj = TypeVar( - "T_TIobj", bound="TraversableIterableObj" -) # for TraversableIterableObj.traverse() +T_TIobj = TypeVar("T_TIobj", bound="TraversableIterableObj") # for TraversableIterableObj.traverse() TraversedTup = Union[ Tuple[Union["Traversable", None], "Traversable"], # for commit, submodule @@ -133,9 +131,7 @@ def get_object_type_by_name( return tree.Tree else: - raise ValueError( - "Cannot handle unknown object type: %s" % object_type_name.decode() - ) + raise ValueError("Cannot handle unknown object type: %s" % object_type_name.decode()) def utctz_to_altz(utctz: str) -> int: @@ -164,12 +160,7 @@ def verify_utctz(offset: str) -> str: raise fmt_exc if offset[0] not in "+-": raise fmt_exc - if ( - offset[1] not in digits - or offset[2] not in digits - or offset[3] not in digits - or offset[4] not in digits - ): + if offset[1] not in digits or offset[2] not in digits or offset[3] not in digits or offset[4] not in digits: raise fmt_exc # END for each char return offset @@ -222,15 +213,11 @@ def parse_date(string_date: Union[str, datetime]) -> Tuple[int, int]: """ if isinstance(string_date, datetime): if string_date.tzinfo: - utcoffset = cast( - timedelta, string_date.utcoffset() - ) # typeguard, if tzinfoand is not None + utcoffset = cast(timedelta, string_date.utcoffset()) # typeguard, if tzinfoand is not None offset = -int(utcoffset.total_seconds()) return int(string_date.astimezone(utc).timestamp()), offset else: - raise ValueError( - f"string_date datetime object without tzinfo, {string_date}" - ) + raise ValueError(f"string_date datetime object without tzinfo, {string_date}") # git time try: @@ -302,9 +289,7 @@ def parse_date(string_date: Union[str, datetime]) -> Tuple[int, int]: raise ValueError("no format matched") # END handle format except Exception as e: - raise ValueError( - f"Unsupported date format or type: {string_date}, type={type(string_date)}" - ) from e + raise ValueError(f"Unsupported date format or type: {string_date}, type={type(string_date)}") from e # END handle exceptions @@ -411,9 +396,7 @@ class Traversable(Protocol): # could add _id_attribute_ to Traversable, or make all Traversable also Iterable? if not as_edge: - out: IterableList[ - Union["Commit", "Submodule", "Tree", "Blob"] - ] = IterableList(id) + out: IterableList[Union["Commit", "Submodule", "Tree", "Blob"]] = IterableList(id) out.extend(self.traverse(as_edge=as_edge, *args, **kwargs)) return out # overloads in subclasses (mypy doesn't allow typing self: subclass) @@ -437,12 +420,8 @@ class Traversable(Protocol): def _traverse( self, - predicate: Callable[ - [Union["Traversable", "Blob", TraversedTup], int], bool - ] = lambda i, d: True, - prune: Callable[ - [Union["Traversable", "Blob", TraversedTup], int], bool - ] = lambda i, d: False, + predicate: Callable[[Union["Traversable", "Blob", TraversedTup], int], bool] = lambda i, d: True, + prune: Callable[[Union["Traversable", "Blob", TraversedTup], int], bool] = lambda i, d: False, depth: int = -1, branch_first: bool = True, visit_once: bool = True, @@ -506,10 +485,7 @@ class Traversable(Protocol): if branch_first: stack.extendleft(TraverseNT(depth, i, src_item) for i in lst) else: - reviter = ( - TraverseNT(depth, lst[i], src_item) - for i in range(len(lst) - 1, -1, -1) - ) + reviter = (TraverseNT(depth, lst[i], src_item) for i in range(len(lst) - 1, -1, -1)) stack.extend(reviter) # END addToStack local method @@ -524,9 +500,7 @@ class Traversable(Protocol): visited.add(item) rval: Union[TraversedTup, "Traversable", "Blob"] - if ( - as_edge - ): # if as_edge return (src, item) unless rrc is None (e.g. for first item) + if as_edge: # if as_edge return (src, item) unless rrc is None (e.g. for first item) rval = (src, item) else: rval = item @@ -575,9 +549,7 @@ class TraversableIterableObj(IterableObj, Traversable): TIobj_tuple = Tuple[Union[T_TIobj, None], T_TIobj] - def list_traverse( - self: T_TIobj, *args: Any, **kwargs: Any - ) -> IterableList[T_TIobj]: + def list_traverse(self: T_TIobj, *args: Any, **kwargs: Any) -> IterableList[T_TIobj]: return super(TraversableIterableObj, self)._list_traverse(*args, **kwargs) @overload # type: ignore @@ -587,12 +559,8 @@ class TraversableIterableObj(IterableObj, Traversable): @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 - ], + 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], depth: int, branch_first: bool, visit_once: bool, @@ -604,12 +572,8 @@ class TraversableIterableObj(IterableObj, Traversable): @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 - ], + 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], depth: int, branch_first: bool, visit_once: bool, @@ -633,18 +597,14 @@ class TraversableIterableObj(IterableObj, Traversable): def traverse( self: T_TIobj, - predicate: Callable[ - [Union[T_TIobj, TIobj_tuple], int], bool - ] = lambda i, d: True, + predicate: Callable[[Union[T_TIobj, TIobj_tuple], int], bool] = lambda i, d: True, prune: Callable[[Union[T_TIobj, TIobj_tuple], int], bool] = lambda i, d: False, depth: int = -1, branch_first: bool = True, visit_once: bool = True, ignore_self: int = 1, as_edge: bool = False, - ) -> Union[ - Iterator[T_TIobj], Iterator[Tuple[T_TIobj, T_TIobj]], Iterator[TIobj_tuple] - ]: + ) -> Union[Iterator[T_TIobj], Iterator[Tuple[T_TIobj, T_TIobj]], Iterator[TIobj_tuple]]: """For documentation, see util.Traversable._traverse()""" """ |