Implement refactorings found by pylint

Signed-off-by: Benjamin Drung <benjamin.drung@canonical.com>
This commit is contained in:
Benjamin Drung 2023-01-31 16:58:24 +01:00
parent 4449cf2437
commit 444b319c12
24 changed files with 137 additions and 134 deletions

View File

@ -27,7 +27,7 @@ confidence=HIGH
# --enable=similarities". If you want to run only the classes checker, but have # --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes # no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W" # --disable=W"
disable=fixme,locally-disabled,missing-docstring disable=fixme,locally-disabled,missing-docstring,useless-option-value
[REPORTS] [REPORTS]

View File

@ -285,19 +285,19 @@ def get_old_version(source, release):
return pkg.getVersion() return pkg.getVersion()
except (SeriesNotFoundException, PackageNotFoundException): except (SeriesNotFoundException, PackageNotFoundException):
pass pass
return None
def get_backport_dist(release, release_pocket): def get_backport_dist(release, release_pocket):
if release_pocket: if release_pocket:
return release return release
else: return "%s-backports" % release
return "%s-backports" % release
def do_build(workdir, dsc, release, builder, update): def do_build(workdir, dsc, release, builder, update):
builder = get_builder(builder) builder = get_builder(builder)
if not builder: if not builder:
return return None
if update: if update:
if 0 != builder.update(release): if 0 != builder.update(release):

View File

@ -66,16 +66,16 @@ def check_support(apt_cache, pkgname, alt=False):
if src["Section"].startswith("universe") or src["Section"].startswith("multiverse"): if src["Section"].startswith("universe") or src["Section"].startswith("multiverse"):
print(prefix, "binary and source package is in", section.split("/")[0]) print(prefix, "binary and source package is in", section.split("/")[0])
return False return False
else:
print( print(
prefix, prefix,
"is in", "is in",
section.split("/")[0] + ", but its source", section.split("/")[0] + ", but its source",
pkg.candidate.source_name, pkg.candidate.source_name,
"is already in main; file an ubuntu-archive bug for " "is already in main; file an ubuntu-archive bug for "
"promoting the current preferred alternative", "promoting the current preferred alternative",
) )
return True return True
if alt: if alt:
print(prefix, "is already in main; consider preferring it") print(prefix, "is already in main; consider preferring it")

View File

@ -51,7 +51,7 @@ from ubuntutools.question import YesNoQuestion
Logger = getLogger() Logger = getLogger()
class PbuilderDist(object): class PbuilderDist:
def __init__(self, builder): def __init__(self, builder):
# Base directory where pbuilder will put all the files it creates. # Base directory where pbuilder will put all the files it creates.
self.base = None self.base = None
@ -179,19 +179,18 @@ class PbuilderDist(object):
if os.path.isfile(operation): if os.path.isfile(operation):
self.operation = "build" self.operation = "build"
return [operation] return [operation]
else: Logger.error('Could not find file "%s".', operation)
Logger.error('Could not find file "%s".', operation)
sys.exit(1)
else:
Logger.error(
'"%s" is not a recognized argument.\nPlease use one of these: %s.',
operation,
", ".join(arguments),
)
sys.exit(1) sys.exit(1)
else:
self.operation = operation Logger.error(
return [] '"%s" is not a recognized argument.\nPlease use one of these: %s.',
operation,
", ".join(arguments),
)
sys.exit(1)
self.operation = operation
return []
def get_command(self, remaining_arguments=None): def get_command(self, remaining_arguments=None):
"""PbuilderDist.get_command -> string """PbuilderDist.get_command -> string

View File

@ -177,6 +177,7 @@ def locate_package(package, distribution):
Logger.info( Logger.info(
"Binary package specified, considering its source package instead: %s", package "Binary package specified, considering its source package instead: %s", package
) )
return None
def request_backport(package_spph, source, destinations): def request_backport(package_spph, source, destinations):

View File

@ -378,7 +378,7 @@ def main():
status = "new" status = "new"
subscribe = "ubuntu-release" subscribe = "ubuntu-release"
srcpkg = not newsource and srcpkg or None srcpkg = None if newsource else srcpkg
if lpapi: if lpapi:
# Map status to the values expected by LP API # Map status to the values expected by LP API
mapping = {"new": "New", "confirmed": "Confirmed"} mapping = {"new": "New", "confirmed": "Confirmed"}

View File

@ -53,6 +53,7 @@ def load_index(url):
"Unable to parse seed data: %s. Deleting cached data, please try again.", str(e) "Unable to parse seed data: %s. Deleting cached data, please try again.", str(e)
) )
os.unlink(seeded) os.unlink(seeded)
return None
def resolve_binaries(sources): def resolve_binaries(sources):

