fix: Use lazy % formatting in logging functions

pylint complains about W1201: Use lazy % formatting in logging functions
(logging-not-lazy) and W1203: Use lazy % formatting in logging functions
(logging-fstring-interpolation).

Signed-off-by: Benjamin Drung <benjamin.drung@canonical.com>
This commit is contained in:
Benjamin Drung 2023-01-31 11:13:07 +01:00
parent 17bed46ffb
commit f6fde2e217
24 changed files with 178 additions and 156 deletions

View File

@ -50,8 +50,8 @@ from ubuntutools.question import YesNoQuestion
Logger = getLogger()
def error(msg):
Logger.error(msg)
def error(msg, *args):
Logger.error(msg, *args)
sys.exit(1)
@ -59,7 +59,7 @@ def check_call(cmd, *args, **kwargs):
Logger.debug(" ".join(cmd))
ret = subprocess.call(cmd, *args, **kwargs)
if ret != 0:
error("%s returned %d." % (cmd[0], ret))
error("%s returned %d.", cmd[0], ret)
def parse(args):
@ -194,7 +194,7 @@ def find_release_package(mirror, workdir, package, version, source_release, conf
if source_release:
distribution = codename_to_distribution(source_release)
if not distribution:
error("Unknown release codename %s" % source_release)
error("Unknown release codename %s", source_release)
info = vendor_to_distroinfo(distribution)()
source_release = info.codename(source_release, default=source_release)
else:
@ -208,7 +208,7 @@ def find_release_package(mirror, workdir, package, version, source_release, conf
try:
spph = archive.getSourcePackage(package, source_release)
except (SeriesNotFoundException, PackageNotFoundException) as e:
error(str(e))
error("%s", str(e))
version = spph.getVersion()
if distribution == "Debian":
@ -237,8 +237,11 @@ def find_package(mirror, workdir, package, version, source_release, config):
srcpkg = find_release_package(mirror, workdir, package, version, source_release, config)
if version and srcpkg.version != version:
error(
"Requested backport of version %s but version of %s in %s is %s"
% (version, package, source_release, srcpkg.version)
"Requested backport of version %s but version of %s in %s is %s",
version,
package,
source_release,
srcpkg.version,
)
return srcpkg
@ -247,23 +250,23 @@ def find_package(mirror, workdir, package, version, source_release, config):
def get_backport_version(version, suffix, upload, release):
distribution = codename_to_distribution(release)
if not distribution:
error("Unknown release codename %s" % release)
error("Unknown release codename %s", release)
if distribution == "Debian":
debian_distro_info = DebianDistroInfo()
debian_codenames = debian_distro_info.supported()
if release in debian_codenames:
release_version = debian_distro_info.version(release)
if not release_version:
error(f"Can't find the release version for {release}")
error("Can't find the release version for %s", release)
backport_version = "{}~bpo{}+1".format(version, release_version)
else:
error(f"{release} is not a supported release ({debian_codenames})")
error("%s is not a supported release (%s)", release, debian_codenames)
elif distribution == "Ubuntu":
series = Distribution(distribution.lower()).getSeries(name_or_version=release)
backport_version = version + ("~bpo%s.1" % (series.version))
else:
error("Unknown distribution «%s» for release «%s»" % (distribution, release))
error("Unknown distribution «%s» for release «%s»", distribution, release)
if suffix is not None:
backport_version += suffix
elif upload and upload.startswith("ppa:"):
@ -450,7 +453,7 @@ def main(args):
if current_distro == "Debian":
opts.dest_releases = [DebianDistroInfo().stable()]
else:
error(f"Unknown distribution {current_distro}, can't guess target release")
error("Unknown distribution %s, can't guess target release", current_distro)
if opts.workdir:
workdir = os.path.expanduser(opts.workdir)
@ -483,7 +486,7 @@ def main(args):
opts.prompt,
)
except DownloadError as e:
error(str(e))
error("%s", str(e))
finally:
if not opts.workdir:
shutil.rmtree(workdir)

View File

@ -33,8 +33,8 @@ from ubuntutools.config import UDTConfig
Logger = getLogger()
def error_out(msg):
Logger.error(msg)
def error_out(msg, *args):
Logger.error(msg, *args)
sys.exit(1)
@ -42,7 +42,7 @@ def save_entry(entry):
try:
entry.lp_save()
except HTTPError as error:
error_out(error.content)
error_out("%s", error.content)
def tag_bug(bug):
@ -84,9 +84,7 @@ def main():
bug = launchpad.bugs[args[0]]
except HTTPError as error:
if error.response.status == 401:
error_out(
"Don't have enough permissions to access bug %s. %s" % (args[0], error.content)
)
error_out("Don't have enough permissions to access bug %s. %s", args[0], error.content)
else:
raise
if "bitesize" in bug.tags:

View File

@ -68,7 +68,7 @@ def main():
Logger.exception(e)
sys.exit(1)
if headers.status != 200:
Logger.error("%s: %s %s" % (url, headers.status, headers.reason))
Logger.error("%s: %s %s", url, headers.status, headers.reason)
sys.exit(1)
for merge in json.loads(page):
@ -88,7 +88,7 @@ def main():
or match in uploader
or match in teams
):
Logger.info("%s\t%s" % (package, pretty_uploader))
Logger.info("%s\t%s", package, pretty_uploader)
if __name__ == "__main__":

View File

