commit:     2f1bad6572e345c9fa7e6c92440c7cd254284140
Author:     Arthur Zamarin <arthurzam <AT> gentoo <DOT> org>
AuthorDate: Thu Jan 19 20:43:22 2023 +0000
Commit:     Arthur Zamarin <arthurzam <AT> gentoo <DOT> org>
CommitDate: Thu Jan 19 20:43:22 2023 +0000
URL:        
https://gitweb.gentoo.org/proj/pkgcore/pkgcore.git/commit/?id=2f1bad65

refactor: use f-strings

Signed-off-by: Arthur Zamarin <arthurzam <AT> gentoo.org>

 src/pkgcore/ebuild/atom.py              |  1 -
 src/pkgcore/ebuild/conditionals.py      | 17 ++++++++++++++---
 src/pkgcore/ebuild/cpv.py               |  4 ++--
 src/pkgcore/ebuild/digest.py            |  4 ++--
 src/pkgcore/ebuild/ebuild_built.py      |  2 +-
 src/pkgcore/ebuild/profiles.py          |  7 +++----
 src/pkgcore/ebuild/repo_objs.py         |  2 +-
 src/pkgcore/ebuild/resolver.py          |  1 -
 src/pkgcore/restrictions/boolean.py     |  8 +++-----
 src/pkgcore/restrictions/restriction.py | 12 ++++--------
 src/pkgcore/restrictions/values.py      | 11 +++--------
 src/pkgcore/util/commandline.py         | 19 +++++++------------
 12 files changed, 40 insertions(+), 48 deletions(-)

diff --git a/src/pkgcore/ebuild/atom.py b/src/pkgcore/ebuild/atom.py
index 166d8c7b0..2efbfd8b1 100644
--- a/src/pkgcore/ebuild/atom.py
+++ b/src/pkgcore/ebuild/atom.py
@@ -54,7 +54,6 @@ class atom(boolean.AndRestriction, 
metaclass=klass.generic_equality):
         "slot",
         "subslot",
         "repo_id",
-        "_hash",
         "_cpv",
         "_restrictions",
     )

diff --git a/src/pkgcore/ebuild/conditionals.py 
b/src/pkgcore/ebuild/conditionals.py
index 6c2984aae..80773974e 100644
--- a/src/pkgcore/ebuild/conditionals.py
+++ b/src/pkgcore/ebuild/conditionals.py
@@ -6,6 +6,8 @@ appropriate conditionals.
 
 __all__ = ("DepSet", "stringify_boolean")
 
+import typing
+
 from snakeoil.compatibility import IGNORED_EXCEPTIONS
 from snakeoil.iterables import expandable_chain
 from snakeoil.sequences import iflatten_instance
@@ -289,7 +291,11 @@ class DepSet(boolean.AndRestriction):
         return self.restrictions[key]
 
 
-def stringify_boolean(node, func=str, domain=None):
+def stringify_boolean(
+    node: restriction.base,
+    func: typing.Callable[[restriction.base], str] = str,
+    domain=None,
+):
     """func is used to stringify the actual content. Useful for fetchables."""
     l = []
     if isinstance(node, DepSet):
@@ -300,7 +306,12 @@ def stringify_boolean(node, func=str, domain=None):
     return " ".join(l)
 
 
-def _internal_stringify_boolean(node, domain, func, visit):
+def _internal_stringify_boolean(
+    node: restriction.base,
+    domain,
+    func: typing.Callable[[restriction.base], str],
+    visit: typing.Callable[[str], None],
+):
     """func is used to stringify the actual content. Useful for fetchables."""
 
     if isinstance(node, boolean.OrRestriction):