View File

@ -51,6 +51,7 @@ def get_most_recent_debian_version(changelog):
version = block.version.full_version version = block.version.full_version
if not re.search("(ubuntu|build)", version): if not re.search("(ubuntu|build)", version):
return version return version
return None
def get_bug_body(changelog): def get_bug_body(changelog):
@ -69,7 +70,7 @@ In Ubuntu, the attached patch was applied to achieve the following:
Thanks for considering the patch. Thanks for considering the patch.
""" % ( """ % (
"\n".join([a for a in entry.changes()]) "\n".join(entry.changes())
) )
return msg return msg
@ -128,11 +129,10 @@ def gen_debdiff(tmpdir, changelog):
def check_file(fname, critical=True): def check_file(fname, critical=True):
if os.path.exists(fname): if os.path.exists(fname):
return fname return fname
else: if not critical:
if not critical: return False
return False Logger.info("Couldn't find «%s».\n", fname)
Logger.info("Couldn't find «%s».\n", fname) sys.exit(1)
sys.exit(1)
def submit_bugreport(body, debdiff, deb_version, changelog): def submit_bugreport(body, debdiff, deb_version, changelog):

View File

@ -87,7 +87,7 @@ def add_fixed_bugs(changes, bugs):
bugs.update(changes[i][22:].strip().split(" ")) bugs.update(changes[i][22:].strip().split(" "))
changes[i] = "Launchpad-Bugs-Fixed: %s" % (" ".join(bugs)) changes[i] = "Launchpad-Bugs-Fixed: %s" % (" ".join(bugs))
break break
elif i == len(changes) - 1: if i == len(changes) - 1:
# Launchpad-Bugs-Fixed entry does not exist in changes file # Launchpad-Bugs-Fixed entry does not exist in changes file
line = "Launchpad-Bugs-Fixed: %s" % (" ".join(bugs)) line = "Launchpad-Bugs-Fixed: %s" % (" ".join(bugs))
changes.append(line) changes.append(line)
@ -523,7 +523,7 @@ def parse():
metavar="BUG", metavar="BUG",
dest="bugs", dest="bugs",
action="append", action="append",
default=list(), default=[],
help="Mark Launchpad bug BUG as being fixed by this upload.", help="Mark Launchpad bug BUG as being fixed by this upload.",
) )
parser.add_argument( parser.add_argument(

View File

@ -277,7 +277,7 @@ def main():
me = PersonTeam.me me = PersonTeam.me
# Check permisions (part 1): Rescoring can only be done by buildd admins # Check permisions (part 1): Rescoring can only be done by buildd admins
can_rescore = (args.priority and me.isLpTeamMember("launchpad-buildd-admins")) or False can_rescore = args.priority and me.isLpTeamMember("launchpad-buildd-admins")
if args.priority and not can_rescore: if args.priority and not can_rescore:
Logger.error( Logger.error(
"You don't have the permissions to rescore builds. Ignoring your rescore request." "You don't have the permissions to rescore builds. Ignoring your rescore request."

View File

@ -446,7 +446,8 @@ class SourcePackage(ABC):
Logger.error("Download Error: %s", e) Logger.error("Download Error: %s", e)
raise DownloadError(f"Failed to download {filename}") raise DownloadError(f"Failed to download {filename}")
def pull_dsc(self): @staticmethod
def pull_dsc():
"""DEPRECATED """DEPRECATED
This method is badly named and historically has only 'pulled' the This method is badly named and historically has only 'pulled' the
@ -565,7 +566,7 @@ class DebianSPPH(SourcePackagePublishingHistory):
resource_type = "source_package_publishing_history" resource_type = "source_package_publishing_history"
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(DebianSPPH, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self._srcpkg = None self._srcpkg = None
def getBinaries(self, arch=None, name=None, ext=None): def getBinaries(self, arch=None, name=None, ext=None):
@ -589,7 +590,7 @@ class DebianSourcePackage(SourcePackage):
return DebianSPPH return DebianSPPH
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(DebianSourcePackage, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.masters.append(UDTConfig.defaults["DEBSEC_MIRROR"]) self.masters.append(UDTConfig.defaults["DEBSEC_MIRROR"])
# Cached values: # Cached values:
@ -611,7 +612,7 @@ class DebianSourcePackage(SourcePackage):
if not self._spph: if not self._spph:
try: try:
# superclass will set self._spph # superclass will set self._spph
return super(DebianSourcePackage, self).lp_spph return super().lp_spph
except PackageNotFoundException: except PackageNotFoundException:
pass pass
except SeriesNotFoundException: except SeriesNotFoundException:
@ -631,7 +632,7 @@ class DebianSourcePackage(SourcePackage):
def _source_urls(self, name): def _source_urls(self, name):
"Generator of sources for name" "Generator of sources for name"
for url in super(DebianSourcePackage, self)._source_urls(name): for url in super()._source_urls(name):
yield url yield url
if name in self.snapshot_files: if name in self.snapshot_files:
yield self.snapshot_files[name] yield self.snapshot_files[name]
@ -683,7 +684,7 @@ class PersonalPackageArchiveSourcePackage(UbuntuSourcePackage):
"Download / unpack an Ubuntu Personal Package Archive source package" "Download / unpack an Ubuntu Personal Package Archive source package"
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(PersonalPackageArchiveSourcePackage, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
assert "ppa" in kwargs assert "ppa" in kwargs
ppa = kwargs["ppa"].split("/") ppa = kwargs["ppa"].split("/")
if len(ppa) != 2: if len(ppa) != 2:
@ -755,7 +756,7 @@ class UbuntuCloudArchiveSourcePackage(PersonalPackageArchiveSourcePackage):
) )
kwargs["ppa"] = f"{self.TEAM}/{series}-{pocket}" kwargs["ppa"] = f"{self.TEAM}/{series}-{pocket}"
super(UbuntuCloudArchiveSourcePackage, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
if pocket == "staging": if pocket == "staging":
# Don't bother with the archive; just get directly from the staging ppa, since # Don't bother with the archive; just get directly from the staging ppa, since
@ -776,7 +777,7 @@ class UbuntuCloudArchiveSourcePackage(PersonalPackageArchiveSourcePackage):
"Binaries from 'staging' pocket will not match published binaries; " "Binaries from 'staging' pocket will not match published binaries; "
"see https://bugs.launchpad.net/cloud-archive/+bug/1649979" "see https://bugs.launchpad.net/cloud-archive/+bug/1649979"
) )
return super(UbuntuCloudArchiveSourcePackage, self).pull_binaries(arch, name, ext) return super().pull_binaries(arch, name, ext)
@classmethod @classmethod
@functools.lru_cache() @functools.lru_cache()
@ -925,8 +926,8 @@ class UbuntuCloudArchiveSourcePackage(PersonalPackageArchiveSourcePackage):
return default return default
class _WebJSON(object): class _WebJSON:
def getHostUrl(self): def getHostUrl(self): # pylint: disable=no-self-use
raise Exception("Not implemented") raise Exception("Not implemented")
def load(self, path=""): def load(self, path=""):
@ -949,7 +950,7 @@ class Madison(_WebJSON):
} }
def __init__(self, distro="debian"): def __init__(self, distro="debian"):
super(Madison, self).__init__() super().__init__()
self._distro = distro self._distro = distro
# This currently will NOT work with ubuntu; it doesn't support f=json # This currently will NOT work with ubuntu; it doesn't support f=json
if distro != "debian": if distro != "debian":
@ -1043,7 +1044,7 @@ class _Snapshot(_WebJSON):
Snapshot = _Snapshot() Snapshot = _Snapshot()
class SnapshotPackage(object): class SnapshotPackage:
def __init__(self, obj): def __init__(self, obj):
self.name = None self.name = None
self._obj = obj self._obj = obj
@ -1064,7 +1065,7 @@ class SnapshotPackage(object):
class SnapshotSourcePackage(SnapshotPackage): class SnapshotSourcePackage(SnapshotPackage):
def __init__(self, obj, name): def __init__(self, obj, name):
# obj required fields: 'version' # obj required fields: 'version'
super(SnapshotSourcePackage, self).__init__(obj) super().__init__(obj)
self.name = name self.name = name
self._binary_files = None self._binary_files = None
self._spph = None self._spph = None
@ -1163,7 +1164,7 @@ class SnapshotBinaryPackage(SnapshotPackage):
return [f for f in self._files if f.isArch(arch)] return [f for f in self._files if f.isArch(arch)]
class SnapshotFile(object): class SnapshotFile:
def __init__(self, pkg_name, pkg_version, component, obj, h): # pylint: disable=invalid-name def __init__(self, pkg_name, pkg_version, component, obj, h): # pylint: disable=invalid-name
self.package_name = pkg_name self.package_name = pkg_name
self.package_version = pkg_version self.package_version = pkg_version
@ -1171,7 +1172,8 @@ class SnapshotFile(object):
self._obj = obj self._obj = obj
self._hash = h self._hash = h
def getType(self): @staticmethod
def getType():
return None return None
@property @property
@ -1198,11 +1200,10 @@ class SnapshotFile(object):
def date(self): def date(self):
if "run" in self._obj: if "run" in self._obj:
return self._obj["run"] return self._obj["run"]
elif "first_seen" in self._obj: if "first_seen" in self._obj:
return self._obj["first_seen"] return self._obj["first_seen"]
else: Logger.error("File %s has no date information", self.name)
Logger.error("File %s has no date information", self.name) return "unknown"
return "unknown"
def getHash(self): def getHash(self):
return self._hash return self._hash
@ -1215,13 +1216,14 @@ class SnapshotFile(object):
class SnapshotSourceFile(SnapshotFile): class SnapshotSourceFile(SnapshotFile):
def getType(self): @staticmethod
def getType():
return "source" return "source"
class SnapshotBinaryFile(SnapshotFile): class SnapshotBinaryFile(SnapshotFile):
def __init__(self, name, version, component, obj, h, arch, source): def __init__(self, name, version, component, obj, h, arch, source):
super(SnapshotBinaryFile, self).__init__(name, version, component, obj, h) super().__init__(name, version, component, obj, h)
self.source = source self.source = source
self.arch = arch self.arch = arch
self._bpph = None self._bpph = None
@ -1233,7 +1235,8 @@ class SnapshotBinaryFile(SnapshotFile):
return True return True
return arch == self.arch return arch == self.arch
def getType(self): @staticmethod
def getType():
return "binary" return "binary"
def getBPPH(self): def getBPPH(self):
@ -1242,7 +1245,7 @@ class SnapshotBinaryFile(SnapshotFile):
return self._bpph return self._bpph
class SnapshotSPPH(object): class SnapshotSPPH:
"""Provide the same interface as SourcePackagePublishingHistory""" """Provide the same interface as SourcePackagePublishingHistory"""
def __init__(self, snapshot_pkg): def __init__(self, snapshot_pkg):
@ -1309,7 +1312,7 @@ class SnapshotSPPH(object):
return f["sha1"] return f["sha1"]
return None return None
def sourceFileSha256(self, url_or_filename): # pylint: disable=unused-argument def sourceFileSha256(self, url_or_filename): # pylint: disable=no-self-use,unused-argument
return None return None
def sourceFileSize(self, url_or_filename): def sourceFileSize(self, url_or_filename):
@ -1366,7 +1369,7 @@ class SnapshotSPPH(object):
return [b.getBPPH() for b in self._pkg.getBinaryFiles(arch=arch, name=name, ext=ext)] return [b.getBPPH() for b in self._pkg.getBinaryFiles(arch=arch, name=name, ext=ext)]
class SnapshotBPPH(object): class SnapshotBPPH: # pylint: disable=too-many-public-methods
"""Provide the same interface as BinaryPackagePublishingHistory""" """Provide the same interface as BinaryPackagePublishingHistory"""
def __init__(self, snapshot_binfile): def __init__(self, snapshot_binfile):
@ -1439,7 +1442,7 @@ class SnapshotBPPH(object):
return self._file.getHash() return self._file.getHash()
return None return None
def binaryFileSha256(self, url_or_filename): # pylint: disable=unused-argument def binaryFileSha256(self, url_or_filename): # pylint: disable=no-self-use,unused-argument
return None return None
def binaryFileSize(self, url_or_filename): def binaryFileSize(self, url_or_filename):
@ -1447,7 +1450,8 @@ class SnapshotBPPH(object):
return int(self._file.size) return int(self._file.size)
return 0 return 0
def getBuild(self): @staticmethod
def getBuild():
return None return None
def getUrl(self): def getUrl(self):

View File

@ -31,7 +31,7 @@ def _build_preparation(result_directory):
os.makedirs(result_directory) os.makedirs(result_directory)
class Builder(object): class Builder:
def __init__(self, name): def __init__(self, name):
self.name = name self.name = name
cmd = ["dpkg-architecture", "-qDEB_BUILD_ARCH_CPU"] cmd = ["dpkg-architecture", "-qDEB_BUILD_ARCH_CPU"]
@ -197,3 +197,4 @@ def get_builder(name):
else: else:
Logger.error("Unsupported builder specified: %s.", name) Logger.error("Unsupported builder specified: %s.", name)
Logger.error("Supported builders: %s", ", ".join(sorted(_SUPPORTED_BUILDERS.keys()))) Logger.error("Supported builders: %s", ", ".join(sorted(_SUPPORTED_BUILDERS.keys())))
return None

View File

@ -27,7 +27,7 @@ import sys
Logger = logging.getLogger(__name__) Logger = logging.getLogger(__name__)
class UDTConfig(object): class UDTConfig:
"""Ubuntu Dev Tools configuration file (devscripts config file) and """Ubuntu Dev Tools configuration file (devscripts config file) and
environment variable parsing. environment variable parsing.
""" """
@ -61,7 +61,8 @@ class UDTConfig(object):
if not no_conf: if not no_conf:
self.config = self.parse_devscripts_config() self.config = self.parse_devscripts_config()
def parse_devscripts_config(self): @staticmethod
def parse_devscripts_config():
"""Read the devscripts configuration files, and return the values as a """Read the devscripts configuration files, and return the values as a
dictionary dictionary
""" """

View File

@ -73,7 +73,7 @@ __all__ = [
] ]
class _Launchpad(object): class _Launchpad:
"""Singleton for LP API access.""" """Singleton for LP API access."""
__lp = None __lp = None
@ -131,10 +131,10 @@ class MetaWrapper(type):
super(MetaWrapper, cls).__init__(name, bases, attrd) super(MetaWrapper, cls).__init__(name, bases, attrd)
if "resource_type" not in attrd: if "resource_type" not in attrd:
raise TypeError('Class "%s" needs an associated resource type' % name) raise TypeError('Class "%s" needs an associated resource type' % name)
cls._cache = dict() cls._cache = {}
class BaseWrapper(object, metaclass=MetaWrapper): class BaseWrapper(metaclass=MetaWrapper):
""" """
A base class from which other wrapper classes are derived. A base class from which other wrapper classes are derived.
""" """
@ -173,15 +173,13 @@ class BaseWrapper(object, metaclass=MetaWrapper):
if isinstance(cache, collections.abc.Callable): if isinstance(cache, collections.abc.Callable):
cache(cached) cache(cached)
return cached return cached
else: raise TypeError("'%s' is not a '%s' object" % (str(data), str(cls.resource_type)))
raise TypeError("'%s' is not a '%s' object" % (str(data), str(cls.resource_type)))
else: # not a LP API representation, let the specific class handle it
# not a LP API representation, let the specific class handle it fetch = getattr(cls, "fetch", None)
fetch = getattr(cls, "fetch", None) if isinstance(fetch, collections.abc.Callable):
if isinstance(fetch, collections.abc.Callable): return fetch(data)
return fetch(data) raise NotImplementedError("Don't know how to fetch '%s' from LP" % str(data))
else:
raise NotImplementedError("Don't know how to fetch '%s' from LP" % str(data))
def __call__(self): def __call__(self):
return self._lpobject return self._lpobject
@ -192,8 +190,7 @@ class BaseWrapper(object, metaclass=MetaWrapper):
def __repr__(self): def __repr__(self):
if hasattr(str, "format"): if hasattr(str, "format"):
return "<{0}: {1!r}>".format(self.__class__.__name__, self._lpobject) return "<{0}: {1!r}>".format(self.__class__.__name__, self._lpobject)
else: return "<%s: %r>" % (self.__class__.__name__, self._lpobject)
return "<%s: %r>" % (self.__class__.__name__, self._lpobject)
class Distribution(BaseWrapper): class Distribution(BaseWrapper):
@ -204,9 +201,9 @@ class Distribution(BaseWrapper):
resource_type = "distribution" resource_type = "distribution"
def __init__(self, *args): # pylint: disable=unused-argument def __init__(self, *args): # pylint: disable=unused-argument
self._archives = dict() self._archives = {}
self._series_by_name = dict() self._series_by_name = {}
self._series = dict() self._series = {}
self._dev_series = None self._dev_series = None
self._have_all_series = False self._have_all_series = False
self._main_archive = None self._main_archive = None
@ -253,13 +250,12 @@ class Distribution(BaseWrapper):
if res: if res:
return res return res
else: message = "The Archive '%s' doesn't exist in %s" % (archive, self.display_name)
message = "The Archive '%s' doesn't exist in %s" % (archive, self.display_name) raise ArchiveNotFoundException(message)
raise ArchiveNotFoundException(message)
else: if self._main_archive is None:
if self._main_archive is None: self._main_archive = Archive(self.main_archive_link)
self._main_archive = Archive(self.main_archive_link) return self._main_archive
return self._main_archive
def getSeries(self, name_or_version): def getSeries(self, name_or_version):
""" """
@ -310,7 +306,7 @@ class Distribution(BaseWrapper):
return collections.OrderedDict((s.name, s) for s in allseries) return collections.OrderedDict((s.name, s) for s in allseries)
class DistroArchSeries(BaseWrapper): class DistroArchSeries(BaseWrapper): # pylint: disable=too-few-public-methods
""" """
Wrapper class around a LP distro arch series object. Wrapper class around a LP distro arch series object.
""" """
@ -333,7 +329,7 @@ class DistroSeries(BaseWrapper):
def __init__(self, *args): # pylint: disable=unused-argument def __init__(self, *args): # pylint: disable=unused-argument
if "_architectures" not in self.__dict__: if "_architectures" not in self.__dict__:
self._architectures = dict() self._architectures = {}
def getArchSeries(self, archtag=None): def getArchSeries(self, archtag=None):
""" """
@ -625,7 +621,7 @@ class Archive(BaseWrapper):
series_to_check = [dist.getDevelopmentSeries()] series_to_check = [dist.getDevelopmentSeries()]
# check each series - if only version was provided, series will be None # check each series - if only version was provided, series will be None
for series in series_to_check: for series in series_to_check: # pylint: disable=redefined-argument-from-local
arch_series = None arch_series = None
if isinstance(series, DistroArchSeries): if isinstance(series, DistroArchSeries):
@ -851,7 +847,7 @@ class SourcePackagePublishingHistory(BaseWrapper):
# Don't share _builds between different # Don't share _builds between different
# SourcePackagePublishingHistory objects # SourcePackagePublishingHistory objects
if "_builds" not in self.__dict__: if "_builds" not in self.__dict__:
self._builds = dict() self._builds = {}
def getDistroSeries(self): def getDistroSeries(self):
""" """
@ -1109,7 +1105,7 @@ class SourcePackagePublishingHistory(BaseWrapper):
self._builds[build.arch_tag] = Build(build) self._builds[build.arch_tag] = Build(build)
def getBuildStates(self, archs): def getBuildStates(self, archs):
res = list() res = []
if not self._builds: if not self._builds:
self._fetch_builds() self._fetch_builds()
@ -1121,7 +1117,7 @@ class SourcePackagePublishingHistory(BaseWrapper):
return "Build state(s) for '%s':\n%s" % (self.getPackageName(), "\n".join(res)) return "Build state(s) for '%s':\n%s" % (self.getPackageName(), "\n".join(res))
def rescoreBuilds(self, archs, score): def rescoreBuilds(self, archs, score):
res = list() res = []
if not self._builds: if not self._builds:
self._fetch_builds() self._fetch_builds()
@ -1140,7 +1136,7 @@ class SourcePackagePublishingHistory(BaseWrapper):
) )
def retryBuilds(self, archs): def retryBuilds(self, archs):
res = list() res = []
if not self._builds: if not self._builds:
self._fetch_builds() self._fetch_builds()
@ -1317,8 +1313,7 @@ class BinaryPackagePublishingHistory(BaseWrapper):
""" """
if bool(self._lpobject.architecture_specific): if bool(self._lpobject.architecture_specific):
return self.arch return self.arch
else: return "all"
return "all"
def getFileExt(self): def getFileExt(self):
""" """
@ -1394,7 +1389,7 @@ class PersonTeam(BaseWrapper, metaclass=MetaPersonTeam):
# Don't share _upload between different PersonTeams # Don't share _upload between different PersonTeams
self._ppas = None self._ppas = None
if "_upload" not in self.__dict__: if "_upload" not in self.__dict__:
self._upload = dict() self._upload = {}
def __str__(self): def __str__(self):
return "%s (%s)" % (self.display_name, self.name) return "%s (%s)" % (self.display_name, self.name)
@ -1513,7 +1508,7 @@ class Project(BaseWrapper):
return Project(Launchpad.projects(project)) return Project(Launchpad.projects(project))
class ProjectSeries(BaseWrapper): class ProjectSeries(BaseWrapper): # pylint: disable=too-few-public-methods
""" """
Wrapper class around a LP project_series object. Wrapper class around a LP project_series object.
""" """
@ -1556,7 +1551,7 @@ class Build(BaseWrapper):
return False return False
class DistributionSourcePackage(BaseWrapper): class DistributionSourcePackage(BaseWrapper): # pylint: disable=too-few-public-methods
""" """
Caching class for distribution_source_package objects. Caching class for distribution_source_package objects.
""" """
@ -1564,7 +1559,7 @@ class DistributionSourcePackage(BaseWrapper):
resource_type = "distribution_source_package" resource_type = "distribution_source_package"
class Packageset(BaseWrapper): class Packageset(BaseWrapper): # pylint: disable=too-few-public-methods
""" """
Caching class for packageset objects. Caching class for packageset objects.
""" """

