import configparser import uuid from pathlib import Path from typing import List from ee import EeException from ee.digikey import DigikeyStore from ee.tools import mk_parents def load_config(project_dir: Path) -> configparser.ConfigParser: config = configparser.ConfigParser() config_path = project_dir / "eeconfig" try: with config_path.open("r") as f: config.read_file(f, source=str(config_path)) except FileNotFoundError: pass return config class SupplierDescriptor(object): def __init__(self, key: str, uri: str, name: str): self.key = key self.uri = uri self.name = name class Project(object): def __init__(self, project_dir: Path, cfg: configparser.ConfigParser): self.project_dir = project_dir self._cfg = cfg project = self.get_or_create_section("project") project["uuid"] = project.get("uuid", str(uuid.uuid4())) self.public_dir = self.project_dir / "ee" self.report_dir = self.public_dir / "reports" self.cache_dir = self.public_dir / "cache" self.orders_dir = Path(project.get("orders-dir", self.public_dir / "orders")) # TODO: read from config self._suppliers = [] digikey_store = DigikeyStore.from_store_code("us") self._suppliers.append(SupplierDescriptor("digikey", digikey_store.url, "Digikey")) @property def suppliers(self) -> List[SupplierDescriptor]: return self._suppliers def get_supplier_by_key(self, key) -> SupplierDescriptor: sd = next((s for s in self._suppliers if s.key == key), None) if sd: return sd raise EeException("No such supplier configured: {}".format(key)) def get_supplier_by_uri(self, uri) -> SupplierDescriptor: sd = next((s for s in self._suppliers if s.uri == uri), None) if sd: return sd raise EeException("No such supplier configured: {}".format(uri)) @property def cfg(self): return self._cfg def get_or_create_section(self, section): try: return self._cfg[section] except KeyError: self._cfg.add_section(section) return self._cfg[section] @property def uuid(self): return uuid.UUID(hex=self._cfg["project"]["uuid"]) @classmethod def load(cls, project_dir=Path(".")): cfg = load_config(project_dir) return Project(project_dir, cfg) def save(self): path = self.project_dir / "eeconfig" mk_parents(path) with path.open("w") as f: self._cfg.write(f)