Skip to content

Commit

Permalink
Require Python 3.6, use f-strings (#480)
Browse files Browse the repository at this point in the history
  • Loading branch information
cottsay authored Mar 31, 2022
1 parent d8e455e commit 15fdd96
Show file tree
Hide file tree
Showing 49 changed files with 215 additions and 302 deletions.
3 changes: 1 addition & 2 deletions bin/colcon
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ custom_entry_points = {}
def custom_load_entry_points(group_name, *, exclude_names=None): # noqa: D103
global custom_entry_points
assert group_name in custom_entry_points, \
"get_entry_points() not overridden for group '{group_name}'" \
.format_map(locals())
f"get_entry_points() not overridden for group '{group_name}'"
return {
k: v for k, v in custom_entry_points[group_name].items()
if exclude_names is None or k not in exclude_names}
Expand Down
3 changes: 1 addition & 2 deletions colcon_core/argument_parser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ def decorate_argument_parser(parser):
exc = traceback.format_exc()
logger.error(
'Exception in argument parser decorator extension '
"'{extension.ARGUMENT_PARSER_DECORATOR_NAME}': {e}\n{exc}"
.format_map(locals()))
f"'{extension.ARGUMENT_PARSER_DECORATOR_NAME}': {e}\n{exc}")
# skip failing extension, continue with next one
else:
parser = decorated_parser
Expand Down
49 changes: 20 additions & 29 deletions colcon_core/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@
category = warnings._getcategory(category)
except Exception: # noqa: B902
print(
"The category field '{category}' must be a valid warnings "
'class name'.format_map(locals()), file=sys.stderr)
f"The category field '{category}' must be a valid warnings "
'class name', file=sys.stderr)
sys.exit(1)
if module:
print(
'The module field of the {WARNINGS_ENVIRONMENT_VARIABLE.name} '
'filter should be empty, otherwise use PYTHONWARNINGS instead'
.format_map(locals()), file=sys.stderr)
'The module field of the '
f'{WARNINGS_ENVIRONMENT_VARIABLE.name} filter should be '
'empty, otherwise use PYTHONWARNINGS instead', file=sys.stderr)
sys.exit(1)
warnings.filterwarnings(
action, message=message, category=category or Warning,
Expand Down Expand Up @@ -130,16 +130,15 @@ def _main(*, command_name, argv):
# default log level, for searchability: COLCON_LOG_LEVEL
colcon_logger.setLevel(logging.WARNING)
set_logger_level_from_env(
colcon_logger, '{command_name}_LOG_LEVEL'.format_map(locals()).upper())
colcon_logger, f'{command_name}_LOG_LEVEL'.upper())
colcon_logger.debug(
'Command line arguments: {argv}'
.format(argv=argv if argv is not None else sys.argv))

# set default locations for config files, for searchability: COLCON_HOME
set_default_config_path(
path=(
Path('~') / '.{command_name}'.format_map(locals())).expanduser(),
env_var='{command_name}_HOME'.format_map(locals()).upper())
path=(Path('~') / f'.{command_name}').expanduser(),
env_var=f'{command_name}_HOME'.upper())

parser = create_parser('colcon_core.environment_variable')

Expand All @@ -165,8 +164,7 @@ def _main(*, command_name, argv):
# the value might be provided externally and needs to be checked again
colcon_logger.setLevel(get_numeric_log_level(args.log_level))

colcon_logger.debug(
'Parsed command line arguments: {args}'.format_map(locals()))
colcon_logger.debug(f'Parsed command line arguments: {args}')

# error: no verb provided
if args.verb_name is None:
Expand All @@ -178,8 +176,8 @@ def _main(*, command_name, argv):
now_str = str(now)[:-7].replace(' ', '_').replace(':', '-')
set_default_log_path(
base_path=args.log_base,
env_var='{command_name}_LOG_PATH'.format_map(locals()).upper(),
subdirectory='{args.verb_name}_{now_str}'.format_map(locals()))
env_var=f'{command_name}_LOG_PATH'.upper(),
subdirectory=f'{args.verb_name}_{now_str}')