View File

@ -215,6 +215,7 @@ def codename_to_distribution(codename):
if info().valid(codename): if info().valid(codename):
return distro return distro
return None
def verify_file_checksums(pathname, checksums=None, size=0): def verify_file_checksums(pathname, checksums=None, size=0):
@ -364,7 +365,7 @@ def download(src, dst, size=0, *, blocksize=DOWNLOAD_BLOCKSIZE_DEFAULT):
return dst return dst
class _StderrProgressBar(object): class _StderrProgressBar:
BAR_WIDTH_MIN = 40 BAR_WIDTH_MIN = 40
BAR_WIDTH_DEFAULT = 60 BAR_WIDTH_DEFAULT = 60

View File

@ -88,7 +88,7 @@ class InvalidPullValueError(ValueError):
"""Thrown when --pull value is invalid""" """Thrown when --pull value is invalid"""
class PullPkg(object): class PullPkg:
"""Class used to pull file(s) associated with a specific package""" """Class used to pull file(s) associated with a specific package"""
@classmethod @classmethod
@ -218,7 +218,8 @@ class PullPkg(object):
return self.parse_options(vars(newparser.parse_args(args))) return self.parse_options(vars(newparser.parse_args(args)))
def parse_pull(self, pull): @staticmethod
def parse_pull(pull):
if not pull: if not pull:
raise InvalidPullValueError("Must specify --pull") raise InvalidPullValueError("Must specify --pull")
@ -236,7 +237,8 @@ class PullPkg(object):
return pull return pull
def parse_distro(self, distro): @staticmethod
def parse_distro(distro):
if not distro: if not distro:
raise InvalidDistroValueError("Must specify --distro") raise InvalidDistroValueError("Must specify --distro")
@ -256,7 +258,8 @@ class PullPkg(object):
return distro return distro
def parse_release(self, distro, release): @staticmethod
def parse_release(distro, release):
if distro == DISTRO_UCA: if distro == DISTRO_UCA:
return UbuntuCloudArchiveSourcePackage.parseReleaseAndPocket(release) return UbuntuCloudArchiveSourcePackage.parseReleaseAndPocket(release)
@ -503,7 +506,7 @@ class PullPkg(object):
status=None, status=None,
download_only=None, download_only=None,
**kwargs, **kwargs,
): # pylint: disable=unused-argument ): # pylint: disable=no-self-use,unused-argument
if not series: if not series:
Logger.error("Using --upload-queue requires specifying series") Logger.error("Using --upload-queue requires specifying series")
return return

