shoestring-assembler 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shoestring_assembler/__init__.py +5 -0
- shoestring_assembler/assembler.py +683 -0
- shoestring_assembler/cli.py +104 -0
- shoestring_assembler/display.py +64 -0
- shoestring_assembler/minimal_mustache.py +29 -0
- shoestring_assembler/recipe.schema.json +126 -0
- shoestring_assembler-0.0.1.dist-info/AUTHORS.rst +13 -0
- shoestring_assembler-0.0.1.dist-info/LICENSE +674 -0
- shoestring_assembler-0.0.1.dist-info/METADATA +56 -0
- shoestring_assembler-0.0.1.dist-info/RECORD +13 -0
- shoestring_assembler-0.0.1.dist-info/WHEEL +5 -0
- shoestring_assembler-0.0.1.dist-info/entry_points.txt +2 -0
- shoestring_assembler-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
"""Main module."""
|
|
2
|
+
|
|
3
|
+
import rich.progress
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
import sys
|
|
7
|
+
import subprocess
|
|
8
|
+
import hashlib
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from . import display
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from pathlib import UnsupportedOperation
|
|
14
|
+
except ImportError:
|
|
15
|
+
UnsupportedOperation = NotImplementedError
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import tomllib as toml
|
|
20
|
+
except ImportError:
|
|
21
|
+
import tomli as toml
|
|
22
|
+
|
|
23
|
+
import yaml
|
|
24
|
+
import jsonschema
|
|
25
|
+
import re
|
|
26
|
+
import select
|
|
27
|
+
from . import minimal_mustache
|
|
28
|
+
|
|
29
|
+
src_dir = os.path.dirname(os.path.realpath(__file__))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# CONSTANTS
|
|
33
|
+
SOLUTION_FILES_DIR = "solution_files"
|
|
34
|
+
BASE_MODULE_FILES_DIR = f"{SOLUTION_FILES_DIR}/sources"
|
|
35
|
+
SOLUTION_CONFIG_DIR = f"{SOLUTION_FILES_DIR}/config"
|
|
36
|
+
|
|
37
|
+
DATA_DIR = "data"
|
|
38
|
+
USER_CONFIG_DIR = "user_config"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
DOCKER_NETWORK_NAME = "internal"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Assembler:
|
|
45
|
+
def __init__(self, recipe_filepath):
|
|
46
|
+
self._recipe_filepath_provided = recipe_filepath
|
|
47
|
+
self._recipe_location = Path.resolve(Path(recipe_filepath))
|
|
48
|
+
self._recipe = None
|
|
49
|
+
self._recipe_hash = None
|
|
50
|
+
|
|
51
|
+
def load_recipe(self):
|
|
52
|
+
display.print_header("Loading Recipe")
|
|
53
|
+
try:
|
|
54
|
+
# check file type is supported and find parser
|
|
55
|
+
ext = self._recipe_location.suffix
|
|
56
|
+
|
|
57
|
+
if ext == ".yml" or ext == ".yaml":
|
|
58
|
+
parser = self._parse_yaml
|
|
59
|
+
elif ext == ".toml":
|
|
60
|
+
parser = self._parse_toml
|
|
61
|
+
elif ext == ".json":
|
|
62
|
+
parser = self._parse_json
|
|
63
|
+
else:
|
|
64
|
+
display.print_error(
|
|
65
|
+
f"Recipe format unsupported - expects a json, yaml or toml file"
|
|
66
|
+
)
|
|
67
|
+
sys.exit(255)
|
|
68
|
+
|
|
69
|
+
# parse file
|
|
70
|
+
with rich.progress.open(
|
|
71
|
+
self._recipe_location, "rb", description="Loading File..."
|
|
72
|
+
) as file:
|
|
73
|
+
self._recipe = parser(file)
|
|
74
|
+
file.seek(0) # reset file
|
|
75
|
+
hash_fn = hashlib.sha256()
|
|
76
|
+
hash_fn.update(file.read())
|
|
77
|
+
self._recipe_hash = hash_fn.hexdigest()
|
|
78
|
+
|
|
79
|
+
except FileNotFoundError:
|
|
80
|
+
display.print_error(
|
|
81
|
+
f"Unable to find recipe file. Expected to find it at: {self._recipe_location}"
|
|
82
|
+
)
|
|
83
|
+
sys.exit(255)
|
|
84
|
+
|
|
85
|
+
display.print_complete("Recipe loaded")
|
|
86
|
+
|
|
87
|
+
def _parse_json(self, file):
|
|
88
|
+
return json.load(file)
|
|
89
|
+
|
|
90
|
+
def _parse_yaml(self, file):
|
|
91
|
+
return yaml.safe_load(file)
|
|
92
|
+
|
|
93
|
+
def _parse_toml(self, file):
|
|
94
|
+
return toml.load(file)
|
|
95
|
+
|
|
96
|
+
def validate_recipe(self):
|
|
97
|
+
display.print_header("Validating Recipe")
|
|
98
|
+
schema_location = os.path.join(src_dir, "recipe.schema.json")
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
with rich.progress.open(
|
|
102
|
+
schema_location, "rb", description="Loading Recipe Schema..."
|
|
103
|
+
) as file:
|
|
104
|
+
schema = json.load(file)
|
|
105
|
+
|
|
106
|
+
do_validate(self._recipe, schema)
|
|
107
|
+
|
|
108
|
+
except FileNotFoundError:
|
|
109
|
+
display.print_error(
|
|
110
|
+
f"Unable to find recipe schema. Expected to find it at: {schema_location}"
|
|
111
|
+
)
|
|
112
|
+
sys.exit(255)
|
|
113
|
+
|
|
114
|
+
display.print_complete("Recipe valid")
|
|
115
|
+
|
|
116
|
+
def clean(self):
|
|
117
|
+
display.print_header("Cleaning")
|
|
118
|
+
# TODO
|
|
119
|
+
rmtree(Path(BASE_MODULE_FILES_DIR))
|
|
120
|
+
display.print_complete("Old files cleared")
|
|
121
|
+
|
|
122
|
+
def verify_filestructure(self, check_sources=False):
|
|
123
|
+
display.print_header("Verifying filesystem structure")
|
|
124
|
+
|
|
125
|
+
source_list = self._recipe["source"].keys()
|
|
126
|
+
instance_list = [
|
|
127
|
+
*self._recipe.get("service_module", {}).keys(),
|
|
128
|
+
*self._recipe.get("infrastructure", {}).keys(),
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
all_ok = True
|
|
132
|
+
|
|
133
|
+
# check solution directories
|
|
134
|
+
all_ok = check_dir(SOLUTION_FILES_DIR) and all_ok
|
|
135
|
+
all_ok = check_dir(SOLUTION_CONFIG_DIR) and all_ok
|
|
136
|
+
for source_name in source_list:
|
|
137
|
+
all_ok = check_dir(f"{SOLUTION_CONFIG_DIR}/{source_name}") and all_ok
|
|
138
|
+
|
|
139
|
+
all_ok = check_or_create_dir(BASE_MODULE_FILES_DIR) and all_ok
|
|
140
|
+
if check_sources:
|
|
141
|
+
for source_name in source_list:
|
|
142
|
+
all_ok = check_dir(f"{BASE_MODULE_FILES_DIR}/{source_name}") and all_ok
|
|
143
|
+
|
|
144
|
+
# check data directories
|
|
145
|
+
all_ok = check_or_create_dir(DATA_DIR) and all_ok
|
|
146
|
+
for instance in instance_list:
|
|
147
|
+
all_ok = check_or_create_dir(f"data/{instance}") and all_ok
|
|
148
|
+
|
|
149
|
+
# check user config directories
|
|
150
|
+
all_ok = check_or_create_dir(USER_CONFIG_DIR) and all_ok
|
|
151
|
+
for instance in instance_list:
|
|
152
|
+
all_ok = check_or_create_dir(f"{USER_CONFIG_DIR}/{instance}") and all_ok
|
|
153
|
+
|
|
154
|
+
# check log directories
|
|
155
|
+
all_ok = check_or_create_dir("logs") and all_ok
|
|
156
|
+
# for source_name in self._recipe["source"].keys():
|
|
157
|
+
# all_ok = check_or_create_dir(f"logs/{source_name}") and all_ok
|
|
158
|
+
|
|
159
|
+
if not all_ok:
|
|
160
|
+
display.print_error(
|
|
161
|
+
"Filesystem structure failed validation - unable to continue"
|
|
162
|
+
)
|
|
163
|
+
sys.exit(255)
|
|
164
|
+
else:
|
|
165
|
+
display.print_complete("Filesystem structure valid")
|
|
166
|
+
|
|
167
|
+
def gather_base_service_modules(self):
|
|
168
|
+
display.print_header("Gathering Service Module Sources")
|
|
169
|
+
number_of_service_modules = len(self._recipe["source"])
|
|
170
|
+
|
|
171
|
+
with rich.progress.Progress() as progress: # displays progress bar on console
|
|
172
|
+
task = progress.add_task(
|
|
173
|
+
"[cyan]Gathering Service Module Sources",
|
|
174
|
+
total=number_of_service_modules,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
listed_sources = self._recipe["source"]
|
|
178
|
+
service_module_source_set = [
|
|
179
|
+
details["source"]
|
|
180
|
+
for details in self._recipe.get("service_module", {}).values()
|
|
181
|
+
]
|
|
182
|
+
infrastructure_source_set = [
|
|
183
|
+
details["source"]
|
|
184
|
+
for details in self._recipe.get("infrastructure", {}).values()
|
|
185
|
+
]
|
|
186
|
+
|
|
187
|
+
used_sources = {
|
|
188
|
+
source_name: listed_sources[source_name]
|
|
189
|
+
for source_name in service_module_source_set
|
|
190
|
+
}
|
|
191
|
+
used_sources.update(
|
|
192
|
+
{
|
|
193
|
+
source_name: listed_sources[source_name]
|
|
194
|
+
for source_name in infrastructure_source_set
|
|
195
|
+
}
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
for source_name, source_details in used_sources.items():
|
|
199
|
+
display.print_log(f"Fetching {source_name}", console=progress.console)
|
|
200
|
+
|
|
201
|
+
if "file" in source_details:
|
|
202
|
+
result = handle_file_source(
|
|
203
|
+
source_name, source_details["file"], console=progress.console
|
|
204
|
+
)
|
|
205
|
+
elif "git" in source_details:
|
|
206
|
+
result = handle_git_source(
|
|
207
|
+
source_name,
|
|
208
|
+
source_details["git"],
|
|
209
|
+
console=progress.console,
|
|
210
|
+
progress=progress,
|
|
211
|
+
)
|
|
212
|
+
else:
|
|
213
|
+
# this should never happen due to recipe validation
|
|
214
|
+
display.print_error(
|
|
215
|
+
f"Source {source_name} does not include details on where to get it",
|
|
216
|
+
console=progress.console,
|
|
217
|
+
)
|
|
218
|
+
sys.exit(255)
|
|
219
|
+
|
|
220
|
+
if result:
|
|
221
|
+
display.print_complete(
|
|
222
|
+
f"Fetched '{source_name}' ", console=progress.console
|
|
223
|
+
)
|
|
224
|
+
progress.update(task, advance=1) # updates progress bar
|
|
225
|
+
else:
|
|
226
|
+
progress.update(task, visible=False)
|
|
227
|
+
display.print_error(
|
|
228
|
+
f"An error occured while fetching '{source_name}'",
|
|
229
|
+
console=progress.console,
|
|
230
|
+
)
|
|
231
|
+
sys.exit(255)
|
|
232
|
+
|
|
233
|
+
def check_user_config(self):
|
|
234
|
+
display.print_header("Checking User Config")
|
|
235
|
+
|
|
236
|
+
display.print_complete(f"User config ready")
|
|
237
|
+
|
|
238
|
+
def generate_compose_file(self):
|
|
239
|
+
display.print_header("Generating Compose File")
|
|
240
|
+
compose_definition = {
|
|
241
|
+
"services": {},
|
|
242
|
+
"networks": {DOCKER_NETWORK_NAME: {"name": "shoestring-internal"}},
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
for service_module_name, service_module_details in self._recipe.get(
|
|
246
|
+
"service_module", {}
|
|
247
|
+
).items():
|
|
248
|
+
service_set = self.generate_docker_services_for_module(
|
|
249
|
+
service_module_name, service_module_details, "service_module"
|
|
250
|
+
)
|
|
251
|
+
compose_definition["services"].update(service_set)
|
|
252
|
+
|
|
253
|
+
for infra_module_name, infra_module_details in self._recipe.get(
|
|
254
|
+
"infrastructure", {}
|
|
255
|
+
).items():
|
|
256
|
+
service_set = self.generate_docker_services_for_module(
|
|
257
|
+
infra_module_name, infra_module_details, "infrastructure"
|
|
258
|
+
)
|
|
259
|
+
compose_definition["services"].update(service_set)
|
|
260
|
+
|
|
261
|
+
compose_definition["x-shoestring"] = {
|
|
262
|
+
"filename": self._recipe_filepath_provided,
|
|
263
|
+
"hash":self._recipe_hash
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
with open(Path.resolve(Path.cwd()) / Path("compose.yml"), "w") as f:
|
|
267
|
+
yaml.safe_dump(
|
|
268
|
+
compose_definition, f, default_flow_style=False, sort_keys=False
|
|
269
|
+
)
|
|
270
|
+
display.print_complete(f"Compose file complete")
|
|
271
|
+
|
|
272
|
+
def generate_docker_services_for_module(
|
|
273
|
+
self, module_name, module_details, module_type
|
|
274
|
+
):
|
|
275
|
+
display.print_log(f"Generating compose services for {module_name}")
|
|
276
|
+
module_services = {}
|
|
277
|
+
# load meta.toml
|
|
278
|
+
source = module_details["source"]
|
|
279
|
+
try:
|
|
280
|
+
meta_file_path = f"./{BASE_MODULE_FILES_DIR}/{source}/meta.toml"
|
|
281
|
+
with rich.progress.open(
|
|
282
|
+
meta_file_path,
|
|
283
|
+
"rb",
|
|
284
|
+
description="Loading meta...",
|
|
285
|
+
) as file:
|
|
286
|
+
meta = toml.load(file)
|
|
287
|
+
except FileNotFoundError:
|
|
288
|
+
display.print_error(
|
|
289
|
+
f"Unable to find meta file for {source}. Expected to find it at: {meta_file_path}"
|
|
290
|
+
)
|
|
291
|
+
sys.exit(255)
|
|
292
|
+
|
|
293
|
+
container_list = module_details.get("containers", [])
|
|
294
|
+
for container in container_list:
|
|
295
|
+
container_meta = meta[container]
|
|
296
|
+
entry_identifier = (
|
|
297
|
+
f"{module_name}-{container}" if len(container_list) > 1 else module_name
|
|
298
|
+
)
|
|
299
|
+
network_alias = (
|
|
300
|
+
module_details["alias"].get(container, entry_identifier)
|
|
301
|
+
if "alias" in module_details
|
|
302
|
+
else entry_identifier
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# form base
|
|
306
|
+
service_definition = {
|
|
307
|
+
"build": {
|
|
308
|
+
"context": f"./{BASE_MODULE_FILES_DIR}/{source}/",
|
|
309
|
+
"dockerfile": f"./{container_meta.get('dockerfile','Dockerfile')}",
|
|
310
|
+
"additional_contexts": [
|
|
311
|
+
f"solution_config=./{SOLUTION_CONFIG_DIR}/{source}"
|
|
312
|
+
],
|
|
313
|
+
},
|
|
314
|
+
"networks": {
|
|
315
|
+
DOCKER_NETWORK_NAME: {"aliases": [f"{network_alias}.docker.local"]}
|
|
316
|
+
},
|
|
317
|
+
"logging": {
|
|
318
|
+
"driver": "syslog",
|
|
319
|
+
"options": {"tag": f"docker-{entry_identifier}"},
|
|
320
|
+
},
|
|
321
|
+
"labels": {
|
|
322
|
+
"net.digitalshoestring.solution": self._recipe["solution"]["slug"],
|
|
323
|
+
"net.digitalshoestring.function": module_type,
|
|
324
|
+
},
|
|
325
|
+
"restart": "unless-stopped",
|
|
326
|
+
}
|
|
327
|
+
# extend with partials
|
|
328
|
+
partials = {}
|
|
329
|
+
if "compose_partial" in container_meta:
|
|
330
|
+
try:
|
|
331
|
+
partial_file_path = f'./{BASE_MODULE_FILES_DIR}/{source}/{container_meta["compose_partial"]}'
|
|
332
|
+
with rich.progress.open(
|
|
333
|
+
partial_file_path,
|
|
334
|
+
"r",
|
|
335
|
+
description="Loading compose partials...",
|
|
336
|
+
) as file:
|
|
337
|
+
template_applied_string = minimal_mustache.render(
|
|
338
|
+
file.read(), module_details.get("template",{})
|
|
339
|
+
)
|
|
340
|
+
partials = yaml.safe_load(template_applied_string)
|
|
341
|
+
except FileNotFoundError:
|
|
342
|
+
display.print_error(
|
|
343
|
+
f"Unable to find compose partial file for {source}. Expected to find it at: {partial_file_path}"
|
|
344
|
+
)
|
|
345
|
+
sys.exit(255)
|
|
346
|
+
|
|
347
|
+
service_definition = {
|
|
348
|
+
**partials,
|
|
349
|
+
**service_definition,
|
|
350
|
+
} # update in this way to prevent partials from overwriting service_definition keys
|
|
351
|
+
|
|
352
|
+
# sort out volumes
|
|
353
|
+
volumes = {
|
|
354
|
+
"data": {"host": f"./{DATA_DIR}/{module_name}"},
|
|
355
|
+
"user_config": {"host": f"./{USER_CONFIG_DIR}/{module_name}"},
|
|
356
|
+
} # defaults
|
|
357
|
+
container_vols = container_meta.get("volume", {})
|
|
358
|
+
# map in items
|
|
359
|
+
for name, details in container_vols.items():
|
|
360
|
+
if name not in volumes:
|
|
361
|
+
volumes[name] = {}
|
|
362
|
+
volumes[name]["container"] = details
|
|
363
|
+
|
|
364
|
+
compose_volumes = []
|
|
365
|
+
for name, mapping in volumes.items():
|
|
366
|
+
has_host = "host" in mapping
|
|
367
|
+
has_cnt = "container" in mapping
|
|
368
|
+
if has_host and has_cnt: # everything as expected
|
|
369
|
+
if mapping["container"].get("ignore") == True:
|
|
370
|
+
continue # container doesn't use this volume
|
|
371
|
+
|
|
372
|
+
if "mode" in mapping["container"]:
|
|
373
|
+
container_entry = f'{mapping["container"]["path"]}:{mapping["container"]["mode"]}'
|
|
374
|
+
else:
|
|
375
|
+
container_entry = f'{mapping["container"]["path"]}'
|
|
376
|
+
|
|
377
|
+
entry = f'{mapping["host"]}:{container_entry}'
|
|
378
|
+
compose_volumes.append(entry)
|
|
379
|
+
elif has_host:
|
|
380
|
+
# no container entry to map to
|
|
381
|
+
display.print_error(
|
|
382
|
+
f"No corresponding container entry for volume {name} of {entry_identifier}."
|
|
383
|
+
)
|
|
384
|
+
sys.exit(255)
|
|
385
|
+
elif has_cnt:
|
|
386
|
+
# no host entry to map to
|
|
387
|
+
display.print_error(
|
|
388
|
+
f"No corresponding host entry for volume {name} of {entry_identifier}."
|
|
389
|
+
)
|
|
390
|
+
sys.exit(255)
|
|
391
|
+
if len(compose_volumes) > 0:
|
|
392
|
+
service_definition["volumes"] = compose_volumes
|
|
393
|
+
|
|
394
|
+
# map in ports
|
|
395
|
+
ports = {} # defaults
|
|
396
|
+
|
|
397
|
+
# map in container ports
|
|
398
|
+
container_ports = container_meta.get("ports", {})
|
|
399
|
+
for name, port_number in container_ports.items():
|
|
400
|
+
if name not in ports:
|
|
401
|
+
ports[name] = {}
|
|
402
|
+
ports[name]["container"] = port_number
|
|
403
|
+
# map in host ports
|
|
404
|
+
host_ports = module_details.get("ports", {}).get(container, {})
|
|
405
|
+
for name, port_number in host_ports.items():
|
|
406
|
+
if name not in ports:
|
|
407
|
+
ports[name] = {}
|
|
408
|
+
ports[name]["host"] = port_number
|
|
409
|
+
|
|
410
|
+
# combine mappings
|
|
411
|
+
compose_ports = []
|
|
412
|
+
for name, mapping in ports.items():
|
|
413
|
+
has_host = "host" in mapping
|
|
414
|
+
has_cnt = "container" in mapping
|
|
415
|
+
if has_host and has_cnt: # everything as expected
|
|
416
|
+
entry = f'{mapping["host"]}:{mapping["container"]}'
|
|
417
|
+
compose_ports.append(entry)
|
|
418
|
+
elif has_host:
|
|
419
|
+
# no container entry to map to
|
|
420
|
+
display.print_error(
|
|
421
|
+
f"No corresponding container entry for port {name} of {entry_identifier}."
|
|
422
|
+
)
|
|
423
|
+
sys.exit(255)
|
|
424
|
+
elif has_cnt:
|
|
425
|
+
# no host entry to map to
|
|
426
|
+
display.print_error(
|
|
427
|
+
f"No corresponding host entry for port {name} of {entry_identifier}."
|
|
428
|
+
)
|
|
429
|
+
sys.exit(255)
|
|
430
|
+
if len(compose_ports) > 0:
|
|
431
|
+
service_definition["ports"] = compose_ports
|
|
432
|
+
|
|
433
|
+
module_services[entry_identifier] = service_definition
|
|
434
|
+
|
|
435
|
+
return module_services
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
## Filesystem Utilities
|
|
439
|
+
def check_dir(rel_path):
|
|
440
|
+
full_path = Path.resolve(Path.cwd()) / Path(rel_path)
|
|
441
|
+
if full_path.is_dir():
|
|
442
|
+
display.print_log(f"[green]\[ok] [white] {rel_path}")
|
|
443
|
+
return True
|
|
444
|
+
else:
|
|
445
|
+
display.print_log(f"[red]\[error - not found] {rel_path}")
|
|
446
|
+
return False
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def check_or_create_dir(rel_path):
|
|
450
|
+
full_path = Path.resolve(Path.cwd()) / Path(rel_path)
|
|
451
|
+
try:
|
|
452
|
+
full_path.mkdir(exist_ok=False)
|
|
453
|
+
display.print_log(f"[green]\[created] [white]{rel_path}")
|
|
454
|
+
except FileExistsError:
|
|
455
|
+
try:
|
|
456
|
+
full_path.mkdir(exist_ok=True)
|
|
457
|
+
display.print_log(f"[green]\[ok] [white] {rel_path}")
|
|
458
|
+
except FileExistsError:
|
|
459
|
+
display.print_log(f"[red]\[error - can't create] {rel_path}")
|
|
460
|
+
return False
|
|
461
|
+
except FileNotFoundError:
|
|
462
|
+
display.print_log(f"[red]\[error - no parent] {rel_path}")
|
|
463
|
+
return False
|
|
464
|
+
|
|
465
|
+
return True
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
if sys.version_info[0] == 3 and sys.version_info[1] < 14:
|
|
469
|
+
|
|
470
|
+
def do_copy(src_path, dest_path):
|
|
471
|
+
import shutil
|
|
472
|
+
|
|
473
|
+
shutil.copytree(src_path, dest_path)
|
|
474
|
+
|
|
475
|
+
else:
|
|
476
|
+
|
|
477
|
+
def do_copy(src_path, dest_path):
|
|
478
|
+
src_path.copy_into(dest_path)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
if sys.version_info[0] == 3 and sys.version_info[1] < 12:
|
|
482
|
+
|
|
483
|
+
def rmtree(root: Path):
|
|
484
|
+
display.print_log(f"Clearing {root}")
|
|
485
|
+
for walk_root, dirs, files in os.walk(root, topdown=False):
|
|
486
|
+
walk_root = Path(walk_root)
|
|
487
|
+
for name in files:
|
|
488
|
+
(walk_root / name).unlink()
|
|
489
|
+
for name in dirs:
|
|
490
|
+
path = walk_root / name
|
|
491
|
+
if path.is_symlink():
|
|
492
|
+
path.unlink()
|
|
493
|
+
else:
|
|
494
|
+
path.rmdir()
|
|
495
|
+
|
|
496
|
+
else:
|
|
497
|
+
|
|
498
|
+
def rmtree(root: Path):
|
|
499
|
+
display.print_log(f"Clearing {root}")
|
|
500
|
+
for root, dirs, files in root.walk(top_down=False):
|
|
501
|
+
for name in files:
|
|
502
|
+
(root / name).unlink()
|
|
503
|
+
for name in dirs:
|
|
504
|
+
(root / name).rmdir()
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
# schema utilities
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def do_validate(config, schema):
|
|
511
|
+
try:
|
|
512
|
+
jsonschema.validate(
|
|
513
|
+
instance=config,
|
|
514
|
+
schema=schema,
|
|
515
|
+
format_checker=jsonschema.Draft202012Validator.FORMAT_CHECKER,
|
|
516
|
+
)
|
|
517
|
+
except jsonschema.ValidationError as v_err:
|
|
518
|
+
display.print_error(f"Recipe error at {v_err.json_path}:\n\n{v_err.message}")
|
|
519
|
+
display.print_error(
|
|
520
|
+
"Config File is not valid -- unable to start the solution -- please correct the issues flagged above and try again."
|
|
521
|
+
)
|
|
522
|
+
sys.exit(255)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
# source utilities
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def handle_file_source(name, details, console=None):
|
|
529
|
+
mode = details.get("mode", "copy")
|
|
530
|
+
path = details["path"] # could throw error but shouldn't due to validation
|
|
531
|
+
|
|
532
|
+
display.print_log(f"type: file, mode: {mode}", console=console)
|
|
533
|
+
|
|
534
|
+
src_path = Path.resolve(Path(path))
|
|
535
|
+
dest_path = Path.resolve(Path.cwd()) / BASE_MODULE_FILES_DIR / name
|
|
536
|
+
|
|
537
|
+
if mode == "copy":
|
|
538
|
+
do_copy(src_path, dest_path)
|
|
539
|
+
display.print_log(
|
|
540
|
+
f"{src_path} [green]copied[/green] to {dest_path}", console=console
|
|
541
|
+
)
|
|
542
|
+
elif mode == "link":
|
|
543
|
+
try:
|
|
544
|
+
dest_path.symlink_to(src_path, target_is_directory=True)
|
|
545
|
+
display.print_log(
|
|
546
|
+
f"{src_path} [green]linked[/green] to {dest_path}", console=console
|
|
547
|
+
)
|
|
548
|
+
except UnsupportedOperation:
|
|
549
|
+
display.print_error(
|
|
550
|
+
f"Operating system does not support symlinks. Could not link [purple]{src_path}[/purple] to [purple]{dest_path}[/purple] for source {name}. Consider changing [cyan]mode[/cyan] to [cyan]copy[/cyan].",
|
|
551
|
+
console=console,
|
|
552
|
+
)
|
|
553
|
+
return False
|
|
554
|
+
except FileExistsError:
|
|
555
|
+
display.print_error(
|
|
556
|
+
f"Files already present at destination - Could not link [purple]{src_path}[/purple] to [purple]{dest_path}[/purple] for source {name}.",
|
|
557
|
+
console=console,
|
|
558
|
+
)
|
|
559
|
+
return False
|
|
560
|
+
|
|
561
|
+
return True
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def handle_git_source(name, details, console, progress: rich.progress.Progress):
|
|
565
|
+
tag = details.get("tag")
|
|
566
|
+
branch = details.get("branch")
|
|
567
|
+
path = details["path"] # could throw error but shouldn't due to validation
|
|
568
|
+
|
|
569
|
+
dest_path = Path.resolve(Path.cwd()) / BASE_MODULE_FILES_DIR / name
|
|
570
|
+
|
|
571
|
+
num_slashes = path.count("/")
|
|
572
|
+
if num_slashes == 0:
|
|
573
|
+
url = f"https://github.com/DigitalShoestringSolutions/{path}"
|
|
574
|
+
elif num_slashes == 1:
|
|
575
|
+
url = f"https://github.com/{path}"
|
|
576
|
+
else:
|
|
577
|
+
url = path
|
|
578
|
+
|
|
579
|
+
display.print_log(
|
|
580
|
+
f"type: git, repo: {url} target:{ f'tag {tag}' if tag else f' branch {branch}'}",
|
|
581
|
+
console=console,
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
env = os.environ.copy()
|
|
585
|
+
env["GIT_TERMINAL_PROMPT"] = (
|
|
586
|
+
"0" # prevents hanging on username input if url invalid
|
|
587
|
+
)
|
|
588
|
+
|
|
589
|
+
command = [
|
|
590
|
+
"git",
|
|
591
|
+
"clone",
|
|
592
|
+
"--progress", # force inclusion of progress updates
|
|
593
|
+
"--depth",
|
|
594
|
+
"1", # only download latest commit - no history (massive speed up)
|
|
595
|
+
"--branch",
|
|
596
|
+
tag if tag else branch,
|
|
597
|
+
url,
|
|
598
|
+
dest_path,
|
|
599
|
+
]
|
|
600
|
+
|
|
601
|
+
display.print_debug(f"command: {command}", console=console)
|
|
602
|
+
|
|
603
|
+
process = subprocess.Popen(
|
|
604
|
+
command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=env
|
|
605
|
+
) # git outputs updates over stderr
|
|
606
|
+
|
|
607
|
+
# likely overkill but would be good to be able to relay updates
|
|
608
|
+
buffer = bytearray()
|
|
609
|
+
active_progress_tracker = None
|
|
610
|
+
regex = re.compile("^(?P<label>.*)\d+% \((?P<progress>\d*)/(?P<total>\d*)\).*")
|
|
611
|
+
while process.returncode == None:
|
|
612
|
+
while True:
|
|
613
|
+
line = None
|
|
614
|
+
line_update = False
|
|
615
|
+
|
|
616
|
+
read_list, _wlist, _xlist = select.select([process.stderr], [], [], 1)
|
|
617
|
+
# display.print_log(read_list,console=console)
|
|
618
|
+
if process.stderr in read_list:
|
|
619
|
+
char = process.stderr.read(1)
|
|
620
|
+
if char == b"\r" or char == b"\n":
|
|
621
|
+
if char == b"\r":
|
|
622
|
+
line_update = True
|
|
623
|
+
line = buffer.decode()
|
|
624
|
+
buffer.clear()
|
|
625
|
+
elif char:
|
|
626
|
+
# display.print_log(f"char: {char}", console=console)
|
|
627
|
+
buffer += char
|
|
628
|
+
else:
|
|
629
|
+
break # end of file
|
|
630
|
+
else:
|
|
631
|
+
break # timeout - break to check if process terminated
|
|
632
|
+
|
|
633
|
+
if line:
|
|
634
|
+
if active_progress_tracker or line_update: # progress update line
|
|
635
|
+
m = regex.match(line)
|
|
636
|
+
if active_progress_tracker:
|
|
637
|
+
if line_update: # update
|
|
638
|
+
progress.update(
|
|
639
|
+
active_progress_tracker,
|
|
640
|
+
completed=int(m.group("progress")),
|
|
641
|
+
)
|
|
642
|
+
else: # end
|
|
643
|
+
if m:
|
|
644
|
+
progress.update(
|
|
645
|
+
active_progress_tracker,
|
|
646
|
+
completed=int(m.group("progress")),
|
|
647
|
+
)
|
|
648
|
+
else:
|
|
649
|
+
progress.update(active_progress_tracker, advance=100000)
|
|
650
|
+
progress.stop_task(active_progress_tracker)
|
|
651
|
+
progress.remove_task(active_progress_tracker)
|
|
652
|
+
active_progress_tracker = None
|
|
653
|
+
display.print_log(f"[white]{line}", console=console)
|
|
654
|
+
elif line_update: # new
|
|
655
|
+
active_progress_tracker = progress.add_task(
|
|
656
|
+
m.group("label"),
|
|
657
|
+
start=True,
|
|
658
|
+
completed=int(m.group("progress")),
|
|
659
|
+
total=int(m.group("total")),
|
|
660
|
+
)
|
|
661
|
+
else: # normal line
|
|
662
|
+
display.print_log(f"[white]{line}", console=console)
|
|
663
|
+
else:
|
|
664
|
+
pass
|
|
665
|
+
|
|
666
|
+
process.poll()
|
|
667
|
+
|
|
668
|
+
return process.returncode == 0
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
"""
|
|
672
|
+
TO DO List:
|
|
673
|
+
* work out what clean means
|
|
674
|
+
* user_config templates
|
|
675
|
+
* solution config templates & bootstrapping
|
|
676
|
+
|
|
677
|
+
Longer term
|
|
678
|
+
* host side volume specification
|
|
679
|
+
* named volumes
|
|
680
|
+
* Environment variables
|
|
681
|
+
* coveying port and alias mappings to services
|
|
682
|
+
* external resources
|
|
683
|
+
"""
|