1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2024-11-22 21:03:00 +00:00
kiwi-scp/kiwi_scp/instance.py

67 lines
1.7 KiB
Python
Raw Normal View History

2021-10-22 15:50:26 +00:00
import functools
import re
from pathlib import Path
2021-10-25 11:00:11 +00:00
from typing import List, Dict, Any, Generator
2021-10-22 15:50:26 +00:00
import attr
2021-10-25 11:29:12 +00:00
import click
2021-10-22 15:50:26 +00:00
from ._constants import COMPOSE_FILE_NAME
2021-10-27 11:33:26 +00:00
from .config import KiwiConfig
from .misc import YAML
2021-10-22 15:50:26 +00:00
_RE_CONFDIR = re.compile(r"^\s*\$(?:CONFDIR|{CONFDIR})/+(.*)$", flags=re.UNICODE)
@attr.s
class Service:
name: str = attr.ib()
configs: List[Path] = attr.ib()
@classmethod
def from_description(cls, name: str, description: Dict[str, Any]):
configs: List[Path] = []
if "volumes" in description:
volumes: List[str] = description["volumes"]
for volume in volumes:
host_part = volume.split(":")[0]
confdir = _RE_CONFDIR.match(host_part)
if confdir:
configs.append(Path(confdir.group(1)))
return cls(
name=name,
configs=configs,
)
@attr.s
class Instance:
directory: Path = attr.ib(default=Path('.'))
@property
2021-10-26 13:59:38 +00:00
def config(self) -> KiwiConfig:
2021-10-22 15:50:26 +00:00
"""shorthand: get the current configuration"""
2021-10-26 13:59:38 +00:00
return KiwiConfig.from_directory(self.directory)
2021-10-26 10:28:06 +00:00
2021-10-26 13:59:38 +00:00
@classmethod
@functools.lru_cache(maxsize=10)
def _parse_compose_file(cls, directory: Path):
with open(directory.joinpath(COMPOSE_FILE_NAME), "r") as cf:
2021-10-27 11:33:26 +00:00
return YAML().load(cf)
2021-10-26 13:59:38 +00:00
def get_services(self, project_name: str) -> Generator[Service, None, None]:
yml = Instance._parse_compose_file(self.directory.joinpath(project_name))
2021-10-22 15:50:26 +00:00
2021-10-25 11:00:11 +00:00
return (
2021-10-26 13:59:38 +00:00
Service.from_description(name, description)
for name, description in yml["services"].items()
2021-10-25 11:00:11 +00:00
)
2021-10-25 11:29:12 +00:00
pass_instance = click.make_pass_decorator(Instance, ensure=True)