View File

@ -23,7 +23,7 @@ import sys
import tempfile import tempfile
class Question(object): class Question:
def __init__(self, options, show_help=True): def __init__(self, options, show_help=True):
assert len(options) >= 2 assert len(options) >= 2
self.options = [s.lower() for s in options] self.options = [s.lower() for s in options]
@ -116,7 +116,7 @@ def confirmation_prompt(message=None, action=None):
sys.exit(1) sys.exit(1)
class EditFile(object): class EditFile:
def __init__(self, filename, description, placeholders=None): def __init__(self, filename, description, placeholders=None):
self.filename = filename self.filename = filename
self.description = description self.description = description
@ -158,7 +158,7 @@ class EditFile(object):
elif self.check_edit(): elif self.check_edit():
done = True done = True
def check_edit(self): def check_edit(self): # pylint: disable=no-self-use
"""Override this to implement extra checks on the edited report. """Override this to implement extra checks on the edited report.
Should return False if another round of editing is needed, Should return False if another round of editing is needed,
and should prompt the user to confirm that, if necessary. and should prompt the user to confirm that, if necessary.
@ -176,7 +176,7 @@ class EditBugReport(EditFile):
("Summary (one line):\n%s\n\nDescription:\n%s" % (subject, body)).encode("utf-8") ("Summary (one line):\n%s\n\nDescription:\n%s" % (subject, body)).encode("utf-8")
) )
tmpfile.close() tmpfile.close()
super(EditBugReport, self).__init__(tmpfile.name, "bug report", placeholders) super().__init__(tmpfile.name, "bug report", placeholders)
def check_edit(self): def check_edit(self):
with open(self.filename, "r", encoding="utf-8") as f: with open(self.filename, "r", encoding="utf-8") as f:

