Skip to content

Commit

Permalink
Run pyupgrade --py39-plus
Browse files Browse the repository at this point in the history
Signed-off-by: Sam James <[email protected]>
  • Loading branch information
thesamesam committed Aug 7, 2023
1 parent 9fbd05c commit 1a2c70d
Show file tree
Hide file tree
Showing 53 changed files with 200 additions and 244 deletions.
4 changes: 0 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,10 @@ jobs:
strategy:
matrix:
python-version:
- '3.7'
- '3.8'
- '3.9'
- '3.10'
- '3.11'
- '3.12-dev'
- 'pypy-3.7'
- 'pypy-3.8'
- 'pypy-3.9'

env:
Expand Down
2 changes: 1 addition & 1 deletion bin/epkginfo
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def print_epkginfo_help():

equery.initialize_configuration()
args = sys.argv[1:]
if not args or set(('-h', '--help')).intersection(args):
if not args or {'-h', '--help'}.intersection(args):
print_epkginfo_help()
else:
try:
Expand Down
1 change: 0 additions & 1 deletion bin/eshowkw
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/python
# vim:fileencoding=utf-8
# Copyright 2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

Expand Down
11 changes: 6 additions & 5 deletions bin/merge-driver-ekeyword
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@ import os
import sys
import tempfile

from typing import List, Optional, Sequence, Tuple
from typing import List, Optional, Tuple
from collections.abc import Sequence

from gentoolkit.ekeyword import ekeyword


KeywordChanges = List[Tuple[Optional[List[str]], Optional[List[str]]]]
KeywordChanges = list[tuple[Optional[list[str]], Optional[list[str]]]]


def keyword_array(keyword_line: str) -> List[str]:
def keyword_array(keyword_line: str) -> list[str]:
# Find indices of string inside the double-quotes
i1: int = keyword_line.find('"') + 1
i2: int = keyword_line.rfind('"')
Expand All @@ -32,8 +33,8 @@ def keyword_array(keyword_line: str) -> List[str]:


def keyword_line_changes(old: str, new: str) -> KeywordChanges:
a: List[str] = keyword_array(old)
b: List[str] = keyword_array(new)
a: list[str] = keyword_array(old)
b: list[str] = keyword_array(new)

s = difflib.SequenceMatcher(a=a, b=b)

Expand Down
8 changes: 4 additions & 4 deletions pym/gentoolkit/atom.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,21 +167,21 @@ def __gt__(self, other):
def __le__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"other isn't of %s type, is %s" % (self.__class__, other.__class__)
f"other isn't of {self.__class__} type, is {other.__class__}"
)
return self < other or self == other

def __ge__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"other isn't of %s type, is %s" % (self.__class__, other.__class__)
f"other isn't of {self.__class__} type, is {other.__class__}"
)
return self > other or self == other

def __repr__(self):
uc = self.use_conditional
uc = "%s? " % uc if uc is not None else ""
return "<%s %r>" % (self.__class__.__name__, "%s%s" % (uc, self.atom))
return "<{} {!r}>".format(self.__class__.__name__, f"{uc}{self.atom}")

def __setattr__(self, name, value):
object.__setattr__(self, name, value)
Expand Down Expand Up @@ -336,7 +336,7 @@ def get_depstr(self):
"""Returns a string representation of the original dep"""
uc = self.use_conditional
uc = "%s? " % uc if uc is not None else ""
return "%s%s" % (uc, self.atom)
return f"{uc}{self.atom}"


# vim: set ts=4 sw=4 tw=79:
26 changes: 13 additions & 13 deletions pym/gentoolkit/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ def split_arguments(args):

def main_usage(module_info):
"""Return the main usage message for analyse"""
return "%(usage)s %(product)s [%(g_opts)s] %(mod_name)s [%(mod_opts)s]" % {
"usage": pp.emph("Usage:"),
"product": pp.productname(module_info["__productname__"]),
"g_opts": pp.globaloption("global-options"),
"mod_name": pp.command("module-name"),
"mod_opts": pp.localoption("module-options"),
}
return "{usage} {product} [{g_opts}] {mod_name} [{mod_opts}]".format(
usage=pp.emph("Usage:"),
product=pp.productname(module_info["__productname__"]),
g_opts=pp.globaloption("global-options"),
mod_name=pp.command("module-name"),
mod_opts=pp.localoption("module-options"),
)


