many-repos/many_repos/config.py

49 lines
1.3 KiB
Python
Raw Normal View History

2024-05-25 23:43:15 +02:00
import tomllib
from pathlib import Path
2024-05-27 08:55:13 +02:00
from typing import Any
2024-05-25 23:43:15 +02:00
from typing import NamedTuple
2024-05-27 08:55:13 +02:00
from typing import Self
2024-05-25 23:43:15 +02:00
from many_repos import errors
2024-05-27 08:55:13 +02:00
2024-05-25 23:43:15 +02:00
class Source(NamedTuple):
source_type: str
username: str
token: str
2024-05-27 08:55:13 +02:00
forks: bool
@classmethod
def from_dict(cls, _dict: dict[str, Any]) -> Self:
return cls(
source_type=_dict.get("type"),
username=_dict.get("username"),
token=_dict.get("token"),
forks=_dict.get("forks", False)
)
2024-05-25 23:43:15 +02:00
class Config(NamedTuple):
output_dir: str | Path
2024-05-27 08:55:13 +02:00
sources_configs: dict[str, Source] | None
@classmethod
def from_dict(cls, _dict: dict[str, Any]) -> Self:
output_dir = _dict.get("config").get("output_dir", None)
sources = {name: Source.from_dict(src) for name, src in _dict.get("sources").items()}
if not output_dir:
raise errors.InvalidConfig("`output_dir` needs to be specified!")
cfg = cls(output_dir=output_dir, sources_configs=sources)
return cfg
2024-05-25 23:43:15 +02:00
def load_config(config_path: str | Path) -> Config:
config_path = Path(config_path)
if not config_path.exists():
raise errors.ConfigNotFound(f"Config at path {config_path} not found!")
2024-05-27 08:55:13 +02:00
with config_path.open("rb") as fp:
2024-05-25 23:43:15 +02:00
parsed_config = tomllib.load(fp)
2024-05-27 08:55:13 +02:00
return Config.from_dict(parsed_config)