# add a file handler writing all levels if logging isn't disabled
log_path = get_log_path()
Expand All @@ -196,8 +194,7 @@ def _main(*, command_name, argv):
handler.handle(log_record)
log_record = colcon_logger.makeRecord(
colcon_logger.name, logging.DEBUG, __file__, 0,
'Parsed command line arguments: {args}'.format_map(locals()),
None, None)
f'Parsed command line arguments: {args}', None, None)
handler.handle(log_record)

# set an environment variable named after the command (if not already set)
Expand Down Expand Up @@ -311,7 +308,7 @@ def add_log_level_argument(parser):
parser.add_argument(
'--log-base',
help='The base path for all log directories (default: ./log, to '
'disable: {os.devnull})'.format_map(globals()))
f'disable: {os.devnull})')
parser.add_argument(
'--log-level', action=LogLevelAction,
help='Set log level for the console output, either by numeric or '
Expand All @@ -332,9 +329,7 @@ def __call__(self, parser, namespace, values, option_string=None):
try:
value = get_numeric_log_level(values)
except ValueError as e: # noqa: F841
parser.error(
'{option_string} has unsupported value, {e}'
.format_map(locals()))
parser.error(f'{option_string} has unsupported value, {e}')
setattr(namespace, self.dest, value)


Expand Down Expand Up @@ -391,11 +386,10 @@ def create_subparser(parser, cmd_name, verb_extensions, *, attribute):

# add subparser with description of verb extensions
subparser = parser.add_subparsers(
title='{cmd_name} verbs'.format_map(locals()),
title=f'{cmd_name} verbs',
description='\n'.join(verbs),
dest=attribute,
help='call `{cmd_name} VERB -h` for specific help'
.format_map(locals())
help=f'call `{cmd_name} VERB -h` for specific help',
)
return subparser

Expand Down Expand Up @@ -445,8 +439,8 @@ def add_parser_arguments(verb_parser, extension):
retval = extension.add_arguments(parser=verb_parser)
if retval is not None:
colcon_logger.error(
"Exception in verb extension '{extension.VERB_NAME}': "
'add_arguments() should return None'.format_map(locals()))
f"Exception in verb extension '{extension.VERB_NAME}': "
'add_arguments() should return None')


def _format_pair(key, value, *, indent, align):
Expand Down Expand Up @@ -528,15 +522,12 @@ def verb_main(context, logger):
rc = context.args.main(context=context)
except RuntimeError as e: # noqa: F841
# only log the error message for "known" exceptions
logger.error(
'{context.command_name} {context.args.verb_name}: {e}'
.format_map(locals()))
logger.error(f'{context.command_name} {context.args.verb_name}: {e}')
return 1
except Exception as e: # noqa: F841
# log the error message and a traceback for "unexpected" exceptions
exc = traceback.format_exc()
logger.error(
'{context.command_name} {context.args.verb_name}: {e}\n{exc}'
.format_map(locals()))
f'{context.command_name} {context.args.verb_name}: {e}\n{exc}')
return 1
return rc
22 changes: 10 additions & 12 deletions colcon_core/entry_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ def get_all_entry_points():
if entry_point_name in entry_points[group_name]:
previous = entry_points[group_name][entry_point_name]
logger.error(
"Entry point '{group_name}.{entry_point_name}' is "
"declared multiple times, '{entry_point}' overwriting "
"'{previous}'".format_map(locals()))
f"Entry point '{group_name}.{entry_point_name}' is "
f"declared multiple times, '{entry_point}' "
f"overwriting '{previous}'")
entry_points[group_name][entry_point_name] = \
(dist, entry_point)
return entry_points
Expand All @@ -96,9 +96,9 @@ def get_entry_points(group_name):
if entry_point.name in entry_points:
previous_entry_point = entry_points[entry_point.name]
logger.error(
"Entry point '{group_name}.{entry_point.name}' is declared "
"multiple times, '{entry_point}' overwriting "
"'{previous_entry_point}'".format_map(locals()))
f"Entry point '{group_name}.{entry_point.name}' is declared "
f"multiple times, '{entry_point}' overwriting "
f"'{previous_entry_point}'")
entry_points[entry_point.name] = entry_point
return entry_points