def print_version(module_info):
Expand Down Expand Up @@ -145,9 +145,9 @@ def mod_usage(mod_name="module", arg="pkgspec", optional=False):
@param optional: is the argument optional?
"""

return "%(usage)s: %(mod_name)s [%(opts)s] %(arg)s" % {
"usage": pp.emph("Usage"),
"mod_name": pp.command(mod_name),
"opts": pp.localoption("options"),
"arg": ("[%s]" % pp.emph(arg)) if optional else pp.emph(arg),
}
return "{usage}: {mod_name} [{opts}] {arg}".format(
usage=pp.emph("Usage"),
mod_name=pp.command(mod_name),
opts=pp.localoption("options"),
arg=("[%s]" % pp.emph(arg)) if optional else pp.emph(arg),
)
10 changes: 5 additions & 5 deletions pym/gentoolkit/cpv.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __ne__(self, other):
def __lt__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"other isn't of %s type, is %s" % (self.__class__, other.__class__)
f"other isn't of {self.__class__} type, is {other.__class__}"
)

if self.category != other.category:
Expand All @@ -140,26 +140,26 @@ def __lt__(self, other):
def __gt__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"other isn't of %s type, is %s" % (self.__class__, other.__class__)
f"other isn't of {self.__class__} type, is {other.__class__}"
)
return not self <= other

def __le__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"other isn't of %s type, is %s" % (self.__class__, other.__class__)
f"other isn't of {self.__class__} type, is {other.__class__}"
)
return self < other or self == other

def __ge__(self, other):
if not isinstance(other, self.__class__):
raise TypeError(
"other isn't of %s type, is %s" % (self.__class__, other.__class__)
f"other isn't of {self.__class__} type, is {other.__class__}"
)
return self > other or self == other

def __repr__(self):
return "<%s %r>" % (self.__class__.__name__, str(self))
return f"<{self.__class__.__name__} {str(self)!r}>"

def __str__(self):
return self.cpv
Expand Down
4 changes: 2 additions & 2 deletions pym/gentoolkit/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class Dependencies(Query):
def __init__(self, query, parser=None):
Query.__init__(self, query)
self.use = []
self.depatom = str()
self.depatom = ""

# Allow a custom parser function:
self.parser = parser if parser else self._parser
Expand All @@ -61,7 +61,7 @@ def __hash__(self):
return hash((self.atom, self.depatom, tuple(self.use)))

def __repr__(self):
return "<%s %r>" % (self.__class__.__name__, self.atom)
return f"<{self.__class__.__name__} {self.atom!r}>"

def environment(self, envvars):
"""Returns predefined env vars DEPEND, SRC_URI, etc."""
Expand Down
8 changes: 4 additions & 4 deletions pym/gentoolkit/eclean/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def _get_size(self, key):
statinfo = os.stat(file_)
if statinfo.st_nlink == 1:
key_size += statinfo.st_size
except EnvironmentError as er:
except OSError as er:
print(pp.error("Could not get stat info for:" + file_), file=sys.stderr)
print(pp.error("Error: %s" % str(er)), file=sys.stderr)
return key_size
Expand All @@ -111,7 +111,7 @@ def _clean_files(self, files, key, file_type):
# ...get its statinfo
try:
statinfo = os.stat(file_)
except EnvironmentError as er:
except OSError as er:
if not os.path.exists(os.readlink(file_)):
try:
os.remove(file_)
Expand All @@ -120,7 +120,7 @@ def _clean_files(self, files, key, file_type):
file=sys.stderr,
)
break
except EnvironmentError as er:
except OSError as er:
print(
pp.error("Error deleting broken symbolic link " + file_),
file=sys.stderr,
Expand All @@ -144,7 +144,7 @@ def _clean_files(self, files, key, file_type):
os.rmdir(os.path.dirname(file_))
except OSError:
pass
except EnvironmentError as er:
except OSError as er:
print(pp.error("Could not delete " + file_), file=sys.stderr)
print(pp.error("Error: %s" % str(er)), file=sys.stderr)
return clean_size
24 changes: 9 additions & 15 deletions pym/gentoolkit/eclean/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@

def printVersion():
"""Output the version info."""
print("%s (%s) - %s" % (__productname__, __version__, __description__))
print(f"{__productname__} ({__version__}) - {__description__}")
print()
print("Author: %s <%s>" % (__author__, __email__))
print(f"Author: {__author__} <{__email__}>")
print("Copyright 2003-2023 Gentoo Authors")
print("Distributed under the terms of the GNU General Public License v2")

Expand Down Expand Up @@ -586,25 +586,19 @@ def doAction(action, options, exclude={}, output=None):
if saved and not options["quiet"]:
print()
print(
(
pp.emph(" The following ")
+ yellow("unavailable")
+ pp.emph(
" files were saved from cleaning due to exclusion file entries"
)
)
pp.emph(" The following ")
+ yellow("unavailable")
+ pp.emph(" files were saved from cleaning due to exclusion file entries")
)
output.set_colors("deprecated")
clean_size = cleaner.pretend_clean(saved)
output.total("deprecated", clean_size, len(saved), verb, action)
if deprecated and not options["quiet"]:
print()
print(
(
pp.emph(" The following ")
+ yellow("unavailable")
+ pp.emph(" installed packages were found")
)
pp.emph(" The following ")
+ yellow("unavailable")
+ pp.emph(" installed packages were found")
)
output.set_colors("deprecated")
output.list_pkgs(deprecated)
Expand Down Expand Up @@ -646,7 +640,7 @@ def main():
# parse the exclusion file
if not "exclude-file" in options:
# set it to the default exclude file if it exists
exclude_file = "%s/etc/%s/%s.exclude" % (EPREFIX, __productname__, action)
exclude_file = f"{EPREFIX}/etc/{__productname__}/{action}.exclude"
if os.path.isfile(exclude_file):
options["exclude-file"] = exclude_file
if "exclude-file" in options:
Expand Down
3 changes: 1 addition & 2 deletions pym/gentoolkit/eclean/exclude.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,9 @@ def parseExcludeFile(filepath, output):
try:
file_ = open(
_unicode_encode(filepath, encoding=_encodings["fs"]),
mode="r",
encoding=_encodings["content"],
)
except IOError:
except OSError:
raise ParseExcludeFileException("Could not open exclusion file: " + filepath)
filecontents = file_.readlines()
file_.close()
Expand Down
4 changes: 2 additions & 2 deletions pym/gentoolkit/eclean/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def _check_limits(self, _distdir, checks, clean_me=None):
filepath = os.path.join(_distdir, file)
try:
file_stat = os.lstat(filepath)
except EnvironmentError:
except OSError:
continue
is_dirty = False
# for check, check_name in checks:
Expand Down Expand Up @@ -547,7 +547,7 @@ def findPackages(
try:
test = os.listdir(pkgdir)
del test
except EnvironmentError as er:
except OSError as er:
if options["ignore-failure"]:
exit(0)
print(pp.error("Error accessing PKGDIR."), file=sys.stderr)
Expand Down
16 changes: 8 additions & 8 deletions pym/gentoolkit/ekeyword/ekeyword.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def process_keywords(keywords, ops, arch_status=None):
if oarch == "all":
if arch_status is None:
raise ValueError('unable to process "all" w/out profiles.desc')
old_arches = set([keyword_to_arch(a) for a in new_keywords])
old_arches = {keyword_to_arch(a) for a in new_keywords}
if op is None:
# Process just stable keywords.
arches = [
Expand Down Expand Up @@ -219,12 +219,12 @@ def process_keywords(keywords, ops, arch_status=None):

# Finally do the actual update of the keywords list.
for arch in arches:
new_keywords -= set(["%s%s" % (x, arch) for x in ("", "~", "-")])
new_keywords -= {f"{x}{arch}" for x in ("", "~", "-")}

if op is None:
new_keywords.add(arch)
elif op in ("~", "-"):
new_keywords.add("%s%s" % (op, arch))
new_keywords.add(f"{op}{arch}")
elif op == "^":
# Already deleted. Whee.
pass
Expand All @@ -243,7 +243,7 @@ def process_content(
disp_name = ebuild

def logit(msg):
print("%s: %s" % (disp_name, msg))
print(f"{disp_name}: {msg}")

elif quiet > 1:

Expand All @@ -255,7 +255,7 @@ def logit(_msg):
disp_name, _, _ = os.path.basename(ebuild).partition(".ebuild")

def logit(msg):
print("%s: %s" % (disp_name, msg))
print(f"{disp_name}: {msg}")

# Match any KEYWORDS= entry that isn't commented out.
keywords_re = re.compile(r'^([^#]*\bKEYWORDS=)([\'"])(.*)(\2)(.*)')
Expand Down Expand Up @@ -297,7 +297,7 @@ def logit(msg):
old_keywords = sort_keywords(old_keywords)

new_keywords = sort_keywords(new_keywords)
line = '%s"%s"%s\n' % (m.group(1), " ".join(new_keywords), m.group(5))
line = '{}"{}"{}\n'.format(m.group(1), " ".join(new_keywords), m.group(5))
if style in ("color-inline", "inline"):
logit(diff_keywords(old_keywords, new_keywords, style=style))
else:
Expand Down Expand Up @@ -359,7 +359,7 @@ def process_ebuild(
Returns:
Whether any updates were processed
"""
with io.open(ebuild, encoding="utf8") as f:
with open(ebuild, encoding="utf8") as f:
updated, content = process_content(
ebuild,
f,
Expand All @@ -370,7 +370,7 @@ def process_ebuild(
style=style,
)
if updated and not dry_run:
with io.open(ebuild, "w", encoding="utf8") as f:
with open(ebuild, "w", encoding="utf8") as f:
f.writelines(content)
if manifest:
subprocess.check_call(["ebuild", ebuild, "manifest"])
Expand Down
2 changes: 1 addition & 1 deletion pym/gentoolkit/enalyze/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def main():
loaded_module.main(module_args)
except portage.exception.AmbiguousPackageName as err:
raise errors.GentoolkitAmbiguousPackage(err.args[0])
except IOError as err:
except OSError as err:
if err.errno != errno.EPIPE:
raise

Expand Down
6 changes: 2 additions & 4 deletions pym/gentoolkit/enalyze/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,10 +435,8 @@ def analyse_keywords(self, keywords=None):
if self.analyser.mismatched:
print("_________________________________________________")
print(
(
"The following packages were found to have a \n"
+ "different recorded ARCH than the current system ARCH"
)
"The following packages were found to have a \n"
+ "different recorded ARCH than the current system ARCH"
)
for cpv in self.analyser.mismatched:
print("\t", pp.cpv(cpv))
Expand Down
Loading

0 comments on commit 1a2c70d

Please sign in to comment.