@@ -314,7 +325,7 @@ def _internal_stringify_boolean(node, domain, func, visit):
         iterable = node.payload
         visit(
             "%s%s? ("
-            % (node.restriction.negate and "!" or "", 
list(node.restriction.vals)[0])
+            % ("!" if node.restriction.negate else "", 
list(node.restriction.vals)[0])
         )
     else:
         if domain is not None and (

diff --git a/src/pkgcore/ebuild/cpv.py b/src/pkgcore/ebuild/cpv.py
index 41d3a32c8..1a5d7ab8d 100644
--- a/src/pkgcore/ebuild/cpv.py
+++ b/src/pkgcore/ebuild/cpv.py
@@ -45,7 +45,7 @@ def isvalid_pkg_name(chunks):
     return True
 
 
-def isvalid_rev(s):
+def isvalid_rev(s: str):
     return s and s[0] == "r" and s[1:].isdigit()
 
 
@@ -118,7 +118,7 @@ class Revision(UserString):
         return self.data >= other
 
 
-def ver_cmp(ver1, rev1, ver2, rev2):
+def ver_cmp(ver1: str, rev1: str, ver2: str, rev2: str) -> int:
     # If the versions are the same, comparing revisions will suffice.
     if ver1 == ver2:
         # revisions are equal if 0 or None (versionless cpv)

diff --git a/src/pkgcore/ebuild/digest.py b/src/pkgcore/ebuild/digest.py
index 5a9cce5b2..392a2d1ec 100644
--- a/src/pkgcore/ebuild/digest.py
+++ b/src/pkgcore/ebuild/digest.py
@@ -45,7 +45,7 @@ def parse_manifest(source, ignore_gpg=True):
     # manifest v1 format is
     # CHF sum filename size
     # note that we do _not_ support manifest1
-    chf_types = set(["size"])
+    chf_types = {"size"}
     f = None
     try:
         if isinstance(source, str):
@@ -67,7 +67,7 @@ def parse_manifest(source, ignore_gpg=True):
                 raise errors.ParseChksumError(
                     source,
                     "manifest 2 entry doesn't have right "
-                    "number of tokens, %i: %r" % (len(line), line),
+                    f"number of tokens, {len(line)}: {line!r}",
                 )
             chf_types.update(line[3::2])
             # this is a trick to do pairwise collapsing;

diff --git a/src/pkgcore/ebuild/ebuild_built.py 
b/src/pkgcore/ebuild/ebuild_built.py
index 5cd9c512b..a2051ba02 100644
--- a/src/pkgcore/ebuild/ebuild_built.py
+++ b/src/pkgcore/ebuild/ebuild_built.py
@@ -173,7 +173,7 @@ class package(ebuild_src.base):
         return self._parent._get_metadata(self)
 
     def __str__(self):
-        return "built ebuild: %s" % (self.cpvstr)
+        return f"built ebuild: {self.cpvstr}"
 
     def build(self, **kwargs):
         return self.repo._generate_buildop(self)

diff --git a/src/pkgcore/ebuild/profiles.py b/src/pkgcore/ebuild/profiles.py
index a20443fa6..89c273915 100644
--- a/src/pkgcore/ebuild/profiles.py
+++ b/src/pkgcore/ebuild/profiles.py
@@ -639,15 +639,14 @@ class ProfileStack:
             for path, line, lineno in node.parent_paths:
                 try:
                     x = self._node_kls._autodetect_and_create(path)
-                except ProfileError as e:
+                except ProfileError as exc:
                     repo_id = node.repoconfig.repo_id
                     logger.error(
                         f"repo {repo_id!r}: '{self.name}/parent' (line 
{lineno}), "
-                        f"bad profile parent {line!r}: {e.error}"
+                        f"bad profile parent {line!r}: {exc.error}"
                     )
                     continue
-                for y in f(x):
-                    yield y
+                yield from f(x)
             yield node
 
         return tuple(f(self.node))

diff --git a/src/pkgcore/ebuild/repo_objs.py b/src/pkgcore/ebuild/repo_objs.py
index e6477b581..2bcb1b407 100644
--- a/src/pkgcore/ebuild/repo_objs.py
+++ b/src/pkgcore/ebuild/repo_objs.py
@@ -771,7 +771,7 @@ class RepoConfig(syncable.tree, klass.ImmutableInstance, 
metaclass=WeakInstMeta)
         object.__setattr__(self, "config_name", config_name)
         object.__setattr__(self, "external", (config_name is None))
         object.__setattr__(self, "location", location)