@ -136,8 +136,8 @@ def main():
# LP limits descriptions to 50K chars
description = (description[:49994] + " [...]") if len(description) > 50000 else description
Logger.debug("Target: %s" % target)
Logger.debug("Subject: %s" % subject)
Logger.debug("Target: %s", target)
Logger.debug("Subject: %s", subject)
Logger.debug("Description: ")
Logger.debug(description)

View File

@ -74,7 +74,7 @@ def merge_changelog(left_changelog, right_changelog):
assert block.version == version
Logger.info(str(block).strip() + ("\n" if remaining else ""))
Logger.info("%s%s", str(block).strip(), "\n" if remaining else "")
def main():

View File

@ -123,7 +123,7 @@ def main():
except DownloadError as e:
Logger.error("Failed to download: %s", str(e))
sys.exit(1)
Logger.info("file://" + oldpkg.debdiff(newpkg, diffstat=True))
Logger.info("file://%s", oldpkg.debdiff(newpkg, diffstat=True))
if __name__ == "__main__":

View File

@ -149,7 +149,7 @@ def main():
elif options.lpinstance == "staging":
bug_mail_domain = "bugs.staging.launchpad.net"
else:
Logger.error("Error: Unknown launchpad instance: %s" % options.lpinstance)
Logger.error("Error: Unknown launchpad instance: %s", options.lpinstance)
sys.exit(1)
mailserver_host = config.get_value(
@ -225,7 +225,7 @@ def main():
else:
ubu_info = UbuntuDistroInfo()
release = ubu_info.devel()
Logger.warning("Target release missing - assuming %s" % release)
Logger.warning("Target release missing - assuming %s", release)
elif len(args) == 2:
release = args[1]
elif len(args) == 3:
@ -247,7 +247,7 @@ def main():
ubuntu_version = Version("~")
ubuntu_component = None # Set after getting the Debian info
if not newsource:
Logger.info("'%s' doesn't exist in 'Ubuntu %s'." % (srcpkg, release))
Logger.info("'%s' doesn't exist in 'Ubuntu %s'.", srcpkg, release)
Logger.info("Do you want to sync a new package?")
confirmation_prompt()
newsource = True
@ -288,14 +288,15 @@ def main():
if ubuntu_version == debian_version:
Logger.error(
"The versions in Debian and Ubuntu are the "
"same already (%s). Aborting." % ubuntu_version
"The versions in Debian and Ubuntu are the same already (%s). Aborting.",
ubuntu_version,
)
sys.exit(1)
if ubuntu_version > debian_version:
Logger.error(
"The version in Ubuntu (%s) is newer than "
"the version in Debian (%s). Aborting." % (ubuntu_version, debian_version)
"The version in Ubuntu (%s) is newer than the version in Debian (%s). Aborting.",
ubuntu_version,
debian_version,
)
sys.exit(1)

View File

@ -231,8 +231,8 @@ def display_verbose(package, values):
if all_archs:
Logger.info(
"Packages without architectures listed are "
"reverse-dependencies in: %s" % ", ".join(sorted(list(all_archs)))
"Packages without architectures listed are reverse-dependencies in: %s",
", ".join(sorted(list(all_archs))),
)

View File

@ -89,10 +89,10 @@ def output_binaries(index, binaries):
"""Print binaries found in index"""
for binary in binaries:
if binary in index:
Logger.info("%s is seeded in:" % binary)
Logger.info("%s is seeded in:", binary)
Logger.info(present_on(index[binary]))
else:
Logger.info("%s is not seeded (and may not exist)." % binary)
Logger.info("%s is not seeded (and may not exist).", binary)
def output_by_source(index, by_source):
@ -102,16 +102,17 @@ def output_by_source(index, by_source):
if not binaries:
Logger.info(
"Status unknown: No binary packages built by the latest "
"%s.\nTry again using -b and the expected binary packages." % source
"%s.\nTry again using -b and the expected binary packages.",
source,
)
continue
for binary in binaries:
if binary in index:
seen = True
Logger.info("%s (from %s) is seeded in:" % (binary, source))
Logger.info("%s (from %s) is seeded in:", binary, source)
Logger.info(present_on(index[binary]))
if not seen:
Logger.info("%s's binaries are not seeded." % source)
Logger.info("%s's binaries are not seeded.", source)
def main():

View File

@ -135,14 +135,14 @@ def parse(script_name):
Logger.error("No bug number specified.")
sys.exit(1)
elif len(args) > 1:
Logger.error("Multiple bug numbers specified: %s" % (", ".join(args)))
Logger.error("Multiple bug numbers specified: %s", ", ".join(args))
sys.exit(1)
bug_number = args[0]
if bug_number.isdigit():
bug_number = int(bug_number)
else:
Logger.error("Invalid bug number specified: %s" % (bug_number))
Logger.error("Invalid bug number specified: %s", bug_number)
sys.exit(1)
config = UDTConfig(options.no_conf)

View File

@ -91,7 +91,7 @@ def gen_debdiff(tmpdir, changelog):
diff_cmd = ["bzr", "diff", "-r", "tag:" + str(oldver)]
if call(diff_cmd, stdout=DEVNULL, stderr=DEVNULL) == 1:
Logger.info("Extracting bzr diff between %s and %s" % (oldver, newver))
Logger.info("Extracting bzr diff between %s and %s", oldver, newver)
else:
if oldver.epoch is not None:
oldver = str(oldver)[str(oldver).index(":") + 1 :]
@ -104,7 +104,7 @@ def gen_debdiff(tmpdir, changelog):
check_file(olddsc)
check_file(newdsc)
Logger.info("Generating debdiff between %s and %s" % (oldver, newver))
Logger.info("Generating debdiff between %s and %s", oldver, newver)
diff_cmd = ["debdiff", olddsc, newdsc]
with Popen(diff_cmd, stdout=PIPE, encoding="utf-8") as diff:
@ -125,7 +125,7 @@ def check_file(fname, critical=True):
else:
if not critical:
return False
Logger.info("Couldn't find «%s».\n" % fname)
Logger.info("Couldn't find «%s».\n", fname)
sys.exit(1)
@ -225,8 +225,9 @@ the bug to you at <%s>
If this is not correct, please exit now and edit ~/.reportbugrc or run
reportbug --configure for its configuration wizard.
"""
% (email, reportbugrc.strip())
""",
email,
reportbugrc.strip(),
)
if YesNoQuestion().ask("Continue submitting this bug", "yes") == "no":

