Skip to content
Snippets Groups Projects
Verified Commit ec8a339b authored by Dominik Rimpf's avatar Dominik Rimpf :chipmunk:
Browse files

reformatted code

parent 7211ac98
No related branches found
No related tags found
1 merge request!1Click support and argument deprecation
......@@ -9,10 +9,28 @@ app = typer.Typer()
@app.command(context_settings={'help_option_names': ['-h', '--help'], 'max_content_width': 120})
def main(
_netdb_config: Path = typer.Option(Path('~/.config/netdb_client.ini'), '--netdb-config', help='netdb auth config file path', callback=netdb_config_callback, is_eager=True, expose_value=False),
netdb_endpoint: str = typer.Option(None, '--netdb-endpoint', envvar='NETDB_ENDPOINT', help='endpoint to use. Config: [DEFAULT]: endpoint', callback=netdb_endpoint_callback, expose_value=False),
netdb_base_url: str = typer.Option(None, '--netdb-base-url', envvar='NETDB_BASE_URL', help='webapi server. Config: [$endpoint]: base_url'),
netdb_token: str = typer.Option(None, '--netdb-token', envvar='NETDB_TOKEN', show_default=False, help='user API token. Config: [$endpoint]: token'),
_netdb_config: Path = typer.Option(
Path('~/.config/netdb_client.ini'),
'--netdb-config',
help='netdb auth config file path',
callback=netdb_config_callback,
is_eager=True,
expose_value=False,
),
netdb_endpoint: str = typer.Option(
None,
'--netdb-endpoint',
envvar='NETDB_ENDPOINT',
help='endpoint to use. Config: [DEFAULT]: endpoint',
callback=netdb_endpoint_callback,
expose_value=False,
),
netdb_base_url: str = typer.Option(
None, '--netdb-base-url', envvar='NETDB_BASE_URL', help='webapi server. Config: [$endpoint]: base_url'
),
netdb_token: str = typer.Option(
None, '--netdb-token', envvar='NETDB_TOKEN', show_default=False, help='user API token. Config: [$endpoint]: token'
),
):
netdb_enpoint = APIEndpoint(base_url=netdb_base_url, token=netdb_token)
netdb_api = APISession(netdb_enpoint)
......@@ -22,5 +40,5 @@ def main(
print(fqdn)
if __name__ == "__main__":
if __name__ == '__main__':
app()
"""netdb_client helper functions for configuration and response-parsing"""
from .argparse import ArgumentParser # for backwards compatibility
__all__ = ['ArgumentParser', 'list_to_generator_map_one2one', 'list_to_generator_map_one2many']
......@@ -12,7 +13,7 @@ def list_to_generator_map_one2one(array, key_name):
def list_to_generator_map_one2many(array, key_name):
"""Mapping function to convert list of dicts to a mapping with values as key for each lists
(1 to n Mapping). Returns a generator object."""
(1 to n Mapping). Returns a generator object."""
res = {}
for item in array:
if item[key_name] not in res:
......
"""Argparse Wrapper Class for automatic config loading"""
import argparse
import os
import sys
......@@ -6,6 +7,7 @@ from pathlib import Path
from .config import NETDBConfig, NETDBConfigError
class DeprecateAction(argparse.Action):
def __init__(self, *args, **kwargs):
self.call_count = 0
......@@ -13,54 +15,45 @@ class DeprecateAction(argparse.Action):
kwargs['help'] = f'[DEPRECATED] {kwargs["help"]}'
super().__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if self.call_count == 0:
sys.stderr.write(f"The option `{option_string}` is deprecated. Help:\n")
sys.stderr.write(f"{self.help}\n")
sys.stderr.write(f'The option `{option_string}` is deprecated. Help:\n')
sys.stderr.write(f'{self.help}\n')
sys.exit(1)
class ArgumentParser(argparse.ArgumentParser):
"""Argument parser with default common arguments for NetDB-api cli
tools. Includes default values."""
def __init__(
self,
epilog="The Variables BASE_URL, VERSION and TOKEN can be loaded from config file,"
"environment or from command line arguments.\n"
"Variable precendence is as followed (from greatest to least,"
"means the first listed variable overwrites all other variables):\n"
" 1. cli-arguments\n"
" 2. environment variables\n"
" 3. config-file\n",
formatter_class=argparse.RawTextHelpFormatter,
**kwargs
self,
epilog='The Variables BASE_URL, VERSION and TOKEN can be loaded from config file,'
'environment or from command line arguments.\n'
'Variable precendence is as followed (from greatest to least,'
'means the first listed variable overwrites all other variables):\n'
' 1. cli-arguments\n'
' 2. environment variables\n'
' 3. config-file\n',
formatter_class=argparse.RawTextHelpFormatter,
**kwargs,
):
super().__init__(formatter_class=formatter_class, epilog=epilog, **kwargs)
self.register('action', 'deprecated', DeprecateAction)
self.add_argument('--auth-config', action='deprecated',
help='please use --netdb-config instead')
self.add_argument('--endpoint', '-e', action='deprecated',
help='please use --netdb-enpoint instead')
self.add_argument('--base-url', '-b', action='deprecated',
help='please use --netdb-base-url instead')
self.add_argument('--token', '-t', action='deprecated',
help='please use --netdb-token instead')
self.add_argument('--netdb-config',
default='~/.config/netdb_client.ini',
help='config file path (default: %(default)s)')
self.add_argument('--netdb-endpoint',
help='endpoint to use.\n'
'Environment: "NETDB_ENDPOINT"\n'
'Config: [DEFAULT]: endpoint')
self.add_argument('--netdb-base-url',
help='webapi server.\n'
'Environment: "NETDB_BASE_URL"\n'
'Config: [$endpoint]: base_url')
self.add_argument('--netdb-token',
help='user API token.\n'
'Environment: "NETDB_TOKEN"\n'
'Config: [$endpoint]: token')
self.add_argument('--auth-config', action='deprecated', help='please use --netdb-config instead')
self.add_argument('--endpoint', '-e', action='deprecated', help='please use --netdb-enpoint instead')
self.add_argument('--base-url', '-b', action='deprecated', help='please use --netdb-base-url instead')
self.add_argument('--token', '-t', action='deprecated', help='please use --netdb-token instead')
self.add_argument(
'--netdb-config', default='~/.config/netdb_client.ini', help='config file path (default: %(default)s)'
)
self.add_argument(
'--netdb-endpoint', help='endpoint to use.\n' 'Environment: "NETDB_ENDPOINT"\n' 'Config: [DEFAULT]: endpoint'
)
self.add_argument(
'--netdb-base-url', help='webapi server.\n' 'Environment: "NETDB_BASE_URL"\n' 'Config: [$endpoint]: base_url'
)
self.add_argument('--netdb-token', help='user API token.\n' 'Environment: "NETDB_TOKEN"\n' 'Config: [$endpoint]: token')
def parse_args(self, args=None, namespace=None):
args = super().parse_args(args, namespace)
......@@ -91,7 +84,8 @@ class ArgumentParser(argparse.ArgumentParser):
if value is None:
self.error(
f'No {option_name} specified (looked in args, environment variable '
f'"{envvar_name}", config-file in "{args.netdb_config} section {args.netdb_endpoint}")')
f'"{envvar_name}", config-file in "{args.netdb_config} section {args.netdb_endpoint}")'
)
# we have a value now and can use it
setattr(args, option, value)
......
"""click framework helper functions for config loading"""
import types
from pathlib import Path
from pprint import pprint
from typing import Optional
import click
......@@ -111,10 +111,7 @@ def netdb_api_options(client_lib_module: types.ModuleType, target: str = 'netdb_
@netdb_base_url_option()
@netdb_token_option()
def _decorator(*args, **kwargs):
api_endpoint = client_lib_module.APIEndpoint(
base_url=kwargs.pop('netdb_base_url'),
token=kwargs.pop('netdb_token')
)
api_endpoint = client_lib_module.APIEndpoint(base_url=kwargs.pop('netdb_base_url'), token=kwargs.pop('netdb_token'))
kwargs[target] = api_endpoint
return func(*args, **kwargs)
......
......@@ -12,7 +12,9 @@ class NETDBConfig:
config_path_expanded = config_path.expanduser()
if config_path_expanded.is_file():
if config_path_expanded.stat().st_mode & stat.S_IRWXO:
raise NETDBConfigError('Config file is readable by others. Please set it at least to 600 but never other-readable.')
raise NETDBConfigError(
'Config file is readable by others. Please set it at least to 600 but never other-readable.'
)
self.config.read(config_path_expanded)
self.default_endpoint = self.config.get('DEFAULT', 'endpoint', fallback=None)
......@@ -40,4 +42,4 @@ class NETDBConfig:
if token is None:
raise NETDBConfigError('No token was provided')
return token
\ No newline at end of file
return token
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment