import yaml import os from glob import glob from slugify import slugify from .util import pushd class ConfigException(Exception): pass class BaseConfig(object): def __getitem__(self, name): return self._data[name] def __contains__(self, name): return name in self._data def __str__(self): return yaml.dump(self._data, default_flow_style=False) class ChildConfig(BaseConfig): def __init__(self, config, path): self.path = path self.config = config self.id = slugify(path, max_length=255) self.name = os.path.splitext(os.path.basename(path))[0] if not os.path.exists(path): raise ConfigException("Repo config file not found: {}".format(path)) with open(path) as f: self._data = yaml.load(f, Loader=yaml.SafeLoader) or {} self._data['name'] = self.name class Config(BaseConfig): def __init__(self, path): self.path = os.path.join(path, 'pacman-repo.yml') if not os.path.exists(self.path): self.path = os.path.join(path, 'pacman-repo.yaml') if not os.path.exists(self.path): raise ConfigException("Base config file not found: {}".format(path)) with open(self.path) as f: self._data = yaml.load(f, Loader=yaml.SafeLoader) or {} if not self._data.get("cachedir"): self._data["cachedir"] = "/var/cache/pacman-repo.d" if "~" in self["cachedir"]: self._data["cachedir"] = os.path.expanduser(self["cachedir"]) self._data["cachedir"] = os.path.abspath(self["cachedir"]) if not os.path.exists(self["cachedir"]): os.makedirs(self["cachedir"]) print("Creating cachedir {}".format(self["cachedir"])) self.repos = [] self.servers = [] with pushd(path): for source in self["repos"]: for path in glob('{}/*.yml'.format(source)) + \ glob('{}/*.yaml'.format(source)): self.repos.append(RepoConfig(self, path)) for server in self["servers"]: for path in glob('{}/*.yml'.format(server)) + \ glob('{}/*.yaml'.format(server)): self.servers.append(ServerConfig(self, path)) class RepoConfig(ChildConfig): pass class ServerConfig(ChildConfig): pass