From 66986b73b2506395888b8a362c821f0249fd89b8 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Tue, 28 Mar 2023 18:44:05 +0200 Subject: cli: have a hint if fietsboek.ini is not found --- fietsboek/scripts/__init__.py | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/fietsboek/scripts/__init__.py b/fietsboek/scripts/__init__.py index c7bbe98..b8a883a 100644 --- a/fietsboek/scripts/__init__.py +++ b/fietsboek/scripts/__init__.py @@ -1,5 +1,39 @@ """Various command line scripts to interact with the fietsboek installation.""" +from typing import Any, Optional + import click +from click.core import ParameterSource + + +class ConfigOption(click.Path): + """Special :class:`~click.Path` subclass to print a more helpful error + message. + + This class recognizes if the config option is not given and prints a hint + if the file does not exist in this case. + """ + + def __init__(self): + super().__init__(exists=True, dir_okay=False) + + def convert( + self, + value: Any, + param: Optional[click.Parameter], + ctx: Optional[click.Context], + ) -> Any: + try: + return super().convert(value, param, ctx) + except click.BadParameter as exc: + if param is not None and param.name is not None and ctx is not None: + source = ctx.get_parameter_source(param.name) + if source == ParameterSource.DEFAULT: + exc.message += ( + f"\n\nHint: {value!r} is the default, " + "try specifying a configuration file explicitely." + ) + raise exc + # We keep this as a separate option that is added to each subcommand as Click # (unlike argparse) cannot handle "--help" without the required arguments of @@ -10,7 +44,7 @@ import click config_option = click.option( "-c", "--config", - type=click.Path(exists=True, dir_okay=False), + type=ConfigOption(), required=True, default="fietsboek.ini", help="Path to the Fietsboek configuration file", -- cgit v1.2.3