chore: apply pre-commit hooks

This commit is contained in:
Xyphuz 2022-05-18 23:28:18 +08:00
parent a5f767b170
commit 1ec80883f0
79 changed files with 1807 additions and 1451 deletions

View file

@ -1,5 +1,4 @@
from compose_viz.cli import start_cli from compose_viz.cli import start_cli
if __name__ == "__main__": if __name__ == "__main__":
start_cli() start_cli()

View file

@ -1,9 +1,11 @@
from enum import Enum from enum import Enum
import typer
from typing import Optional from typing import Optional
import typer
from compose_viz import __app_name__, __version__ from compose_viz import __app_name__, __version__
from compose_viz.parser import Parser
from compose_viz.graph import Graph from compose_viz.graph import Graph
from compose_viz.parser import Parser
class VisualizationFormats(str, Enum): class VisualizationFormats(str, Enum):
@ -47,7 +49,7 @@ def compose_viz(
help="Show the version of compose-viz.", help="Show the version of compose-viz.",
callback=_version_callback, callback=_version_callback,
is_eager=True, is_eager=True,
) ),
) -> None: ) -> None:
parser = Parser() parser = Parser()
compose = parser.parse(input_path) compose = parser.parse(input_path)

View file

@ -1,4 +1,5 @@
from typing import List from typing import List
from compose_viz.service import Service from compose_viz.service import Service

View file

@ -1,5 +1,8 @@
from typing import Optional
class Extends: class Extends:
def __init__(self, service_name: str, from_file: str = None): def __init__(self, service_name: str, from_file: Optional[str] = None):
self._service_name = service_name self._service_name = service_name
self._from_file = from_file self._from_file = from_file

View file

@ -5,17 +5,17 @@ from compose_viz.compose import Compose
def apply_vertex_style(type) -> dict: def apply_vertex_style(type) -> dict:
style = { style = {
'service': { "service": {
'shape': 'component', "shape": "component",
}, },
'volume': { "volume": {
'shape': 'folder', "shape": "folder",
}, },
'network': { "network": {
'shape': 'pentagon', "shape": "pentagon",
}, },
'port': { "port": {
'shape': 'circle', "shape": "circle",
}, },
} }
@ -24,18 +24,18 @@ def apply_vertex_style(type) -> dict:
def apply_edge_style(type) -> dict: def apply_edge_style(type) -> dict:
style = { style = {
'ports': { "ports": {
'style': 'solid', "style": "solid",
}, },
'links': { "links": {
'style': 'solid', "style": "solid",
}, },
'volumes': { "volumes": {
'style': 'dashed', "style": "dashed",
},
"depends_on": {
"style": "dotted",
}, },
'depends_on': {
'style': 'dotted',
}
} }
return style[type] return style[type]
@ -44,7 +44,7 @@ def apply_edge_style(type) -> dict:
class Graph: class Graph:
def __init__(self, compose: Compose, filename: str) -> None: def __init__(self, compose: Compose, filename: str) -> None:
self.dot = graphviz.Digraph() self.dot = graphviz.Digraph()
self.dot.attr('graph', background='#ffffff', pad='0.5', ratio='fill') self.dot.attr("graph", background="#ffffff", pad="0.5", ratio="fill")
self.compose = compose self.compose = compose
self.filename = filename self.filename = filename
@ -56,17 +56,17 @@ class Graph:
def render(self, format: str, cleanup: bool = True) -> None: def render(self, format: str, cleanup: bool = True) -> None:
for service in self.compose.services: for service in self.compose.services:
self.add_vertex(service.name, 'service') self.add_vertex(service.name, "service")
for network in service.networks: for network in service.networks:
self.add_vertex("net#" + network, 'network') self.add_vertex("net#" + network, "network")
self.add_edge(service.name, "net#" + network, 'links') self.add_edge(service.name, "net#" + network, "links")
for volume in service.volumes: for volume in service.volumes:
self.add_vertex(volume, 'volume') self.add_vertex(volume, "volume")
self.add_edge(service.name, volume, 'links') self.add_edge(service.name, volume, "links")
for port in service.ports: for port in service.ports:
self.add_vertex(port, 'port') self.add_vertex(port, "port")
self.add_edge(service.name, port, 'ports') self.add_edge(service.name, port, "ports")
for depends_on in service.depends_on: for depends_on in service.depends_on:
self.dot.edge(depends_on, service.name, 'depends_on') self.dot.edge(depends_on, service.name, "depends_on")
self.dot.render(outfile=self.filename, format=format, cleanup=cleanup) self.dot.render(outfile=self.filename, format=format, cleanup=cleanup)

View file

