Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up python2 style code #7294

Merged
merged 2 commits into from
Aug 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,9 @@
language_version: 'python3.7'
args:
- --py3-plus
- repo: https://github.com/asottile/pyupgrade
rev: v2.1.0
hooks:
- id: pyupgrade
args:
- --py3-plus
1 change: 0 additions & 1 deletion compose/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@

__version__ = '1.27.0dev'
8 changes: 4 additions & 4 deletions compose/cli/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@

def get_pairs():
for i, name in enumerate(NAMES):
yield(name, str(30 + i))
yield('intense_' + name, str(30 + i) + ';1')
yield (name, str(30 + i))
yield ('intense_' + name, str(30 + i) + ';1')


def ansi(code):
return '\033[{0}m'.format(code)
return '\033[{}m'.format(code)


def ansi_color(code, s):
return '{0}{1}{2}'.format(ansi(code), s, ansi(0))
return '{}{}{}'.format(ansi(code), s, ansi(0))


def make_color_fn(code):
Expand Down
13 changes: 8 additions & 5 deletions compose/cli/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,15 +147,17 @@ def get_project(project_dir, config_path=None, project_name=None, verbose=False,

def execution_context_labels(config_details, environment_file):
extra_labels = [
'{0}={1}'.format(LABEL_WORKING_DIR, os.path.abspath(config_details.working_dir))
'{}={}'.format(LABEL_WORKING_DIR, os.path.abspath(config_details.working_dir))
]

if not use_config_from_stdin(config_details):
extra_labels.append('{0}={1}'.format(LABEL_CONFIG_FILES, config_files_label(config_details)))
extra_labels.append('{}={}'.format(LABEL_CONFIG_FILES, config_files_label(config_details)))

if environment_file is not None:
extra_labels.append('{0}={1}'.format(LABEL_ENVIRONMENT_FILE,
os.path.normpath(environment_file)))
extra_labels.append('{}={}'.format(
LABEL_ENVIRONMENT_FILE,
os.path.normpath(environment_file))
)
return extra_labels


Expand All @@ -168,7 +170,8 @@ def use_config_from_stdin(config_details):

def config_files_label(config_details):
return ",".join(
map(str, (os.path.normpath(c.filename) for c in config_details.config_files)))
os.path.normpath(c.filename) for c in config_details.config_files
)


def get_project_name(working_dir, project_name=None, environment=None):
Expand Down
4 changes: 2 additions & 2 deletions compose/cli/docopt_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def docopt_full_help(docstring, *args, **kwargs):
raise SystemExit(docstring)


class DocoptDispatcher(object):
class DocoptDispatcher:

def __init__(self, command_class, options):
self.command_class = command_class
Expand Down Expand Up @@ -50,7 +50,7 @@ def get_handler(command_class, command):

class NoSuchCommand(Exception):
def __init__(self, command, supercommand):
super(NoSuchCommand, self).__init__("No such command: %s" % command)
super().__init__("No such command: %s" % command)

self.command = command
self.supercommand = supercommand
4 changes: 1 addition & 3 deletions compose/cli/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,9 @@ class UserError(Exception):
def __init__(self, msg):
self.msg = dedent(msg).strip()

def __unicode__(self):
def __str__(self):
return self.msg

__str__ = __unicode__


class ConnectionError(Exception):
pass
Expand Down
17 changes: 6 additions & 11 deletions compose/cli/formatter.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import logging
import shutil
from shutil import get_terminal_size

import texttable

from compose.cli import colors

if hasattr(shutil, "get_terminal_size"):
from shutil import get_terminal_size
else:
from backports.shutil_get_terminal_size import get_terminal_size


def get_tty_width():
try:
Expand Down Expand Up @@ -45,15 +40,15 @@ class ConsoleWarningFormatter(logging.Formatter):

def get_level_message(self, record):
separator = ': '
if record.levelno == logging.WARNING:
return colors.yellow(record.levelname) + separator
if record.levelno == logging.ERROR:
if record.levelno >= logging.ERROR:
return colors.red(record.levelname) + separator
if record.levelno >= logging.WARNING:
return colors.yellow(record.levelname) + separator

return ''

def format(self, record):
if isinstance(record.msg, bytes):
record.msg = record.msg.decode('utf-8')
message = super(ConsoleWarningFormatter, self).format(record)
return '{0}{1}'.format(self.get_level_message(record), message)
message = super().format(record)
return '{}{}'.format(self.get_level_message(record), message)
11 changes: 6 additions & 5 deletions compose/cli/log_printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys
from collections import namedtuple
from itertools import cycle
from operator import attrgetter
from queue import Empty
from queue import Queue
from threading import Thread
Expand All @@ -13,7 +14,7 @@
from compose.utils import split_buffer


class LogPresenter(object):
class LogPresenter:

def __init__(self, prefix_width, color_func):
self.prefix_width = prefix_width
Expand Down Expand Up @@ -50,7 +51,7 @@ def max_name_width(service_names, max_index_width=3):
return max(len(name) for name in service_names) + max_index_width


