Debian Codegraph @

lib/ansible/_internal/_display_utils.py

raw
1 from __future__ import annotations
2
3 import dataclasses
4
5 from ansible.module_utils._internal import _ambient_context, _messages
6 from . import _event_formatting
7
8
9 class DeferredWarningContext(_ambient_context.AmbientContextBase):
10 """
11 Calls to `Display.warning()` and `Display.deprecated()` within this context will cause the resulting warnings to be captured and not displayed.
12 The intended use is for task-initiated warnings to be recorded with the task result, which makes them visible to registered results, callbacks, etc.
13 The active display callback is responsible for communicating any warnings to the user.
14 """
15
16 # DTFIX-FUTURE: once we start implementing nested scoped contexts for our own bookkeeping, this should be an interface facade that forwards to the nearest
17 # context that actually implements the warnings collection capability
18
19 def __init__(self, *, variables: dict[str, object]) -> None:
20 self._variables = variables # DTFIX-FUTURE: move this to an AmbientContext-derived TaskContext (once it exists)
21 self._deprecation_warnings: list[_messages.DeprecationSummary] = []
22 self._warnings: list[_messages.WarningSummary] = []
23 self._seen: set[_messages.WarningSummary] = set()
24
25 def capture(self, warning: _messages.WarningSummary) -> None:
26 """Add the warning/deprecation to the context if it has not already been seen by this context."""
27 if warning in self._seen:
28 return
29
30 self._seen.add(warning)
31
32 if isinstance(warning, _messages.DeprecationSummary):
33 self._deprecation_warnings.append(warning)
34 else:
35 self._warnings.append(warning)
36
37 def get_warnings(self) -> list[_messages.WarningSummary]:
38 """Return a list of the captured non-deprecation warnings."""
39 # DTFIX-FUTURE: return a read-only list proxy instead
40 return self._warnings
41
42 def get_deprecation_warnings(self) -> list[_messages.DeprecationSummary]:
43 """Return a list of the captured deprecation warnings."""
44 # DTFIX-FUTURE: return a read-only list proxy instead
45 return self._deprecation_warnings
46
47
48 def format_message(summary: _messages.SummaryBase, include_traceback: bool) -> str:
49 if isinstance(summary, _messages.DeprecationSummary):
50 deprecation_message = get_deprecation_message_with_plugin_info(
51 msg=summary.event.msg,
52 version=summary.version,
53 date=summary.date,
54 deprecator=summary.deprecator,
55 )
56
57 event = dataclasses.replace(summary.event, msg=deprecation_message)
58 else:
59 event = summary.event
60
61 return _event_formatting.format_event(event, include_traceback)
62
63
64 def get_deprecation_message_with_plugin_info(
65 *,
66 msg: str,
67 version: str | None,
68 removed: bool = False,
69 date: str | None,
70 deprecator: _messages.PluginInfo | None,
71 ) -> str:
72 """Internal use only. Return a deprecation message and help text for display."""
73 # DTFIX-FUTURE: the logic for omitting date/version doesn't apply to the payload, so it shows up in vars in some cases when it should not
74
75 if removed:
76 removal_fragment = 'This feature was removed'
77 else:
78 removal_fragment = 'This feature will be removed'
79
80 if not deprecator or not deprecator.type:
81 # indeterminate has no resolved_name or type
82 # collections have a resolved_name but no type
83 collection = deprecator.resolved_name if deprecator else None
84 plugin_fragment = ''
85 elif deprecator.resolved_name == 'ansible.builtin':
86 # core deprecations from base classes (the API) have no plugin name, only 'ansible.builtin'
87 plugin_type_name = str(deprecator.type) if deprecator.type is _messages.PluginType.MODULE else f'{deprecator.type} plugin'
88
89 collection = deprecator.resolved_name
90 plugin_fragment = f'the {plugin_type_name} API'
91 else:
92 parts = deprecator.resolved_name.split('.')
93 plugin_name = parts[-1]
94 plugin_type_name = str(deprecator.type) if deprecator.type is _messages.PluginType.MODULE else f'{deprecator.type} plugin'
95
96 collection = '.'.join(parts[:2]) if len(parts) > 2 else None
97 plugin_fragment = f'{plugin_type_name} {plugin_name!r}'
98
99 if collection and plugin_fragment:
100 plugin_fragment += ' in'
101
102 if collection == 'ansible.builtin':
103 collection_fragment = 'ansible-core'
104 elif collection:
105 collection_fragment = f'collection {collection!r}'
106 else:
107 collection_fragment = ''
108
109 if not collection:
110 when_fragment = 'in the future' if not removed else ''
111 elif date:
112 when_fragment = f'in a release after {date}'
113 elif version:
114 when_fragment = f'version {version}'
115 else:
116 when_fragment = 'in a future release' if not removed else ''
117
118 if plugin_fragment or collection_fragment:
119 from_fragment = 'from'
120 else:
121 from_fragment = ''
122
123 deprecation_msg = ' '.join(f for f in [removal_fragment, from_fragment, plugin_fragment, collection_fragment, when_fragment] if f) + '.'
124
125 return join_sentences(msg, deprecation_msg)
126
127
128 def join_sentences(first: str | None, second: str | None) -> str:
129 """Join two sentences together."""
130 first = (first or '').strip()
131 second = (second or '').strip()
132
133 if first and first[-1] not in ('!', '?', '.'):
134 first += '.'
135
136 if second and second[-1] not in ('!', '?', '.'):
137 second += '.'
138
139 if first and not second:
140 return first
141
142 if not first and second:
143 return second
144
145 return ' '.join((first, second))