EOX GitLab Instance

config.py 1.63 KB
Newer Older
1
2
3
4
import os
import re
import datetime

Nikola Jankovic's avatar
Nikola Jankovic committed
5
import jsonschema
6
7
8
import yaml


Nikola Jankovic's avatar
Nikola Jankovic committed
9
10
ENV_PATTERN = re.compile(r".*?\${(\w+)}.*?")
LOADER = yaml.SafeLoader
11
12
13


def constructor_env_variables(loader, node):
Nikola Jankovic's avatar
Nikola Jankovic committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    """
    Extracts the environment variable from the node's value
    :param yaml.Loader loader: the yaml loader
    :param node: the current node in the yaml
    :return: the parsed string that contains the value of the environment
    variable
    """
    value = loader.construct_scalar(node)
    match = ENV_PATTERN.findall(value)  # to find all env variables in line
    if match:
        full_value = value
        for g in match:
            env_variable = os.environ.get(
                g,
            )
            if env_variable is not None:
                full_value = full_value.replace(f"${{{g}}}", env_variable)
            else:
                return None
        return full_value
    return value


def constructor_now(loader, node):
38
39
40
    return datetime.datetime.now(tz=datetime.timezone.utc).isoformat()


Nikola Jankovic's avatar
Nikola Jankovic committed
41
42
43
44
45
46
# the tag will be used to mark where to start searching for the pattern
# e.g. somekey: !env somestring${MYENVVAR}blah blah blah
LOADER.add_implicit_resolver("!env", ENV_PATTERN, None)
LOADER.add_constructor("!env", constructor_env_variables)
# this tag resolves !now to datetime.now
LOADER.add_constructor("!now", constructor_now)
47
48


Nikola Jankovic's avatar
Nikola Jankovic committed
49
50
51
52
53
54
55
56
57
58
59
def load_config(input_file: str) -> dict:
    return yaml.load(input_file, Loader=LOADER)


def validate_config(config):
    with open(
        os.path.join(os.path.dirname(__file__), "config-schema.yaml"), encoding="utf-8"
    ) as file:
        schema = yaml.load(file, LOADER)

    jsonschema.validate(config, schema)