kiwi-scp/kiwi_scp/config.py

80 lines
1.9 KiB
Python
Raw Normal View History

2020-08-12 15:46:50 +00:00
import re
2021-10-11 00:58:49 +00:00
from typing import Optional, Dict, List
2020-08-04 18:24:19 +00:00
2021-10-11 00:58:49 +00:00
import pydantic
2020-08-06 01:45:12 +00:00
2020-08-04 14:52:30 +00:00
2021-10-11 00:58:49 +00:00
class _Storage(pydantic.BaseModel):
"""a storage subsection"""
2020-08-13 08:48:01 +00:00
2021-10-11 00:58:49 +00:00
directory: str
2020-08-06 01:45:12 +00:00
2020-08-13 08:48:01 +00:00
2021-10-11 00:58:49 +00:00
class _Project(pydantic.BaseModel):
"""a project subsection"""
2020-08-06 12:34:25 +00:00
2021-10-11 00:58:49 +00:00
name: str
enabled: bool = True
storage: Optional[_Storage]
2020-08-06 12:34:25 +00:00
2021-10-11 00:58:49 +00:00
@pydantic.root_validator(pre=True)
@classmethod
def check_grammar(cls, values):
if isinstance(values, dict):
if "name" in values:
return values
2020-08-11 15:23:24 +00:00
2021-10-11 00:58:49 +00:00
elif len(values) == 1:
name, enabled = list(values.items())[0]
return {"name": name, "enabled": True if enabled is None else enabled}
2020-08-11 15:23:24 +00:00
2021-10-11 00:58:49 +00:00
elif isinstance(values, str):
return {"name": values}
2020-08-20 11:29:08 +00:00
2021-10-11 00:58:49 +00:00
class _Network(pydantic.BaseModel):
"""a network subsection"""
2020-08-20 11:29:08 +00:00
2021-10-11 00:58:49 +00:00
name: str
cidr: str
2020-08-13 08:48:01 +00:00
2020-08-06 12:34:25 +00:00
2021-10-11 00:58:49 +00:00
class Config(pydantic.BaseModel):
"""represents a kiwi.yml"""
2021-10-11 00:58:49 +00:00
version: str
shells: Optional[List[str]]
environment: Optional[Dict[str, Optional[str]]]
2020-08-13 08:48:01 +00:00
2021-10-11 00:58:49 +00:00
projects: Optional[List[_Project]]
storage: _Storage
network: _Network
2021-10-11 00:58:49 +00:00
@pydantic.validator("version")
2020-08-06 11:43:45 +00:00
@classmethod
2021-10-11 00:58:49 +00:00
def check_version(cls, value: str) -> str:
if not re.match(r"^[0-9]+(\.[0-9]+(\.[0-9]+)?)?$", value):
raise ValueError
2020-08-06 01:45:12 +00:00
2021-10-11 00:58:49 +00:00
return value
2020-08-13 08:48:01 +00:00
2021-10-11 00:58:49 +00:00
@pydantic.validator("environment", pre=True)
2020-08-06 11:43:45 +00:00
@classmethod
2021-10-11 00:58:49 +00:00
def unify_env(cls, value) -> Optional[Dict[str, Optional[str]]]:
if isinstance(value, dict):
return value
elif isinstance(value, list):
result: Dict[str, Optional[str]] = {}
for item in value:
idx = item.find("=")
if idx == -1:
key, value = item, None
else:
key, value = item[:idx], item[idx + 1:]
result[key] = value
return result
else:
return None