[Git][reproducible-builds/diffoscope][master] Update a bunch of %-style string interpolations into f-strings or str.format.
Chris Lamb (@lamby)
gitlab at salsa.debian.org
Thu Nov 18 18:14:39 UTC 2021
Chris Lamb pushed to branch master at Reproducible Builds / diffoscope
Commits:
9bf746ab by Chris Lamb at 2021-11-18T10:10:42-08:00
Update a bunch of %-style string interpolations into f-strings or str.format.
- - - - -
15 changed files:
- diffoscope/comparators/deb.py
- diffoscope/comparators/device.py
- diffoscope/comparators/elf.py
- diffoscope/comparators/missing_file.py
- diffoscope/comparators/rpm.py
- diffoscope/comparators/squashfs.py
- diffoscope/comparators/symlink.py
- diffoscope/comparators/utils/archive.py
- diffoscope/comparators/utils/compare.py
- diffoscope/comparators/utils/file.py
- diffoscope/comparators/utils/libarchive.py
- diffoscope/diff.py
- diffoscope/difference.py
- diffoscope/presenters/html/html.py
- diffoscope/presenters/utils.py
Changes:
=====================================
diffoscope/comparators/deb.py
=====================================
@@ -184,7 +184,7 @@ class Md5sumsFile(File):
with open(self.path, "r", encoding="utf-8") as f:
for line in f:
md5sum, path = re.split(r"\s+", line.strip(), maxsplit=1)
- md5sums["./%s" % path] = md5sum
+ md5sums[f"./{path}"] = md5sum
return md5sums
except (UnicodeDecodeError, ValueError):
logger.debug("Malformed md5sums, ignoring.")
=====================================
diffoscope/comparators/device.py
=====================================
@@ -88,4 +88,4 @@ def format_device(mode, major, minor):
kind = "block"
else:
kind = "weird"
- return "device:%s\nmajor: %d\nminor: %d\n" % (kind, major, minor)
+ return f"device:{kind}\nmajor: {major}\nminor: {minor}\n"
=====================================
diffoscope/comparators/elf.py
=====================================
@@ -158,7 +158,7 @@ class RedaelfVersionInfo(Readelf):
class ReadelfDebugDump(Readelf):
def readelf_options(self):
- return ["--debug-dump=%s" % self._debug_section_group]
+ return [f"--debug-dump={self._debug_section_group}"]
READELF_DEBUG_DUMP_COMMANDS = [
=====================================
diffoscope/comparators/missing_file.py
=====================================
@@ -40,7 +40,7 @@ class MissingFile(File, AbstractMissingType):
@classmethod
def recognizes(cls, file):
if isinstance(file, FilesystemFile) and not os.path.lexists(file.name):
- assert Config().new_file, "%s does not exist" % file.name
+ assert Config().new_file, f"{file.name} does not exist"
return True
return False
=====================================
diffoscope/comparators/rpm.py
=====================================
@@ -70,7 +70,7 @@ def get_rpm_header(path, ts):
for rpmtag in sorted(rpm.tagnames):
if rpmtag not in hdr:
continue
- s.write(u"%s: " % rpm.tagnames[rpmtag])
+ s.write(u"{}: ".format(rpm.tagnames[rpmtag]))
convert_header_field(s, hdr[rpmtag])
s.write(u"\n")
return s.getvalue()
=====================================
diffoscope/comparators/squashfs.py
=====================================
@@ -187,22 +187,20 @@ class SquashfsDevice(Device, SquashfsMember):
d["mode"] = SquashfsDevice.KIND_MAP[d["kind"]]
del d["kind"]
except KeyError:
- raise SquashfsInvalidLineFormat(
- "unknown device kind %s" % d["kind"]
- )
+ raise SquashfsInvalidLineFormat(f"unknown device kind {d['kind']}")
try:
d["major"] = int(d["major"])
except ValueError:
raise SquashfsInvalidLineFormat(
- "unable to parse major number %s" % d["major"]
+ f"unable to parse major number {d['major']}"
)
try:
d["minor"] = int(d["minor"])
except ValueError:
raise SquashfsInvalidLineFormat(
- "unable to parse minor number %s" % d["minor"]
+ f"unable to parse minor number {d['minor']}"
)
return d
=====================================
diffoscope/comparators/symlink.py
=====================================
@@ -41,7 +41,7 @@ class Symlink(File):
def create_placeholder(self):
with get_named_temporary_file("w+", delete=False) as f:
- f.write("destination: %s\n" % self.symlink_destination)
+ f.write(f"destination: {self.symlink_destination}\n")
f.flush()
return f.name
=====================================
diffoscope/comparators/utils/archive.py
=====================================
@@ -85,7 +85,7 @@ class Archive(Container, metaclass=abc.ABCMeta):
basename = os.path.basename(self.source.name)
if not basename.endswith(expected_extension):
- return "%s-content" % basename
+ return f"{basename}-content"
return basename[: -len(expected_extension)]
=====================================
diffoscope/comparators/utils/compare.py
=====================================
@@ -171,5 +171,7 @@ def hexdump_fallback(path):
hexdump = io.StringIO()
with open(path, "rb") as f:
for buf in iter(lambda: f.read(32), b""):
- hexdump.write("%s\n" % binascii.hexlify(buf).decode("us-ascii"))
+ hexdump.write(
+ "{}\n".format(binascii.hexlify(buf).decode("us-ascii"))
+ )
return hexdump.getvalue()
=====================================
diffoscope/comparators/utils/file.py
=====================================
@@ -113,7 +113,7 @@ class File(metaclass=abc.ABCMeta):
self._container = container
def __repr__(self):
- return "<%s %s>" % (self.__class__, self.name)
+ return f"<{self.__class__} {self.name}>"
# This should return a path that allows to access the file content
@property
@@ -567,8 +567,7 @@ class File(metaclass=abc.ABCMeta):
if difference is None:
return None
difference.add_comment(
- "Error parsing output of `%s` for %s"
- % (e.operation, e.object_class)
+ f"Error parsing output of `{e.operation}` for {e.object_class}"
)
except ContainerExtractionError as e:
difference = self.compare_bytes(other, source=source)
=====================================
diffoscope/comparators/utils/libarchive.py
=====================================
@@ -260,7 +260,7 @@ class LibarchiveContainer(Archive):
for entry in archive:
if entry.pathname == member_name:
return self.get_subclass(entry)
- raise KeyError("%s not found in archive" % member_name)
+ raise KeyError(f"{member_name} not found in archive")
def get_filtered_members(self):
try:
=====================================
diffoscope/diff.py
=====================================
@@ -100,7 +100,7 @@ class DiffParser:
found = DiffParser.RANGE_RE.match(line)
if not found:
- raise ValueError("Unable to parse diff headers: %r" % line)
+ raise ValueError(f"Unable to parse diff headers: {line!r}")
self._diff.write(line + b"\n")
if found.group("len1"):
@@ -137,7 +137,7 @@ class DiffParser:
elif self._remaining_hunk_lines == 0:
return self.read_headers(line)
else:
- raise ValueError("Unable to parse diff hunk: %r" % line)
+ raise ValueError(f"Unable to parse diff hunk: {line!r}")
self._diff.write(line + b"\n")
=====================================
diffoscope/difference.py
=====================================
@@ -76,10 +76,8 @@ class Difference:
self._size_cache = None
def __repr__(self):
- return "<Difference %s -- %s %s>" % (
- self._source1,
- self._source2,
- self._details,
+ return (
+ f"<Difference {self._source1} -- {self._source2} {self._details}>"
)
def map_lines(self, f_diff, f_comment):
=====================================
diffoscope/presenters/html/html.py
=====================================
@@ -134,9 +134,9 @@ def convert(s, ponct=0, tag=""):
for c in s:
# used by diffs
if c == DIFFON:
- t.write("<%s>" % tag)
+ t.write(f"<{tag}>")
elif c == DIFFOFF:
- t.write("</%s>" % tag)
+ t.write(f"</{tag}>")
# special highlighted chars
elif c == "\t" and ponct == 1:
@@ -150,7 +150,7 @@ def convert(s, ponct=0, tag=""):
t.write('<br/><span class="dp">\\</span>')
elif ord(c) < 32:
conv = "\\x%x" % ord(c)
- t.write("<em>%s</em>" % conv)
+ t.write(f"<em>{conv}</em>")
i += len(conv)
else:
t.write(html.escape(c))
@@ -305,15 +305,12 @@ def output_node(ctx, difference, path, indentstr, indentnum):
def output_header(css_url, our_css_url=False, icon_url=None):
if css_url:
css_link = (
- ' <link href="%s" type="text/css" rel="stylesheet" />\n' % css_url
+ f' <link href="{css_url}" type="text/css" rel="stylesheet" />\n'
)
else:
css_link = ""
if our_css_url:
- css_style = (
- ' <link href="%s" type="text/css" rel="stylesheet" />\n'
- % our_css_url
- )
+ css_style = f' <link href="{our_css_url}" type="text/css" rel="stylesheet" />\n'
else:
css_style = "<style>\n{}</style>\n".format(templates.STYLES)
if icon_url:
@@ -414,7 +411,7 @@ class HTMLSideBySidePresenter:
def output_line(
self, has_internal_linenos, type_name, s1, line1, s2, line2
):
- self.spl_print_func('<tr class="diff%s">' % type_name)
+ self.spl_print_func(f'<tr class="diff{type_name}">')
try:
if s1:
if has_internal_linenos:
@@ -499,7 +496,7 @@ class HTMLSideBySidePresenter:
_, rotation_params = self.spl_print_ctrl
ctx, mainname = rotation_params
self.spl_current_page += 1
- filename = "%s.html" % (mainname)
+ filename = f"{mainname}.html"
# rotate to the next child page
memory = self.write_memory
@@ -543,7 +540,7 @@ class HTMLSideBySidePresenter:
elif t == "H":
self.output_hunk_header(*args)
elif t == "C":
- self.spl_print_func('<td colspan="2">%s</td>\n' % args)
+ self.spl_print_func(f'<td colspan="2">{args}</td>\n')
else:
raise AssertionError()
self.spl_rows += 1
@@ -634,7 +631,7 @@ class HTMLSideBySidePresenter:
if truncated:
text += " (truncated)"
parent_last_row = templates.UD_TABLE_FOOTER % {
- "filename": html.escape("%s.html" % mainname),
+ "filename": html.escape(f"{mainname}.html"),
"text": text,
}
yield self.bytes_written, parent_last_row
@@ -803,7 +800,7 @@ class HTMLPresenter(Presenter):
printers[node] = (
(make_printer, ctx.target)
if ctx.single_page
- else (file_printer, ctx.target, "%s.html" % pagename)
+ else (file_printer, ctx.target, f"{pagename}.html")
)
stored = node
@@ -893,7 +890,7 @@ class HTMLPresenter(Presenter):
os.makedirs(directory)
if not os.path.isdir(directory):
- raise ValueError("%s is not a directory" % directory)
+ raise ValueError(f"{directory} is not a directory")
jquery_url = self.ensure_jquery(jquery_url, directory, "jquery.js")
with open(os.path.join(directory, "common.css"), "w") as fp:
=====================================
diffoscope/presenters/utils.py
=====================================
@@ -40,7 +40,7 @@ def sizeof_fmt(num, suffix="B", sigfig=3):
num /= 1024.0
else:
unit = "Y"
- return "%s %s%s" % (round_sigfig(num, sigfig), unit, suffix)
+ return "{} {}{}".format(round_sigfig(num, sigfig), unit, suffix)
class Presenter:
@@ -150,13 +150,13 @@ class FormatPlaceholder:
self.ident = str(ident)
def __repr__(self):
- return "%s(%r)" % (self.__class__.__name__, self.ident)
+ return f"{self.__class__.__name__}({self.ident!r})"
def __format__(self, spec):
result = self.ident
if spec:
result += ":" + spec
- return "{" + result + "}"
+ return f"{{{result}}}"
def __getitem__(self, key):
return FormatPlaceholder(self.ident + "[" + str(key) + "]")
@@ -354,7 +354,7 @@ class PartialString:
mapping = {}
real_mapping, new_holes = self._pformat(mapping, False)
if new_holes:
- raise ValueError("not all holes filled: %r" % new_holes)
+ raise ValueError(f"not all holes filled: {new_holes!r}")
return self._fmtstr.format(*real_mapping)
def formatl(self, *args):
View it on GitLab: https://salsa.debian.org/reproducible-builds/diffoscope/-/commit/9bf746ab16c3a31776a4492fbbf0beda2bf200eb
--
View it on GitLab: https://salsa.debian.org/reproducible-builds/diffoscope/-/commit/9bf746ab16c3a31776a4492fbbf0beda2bf200eb
You're receiving this email because of your account on salsa.debian.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.reproducible-builds.org/pipermail/rb-commits/attachments/20211118/df8572ab/attachment.htm>
More information about the rb-commits
mailing list