diff options
| author | Daniel Schadt <kingdread@gmx.de> | 2023-03-28 18:44:05 +0200 | 
|---|---|---|
| committer | Daniel Schadt <kingdread@gmx.de> | 2023-03-28 18:44:05 +0200 | 
| commit | 66986b73b2506395888b8a362c821f0249fd89b8 (patch) | |
| tree | 3d0a51658f86a87c3e58c9e87176aef0d06bc0f6 | |
| parent | f65e4ac358d18b1bd55f39f4f61a3975888aa51e (diff) | |
| download | fietsboek-66986b73b2506395888b8a362c821f0249fd89b8.tar.gz fietsboek-66986b73b2506395888b8a362c821f0249fd89b8.tar.bz2 fietsboek-66986b73b2506395888b8a362c821f0249fd89b8.zip  | |
cli: have a hint if fietsboek.ini is not found
| -rw-r--r-- | fietsboek/scripts/__init__.py | 36 | 
1 files changed, 35 insertions, 1 deletions
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",  | 