class LogPrinter(object):
class LogPrinter:
"""Print logs from many containers to a single output stream."""

def __init__(self,
Expand Down Expand Up @@ -133,7 +134,7 @@ def build_thread_map(initial_containers, presenters, thread_args):
# Container order is unspecified, so they are sorted by name in order to make
# container:presenter (log color) assignment deterministic when given a list of containers
# with the same names.
for container in sorted(initial_containers, key=lambda c: c.name)
for container in sorted(initial_containers, key=attrgetter('name'))
}


Expand Down Expand Up @@ -194,9 +195,9 @@ def build_log_generator(container, log_args):
def wait_on_exit(container):
try:
exit_code = container.wait()
return "%s exited with code %s\n" % (container.name, exit_code)
return "{} exited with code {}\n".format(container.name, exit_code)
except APIError as e:
return "Unexpected API error for %s (HTTP code %s)\nResponse body:\n%s\n" % (
return "Unexpected API error for {} (HTTP code {})\nResponse body:\n{}\n".format(
container.name, e.response.status_code,
e.response.text or '[empty]'
)
Expand Down
13 changes: 5 additions & 8 deletions compose/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def main():
log.error(e.msg)
sys.exit(1)
except BuildError as e:
log.error("Service '%s' failed to build: %s" % (e.service.name, e.reason))
log.error("Service '{}' failed to build: {}".format(e.service.name, e.reason))
sys.exit(1)
except StreamOutputError as e:
log.error(e)
Expand Down Expand Up @@ -175,7 +175,7 @@ def parse_doc_section(name, source):
return [s.strip() for s in pattern.findall(source)]


class TopLevelCommand(object):
class TopLevelCommand:
"""Define and run multi-container applications with Docker.

Usage:
Expand Down Expand Up @@ -546,7 +546,7 @@ def images(self, options):
key=attrgetter('name'))

if options['--quiet']:
for image in set(c.image for c in containers):
for image in {c.image for c in containers}:
print(image.split(':')[1])
return

Expand Down Expand Up @@ -1130,7 +1130,7 @@ def compute_service_exit_code(exit_value_from, attached_containers):
attached_containers))
if not candidates:
log.error(
'No containers matching the spec "{0}" '
'No containers matching the spec "{}" '
'were run.'.format(exit_value_from)
)
return 2
Expand Down Expand Up @@ -1453,10 +1453,7 @@ def call_docker(args, dockeropts, environment):
args = [executable_path] + tls_options + args
log.debug(" ".join(map(pipes.quote, args)))

filtered_env = {}
for k, v in environment.items():
if v is not None:
filtered_env[k] = environment[k]
filtered_env = {k: v for k, v in environment.items() if v is not None}

return subprocess.call(args, env=filtered_env)

Expand Down
13 changes: 3 additions & 10 deletions compose/cli/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,6 @@
import compose
from ..const import IS_WINDOWS_PLATFORM

# WindowsError is not defined on non-win32 platforms. Avoid runtime errors by
# defining it as OSError (its parent class) if missing.
try:
WindowsError
except NameError:
WindowsError = OSError


def yesno(prompt, default=None):
"""
Expand Down Expand Up @@ -58,7 +51,7 @@ def call_silently(*args, **kwargs):
with open(os.devnull, 'w') as shutup:
try:
return subprocess.call(*args, stdout=shutup, stderr=shutup, **kwargs)
except WindowsError:
except OSError:
# On Windows, subprocess.call() can still raise exceptions. Normalize
# to POSIXy behaviour by returning a nonzero exit code.
return 1
Expand Down Expand Up @@ -120,7 +113,7 @@ def generate_user_agent():
try:
p_system = platform.system()
p_release = platform.release()
except IOError:
except OSError:
pass
else:
parts.append("{}/{}".format(p_system, p_release))
Expand All @@ -133,7 +126,7 @@ def human_readable_file_size(size):
if order >= len(suffixes):
order = len(suffixes) - 1

return '{0:.4g} {1}'.format(
return '{:.4g} {}'.format(
size / pow(10, order * 3),
suffixes[order]
)
Expand Down
8 changes: 4 additions & 4 deletions compose/cli/verbose_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@

def format_call(args, kwargs):
args = (repr(a) for a in args)
kwargs = ("{0!s}={1!r}".format(*item) for item in kwargs.items())
return "({0})".format(", ".join(chain(args, kwargs)))
kwargs = ("{!s}={!r}".format(*item) for item in kwargs.items())
return "({})".format(", ".join(chain(args, kwargs)))


def format_return(result, max_lines):
if isinstance(result, (list, tuple, set)):
return "({0} with {1} items)".format(type(result).__name__, len(result))
return "({} with {} items)".format(type(result).__name__, len(result))

if result:
lines = pprint.pformat(result).split('\n')
Expand All @@ -22,7 +22,7 @@ def format_return(result, max_lines):
return result


class VerboseProxy(object):
class VerboseProxy:
"""Proxy all function calls to another class and log method name, arguments
and return values for each call.
"""
Expand Down
Loading