-
Notifications
You must be signed in to change notification settings - Fork 42
/
generate.py
executable file
·223 lines (183 loc) · 7.03 KB
/
generate.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
223
#!/usr/bin/env python3
"""Generate the dockerfiles from a jinja template."""
import ruamel.yaml
import json
import logging
from jinja2 import Environment, FileSystemLoader
log = logging.getLogger(__name__)
json_parser = json
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
class Templates:
"""Accessor to the templates file."""
def __init__(self):
"""Initialize with a cache the templates.yml file."""
self._settings = None
with open("templates.yml", "r") as file:
self._settings = yaml.load(file)
def raw(self) -> dict:
"""Get raw template settings.
Returns:
dict: template settings
"""
return self._settings
def dockerfile_settings(self, eol: bool = False) -> dict:
"""Get dockerfile generation settings.
Args:
eol (bool, optional): Include eol images. Defaults to False.
Returns:
dict: Repository generation settings
"""
dockerfiles = []
for repository in self._settings:
for settings in self._settings[repository]:
if not eol and "eol" in settings:
continue
name = settings["name"]
settings["template_file"] = f"{repository}.dockerfile.jinja"
settings["out_file"] = f"{repository}/{name}.Dockerfile"
dockerfiles.append(settings)
return dockerfiles
def images(self, eol: bool = False) -> dict:
"""Get dict of images and targets to build.
Args:
eol (bool, optional): Include eol images. Defaults to False.
Returns:
dict: images and targets
"""
image_list = {}
for repository in self._settings:
for dockerfile in self._settings[repository]:
if not eol and "eol" in dockerfile:
continue
targets = list()
for target in dockerfile["targets"]:
targets.append(target["target"])
image_list[dockerfile["name"]] = {
"repository": repository,
"targets": targets,
}
return image_list
def workflow_names(self, eol: bool = False) -> list:
"""List workflow docker images.
Args:
eol (bool, optional): Include eol images. Defaults to False.
Returns:
list: A list includes for github workflow
"""
data = self._settings
output = []
for repo in data:
for entry in data[repo]:
tag = entry["name"]
if not eol and "eol" in entry.keys():
continue
for target in entry["targets"]:
item = {
"label": repo,
"tag": tag,
"target": target["target"],
"platforms": target["platforms"],
}
output.append(item)
return output
def task_names(self, eol: bool = False) -> list:
"""List workflow docker images.
Args:
eol (bool, optional): Include eol images. Defaults to False.
Returns:
list: A list of image names
"""
image_list = []
for repository in self._settings:
for dockerfile in self._settings[repository]:
if not eol and "eol" in dockerfile.keys():
continue
image_list.append(dockerfile["name"])
return image_list
def repo_names(self) -> list:
"""List the docker repos.
Returns:
list: The docker repository names
"""
return [repository for repository in self._settings]
templates = Templates()
def generate_dockerfiles(log):
"""Generate the dockerfiles for this repo."""
file_loader = FileSystemLoader("template")
env = Environment(loader=file_loader)
for dockerfile in templates.dockerfile_settings():
# The jinja template
template = env.get_template(dockerfile["template_file"])
output = template.render(dockerfile)
out_file = dockerfile["out_file"]
log.info(f"Generating {out_file}")
dockerfile_out = open(out_file, "w")
dockerfile_out.write(output)
dockerfile_out.close()
def generate_readmes(log):
"""Generate the readme files."""
file_loader = FileSystemLoader("template")
env = Environment(loader=file_loader)
repositories = templates.repo_names()
for repository in repositories:
dockerfiles = templates.raw()[repository]
log.info("Generating readme for {}".format(repository))
readme_template = env.get_template("readme.md.jinja")
readme_output = readme_template.render(
{"repo_name": repository, "dockerfiles": dockerfiles}
)
readme_file = f"{repository}/README.md"
readme_out = open(readme_file, "w")
readme_out.write(readme_output)
readme_out.close()
def generate_docker_workflow(log):
"""Generate workflow with non-eol images."""
log.info("Generating workflow file.")
workflow_file = ".github/workflows/docker.yml"
docker_workflow = None
with open(workflow_file, 'r') as file:
docker_workflow = yaml.load(file)
docker_workflow["jobs"]["docker"]["strategy"]["matrix"] = {
"include": templates.workflow_names()}
with open(workflow_file, "w") as file:
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.width = 4294967296 # A very large number
yaml.dump(docker_workflow, file)
def generate_readme_workflow(log):
"""Generate docker readme file workflow."""
workflow_file = ".github/workflows/docker_readme.yml"
docker_workflow = None
with open(workflow_file, "r") as file:
docker_workflow = yaml.load(file)
docker_workflow["jobs"]["readme"]["strategy"]["matrix"] = {
"docker_repo": templates.repo_names()
}
with open(workflow_file, "w") as file:
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.dump(docker_workflow, file)
def generate_tasks(log):
"""Generate tasks with non-eol images."""
log.info("Generating tasks.")
tasks_file = ".vscode/tasks.json"
with open(tasks_file, "r") as file:
tasks = json_parser.load(file)
for input in tasks["inputs"]:
if input["id"] == "build_name":
input["options"] = templates.task_names() + ["all"]
with open(tasks_file, "w") as file:
json_parser.dump(tasks, file, indent=2)
if __name__ == "__main__":
# Set up logger.
log.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
generate_dockerfiles(log)
generate_readmes(log)
generate_docker_workflow(log)
generate_readme_workflow(log)
generate_tasks(log)
log.info("Finished generating dockerfiles.")