Debian Codegraph @

lib/ansible/module_utils/_internal/_deprecator.py

raw
1 from __future__ import annotations
2
3 import re
4 import pathlib
5 import sys
6 import typing as t
7
8 from ansible.module_utils._internal import _stack, _messages, _validation, _plugin_info
9
10
11 def deprecator_from_collection_name(collection_name: str | None) -> _messages.PluginInfo | None:
12 """Returns an instance with the special `collection` type to refer to a non-plugin or ambiguous caller within a collection."""
13 # CAUTION: This function is exposed in public API as ansible.module_utils.datatag.deprecator_from_collection_name.
14
15 if not collection_name:
16 return None
17
18 _validation.validate_collection_name(collection_name)
19
20 return _messages.PluginInfo(
21 resolved_name=collection_name,
22 type=None,
23 )
24
25
26 def get_best_deprecator(*, deprecator: _messages.PluginInfo | None = None, collection_name: str | None = None) -> _messages.PluginInfo:
27 """Return the best-available `PluginInfo` for the caller of this method."""
28 _skip_stackwalk = True
29
30 if deprecator and collection_name:
31 raise ValueError('Specify only one of `deprecator` or `collection_name`.')
32
33 return deprecator or deprecator_from_collection_name(collection_name) or get_caller_plugin_info() or INDETERMINATE_DEPRECATOR
34
35
36 def get_caller_plugin_info() -> _messages.PluginInfo | None:
37 """Try to get `PluginInfo` for the caller of this method, ignoring marked infrastructure stack frames."""
38 _skip_stackwalk = True
39
40 if frame_info := _stack.caller_frame():
41 return _path_as_plugininfo(frame_info.filename)
42
43 return None # pragma: nocover
44
45
46 def _path_as_plugininfo(path: str) -> _messages.PluginInfo | None:
47 """Return a `PluginInfo` instance if the provided `path` refers to a plugin."""
48 return _path_as_core_plugininfo(path) or _path_as_collection_plugininfo(path)
49
50
51 def _path_as_core_plugininfo(path: str) -> _messages.PluginInfo | None:
52 """Return a `PluginInfo` instance if the provided `path` refers to a core plugin."""
53 try:
54 relpath = str(pathlib.Path(path).relative_to(_ANSIBLE_MODULE_BASE_PATH))
55 except ValueError:
56 return None # not ansible-core
57
58 namespace = 'ansible.builtin'
59
60 if match := re.match(r'plugins/(?P<plugin_type>\w+)/(?P<plugin_name>\w+)', relpath):
61 plugin_name = match.group("plugin_name")
62 plugin_type = _plugin_info.normalize_plugin_type(match.group("plugin_type"))
63
64 if plugin_type not in _DEPRECATOR_PLUGIN_TYPES:
65 # The plugin type isn't a known deprecator type, so we have to assume the caller is intermediate code.
66 # We have no way of knowing if the intermediate code is deprecating its own feature, or acting on behalf of another plugin.
67 # Callers in this case need to identify the deprecating plugin name, otherwise only ansible-core will be reported.
68 # Reporting ansible-core is never wrong, it just may be missing an additional detail (plugin name) in the "on behalf of" case.
69 return ANSIBLE_CORE_DEPRECATOR
70
71 if plugin_name == '__init__':
72 # The plugin type is known, but the caller isn't a specific plugin -- instead, it's core plugin infrastructure (the base class).
73 return _messages.PluginInfo(resolved_name=namespace, type=plugin_type)
74 elif match := re.match(r'modules/(?P<module_name>\w+)', relpath):
75 # AnsiballZ Python package for core modules
76 plugin_name = match.group("module_name")
77 plugin_type = _messages.PluginType.MODULE
78 elif match := re.match(r'legacy/(?P<module_name>\w+)', relpath):
79 # AnsiballZ Python package for non-core library/role modules
80 namespace = 'ansible.legacy'
81
82 plugin_name = match.group("module_name")
83 plugin_type = _messages.PluginType.MODULE
84 else:
85 return ANSIBLE_CORE_DEPRECATOR # non-plugin core path, safe to use ansible-core for the same reason as the non-deprecator plugin type case above
86
87 name = f'{namespace}.{plugin_name}'
88
89 return _messages.PluginInfo(resolved_name=name, type=plugin_type)
90
91
92 def _path_as_collection_plugininfo(path: str) -> _messages.PluginInfo | None:
93 """Return a `PluginInfo` instance if the provided `path` refers to a collection plugin."""
94 if not (match := re.search(r'/ansible_collections/(?P<ns>\w+)/(?P<coll>\w+)/plugins/(?P<plugin_type>\w+)/(?P<plugin_name>\w+)', path)):
95 return None
96
97 plugin_type = _plugin_info.normalize_plugin_type(match.group('plugin_type'))
98
99 if plugin_type in _AMBIGUOUS_DEPRECATOR_PLUGIN_TYPES:
100 # We're able to detect the namespace, collection and plugin type -- but we have no way to identify the plugin name currently.
101 # To keep things simple we'll fall back to just identifying the namespace and collection.
102 # In the future we could improve the detection and/or make it easier for a caller to identify the plugin name.
103 return deprecator_from_collection_name('.'.join((match.group('ns'), match.group('coll'))))
104
105 if plugin_type not in _DEPRECATOR_PLUGIN_TYPES:
106 # The plugin type isn't a known deprecator type, so we have to assume the caller is intermediate code.
107 # We have no way of knowing if the intermediate code is deprecating its own feature, or acting on behalf of another plugin.
108 # Callers in this case need to identify the deprecator to avoid ambiguity, since it could be the same collection or another collection.
109 return INDETERMINATE_DEPRECATOR
110
111 name = '.'.join((match.group('ns'), match.group('coll'), match.group('plugin_name')))
112
113 # DTFIX-FUTURE: deprecations from __init__ will be incorrectly attributed to a plugin of that name
114
115 return _messages.PluginInfo(resolved_name=name, type=plugin_type)
116
117
118 _ANSIBLE_MODULE_BASE_PATH: t.Final = pathlib.Path(sys.modules['ansible'].__file__).parent
119 """Runtime-detected base path of the `ansible` Python package to distinguish between Ansible-owned and external code."""
120
121 ANSIBLE_CORE_DEPRECATOR: t.Final = deprecator_from_collection_name('ansible.builtin')
122 """Singleton `PluginInfo` instance for ansible-core callers where the plugin can/should not be identified in messages."""
123
124 INDETERMINATE_DEPRECATOR: t.Final = _messages.PluginInfo(resolved_name=None, type=None)
125 """Singleton `PluginInfo` instance for indeterminate deprecator."""
126
127 _DEPRECATOR_PLUGIN_TYPES: t.Final = frozenset(
128 {
129 _messages.PluginType.ACTION,
130 _messages.PluginType.BECOME,
131 _messages.PluginType.CACHE,
132 _messages.PluginType.CALLBACK,
133 _messages.PluginType.CLICONF,
134 _messages.PluginType.CONNECTION,
135 # DOC_FRAGMENTS - no code execution
136 # FILTER - basename inadequate to identify plugin
137 _messages.PluginType.HTTPAPI,
138 _messages.PluginType.INVENTORY,
139 _messages.PluginType.LOOKUP,
140 _messages.PluginType.MODULE, # only for collections
141 _messages.PluginType.NETCONF,
142 _messages.PluginType.SHELL,
143 _messages.PluginType.STRATEGY,
144 _messages.PluginType.TERMINAL,
145 # TEST - basename inadequate to identify plugin
146 _messages.PluginType.VARS,
147 }
148 )
149 """Plugin types which are valid for identifying a deprecator for deprecation purposes."""
150
151 _AMBIGUOUS_DEPRECATOR_PLUGIN_TYPES: t.Final = frozenset(
152 {
153 _messages.PluginType.FILTER,
154 _messages.PluginType.TEST,
155 }
156 )
157 """Plugin types for which basename cannot be used to identify the plugin name."""