Expand All @@ -125,8 +125,7 @@ def load_entry_points(group_name, *, exclude_names=None):
exc = traceback.format_exc()
logger.error(
'Exception loading extension '
"'{group_name}.{entry_point.name}': {e}\n{exc}"
.format_map(locals()))
f"'{group_name}.{entry_point.name}': {e}\n{exc}")
# skip failing entry point, continue with next one
continue
extension_types[entry_point.name] = extension_type
Expand Down Expand Up @@ -158,11 +157,10 @@ def load_entry_point(entry_point):
if entry_point.group_name in blocklist:
raise RuntimeError(
'The entry point group name is listed in the environment '
"variable '{env_var_name}'".format_map(locals()))
full_name = '{entry_point.group_name}.{entry_point.name}' \
.format_map(locals())
f"variable '{env_var_name}'")
full_name = f'{entry_point.group_name}.{entry_point.name}'
if full_name in blocklist:
raise RuntimeError(
'The entry point name is listed in the environment variable '
"'{env_var_name}'".format_map(locals()))
f"'{env_var_name}'")
return entry_point.load()
7 changes: 3 additions & 4 deletions colcon_core/environment/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ def create_environment_scripts_only(
# catch exceptions raised in shell extension
exc = traceback.format_exc()
logger.error(
"Exception in shell extension '{extension.SHELL_NAME}': "
'{e}\n{exc}'.format_map(locals()))
f"Exception in shell extension '{extension.SHELL_NAME}': "
f'{e}\n{exc}')
# skip failing extension, continue with next one


Expand Down Expand Up @@ -180,8 +180,7 @@ def create_environment_hooks(prefix_path, pkg_name):
exc = traceback.format_exc()
logger.error(
'Exception in environment extension '
"'{extension.ENVIRONMENT_NAME}': {e}\n{exc}"
.format_map(locals()))
f"'{extension.ENVIRONMENT_NAME}': {e}\n{exc}")
# skip failing extension, continue with next one
continue
all_hooks += hooks
Expand Down
8 changes: 4 additions & 4 deletions colcon_core/event/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def to_string(self):
The message includes the working directory, modifications to
environment variable and the command including the arguments.
"""
string = "Invoking command in '{self.cwd}': ".format_map(locals())
string = f"Invoking command in '{self.cwd}': "
string += self._get_env_string()
string += self._get_cmd_string()
return string
Expand Down Expand Up @@ -77,7 +77,7 @@ def _get_env_string(self):
if env:
for name in sorted(env.keys()):
value = env[name]
string += '{name}={value} '.format_map(locals())
string += f'{name}={value} '
return string

def _get_cmd_string(self):
Expand Down Expand Up @@ -106,8 +106,8 @@ def __init__(self, cmd, *, cwd, returncode, env=None, shell=False):

def to_string(self):
"""Get a string describing the invoked command and its return code."""
string = "Invoked command in '{self.cwd}' returned " \
"'{self.returncode}': ".format_map(locals())
string = f"Invoked command in '{self.cwd}' returned " \
f"'{self.returncode}': "
string += self._get_env_string()
string += self._get_cmd_string()
return string
13 changes: 6 additions & 7 deletions colcon_core/event_handler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def add_event_handler_arguments(parser):
# since they are already listed in the defaults
if desc:
# it requires a custom formatter to maintain the newline
descriptions += '\n* {key}: {desc}'.format_map(locals())
descriptions += f'\n* {key}: {desc}'

argument = group.add_argument(
'--event-handlers',
Expand Down Expand Up @@ -125,8 +125,7 @@ def format_duration(seconds, *, fixed_decimal_points=None):
"""
if seconds < 0.0:
raise ValueError(
"The duration '{seconds}' must be a non-negative number"
.format_map(locals()))
f"The duration '{seconds}' must be a non-negative number")
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)

Expand Down Expand Up @@ -154,9 +153,9 @@ def format_duration(seconds, *, fixed_decimal_points=None):
minutes = 0.0
hours += 1

format_string = '{seconds:.%sf}s' % decimal_points
format_string = f'{seconds:.{decimal_points}f}s'
if hours or minutes:
format_string = '{minutes:.0f}min ' + format_string
format_string = f'{minutes:.0f}min ' + format_string
if hours:
format_string = '{hours:.0f}h ' + format_string
return format_string.format_map(locals())
format_string = f'{hours:.0f}h ' + format_string
return format_string
15 changes: 5 additions & 10 deletions colcon_core/event_handler/console_start_end.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ def __call__(self, event): # noqa: D102
data = event[0]

