Skip to content

Commit

Permalink
refactor: enable pyupgrade(UP) checks in ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
ThirVondukr committed Sep 16, 2024
1 parent c2d697d commit 73ddde3
Show file tree
Hide file tree
Showing 61 changed files with 403 additions and 498 deletions.
6 changes: 3 additions & 3 deletions admin/bench_pbkdf2.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def benchmark(name, setup, stmt, supported=True):
print(cell.format("-"), end="")
continue
else:
raise AssertionError("expected %r / %r to fail" % (name, alg))
raise AssertionError(f"expected {name!r} / {alg!r} to fail")
rounds_per_sec = rounds / timeit(alg_stmt, setup)
print(num_cell.format(int(rounds_per_sec / units_per_sec)), end="")
sys.stdout.flush()
Expand Down Expand Up @@ -106,7 +106,7 @@ def na(name):

if backend:
benchmark(
"hashlib/%s" % backend,
f"hashlib/{backend}",
"from hashlib import pbkdf2_hmac",
"pbkdf2_hmac({alg!r}, {secret!r}, {salt!r}, {rounds})",
)
Expand All @@ -120,7 +120,7 @@ def na(name):
import passlib.crypto.digest as digest_mod

for backend in ["from-bytes", "unpack", "hexlify"]:
name = "p/%s" % backend
name = f"p/{backend}"
os.environ["PASSLIB_PBKDF2_BACKEND"] = backend
reload(digest_mod)
benchmark(
Expand Down
5 changes: 2 additions & 3 deletions admin/benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ def marker(func):
def run(cls, source, **defaults):
"""run benchmark for all tasks in source, yielding result records"""
for obj in source.values():
for record in cls._run_object(obj, defaults):
yield record
yield from cls._run_object(obj, defaults)

@classmethod
def _run_object(cls, obj, defaults):
Expand All @@ -58,7 +57,7 @@ def _run_object(cls, obj, defaults):
secs, precision = cls.measure(func, None, **kwds)
yield name, secs, precision
else:
raise ValueError("invalid mode: %r" % (mode,))
raise ValueError(f"invalid mode: {mode!r}")

measure = staticmethod(time_call)

Expand Down
2 changes: 1 addition & 1 deletion admin/plot_verify_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def main(*args):
plt.xlabel("loop count")
plt.legend(shadow=True, title="Legend", fancybox=True)

plt.title("%s verify timing" % ctx.handler().name)
plt.title(f"{ctx.handler().name} verify timing")
pdf.savefig()
plt.close()

Expand Down
21 changes: 10 additions & 11 deletions admin/regen.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,21 +39,20 @@ def replace_section(data, ident, content):
m = re.match(
r"""(?ixms)
(?P<head>.*?\n)
\#[-=]{10,}\n
\# \s begin \s* %(ident)s .* \n
\#[-=]{10,}\n
\#[-=]{{10,}}\n
\# \s begin \s* {ident} .* \n
\#[-=]{{10,}}\n
.*?
\#[-=]{10,}\n
\# \s end \s* %(ident)s \s* \n
\#[-=]{10,}\n
\#[-=]{{10,}}\n
\# \s end \s* {ident} \s* \n
\#[-=]{{10,}}\n
(?P<tail>.*)
"""
% dict(
""".format(**dict(
ident=re.escape(ident).replace("\\ ", "\\s+"),
),
)),
data.replace("\r\n", "\n"),
)
assert m, "%r section not found" % (ident,)
assert m, f"{ident!r} section not found"

begin_row = "# begin " + ident + " (autogenerated " + now + ")\n"

Expand Down Expand Up @@ -92,7 +91,7 @@ def main():
for name, path in _locations.items():
modules.setdefault(path, []).append(name)
for path, names in sorted(modules.items()):
row = " from %s import %s\n" % (path, ", ".join(sorted(names)))
row = " from {} import {}\n".format(path, ", ".join(sorted(names)))
content += row

hash_path = os.path.join(source_dir, "passlib", "hash.py")
Expand Down
14 changes: 7 additions & 7 deletions choose_rounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def main(*args):
args = list(args)

def print_error(msg):
print("error: %s\n" % msg)
print(f"error: {msg}\n")

# parse hasher
if args:
Expand All @@ -37,10 +37,10 @@ def print_error(msg):
try:
hasher = get_crypt_handler(name)
except KeyError:
print_error("unknown hash %r" % name)
print_error(f"unknown hash {name!r}")
return 1
if "rounds" not in hasher.setting_kwds:
print_error("%s does not support variable rounds" % name)
print_error(f"{name} does not support variable rounds")
return 1
else:
print_error("hash name not specified")
Expand Down Expand Up @@ -135,13 +135,13 @@ def helper():
# using final estimate, calc desired number of rounds for target time
# ---------------------------------------------------------------
if hasattr(hasher, "backends"):
name = "%s (using %s backend)" % (name, hasher.get_backend())
print("hash............: %s" % name)
name = f"{name} (using {hasher.get_backend()} backend)"
print(f"hash............: {name}")
if speed < 1000:
speedstr = "%.2f" % speed
speedstr = f"{speed:.2f}"
else:
speedstr = int(speed)
print("speed...........: %s iterations/second" % speedstr)
print(f"speed...........: {speedstr} iterations/second")
print("target time.....: %d ms" % (target * 1000,))
rounds = cost_to_rounds(speed * target)
if hasher.rounds_cost == "log2":
Expand Down
7 changes: 3 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Sphinx configuration file for the Passlib documentation.
Expand Down Expand Up @@ -149,7 +148,7 @@
modindex_common_prefix = ["passlib."]

# appended to all pages
rst_epilog = "\n.. |updated| replace:: %s\n" % updated
rst_epilog = f"\n.. |updated| replace:: {updated}\n"

# Intersphinx
intersphinx_mapping = {
Expand Down Expand Up @@ -201,10 +200,10 @@

# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "%s v%s Documentation" % (project, release)
html_title = f"{project} v{release} Documentation"

# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = "%s %s Documentation" % (project, version)
html_short_title = f"{project} {version} Documentation"

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
Expand Down
2 changes: 1 addition & 1 deletion passlib/_setup/stamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def set_command_options(opts, command, **kwds):


def _get_file(path):
with open(path, "r") as fh:
with open(path) as fh:
return fh.read()


Expand Down
29 changes: 12 additions & 17 deletions passlib/apache.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
_RECORD = "record"


class _CommonFile(object):
class _CommonFile:
"""common framework for HtpasswdFile & HtdigestFile"""

# charset encoding used by file (defaults to utf-8)
Expand Down Expand Up @@ -132,10 +132,10 @@ def __repr__(self):
if self.autosave:
tail += " autosave=True"
if self._path:
tail += " path=%r" % self._path
tail += f" path={self._path!r}"
if self.encoding != "utf-8":
tail += " encoding=%r" % self.encoding
return "<%s 0x%0x%s>" % (self.__class__.__name__, id(self), tail)
tail += f" encoding={self.encoding!r}"
return f"<{self.__class__.__name__} 0x{id(self):0x}{tail}>"

# NOTE: ``path`` is a property so that ``_mtime`` is wiped when it's set.

Expand All @@ -157,7 +157,7 @@ def mtime(self):
def load_if_changed(self):
"""Reload from ``self.path`` only if file has changed since last load"""
if not self._path:
raise RuntimeError("%r is not bound to a local file" % self)
raise RuntimeError(f"{self!r} is not bound to a local file")
if self._mtime and self._mtime == os.path.getmtime(self._path):
return False
self.load()
Expand All @@ -180,8 +180,7 @@ def load(self, path: Optional[PathLike] = None) -> Literal[True]:
self._load_lines(fh)
else:
raise RuntimeError(
"%s().path is not set, an explicit path is required"
% self.__class__.__name__
f"{self.__class__.__name__}().path is not set, an explicit path is required"
)
return True

Expand Down Expand Up @@ -213,7 +212,7 @@ def _load_lines(self, lines):
# which seems to match htpasswd source
if key in records:
logging.warning(
"username occurs multiple times in source file: %r" % key
f"username occurs multiple times in source file: {key!r}"
)
skipped += line
continue
Expand Down Expand Up @@ -270,7 +269,7 @@ def save(self, path=None):
self._mtime = os.path.getmtime(self._path)
else:
raise RuntimeError(
"%s().path is not set, cannot autosave" % self.__class__.__name__
f"{self.__class__.__name__}().path is not set, cannot autosave"
)

def to_string(self):
Expand Down Expand Up @@ -310,7 +309,7 @@ def _iter_lines(self):
if __debug__:
# sanity check that we actually wrote all the records
# (otherwise _source & _records are somehow out of sync)
assert not pending, "failed to write all records: missing=%r" % (pending,)
assert not pending, f"failed to write all records: missing={pending!r}"

def _render_record(self, key, value): # pragma: no cover - abstract method
"""given key/value pair, encode as line of file"""
Expand Down Expand Up @@ -346,14 +345,10 @@ def _encode_field(self, value, param="field"):
elif not isinstance(value, bytes):
raise ExpectedStringError(value, param)
if len(value) > 255:
raise ValueError("%s must be at most 255 characters: %r" % (param, value))
raise ValueError(f"{param} must be at most 255 characters: {value!r}")
if any(c in _INVALID_FIELD_CHARS for c in value):
raise ValueError(
"%s contains invalid characters: %r"
% (
param,
value,
)
f"{param} contains invalid characters: {value!r}"
)
return value

Expand Down Expand Up @@ -658,7 +653,7 @@ def __init__(
if default_scheme in _warn_no_bcrypt:
warn(
"HtpasswdFile: no bcrypt backends available, "
"using fallback for default scheme %r" % default_scheme,
f"using fallback for default scheme {default_scheme!r}",
exc.PasslibSecurityWarning,
)
default_scheme = htpasswd_defaults.get(default_scheme, default_scheme)
Expand Down
Loading

0 comments on commit 73ddde3

Please sign in to comment.