config.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import yaml
  2. import os
  3. from glob import glob
  4. from slugify import slugify
  5. from .util import pushd
  6. class ConfigException(Exception):
  7. pass
  8. class BaseConfig(object):
  9. def __getitem__(self, name):
  10. return self._data[name]
  11. def __contains__(self, name):
  12. return name in self._data
  13. def __str__(self):
  14. return yaml.dump(self._data, default_flow_style=False)
  15. class Config(BaseConfig):
  16. def __init__(self, path):
  17. self.path = os.path.join(path, 'pacman-repo.yml')
  18. if not os.path.exists(self.path):
  19. self.path = os.path.join(path, 'pacman-repo.yaml')
  20. if not os.path.exists(self.path):
  21. raise ConfigException("Base config file not found: {}".format(path))
  22. with open(self.path) as f:
  23. self._data = yaml.load(f, Loader=yaml.SafeLoader) or {}
  24. self.repos = []
  25. self.servers = []
  26. with pushd(path):
  27. for source in self["repos"]:
  28. for path in glob('{}/*.yml'.format(source)) + \
  29. glob('{}/*.yaml'.format(source)):
  30. self.repos.append(RepoConfig(self, path))
  31. for server in self["servers"]:
  32. for path in glob('{}/*.yml'.format(server)) + \
  33. glob('{}/*.yaml'.format(server)):
  34. self.servers.append(ServerConfig(self, path))
  35. class RepoConfig(BaseConfig):
  36. def __init__(self, config, path):
  37. self.path = path
  38. self.config = config
  39. self.id = slugify(path, max_length=255)
  40. self.name = os.path.splitext(os.path.basename(path))[0]
  41. if not os.path.exists(path):
  42. raise ConfigException("Repo config file not found: {}".format(path))
  43. with open(path) as f:
  44. self._data = yaml.load(f, Loader=yaml.SafeLoader) or {}
  45. self._data['name'] = self.name
  46. class ServerConfig(BaseConfig):
  47. def __init__(self, config, path):
  48. self.path = path
  49. self.config = config
  50. self.id = slugify(path, max_length=255)
  51. self.name = os.path.splitext(os.path.basename(path))[0]
  52. if not os.path.exists(path):
  53. raise ConfigException("Repo config file not found: {}".format(path))
  54. with open(path) as f:
  55. self._data = yaml.load(f, Loader=yaml.SafeLoader) or {}
  56. self._data['name'] = self.name