Debian Codegraph @

lib/ansible/cli/doc.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # Copyright: (c) 2014, James Tanner <[email protected]>
3 # Copyright: (c) 2018, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # PYTHON_ARGCOMPLETE_OK
6
7 from __future__ import annotations
8
9 # ansible.cli needs to be imported first, to ensure the source bin/* scripts run that code first
10 from ansible.cli import CLI
11
12 import collections.abc
13 import importlib
14 import pkgutil
15 import os
16 import os.path
17 import re
18 import textwrap
19 import typing as t
20
21 import yaml
22
23 import ansible.plugins.loader as plugin_loader
24
25 from pathlib import Path
26
27 from ansible import constants as C
28 from ansible import context
29 from ansible.cli.arguments import option_helpers as opt_help
30 from ansible.collections.list import list_collection_dirs
31 from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError, AnsiblePluginNotFound
32 from ansible.module_utils.common.text.converters import to_native, to_text
33 from ansible.module_utils.common.collections import is_sequence
34 from ansible.module_utils.common.yaml import yaml_dump
35 from ansible.parsing.plugin_docs import read_docstub
36 from ansible.parsing.yaml.dumper import AnsibleDumper
37 from ansible.parsing.yaml.loader import AnsibleLoader
38 from ansible._internal._yaml._loader import AnsibleInstrumentedLoader
39 from ansible.plugins.list import _list_plugins_with_info, _PluginDocMetadata
40 from ansible.plugins.loader import action_loader, fragment_loader
41 from ansible.utils.collection_loader import AnsibleCollectionConfig, AnsibleCollectionRef
42 from ansible.utils.collection_loader._collection_finder import _get_collection_name_from_path
43 from ansible.utils.color import stringc
44 from ansible.utils.display import Display
45 from ansible.utils.plugin_docs import get_plugin_docs, get_docstring, get_versioned_doclink
46 from ansible.template import trust_as_template
47 from ansible._internal import _json
48 from ansible._internal._templating import _jinja_plugins
49
50 display = Display()
51
52
53 TARGET_OPTIONS = C.DOCUMENTABLE_PLUGINS + ('role', 'keyword',)
54 PB_OBJECTS = ['Play', 'Role', 'Block', 'Task', 'Handler']
55 PB_LOADED = {}
56 SNIPPETS = ['inventory', 'lookup', 'module']
57
58 # hardcoded from ascii values
59 STYLE = {
60 'BLINK': '\033[5m',
61 'BOLD': '\033[1m',
62 'HIDE': '\033[8m',
63 # 'NORMAL': '\x01b[0m', # newer?
64 'NORMAL': '\033[0m',
65 'RESET': "\033[0;0m",
66 # 'REVERSE':"\033[;7m", # newer?
67 'REVERSE': "\033[7m",
68 'UNDERLINE': '\033[4m',
69 }
70
71 # previously existing string identifiers
72 NOCOLOR = {
73 'BOLD': r'*%s*',
74 'UNDERLINE': r'`%s`',
75 'MODULE': r'[%s]',
76 'PLUGIN': r'[%s]',
77 }
78
79 ref_style = {
80 'MODULE': C.COLOR_DOC_MODULE,
81 'REF': C.COLOR_DOC_REFERENCE,
82 'LINK': C.COLOR_DOC_LINK,
83 'DEP': C.COLOR_DOC_DEPRECATED,
84 'CONSTANT': C.COLOR_DOC_CONSTANT,
85 'PLUGIN': C.COLOR_DOC_PLUGIN,
86 }
87
88
89 def jdump(text):
90 try:
91 display.display(_json.json_dumps_formatted(text))
92 except TypeError as ex:
93 raise AnsibleError('We could not convert all the documentation into JSON as there was a conversion issue.') from ex
94
95
96 class RoleMixin(object):
97 """A mixin containing all methods relevant to role argument specification functionality.
98
99 Note: The methods for actual display of role data are not present here.
100 """
101
102 # Potential locations of the role arg spec file in the meta subdir, with main.yml
103 # having the lowest priority.
104 ROLE_METADATA_FILES = ["main" + e for e in C.YAML_FILENAME_EXTENSIONS]
105 ROLE_ARGSPEC_FILES = ['argument_specs' + e for e in C.YAML_FILENAME_EXTENSIONS] + ROLE_METADATA_FILES
106
107 def _load_role_data(self, root, files, role_name, collection):
108 """ Load and process the YAML for the first found of a set of role files
109
110 :param str root: The root path to get the files from
111 :param list files: List of candidate file names in order of precedence
112 :param str role_name: The name of the role for which we want the argspec data.
113 :param str collection: collection name or None in case of stand alone roles
114
115 :returns: A dict that contains the data requested, empty if no data found
116 """
117
118 if collection:
119 meta_path = os.path.join(root, 'roles', role_name, 'meta')
120 else:
121 meta_path = os.path.join(root, 'meta')
122
123 # Check all potential spec files
124 path = None
125 for specfile in files:
126 full_path = os.path.join(meta_path, specfile)
127 if os.path.exists(full_path):
128 path = full_path
129 break
130
131 if path is None:
132 return {}
133
134 try:
135 with open(path, 'r') as f:
136 data = yaml.load(trust_as_template(f), Loader=AnsibleLoader)
137 if data is None:
138 data = {}
139 except OSError as ex:
140 raise AnsibleParserError(f"Could not read the role {role_name!r} at {path!r}.") from ex
141
142 return data
143
144 def _load_metadata(self, role_name, role_path, collection):
145 """Load the roles metadata from the source file.
146
147 :param str role_name: The name of the role for which we want the argspec data.
148 :param str role_path: Path to the role/collection root.
149 :param str collection: collection name or None in case of stand alone roles
150
151 :returns: A dict of all role meta data, except ``argument_specs`` or an empty dict
152 """
153
154 data = self._load_role_data(role_path, self.ROLE_METADATA_FILES, role_name, collection)
155 del data['argument_specs']
156
157 return data
158
159 def _load_argspec(self, role_name, role_path, collection):
160 """Load the role argument spec data from the source file.
161
162 :param str role_name: The name of the role for which we want the argspec data.
163 :param str role_path: Path to the role/collection root.
164 :param str collection: collection name or None in case of stand alone roles
165
166 We support two files containing the role arg spec data: either meta/main.yml
167 or meta/argument_spec.yml. The argument_spec.yml file will take precedence
168 over the meta/main.yml file, if it exists. Data is NOT combined between the
169 two files.
170
171 :returns: A dict of all data underneath the ``argument_specs`` top-level YAML
172 key in the argspec data file. Empty dict is returned if there is no data.
173 """
174
175 try:
176 data = self._load_role_data(role_path, self.ROLE_ARGSPEC_FILES, role_name, collection)
177 data = data.get('argument_specs', {})
178
179 except Exception as e:
180 # we keep error info, but let caller deal with it
181 data = {'error': 'Failed to process role (%s): %s' % (role_name, to_native(e)), 'exception': e}
182 return data
183
184 def _find_all_normal_roles(self, role_paths, name_filters=None):
185 """Find all non-collection roles that have an argument spec file.
186
187 Note that argument specs do not actually need to exist within the spec file.
188
189 :param role_paths: A tuple of one or more role paths. When a role with the same name
190 is found in multiple paths, only the first-found role is returned.
191 :param name_filters: A tuple of one or more role names used to filter the results.
192
193 :returns: A set of tuples consisting of: role name, full role path
194 """
195 found = set()
196 found_names = set()
197
198 for path in role_paths:
199 if not os.path.isdir(path):
200 continue
201
202 # Check each subdir for an argument spec file
203 for entry in os.listdir(path):
204 role_path = os.path.join(path, entry)
205
206 # Check all potential spec files
207 for specfile in self.ROLE_ARGSPEC_FILES:
208 full_path = os.path.join(role_path, 'meta', specfile)
209 if os.path.exists(full_path):
210 if name_filters is None or entry in name_filters:
211 # select first-found role
212 if entry not in found_names:
213 found_names.add(entry)
214 # None here stands for 'colleciton', which stand alone roles dont have
215 # makes downstream code simpler by having same structure as collection roles
216 found.add((entry, None, role_path))
217 # only read first existing spec
218 break
219 return found
220
221 def _find_all_collection_roles(self, name_filters=None, collection_filter=None):
222 """Find all collection roles with an argument spec file.
223
224 Note that argument specs do not actually need to exist within the spec file.
225
226 :param name_filters: A tuple of one or more role names used to filter the results. These
227 might be fully qualified with the collection name (e.g., community.general.roleA)
228 or not (e.g., roleA).
229
230 :param collection_filter: A list of strings containing the FQCN of a collection which will
231 be used to limit results. This filter will take precedence over the name_filters.
232
233 :returns: A set of tuples consisting of: role name, collection name, collection path
234 """
235 found = set()
236 b_colldirs = list_collection_dirs(coll_filter=collection_filter)
237 for b_path in b_colldirs:
238 path = to_text(b_path, errors='surrogate_or_strict')
239 if not (collname := _get_collection_name_from_path(b_path)):
240 display.debug(f'Skipping invalid path {b_path!r}')
241 continue
242
243 roles_dir = os.path.join(path, 'roles')
244 if os.path.exists(roles_dir):
245 for entry in os.listdir(roles_dir):
246
247 # Check all potential spec files
248 for specfile in self.ROLE_ARGSPEC_FILES:
249 full_path = os.path.join(roles_dir, entry, 'meta', specfile)
250 if os.path.exists(full_path):
251 if name_filters is None:
252 found.add((entry, collname, path))
253 else:
254 # Name filters might contain a collection FQCN or not.
255 for fqcn in name_filters:
256 if len(fqcn.split('.')) == 3:
257 (ns, col, role) = fqcn.split('.')
258 if '.'.join([ns, col]) == collname and entry == role:
259 found.add((entry, collname, path))
260 elif fqcn == entry:
261 found.add((entry, collname, path))
262 break
263 return found
264
265 def _build_summary(self, role, collection, meta, argspec):
266 """Build a summary dict for a role.
267
268 Returns a simplified role arg spec containing only the role entry points and their
269 short descriptions, and the role collection name (if applicable).
270
271 :param role: The simple role name.
272 :param collection: The collection containing the role (None or empty string if N/A).
273 :param meta: dictionary with galaxy information (None or empty string if N/A).
274 :param argspec: The complete role argspec data dict.
275
276 :returns: A tuple with the FQCN role name and a summary dict.
277 """
278
279 if meta and meta.get('galaxy_info'):
280 summary = meta['galaxy_info']
281 else:
282 summary = {'description': 'UNDOCUMENTED'}
283 summary['entry_points'] = {}
284
285 if collection:
286 fqcn = '.'.join([collection, role])
287 summary['collection'] = collection
288 else:
289 fqcn = role
290
291 for ep in argspec.keys():
292 entry_spec = argspec[ep] or {}
293 summary['entry_points'][ep] = entry_spec.get('short_description', '')
294 return (fqcn, summary)
295
296 def _build_doc(self, role, path, collection, argspec, entry_point):
297 if collection:
298 fqcn = '.'.join([collection, role])
299 else:
300 fqcn = role
301 doc = {}
302 doc['path'] = path
303 doc['collection'] = collection
304 if 'error' in argspec:
305 doc.update(argspec)
306 else:
307 doc['entry_points'] = {}
308 for ep in argspec.keys():
309 if entry_point is None or ep == entry_point:
310 entry_spec = argspec[ep] or {}
311 doc['entry_points'][ep] = entry_spec
312
313 # If we didn't add any entry points (b/c of filtering), ignore this entry.
314 if len(doc['entry_points'].keys()) == 0:
315 doc = None
316
317 return (fqcn, doc)
318
319 def _create_role_list(self, fail_on_errors=True):
320 """Return a dict describing the listing of all roles with arg specs.
321
322 :param role_paths: A tuple of one or more role paths.
323
324 :returns: A dict indexed by role name, with 'collection' and 'entry_points' keys per role.
325
326 Example return:
327
328 results = {
329 'roleA': {
330 'collection': '',
331 'entry_points': {
332 'main': 'Short description for main'
333 }
334 },
335 'a.b.c.roleB': {
336 'collection': 'a.b.c',
337 'entry_points': {
338 'main': 'Short description for main',
339 'alternate': 'Short description for alternate entry point'
340 }
341 'x.y.z.roleB': {
342 'collection': 'x.y.z',
343 'entry_points': {
344 'main': 'Short description for main',
345 }
346 },
347 }
348 """
349 roles_path = self._get_roles_path()
350 collection_filter = self._get_collection_filter()
351 if not collection_filter:
352 roles = self._find_all_normal_roles(roles_path)
353 else:
354 roles = set()
355 collroles = self._find_all_collection_roles(collection_filter=collection_filter)
356
357 result = {}
358
359 for role, collection, role_path in (roles | collroles):
360
361 try:
362 meta = self._load_metadata(role, role_path, collection)
363 except Exception as e:
364 display.vvv(f'No metadata for role ({role}) due to: {e}')
365 meta = {}
366
367 argspec = self._load_argspec(role, role_path, collection)
368 if 'error' in argspec:
369 if fail_on_errors:
370 raise argspec['exception']
371 else:
372 display.warning(f'Skipping role ({role}) due to: {argspec["error"]}')
373 continue
374
375 fqcn, summary = self._build_summary(role, collection, meta, argspec)
376 result[fqcn] = summary
377
378 return result
379
380 def _create_role_doc(self, role_names, entry_point=None, fail_on_errors=True):
381 """
382 :param role_names: A tuple of one or more role names.
383 :param role_paths: A tuple of one or more role paths.
384 :param entry_point: A role entry point name for filtering.
385 :param fail_on_errors: When set to False, include errors in the JSON output instead of raising errors
386
387 :returns: A dict indexed by role name, with 'collection', 'entry_points', and 'path' keys per role.
388 """
389 roles_path = self._get_roles_path()
390 roles = self._find_all_normal_roles(roles_path, name_filters=role_names)
391 collroles = self._find_all_collection_roles(name_filters=role_names)
392
393 result = {}
394
395 for role, collection, role_path in (roles | collroles):
396 argspec = self._load_argspec(role, role_path, collection)
397 if 'error' in argspec:
398 if fail_on_errors:
399 raise argspec['exception']
400 else:
401 display.warning('Skipping role (%s) due to: %s' % (role, argspec['error']), True)
402 continue
403 fqcn, doc = self._build_doc(role, role_path, collection, argspec, entry_point)
404 if doc:
405 result[fqcn] = doc
406
407 return result
408
409
410 def _doclink(url):
411 # assume that if it is relative, it is for docsite, ignore rest
412 if not url.startswith(("http", "..")):
413 url = get_versioned_doclink(url)
414 return url
415
416
417 def _format(string, *args):
418
419 """ add ascii formatting or delimiters """
420
421 for style in args:
422
423 if style not in ref_style and style.upper() not in STYLE and style not in C.COLOR_CODES:
424 raise KeyError("Invalid format value supplied: %s" % style)
425
426 if C.ANSIBLE_NOCOLOR:
427 # ignore most styles, but some already had 'identifier strings'
428 if style in NOCOLOR:
429 string = NOCOLOR[style] % string
430 elif style in C.COLOR_CODES:
431 string = stringc(string, style)
432 elif style in ref_style:
433 # assumes refs are also always colors
434 string = stringc(string, ref_style[style])
435 else:
436 # start specific style and 'end' with normal
437 string = '%s%s%s' % (STYLE[style.upper()], string, STYLE['NORMAL'])
438
439 return string
440
441
442 class DocCLI(CLI, RoleMixin):
443 """ displays information on modules installed in Ansible libraries.
444 It displays a terse listing of plugins and their short descriptions,
445 provides a printout of their DOCUMENTATION strings,
446 and it can create a short "snippet" which can be pasted into a playbook. """
447
448 name = 'ansible-doc'
449
450 # default ignore list for detailed views
451 IGNORE = ('module', 'docuri', 'version_added', 'version_added_collection', 'short_description',
452 'now_date', 'plainexamples', 'returndocs', 'collection', 'plugin_name')
453
454 # Warning: If you add more elements here, you also need to add it to the docsite build (in the
455 # ansible-community/antsibull repo)
456 _ITALIC = re.compile(r"\bI\(([^)]+)\)")
457 _BOLD = re.compile(r"\bB\(([^)]+)\)")
458 _MODULE = re.compile(r"\bM\(([^)]+)\)")
459 _PLUGIN = re.compile(r"\bP\(([^#)]+)#([a-z]+)\)")
460 _LINK = re.compile(r"\bL\(([^)]+), *([^)]+)\)")
461 _URL = re.compile(r"\bU\(([^)]+)\)")
462 _REF = re.compile(r"\bR\(([^)]+), *([^)]+)\)")
463 _CONST = re.compile(r"\bC\(([^)]+)\)")
464 _SEM_PARAMETER_STRING = r"\(((?:[^\\)]+|\\.)+)\)"
465 _SEM_OPTION_NAME = re.compile(r"\bO" + _SEM_PARAMETER_STRING)
466 _SEM_OPTION_VALUE = re.compile(r"\bV" + _SEM_PARAMETER_STRING)
467 _SEM_ENV_VARIABLE = re.compile(r"\bE" + _SEM_PARAMETER_STRING)
468 _SEM_RET_VALUE = re.compile(r"\bRV" + _SEM_PARAMETER_STRING)
469 _RULER = re.compile(r"\bHORIZONTALLINE\b")
470
471 # helper for unescaping
472 _UNESCAPE = re.compile(r"\\(.)")
473 _FQCN_TYPE_PREFIX_RE = re.compile(r'^([^.]+\.[^.]+\.[^#]+)#([a-z]+):(.*)$')
474 _IGNORE_MARKER = 'ignore:'
475
476 # rst specific
477 _RST_NOTE = re.compile(r".. note::")
478 _RST_SEEALSO = re.compile(r".. seealso::")
479 _RST_ROLES = re.compile(r":\w+?:`")
480 _RST_DIRECTIVES = re.compile(r".. \w+?::")
481
482 def __init__(self, args):
483
484 super(DocCLI, self).__init__(args)
485 self.plugin_list = set()
486
487 @staticmethod
488 def _tty_ify_sem_simle(matcher):
489 text = DocCLI._UNESCAPE.sub(r'\1', matcher.group(1))
490 return f"`{text}'"
491
492 @staticmethod
493 def _tty_ify_sem_complex(matcher):
494 text = DocCLI._UNESCAPE.sub(r'\1', matcher.group(1))
495 value = None
496 if '=' in text:
497 text, value = text.split('=', 1)
498 m = DocCLI._FQCN_TYPE_PREFIX_RE.match(text)
499 if m:
500 plugin_fqcn = m.group(1)
501 plugin_type = m.group(2)
502 text = m.group(3)
503 elif text.startswith(DocCLI._IGNORE_MARKER):
504 text = text[len(DocCLI._IGNORE_MARKER):]
505 plugin_fqcn = plugin_type = ''
506 else:
507 plugin_fqcn = plugin_type = ''
508 entrypoint = None
509 if ':' in text:
510 entrypoint, text = text.split(':', 1)
511 if value is not None:
512 text = f"{text}={value}"
513 if plugin_fqcn and plugin_type:
514 plugin_suffix = '' if plugin_type in ('role', 'module', 'playbook') else ' plugin'
515 plugin = f"{plugin_type}{plugin_suffix} {plugin_fqcn}"
516 if plugin_type == 'role' and entrypoint is not None:
517 plugin = f"{plugin}, {entrypoint} entrypoint"
518 return f"`{text}' (of {plugin})"
519 return f"`{text}'"
520
521 @classmethod
522 def tty_ify(cls, text):
523
524 # general formatting
525 t = cls._ITALIC.sub(_format(r"\1", 'UNDERLINE'), text) # no ascii code for this
526 t = cls._BOLD.sub(_format(r"\1", 'BOLD'), t)
527 t = cls._MODULE.sub(_format(r"\1", 'MODULE'), t) # M(word) => [word]
528 t = cls._URL.sub(r"\1", t) # U(word) => word
529 t = cls._LINK.sub(r"\1 <\2>", t) # L(word, url) => word <url>
530
531 t = cls._PLUGIN.sub(_format("[" + r"\1" + "]", 'PLUGIN'), t) # P(word#type) => [word]
532
533 t = cls._REF.sub(_format(r"\1", 'REF'), t) # R(word, sphinx-ref) => word
534 t = cls._CONST.sub(_format(r"`\1'", 'CONSTANT'), t)
535 t = cls._SEM_OPTION_NAME.sub(cls._tty_ify_sem_complex, t) # O(expr)
536 t = cls._SEM_OPTION_VALUE.sub(cls._tty_ify_sem_simle, t) # V(expr)
537 t = cls._SEM_ENV_VARIABLE.sub(cls._tty_ify_sem_simle, t) # E(expr)
538 t = cls._SEM_RET_VALUE.sub(cls._tty_ify_sem_complex, t) # RV(expr)
539 t = cls._RULER.sub("\n{0}\n".format("-" * 13), t) # HORIZONTALLINE => -------
540
541 # remove rst
542 t = cls._RST_SEEALSO.sub(r"See also:", t) # seealso to See also:
543 t = cls._RST_NOTE.sub(_format(r"Note:", 'bold'), t) # .. note:: to note:
544 t = cls._RST_ROLES.sub(r"`", t) # remove :ref: and other tags, keep tilde to match ending one
545 t = cls._RST_DIRECTIVES.sub(r"", t) # remove .. stuff:: in general
546
547 # handle docsite refs
548 # U(word) => word
549 t = re.sub(cls._URL, lambda m: _format(r"%s" % _doclink(m.group(1)), 'LINK'), t)
550 # L(word, url) => word <url>
551 t = re.sub(cls._LINK, lambda m: r"%s <%s>" % (m.group(1), _format(_doclink(m.group(2)), 'LINK')), t)
552
553 return t
554
555 def init_parser(self):
556
557 coll_filter = 'A supplied argument will be used for filtering, can be a namespace or full collection name.'
558
559 super(DocCLI, self).init_parser(
560 desc="plugin documentation tool",
561 epilog="See man pages for Ansible CLI options or website for tutorials https://docs.ansible.com"
562 )
563 opt_help.add_module_options(self.parser)
564 opt_help.add_basedir_options(self.parser)
565
566 # targets
567 self.parser.add_argument('args', nargs='*', help='Plugin', metavar='plugin')
568
569 self.parser.add_argument("-t", "--type", action="store", default='module', dest='type',
570 help='Choose which plugin type (defaults to "module"). '
571 'Available plugin types are : {0}'.format(TARGET_OPTIONS),
572 choices=TARGET_OPTIONS)
573
574 # formatting
575 self.parser.add_argument("-j", "--json", action="store_true", default=False, dest='json_format',
576 help='Change output into json format.')
577
578 # TODO: warn if not used with -t roles
579 # role-specific options
580 self.parser.add_argument("-r", "--roles-path", dest='roles_path', default=C.DEFAULT_ROLES_PATH,
581 type=opt_help.unfrack_path(pathsep=True),
582 action=opt_help.PrependListAction,
583 help='The path to the directory containing your roles.')
584
585 # exclusive modifiers
586 exclusive = self.parser.add_mutually_exclusive_group()
587
588 # TODO: warn if not used with -t roles
589 exclusive.add_argument("-e", "--entry-point", dest="entry_point",
590 help="Select the entry point for role(s).")
591
592 # TODO: warn with --json as it is incompatible
593 exclusive.add_argument("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
594 help='Show playbook snippet for these plugin types: %s' % ', '.join(SNIPPETS))
595
596 # TODO: warn when arg/plugin is passed
597 exclusive.add_argument("-F", "--list_files", action="store_true", default=False, dest="list_files",
598 help='Show plugin names and their source files without summaries (implies --list). %s' % coll_filter)
599 exclusive.add_argument("-l", "--list", action="store_true", default=False, dest='list_dir',
600 help='List available plugins. %s' % coll_filter)
601 exclusive.add_argument("--metadata-dump", action="store_true", default=False, dest='dump',
602 help='**For internal use only** Dump json metadata for all entries, ignores other options.')
603
604 # generic again
605 self.parser.add_argument("--no-fail-on-errors", action="store_true", default=False, dest='no_fail_on_errors',
606 help='**For internal use only** Only used for --metadata-dump. '
607 'Do not fail on errors. Report the error message in the JSON instead.')
608
609 def post_process_args(self, options):
610 options = super(DocCLI, self).post_process_args(options)
611
612 display.verbosity = options.verbosity
613
614 return options
615
616 def display_plugin_list(self, results):
617
618 # format for user
619 displace = max(len(x) for x in results.keys())
620 linelimit = display.columns - displace - 5
621 text = []
622 deprecated = []
623
624 # format display per option
625 if context.CLIARGS['list_files']:
626 # list plugin file names
627 for plugin in sorted(results.keys()):
628 filename = to_native(results[plugin])
629
630 # handle deprecated for builtin/legacy
631 pbreak = plugin.split('.')
632 if pbreak[-1].startswith('_') and pbreak[0] == 'ansible' and pbreak[1] in ('builtin', 'legacy'):
633 pbreak[-1] = pbreak[-1][1:]
634 plugin = '.'.join(pbreak)
635 deprecated.append("%-*s %-*.*s" % (displace, plugin, linelimit, len(filename), filename))
636 else:
637 text.append("%-*s %-*.*s" % (displace, plugin, linelimit, len(filename), filename))
638 else:
639 # list plugin names and short desc
640 for plugin in sorted(results.keys()):
641 desc = DocCLI.tty_ify(results[plugin])
642
643 if len(desc) > linelimit:
644 desc = desc[:linelimit] + '...'
645
646 pbreak = plugin.split('.')
647 # TODO: add mark for deprecated collection plugins
648 if pbreak[-1].startswith('_') and plugin.startswith(('ansible.builtin.', 'ansible.legacy.')):
649 # Handle deprecated ansible.builtin plugins
650 pbreak[-1] = pbreak[-1][1:]
651 plugin = '.'.join(pbreak)
652 deprecated.append("%-*s %-*.*s" % (displace, plugin, linelimit, len(desc), desc))
653 else:
654 text.append("%-*s %-*.*s" % (displace, plugin, linelimit, len(desc), desc))
655
656 if len(deprecated) > 0:
657 text.append("\nDEPRECATED:")
658 text.extend(deprecated)
659
660 # display results
661 DocCLI.pager("\n".join(text))
662
663 def _display_available_roles(self, list_json):
664 """Display all roles we can find with a valid argument specification.
665
666 Output is: fqcn role name, entry point, short description
667 """
668 roles = list(list_json.keys())
669 entry_point_names = set() # to find max len
670 for role in roles:
671 for entry_point in list_json[role]['entry_points'].keys():
672 entry_point_names.add(entry_point)
673
674 max_role_len = 0
675 max_ep_len = 0
676
677 if entry_point_names:
678 max_ep_len = max(len(x) for x in entry_point_names)
679
680 linelimit = display.columns - max_role_len - max_ep_len - 5
681 text = []
682
683 for role in sorted(roles):
684 if list_json[role]['entry_points']:
685 text.append('%s:' % role)
686 text.append(' specs:')
687 for entry_point, desc in list_json[role]['entry_points'].items():
688 if len(desc) > linelimit:
689 desc = desc[:linelimit] + '...'
690 text.append(" %-*s: %s" % (max_ep_len, entry_point, desc))
691 else:
692 text.append('%s' % role)
693
694 # display results
695 DocCLI.pager("\n".join(text))
696
697 def _display_role_doc(self, role_json):
698 roles = list(role_json.keys())
699 text = []
700 for role in roles:
701 try:
702 if 'error' in role_json[role]:
703 display.warning("Skipping role '%s' due to: %s" % (role, role_json[role]['error']), True)
704 continue
705 text += self.get_role_man_text(role, role_json[role])
706 except AnsibleError as ex:
707 # TODO: warn and skip role?
708 raise AnsibleParserError(f"Error extracting role docs from {role!r}.") from ex
709
710 # display results
711 DocCLI.pager("\n".join(text))
712
713 @staticmethod
714 def _list_keywords():
715 return yaml.load(pkgutil.get_data('ansible', 'keyword_desc.yml'), Loader=AnsibleInstrumentedLoader)
716
717 @staticmethod
718 def _get_keywords_docs(keys):
719
720 data = {}
721 descs = DocCLI._list_keywords()
722 for key in keys:
723
724 if key.startswith('with_'):
725 # simplify loops, dont want to handle every with_<lookup> combo
726 keyword = 'loop'
727 elif key == 'async':
728 # cause async became reserved in python we had to rename internally
729 keyword = 'async_val'
730 else:
731 keyword = key
732
733 try:
734 # if no desc, typeerror raised ends this block
735 kdata = {'description': descs[key]}
736
737 # get playbook objects for keyword and use first to get keyword attributes
738 kdata['applies_to'] = []
739 for pobj in PB_OBJECTS:
740 if pobj not in PB_LOADED:
741 obj_class = 'ansible.playbook.%s' % pobj.lower()
742 loaded_class = importlib.import_module(obj_class)
743 PB_LOADED[pobj] = getattr(loaded_class, pobj, None)
744
745 if keyword in PB_LOADED[pobj].fattributes:
746 kdata['applies_to'].append(pobj)
747
748 # we should only need these once
749 if 'type' not in kdata:
750
751 fa = PB_LOADED[pobj].fattributes.get(keyword)
752 if getattr(fa, 'private'):
753 kdata = {}
754 raise KeyError
755
756 kdata['type'] = getattr(fa, 'isa', 'string')
757
758 if keyword.endswith('when') or keyword in ('until',):
759 # TODO: make this a field attribute property,
760 # would also helps with the warnings on {{}} stacking
761 kdata['template'] = 'implicit'
762 elif getattr(fa, 'static'):
763 kdata['template'] = 'static'
764 else:
765 kdata['template'] = 'explicit'
766
767 # those that require no processing
768 for visible in ('alias', 'priority'):
769 kdata[visible] = getattr(fa, visible)
770
771 # remove None keys
772 for k in list(kdata.keys()):
773 if kdata[k] is None:
774 del kdata[k]
775
776 data[key] = kdata
777
778 except (AttributeError, KeyError) as ex:
779 display.error_as_warning(f'Skipping invalid keyword {key!r}.', ex)
780
781 return data
782
783 def _get_collection_filter(self):
784
785 coll_filter = None
786 if len(context.CLIARGS['args']) >= 1:
787 coll_filter = context.CLIARGS['args']
788 for coll_name in coll_filter:
789 if not AnsibleCollectionRef.is_valid_collection_name(coll_name):
790 raise AnsibleError('Invalid collection name (must be of the form namespace.collection): {0}'.format(coll_name))
791
792 return coll_filter
793
794 def _list_plugins(self, plugin_type, content):
795 DocCLI._prep_loader(plugin_type)
796
797 coll_filter = self._get_collection_filter()
798 plugins = _list_plugins_with_info(plugin_type, coll_filter)
799
800 # Remove the internal ansible._protomatter plugins if getting all plugins
801 if not coll_filter:
802 plugins = {k: v for k, v in plugins.items() if not k.startswith('ansible._protomatter.')}
803
804 # get appropriate content depending on option
805 if content == 'dir':
806 results = self._get_plugin_list_descriptions(plugins)
807 elif content == 'files':
808 results = {k: v.path for k, v in plugins.items()}
809 else:
810 results = {k: {} for k in plugins.keys()}
811 self.plugin_list = set() # reset for next iteration
812
813 return results
814
815 def _get_plugins_docs(self, plugin_type: str, names: collections.abc.Iterable[str], fail_ok: bool = False, fail_on_errors: bool = True) -> dict[str, dict]:
816 loader = DocCLI._prep_loader(plugin_type)
817
818 if plugin_type in ('filter', 'test'):
819 jinja2_builtins = _jinja_plugins.get_jinja_builtin_plugin_descriptions(plugin_type)
820 jinja2_builtins.update({name.split('.')[-1]: value for name, value in jinja2_builtins.items()}) # add short-named versions for lookup
821 else:
822 jinja2_builtins = {}
823
824 # get the docs for plugins in the command line list
825 plugin_docs = {}
826 for plugin in names:
827 doc: dict[str, t.Any] = {}
828 try:
829 doc, plainexamples, returndocs, metadata = self._get_plugin_docs_with_jinja2_builtins(
830 plugin,
831 plugin_type,
832 loader,
833 fragment_loader,
834 jinja2_builtins,
835 )
836 except AnsiblePluginNotFound as e:
837 display.warning(to_native(e))
838 continue
839 except Exception as ex:
840 msg = "Missing documentation (or could not parse documentation)"
841
842 if not fail_on_errors:
843 plugin_docs[plugin] = {'error': f'{msg}: {ex}.'}
844 continue
845
846 msg = f"{plugin_type} {plugin} {msg}"
847
848 if fail_ok:
849 display.warning(f'{msg}: {ex}')
850 else:
851 raise AnsibleError(f'{msg}.') from ex
852
853 if not doc:
854 # The doc section existed but was empty
855 if not fail_on_errors:
856 plugin_docs[plugin] = {'error': 'No valid documentation found'}
857 continue
858
859 docs = DocCLI._combine_plugin_doc(plugin, plugin_type, doc, plainexamples, returndocs, metadata)
860 if not fail_on_errors:
861 # Check whether JSON serialization would break
862 try:
863 _json.json_dumps_formatted(docs)
864 except Exception as ex: # pylint:disable=broad-except
865 plugin_docs[plugin] = {'error': f'Cannot serialize documentation as JSON: {ex}'}
866 continue
867
868 plugin_docs[plugin] = docs
869
870 return plugin_docs
871
872 def _get_plugin_docs_with_jinja2_builtins(
873 self,
874 plugin_name: str,
875 plugin_type: str,
876 loader: t.Any,
877 fragment_loader: t.Any,
878 jinja_builtins: dict[str, str],
879 ) -> tuple[dict, str | None, dict | None, dict | None]:
880 try:
881 return get_plugin_docs(plugin_name, plugin_type, loader, fragment_loader, (context.CLIARGS['verbosity'] > 0))
882 except Exception:
883 if (desc := jinja_builtins.get(plugin_name, ...)) is not ...:
884 short_name = plugin_name.split('.')[-1]
885 long_name = f'ansible.builtin.{short_name}'
886 # Dynamically build a doc stub for any Jinja2 builtin plugin we haven't
887 # explicitly documented.
888 doc = dict(
889 collection='ansible.builtin',
890 plugin_name=long_name,
891 filename='',
892 short_description=desc,
893 description=[
894 desc,
895 f"This is the Jinja builtin {plugin_type} plugin {short_name!r}.",
896 f"See: U(https://jinja.palletsprojects.com/en/stable/templates/#jinja-{plugin_type}s.{short_name})",
897 ],
898 )
899
900 return doc, None, None, None
901
902 raise
903
904 def _get_roles_path(self):
905 """
906 Add any 'roles' subdir in playbook dir to the roles search path.
907 And as a last resort, add the playbook dir itself. Order being:
908 - 'roles' subdir of playbook dir
909 - DEFAULT_ROLES_PATH (default in cliargs)
910 - playbook dir (basedir)
911 NOTE: This matches logic in RoleDefinition._load_role_path() method.
912 """
913 roles_path = context.CLIARGS['roles_path']
914 if context.CLIARGS['basedir'] is not None:
915 subdir = os.path.join(context.CLIARGS['basedir'], "roles")
916 if os.path.isdir(subdir):
917 roles_path = (subdir,) + roles_path
918 roles_path = roles_path + (context.CLIARGS['basedir'],)
919 return roles_path
920
921 @staticmethod
922 def _prep_loader(plugin_type):
923 """ return a plugint type specific loader """
924 loader = getattr(plugin_loader, '%s_loader' % plugin_type)
925
926 # add to plugin paths from command line
927 if context.CLIARGS['basedir'] is not None:
928 loader.add_directory(context.CLIARGS['basedir'], with_subdir=True)
929
930 if context.CLIARGS['module_path']:
931 for path in context.CLIARGS['module_path']:
932 if path:
933 loader.add_directory(path)
934
935 # save only top level paths for errors
936 loader._paths = None # reset so we can use subdirs later
937
938 return loader
939
940 def run(self):
941
942 super(DocCLI, self).run()
943
944 basedir = context.CLIARGS['basedir']
945 plugin_type = context.CLIARGS['type'].lower()
946 do_json = context.CLIARGS['json_format'] or context.CLIARGS['dump']
947 listing = context.CLIARGS['list_files'] or context.CLIARGS['list_dir']
948 no_fail = bool(not context.CLIARGS['no_fail_on_errors'])
949
950 if context.CLIARGS['list_files']:
951 content = 'files'
952 elif context.CLIARGS['list_dir']:
953 content = 'dir'
954 else:
955 content = None
956
957 docs = {}
958
959 if basedir:
960 AnsibleCollectionConfig.playbook_paths = basedir
961
962 if plugin_type not in TARGET_OPTIONS:
963 raise AnsibleOptionsError("Unknown or undocumentable plugin type: %s" % plugin_type)
964
965 if context.CLIARGS['dump']:
966 # we always dump all types, ignore restrictions
967 ptypes = TARGET_OPTIONS
968 docs['all'] = {}
969 for ptype in ptypes:
970
971 if ptype == 'role':
972 roles = self._create_role_list(fail_on_errors=no_fail)
973 docs['all'][ptype] = self._create_role_doc(roles.keys(), context.CLIARGS['entry_point'], fail_on_errors=no_fail)
974 elif ptype == 'keyword':
975 names = DocCLI._list_keywords()
976 docs['all'][ptype] = DocCLI._get_keywords_docs(names.keys())
977 else:
978 plugin_names = self._list_plugins(ptype, None)
979 docs['all'][ptype] = self._get_plugins_docs(ptype, plugin_names, fail_ok=(ptype in ('test', 'filter')), fail_on_errors=no_fail)
980 # reset list after each type to avoid pollution
981 elif listing:
982 if plugin_type == 'keyword':
983 docs = DocCLI._list_keywords()
984 elif plugin_type == 'role':
985 docs = self._create_role_list(fail_on_errors=False)
986 else:
987 docs = self._list_plugins(plugin_type, content)
988 else:
989 # here we require a name
990 if len(context.CLIARGS['args']) == 0:
991 raise AnsibleOptionsError("Missing name(s), incorrect options passed for detailed documentation.")
992
993 if plugin_type == 'keyword':
994 docs = DocCLI._get_keywords_docs(context.CLIARGS['args'])
995 elif plugin_type == 'role':
996 docs = self._create_role_doc(context.CLIARGS['args'], context.CLIARGS['entry_point'], fail_on_errors=no_fail)
997 else:
998 # display specific plugin docs
999 docs = self._get_plugins_docs(plugin_type, context.CLIARGS['args'])
1000
1001 # Display the docs
1002 if do_json:
1003 jdump(docs)
1004 else:
1005 text = []
1006 if plugin_type in C.DOCUMENTABLE_PLUGINS:
1007 if listing and docs:
1008 self.display_plugin_list(docs)
1009 elif context.CLIARGS['show_snippet']:
1010 if plugin_type not in SNIPPETS:
1011 raise AnsibleError('Snippets are only available for the following plugin'
1012 ' types: %s' % ', '.join(SNIPPETS))
1013
1014 for plugin, doc_data in docs.items():
1015 try:
1016 textret = DocCLI.format_snippet(plugin, plugin_type, doc_data['doc'])
1017 except ValueError as e:
1018 display.warning("Unable to construct a snippet for"
1019 " '{0}': {1}".format(plugin, to_text(e)))
1020 else:
1021 text.append(textret)
1022 else:
1023 # Some changes to how plain text docs are formatted
1024 for plugin, doc_data in docs.items():
1025
1026 textret = DocCLI.format_plugin_doc(plugin, plugin_type,
1027 doc_data['doc'], doc_data['examples'],
1028 doc_data['return'], doc_data['metadata'])
1029 if textret:
1030 text.append(textret)
1031 else:
1032 display.warning("No valid documentation was retrieved from '%s'" % plugin)
1033
1034 elif plugin_type == 'role':
1035 if context.CLIARGS['list_dir'] and docs:
1036 self._display_available_roles(docs)
1037 elif docs:
1038 self._display_role_doc(docs)
1039
1040 elif docs:
1041 text = DocCLI.tty_ify(DocCLI._dump_yaml(docs))
1042
1043 if text:
1044 DocCLI.pager(''.join(text))
1045
1046 return 0
1047
1048 @staticmethod
1049 def get_all_plugins_of_type(plugin_type):
1050 loader = getattr(plugin_loader, '%s_loader' % plugin_type)
1051 paths = loader._get_paths_with_context()
1052 plugins = []
1053 for path_context in paths:
1054 plugins += _list_plugins_with_info(plugin_type).keys()
1055 return sorted(plugins)
1056
1057 @staticmethod
1058 def get_plugin_metadata(plugin_type, plugin_name):
1059 # if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
1060 loader = getattr(plugin_loader, '%s_loader' % plugin_type)
1061 result = loader.find_plugin_with_context(plugin_name, mod_type='.py', ignore_deprecated=True, check_aliases=True)
1062 if not result.resolved:
1063 raise AnsibleError("unable to load {0} plugin named {1} ".format(plugin_type, plugin_name))
1064 filename = result.plugin_resolved_path
1065 collection_name = result.plugin_resolved_collection
1066
1067 try:
1068 doc, __, __, __ = get_docstring(
1069 filename=filename,
1070 fragment_loader=fragment_loader,
1071 verbose=(context.CLIARGS['verbosity'] > 0),
1072 collection_name=collection_name,
1073 plugin_type=plugin_type,
1074 )
1075 except Exception as ex:
1076 raise AnsibleError(f"{plugin_type} {plugin_name} at {filename!r} has a documentation formatting error or is missing documentation.") from ex
1077
1078 if doc is None:
1079 # Removed plugins don't have any documentation
1080 return None
1081
1082 return dict(
1083 name=plugin_name,
1084 namespace=DocCLI.namespace_from_plugin_filepath(filename, plugin_name, loader.package_path),
1085 description=doc.get('short_description', "UNKNOWN"),
1086 version_added=doc.get('version_added', "UNKNOWN")
1087 )
1088
1089 @staticmethod
1090 def namespace_from_plugin_filepath(filepath, plugin_name, basedir):
1091 if not basedir.endswith('/'):
1092 basedir += '/'
1093 rel_path = filepath.replace(basedir, '')
1094 extension_free = os.path.splitext(rel_path)[0]
1095 namespace_only = extension_free.rsplit(plugin_name, 1)[0].strip('/_')
1096 clean_ns = namespace_only.replace('/', '.')
1097 if clean_ns == '':
1098 clean_ns = None
1099
1100 return clean_ns
1101
1102 @staticmethod
1103 def _combine_plugin_doc(plugin, plugin_type, doc, plainexamples, returndocs, metadata):
1104 # generate extra data
1105 if plugin_type == 'module':
1106 # is there corresponding action plugin?
1107 if plugin in action_loader:
1108 doc['has_action'] = True
1109 else:
1110 doc['has_action'] = False
1111
1112 # return everything as one dictionary
1113 return {'doc': doc, 'examples': plainexamples, 'return': returndocs, 'metadata': metadata}
1114
1115 @staticmethod
1116 def format_snippet(plugin, plugin_type, doc):
1117 """ return heavily commented plugin use to insert into play """
1118 if plugin_type == 'inventory' and doc.get('options', {}).get('plugin'):
1119 # these do not take a yaml config that we can write a snippet for
1120 raise ValueError('The {0} inventory plugin does not take YAML type config source'
1121 ' that can be used with the "auto" plugin so a snippet cannot be'
1122 ' created.'.format(plugin))
1123
1124 text = []
1125
1126 if plugin_type == 'lookup':
1127 text = _do_lookup_snippet(doc)
1128
1129 elif 'options' in doc:
1130 text = _do_yaml_snippet(doc)
1131
1132 text.append('')
1133 return "\n".join(text)
1134
1135 @staticmethod
1136 def format_plugin_doc(plugin, plugin_type, doc, plainexamples, returndocs, metadata):
1137 collection_name = doc['collection']
1138
1139 # TODO: do we really want this?
1140 # add_collection_to_versions_and_dates(doc, '(unknown)', is_module=(plugin_type == 'module'))
1141 # remove_current_collection_from_versions_and_dates(doc, collection_name, is_module=(plugin_type == 'module'))
1142 # remove_current_collection_from_versions_and_dates(
1143 # returndocs, collection_name, is_module=(plugin_type == 'module'), return_docs=True)
1144
1145 # assign from other sections
1146 doc['plainexamples'] = plainexamples
1147 doc['returndocs'] = returndocs
1148 doc['metadata'] = metadata
1149
1150 try:
1151 text = DocCLI.get_man_text(doc, collection_name, plugin_type)
1152 except Exception as ex:
1153 raise AnsibleError(f"Unable to retrieve documentation from {plugin!r}.") from ex
1154
1155 return text
1156
1157 def _get_plugin_list_descriptions(self, plugins: dict[str, _PluginDocMetadata]) -> dict[str, str]:
1158
1159 descs = {}
1160 for plugin, plugin_info in plugins.items():
1161 # TODO: move to plugin itself i.e: plugin.get_desc()
1162 doc = None
1163
1164 docerror = None
1165 if plugin_info.path:
1166 filename = Path(to_native(plugin_info.path))
1167 try:
1168 doc = read_docstub(filename)
1169 except Exception as e:
1170 docerror = e
1171
1172 # plugin file was empty or had error, lets try other options
1173 if doc is None:
1174 # handle test/filters that are in file with diff name
1175 base = plugin.split('.')[-1]
1176 basefile = filename.with_name(base + filename.suffix)
1177 for extension in C.DOC_EXTENSIONS:
1178 docfile = basefile.with_suffix(extension)
1179 try:
1180 if docfile.exists():
1181 doc = read_docstub(docfile)
1182 except Exception as e:
1183 docerror = e
1184
1185 # Do a final fallback to see if the plugin is a shadowed Jinja2 plugin
1186 # without any explicit documentation.
1187 if doc is None and plugin_info.jinja_builtin_short_description:
1188 descs[plugin] = plugin_info.jinja_builtin_short_description
1189 continue
1190
1191 if docerror:
1192 display.error_as_warning(f"{plugin} has a documentation formatting error.", exception=docerror)
1193 continue
1194
1195 if not doc or not isinstance(doc, dict):
1196 desc = 'UNDOCUMENTED'
1197 else:
1198 desc = doc.get('short_description', 'INVALID SHORT DESCRIPTION').strip()
1199
1200 descs[plugin] = desc
1201
1202 return descs
1203
1204 @staticmethod
1205 def print_paths(finder):
1206 """ Returns a string suitable for printing of the search path """
1207
1208 # Uses a list to get the order right
1209 ret = []
1210 for i in finder._get_paths(subdirs=False):
1211 i = to_text(i, errors='surrogate_or_strict')
1212 if i not in ret:
1213 ret.append(i)
1214 return os.pathsep.join(ret)
1215
1216 @staticmethod
1217 def _dump_yaml(struct, flow_style=False):
1218 return yaml_dump(struct, default_flow_style=flow_style, default_style="''", Dumper=AnsibleDumper).rstrip('\n')
1219
1220 @staticmethod
1221 def _indent_lines(text, indent):
1222 return DocCLI.tty_ify('\n'.join([indent + line for line in text.split('\n')]))
1223
1224 @staticmethod
1225 def _format_version_added(version_added, version_added_collection=None):
1226 if version_added_collection == 'ansible.builtin':
1227 version_added_collection = 'ansible-core'
1228 # In ansible-core, version_added can be 'historical'
1229 if version_added == 'historical':
1230 return 'historical'
1231 if version_added_collection:
1232 version_added = '%s of %s' % (version_added, version_added_collection)
1233 return 'version %s' % (version_added, )
1234
1235 @staticmethod
1236 def warp_fill(text, limit, initial_indent='', subsequent_indent='', initial_extra=0, **kwargs):
1237 result = []
1238 for paragraph in text.split('\n\n'):
1239 wrapped = textwrap.fill(paragraph, limit, initial_indent=initial_indent + ' ' * initial_extra, subsequent_indent=subsequent_indent,
1240 break_on_hyphens=False, break_long_words=False, drop_whitespace=True, **kwargs)
1241 if initial_extra and wrapped.startswith(' ' * initial_extra):
1242 wrapped = wrapped[initial_extra:]
1243 result.append(wrapped)
1244 initial_indent = subsequent_indent
1245 initial_extra = 0
1246 return '\n'.join(result)
1247
1248 @staticmethod
1249 def add_fields(text, fields, limit, opt_indent, return_values=False, base_indent='', man=False):
1250
1251 for o in sorted(fields):
1252 # Create a copy so we don't modify the original (in case YAML anchors have been used)
1253 opt = dict(fields[o])
1254
1255 # required is used as indicator and removed
1256 required = opt.pop('required', False)
1257 if not isinstance(required, bool):
1258 raise AnsibleError("Incorrect value for 'Required', a boolean is needed.: %s" % required)
1259
1260 opt_leadin = ' '
1261 key = ''
1262 if required:
1263 if C.ANSIBLE_NOCOLOR:
1264 opt_leadin = "="
1265 key = "%s%s %s" % (base_indent, opt_leadin, _format(o, 'bold', 'red'))
1266 else:
1267 if C.ANSIBLE_NOCOLOR:
1268 opt_leadin = "-"
1269 key = "%s%s %s" % (base_indent, opt_leadin, _format(o, 'yellow'))
1270
1271 # description is specifically formatted and can either be string or list of strings
1272 if 'description' not in opt:
1273 raise AnsibleError("All (sub-)options and return values must have a 'description' field", obj=o)
1274 text.append('')
1275
1276 # TODO: push this to top of for and sort by size, create indent on largest key?
1277 inline_indent = ' ' * max((len(opt_indent) - len(o)) - len(base_indent), 2)
1278 extra_indent = base_indent + ' ' * (len(o) + 3)
1279 sub_indent = inline_indent + extra_indent
1280 if is_sequence(opt['description']):
1281 for entry_idx, entry in enumerate(opt['description'], 1):
1282 if not isinstance(entry, str):
1283 raise AnsibleError("Expected string in description of %s at index %s, got %s" % (o, entry_idx, type(entry)))
1284 if entry_idx == 1:
1285 text.append(key + DocCLI.warp_fill(DocCLI.tty_ify(entry), limit,
1286 initial_indent=inline_indent, subsequent_indent=sub_indent, initial_extra=len(extra_indent)))
1287 else:
1288 text.append(DocCLI.warp_fill(DocCLI.tty_ify(entry), limit, initial_indent=sub_indent, subsequent_indent=sub_indent))
1289 else:
1290 if not isinstance(opt['description'], str):
1291 raise AnsibleError("Expected string in description of %s, got %s" % (o, type(opt['description'])))
1292 text.append(key + DocCLI.warp_fill(DocCLI.tty_ify(opt['description']), limit,
1293 initial_indent=inline_indent, subsequent_indent=sub_indent, initial_extra=len(extra_indent)))
1294 del opt['description']
1295
1296 suboptions = []
1297 for subkey in ('options', 'suboptions', 'contains', 'spec'):
1298 if subkey in opt:
1299 suboptions.append((subkey, opt.pop(subkey)))
1300
1301 if not required and not return_values and 'default' not in opt:
1302 opt['default'] = None
1303
1304 # sanitize config items
1305 conf = {}
1306 for config in ('env', 'ini', 'yaml', 'vars', 'keyword'):
1307 if config in opt and opt[config]:
1308 # Create a copy so we don't modify the original (in case YAML anchors have been used)
1309 conf[config] = [dict(item) for item in opt.pop(config)]
1310 for ignore in DocCLI.IGNORE:
1311 for item in conf[config]:
1312 if display.verbosity > 0 and 'version_added' in item:
1313 item['added_in'] = DocCLI._format_version_added(item['version_added'], item.get('version_added_colleciton', 'ansible-core'))
1314 if ignore in item:
1315 del item[ignore]
1316
1317 # reformat cli options
1318 if 'cli' in opt and opt['cli']:
1319 conf['cli'] = []
1320 for cli in opt['cli']:
1321 if 'option' not in cli:
1322 conf['cli'].append({'name': cli['name'], 'option': '--%s' % cli['name'].replace('_', '-')})
1323 else:
1324 conf['cli'].append(cli)
1325 del opt['cli']
1326
1327 # add custom header for conf
1328 if conf:
1329 text.append(DocCLI._indent_lines(DocCLI._dump_yaml({'set_via': conf}), opt_indent))
1330
1331 # these we handle at the end of generic option processing
1332 version_added = opt.pop('version_added', None)
1333 version_added_collection = opt.pop('version_added_collection', None)
1334
1335 # general processing for options
1336 for k in sorted(opt):
1337 if k.startswith('_'):
1338 continue
1339
1340 if is_sequence(opt[k]):
1341 text.append(DocCLI._indent_lines('%s: %s' % (k, DocCLI._dump_yaml(opt[k], flow_style=True)), opt_indent))
1342 else:
1343 text.append(DocCLI._indent_lines(DocCLI._dump_yaml({k: opt[k]}), opt_indent))
1344
1345 if version_added and not man:
1346 text.append("%sadded in: %s" % (opt_indent, DocCLI._format_version_added(version_added, version_added_collection)))
1347
1348 for subkey, subdata in suboptions:
1349 text.append("%s%s:" % (opt_indent, subkey))
1350 DocCLI.add_fields(text, subdata, limit, opt_indent + ' ', return_values, opt_indent)
1351
1352 @staticmethod
1353 def _add_seealso(text: list[str], seealsos: list[dict[str, t.Any]], limit: int, opt_indent: str) -> None:
1354 for item in seealsos:
1355 if 'module' in item:
1356 text.append(DocCLI.warp_fill(DocCLI.tty_ify('Module %s' % item['module']),
1357 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1358 description = item.get('description')
1359 if description is None and item['module'].startswith('ansible.builtin.'):
1360 description = 'The official documentation on the %s module.' % item['module']
1361 if description is not None:
1362 text.append(DocCLI.warp_fill(DocCLI.tty_ify(description),
1363 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1364 if item['module'].startswith('ansible.builtin.'):
1365 relative_url = 'collections/%s_module.html' % item['module'].replace('.', '/', 2)
1366 text.append(DocCLI.warp_fill(DocCLI.tty_ify(get_versioned_doclink(relative_url)),
1367 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent))
1368 elif 'plugin' in item and 'plugin_type' in item:
1369 plugin_suffix = ' plugin' if item['plugin_type'] not in ('module', 'role') else ''
1370 text.append(DocCLI.warp_fill(DocCLI.tty_ify('%s%s %s' % (item['plugin_type'].title(), plugin_suffix, item['plugin'])),
1371 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1372 description = item.get('description')
1373 if description is None and item['plugin'].startswith('ansible.builtin.'):
1374 description = 'The official documentation on the %s %s%s.' % (item['plugin'], item['plugin_type'], plugin_suffix)
1375 if description is not None:
1376 text.append(DocCLI.warp_fill(DocCLI.tty_ify(description),
1377 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1378 if item['plugin'].startswith('ansible.builtin.'):
1379 relative_url = 'collections/%s_%s.html' % (item['plugin'].replace('.', '/', 2), item['plugin_type'])
1380 text.append(DocCLI.warp_fill(DocCLI.tty_ify(get_versioned_doclink(relative_url)),
1381 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent))
1382 elif 'name' in item and 'link' in item and 'description' in item:
1383 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['name']),
1384 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1385 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['description']),
1386 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1387 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['link']),
1388 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1389 elif 'ref' in item and 'description' in item:
1390 text.append(DocCLI.warp_fill(DocCLI.tty_ify('Ansible documentation [%s]' % item['ref']),
1391 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1392 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['description']),
1393 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1394 text.append(DocCLI.warp_fill(DocCLI.tty_ify(get_versioned_doclink('/#stq=%s&stp=1' % item['ref'])),
1395 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1396
1397 def get_role_man_text(self, role, role_json):
1398 """Generate text for the supplied role suitable for display.
1399
1400 This is similar to get_man_text(), but roles are different enough that we have
1401 a separate method for formatting their display.
1402
1403 :param role: The role name.
1404 :param role_json: The JSON for the given role as returned from _create_role_doc().
1405
1406 :returns: A array of text suitable for displaying to screen.
1407 """
1408 text = []
1409 opt_indent = " "
1410 pad = display.columns * 0.20
1411 limit = max(display.columns - int(pad), 70)
1412
1413 text.append("> ROLE: %s (%s)" % (_format(role, 'BOLD'), role_json.get('path')))
1414
1415 for entry_point in role_json['entry_points']:
1416 doc = role_json['entry_points'][entry_point]
1417 desc = ''
1418 if doc.get('short_description'):
1419 desc = "- %s" % (doc.get('short_description'))
1420 text.append('')
1421 text.append("ENTRY POINT: %s %s" % (_format(entry_point, "BOLD"), desc))
1422 text.append('')
1423
1424 if version_added := doc.pop('version_added', None):
1425 text.append(_format("ADDED IN:", 'bold') + " %s\n" % DocCLI._format_version_added(version_added))
1426
1427 if doc.get('description'):
1428 if isinstance(doc['description'], list):
1429 descs = doc['description']
1430 else:
1431 descs = [doc['description']]
1432 for desc in descs:
1433 text.append("%s" % DocCLI.warp_fill(DocCLI.tty_ify(desc), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
1434 text.append('')
1435
1436 if doc.get('options'):
1437 text.append(_format("Options", 'bold') + " (%s indicates it is required):" % ("=" if C.ANSIBLE_NOCOLOR else 'red'))
1438 DocCLI.add_fields(text, doc.pop('options'), limit, opt_indent)
1439
1440 if notes := doc.pop('notes', False):
1441 text.append("")
1442 text.append(_format("NOTES:", 'bold'))
1443 for note in notes:
1444 text.append(DocCLI.warp_fill(DocCLI.tty_ify(note), limit - 6,
1445 initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1446
1447 if seealso := doc.pop('seealso', False):
1448 text.append("")
1449 text.append(_format("SEE ALSO:", 'bold'))
1450 DocCLI._add_seealso(text, seealso, limit=limit, opt_indent=opt_indent)
1451
1452 # generic elements we will handle identically
1453 for k in ('author',):
1454 if k not in doc:
1455 continue
1456 text.append('')
1457 if isinstance(doc[k], str):
1458 text.append('%s: %s' % (k.upper(), DocCLI.warp_fill(DocCLI.tty_ify(doc[k]),
1459 limit - (len(k) + 2), subsequent_indent=opt_indent)))
1460 elif isinstance(doc[k], (list, tuple)):
1461 text.append('%s: %s' % (k.upper(), ', '.join(doc[k])))
1462 else:
1463 # use empty indent since this affects the start of the yaml doc, not it's keys
1464 text.append(DocCLI._indent_lines(DocCLI._dump_yaml({k.upper(): doc[k]}), ''))
1465
1466 if doc.get('examples', False):
1467 text.append('')
1468 text.append(_format("EXAMPLES:", 'bold'))
1469 if isinstance(doc['examples'], str):
1470 text.append(doc.pop('examples').strip())
1471 else:
1472 try:
1473 text.append(yaml_dump(doc.pop('examples'), indent=2, default_flow_style=False))
1474 except Exception as e:
1475 raise AnsibleParserError("Unable to parse examples section.") from e
1476
1477 return text
1478
1479 @staticmethod
1480 def get_man_text(doc, collection_name='', plugin_type=''):
1481 # Create a copy so we don't modify the original
1482 doc = dict(doc)
1483
1484 DocCLI.IGNORE = DocCLI.IGNORE + (context.CLIARGS['type'],)
1485 opt_indent = " "
1486 base_indent = " "
1487 text = []
1488 pad = display.columns * 0.20
1489 limit = max(display.columns - int(pad), 70)
1490
1491 text.append("> %s %s (%s)" % (plugin_type.upper(), _format(doc.pop('plugin_name'), 'bold'), doc.pop('filename') or 'Jinja2'))
1492
1493 if isinstance(doc['description'], list):
1494 descs = doc.pop('description')
1495 else:
1496 descs = [doc.pop('description')]
1497
1498 text.append('')
1499 for desc in descs:
1500 text.append(DocCLI.warp_fill(DocCLI.tty_ify(desc), limit, initial_indent=base_indent, subsequent_indent=base_indent))
1501
1502 if display.verbosity > 0:
1503 doc['added_in'] = DocCLI._format_version_added(doc.pop('version_added', 'historical'), doc.pop('version_added_collection', 'ansible-core'))
1504
1505 if doc.get('deprecated', False):
1506 text.append(_format("DEPRECATED: ", 'bold', 'DEP'))
1507 if isinstance(doc['deprecated'], dict):
1508 if 'removed_at_date' not in doc['deprecated'] and 'version' in doc['deprecated'] and 'removed_in' not in doc['deprecated']:
1509 doc['deprecated']['removed_in'] = doc['deprecated']['version']
1510 try:
1511 text.append('\t' + C.config.get_deprecated_msg_from_config(doc['deprecated'], True, collection_name=collection_name))
1512 except KeyError as e:
1513 raise AnsibleError("Invalid deprecation documentation structure.") from e
1514 else:
1515 text.append("%s" % doc['deprecated'])
1516 del doc['deprecated']
1517
1518 if doc.pop('has_action', False):
1519 text.append("")
1520 text.append(_format(" * note:", 'bold') + " This module has a corresponding action plugin.")
1521
1522 if doc.get('options', False):
1523 text.append("")
1524 text.append(_format("OPTIONS", 'bold') + " (%s indicates it is required):" % ("=" if C.ANSIBLE_NOCOLOR else 'red'))
1525 DocCLI.add_fields(text, doc.pop('options'), limit, opt_indent, man=(display.verbosity == 0))
1526
1527 if doc.get('attributes', False):
1528 text.append("")
1529 text.append(_format("ATTRIBUTES:", 'bold'))
1530 for k in doc['attributes'].keys():
1531 text.append('')
1532 text.append(DocCLI.warp_fill(DocCLI.tty_ify(_format('%s:' % k, 'UNDERLINE')), limit - 6, initial_indent=opt_indent,
1533 subsequent_indent=opt_indent))
1534 text.append(DocCLI._indent_lines(DocCLI._dump_yaml(doc['attributes'][k]), opt_indent))
1535 del doc['attributes']
1536
1537 if doc.get('notes', False):
1538 text.append("")
1539 text.append(_format("NOTES:", 'bold'))
1540 for note in doc['notes']:
1541 text.append(DocCLI.warp_fill(DocCLI.tty_ify(note), limit - 6,
1542 initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1543 del doc['notes']
1544
1545 if doc.get('seealso', False):
1546 text.append("")
1547 text.append(_format("SEE ALSO:", 'bold'))
1548 DocCLI._add_seealso(text, doc['seealso'], limit=limit, opt_indent=opt_indent)
1549 del doc['seealso']
1550
1551 if doc.get('requirements', False):
1552 text.append('')
1553 req = ", ".join(doc.pop('requirements'))
1554 text.append(_format("REQUIREMENTS:", 'bold') + "%s\n" % DocCLI.warp_fill(DocCLI.tty_ify(req), limit - 16, initial_indent=" ",
1555 subsequent_indent=opt_indent))
1556
1557 # Generic handler
1558 for k in sorted(doc):
1559 if not doc[k] or k in DocCLI.IGNORE:
1560 continue
1561 text.append('')
1562 header = _format(k.upper(), 'bold')
1563 if isinstance(doc[k], str):
1564 text.append('%s: %s' % (header, DocCLI.warp_fill(DocCLI.tty_ify(doc[k]), limit - (len(k) + 2), subsequent_indent=opt_indent)))
1565 elif isinstance(doc[k], (list, tuple)):
1566 text.append('%s: %s' % (header, ', '.join(doc[k])))
1567 else:
1568 # use empty indent since this affects the start of the yaml doc, not it's keys
1569 text.append('%s: ' % header + DocCLI._indent_lines(DocCLI._dump_yaml(doc[k]), ' ' * (len(k) + 2)))
1570 del doc[k]
1571
1572 if doc.get('plainexamples', False):
1573 text.append('')
1574 text.append(_format("EXAMPLES:", 'bold'))
1575 if isinstance(doc['plainexamples'], str):
1576 text.append(doc.pop('plainexamples').strip())
1577 else:
1578 try:
1579 text.append(yaml_dump(doc.pop('plainexamples'), indent=2, default_flow_style=False))
1580 except Exception as ex:
1581 raise AnsibleParserError("Unable to parse examples section.") from ex
1582
1583 if doc.get('returndocs', False):
1584 text.append('')
1585 text.append(_format("RETURN VALUES:", 'bold'))
1586 DocCLI.add_fields(text, doc.pop('returndocs'), limit, opt_indent, return_values=True, man=(display.verbosity == 0))
1587
1588 text.append('\n')
1589 return "\n".join(text)
1590
1591
1592 def _do_yaml_snippet(doc):
1593 text = []
1594
1595 mdesc = DocCLI.tty_ify(doc['short_description'])
1596 module = doc.get('module')
1597
1598 if module:
1599 # this is actually a usable task!
1600 text.append("- name: %s" % (mdesc))
1601 text.append(" %s:" % (module))
1602 else:
1603 # just a comment, hopefully useful yaml file
1604 text.append("# %s:" % doc.get('plugin', doc.get('name')))
1605
1606 pad = 29
1607 subdent = '# '.rjust(pad + 2)
1608 limit = display.columns - pad
1609
1610 for o in sorted(doc['options'].keys()):
1611 opt = doc['options'][o]
1612 if isinstance(opt['description'], str):
1613 desc = DocCLI.tty_ify(opt['description'])
1614 else:
1615 desc = DocCLI.tty_ify(" ".join(opt['description']))
1616
1617 required = opt.get('required', False)
1618 if not isinstance(required, bool):
1619 raise ValueError("Incorrect value for 'Required', a boolean is needed: %s" % required)
1620
1621 o = '%s:' % o
1622 if module:
1623 if required:
1624 desc = "(required) %s" % desc
1625 text.append(" %-20s # %s" % (o, DocCLI.warp_fill(desc, limit, subsequent_indent=subdent)))
1626 else:
1627 if required:
1628 default = '(required)'
1629 else:
1630 default = opt.get('default', 'None')
1631
1632 text.append("%s %-9s # %s" % (o, default, DocCLI.warp_fill(desc, limit, subsequent_indent=subdent, max_lines=3)))
1633
1634 return text
1635
1636
1637 def _do_lookup_snippet(doc):
1638 text = []
1639 snippet = "lookup('%s', " % doc.get('plugin', doc.get('name'))
1640 comment = []
1641
1642 for o in sorted(doc['options'].keys()):
1643
1644 opt = doc['options'][o]
1645 comment.append('# %s(%s): %s' % (o, opt.get('type', 'string'), opt.get('description', '')))
1646 if o in ('_terms', '_raw', '_list'):
1647 # these are 'list of arguments'
1648 snippet += '< %s >' % (o)
1649 continue
1650
1651 required = opt.get('required', False)
1652 if not isinstance(required, bool):
1653 raise ValueError("Incorrect value for 'Required', a boolean is needed: %s" % required)
1654
1655 if required:
1656 default = '<REQUIRED>'
1657 else:
1658 default = opt.get('default', 'None')
1659
1660 if opt.get('type') in ('string', 'str'):
1661 snippet += ", %s='%s'" % (o, default)
1662 else:
1663 snippet += ', %s=%s' % (o, default)
1664
1665 snippet += ")"
1666
1667 if comment:
1668 text.extend(comment)
1669 text.append('')
1670 text.append(snippet)
1671
1672 return text
1673
1674
1675 def main(args=None):
1676 DocCLI.cli_executor(args)
1677
1678
1679 if __name__ == '__main__':
1680 main()