| 1 |
# Copyright: (c) 2017, Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import ast |
| 7 |
|
| 8 |
import yaml |
| 9 |
|
| 10 |
from ansible import constants as C |
| 11 |
from ansible.errors import AnsibleError, AnsibleParserError |
| 12 |
from ansible.module_utils.common.text.converters import to_text, to_native |
| 13 |
from ansible.parsing.yaml.loader import AnsibleLoader |
| 14 |
from ansible.utils.display import Display |
| 15 |
from ansible._internal._datatag import _tags |
| 16 |
|
| 17 |
display = Display() |
| 18 |
|
| 19 |
|
| 20 |
string_to_vars = { |
| 21 |
'DOCUMENTATION': 'doc', |
| 22 |
'EXAMPLES': 'plainexamples', |
| 23 |
'RETURN': 'returndocs', |
| 24 |
'ANSIBLE_METADATA': 'metadata', # NOTE: now unused, but kept for backwards compat |
| 25 |
} |
| 26 |
|
| 27 |
|
| 28 |
def _init_doc_dict(): |
| 29 |
""" initialize a return dict for docs with the expected structure """ |
| 30 |
return {k: None for k in string_to_vars.values()} |
| 31 |
|
| 32 |
|
| 33 |
def read_docstring_from_yaml_file(filename, verbose=True, ignore_errors=True): |
| 34 |
""" Read docs from 'sidecar' yaml file doc for a plugin """ |
| 35 |
|
| 36 |
data = _init_doc_dict() |
| 37 |
file_data = {} |
| 38 |
|
| 39 |
try: |
| 40 |
with open(filename, 'rb') as yamlfile: |
| 41 |
file_data = yaml.load(yamlfile, Loader=AnsibleLoader) |
| 42 |
except Exception as ex: |
| 43 |
msg = f"Unable to parse yaml file {filename}" |
| 44 |
# DTFIX-FUTURE: find a better pattern for this (can we use the new optional error behavior?) |
| 45 |
if not ignore_errors: |
| 46 |
raise AnsibleParserError(f'{msg}.') from ex |
| 47 |
elif verbose: |
| 48 |
display.error(f'{msg}: {ex}') |
| 49 |
|
| 50 |
if file_data: |
| 51 |
for key in string_to_vars: |
| 52 |
data[string_to_vars[key]] = file_data.get(key, None) |
| 53 |
|
| 54 |
return data |
| 55 |
|
| 56 |
|
| 57 |
def read_docstring_from_python_file(filename, verbose=True, ignore_errors=True): |
| 58 |
""" |
| 59 |
Use ast to search for assignment of the DOCUMENTATION and EXAMPLES variables in the given file. |
| 60 |
Parse DOCUMENTATION from YAML and return the YAML doc or None together with EXAMPLES, as plain text. |
| 61 |
""" |
| 62 |
data = _init_doc_dict() |
| 63 |
|
| 64 |
try: |
| 65 |
with open(filename, 'rb') as b_module_data: |
| 66 |
M = ast.parse(b_module_data.read()) |
| 67 |
|
| 68 |
for child in M.body: |
| 69 |
if isinstance(child, ast.Assign): |
| 70 |
for t in child.targets: |
| 71 |
try: |
| 72 |
theid = t.id |
| 73 |
except AttributeError: |
| 74 |
# skip errors can happen when trying to use the normal code |
| 75 |
display.warning("Building documentation, failed to assign id for %s on %s, skipping" % (t, filename)) |
| 76 |
continue |
| 77 |
|
| 78 |
if theid in string_to_vars: |
| 79 |
varkey = string_to_vars[theid] |
| 80 |
if isinstance(child.value, ast.Dict): |
| 81 |
data[varkey] = ast.literal_eval(child.value) |
| 82 |
else: |
| 83 |
if theid == 'EXAMPLES': |
| 84 |
# examples 'can' be yaml, but even if so, we dont want to parse as such here |
| 85 |
# as it can create undesired 'objects' that don't display well as docs. |
| 86 |
data[varkey] = to_text(child.value.value) |
| 87 |
else: |
| 88 |
# string should be yaml if already not a dict |
| 89 |
child_value = _tags.Origin(path=filename, line_num=child.value.lineno).tag(child.value.value) |
| 90 |
data[varkey] = yaml.load(child_value, Loader=AnsibleLoader) |
| 91 |
|
| 92 |
display.debug('Documentation assigned: %s' % varkey) |
| 93 |
|
| 94 |
except Exception as ex: |
| 95 |
msg = f"Unable to parse documentation in python file {filename!r}" |
| 96 |
# DTFIX-FUTURE: better pattern to conditionally raise/display |
| 97 |
if not ignore_errors: |
| 98 |
raise AnsibleParserError(f'{msg}.') from ex |
| 99 |
elif verbose: |
| 100 |
display.error(f'{msg}: {ex}.') |
| 101 |
|
| 102 |
return data |
| 103 |
|
| 104 |
|
| 105 |
def read_docstring(filename, verbose=True, ignore_errors=True): |
| 106 |
""" returns a documentation dictionary from Ansible plugin docstrings """ |
| 107 |
|
| 108 |
# NOTE: adjacency of doc file to code file is responsibility of caller |
| 109 |
if filename.endswith(C.YAML_DOC_EXTENSIONS): |
| 110 |
docstring = read_docstring_from_yaml_file(filename, verbose=verbose, ignore_errors=ignore_errors) |
| 111 |
elif filename.endswith(C.PYTHON_DOC_EXTENSIONS): |
| 112 |
docstring = read_docstring_from_python_file(filename, verbose=verbose, ignore_errors=ignore_errors) |
| 113 |
elif not ignore_errors: |
| 114 |
raise AnsibleError("Unknown documentation format: %s" % to_native(filename)) |
| 115 |
|
| 116 |
if not docstring and not ignore_errors: |
| 117 |
raise AnsibleError("Unable to parse documentation for: %s" % to_native(filename)) |
| 118 |
|
| 119 |
# cause seealso is specially processed from 'doc' later on |
| 120 |
# TODO: stop any other 'overloaded' implementation in main doc |
| 121 |
docstring['seealso'] = None |
| 122 |
|
| 123 |
return docstring |
| 124 |
|
| 125 |
|
| 126 |
def read_docstub(filename): |
| 127 |
""" |
| 128 |
Quickly find short_description using string methods instead of node parsing. |
| 129 |
This does not return a full set of documentation strings and is intended for |
| 130 |
operations like ansible-doc -l. |
| 131 |
""" |
| 132 |
|
| 133 |
in_documentation = False |
| 134 |
capturing = False |
| 135 |
indent_detection = '' |
| 136 |
doc_stub = [] |
| 137 |
|
| 138 |
with open(filename, 'r') as t_module_data: |
| 139 |
for line in t_module_data: |
| 140 |
if in_documentation: |
| 141 |
# start capturing the stub until indentation returns |
| 142 |
if capturing and line.startswith(indent_detection): |
| 143 |
doc_stub.append(line) |
| 144 |
|
| 145 |
elif capturing and not line.startswith(indent_detection): |
| 146 |
break |
| 147 |
|
| 148 |
elif line.lstrip().startswith('short_description:'): |
| 149 |
capturing = True |
| 150 |
# Detect that the short_description continues on the next line if it's indented more |
| 151 |
# than short_description itself. |
| 152 |
indent_detection = ' ' * (len(line) - len(line.lstrip()) + 1) |
| 153 |
doc_stub.append(line) |
| 154 |
|
| 155 |
elif line.startswith('DOCUMENTATION') and ('=' in line or ':' in line): |
| 156 |
in_documentation = True |
| 157 |
|
| 158 |
short_description = r''.join(doc_stub).strip().rstrip('.') |
| 159 |
data = yaml.load(_tags.Origin(path=str(filename)).tag(short_description), Loader=AnsibleLoader) |
| 160 |
|
| 161 |
return data |