-        object.__setattr__(self, "profiles_base", pjoin(self.location, 
profiles_base))
+        object.__setattr__(self, "profiles_base", pjoin(location, 
profiles_base))
 
         try:
             self._parse_config()

diff --git a/src/pkgcore/ebuild/resolver.py b/src/pkgcore/ebuild/resolver.py
index 03b40f3fb..b7896f3ac 100644
--- a/src/pkgcore/ebuild/resolver.py
+++ b/src/pkgcore/ebuild/resolver.py
@@ -22,7 +22,6 @@ def upgrade_resolver(
     resolver_cls=plan.merge_plan,
     **kwds,
 ):
-
     """
     generate and configure a resolver for upgrading all processed nodes.
 

diff --git a/src/pkgcore/restrictions/boolean.py 
b/src/pkgcore/restrictions/boolean.py
index 02195dc84..53de6e9ce 100644
--- a/src/pkgcore/restrictions/boolean.py
+++ b/src/pkgcore/restrictions/boolean.py
@@ -54,13 +54,11 @@ class base(restriction.base, metaclass=generic_equality):
                 for r in restrictions:
                     if r.type is not None and r.type != node_type:
                         raise TypeError(
-                            "instance '%s' is restriction type '%s', "
-                            "must be '%s'" % (r, r.type, node_type)
+                            f"instance '{r}' is restriction type '{r.type}', 
must be '{node_type}'"
                         )
             except AttributeError:
                 raise TypeError(
-                    "type '%s' instance '%s' has no restriction type, "
-                    "'%s' required" % (r.__class__, r, node_type)
+                    f"type '{r.__class__}' instance '{r}' has no restriction 
type, '{node_type}' required"
                 )
 
         if kwds.pop("finalize", True):
@@ -74,7 +72,7 @@ class base(restriction.base, metaclass=generic_equality):
         if kwds:
             kwds.pop("disable_inst_caching", None)
             if kwds:
-                raise TypeError("unknown keywords to %s: %s" % 
(self.__class__, kwds))
+                raise TypeError(f"unknown keywords to {self.__class__}: 
{kwds}")
 
     def change_restrictions(self, *restrictions, **kwds):
         """return a new instance of self.__class__, using supplied 
restrictions"""

diff --git a/src/pkgcore/restrictions/restriction.py 
b/src/pkgcore/restrictions/restriction.py
index b77856be0..85265381a 100644
--- a/src/pkgcore/restrictions/restriction.py
+++ b/src/pkgcore/restrictions/restriction.py
@@ -122,7 +122,7 @@ class FakeType(base):
         return self._restrict.match(*a, **kw)
 
     def __str__(self):
-        return "Faked type(%s): %s" % (self.type, self._restrict)
+        return f"Faked type({self.type}): {self._restrict}"
 
 
 class AnyMatch(base):
@@ -150,14 +150,10 @@ class AnyMatch(base):
         return self.negate
 
     def __str__(self):
-        return "any: %s match" % (self.restriction,)
+        return f"any: {self.restriction} match"
 
     def __repr__(self):
-        return "<%s restriction=%r @%#8x>" % (
-            self.__class__.__name__,
-            self.restriction,
-            id(self),
-        )
+        return f"<{self.__class__.__name__} restriction={self.restriction!r} 
@{id(self):#8x}>"
 
 
 def curry_node_type(cls, node_type, extradoc=None):
@@ -174,7 +170,7 @@ def curry_node_type(cls, node_type, extradoc=None):
     :return: a wrapped callable.
     """
     if extradoc is None:
-        extradoc = "Automatically set to %s type." % (node_type,)
+        extradoc = f"Automatically set to {node_type} type."
     doc = cls.__doc__
     result = partial(cls, node_type=node_type)
     if doc is None:

