compose-viz/compose_viz/parser.py

62 lines
1.8 KiB
Python
Raw Normal View History

2022-05-18 17:28:18 +02:00
from typing import List, Optional
2022-05-16 18:53:29 +02:00
from ruamel.yaml import YAML
2022-05-07 18:42:14 +02:00
2022-05-18 17:28:18 +02:00
from compose_viz.compose import Compose, Service
2022-05-14 20:27:33 +02:00
2022-05-07 18:42:14 +02:00
class Parser:
def __init__(self):
pass
def parse(self, file_path: str) -> Compose:
2022-05-14 15:30:18 +02:00
# load the yaml file
with open(file_path, "r") as f:
try:
2022-05-18 17:28:18 +02:00
yaml = YAML(typ="safe", pure=True)
2022-05-16 18:53:29 +02:00
yaml_data = yaml.load(f)
2022-05-18 17:28:18 +02:00
except Exception as e:
raise Exception(f"Error parsing file {file_path}: {e}")
2022-05-14 15:30:18 +02:00
# validate the yaml file
if not yaml_data:
print("Error: empty yaml file")
raise ValueError
2022-05-18 17:28:18 +02:00
2022-05-14 15:30:18 +02:00
if not yaml_data.get("services"):
print("Error: no services found")
raise ValueError
2022-05-18 17:28:18 +02:00
2022-05-14 15:30:18 +02:00
# parse services data into Service objects
services_data = yaml_data["services"]
services = []
2022-05-18 17:28:18 +02:00
2022-05-14 15:30:18 +02:00
for service, service_name in zip(services_data.values(), services_data.keys()):
2022-05-18 17:28:18 +02:00
# print("name: {}".format(service_name))
service_image: Optional[str] = None
2022-05-14 15:30:18 +02:00
if service.get("image"):
service_image = service["image"]
2022-05-18 17:28:18 +02:00
# print("image: {}".format(service_image))
service_networks: List[str] = []
2022-05-14 15:30:18 +02:00
if service.get("networks"):
2022-05-18 17:28:18 +02:00
if type(service["networks"]) is list:
2022-05-16 19:27:59 +02:00
service_networks = service["networks"]
else:
service_networks = list(service["networks"].keys())
2022-05-18 17:28:18 +02:00
# print("networks: {}".format(service_networks))
services.append(
Service(
name=service_name,
image=service_image,
networks=service_networks,
)
)
2022-05-14 15:30:18 +02:00
# create Compose object
compose = Compose(services)
return compose