summaryrefslogtreecommitdiffstats
path: root/test/lib/ansible_test/_internal/cli/parsers/__init__.py
blob: 1aedf6301e4de12aefc4aa691a25adeab403aad0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
"""Composite argument parsers for ansible-test specific command-line arguments."""
from __future__ import annotations

import typing as t

from ...constants import (
    SUPPORTED_PYTHON_VERSIONS,
)

from ...ci import (
    get_ci_provider,
)

from ...host_configs import (
    ControllerConfig,
    NetworkConfig,
    NetworkInventoryConfig,
    PosixConfig,
    WindowsConfig,
    WindowsInventoryConfig,
)

from ..argparsing.parsers import (
    DocumentationState,
    Parser,
    ParserState,
    TypeParser,
)

from .value_parsers import (
    PythonParser,
)

from .host_config_parsers import (
    ControllerParser,
    DockerParser,
    NetworkInventoryParser,
    NetworkRemoteParser,
    OriginParser,
    PosixRemoteParser,
    PosixSshParser,
    WindowsInventoryParser,
    WindowsRemoteParser,
)


from .base_argument_parsers import (
    ControllerNamespaceParser,
    TargetNamespaceParser,
    TargetsNamespaceParser,
)


class OriginControllerParser(ControllerNamespaceParser, TypeParser):
    """Composite argument parser for the controller when delegation is not supported."""
    def get_stateless_parsers(self) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        return dict(
            origin=OriginParser(),
        )

    def document(self, state: DocumentationState) -> t.Optional[str]:
        """Generate and return documentation for this parser."""
        section = '--controller options:'

        state.sections[section] = ''  # place this section before the sections created by the parsers below
        state.sections[section] = '\n'.join([f'  {name}:{parser.document(state)}' for name, parser in self.get_stateless_parsers().items()])

        return None


class DelegatedControllerParser(ControllerNamespaceParser, TypeParser):
    """Composite argument parser for the controller when delegation is supported."""
    def get_stateless_parsers(self) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        parsers: dict[str, Parser] = dict(
            origin=OriginParser(),
            docker=DockerParser(controller=True),
        )

        if get_ci_provider().supports_core_ci_auth():
            parsers.update(
                remote=PosixRemoteParser(controller=True),
            )

        return parsers

    def document(self, state: DocumentationState) -> t.Optional[str]:
        """Generate and return documentation for this parser."""
        section = '--controller options:'

        state.sections[section] = ''  # place this section before the sections created by the parsers below
        state.sections[section] = '\n'.join([f'  {name}:{parser.document(state)}' for name, parser in self.get_stateless_parsers().items()])

        return None


class PosixTargetParser(TargetNamespaceParser, TypeParser):
    """Composite argument parser for a POSIX target."""
    def get_stateless_parsers(self) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        parsers: dict[str, Parser] = dict(
            controller=ControllerParser(),
            docker=DockerParser(controller=False),
        )

        if get_ci_provider().supports_core_ci_auth():
            parsers.update(
                remote=PosixRemoteParser(controller=False),
            )

        parsers.update(
            ssh=PosixSshParser(),
        )

        return parsers

    def document(self, state: DocumentationState) -> t.Optional[str]:
        """Generate and return documentation for this parser."""
        section = f'{self.option_name} options (choose one):'

        state.sections[section] = ''  # place this section before the sections created by the parsers below
        state.sections[section] = '\n'.join([f'  {name}:{parser.document(state)}' for name, parser in self.get_stateless_parsers().items()])

        return None


class WindowsTargetParser(TargetsNamespaceParser, TypeParser):
    """Composite argument parser for a Windows target."""
    @property
    def allow_inventory(self) -> bool:
        """True if inventory is allowed, otherwise False."""
        return True

    def get_parsers(self, state: ParserState) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        return self.get_internal_parsers(state.root_namespace.targets)

    def get_stateless_parsers(self) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        return self.get_internal_parsers([])

    def get_internal_parsers(self, targets: list[WindowsConfig]) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        parsers: dict[str, Parser] = {}

        if self.allow_inventory and not targets:
            parsers.update(
                inventory=WindowsInventoryParser(),
            )

        if not targets or not any(isinstance(target, WindowsInventoryConfig) for target in targets):
            if get_ci_provider().supports_core_ci_auth():
                parsers.update(
                    remote=WindowsRemoteParser(),
                )

        return parsers

    def document(self, state: DocumentationState) -> t.Optional[str]:
        """Generate and return documentation for this parser."""
        section = f'{self.option_name} options (choose one):'

        state.sections[section] = ''  # place this section before the sections created by the parsers below
        state.sections[section] = '\n'.join([f'  {name}:{parser.document(state)}' for name, parser in self.get_stateless_parsers().items()])

        return None