View File

@ -37,7 +37,7 @@ def is_sync(bug):
return "sync" in bug.title.lower().split(" ") or "sync" in bug.tags return "sync" in bug.title.lower().split(" ") or "sync" in bug.tags
class BugTask(object): class BugTask:
def __init__(self, bug_task, launchpad): def __init__(self, bug_task, launchpad):
self.bug_task = bug_task self.bug_task = bug_task
self.launchpad = launchpad self.launchpad = launchpad
@ -126,8 +126,7 @@ class BugTask(object):
if self.series is None or latest_release: if self.series is None or latest_release:
dist = self.launchpad.distributions[self.project] dist = self.launchpad.distributions[self.project]
return dist.current_series.name return dist.current_series.name
else: return self.series
return self.series
def get_short_info(self): def get_short_info(self):
return self.bug_task.bug_target_name + ": " + self.bug_task.status return self.bug_task.bug_target_name + ": " + self.bug_task.status

View File

@ -26,7 +26,7 @@ from ubuntutools.sponsor_patch.question import ask_for_manual_fixing
Logger = logging.getLogger(__name__) Logger = logging.getLogger(__name__)
class Patch(object): class Patch:
"""This object represents a patch that can be downloaded from Launchpad.""" """This object represents a patch that can be downloaded from Launchpad."""
def __init__(self, patch): def __init__(self, patch):

