forked from pyinfra-dev/pyinfra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_operations_docs.py
executable file
·222 lines (171 loc) · 6.69 KB
/
generate_operations_docs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python
import sys
from glob import glob
from importlib import import_module
from inspect import getfullargspec, getmembers, isclass
from os import makedirs, path
from types import FunctionType
from pyinfra.api.facts import FactBase
sys.path.append(".")
from docs.utils import format_doc_line, title_line # noqa: E402
MODULE_DEF_LINE_MAX = 90
def build_operations_docs():
this_dir = path.dirname(path.realpath(__file__))
docs_dir = path.abspath(path.join(this_dir, "..", "docs"))
operations_dir = path.join(this_dir, "..", "pyinfra", "operations", "*.py")
makedirs(path.join(docs_dir, "operations"), exist_ok=True)
op_module_names = [
path.basename(name)[:-3]
for name in glob(operations_dir)
if not name.endswith("__init__.py")
]
for module_name in op_module_names:
lines = []
print("--> Doing module: {0}".format(module_name))
module = import_module("pyinfra.operations.{0}".format(module_name))
full_title = "{0} Operations".format(module_name.title())
lines.append(full_title)
lines.append(title_line("-", full_title))
lines.append("")
if module.__doc__:
lines.append(module.__doc__)
operation_facts = [
(key, value)
for key, value in getmembers(module)
if (isclass(value) and issubclass(value, FactBase))
]
if operation_facts:
lines.append("")
items = []
for key, value in operation_facts:
fact_module = value.__module__.replace("pyinfra.facts.", "")
items.append(f":ref:`facts:{fact_module}.{key}`")
lines.append("Facts used in these operations: {0}.".format(", ".join(items)))
lines.append("")
operation_functions = [
(key, value._inner)
for key, value in getmembers(module)
if (
isinstance(value, FunctionType)
and value.__module__ == module.__name__
and getattr(value, "_inner", False)
and not value.__name__.startswith("_")
and not key.startswith("_")
)
]
for name, func in operation_functions:
decorated_func = getattr(func, "_inner", None)
while decorated_func:
func = decorated_func
decorated_func = getattr(func, "_inner", None)
lines.append(".. _operations:{0}.{1}:".format(module_name, name))
lines.append("")
title_name = ":code:`{0}.{1}`".format(module_name, name)
lines.append(title_name)
# Underline name with -'s for title
lines.append(title_line("~", title_name))
if getattr(func, "is_idempotent", None) is False:
text = (
getattr(func, "idempotent_notice", None)
or "This operation will always execute commands and is not idempotent."
)
lines.append(
"""
.. admonition:: Stateless operation
:class: important
{0}
""".format(
text,
),
)
doc = func.__doc__
if doc:
docbits = doc.strip().split("\n")
description_lines = []
for line in docbits:
if line:
description_lines.append(line)
else:
break
if len(docbits) > 0:
lines.append("")
lines.extend([line.strip() for line in description_lines])
lines.append("")
doc = "\n".join(docbits[len(description_lines) :])
argspec = getfullargspec(func)
# Make default strings appear as strings
arg_defaults = (
['"{}"'.format(arg) if isinstance(arg, str) else arg for arg in argspec.defaults]
if argspec.defaults
else None
)
# Create a dict of arg name -> default
defaults = (
dict(
zip(
argspec.args[-len(arg_defaults) :],
arg_defaults,
),
)
if arg_defaults
else {}
)
# Build args string
args = []
for arg in argspec.args:
if arg in ("state", "host") or arg.startswith("_"):
continue
value = arg
if arg in argspec.annotations:
value += f": {argspec.annotations[arg]}"
if arg in defaults:
value += f"={defaults[arg]}"
args.append(value)
# Add **kwargs to indicate global arguments
args.append("**kwargs")
if len(", ".join(args)) <= MODULE_DEF_LINE_MAX:
args_string = ", ".join(args)
else:
arg_buffer = []
arg_lines = []
for arg in args:
if len(", ".join(arg_buffer + [arg])) >= MODULE_DEF_LINE_MAX:
arg_lines.append(arg_buffer)
arg_buffer = []
arg_buffer.append(arg)
if arg_buffer:
arg_lines.append(arg_buffer)
arg_lines = [" {0}".format(", ".join(line_args)) for line_args in arg_lines]
args_string = "\n{0},\n ".format(",\n".join(arg_lines))
# Attach the code block
lines.append(
"""
.. code:: python
{0}.{1}({2})
""".strip().format(
module_name,
name,
args_string,
),
)
# Append any remaining docstring
if doc:
lines.append("")
lines.append(
"{0}".format(
"\n".join([format_doc_line(line) for line in doc.split("\n")]),
).strip(),
)
lines.append(
"Note:\n\tThis operation also inherits all :doc:`global arguments </arguments>`."
)
lines.append("")
lines.append("")
# Write out the file
module_filename = path.join(docs_dir, "operations", "{0}.rst".format(module_name))
print("--> Writing {0}".format(module_filename))
with open(module_filename, "w", encoding="utf-8") as outfile:
outfile.write("\n".join(lines))
if __name__ == "__main__":
print("### Building operations docs")
build_operations_docs()