1# Copyright: (c) 2018, Toshio Kuratomi <tkuratomi@ansible.com>
2# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4# Make coding more python3-ish
5from __future__ import (absolute_import, division, print_function)
6__metaclass__ = type
7
8"""
9Context of the running Ansible.
10
11In the future we *may* create Context objects to allow running multiple Ansible plays in parallel
12with different contexts but that is currently out of scope as the Ansible library is just for
13running the ansible command line tools.
14
15These APIs are still in flux so do not use them unless you are willing to update them with every Ansible release
16"""
17
18from ansible.module_utils.common._collections_compat import Mapping, Set
19from ansible.module_utils.common.collections import is_sequence
20from ansible.utils.context_objects import CLIArgs, GlobalCLIArgs
21
22
23__all__ = ('CLIARGS',)
24
25# Note: this is not the singleton version.  The Singleton is only created once the program has
26# actually parsed the args
27CLIARGS = CLIArgs({})
28
29
30# This should be called immediately after cli_args are processed (parsed, validated, and any
31# normalization performed on them).  No other code should call it
32def _init_global_context(cli_args):
33    """Initialize the global context objects"""
34    global CLIARGS
35    CLIARGS = GlobalCLIArgs.from_options(cli_args)
36
37
38def cliargs_deferred_get(key, default=None, shallowcopy=False):
39    """Closure over getting a key from CLIARGS with shallow copy functionality
40
41    Primarily used in ``FieldAttribute`` where we need to defer setting the default
42    until after the CLI arguments have been parsed
43
44    This function is not directly bound to ``CliArgs`` so that it works with
45    ``CLIARGS`` being replaced
46    """
47    def inner():
48        value = CLIARGS.get(key, default=default)
49        if not shallowcopy:
50            return value
51        elif is_sequence(value):
52            return value[:]
53        elif isinstance(value, (Mapping, Set)):
54            return value.copy()
55        return value
56    return inner
57