if isinstance(data, JobStarted):
print(
'Starting >>> {data.identifier}'.format_map(locals()),
flush=True)
print(f'Starting >>> {data.identifier}', flush=True)
self._start_times[data.identifier] = time.monotonic()

elif isinstance(data, TestFailure):
Expand All @@ -48,22 +46,19 @@ def __call__(self, event): # noqa: D102
time.monotonic() - self._start_times[data.identifier]
duration_string = format_duration(duration)
if not data.rc:
msg = 'Finished <<< {data.identifier} [{duration_string}]' \
.format_map(locals())
msg = f'Finished <<< {data.identifier} [{duration_string}]'
job = event[1]
if job in self._with_test_failures:
msg += '\t[ with test failures ]'
writable = sys.stdout

elif data.rc == SIGINT_RESULT:
msg = 'Aborted <<< {data.identifier} [{duration_string}]' \
.format_map(locals())
msg = f'Aborted <<< {data.identifier} [{duration_string}]'
writable = sys.stdout

else:
msg = 'Failed <<< {data.identifier} ' \
'[{duration_string}, exited with code {data.rc}]' \
.format_map(locals())
msg = f'Failed <<< {data.identifier} ' \
f'[{duration_string}, exited with code {data.rc}]'
writable = sys.stderr

print(msg, file=writable, flush=True)
3 changes: 1 addition & 2 deletions colcon_core/event_reactor.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ def _notify_observers(self, event):
except Exception as e: # noqa: F841
# catch exceptions raised in event handler extension
msg = 'Exception in event handler extension ' \
"'{observer.EVENT_HANDLER_NAME}': {e}" \
.format_map(locals())
f"'{observer.EVENT_HANDLER_NAME}': {e}"
if not isinstance(e, RuntimeError):
msg += '\n' + traceback.format_exc()
logger.error(msg)
Expand Down
18 changes: 8 additions & 10 deletions colcon_core/executor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def add_executor_arguments(parser):
# to mention the available options
desc = '<no description>'
# it requires a custom formatter to maintain the newline
descriptions += '\n* {key}: {desc}'.format_map(locals())
descriptions += f'\n* {key}: {desc}'
assert keys, 'No executor extensions found'

default = os.environ.get(DEFAULT_EXECUTOR_ENVIRONMENT_VARIABLE.name)
Expand All @@ -243,8 +243,8 @@ def add_executor_arguments(parser):

group.add_argument(
'--executor', type=str, choices=keys, default=default,
help='The executor to process all packages (default: {default})'
'{descriptions}'.format_map(locals()))
help=f'The executor to process all packages (default: {default})'
f'{descriptions}')

for priority in extensions.keys():
extensions_same_prio = extensions[priority]
Expand All @@ -257,8 +257,7 @@ def add_executor_arguments(parser):
exc = traceback.format_exc()
logger.error(
'Exception in executor extension '
"'{extension.EXECUTOR_NAME}': {e}\n{exc}"
.format_map(locals()))
f"'{extension.EXECUTOR_NAME}': {e}\n{exc}")
# skip failing extension, continue with next one


Expand Down Expand Up @@ -325,9 +324,8 @@ def execute_jobs(
# fallback to legacy API
assert 'abort_on_error' in signature.parameters
warnings.warn(
"The ExecutorExtensionPoint '{executor.EXECUTOR_NAME}' uses a "
"deprecated signature for the 'execute' method"
.format_map(locals()))
f"The ExecutorExtensionPoint '{executor.EXECUTOR_NAME}' uses "
"a deprecated signature for the 'execute' method")
kwargs['abort_on_error'] = on_error == OnError.interrupt

try:
Expand All @@ -336,8 +334,8 @@ def execute_jobs(
# catch exceptions raised in executor extension
exc = traceback.format_exc()
logger.error(
"Exception in executor extension '{executor.EXECUTOR_NAME}': "
'{e}\n{exc}'.format_map(locals()))
f"Exception in executor extension '{executor.EXECUTOR_NAME}': "
f'{e}\n{exc}')
rc = 1
finally:
# generate an event for every skipped job
Expand Down
Loading

0 comments on commit 15fdd96

Please sign in to comment.