1"""
2Environment utilities.
3"""
4
5import os
6
7
8def get_module_environment(env=None, function=None):
9    """
10    Get module optional environment.
11
12    To setup an environment option for a particular module,
13    add either pillar or config at the minion as follows:
14
15    system-environment:
16      modules:
17        pkg:
18          _:
19            LC_ALL: en_GB.UTF-8
20            FOO: bar
21          install:
22            HELLO: world
23      states:
24        pkg:
25          _:
26            LC_ALL: en_US.Latin-1
27            NAME: Fred
28
29    So this will export the environment to all the modules,
30    states, returnes etc. And calling this function with the globals()
31    in that context will fetch the environment for further reuse.
32
33    Underscore '_' exports environment for all functions within the module.
34    If you want to specifially export environment only for one function,
35    specify it as in the example above "install".
36
37    First will be fetched configuration, where virtual name goes first,
38    then the physical name of the module overrides the virtual settings.
39    Then pillar settings will override the configuration in the same order.
40
41    :param env:
42    :param function: name of a particular function
43    :return: dict
44    """
45    result = {}
46    if not env:
47        env = {}
48    for env_src in [env.get("__opts__", {}), env.get("__pillar__", {})]:
49        fname = env.get("__file__", "")
50        physical_name = os.path.basename(fname).split(".")[0]
51        section = os.path.basename(os.path.dirname(fname))
52        m_names = [env.get("__virtualname__")]
53        if physical_name not in m_names:
54            m_names.append(physical_name)
55        for m_name in m_names:
56            if not m_name:
57                continue
58            result.update(
59                env_src.get("system-environment", {})
60                .get(section, {})
61                .get(m_name, {})
62                .get("_", {})
63                .copy()
64            )
65            if function is not None:
66                result.update(
67                    env_src.get("system-environment", {})
68                    .get(section, {})
69                    .get(m_name, {})
70                    .get(function, {})
71                    .copy()
72                )
73
74    return result
75