-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvars2specs.py
185 lines (153 loc) · 6.44 KB
/
vars2specs.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
# Copyright (C) 2022 Guido Grazioli <[email protected]>
# SPDX-License-Identifier: MIT
#
# pylint: disable=invalid-name
"""Generates argument_specs.yml from variables parsed in role.
Usage:
vars2specs.py [-c] [-i IND] [-r DIR]
Options:
-c Parse all roles in a collection [default: no]
-i IND --indent IND White space count for yaml indention. [default: 4]
-r DIR --role_dir=DIR Input role directory [default: ./].
"""
from textwrap import indent
import typing
import yaml
import docopt
import glob
import re
import collections
from ruamel.yaml import YAML
from yaml.composer import Composer
from yaml.constructor import Constructor
from yaml.nodes import ScalarNode
from yaml.resolver import BaseResolver
from yaml.loader import SafeLoader
from pathlib import Path
LINE_NUMBER_KEY: str = "__line__"
ARGUMENTS_SPEC_FILE: str = "argument_specs.yml"
ARGUMENTS_SPEC_PATH: str = "/meta/" + ARGUMENTS_SPEC_FILE
ARGUMENTS_SPEC_DICT: str = """\
argument_specs:
main:
options:
"""
class LineLoader(SafeLoader):
"""
Custom LineLoader which return line number for all variables (not just parsed nodes).
"""
def __init__(self, stream):
super(LineLoader, self).__init__(stream)
def compose_node(self, parent, index):
# the line number where the previous token has ended (plus empty lines)
line = self.line
node = Composer.compose_node(self, parent, index)
node.__line__ = line + 1
return node
def construct_mapping(self, node, deep=False):
node_pair_lst = node.value
node_pair_lst_for_appending = []
for key_node, value_node in node_pair_lst:
shadow_key_node = ScalarNode(tag=BaseResolver.DEFAULT_SCALAR_TAG, value=LINE_NUMBER_KEY + key_node.value)
shadow_value_node = ScalarNode(tag=BaseResolver.DEFAULT_SCALAR_TAG, value=key_node.__line__)
node_pair_lst_for_appending.append((shadow_key_node, shadow_value_node))
node.value = node_pair_lst + node_pair_lst_for_appending
mapping = Constructor.construct_mapping(self, node, deep=deep)
return mapping
class Vars2Specs:
"""
class to generate arguments_spec.yml from parsed variables
"""
role_dir: Path
collection: bool
indent: int = 4
def __init__(self, role: str, collection: bool):
self.collection = collection
self.role_dir: Path = Path(role)
if collection:
self.role_dir = self.role_dir / "roles"
print("Work directory: %s" % self.role_dir)
def lookup_roles(self):
""" find roles """
if self.collection:
return [
Path(role).name
for role in glob.glob(str(self.role_dir)+'/**/')
]
return [self.role_dir.name]
def lookup_var_files(self, role):
""" find var files """
if self.collection:
return glob.glob(str(self.role_dir)+'/'+role+'/defaults/*.yml') + glob.glob(str(self.role_dir)+'/'+role+'/vars/*.yml')
return glob.glob(str(self.role_dir)+'/defaults/*.yml') + glob.glob(str(self.role_dir)+'/vars/*.yml')
def quote_default(self, value, vartype):
escaped = re.sub('\\\\', "\\\\\\\\", str(value))
return '"' + escaped + '"' if vartype not in [ "bool", "int" ] else value
def generate_spec(self, path: Path, defined_vars):
""" parse variables """
results = []
variables = yaml.load(path, Loader=LineLoader)
rel_path = Path(path.name).relative_to(self.role_dir)
for var_name in filter(lambda k: not k.startswith(LINE_NUMBER_KEY) and not isinstance(variables[k],dict), variables.keys()):
linenumber = variables[LINE_NUMBER_KEY + var_name]
try:
description = defined_vars[var_name]['description']
except KeyError:
description = "TODO document argument"
try:
vartype = defined_vars[var_name]['type']
except KeyError:
vartype = type(variables[var_name]).__name__ if variables[var_name] is not None else "str"
default = "default: %s" % self.quote_default(variables[var_name], vartype) if variables[var_name] is not None else 'required: true'
results.append("""%s# line %s of %s
%s:
%s
description: "%s"
type: "%s"
""" % ((" "*3*self.indent), linenumber, str(rel_path), var_name, default, description, vartype))
return results
def load_existing_specs(self, role):
print("Parsing argument_specs for role %s" % role)
try:
with open(str(self.role_dir) + '/' + role + ARGUMENTS_SPEC_PATH, 'r') as specs:
specs = yaml.load(specs, Loader=LineLoader)
return specs['argument_specs']['main']['options']
except:
return {}
def generate(self):
""" write argument specs """
yaml = YAML()
yaml.preserve_quotes = True
yaml.indent(mapping = self.indent)
yaml.width = 800
variable_specs = collections.defaultdict(list)
roles = self.lookup_roles()
for role in roles:
defined_vars = self.load_existing_specs(role)
for var_file in self.lookup_var_files(role):
print("Parsing %s for role %s" % (var_file, role))
with open(var_file, 'r') as f:
variable_specs[role] += self.generate_spec(f, defined_vars)
root_yml = yaml.load(ARGUMENTS_SPEC_DICT)
for role in roles:
specfile = str(self.role_dir) + ARGUMENTS_SPEC_PATH
if self.collection:
specfile = str(self.role_dir) + '/' + role + ARGUMENTS_SPEC_PATH
if len(variable_specs[role]) > 0:
print("Writing argument_specs for role %s: %s" % (role, specfile))
with open(specfile, 'w') as f:
code_yml = yaml.load('\n'.join(variable_specs[role]))
root_yml['argument_specs']['main']['options'] = code_yml
yaml.dump(root_yml, f)
else:
print("No variables found for role directory %s" % self.role_dir)
def main():
args = docopt.docopt(__doc__)
role_dir = args['--role_dir'] or './'
collection = args['-c'] or False
v2s = Vars2Specs(role_dir, collection)
if (args['--indent']):
v2s.indent = int(args['--indent'])
v2s.generate()
if __name__ == '__main__':
main()