View File

@ -58,7 +58,7 @@ def strip_epoch(version):
return version_without_epoch return version_without_epoch
class SourcePackage(object): class SourcePackage:
"""This class represents a source package.""" """This class represents a source package."""
def __init__(self, package, builder, workdir, branch): def __init__(self, package, builder, workdir, branch):
@ -79,7 +79,7 @@ class SourcePackage(object):
answer = question.ask("Do you want to acknowledge the sync request", "no") answer = question.ask("Do you want to acknowledge the sync request", "no")
if answer == "edit": if answer == "edit":
return False return False
elif answer == "no": if answer == "no":
user_abort() user_abort()
bug = task.bug bug = task.bug
@ -139,7 +139,7 @@ class SourcePackage(object):
answer = question.ask("Do you want to upload the package to %s" % target, "no") answer = question.ask("Do you want to upload the package to %s" % target, "no")
if answer == "edit": if answer == "edit":
return False return False
elif answer == "no": if answer == "no":
user_abort() user_abort()
cmd = ["dput", "--force", upload, self._changes_file] cmd = ["dput", "--force", upload, self._changes_file]
Logger.debug(" ".join(cmd)) Logger.debug(" ".join(cmd))
@ -200,13 +200,12 @@ class SourcePackage(object):
answer = question.ask("Do you want to resolve this issue manually", "yes") answer = question.ask("Do you want to resolve this issue manually", "yes")
if answer == "yes": if answer == "yes":
break break
elif answer == "update": if answer == "update":
update = True update = True
continue continue
elif answer == "retry": if answer == "retry":
continue continue
else: user_abort()
user_abort()
successful_built = True successful_built = True
if not successful_built: if not successful_built:
# We want to do a manual fix if the build failed. # We want to do a manual fix if the build failed.