diff --git a/src/pkgcore/restrictions/values.py 
b/src/pkgcore/restrictions/values.py
index a444e1426..8c5ed2286 100644
--- a/src/pkgcore/restrictions/values.py
+++ b/src/pkgcore/restrictions/values.py
@@ -99,7 +99,7 @@ class StrRegex(base, metaclass=hashed_base):
         try:
             compiled_re = re.compile(regex, flags)
         except re.error as e:
-            raise ValueError("invalid regex: %r, %s" % (regex, e))
+            raise ValueError(f"invalid regex: {regex!r}, {e}")
         if match:
             sf(self, "_matchfunc", compiled_re.match)
         else:
@@ -123,7 +123,7 @@ class StrRegex(base, metaclass=hashed_base):
             result.append("match")
         else:
             result.append("search")
-        result.append("@%#8x" % (id(self),))
+        result.append(f"@{id(self):#8x}")
         result = " ".join(result)
         return f"<{result}>"
 
@@ -277,12 +277,7 @@ class EqualityMatch(base, metaclass=generic_equality):
         return (self.data == actual_val) != self.negate
 
     def __repr__(self):
-        return "<%s %r negate=%r @%#8x>" % (
-            self.__class__.__name__,
-            self.data,
-            self.negate,
-            id(self),
-        )
+        return f"<{self.__class__.__name__} {self.data!r} 
negate={self.negate!r} @{id(self):#8x}>"
 
     def __str__(self):
         if self.negate:

diff --git a/src/pkgcore/util/commandline.py b/src/pkgcore/util/commandline.py
index bb6921d9b..52503f371 100644
--- a/src/pkgcore/util/commandline.py
+++ b/src/pkgcore/util/commandline.py
@@ -291,8 +291,7 @@ class StoreRepoObject(StoreConfigObject):
     def __init__(self, *args, **kwargs):
         if "config_type" in kwargs:
             raise ValueError(
-                "StoreRepoObject: config_type keyword is redundant: got %s"
-                % (kwargs["config_type"],)
+                f"StoreRepoObject: config_type keyword is redundant: got 
{kwargs['config_type']}"
             )
 
         self.repo_type = kwargs.pop("repo_type", "all")
@@ -304,12 +303,9 @@ class StoreRepoObject(StoreConfigObject):
         if self.allow_aliases:
             unknown_aliases = 
self.allow_aliases.difference(self.valid_repo_types)
             if unknown_aliases:
+                es = pluralism(unknown_aliases, plural="es")
                 raise argparse.ArgumentTypeError(
-                    "unknown repo alias%s: %s"
-                    % (
-                        pluralism(unknown_aliases, plural="es"),
-                        ", ".join(unknown_aliases),
-                    )
+                    f"unknown repo alias{es}: {', '.join(unknown_aliases)}"
                 )
 
         if self.repo_type == "config":
@@ -381,17 +377,16 @@ class StoreRepoObject(StoreConfigObject):
 
 class DomainFromPath(StoreConfigObject):
     def __init__(self, *args, **kwargs):
-        kwargs["config_type"] = "domain"
-        super().__init__(*args, **kwargs)
+        super().__init__(*args, config_type="domain", **kwargs)
 
     def _load_obj(self, sections, requested_path):
         targets = list(find_domains_from_path(sections, requested_path))
         if not targets:
             raise ValueError(f"couldn't find domain at path 
{requested_path!r}")
         elif len(targets) != 1:
+            domains = ", ".join(repr(x[0]) for x in targets)
             raise ValueError(
-                "multiple domains claim root %r: domains %s"
-                % (requested_path, ", ".join(repr(x[0]) for x in targets))
+                f"multiple domains claim root {requested_path!r}: domains 
{domains}"
             )
         return targets[0][1]
 
@@ -554,7 +549,7 @@ class _ConfigArg(argparse._StoreAction):
     """Store given config path location or use the stub config when 
disabled."""
 
     def __call__(self, parser, namespace, value, option_string=None):
-        if value.lower() in {"false", "no", "n"}:
+        if value.lower() in ("false", "no", "n"):
             path = pjoin(const.DATA_PATH, "stubconfig")
         else:
             path = arghparse.existent_path(value)

Reply via email to