Source code for preprocessor.config

import os
from typing import TextIO
import re

import yaml


ENV_PATTERN = re.compile(r".*?\${(\w+)}.*?")


[docs]def constructor_env_variables(loader, node): """ 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: full_value = full_value.replace(f"${{{g}}}", os.environ.get(g, g)) return full_value return value
[docs]def load_config(input_file: TextIO): tag = "!env" loader = yaml.SafeLoader # 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(tag, ENV_PATTERN, None) loader.add_constructor(tag, constructor_env_variables) return yaml.load(input_file, Loader=loader)