@ -1,48 +1,60 @@
from re import S from typing import List, Optional
from compose_viz.compose import Compose
from compose_viz.compose import Service
from ruamel.yaml import YAML from ruamel.yaml import YAML
from compose_viz.compose import Compose, Service
class Parser: class Parser:
def __init__(self): def __init__(self):
pass pass
def parse(self, file_path: str) -> Compose: def parse(self, file_path: str) -> Compose:
# validate input file using `docker-compose config -q sys.argv[1]` first
# load the yaml file # load the yaml file
with open(file_path, "r") as f: with open(file_path, "r") as f:
try: try:
yaml = YAML(typ='safe', pure=True) yaml = YAML(typ="safe", pure=True)
yaml_data = yaml.load(f) yaml_data = yaml.load(f)
except YAML.YAMLError as exc: except Exception as e:
raise YAML.YAMLError raise Exception(f"Error parsing file {file_path}: {e}")
# validate the yaml file # validate the yaml file
if not yaml_data: if not yaml_data:
print("Error: empty yaml file") print("Error: empty yaml file")
raise ValueError raise ValueError
if not yaml_data.get("services"): if not yaml_data.get("services"):
print("Error: no services found") print("Error: no services found")
raise ValueError raise ValueError
# parse services data into Service objects # parse services data into Service objects
services_data = yaml_data["services"] services_data = yaml_data["services"]
services = [] services = []
for service, service_name in zip(services_data.values(), services_data.keys()): for service, service_name in zip(services_data.values(), services_data.keys()):
#print("name: {}".format(service_name)) # print("name: {}".format(service_name))
service_image: Optional[str] = None
if service.get("image"): if service.get("image"):
service_image = service["image"] service_image = service["image"]
#print("image: {}".format(service_image)) # print("image: {}".format(service_image))
service_networks: List[str] = []
if service.get("networks"): if service.get("networks"):
if(type(service["networks"]) is list): if type(service["networks"]) is list:
service_networks = service["networks"] service_networks = service["networks"]
else: else:
service_networks = list(service["networks"].keys()) service_networks = list(service["networks"].keys())
#print("networks: {}".format(service_networks)) # print("networks: {}".format(service_networks))
services.append(Service(
name=service_name, services.append(
image=service_image, Service(
networks=service_networks, name=service_name,
)) image=service_image,
networks=service_networks,
)
)
# create Compose object # create Compose object
compose = Compose(services) compose = Compose(services)

View file

@ -1,10 +1,20 @@
from typing import List from typing import List, Optional
from compose_viz.extends import Extends from compose_viz.extends import Extends
class Service: class Service:
def __init__(self, name: str, image: str = None, ports: List[str] = [], networks: List[str] = [], volumes: List[str] = [], depends_on: List[str] = [], links: List[str] = [], extends: Extends = None) -> None: def __init__(
self,
name: str,
image: Optional[str] = None,
ports: List[str] = [],
networks: List[str] = [],
volumes: List[str] = [],
depends_on: List[str] = [],
links: List[str] = [],
extends: Optional[Extends] = None,
) -> None:
self._name = name self._name = name
if image is None and extends is None: if image is None and extends is None:

View file

@ -1,77 +1,81 @@
import os import os
import pytest import pytest
from typer.testing import CliRunner from typer.testing import CliRunner
from compose_viz import cli
from compose_viz import cli
runner = CliRunner() runner = CliRunner()
@pytest.mark.parametrize("file_number", [
"000001", @pytest.mark.parametrize(
"000010", "file_number",
"000011", [
"000100", "000001",
"000101", "000010",
"000110", "000011",
"000111", "000100",
"001000", "000101",
"001001", "000110",
"001010", "000111",
"001011", "001000",
"001100", "001001",
"001101", "001010",
"001110", "001011",
"001111", "001100",
"010000", "001101",
"010001", "001110",
"010010", "001111",
"010011", "010000",
"010100", "010001",
"010101", "010010",
"010110", "010011",
"010111", "010100",
"011000", "010101",
"011001", "010110",
"011010", "010111",
"011011", "011000",
"011100", "011001",
"011101", "011010",
"011110", "011011",
"011111", "011100",
"100000", "011101",
"100001", "011110",
"100010", "011111",
"100011", "100000",
"100100", "100001",
"100101", "100010",
"100110", "100011",
"100111", "100100",
"101000", "100101",
"101001", "100110",
"101010", "100111",
"101011", "101000",
"101100", "101001",
"101101", "101010",
"101110", "101011",
"101111", "101100",
"110000", "101101",
"110001", "101110",
"110010", "101111",
"110011", "110000",
"110100", "110001",
"110101", "110010",
"110110", "110011",
"110111", "110100",
"111000", "110101",
"111001", "110110",
"111010", "110111",
"111011", "111000",
"111100", "111001",
"111101", "111010",
"111110", "111011",
"111111", "111100",
]) "111101",
"111110",
"111111",
],
)
def test_cli(file_number: str): def test_cli(file_number: str):
input_path = f"tests/in/{file_number}.yaml" input_path = f"tests/in/{file_number}.yaml"
output_path = f"{file_number}.png" output_path = f"{file_number}.png"

View file

@ -1,22 +1,29 @@
import pytest import pytest
from compose_viz.extends import Extends from compose_viz.extends import Extends
from compose_viz.service import Service from compose_viz.service import Service
def test_extend_init(): def test_extend_init():
try: try:
Extends(service_name='frontend', from_file='tests/in/000001.yaml') Extends(service_name="frontend", from_file="tests/in/000001.yaml")
Extends(service_name='frontend') Extends(service_name="frontend")
assert True assert True
except: except Exception as e:
assert False assert False, e
with pytest.raises(TypeError): with pytest.raises(TypeError):
Extends(from_file='tests/in/000001.yaml') Extends(from_file="tests/in/000001.yaml") # type: ignore
def test_service_init(): def test_service_init():
with pytest.raises(ValueError, match=r"Both image and extends are not defined in service 'frontend', aborting."): with pytest.raises(ValueError, match=r"Both image and extends are not defined in service 'frontend', aborting."):
Service(name='frontend') Service(name="frontend")
with pytest.raises(ValueError, match=r"Only one of image and extends can be defined in service 'frontend', aborting."): with pytest.raises(
Service(name='frontend', image='image', extends=Extends(service_name='frontend', from_file='tests/in/000001.yaml')) ValueError, match=r"Only one of image and extends can be defined in service 'frontend', aborting."
):
Service(
name="frontend", image="image", extends=Extends(service_name="frontend", from_file="tests/in/000001.yaml")
)

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
from typer.testing import CliRunner from typer.testing import CliRunner
from compose_viz import cli, __app_name__, __version__
from compose_viz import __app_name__, __version__, cli
runner = CliRunner() runner = CliRunner()