config.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 ChildConfig(BaseConfig):
  16. def __init__(self, config, path):
  17. self.path = path
  18. self.config = config
  19. self.id = slugify(path, max_length=255)
  20. self.name = os.path.splitext(os.path.basename(path))[0]
  21. if not os.path.exists(path):
  22. raise ConfigException("Repo config file not found: {}".format(path))
  23. with open(path) as f:
  24. self._data = yaml.load(f, Loader=yaml.SafeLoader) or {}
  25. self._data['name'] = self.name
  26. class Config(BaseConfig):
  27. def __init__(self, path):
  28. self.path = os.path.join(path, 'pacman-repo.yml')
  29. if not os.path.exists(self.path):
  30. self.path = os.path.join(path, 'pacman-repo.yaml')
  31. if not os.path.exists(self.path):
  32. raise ConfigException("Base config file not found: {}".format(path))
  33. with open(self.path) as f:
  34. self._data = yaml.load(f, Loader=yaml.SafeLoader) or {}
  35. if not self._data.get("cachedir"):
  36. self._data["cachedir"] = "/var/cache/pacman-repo.d"
  37. if "~" in self["cachedir"]:
  38. self._data["cachedir"] = os.path.expanduser(self["cachedir"])
  39. self._data["cachedir"] = os.path.abspath(self["cachedir"])
  40. if not os.path.exists(self["cachedir"]):
  41. os.makedirs(self["cachedir"])
  42. print("Creating cachedir {}".format(self["cachedir"]))
  43. self.repos = []
  44. self.servers = []
  45. with pushd(path):
  46. for source in self["repos"]:
  47. for path in glob('{}/*.yml'.format(source)) + \
  48. glob('{}/*.yaml'.format(source)):
  49. self.repos.append(RepoConfig(self, path))
  50. for server in self["servers"]:
  51. for path in glob('{}/*.yml'.format(server)) + \
  52. glob('{}/*.yaml'.format(server)):
  53. self.servers.append(ServerConfig(self, path))
  54. class RepoConfig(ChildConfig):
  55. pass
  56. class ServerConfig(ChildConfig):
  57. pass