View File

@ -356,10 +356,7 @@ def sponsor_patch(bug_number, build, builder, edit, keyid, lpinstance, update, u
series = task.get_debian_source_series() series = task.get_debian_source_series()
if source_package.sync(upload, series, bug_number, bug.owner.name): if source_package.sync(upload, series, bug_number, bug.owner.name):
return return
else: edit = True
edit = True
else:
edit = True
if patch: if patch:
edit |= patch.apply(task) edit |= patch.apply(task)

View File

@ -22,7 +22,7 @@ from pathlib import Path
from ubuntutools.version import Version from ubuntutools.version import Version
class ExamplePackage(object): class ExamplePackage:
def __init__(self, source="example", version="1.0-1", destdir="test-data"): def __init__(self, source="example", version="1.0-1", destdir="test-data"):
self.source = source self.source = source
self.version = Version(version) self.version = Version(version)

View File

@ -40,7 +40,7 @@ class ConfigTestCase(unittest.TestCase):
return StringIO(files[filename]) return StringIO(files[filename])
def setUp(self): def setUp(self):
super(ConfigTestCase, self).setUp() super().setUp()
open_mock = mock.mock_open() open_mock = mock.mock_open()
open_mock.side_effect = self._fake_open open_mock.side_effect = self._fake_open
patcher = mock.patch("builtins.open", open_mock) patcher = mock.patch("builtins.open", open_mock)
@ -105,7 +105,8 @@ REPEAT=yes
# self.assertRegex(errs, # self.assertRegex(errs,
# r'Warning: Cannot parse.*\bCOMMAND_EXECUTION=a') # r'Warning: Cannot parse.*\bCOMMAND_EXECUTION=a')
def get_value(self, *args, **kwargs): @staticmethod
def get_value(*args, **kwargs):
config = UDTConfig(prefix="TEST") config = UDTConfig(prefix="TEST")
return config.get_value(*args, **kwargs) return config.get_value(*args, **kwargs)
@ -166,7 +167,8 @@ class UbuEmailTestCase(unittest.TestCase):
def tearDown(self): def tearDown(self):
self.clean_environment() self.clean_environment()
def clean_environment(self): @staticmethod
def clean_environment():
for k in ("UBUMAIL", "DEBEMAIL", "DEBFULLNAME"): for k in ("UBUMAIL", "DEBEMAIL", "DEBFULLNAME"):
if k in os.environ: if k in os.environ:
del os.environ[k] del os.environ[k]

View File

@ -37,7 +37,7 @@ class MaintainerUpdateException(Exception):
pass pass
class Control(object): class Control:
"""Represents a debian/control file""" """Represents a debian/control file"""
def __init__(self, filename): def __init__(self, filename):