From 32b690e90298f3c17e71c08d87e9727cfce8d3fb Mon Sep 17 00:00:00 2001 From: Jhon Honce Date: Tue, 24 Jul 2018 16:44:45 -0700 Subject: Clean up pylint warnings and errors * Some of the pedantic errors were not corrected * Clean up prep for porting to MacOS and PyPi hosting Signed-off-by: Jhon Honce Closes: #1155 Approved by: baude --- contrib/python/pypodman/pypodman/lib/__init__.py | 6 +++--- .../python/pypodman/pypodman/lib/action_base.py | 9 ++++---- .../pypodman/pypodman/lib/actions/__init__.py | 8 ++++---- .../pypodman/pypodman/lib/actions/images_action.py | 8 ++++---- .../pypodman/pypodman/lib/actions/ps_action.py | 6 +++--- .../pypodman/pypodman/lib/actions/rm_action.py | 10 ++++----- .../pypodman/pypodman/lib/actions/rmi_action.py | 12 +++++------ contrib/python/pypodman/pypodman/lib/config.py | 24 ++++++++++++---------- .../pypodman/pypodman/lib/future_abstract.py | 20 ------------------ contrib/python/pypodman/pypodman/lib/report.py | 14 +++++++------ contrib/python/pypodman/pypodman/main.py | 19 ++++++++--------- 11 files changed, 59 insertions(+), 77 deletions(-) delete mode 100644 contrib/python/pypodman/pypodman/lib/future_abstract.py diff --git a/contrib/python/pypodman/pypodman/lib/__init__.py b/contrib/python/pypodman/pypodman/lib/__init__.py index 5a8303668..e3654dc2b 100644 --- a/contrib/python/pypodman/pypodman/lib/__init__.py +++ b/contrib/python/pypodman/pypodman/lib/__init__.py @@ -1,7 +1,7 @@ """Remote podman client support library.""" -from .action_base import AbstractActionBase -from .config import PodmanArgumentParser -from .report import Report, ReportColumn +from pypodman.lib.action_base import AbstractActionBase +from pypodman.lib.config import PodmanArgumentParser +from pypodman.lib.report import (Report, ReportColumn) __all__ = [ 'AbstractActionBase', diff --git a/contrib/python/pypodman/pypodman/lib/action_base.py b/contrib/python/pypodman/pypodman/lib/action_base.py index ff2922262..8b86c02df 100644 --- a/contrib/python/pypodman/pypodman/lib/action_base.py +++ b/contrib/python/pypodman/pypodman/lib/action_base.py @@ -67,11 +67,10 @@ class AbstractActionBase(abc.ABC): if self._args.host is None: return podman.Client( uri=self.local_uri) - else: - return podman.Client( - uri=self.local_uri, - remote_uri=self.remote_uri, - identity_file=self.identity_file) + return podman.Client( + uri=self.local_uri, + remote_uri=self.remote_uri, + identity_file=self.identity_file) def __repr__(self): """Compute the “official” string representation of object.""" diff --git a/contrib/python/pypodman/pypodman/lib/actions/__init__.py b/contrib/python/pypodman/pypodman/lib/actions/__init__.py index cdc58b6ab..4719f5d5c 100644 --- a/contrib/python/pypodman/pypodman/lib/actions/__init__.py +++ b/contrib/python/pypodman/pypodman/lib/actions/__init__.py @@ -1,7 +1,7 @@ """Module to export all the podman subcommands.""" -from .images_action import Images -from .ps_action import Ps -from .rm_action import Rm -from .rmi_action import Rmi +from pypodman.lib.actions.images_action import Images +from pypodman.lib.actions.ps_action import Ps +from pypodman.lib.actions.rm_action import Rm +from pypodman.lib.actions.rmi_action import Rmi __all__ = ['Images', 'Ps', 'Rm', 'Rmi'] diff --git a/contrib/python/pypodman/pypodman/lib/actions/images_action.py b/contrib/python/pypodman/pypodman/lib/actions/images_action.py index f6a7497e5..b8f5ccc78 100644 --- a/contrib/python/pypodman/pypodman/lib/actions/images_action.py +++ b/contrib/python/pypodman/pypodman/lib/actions/images_action.py @@ -3,9 +3,9 @@ import operator from collections import OrderedDict import humanize -import podman -from .. import AbstractActionBase, Report, ReportColumn +import podman +from pypodman.lib import AbstractActionBase, Report, ReportColumn class Images(AbstractActionBase): @@ -55,8 +55,8 @@ class Images(AbstractActionBase): images = sorted( self.client.images.list(), key=operator.attrgetter(self._args.sort)) - if len(images) == 0: - return 0 + if not images: + return rows = list() for image in images: diff --git a/contrib/python/pypodman/pypodman/lib/actions/ps_action.py b/contrib/python/pypodman/pypodman/lib/actions/ps_action.py index 4bbec5578..83954479c 100644 --- a/contrib/python/pypodman/pypodman/lib/actions/ps_action.py +++ b/contrib/python/pypodman/pypodman/lib/actions/ps_action.py @@ -5,7 +5,7 @@ from collections import OrderedDict import humanize import podman -from .. import AbstractActionBase, Report, ReportColumn +from pypodman.lib import AbstractActionBase, Report, ReportColumn class Ps(AbstractActionBase): @@ -55,8 +55,8 @@ class Ps(AbstractActionBase): ctnrs = sorted( self.client.containers.list(), key=operator.attrgetter(self._args.sort)) - if len(ctnrs) == 0: - return 0 + if not ctnrs: + return rows = list() for ctnr in ctnrs: diff --git a/contrib/python/pypodman/pypodman/lib/actions/rm_action.py b/contrib/python/pypodman/pypodman/lib/actions/rm_action.py index bd8950bd6..ae3a42245 100644 --- a/contrib/python/pypodman/pypodman/lib/actions/rm_action.py +++ b/contrib/python/pypodman/pypodman/lib/actions/rm_action.py @@ -3,7 +3,7 @@ import sys import podman -from .. import AbstractActionBase +from pypodman.lib import AbstractActionBase class Rm(AbstractActionBase): @@ -26,17 +26,17 @@ class Rm(AbstractActionBase): def __init__(self, args): """Construct Rm class.""" super().__init__(args) - if len(args.targets) < 1: + if not args.targets: raise ValueError('You must supply at least one container id' ' or name to be deleted.') def remove(self): """Remove container(s).""" - for id in self._args.targets: + for id_ in self._args.targets: try: - ctnr = self.client.containers.get(id) + ctnr = self.client.containers.get(id_) ctnr.remove(self._args.force) - print(id) + print(id_) except podman.ContainerNotFound as e: sys.stdout.flush() print( diff --git a/contrib/python/pypodman/pypodman/lib/actions/rmi_action.py b/contrib/python/pypodman/pypodman/lib/actions/rmi_action.py index 91f0deeaf..8d9fcbb58 100644 --- a/contrib/python/pypodman/pypodman/lib/actions/rmi_action.py +++ b/contrib/python/pypodman/pypodman/lib/actions/rmi_action.py @@ -3,11 +3,11 @@ import sys import podman -from .. import AbstractActionBase +from pypodman.lib import AbstractActionBase class Rmi(AbstractActionBase): - """Clas for removing images from storage.""" + """Class for removing images from storage.""" @classmethod def subparser(cls, parent): @@ -25,17 +25,17 @@ class Rmi(AbstractActionBase): def __init__(self, args): """Construct Rmi class.""" super().__init__(args) - if len(args.targets) < 1: + if not args.targets: raise ValueError('You must supply at least one image id' ' or name to be deleted.') def remove(self): """Remove image(s).""" - for id in self._args.targets: + for id_ in self._args.targets: try: - img = self.client.images.get(id) + img = self.client.images.get(id_) img.remove(self._args.force) - print(id) + print(id_) except podman.ImageNotFound as e: sys.stdout.flush() print( diff --git a/contrib/python/pypodman/pypodman/lib/config.py b/contrib/python/pypodman/pypodman/lib/config.py index 90848b567..75059fc15 100644 --- a/contrib/python/pypodman/pypodman/lib/config.py +++ b/contrib/python/pypodman/pypodman/lib/config.py @@ -6,6 +6,7 @@ import inspect import logging import os import sys +from contextlib import suppress import pkg_resources import pytoml @@ -13,7 +14,7 @@ import pytoml # TODO: setup.py and obtain __version__ from rpm.spec try: __version__ = pkg_resources.get_distribution('pypodman').version -except Exception: +except Exception: # pylint: disable=broad-except __version__ = '0.0.0' @@ -25,7 +26,7 @@ class HelpFormatter(argparse.RawDescriptionHelpFormatter): if 'width' not in kwargs: kwargs['width'] = 80 try: - height, width = curses.initscr().getmaxyx() + _, width = curses.initscr().getmaxyx() kwargs['width'] = width finally: curses.endwin() @@ -85,6 +86,10 @@ class PodmanArgumentParser(argparse.ArgumentParser): actions_parser = self.add_subparsers( dest='subparser_name', help='actions') + # import buried here to prevent import loops + import pypodman.lib.actions # pylint: disable=cyclic-import + assert pypodman.lib.actions + # pull in plugin(s) code for each subcommand for name, obj in inspect.getmembers( sys.modules['pypodman.lib.actions'], @@ -95,8 +100,7 @@ class PodmanArgumentParser(argparse.ArgumentParser): except NameError as e: logging.critical(e) logging.warning( - 'See subparser configuration for Class "{}"'.format( - name)) + 'See subparser configuration for Class "%s"', name) sys.exit(3) def parse_args(self, args=None, namespace=None): @@ -120,18 +124,17 @@ class PodmanArgumentParser(argparse.ArgumentParser): for dir_ in dirs: if dir_ is None: continue - try: + with suppress(OSError): with open(os.path.join(dir_, 'pypodman/pypodman.conf'), 'r') as stream: config.update(pytoml.load(stream)) - except OSError: - pass def reqattr(name, value): if value: setattr(args, name, value) return value - self.error('Required argument "%s" is not configured.' % name) + return self.error( + 'Required argument "{}" is not configured.'.format(name)) reqattr( 'run_dir', @@ -205,7 +208,6 @@ class PodmanArgumentParser(argparse.ArgumentParser): def error(self, message): """Capture message and route to logger.""" - logging.error('{}: {}'.format(self.prog, message)) - logging.error("Try '{} --help' for more information.".format( - self.prog)) + logging.error('%s: %s', self.prog, message) + logging.error("Try '%s --help' for more information.", self.prog) super().exit(2) diff --git a/contrib/python/pypodman/pypodman/lib/future_abstract.py b/contrib/python/pypodman/pypodman/lib/future_abstract.py deleted file mode 100644 index 79256d987..000000000 --- a/contrib/python/pypodman/pypodman/lib/future_abstract.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Utilities for with-statement contexts. See PEP 343.""" - -import abc - -try: - from contextlib import AbstractContextManager - assert AbstractContextManager -except ImportError: - class AbstractContextManager(abc.ABC): - """An abstract base class for context managers.""" - - @abc.abstractmethod - def __enter__(self): - """Return `self` upon entering the runtime context.""" - return self - - @abc.abstractmethod - def __exit__(self, exc_type, exc_value, traceback): - """Raise any exception triggered within the runtime context.""" - return None diff --git a/contrib/python/pypodman/pypodman/lib/report.py b/contrib/python/pypodman/pypodman/lib/report.py index 25fe2ae0d..0fa06f22c 100644 --- a/contrib/python/pypodman/pypodman/lib/report.py +++ b/contrib/python/pypodman/pypodman/lib/report.py @@ -2,8 +2,6 @@ import sys from collections import namedtuple -from .future_abstract import AbstractContextManager - class ReportColumn(namedtuple('ReportColumn', 'key display width default')): """Hold attributes of output column.""" @@ -16,7 +14,7 @@ class ReportColumn(namedtuple('ReportColumn', 'key display width default')): default) -class Report(AbstractContextManager): +class Report(): """Report Manager.""" def __init__(self, columns, heading=True, epilog=None, file=sys.stdout): @@ -41,6 +39,10 @@ class Report(AbstractContextManager): fields = {k: str(v) for k, v in fields.items()} print(self._format.format(**fields)) + def __enter__(self): + """Return `self` upon entering the runtime context.""" + return self + def __exit__(self, exc_type, exc_value, traceback): """Leave Report context and print epilog if provided.""" if self.epilog: @@ -48,7 +50,7 @@ class Report(AbstractContextManager): def layout(self, iterable, keys, truncate=True): """Use data and headings build format for table to fit.""" - format = [] + fmt = [] for key in keys: value = max(map(lambda x: len(str(x.get(key, ''))), iterable)) @@ -63,5 +65,5 @@ class Report(AbstractContextManager): elif value > row.width: value = row.width if row.width != 0 else value - format.append('{{{0}:{1}.{1}}}'.format(key, value)) - self._format = ' '.join(format) + fmt.append('{{{0}:{1}.{1}}}'.format(key, value)) + self._format = ' '.join(fmt) diff --git a/contrib/python/pypodman/pypodman/main.py b/contrib/python/pypodman/pypodman/main.py index 9d747f0ef..e7055d611 100755 --- a/contrib/python/pypodman/pypodman/main.py +++ b/contrib/python/pypodman/pypodman/main.py @@ -1,11 +1,9 @@ """Remote podman client.""" -from __future__ import absolute_import - import logging import os import sys -from .lib import PodmanArgumentParser +from pypodman.lib import PodmanArgumentParser def main(): @@ -24,8 +22,9 @@ def main(): args = parser.parse_args() log.setLevel(args.log_level) - logging.debug('Logging initialized at level {}'.format( - logging.getLevelName(logging.getLogger().getEffectiveLevel()))) + logging.debug( + 'Logging initialized at level %s', + logging.getLevelName(logging.getLogger().getEffectiveLevel())) def want_tb(): """Add traceback when logging events.""" @@ -42,18 +41,18 @@ def main(): returncode = None try: obj = args.class_(args) - except Exception as e: + except Exception as e: # pylint: disable=broad-except logging.critical(repr(e), exc_info=want_tb()) - logging.warning('See subparser "{}" configuration.'.format( - args.subparser_name)) + logging.warning('See subparser "%s" configuration.', + args.subparser_name) sys.exit(5) try: returncode = getattr(obj, args.method)() except AttributeError as e: logging.critical(e, exc_info=want_tb()) - logging.warning('See subparser "{}" configuration.'.format( - args.subparser_name)) + logging.warning('See subparser "%s" configuration.', + args.subparser_name) returncode = 3 except KeyboardInterrupt: pass -- cgit v1.2.3-54-g00ecf