Exemplo n.º 1
0
def variables_from_file(path):
    """Loads variables from a given INI file.

    :param path: The path to the INI file.
    :type path: str

    :rtype: dict | None

    The resulting dictionary flattens the sections and values. For example:

    .. code-block:: ini

        [copyright]
        name = ACME, Inc.
        year = 2020

        [domain]
        name = example.com
        tld = example_com

    The dictionary would contain:

    .. code-block:: python

        {
            'copyright_name': "ACME, Inc.",
            'copyright_year': 2020,
            'domain_name': "example.com",
            'domain_tld': "example_com",
        }

    """
    if not os.path.exists(path):
        log.warning("Variables file does not exist: %s" % path)
        return None

    ini = ConfigParser()
    ini.read(path)

    variables = dict()
    for section in ini.sections():
        for key, value in ini.items(section):
            key = "%s_%s" % (section, key)
            variables[key] = smart_cast(value)

    return variables
Exemplo n.º 2
0
def options_from_cli(options):
    """Takes a list of variables given in the form of ``name:value`` and converts them to a dictionary.

    :param options: A list of strings of ``name:value`` pairs.
    :type options: list[str]

    :rtype: dict

    The ``value`` of the pair passes through "smart casting" to convert it to the appropriate Python data type.

    """
    _options = dict()
    for i in options:
        key, value = i.split(":")
        _options[key] = smart_cast(value)

    return _options
Exemplo n.º 3
0
def _load_variables_ini(path, environment=None):
    """Load variables from an INI file. See ``load_variables()``."""

    ini = RawConfigParser()
    ini.read(path)

    a = list()
    for section in ini.sections():
        if ":" in section:
            variable_name, _environment = section.split(":")
        else:
            _environment = None
            variable_name = section

        _kwargs = {
            'environment': _environment,
        }
        for key, value in ini.items(section):
            if key == "tags":
                value = split_csv(value)
            else:
                value = smart_cast(value)

            _kwargs[key] = value

        a.append(Variable(variable_name, **_kwargs))

    if environment is not None:
        b = list()
        for var in a:
            if var.environment and var.environment == environment or var.environment is None:
                b.append(var)

        return b

    return a