util.py 3.62 KB
Newer Older
1
"""netdb_client helper functions for configuration and response-parsing"""
janis.streib's avatar
janis.streib committed
2
import argparse
3
4
import configparser
import os
janis.streib's avatar
janis.streib committed
5
6
7
8
9


class ArgumentParser(argparse.ArgumentParser):
    """Argument parser with default common arguments for NetDB-api cli
    tools. Includes default values."""
10
11
12
13
14
15
16
17
18
19
20
21
22

    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
    ):
nk2202's avatar
nk2202 committed
23
24
        super().__init__(formatter_class=formatter_class, epilog=epilog, **kwargs)
        self.add_argument('--auth-config',
25
26
27
28
29
30
31
32
33
34
                          default=os.path.expanduser('~/.config/netdb_client.ini'),
                          help='config file path (default: %(default)s)')
        self.add_argument('--base-url', '-b',
                          help='webapi server.\n'
                               'Environment: "NETDB_BASE_URL"\n'
                               'Config: [DEFAULT]: endpoint')
        self.add_argument('--version',
                          help='webapi version.\n'
                               'Environment: "NETDB_VERSION"\n'
                               'Config: [$endpoint]: version')
janis.streib's avatar
janis.streib committed
35
        self.add_argument('--token', '-t',
36
37
38
                          help='user API token.\n'
                               'Environment: "NETDB_TOKEN"\n'
                               'Config: [$endpoint]: token')
janis.streib's avatar
janis.streib committed
39

uydwj's avatar
uydwj committed
40
    def parse_args(self, args=None, namespace=None):
41
42
        args = super().parse_args(args, namespace)
        config = configparser.ConfigParser()
nk2202's avatar
nk2202 committed
43
44
        if os.path.isfile(os.path.expanduser(args.auth_config)):
            config.read(os.path.expanduser(args.auth_config))
45
46
47
48
49
50
51
52
53
54
55
56

        def load_configoption(option):
            if getattr(args, option) is None:
                setattr(args, option, os.getenv(f'NETDB_{option.upper()}', None))
                if getattr(args, option) is None:
                    if option == 'base_url':
                        setattr(args, option, config.get('DEFAULT', 'endpoint', fallback=None))
                    else:
                        setattr(args, option, config.get(args.base_url, option, fallback=None))
                    if getattr(args, option) is None:
                        self.error(
                            f'No {option} specified (looked in args, environment variable '
57
                            f'"NETDB_{option.upper()}", config-file in "{args.auth_config}")'
58
59
60
61
62
63
                        )

        # load base_url first!
        for configoption in ['base_url', 'token', 'version']:
            load_configoption(configoption)

janis.streib's avatar
janis.streib committed
64
65
        return args

uydwj's avatar
uydwj committed
66

67
68
69
70
def list_to_generator_map_one2one(array, key_name):
    """Mapping function to convert list of dicts to an mapping with value as key for each dict
    (1 to 1 Mapping). Returns an generator object."""
    return ((item[key_name], item) for item in array)
uydwj's avatar
uydwj committed
71
72


73
74
75
def list_to_generator_map_one2many(array, key_name):
    """Mapping function to convert list of dicts to an mapping with values as key for each lists
     (1 to n Mapping). Returns an generator object."""
uydwj's avatar
uydwj committed
76
77
    res = {}
    for item in array:
78
79
80
        if not item[key_name] in res:
            res[item[key_name]] = []
        res[item[key_name]].append(item)
81
82
    for key, value in res.items():
        yield key, value