class NetworkTargetParser(TargetsNamespaceParser, TypeParser):
    """Composite argument parser for a network target."""
    @property
    def allow_inventory(self) -> bool:
        """True if inventory is allowed, otherwise False."""
        return True

    def get_parsers(self, state: ParserState) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        return self.get_internal_parsers(state.root_namespace.targets)

    def get_stateless_parsers(self) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        return self.get_internal_parsers([])

    def get_internal_parsers(self, targets: list[NetworkConfig]) -> dict[str, Parser]:
        """Return a dictionary of type names and type parsers."""
        parsers: dict[str, Parser] = {}

        if self.allow_inventory and not targets:
            parsers.update(
                inventory=NetworkInventoryParser(),
            )

        if not targets or not any(isinstance(target, NetworkInventoryConfig) for target in targets):
            if get_ci_provider().supports_core_ci_auth():
                parsers.update(
                    remote=NetworkRemoteParser(),
                )

        return parsers

    def document(self, state: DocumentationState) -> t.Optional[str]:
        """Generate and return documentation for this parser."""
        section = f'{self.option_name} options (choose one):'

        state.sections[section] = ''  # place this section before the sections created by the parsers below
        state.sections[section] = '\n'.join([f'  {name}:{parser.document(state)}' for name, parser in self.get_stateless_parsers().items()])

        return None


class PythonTargetParser(TargetsNamespaceParser, Parser):
    """Composite argument parser for a Python target."""
    def __init__(self, allow_venv: bool) -> None:
        super().__init__()

        self.allow_venv = allow_venv

    @property
    def option_name(self) -> str:
        """The option name used for this parser."""
        return '--target-python'

    def get_value(self, state: ParserState) -> t.Any:
        """Parse the input from the given state and return the result, without storing the result in the namespace."""
        versions = list(SUPPORTED_PYTHON_VERSIONS)

        for target in state.root_namespace.targets or []:  # type: PosixConfig
            versions.remove(target.python.version)

        parser = PythonParser(versions, allow_venv=self.allow_venv, allow_default=True)
        python = parser.parse(state)

        value = ControllerConfig(python=python)

        return value

    def document(self, state: DocumentationState) -> t.Optional[str]:
        """Generate and return documentation for this parser."""
        section = f'{self.option_name} options (choose one):'

        state.sections[section] = '\n'.join([
            f'  {PythonParser(SUPPORTED_PYTHON_VERSIONS, allow_venv=False, allow_default=True).document(state)}  # non-origin controller',
            f'  {PythonParser(SUPPORTED_PYTHON_VERSIONS, allow_venv=True, allow_default=True).document(state)}  # origin controller',
        ])

        return None


class SanityPythonTargetParser(PythonTargetParser):
    """Composite argument parser for a sanity Python target."""
    def __init__(self) -> None:
        super().__init__(allow_venv=False)


class UnitsPythonTargetParser(PythonTargetParser):
    """Composite argument parser for a units Python target."""
    def __init__(self) -> None:
        super().__init__(allow_venv=True)


class PosixSshTargetParser(PosixTargetParser):
    """Composite argument parser for a POSIX SSH target."""
    @property
    def option_name(self) -> str:
        """The option name used for this parser."""
        return '--target-posix'


class WindowsSshTargetParser(WindowsTargetParser):
    """Composite argument parser for a Windows SSH target."""
    @property
    def option_name(self) -> str:
        """The option name used for this parser."""
        return '--target-windows'

    @property
    def allow_inventory(self) -> bool:
        """True if inventory is allowed, otherwise False."""
        return False

    @property
    def limit_one(self) -> bool:
        """True if only one target is allowed, otherwise False."""
        return True


class NetworkSshTargetParser(NetworkTargetParser):
    """Composite argument parser for a network SSH target."""
    @property
    def option_name(self) -> str:
        """The option name used for this parser."""
        return '--target-network'

    @property
    def allow_inventory(self) -> bool:
        """True if inventory is allowed, otherwise False."""
        return False

    @property
    def limit_one(self) -> bool:
        """True if only one target is allowed, otherwise False."""
        return True