Skip to content
Snippets Groups Projects
Unverified Commit 2f7d35dd authored by Samuel GAIST's avatar Samuel GAIST
Browse files

chore: pre-commit cleanup

parent 796e64c9
No related branches found
No related tags found
1 merge request!22fix(ruff): set to line length back to 88 as used originally
Pipeline #86320 passed
...@@ -91,9 +91,7 @@ def verbosity_option( ...@@ -91,9 +91,7 @@ def verbosity_option(
}[value] }[value]
logger.setLevel(log_level) logger.setLevel(log_level)
logger.debug( logger.debug(f'Level of Logger("{logger.name}") was set to {log_level}')
f'Level of Logger("{logger.name}") was set to {log_level}'
)
return value return value
return click.option( return click.option(
...@@ -168,9 +166,7 @@ will override the values of configuration files. You can run this command with ...@@ -168,9 +166,7 @@ will override the values of configuration files. You can run this command with
# Add the config argument to the command # Add the config argument to the command
def configs_argument_callback(ctx, param, value): def configs_argument_callback(ctx, param, value):
config_context = load( config_context = load(value, entry_point_group=self.entry_point_group)
value, entry_point_group=self.entry_point_group
)
config_context = mod_to_context(config_context) config_context = mod_to_context(config_context)
ctx.config_context = config_context ctx.config_context = config_context
...@@ -246,9 +242,7 @@ will override the values of configuration files. You can run this command with ...@@ -246,9 +242,7 @@ will override the values of configuration files. You can run this command with
f" [default: {param.default}]", f" [default: {param.default}]",
) )
config_file.write( config_file.write(f"{begin}: {param.name} ({', '.join(param.opts)}){dflt}")
f"{begin}: {param.name} ({', '.join(param.opts)}){dflt}"
)
if param.help is not None: if param.help is not None:
config_file.write(f"\n{param.help}") config_file.write(f"\n{param.help}")
...@@ -264,9 +258,7 @@ will override the values of configuration files. You can run this command with ...@@ -264,9 +258,7 @@ will override the values of configuration files. You can run this command with
config_file.write('"""\n') config_file.write('"""\n')
click.echo( click.echo(f"Configuration file `{config_file.name}' was written; exiting")
f"Configuration file `{config_file.name}' was written; exiting"
)
config_file.close() config_file.close()
ctx.exit() ctx.exit()
...@@ -356,9 +348,7 @@ class ResourceOption(click.Option): ...@@ -356,9 +348,7 @@ class ResourceOption(click.Option):
self.entry_point_group = entry_point_group self.entry_point_group = entry_point_group
if entry_point_group is not None: if entry_point_group is not None:
name, _, _ = self._parse_decls( name, _, _ = self._parse_decls(param_decls, kwargs.get("expose_value"))
param_decls, kwargs.get("expose_value")
)
help = help or "" # noqa: A001 help = help or "" # noqa: A001
help += ( # noqa: A001 help += ( # noqa: A001
f" Can be a `{entry_point_group}' entry point, a module name, or " f" Can be a `{entry_point_group}' entry point, a module name, or "
...@@ -406,9 +396,7 @@ class ResourceOption(click.Option): ...@@ -406,9 +396,7 @@ class ResourceOption(click.Option):
it used to retrieve it. it used to retrieve it.
""" """
if ( if (not hasattr(ctx, "config_context")) and self.entry_point_group is None:
not hasattr(ctx, "config_context")
) and self.entry_point_group is None:
raise TypeError( raise TypeError(
"The ResourceOption class is not meant to be used this way. " "The ResourceOption class is not meant to be used this way. "
"See package documentation for details." "See package documentation for details."
...@@ -442,9 +430,7 @@ class ResourceOption(click.Option): ...@@ -442,9 +430,7 @@ class ResourceOption(click.Option):
return value, source return value, source
def type_cast_value( def type_cast_value(self, ctx: click.Context, value: typing.Any) -> typing.Any:
self, ctx: click.Context, value: typing.Any
) -> typing.Any:
"""Convert and validate a value against the option's type. """Convert and validate a value against the option's type.
This method considers the option's ``type``, ``multiple``, and ``nargs``. This method considers the option's ``type``, ``multiple``, and ``nargs``.
...@@ -466,9 +452,7 @@ class ResourceOption(click.Option): ...@@ -466,9 +452,7 @@ class ResourceOption(click.Option):
# if the value is a string and an entry_point_group is provided, load it # if the value is a string and an entry_point_group is provided, load it
if self.entry_point_group is not None: if self.entry_point_group is not None:
while ( while isinstance(value, str) and value not in self.string_exceptions:
isinstance(value, str) and value not in self.string_exceptions
):
value = load( value = load(
[value], [value],
entry_point_group=self.entry_point_group, entry_point_group=self.entry_point_group,
...@@ -691,9 +675,7 @@ def config_group( ...@@ -691,9 +675,7 @@ def config_group(
def group_decorator( def group_decorator(
func: typing.Callable[..., typing.Any], func: typing.Callable[..., typing.Any],
) -> typing.Callable[..., typing.Any]: ) -> typing.Callable[..., typing.Any]:
@click.group( @click.group(cls=AliasedGroup, context_settings=_COMMON_CONTEXT_SETTINGS)
cls=AliasedGroup, context_settings=_COMMON_CONTEXT_SETTINGS
)
@verbosity_option(logger=logger) @verbosity_option(logger=logger)
@functools.wraps(func) @functools.wraps(func)
def group_wrapper(**kwargs): def group_wrapper(**kwargs):
...@@ -760,8 +742,7 @@ def config_group( ...@@ -760,8 +742,7 @@ def config_group(
if ":" in ep.value: # it's an object if ":" in ep.value: # it's an object
summary = ( summary = (
f"[{type(obj).__name__}] " f"[{type(obj).__name__}] {pprint.pformat(obj)}"
f"{pprint.pformat(obj)}"
) )
summary = summary.replace("\n", " ") summary = summary.replace("\n", " ")
else: # it's a whole module else: # it's a whole module
...@@ -774,9 +755,7 @@ def config_group( ...@@ -774,9 +755,7 @@ def config_group(
summary += "[undocumented]" summary += "[undocumented]"
except Exception as ex: except Exception as ex:
summary = ( summary = "(cannot be loaded; add another -v for details)"
"(cannot be loaded; add another -v for details)"
)
if (ctx.parent.params["verbose"] >= 2) or ( if (ctx.parent.params["verbose"] >= 2) or (
ctx.params["verbose"] >= 2 ctx.params["verbose"] >= 2
): ):
...@@ -875,9 +854,7 @@ def config_group( ...@@ -875,9 +854,7 @@ def config_group(
return group_decorator return group_decorator
def log_parameters( def log_parameters(logger_handle: logging.Logger, ignore: tuple[str] | None = None):
logger_handle: logging.Logger, ignore: tuple[str] | None = None
):
"""Log the click parameters with the logging module. """Log the click parameters with the logging module.
Parameters Parameters
......
...@@ -147,9 +147,7 @@ def _resolve_entry_point_or_modules( ...@@ -147,9 +147,7 @@ def _resolve_entry_point_or_modules(
object_names = [] object_names = []
for path in paths: for path in paths:
module_name = ( module_name = "user_config" # fixed module name for files with full paths
"user_config" # fixed module name for files with full paths
)
resolved_path, object_name = _object_name(path, common_name) resolved_path, object_name = _object_name(path, common_name)
# if it already points to a file, then do nothing # if it already points to a file, then do nothing
...@@ -163,10 +161,7 @@ def _resolve_entry_point_or_modules( ...@@ -163,10 +161,7 @@ def _resolve_entry_point_or_modules(
object_name = entry.attr if entry.attr else common_name object_name = entry.attr if entry.attr else common_name
resolved_path = _get_module_filename(module_name) resolved_path = _get_module_filename(module_name)
if ( if resolved_path is None or not pathlib.Path(resolved_path).is_file():
resolved_path is None
or not pathlib.Path(resolved_path).is_file()
):
raise ValueError( raise ValueError(
f"The specified entry point `{path}' pointing to module " f"The specified entry point `{path}' pointing to module "
f"`{module_name}' and resolved to `{resolved_path}' does " f"`{module_name}' and resolved to `{resolved_path}' does "
...@@ -177,10 +172,7 @@ def _resolve_entry_point_or_modules( ...@@ -177,10 +172,7 @@ def _resolve_entry_point_or_modules(
else: else:
# if we have gotten here so far then path must resolve as a module # if we have gotten here so far then path must resolve as a module
resolved_path = _get_module_filename(resolved_path) resolved_path = _get_module_filename(resolved_path)
if ( if resolved_path is None or not pathlib.Path(resolved_path).is_file():
resolved_path is None
or not pathlib.Path(resolved_path).is_file()
):
raise ValueError( raise ValueError(
f"The specified path `{path}' is not a file, a entry " f"The specified path `{path}' is not a file, a entry "
f"point name, or a known-module name" f"point name, or a known-module name"
...@@ -267,9 +259,7 @@ def load( ...@@ -267,9 +259,7 @@ def load(
ctxt.__dict__.pop("__name__", None) ctxt.__dict__.pop("__name__", None)
ctxt.__dict__.pop("__package__", None) ctxt.__dict__.pop("__package__", None)
# do not propogate __ variables # do not propogate __ variables
context = { context = {k: v for k, v in ctxt.__dict__.items() if not k.startswith("__")}
k: v for k, v in ctxt.__dict__.items() if not k.startswith("__")
}
mod.__dict__.update(context) mod.__dict__.update(context)
_LOADED_CONFIGS.append(mod) _LOADED_CONFIGS.append(mod)
ctxt = _load_context(k, mod) ctxt = _load_context(k, mod)
......
...@@ -74,8 +74,7 @@ def setup( ...@@ -74,8 +74,7 @@ def setup(
# First check that logger with a matching name or stream is not already # First check that logger with a matching name or stream is not already
# there before attaching a new one. # there before attaching a new one.
if (debug_logger_name not in handlers_installed) or ( if (debug_logger_name not in handlers_installed) or (
getattr(handlers_installed[debug_logger_name], "stream") getattr(handlers_installed[debug_logger_name], "stream") != low_level_stream
!= low_level_stream
): ):
debug_info = logging.StreamHandler(low_level_stream) debug_info = logging.StreamHandler(low_level_stream)
debug_info.setLevel(logging.DEBUG) debug_info.setLevel(logging.DEBUG)
...@@ -89,8 +88,7 @@ def setup( ...@@ -89,8 +88,7 @@ def setup(
# First check that logger with a matching name or stream is not already # First check that logger with a matching name or stream is not already
# there before attaching a new one. # there before attaching a new one.
if (error_logger_name not in handlers_installed) or ( if (error_logger_name not in handlers_installed) or (
getattr(handlers_installed[error_logger_name], "stream") getattr(handlers_installed[error_logger_name], "stream") != high_level_stream
!= high_level_stream
): ):
warn_err = logging.StreamHandler(high_level_stream) warn_err = logging.StreamHandler(high_level_stream)
warn_err.setLevel(logging.WARNING) warn_err.setLevel(logging.WARNING)
......
...@@ -69,9 +69,7 @@ class UserDefaults(collections.abc.MutableMapping): ...@@ -69,9 +69,7 @@ class UserDefaults(collections.abc.MutableMapping):
def read(self) -> None: def read(self) -> None:
"""Read configuration file, replaces any internal values.""" """Read configuration file, replaces any internal values."""
if self.path.exists(): if self.path.exists():
self.logger.debug( self.logger.debug("User configuration file exists, reading contents...")
"User configuration file exists, reading contents..."
)
self.data.clear() self.data.clear()
with self.path.open("rb") as f: with self.path.open("rb") as f:
......
...@@ -224,9 +224,7 @@ def test_config_dump2(tmp_path, datadir): ...@@ -224,9 +224,7 @@ def test_config_dump2(tmp_path, datadir):
runner = CliRunner() runner = CliRunner()
output = tmp_path / "test_dump.py" output = tmp_path / "test_dump.py"
result = runner.invoke( result = runner.invoke(test, ["test", "-H", str(output)], catch_exceptions=False)
test, ["test", "-H", str(output)], catch_exceptions=False
)
ref = datadir / "test_dump_config2.py" ref = datadir / "test_dump_config2.py"
assert result.exit_code == 0 assert result.exit_code == 0
...@@ -235,9 +233,7 @@ def test_config_dump2(tmp_path, datadir): ...@@ -235,9 +233,7 @@ def test_config_dump2(tmp_path, datadir):
def test_config_command_with_callback_options(): def test_config_command_with_callback_options():
@click.command(cls=ConfigCommand, entry_point_group="clapper.test.config") @click.command(cls=ConfigCommand, entry_point_group="clapper.test.config")
@verbosity_option( @verbosity_option(logging.getLogger(__name__), envvar="VERBOSE", cls=ResourceOption)
logging.getLogger(__name__), envvar="VERBOSE", cls=ResourceOption
)
@click.pass_context @click.pass_context
def cli(ctx, **_): def cli(ctx, **_):
verbose = ctx.meta["verbose"] verbose = ctx.meta["verbose"]
......
...@@ -57,9 +57,7 @@ def test_config_with_module(): ...@@ -57,9 +57,7 @@ def test_config_with_module():
def test_config_with_entry_point(): def test_config_with_entry_point():
c = load( c = load(["first", "second", "complex"], entry_point_group="clapper.test.config")
["first", "second", "complex"], entry_point_group="clapper.test.config"
)
assert hasattr(c, "a") and c.a == 1 assert hasattr(c, "a") and c.a == 1
assert hasattr(c, "b") and c.b == 6 assert hasattr(c, "b") and c.b == 6
assert hasattr(c, "cplx") and isinstance(c.cplx, dict) assert hasattr(c, "cplx") and isinstance(c.cplx, dict)
...@@ -173,9 +171,7 @@ def test_config_click_describe_error(cli_messages): ...@@ -173,9 +171,7 @@ def test_config_click_describe_error(cli_messages):
runner = CliRunner() runner = CliRunner()
result = runner.invoke(cli, ["describe", "not-found"]) result = runner.invoke(cli, ["describe", "not-found"])
assert result.exit_code == 0 assert result.exit_code == 0
assert ( assert "Cannot find configuration resource `not-found'" in messages.getvalue()
"Cannot find configuration resource `not-found'" in messages.getvalue()
)
def test_config_click_copy(cli_messages, datadir, tmp_path): def test_config_click_copy(cli_messages, datadir, tmp_path):
...@@ -193,7 +189,4 @@ def test_config_click_copy_error(cli_messages, datadir, tmp_path): ...@@ -193,7 +189,4 @@ def test_config_click_copy_error(cli_messages, datadir, tmp_path):
dest = tmp_path / "file.py" dest = tmp_path / "file.py"
result = runner.invoke(cli, ["copy", "firstx", str(dest)]) result = runner.invoke(cli, ["copy", "firstx", str(dest)])
assert result.exit_code == 0 assert result.exit_code == 0
assert ( assert "[ERROR] Cannot find configuration resource `firstx'" in messages.getvalue()
"[ERROR] Cannot find configuration resource `firstx'"
in messages.getvalue()
)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment