Debian Codegraph @

bin/ansible-doc

raw symbols SCIP
1 #!/usr/bin/env python3
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('No metadata for role (%s) due to: %s' % (role, to_native(e)), True)
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('Skipping role (%s) due to: %s' % (role, argspec['error']), True)
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 '',
896 f"This is the Jinja builtin {plugin_type} plugin {short_name!r}.",
897 f"See: U(https://jinja.palletsprojects.com/en/stable/templates/#jinja-{plugin_type}s.{short_name})",
898 ],
899 )
900
901 return doc, None, None, None
902
903 raise
904
905 def _get_roles_path(self):
906 """
907 Add any 'roles' subdir in playbook dir to the roles search path.
908 And as a last resort, add the playbook dir itself. Order being:
909 - 'roles' subdir of playbook dir
910 - DEFAULT_ROLES_PATH (default in cliargs)
911 - playbook dir (basedir)
912 NOTE: This matches logic in RoleDefinition._load_role_path() method.
913 """
914 roles_path = context.CLIARGS['roles_path']
915 if context.CLIARGS['basedir'] is not None:
916 subdir = os.path.join(context.CLIARGS['basedir'], "roles")
917 if os.path.isdir(subdir):
918 roles_path = (subdir,) + roles_path
919 roles_path = roles_path + (context.CLIARGS['basedir'],)
920 return roles_path
921
922 @staticmethod
923 def _prep_loader(plugin_type):
924 """ return a plugint type specific loader """
925 loader = getattr(plugin_loader, '%s_loader' % plugin_type)
926
927 # add to plugin paths from command line
928 if context.CLIARGS['basedir'] is not None:
929 loader.add_directory(context.CLIARGS['basedir'], with_subdir=True)
930
931 if context.CLIARGS['module_path']:
932 for path in context.CLIARGS['module_path']:
933 if path:
934 loader.add_directory(path)
935
936 # save only top level paths for errors
937 loader._paths = None # reset so we can use subdirs later
938
939 return loader
940
941 def run(self):
942
943 super(DocCLI, self).run()
944
945 basedir = context.CLIARGS['basedir']
946 plugin_type = context.CLIARGS['type'].lower()
947 do_json = context.CLIARGS['json_format'] or context.CLIARGS['dump']
948 listing = context.CLIARGS['list_files'] or context.CLIARGS['list_dir']
949 no_fail = bool(not context.CLIARGS['no_fail_on_errors'])
950
951 if context.CLIARGS['list_files']:
952 content = 'files'
953 elif context.CLIARGS['list_dir']:
954 content = 'dir'
955 else:
956 content = None
957
958 docs = {}
959
960 if basedir:
961 AnsibleCollectionConfig.playbook_paths = basedir
962
963 if plugin_type not in TARGET_OPTIONS:
964 raise AnsibleOptionsError("Unknown or undocumentable plugin type: %s" % plugin_type)
965
966 if context.CLIARGS['dump']:
967 # we always dump all types, ignore restrictions
968 ptypes = TARGET_OPTIONS
969 docs['all'] = {}
970 for ptype in ptypes:
971
972 if ptype == 'role':
973 roles = self._create_role_list(fail_on_errors=no_fail)
974 docs['all'][ptype] = self._create_role_doc(roles.keys(), context.CLIARGS['entry_point'], fail_on_errors=no_fail)
975 elif ptype == 'keyword':
976 names = DocCLI._list_keywords()
977 docs['all'][ptype] = DocCLI._get_keywords_docs(names.keys())
978 else:
979 plugin_names = self._list_plugins(ptype, None)
980 docs['all'][ptype] = self._get_plugins_docs(ptype, plugin_names, fail_ok=(ptype in ('test', 'filter')), fail_on_errors=no_fail)
981 # reset list after each type to avoid pollution
982 elif listing:
983 if plugin_type == 'keyword':
984 docs = DocCLI._list_keywords()
985 elif plugin_type == 'role':
986 docs = self._create_role_list(fail_on_errors=False)
987 else:
988 docs = self._list_plugins(plugin_type, content)
989 else:
990 # here we require a name
991 if len(context.CLIARGS['args']) == 0:
992 raise AnsibleOptionsError("Missing name(s), incorrect options passed for detailed documentation.")
993
994 if plugin_type == 'keyword':
995 docs = DocCLI._get_keywords_docs(context.CLIARGS['args'])
996 elif plugin_type == 'role':
997 docs = self._create_role_doc(context.CLIARGS['args'], context.CLIARGS['entry_point'], fail_on_errors=no_fail)
998 else:
999 # display specific plugin docs
1000 docs = self._get_plugins_docs(plugin_type, context.CLIARGS['args'])
1001
1002 # Display the docs
1003 if do_json:
1004 jdump(docs)
1005 else:
1006 text = []
1007 if plugin_type in C.DOCUMENTABLE_PLUGINS:
1008 if listing and docs:
1009 self.display_plugin_list(docs)
1010 elif context.CLIARGS['show_snippet']:
1011 if plugin_type not in SNIPPETS:
1012 raise AnsibleError('Snippets are only available for the following plugin'
1013 ' types: %s' % ', '.join(SNIPPETS))
1014
1015 for plugin, doc_data in docs.items():
1016 try:
1017 textret = DocCLI.format_snippet(plugin, plugin_type, doc_data['doc'])
1018 except ValueError as e:
1019 display.warning("Unable to construct a snippet for"
1020 " '{0}': {1}".format(plugin, to_text(e)))
1021 else:
1022 text.append(textret)
1023 else:
1024 # Some changes to how plain text docs are formatted
1025 for plugin, doc_data in docs.items():
1026
1027 textret = DocCLI.format_plugin_doc(plugin, plugin_type,
1028 doc_data['doc'], doc_data['examples'],
1029 doc_data['return'], doc_data['metadata'])
1030 if textret:
1031 text.append(textret)
1032 else:
1033 display.warning("No valid documentation was retrieved from '%s'" % plugin)
1034
1035 elif plugin_type == 'role':
1036 if context.CLIARGS['list_dir'] and docs:
1037 self._display_available_roles(docs)
1038 elif docs:
1039 self._display_role_doc(docs)
1040
1041 elif docs:
1042 text = DocCLI.tty_ify(DocCLI._dump_yaml(docs))
1043
1044 if text:
1045 DocCLI.pager(''.join(text))
1046
1047 return 0
1048
1049 @staticmethod
1050 def get_all_plugins_of_type(plugin_type):
1051 loader = getattr(plugin_loader, '%s_loader' % plugin_type)
1052 paths = loader._get_paths_with_context()
1053 plugins = []
1054 for path_context in paths:
1055 plugins += _list_plugins_with_info(plugin_type).keys()
1056 return sorted(plugins)
1057
1058 @staticmethod
1059 def get_plugin_metadata(plugin_type, plugin_name):
1060 # if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
1061 loader = getattr(plugin_loader, '%s_loader' % plugin_type)
1062 result = loader.find_plugin_with_context(plugin_name, mod_type='.py', ignore_deprecated=True, check_aliases=True)
1063 if not result.resolved:
1064 raise AnsibleError("unable to load {0} plugin named {1} ".format(plugin_type, plugin_name))
1065 filename = result.plugin_resolved_path
1066 collection_name = result.plugin_resolved_collection
1067
1068 try:
1069 doc, __, __, __ = get_docstring(filename, fragment_loader, verbose=(context.CLIARGS['verbosity'] > 0),
1070 collection_name=collection_name, plugin_type=plugin_type)
1071 except Exception as ex:
1072 raise AnsibleError(f"{plugin_type} {plugin_name} at {filename!r} has a documentation formatting error or is missing documentation.") from ex
1073
1074 if doc is None:
1075 # Removed plugins don't have any documentation
1076 return None
1077
1078 return dict(
1079 name=plugin_name,
1080 namespace=DocCLI.namespace_from_plugin_filepath(filename, plugin_name, loader.package_path),
1081 description=doc.get('short_description', "UNKNOWN"),
1082 version_added=doc.get('version_added', "UNKNOWN")
1083 )
1084
1085 @staticmethod
1086 def namespace_from_plugin_filepath(filepath, plugin_name, basedir):
1087 if not basedir.endswith('/'):
1088 basedir += '/'
1089 rel_path = filepath.replace(basedir, '')
1090 extension_free = os.path.splitext(rel_path)[0]
1091 namespace_only = extension_free.rsplit(plugin_name, 1)[0].strip('/_')
1092 clean_ns = namespace_only.replace('/', '.')
1093 if clean_ns == '':
1094 clean_ns = None
1095
1096 return clean_ns
1097
1098 @staticmethod
1099 def _combine_plugin_doc(plugin, plugin_type, doc, plainexamples, returndocs, metadata):
1100 # generate extra data
1101 if plugin_type == 'module':
1102 # is there corresponding action plugin?
1103 if plugin in action_loader:
1104 doc['has_action'] = True
1105 else:
1106 doc['has_action'] = False
1107
1108 # return everything as one dictionary
1109 return {'doc': doc, 'examples': plainexamples, 'return': returndocs, 'metadata': metadata}
1110
1111 @staticmethod
1112 def format_snippet(plugin, plugin_type, doc):
1113 """ return heavily commented plugin use to insert into play """
1114 if plugin_type == 'inventory' and doc.get('options', {}).get('plugin'):
1115 # these do not take a yaml config that we can write a snippet for
1116 raise ValueError('The {0} inventory plugin does not take YAML type config source'
1117 ' that can be used with the "auto" plugin so a snippet cannot be'
1118 ' created.'.format(plugin))
1119
1120 text = []
1121
1122 if plugin_type == 'lookup':
1123 text = _do_lookup_snippet(doc)
1124
1125 elif 'options' in doc:
1126 text = _do_yaml_snippet(doc)
1127
1128 text.append('')
1129 return "\n".join(text)
1130
1131 @staticmethod
1132 def format_plugin_doc(plugin, plugin_type, doc, plainexamples, returndocs, metadata):
1133 collection_name = doc['collection']
1134
1135 # TODO: do we really want this?
1136 # add_collection_to_versions_and_dates(doc, '(unknown)', is_module=(plugin_type == 'module'))
1137 # remove_current_collection_from_versions_and_dates(doc, collection_name, is_module=(plugin_type == 'module'))
1138 # remove_current_collection_from_versions_and_dates(
1139 # returndocs, collection_name, is_module=(plugin_type == 'module'), return_docs=True)
1140
1141 # assign from other sections
1142 doc['plainexamples'] = plainexamples
1143 doc['returndocs'] = returndocs
1144 doc['metadata'] = metadata
1145
1146 try:
1147 text = DocCLI.get_man_text(doc, collection_name, plugin_type)
1148 except Exception as ex:
1149 raise AnsibleError(f"Unable to retrieve documentation from {plugin!r}.") from ex
1150
1151 return text
1152
1153 def _get_plugin_list_descriptions(self, plugins: dict[str, _PluginDocMetadata]) -> dict[str, str]:
1154
1155 descs = {}
1156 for plugin, plugin_info in plugins.items():
1157 # TODO: move to plugin itself i.e: plugin.get_desc()
1158 doc = None
1159
1160 docerror = None
1161 if plugin_info.path:
1162 filename = Path(to_native(plugin_info.path))
1163 try:
1164 doc = read_docstub(filename)
1165 except Exception as e:
1166 docerror = e
1167
1168 # plugin file was empty or had error, lets try other options
1169 if doc is None:
1170 # handle test/filters that are in file with diff name
1171 base = plugin.split('.')[-1]
1172 basefile = filename.with_name(base + filename.suffix)
1173 for extension in C.DOC_EXTENSIONS:
1174 docfile = basefile.with_suffix(extension)
1175 try:
1176 if docfile.exists():
1177 doc = read_docstub(docfile)
1178 except Exception as e:
1179 docerror = e
1180
1181 # Do a final fallback to see if the plugin is a shadowed Jinja2 plugin
1182 # without any explicit documentation.
1183 if doc is None and plugin_info.jinja_builtin_short_description:
1184 descs[plugin] = plugin_info.jinja_builtin_short_description
1185 continue
1186
1187 if docerror:
1188 display.error_as_warning(f"{plugin} has a documentation formatting error.", exception=docerror)
1189 continue
1190
1191 if not doc or not isinstance(doc, dict):
1192 desc = 'UNDOCUMENTED'
1193 else:
1194 desc = doc.get('short_description', 'INVALID SHORT DESCRIPTION').strip()
1195
1196 descs[plugin] = desc
1197
1198 return descs
1199
1200 @staticmethod
1201 def print_paths(finder):
1202 """ Returns a string suitable for printing of the search path """
1203
1204 # Uses a list to get the order right
1205 ret = []
1206 for i in finder._get_paths(subdirs=False):
1207 i = to_text(i, errors='surrogate_or_strict')
1208 if i not in ret:
1209 ret.append(i)
1210 return os.pathsep.join(ret)
1211
1212 @staticmethod
1213 def _dump_yaml(struct, flow_style=False):
1214 return yaml_dump(struct, default_flow_style=flow_style, default_style="''", Dumper=AnsibleDumper).rstrip('\n')
1215
1216 @staticmethod
1217 def _indent_lines(text, indent):
1218 return DocCLI.tty_ify('\n'.join([indent + line for line in text.split('\n')]))
1219
1220 @staticmethod
1221 def _format_version_added(version_added, version_added_collection=None):
1222 if version_added_collection == 'ansible.builtin':
1223 version_added_collection = 'ansible-core'
1224 # In ansible-core, version_added can be 'historical'
1225 if version_added == 'historical':
1226 return 'historical'
1227 if version_added_collection:
1228 version_added = '%s of %s' % (version_added, version_added_collection)
1229 return 'version %s' % (version_added, )
1230
1231 @staticmethod
1232 def warp_fill(text, limit, initial_indent='', subsequent_indent='', initial_extra=0, **kwargs):
1233 result = []
1234 for paragraph in text.split('\n\n'):
1235 wrapped = textwrap.fill(paragraph, limit, initial_indent=initial_indent + ' ' * initial_extra, subsequent_indent=subsequent_indent,
1236 break_on_hyphens=False, break_long_words=False, drop_whitespace=True, **kwargs)
1237 if initial_extra and wrapped.startswith(' ' * initial_extra):
1238 wrapped = wrapped[initial_extra:]
1239 result.append(wrapped)
1240 initial_indent = subsequent_indent
1241 initial_extra = 0
1242 return '\n'.join(result)
1243
1244 @staticmethod
1245 def add_fields(text, fields, limit, opt_indent, return_values=False, base_indent='', man=False):
1246
1247 for o in sorted(fields):
1248 # Create a copy so we don't modify the original (in case YAML anchors have been used)
1249 opt = dict(fields[o])
1250
1251 # required is used as indicator and removed
1252 required = opt.pop('required', False)
1253 if not isinstance(required, bool):
1254 raise AnsibleError("Incorrect value for 'Required', a boolean is needed.: %s" % required)
1255
1256 opt_leadin = ' '
1257 key = ''
1258 if required:
1259 if C.ANSIBLE_NOCOLOR:
1260 opt_leadin = "="
1261 key = "%s%s %s" % (base_indent, opt_leadin, _format(o, 'bold', 'red'))
1262 else:
1263 if C.ANSIBLE_NOCOLOR:
1264 opt_leadin = "-"
1265 key = "%s%s %s" % (base_indent, opt_leadin, _format(o, 'yellow'))
1266
1267 # description is specifically formatted and can either be string or list of strings
1268 if 'description' not in opt:
1269 raise AnsibleError("All (sub-)options and return values must have a 'description' field", obj=o)
1270 text.append('')
1271
1272 # TODO: push this to top of for and sort by size, create indent on largest key?
1273 inline_indent = ' ' * max((len(opt_indent) - len(o)) - len(base_indent), 2)
1274 extra_indent = base_indent + ' ' * (len(o) + 3)
1275 sub_indent = inline_indent + extra_indent
1276 if is_sequence(opt['description']):
1277 for entry_idx, entry in enumerate(opt['description'], 1):
1278 if not isinstance(entry, str):
1279 raise AnsibleError("Expected string in description of %s at index %s, got %s" % (o, entry_idx, type(entry)))
1280 if entry_idx == 1:
1281 text.append(key + DocCLI.warp_fill(DocCLI.tty_ify(entry), limit,
1282 initial_indent=inline_indent, subsequent_indent=sub_indent, initial_extra=len(extra_indent)))
1283 else:
1284 text.append(DocCLI.warp_fill(DocCLI.tty_ify(entry), limit, initial_indent=sub_indent, subsequent_indent=sub_indent))
1285 else:
1286 if not isinstance(opt['description'], str):
1287 raise AnsibleError("Expected string in description of %s, got %s" % (o, type(opt['description'])))
1288 text.append(key + DocCLI.warp_fill(DocCLI.tty_ify(opt['description']), limit,
1289 initial_indent=inline_indent, subsequent_indent=sub_indent, initial_extra=len(extra_indent)))
1290 del opt['description']
1291
1292 suboptions = []
1293 for subkey in ('options', 'suboptions', 'contains', 'spec'):
1294 if subkey in opt:
1295 suboptions.append((subkey, opt.pop(subkey)))
1296
1297 if not required and not return_values and 'default' not in opt:
1298 opt['default'] = None
1299
1300 # sanitize config items
1301 conf = {}
1302 for config in ('env', 'ini', 'yaml', 'vars', 'keyword'):
1303 if config in opt and opt[config]:
1304 # Create a copy so we don't modify the original (in case YAML anchors have been used)
1305 conf[config] = [dict(item) for item in opt.pop(config)]
1306 for ignore in DocCLI.IGNORE:
1307 for item in conf[config]:
1308 if display.verbosity > 0 and 'version_added' in item:
1309 item['added_in'] = DocCLI._format_version_added(item['version_added'], item.get('version_added_colleciton', 'ansible-core'))
1310 if ignore in item:
1311 del item[ignore]
1312
1313 # reformat cli options
1314 if 'cli' in opt and opt['cli']:
1315 conf['cli'] = []
1316 for cli in opt['cli']:
1317 if 'option' not in cli:
1318 conf['cli'].append({'name': cli['name'], 'option': '--%s' % cli['name'].replace('_', '-')})
1319 else:
1320 conf['cli'].append(cli)
1321 del opt['cli']
1322
1323 # add custom header for conf
1324 if conf:
1325 text.append(DocCLI._indent_lines(DocCLI._dump_yaml({'set_via': conf}), opt_indent))
1326
1327 # these we handle at the end of generic option processing
1328 version_added = opt.pop('version_added', None)
1329 version_added_collection = opt.pop('version_added_collection', None)
1330
1331 # general processing for options
1332 for k in sorted(opt):
1333 if k.startswith('_'):
1334 continue
1335
1336 if is_sequence(opt[k]):
1337 text.append(DocCLI._indent_lines('%s: %s' % (k, DocCLI._dump_yaml(opt[k], flow_style=True)), opt_indent))
1338 else:
1339 text.append(DocCLI._indent_lines(DocCLI._dump_yaml({k: opt[k]}), opt_indent))
1340
1341 if version_added and not man:
1342 text.append("%sadded in: %s" % (opt_indent, DocCLI._format_version_added(version_added, version_added_collection)))
1343
1344 for subkey, subdata in suboptions:
1345 text.append("%s%s:" % (opt_indent, subkey))
1346 DocCLI.add_fields(text, subdata, limit, opt_indent + ' ', return_values, opt_indent)
1347
1348 @staticmethod
1349 def _add_seealso(text: list[str], seealsos: list[dict[str, t.Any]], limit: int, opt_indent: str) -> None:
1350 for item in seealsos:
1351 if 'module' in item:
1352 text.append(DocCLI.warp_fill(DocCLI.tty_ify('Module %s' % item['module']),
1353 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1354 description = item.get('description')
1355 if description is None and item['module'].startswith('ansible.builtin.'):
1356 description = 'The official documentation on the %s module.' % item['module']
1357 if description is not None:
1358 text.append(DocCLI.warp_fill(DocCLI.tty_ify(description),
1359 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1360 if item['module'].startswith('ansible.builtin.'):
1361 relative_url = 'collections/%s_module.html' % item['module'].replace('.', '/', 2)
1362 text.append(DocCLI.warp_fill(DocCLI.tty_ify(get_versioned_doclink(relative_url)),
1363 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent))
1364 elif 'plugin' in item and 'plugin_type' in item:
1365 plugin_suffix = ' plugin' if item['plugin_type'] not in ('module', 'role') else ''
1366 text.append(DocCLI.warp_fill(DocCLI.tty_ify('%s%s %s' % (item['plugin_type'].title(), plugin_suffix, item['plugin'])),
1367 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1368 description = item.get('description')
1369 if description is None and item['plugin'].startswith('ansible.builtin.'):
1370 description = 'The official documentation on the %s %s%s.' % (item['plugin'], item['plugin_type'], plugin_suffix)
1371 if description is not None:
1372 text.append(DocCLI.warp_fill(DocCLI.tty_ify(description),
1373 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1374 if item['plugin'].startswith('ansible.builtin.'):
1375 relative_url = 'collections/%s_%s.html' % (item['plugin'].replace('.', '/', 2), item['plugin_type'])
1376 text.append(DocCLI.warp_fill(DocCLI.tty_ify(get_versioned_doclink(relative_url)),
1377 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent))
1378 elif 'name' in item and 'link' in item and 'description' in item:
1379 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['name']),
1380 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1381 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['description']),
1382 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1383 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['link']),
1384 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1385 elif 'ref' in item and 'description' in item:
1386 text.append(DocCLI.warp_fill(DocCLI.tty_ify('Ansible documentation [%s]' % item['ref']),
1387 limit - 6, initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1388 text.append(DocCLI.warp_fill(DocCLI.tty_ify(item['description']),
1389 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1390 text.append(DocCLI.warp_fill(DocCLI.tty_ify(get_versioned_doclink('/#stq=%s&stp=1' % item['ref'])),
1391 limit - 6, initial_indent=opt_indent + ' ', subsequent_indent=opt_indent + ' '))
1392
1393 def get_role_man_text(self, role, role_json):
1394 """Generate text for the supplied role suitable for display.
1395
1396 This is similar to get_man_text(), but roles are different enough that we have
1397 a separate method for formatting their display.
1398
1399 :param role: The role name.
1400 :param role_json: The JSON for the given role as returned from _create_role_doc().
1401
1402 :returns: A array of text suitable for displaying to screen.
1403 """
1404 text = []
1405 opt_indent = " "
1406 pad = display.columns * 0.20
1407 limit = max(display.columns - int(pad), 70)
1408
1409 text.append("> ROLE: %s (%s)" % (_format(role, 'BOLD'), role_json.get('path')))
1410
1411 for entry_point in role_json['entry_points']:
1412 doc = role_json['entry_points'][entry_point]
1413 desc = ''
1414 if doc.get('short_description'):
1415 desc = "- %s" % (doc.get('short_description'))
1416 text.append('')
1417 text.append("ENTRY POINT: %s %s" % (_format(entry_point, "BOLD"), desc))
1418 text.append('')
1419
1420 if version_added := doc.pop('version_added', None):
1421 text.append(_format("ADDED IN:", 'bold') + " %s\n" % DocCLI._format_version_added(version_added))
1422
1423 if doc.get('description'):
1424 if isinstance(doc['description'], list):
1425 descs = doc['description']
1426 else:
1427 descs = [doc['description']]
1428 for desc in descs:
1429 text.append("%s" % DocCLI.warp_fill(DocCLI.tty_ify(desc), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
1430 text.append('')
1431
1432 if doc.get('options'):
1433 text.append(_format("Options", 'bold') + " (%s indicates it is required):" % ("=" if C.ANSIBLE_NOCOLOR else 'red'))
1434 DocCLI.add_fields(text, doc.pop('options'), limit, opt_indent)
1435
1436 if notes := doc.pop('notes', False):
1437 text.append("")
1438 text.append(_format("NOTES:", 'bold'))
1439 for note in notes:
1440 text.append(DocCLI.warp_fill(DocCLI.tty_ify(note), limit - 6,
1441 initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1442
1443 if seealso := doc.pop('seealso', False):
1444 text.append("")
1445 text.append(_format("SEE ALSO:", 'bold'))
1446 DocCLI._add_seealso(text, seealso, limit=limit, opt_indent=opt_indent)
1447
1448 # generic elements we will handle identically
1449 for k in ('author',):
1450 if k not in doc:
1451 continue
1452 text.append('')
1453 if isinstance(doc[k], str):
1454 text.append('%s: %s' % (k.upper(), DocCLI.warp_fill(DocCLI.tty_ify(doc[k]),
1455 limit - (len(k) + 2), subsequent_indent=opt_indent)))
1456 elif isinstance(doc[k], (list, tuple)):
1457 text.append('%s: %s' % (k.upper(), ', '.join(doc[k])))
1458 else:
1459 # use empty indent since this affects the start of the yaml doc, not it's keys
1460 text.append(DocCLI._indent_lines(DocCLI._dump_yaml({k.upper(): doc[k]}), ''))
1461
1462 if doc.get('examples', False):
1463 text.append('')
1464 text.append(_format("EXAMPLES:", 'bold'))
1465 if isinstance(doc['examples'], str):
1466 text.append(doc.pop('examples').strip())
1467 else:
1468 try:
1469 text.append(yaml_dump(doc.pop('examples'), indent=2, default_flow_style=False))
1470 except Exception as e:
1471 raise AnsibleParserError("Unable to parse examples section.") from e
1472
1473 return text
1474
1475 @staticmethod
1476 def get_man_text(doc, collection_name='', plugin_type=''):
1477 # Create a copy so we don't modify the original
1478 doc = dict(doc)
1479
1480 DocCLI.IGNORE = DocCLI.IGNORE + (context.CLIARGS['type'],)
1481 opt_indent = " "
1482 base_indent = " "
1483 text = []
1484 pad = display.columns * 0.20
1485 limit = max(display.columns - int(pad), 70)
1486
1487 text.append("> %s %s (%s)" % (plugin_type.upper(), _format(doc.pop('plugin_name'), 'bold'), doc.pop('filename') or 'Jinja2'))
1488
1489 if isinstance(doc['description'], list):
1490 descs = doc.pop('description')
1491 else:
1492 descs = [doc.pop('description')]
1493
1494 text.append('')
1495 for desc in descs:
1496 text.append(DocCLI.warp_fill(DocCLI.tty_ify(desc), limit, initial_indent=base_indent, subsequent_indent=base_indent))
1497
1498 if display.verbosity > 0:
1499 doc['added_in'] = DocCLI._format_version_added(doc.pop('version_added', 'historical'), doc.pop('version_added_collection', 'ansible-core'))
1500
1501 if doc.get('deprecated', False):
1502 text.append(_format("DEPRECATED: ", 'bold', 'DEP'))
1503 if isinstance(doc['deprecated'], dict):
1504 if 'removed_at_date' not in doc['deprecated'] and 'version' in doc['deprecated'] and 'removed_in' not in doc['deprecated']:
1505 doc['deprecated']['removed_in'] = doc['deprecated']['version']
1506 try:
1507 text.append('\t' + C.config.get_deprecated_msg_from_config(doc['deprecated'], True, collection_name=collection_name))
1508 except KeyError as e:
1509 raise AnsibleError("Invalid deprecation documentation structure.") from e
1510 else:
1511 text.append("%s" % doc['deprecated'])
1512 del doc['deprecated']
1513
1514 if doc.pop('has_action', False):
1515 text.append("")
1516 text.append(_format(" * note:", 'bold') + " This module has a corresponding action plugin.")
1517
1518 if doc.get('options', False):
1519 text.append("")
1520 text.append(_format("OPTIONS", 'bold') + " (%s indicates it is required):" % ("=" if C.ANSIBLE_NOCOLOR else 'red'))
1521 DocCLI.add_fields(text, doc.pop('options'), limit, opt_indent, man=(display.verbosity == 0))
1522
1523 if doc.get('attributes', False):
1524 text.append("")
1525 text.append(_format("ATTRIBUTES:", 'bold'))
1526 for k in doc['attributes'].keys():
1527 text.append('')
1528 text.append(DocCLI.warp_fill(DocCLI.tty_ify(_format('%s:' % k, 'UNDERLINE')), limit - 6, initial_indent=opt_indent,
1529 subsequent_indent=opt_indent))
1530 text.append(DocCLI._indent_lines(DocCLI._dump_yaml(doc['attributes'][k]), opt_indent))
1531 del doc['attributes']
1532
1533 if doc.get('notes', False):
1534 text.append("")
1535 text.append(_format("NOTES:", 'bold'))
1536 for note in doc['notes']:
1537 text.append(DocCLI.warp_fill(DocCLI.tty_ify(note), limit - 6,
1538 initial_indent=opt_indent[:-2] + "* ", subsequent_indent=opt_indent))
1539 del doc['notes']
1540
1541 if doc.get('seealso', False):
1542 text.append("")
1543 text.append(_format("SEE ALSO:", 'bold'))
1544 DocCLI._add_seealso(text, doc['seealso'], limit=limit, opt_indent=opt_indent)
1545 del doc['seealso']
1546
1547 if doc.get('requirements', False):
1548 text.append('')
1549 req = ", ".join(doc.pop('requirements'))
1550 text.append(_format("REQUIREMENTS:", 'bold') + "%s\n" % DocCLI.warp_fill(DocCLI.tty_ify(req), limit - 16, initial_indent=" ",
1551 subsequent_indent=opt_indent))
1552
1553 # Generic handler
1554 for k in sorted(doc):
1555 if not doc[k] or k in DocCLI.IGNORE:
1556 continue
1557 text.append('')
1558 header = _format(k.upper(), 'bold')
1559 if isinstance(doc[k], str):
1560 text.append('%s: %s' % (header, DocCLI.warp_fill(DocCLI.tty_ify(doc[k]), limit - (len(k) + 2), subsequent_indent=opt_indent)))
1561 elif isinstance(doc[k], (list, tuple)):
1562 text.append('%s: %s' % (header, ', '.join(doc[k])))
1563 else:
1564 # use empty indent since this affects the start of the yaml doc, not it's keys
1565 text.append('%s: ' % header + DocCLI._indent_lines(DocCLI._dump_yaml(doc[k]), ' ' * (len(k) + 2)))
1566 del doc[k]
1567
1568 if doc.get('plainexamples', False):
1569 text.append('')
1570 text.append(_format("EXAMPLES:", 'bold'))
1571 if isinstance(doc['plainexamples'], str):
1572 text.append(doc.pop('plainexamples').strip())
1573 else:
1574 try:
1575 text.append(yaml_dump(doc.pop('plainexamples'), indent=2, default_flow_style=False))
1576 except Exception as ex:
1577 raise AnsibleParserError("Unable to parse examples section.") from ex
1578
1579 if doc.get('returndocs', False):
1580 text.append('')
1581 text.append(_format("RETURN VALUES:", 'bold'))
1582 DocCLI.add_fields(text, doc.pop('returndocs'), limit, opt_indent, return_values=True, man=(display.verbosity == 0))
1583
1584 text.append('\n')
1585 return "\n".join(text)
1586
1587
1588 def _do_yaml_snippet(doc):
1589 text = []
1590
1591 mdesc = DocCLI.tty_ify(doc['short_description'])
1592 module = doc.get('module')
1593
1594 if module:
1595 # this is actually a usable task!
1596 text.append("- name: %s" % (mdesc))
1597 text.append(" %s:" % (module))
1598 else:
1599 # just a comment, hopefully useful yaml file
1600 text.append("# %s:" % doc.get('plugin', doc.get('name')))
1601
1602 pad = 29
1603 subdent = '# '.rjust(pad + 2)
1604 limit = display.columns - pad
1605
1606 for o in sorted(doc['options'].keys()):
1607 opt = doc['options'][o]
1608 if isinstance(opt['description'], str):
1609 desc = DocCLI.tty_ify(opt['description'])
1610 else:
1611 desc = DocCLI.tty_ify(" ".join(opt['description']))
1612
1613 required = opt.get('required', False)
1614 if not isinstance(required, bool):
1615 raise ValueError("Incorrect value for 'Required', a boolean is needed: %s" % required)
1616
1617 o = '%s:' % o
1618 if module:
1619 if required:
1620 desc = "(required) %s" % desc
1621 text.append(" %-20s # %s" % (o, DocCLI.warp_fill(desc, limit, subsequent_indent=subdent)))
1622 else:
1623 if required:
1624 default = '(required)'
1625 else:
1626 default = opt.get('default', 'None')
1627
1628 text.append("%s %-9s # %s" % (o, default, DocCLI.warp_fill(desc, limit, subsequent_indent=subdent, max_lines=3)))
1629
1630 return text
1631
1632
1633 def _do_lookup_snippet(doc):
1634 text = []
1635 snippet = "lookup('%s', " % doc.get('plugin', doc.get('name'))
1636 comment = []
1637
1638 for o in sorted(doc['options'].keys()):
1639
1640 opt = doc['options'][o]
1641 comment.append('# %s(%s): %s' % (o, opt.get('type', 'string'), opt.get('description', '')))
1642 if o in ('_terms', '_raw', '_list'):
1643 # these are 'list of arguments'
1644 snippet += '< %s >' % (o)
1645 continue
1646
1647 required = opt.get('required', False)
1648 if not isinstance(required, bool):
1649 raise ValueError("Incorrect value for 'Required', a boolean is needed: %s" % required)
1650
1651 if required:
1652 default = '<REQUIRED>'
1653 else:
1654 default = opt.get('default', 'None')
1655
1656 if opt.get('type') in ('string', 'str'):
1657 snippet += ", %s='%s'" % (o, default)
1658 else:
1659 snippet += ', %s=%s' % (o, default)
1660
1661 snippet += ")"
1662
1663 if comment:
1664 text.extend(comment)
1665 text.append('')
1666 text.append(snippet)
1667
1668 return text
1669
1670
1671 def main(args=None):
1672 DocCLI.cli_executor(args)
1673
1674
1675 if __name__ == '__main__':
1676 main()