View File

@ -184,7 +184,7 @@ def sync_dsc(
# change into package directory
directory = src_pkg.source + "-" + new_ver.upstream_version
Logger.debug("cd" + directory)
Logger.debug("cd %s", directory)
os.chdir(directory)
# read Debian distribution from debian/changelog if not specified
@ -209,7 +209,7 @@ def sync_dsc(
cmd.append("-sd")
if not Logger.isEnabledFor(logging.DEBUG):
cmd += ["-q"]
Logger.debug(" ".join(cmd) + "> ../" + changes_filename)
Logger.debug("%s> ../%s", " ".join(cmd), changes_filename)
changes = subprocess.check_output(cmd, encoding="utf-8")
# Add additional bug numbers
@ -775,7 +775,7 @@ def main():
Logger.info("Blacklist Comments:")
for comment in comments:
for line in textwrap.wrap(comment):
Logger.info(" " + line)
Logger.info(" %s", line)
if blacklist_fail:
sys.exit(1)

View File

@ -155,14 +155,14 @@ def main():
# Check our operation.
if operation not in ("rescore", "retry", "status"):
Logger.error("Invalid operation: %s." % operation)
Logger.error("Invalid operation: %s.", operation)
sys.exit(1)
# If the user has specified an architecture to build, we only wish to
# rebuild it and nothing else.
if options.architecture:
if options.architecture[0] not in valid_archs:
Logger.error("Invalid architecture specified: %s." % options.architecture[0])
Logger.error("Invalid architecture specified: %s.", options.architecture[0])
sys.exit(1)
else:
one_arch = True
@ -215,16 +215,20 @@ def main():
if operation in ("rescore", "retry") and not necessary_privs:
Logger.error(
"You cannot perform the %s operation on a %s "
"package as you do not have the permissions "
"to do this action." % (operation, component)
"You cannot perform the %s operation on a %s package as you"
" do not have the permissions to do this action.",
operation,
component,
)
sys.exit(1)
# Output details.
Logger.info(
"The source version for '%s' in %s (%s) is at %s."
% (package, release.capitalize(), component, version)
"The source version for '%s' in %s (%s) is at %s.",
package,
release.capitalize(),
component,
version,
)
Logger.info("Current build status for this package:")
@ -237,27 +241,27 @@ def main():
continue
done = True
Logger.info("%s: %s." % (build.arch_tag, build.buildstate))
Logger.info("%s: %s.", build.arch_tag, build.buildstate)
if operation == "rescore":
if build.can_be_rescored:
# FIXME: make priority an option
priority = 5000
Logger.info("Rescoring build %s to %d..." % (build.arch_tag, priority))
Logger.info("Rescoring build %s to %d...", build.arch_tag, priority)
build.rescore(score=priority)
else:
Logger.info("Cannot rescore build on %s." % build.arch_tag)
Logger.info("Cannot rescore build on %s.", build.arch_tag)
if operation == "retry":
if build.can_be_retried:
Logger.info("Retrying build on %s..." % build.arch_tag)
Logger.info("Retrying build on %s...", build.arch_tag)
build.retry()
else:
Logger.info("Cannot retry build on %s." % build.arch_tag)
Logger.info("Cannot retry build on %s.", build.arch_tag)
# We are done
if done:
sys.exit(0)
Logger.info("No builds for '%s' found in the %s release" % (package, release.capitalize()))
Logger.info("No builds for '%s' found in the %s release", package, release.capitalize())
Logger.info("It may have been built in a former release.")
sys.exit(0)
@ -311,12 +315,16 @@ def main():
if options.retry and not can_retry:
Logger.error(
"You don't have the permissions to retry the "
"build of '%s'. Ignoring your request." % pkg.getPackageName()
"build of '%s'. Ignoring your request.",
pkg.getPackageName(),
)
Logger.info(
"The source version for '%s' in '%s' (%s) is: %s"
% (pkg.getPackageName(), release, pocket, pkg.getVersion())
"The source version for '%s' in '%s' (%s) is: %s",
pkg.getPackageName(),
release,
pocket,
pkg.getVersion(),
)
Logger.info(pkg.getBuildStates(archs))

View File

@ -60,7 +60,7 @@ def main():
version = extract(iso, "/.disk/info")
if len(version) == 0:
Logger.error("%s does not appear to be an Ubuntu ISO" % iso)
Logger.error("%s does not appear to be an Ubuntu ISO", iso)
err = True
continue

View File

@ -99,10 +99,10 @@ def main():
):
component_uploader = archive.getUploadersForComponent(component_name=component)[0]
Logger.info("All upload permissions for %s:" % package)
Logger.info("All upload permissions for %s:", package)
Logger.info("")
Logger.info("Component (%s)" % component)
Logger.info("============" + ("=" * len(component)))
Logger.info("Component (%s)", component)
Logger.info("============%s", "=" * len(component))
print_uploaders([component_uploader], options.list_team_members)
packagesets = sorted(
@ -115,7 +115,7 @@ def main():
Logger.info("===========")
for packageset in packagesets:
Logger.info("")
Logger.info("%s:" % packageset.name)
Logger.info("%s:", packageset.name)
print_uploaders(
archive.getUploadersForPackageset(packageset=packageset),
options.list_team_members,
@ -131,16 +131,18 @@ def main():
Logger.info("")
if PersonTeam.me.canUploadPackage(archive, series, package, component, pocket):
Logger.info("You can upload %s to %s." % (package, options.release))
Logger.info("You can upload %s to %s.", package, options.release)
else:
Logger.info("You can not upload %s to %s, yourself." % (package, options.release))
Logger.info("You can not upload %s to %s, yourself.", package, options.release)
if (
series.status in ("Current Stable Release", "Supported", "Obsolete")
and pocket == "Release"
):
Logger.info(
"%s is in the '%s' state. You may want to query the %s-proposed pocket."
% (release, series.status, release)
"%s is in the '%s' state. You may want to query the %s-proposed pocket.",
release,
series.status,
release,
)
else:
Logger.info(
@ -163,8 +165,11 @@ def print_uploaders(uploaders, expand_teams=False, prefix=""):
"""
for uploader in sorted(uploaders, key=lambda p: p.display_name):
Logger.info(
"%s* %s (%s)%s"
% (prefix, uploader.display_name, uploader.name, " [team]" if uploader.is_team else "")
"%s* %s (%s)%s",
prefix,
uploader.display_name,
uploader.name,
" [team]" if uploader.is_team else "",
)
if expand_teams and uploader.is_team:
print_uploaders(uploader.participants, True, prefix=prefix + " ")

View File

@ -248,7 +248,7 @@ class SourcePackage(ABC):
raise pnfe
Logger.info(
"Source package lookup failed, trying lookup of binary package %s" % self.source
"Source package lookup failed, trying lookup of binary package %s", self.source
)
try:
@ -262,9 +262,7 @@ class SourcePackage(ABC):
self.binary = self.source
self.source = bpph.getSourcePackageName()
Logger.info(
"Using source package '{}' for binary package '{}'".format(
self.source, self.binary
)
"Using source package '%s' for binary package '%s'", self.source, self.binary
)
spph = bpph.getBuild().getSourcePackagePublishingHistory()
@ -381,17 +379,16 @@ class SourcePackage(ABC):
)
except IOError:
Logger.debug(
"Signature on %s could not be verified, install debian-keyring" % self.dsc_name
"Signature on %s could not be verified, install debian-keyring", self.dsc_name
)
return
if gpg_info.valid():
if "GOODSIG" in gpg_info:
Logger.info(
"Good signature by %s (0x%s)"
% (gpg_info["GOODSIG"][1], gpg_info["GOODSIG"][0])
"Good signature by %s (0x%s)", gpg_info["GOODSIG"][1], gpg_info["GOODSIG"][0]
)
elif "VALIDSIG" in gpg_info:
Logger.info("Valid signature by 0x%s" % gpg_info["VALIDSIG"][0])
Logger.info("Valid signature by 0x%s", gpg_info["VALIDSIG"][0])
else:
Logger.info("Valid signature")
elif "NO_PUBKEY" in gpg_info:
@ -399,7 +396,7 @@ class SourcePackage(ABC):
elif "NODATA" in gpg_info:
Logger.warning("Package is not signed")
else:
Logger.warning("Signature on %s could not be verified" % self.dsc_name)
Logger.warning("Signature on %s could not be verified", self.dsc_name)
def _verify_file(self, pathname, dscverify=False, sha1sum=None, sha256sum=None, size=0):
path = Path(pathname)
@ -425,7 +422,7 @@ class SourcePackage(ABC):
can_verify = any((dscverify, sha1sum, sha256sum))
if can_verify and self._verify_file(path, dscverify, sha1sum, sha256sum, size):
Logger.info(f"Using existing file {path}")
Logger.info("Using existing file %s", path)
return True
download(url, path, size)
@ -444,9 +441,9 @@ class SourcePackage(ABC):
return
except NotFoundError:
# It's ok if the file isn't found, just try the next url
Logger.debug(f"File not found at {url}")
Logger.debug("File not found at %s", url)
except DownloadError as e:
Logger.error(f"Download Error: {e}")
Logger.error("Download Error: %s", e)
raise DownloadError(f"Failed to download {filename}")
def pull_dsc(self):
@ -482,7 +479,7 @@ class SourcePackage(ABC):
Returns the number of files downloaded.
"""
Logger.debug("pull_binaries(arch=%s, name=%s, ext=%s)" % (arch, name, ext))
Logger.debug("pull_binaries(arch=%s, name=%s, ext=%s)", arch, name, ext)
if arch == "all":
arch = None
@ -545,7 +542,7 @@ class SourcePackage(ABC):
"""
cmd = ["debdiff", self.dsc_name, newpkg.dsc_name]
difffn = newpkg.dsc_name[:-3] + "debdiff"
Logger.debug(" ".join(cmd) + ("> %s" % difffn))
Logger.debug("%s > %s", " ".join(cmd), difffn)
with open(difffn, "w") as f:
if subprocess.call(cmd, stdout=f, cwd=str(self.workdir)) > 2:
Logger.error("Debdiff failed.")
@ -705,7 +702,7 @@ class PersonalPackageArchiveSourcePackage(UbuntuSourcePackage):
@functools.lru_cache()
def getArchive(self):
ppa = self.team.getPPAByName(self._ppaname)
Logger.debug(f"Using PPA '{ppa.web_link}'")
Logger.debug("Using PPA '%s'", ppa.web_link)
return ppa
def _private_ppa_url(self, filename):
@ -750,8 +747,10 @@ class UbuntuCloudArchiveSourcePackage(PersonalPackageArchiveSourcePackage):
orig_pocket = kwargs.pop("pocket", None)
if orig_pocket and orig_pocket != pocket and pocket == "staging":
Logger.info(
f"Ubuntu Cloud Archive release '{series}' pocket '{orig_pocket}'"
" PPA is not public, using 'staging' pocket instead"
"Ubuntu Cloud Archive release '%s' pocket '%s' PPA is not public,"
" using 'staging' pocket instead",
series,
orig_pocket,
)
kwargs["ppa"] = f"{self.TEAM}/{series}-{pocket}"
@ -888,7 +887,7 @@ class UbuntuCloudArchiveSourcePackage(PersonalPackageArchiveSourcePackage):
)
pocket = "updates"
if cls.isValidRelease(uca_release) and (not pocket or pocket in cls.VALID_POCKETS):
Logger.debug(f"Using Ubuntu Cloud Archive release '{uca_release}'")
Logger.debug("Using Ubuntu Cloud Archive release '%s'", uca_release)
return (uca_release, pocket)
raise SeriesNotFoundException(f"Ubuntu Cloud Archive release '{release}' not found")
@ -932,7 +931,7 @@ class _WebJSON(object):
def load(self, path=""):
reader = codecs.getreader("utf-8")
url = self.getHostUrl() + path
Logger.debug("Loading %s" % url)
Logger.debug("Loading %s", url)
with closing(urlopen(url)) as data:
return json.load(reader(data))
@ -1006,10 +1005,10 @@ class _Snapshot(_WebJSON):
if part.startswith("pool"):
found_pool = True
if not component:
Logger.warning("could not determine component from path %s" % path)
Logger.warning("could not determine component from path %s", path)
return self.DEBIAN_COMPONENTS[0]
if component not in self.DEBIAN_COMPONENTS:
Logger.warning("unexpected component %s" % component)
Logger.warning("unexpected component %s", component)
return component
def _get_package(self, name, url, pkginit, version, sort_key):
@ -1356,7 +1355,7 @@ class SnapshotSPPH(object):
with closing(urlopen(url)) as f:
self._changelog = f.read()
except HTTPError as error:
Logger.error("{}: {}".format(url, error))
Logger.error("%s: %s", url, error)
return None
if since_version is None:

View File

@ -40,7 +40,7 @@ class Builder(object):
def _build_failure(self, returncode, dsc_file):
if returncode != 0:
Logger.error(
"Failed to build %s from source with %s." % (os.path.basename(dsc_file), self.name)
"Failed to build %s from source with %s.", os.path.basename(dsc_file), self.name
)
return returncode
@ -58,7 +58,7 @@ class Builder(object):
def _update_failure(self, returncode, dist):
if returncode != 0:
Logger.error("Failed to update %s chroot for %s." % (dist, self.name))
Logger.error("Failed to update %s chroot for %s.", dist, self.name)
return returncode
@ -138,12 +138,12 @@ class Sbuild(Builder):
def build(self, dsc_file, dist, result_directory):
_build_preparation(result_directory)
workdir = os.getcwd()
Logger.debug("cd " + result_directory)
Logger.debug("cd %s", result_directory)
os.chdir(result_directory)
cmd = ["sbuild", "--arch-all", "--dist=" + dist, "--arch=" + self.architecture, dsc_file]
Logger.debug(" ".join(cmd))
returncode = subprocess.call(cmd)
Logger.debug("cd " + workdir)
Logger.debug("cd %s", workdir)
os.chdir(workdir)
return self._build_failure(returncode, dsc_file)
@ -171,7 +171,7 @@ class Sbuild(Builder):
commands = [["sbuild-update"], ["sbuild-distupgrade"], ["sbuild-clean", "-a", "-c"]]
for cmd in commands:
# pylint: disable=W0631
Logger.debug(" ".join(cmd) + " " + chroot)
Logger.debug("%s %s", " ".join(cmd), chroot)
ret = subprocess.call(cmd + [chroot])
# pylint: enable=W0631
if ret != 0:

View File

@ -165,7 +165,7 @@ class BaseWrapper(object, metaclass=MetaWrapper):
cached._lpobject = data
# and add it to our cache
cls._cache[data.self_link] = cached
Logger.debug("%s: %s" % (cls.__name__, data.self_link))
Logger.debug("%s: %s", cls.__name__, data.self_link)
# add additional class specific caching (if available)
cache = getattr(cls, "cache", None)
if isinstance(cache, collections.abc.Callable):
@ -301,8 +301,8 @@ class Distribution(BaseWrapper):
allseries = filter(lambda s: s.active, self._series.values())
allseries = sorted(allseries, key=lambda s: float(s.version), reverse=True)
Logger.debug(
"Found series: %s"
% ", ".join(map(lambda s: "%s (%s)" % (s.name, s.version), allseries))
"Found series: %s",
", ".join(map(lambda s: "%s (%s)" % (s.name, s.version), allseries)),
)
return collections.OrderedDict((s.name, s) for s in allseries)
@ -663,8 +663,9 @@ class Archive(BaseWrapper):
params["version"] = version
Logger.debug(
"Calling %s(%s)"
% (function, ", ".join(["%s=%s" % (k, v) for (k, v) in params.items()]))
"Calling %s(%s)",
function,
", ".join(["%s=%s" % (k, v) for (k, v) in params.items()]),
)
records = getattr(self, function)(**params)
@ -704,7 +705,7 @@ class Archive(BaseWrapper):
params["version"] = version_.full_version
if len(getattr(self, function)(**params)) > 0:
version_with_epoch = version_.full_version
Logger.debug("Found version with epoch %s" % version_with_epoch)
Logger.debug("Found version with epoch %s", version_with_epoch)
break
if name_key == "binary_name":
@ -911,14 +912,14 @@ class SourcePackagePublishingHistory(BaseWrapper):
url = self._lpobject.changelogUrl()
if url is None:
Logger.error(
"No changelog available for %s %s" % (self.getPackageName(), self.getVersion())
"No changelog available for %s %s", self.getPackageName(), self.getVersion()
)
return None
try:
self._changelog = download_text(url)
except URLError as e:
Logger.error(f"Exception while downloading '{url}': {e}")
Logger.error("Exception while downloading '%s': %s", url, e)
return None
if since_version is None:
@ -955,7 +956,7 @@ class SourcePackagePublishingHistory(BaseWrapper):
urls = self._lpobject.sourceFileUrls(include_meta=True)
if not urls:
Logger.warning(
"SPPH %s_%s has no sourceFileUrls" % (self.getPackageName(), self.getVersion())
"SPPH %s_%s has no sourceFileUrls", self.getPackageName(), self.getVersion()
)
for url in urls:
# make sure mandatory fields are present
@ -1076,7 +1077,7 @@ class SourcePackagePublishingHistory(BaseWrapper):
try:
bpph = archive.getBinaryPackage(**params)
except PackageNotFoundException:
Logger.debug("Could not find pkg in archive: %s" % filename)
Logger.debug("Could not find pkg in archive: %s", filename)
continue
if arch_ not in self._binaries:
self._binaries[arch_] = {}
@ -1222,7 +1223,7 @@ class BinaryPackagePublishingHistory(BaseWrapper):
) from error
if not urls:
Logger.warning(
"BPPH %s_%s has no binaryFileUrls" % (self.getPackageName(), self.getVersion())
"BPPH %s_%s has no binaryFileUrls", self.getPackageName(), self.getVersion()
)
for url in urls:
# make sure mandatory fields are present

View File

@ -141,13 +141,13 @@ def readlist(filename, uniq=True):
path = Path(filename)
if not path.is_file():
Logger.error(f"File {path} does not exist.")
Logger.error("File %s does not exist.", path)
return False
content = path.read_text().replace("\n", " ").replace(",", " ")
if not content.strip():
Logger.error(f"File {path} is empty.")
Logger.error("File %s is empty.", path)
return False
items = [item for item in content.split() if item]
@ -237,11 +237,11 @@ def verify_file_checksums(pathname, checksums={}, size=0):
path = Path(pathname)
if not path.is_file():
Logger.error(f"File {path} not found")
Logger.error("File %s not found", path)
return False
filesize = path.stat().st_size
if size and size != filesize:
Logger.error(f"File {path} incorrect size, got {filesize} expected {size}")
Logger.error("File %s incorrect size, got %s expected %s", path, filesize, size)
return False
for (alg, checksum) in checksums.items():
@ -254,10 +254,10 @@ def verify_file_checksums(pathname, checksums={}, size=0):
hash_.update(block)
digest = hash_.hexdigest()
if digest == checksum:
Logger.debug(f"File {path} checksum ({alg}) verified: {checksum}")
Logger.debug("File %s checksum (%s) verified: %s", path, alg, checksum)
else:
Logger.error(
f"File {path} checksum ({alg}) mismatch: got {digest} expected {checksum}"
"File %s checksum (%s) mismatch: got %s expected %s", path, alg, digest, checksum
)
return False
return True
@ -330,15 +330,15 @@ def download(src, dst, size=0, *, blocksize=DOWNLOAD_BLOCKSIZE_DEFAULT):
if parsedsrc.scheme in ["", "file"]:
src = Path(parsedsrc.path).expanduser().resolve()
if src != parsedsrc.path:
Logger.info(f"Parsed {parsedsrc.path} as {src}")
Logger.info("Parsed %s as %s", parsedsrc.path, src)
if not src.exists():
raise NotFoundError(f"Source file {src} not found")
if dst.exists():
if src.samefile(dst):
Logger.info(f"Using existing file {dst}")
Logger.info("Using existing file %s", dst)
return dst
Logger.info(f"Replacing existing file {dst}")
Logger.info(f"Copying file {src} to {dst}")
Logger.info("Replacing existing file %s", dst)
Logger.info("Copying file %s to %s", src, dst)
shutil.copyfile(src, dst)
return dst
@ -396,7 +396,7 @@ class _StderrProgressBar(object):
def _download(fsrc, fdst, size, *, blocksize):
"""helper method to download src to dst using requests library."""
url = fsrc.url
Logger.debug(f"Using URL: {url}")
Logger.debug("Using URL: %s", url)
if not size:
with suppress(AttributeError, TypeError, ValueError):
@ -406,7 +406,7 @@ def _download(fsrc, fdst, size, *, blocksize):
filename = Path(parsed.path).name
hostname = parsed.hostname
sizemb = " (%0.3f MiB)" % (size / 1024.0 / 1024) if size else ""
Logger.info(f"Downloading {filename} from {hostname}{sizemb}")
Logger.info("Downloading %s from %s%s", filename, hostname, sizemb)
# Don't show progress if:
# logging INFO is suppressed
@ -427,7 +427,7 @@ def _download(fsrc, fdst, size, *, blocksize):
try:
terminal_width = os.get_terminal_size(sys.stderr.fileno()).columns
except Exception as e:
Logger.error(f"Error finding stderr width, suppressing progress bar: {e}")
Logger.error("Error finding stderr width, suppressing progress bar: %s", e)
progress_bar = _StderrProgressBar(max_width=terminal_width)
downloaded = 0
@ -440,8 +440,9 @@ def _download(fsrc, fdst, size, *, blocksize):
progress_bar.finish()
if size and size > downloaded:
Logger.error(
"Partial download: %0.3f MiB of %0.3f MiB"
% (downloaded / 1024.0 / 1024, size / 1024.0 / 1024)
"Partial download: %0.3f MiB of %0.3f MiB",
downloaded / 1024.0 / 1024,
size / 1024.0 / 1024,
)

View File

@ -454,7 +454,7 @@ class PullPkg(object):
name = f.getFileName()
if name.rpartition(".")[0].endswith("all"):
archtext = f" ({f.arch})"
Logger.info(f" {name}{archtext}")
Logger.info(" %s%s", name, archtext)
elif pull == PULL_SOURCE:
# allow DownloadError to flow up to caller
srcpkg.pull()
@ -576,7 +576,7 @@ class PullPkg(object):
Logger.info("Binary files:")
for url in urls:
Logger.info(" %s", url)
Logger.info(" { %s }" % pkg.binaryFileProperties(url))
Logger.info(" { %s }", pkg.binaryFileProperties(url))
else:
Logger.info("No binary files")
urls = pkg.customFileUrls()
@ -594,7 +594,7 @@ class PullPkg(object):
msg += ", please specify the version"
Logger.error("Available package versions/ids are:")
for pkg in packages:
Logger.error("%s %s (id %s)" % (pkg.package_name, pkg.package_version, pkg.id))
Logger.error("%s %s (id %s)", pkg.package_name, pkg.package_version, pkg.id)
raise PackageNotFoundException(msg)
pkg = packages[0]

View File

@ -68,7 +68,7 @@ class BugTask(object):
dsc_file = ""
for url in source_files:
filename = unquote(os.path.basename(url))
Logger.debug("Downloading %s..." % (filename))
Logger.debug("Downloading %s...", filename)
# HttpLib2 isn't suitable for large files (it reads into memory),
# but we want its https certificate validation on the .dsc
if url.endswith(".dsc"):

View File

@ -35,7 +35,7 @@ class Patch(object):
if not reduce(
lambda r, x: r or self._patch.title.endswith(x), (".debdiff", ".diff", ".patch"), False
):
Logger.debug("Patch %s does not have a proper file extension." % (self._patch.title))
Logger.debug("Patch %s does not have a proper file extension.", self._patch.title)
self._patch_file += ".patch"
self._full_path = os.path.realpath(self._patch_file)
self._changed_files = None
@ -82,7 +82,7 @@ class Patch(object):
def download(self):
"""Downloads the patch from Launchpad."""
Logger.debug("Downloading %s." % (self._patch_file))
Logger.debug("Downloading %s.", self._patch_file)
patch_f = open(self._patch_file, "wb")
patch_f.write(self._patch.data.open().read())
patch_f.close()

View File

@ -145,7 +145,7 @@ class SourcePackage(object):
Logger.debug(" ".join(cmd))
if subprocess.call(cmd) != 0:
Logger.error(
"Upload of %s to %s failed." % (os.path.basename(self._changes_file), upload)
"Upload of %s to %s failed.", os.path.basename(self._changes_file), upload
)
sys.exit(1)
@ -274,16 +274,18 @@ class SourcePackage(object):
)
if self._changelog.distributions not in allowed:
Logger.error(
"%s is not an allowed series. It needs to be one of %s."
% (self._changelog.distributions, ", ".join(allowed))
"%s is not an allowed series. It needs to be one of %s.",
self._changelog.distributions,
", ".join(allowed),
)
return ask_for_ignoring_or_fixing()
elif upload and upload.startswith("ppa/"):
allowed = supported_series + [devel_series]
if self._changelog.distributions not in allowed:
Logger.error(
"%s is not an allowed series. It needs to be one of %s."
% (self._changelog.distributions, ", ".join(allowed))
"%s is not an allowed series. It needs to be one of %s.",
self._changelog.distributions,
", ".join(allowed),
)
return ask_for_ignoring_or_fixing()
return True
@ -337,7 +339,7 @@ class SourcePackage(object):
cmd = ["debdiff", dsc_file, self._dsc_file]
if not Logger.isEnabledFor(logging.DEBUG):
cmd.insert(1, "-q")
Logger.debug(" ".join(cmd) + " > " + self._debdiff_filename)
Logger.debug("%s > %s", " ".join(cmd), self._debdiff_filename)
with open(self._debdiff_filename, "w") as debdiff_file:
debdiff = subprocess.run(cmd, check=False, stdout=debdiff_file)
assert debdiff.returncode in (0, 1)
@ -362,7 +364,7 @@ class SourcePackage(object):
lp_bug = lp_bug.duplicate_of
if lp_bug.id not in fixed_bugs:
Logger.error("Launchpad bug #%i is not closed by new version." % (lp_bug.id))
Logger.error("Launchpad bug #%i is not closed by new version.", lp_bug.id)
return ask_for_ignoring_or_fixing()
return True
@ -432,7 +434,7 @@ class SourcePackage(object):
lintian_filename = os.path.join(
self._workdir, self._package + "_" + strip_epoch(self._version) + ".lintian"
)
Logger.debug(" ".join(cmd) + " > " + lintian_filename)
Logger.debug("%s > %s", " ".join(cmd), lintian_filename)
report = subprocess.check_output(cmd, encoding="utf-8")
# write lintian report file

View File

@ -93,7 +93,7 @@ process, exit the shell such that it returns an exit code other than zero.
)
returncode = subprocess.call(cmd)
if returncode != 0:
Logger.error("Shell exited with exit value %i." % (returncode))
Logger.error("Shell exited with exit value %i.", returncode)
sys.exit(1)
@ -176,7 +176,7 @@ def download_branch(branch):
cmd = ["bzr", "branch", branch]
Logger.debug(" ".join(cmd))
if subprocess.call(cmd) != 0:
Logger.error("Failed to download branch %s." % (branch))
Logger.error("Failed to download branch %s.", branch)
sys.exit(1)
return dir_name
@ -186,7 +186,7 @@ def merge_branch(branch):
cmd = ["bzr", "merge", branch]
Logger.debug(" ".join(cmd))
if subprocess.call(cmd) != 0:
Logger.error("Failed to merge branch %s." % (branch))
Logger.error("Failed to merge branch %s.", branch)
ask_for_manual_fixing()
edit = True
return edit
@ -198,7 +198,7 @@ def extract_source(dsc_file, verbose=False):
cmd.insert(1, "-q")
Logger.debug(" ".join(cmd))
if subprocess.call(cmd) != 0:
Logger.error("Extraction of %s failed." % (os.path.basename(dsc_file)))
Logger.error("Extraction of %s failed.", os.path.basename(dsc_file))
sys.exit(1)
@ -219,7 +219,7 @@ def get_open_ubuntu_bug_task(launchpad, bug, branch=None):
branch = branch[3:]
if len(ubuntu_tasks) == 0:
Logger.error("No Ubuntu bug task found on bug #%i." % (bug_id))
Logger.error("No Ubuntu bug task found on bug #%i.", bug_id)
sys.exit(1)
elif len(ubuntu_tasks) == 1:
task = ubuntu_tasks[0]
@ -243,7 +243,7 @@ def get_open_ubuntu_bug_task(launchpad, bug, branch=None):
task = open_ubuntu_tasks[0]
else:
Logger.info(
"https://launchpad.net/bugs/%i has %i Ubuntu tasks:" % (bug_id, len(ubuntu_tasks))
"https://launchpad.net/bugs/%i has %i Ubuntu tasks:", bug_id, len(ubuntu_tasks)
)
for i in range(len(ubuntu_tasks)):
print("%i) %s" % (i + 1, ubuntu_tasks[i].get_package_and_series()))
@ -251,7 +251,7 @@ def get_open_ubuntu_bug_task(launchpad, bug, branch=None):
"To which Ubuntu task does the patch belong", 1, len(ubuntu_tasks)
)
task = ubuntu_tasks[selected - 1]
Logger.debug("Selected Ubuntu task: %s" % (task.get_short_info()))
Logger.debug("Selected Ubuntu task: %s", task.get_short_info())
return task
@ -263,12 +263,14 @@ def _create_and_change_into(workdir):
os.makedirs(workdir)
except os.error as error:
Logger.error(
"Failed to create the working directory %s [Errno %i]: %s."
% (workdir, error.errno, error.strerror)
"Failed to create the working directory %s [Errno %i]: %s.",
workdir,
error.errno,
error.strerror,
)
sys.exit(1)
if workdir != os.getcwd():
Logger.debug("cd " + workdir)
Logger.debug("cd %s", workdir)
os.chdir(workdir)
@ -297,13 +299,13 @@ def _download_and_change_into(task, dsc_file, patch, branch):
branch_dir = download_branch(task.get_branch_link())
# change directory
Logger.debug("cd " + branch_dir)
Logger.debug("cd %s", branch_dir)
os.chdir(branch_dir)
else:
if patch:
patch.download()
Logger.debug("Ubuntu package: %s" % (task.package))
Logger.debug("Ubuntu package: %s", task.package)
if task.is_merge():
Logger.debug("The task is a merge request.")
if task.is_sync():
@ -313,7 +315,7 @@ def _download_and_change_into(task, dsc_file, patch, branch):
# change directory
directory = task.package + "-" + task.get_version().upstream_version
Logger.debug("cd " + directory)
Logger.debug("cd %s", directory)
os.chdir(directory)