config.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from collections import namedtuple
  2. try:
  3. # Python 2
  4. from ConfigParser import ConfigParser
  5. except ImportError:
  6. # Python 3
  7. from configparser import ConfigParser
  8. CONFIG_SECTION_LOCATION = 'location'
  9. CONFIG_SECTION_RETENTION = 'retention'
  10. CONFIG_FORMAT = {
  11. CONFIG_SECTION_LOCATION: ('source_directories', 'repository'),
  12. CONFIG_SECTION_RETENTION: ('keep_daily', 'keep_weekly', 'keep_monthly'),
  13. }
  14. LocationConfig = namedtuple('LocationConfig', CONFIG_FORMAT[CONFIG_SECTION_LOCATION])
  15. RetentionConfig = namedtuple('RetentionConfig', CONFIG_FORMAT[CONFIG_SECTION_RETENTION])
  16. def parse_configuration(config_filename):
  17. '''
  18. Given a config filename of the expected format, return the parse configuration as a tuple of
  19. (LocationConfig, RetentionConfig). Raise if the format is not as expected.
  20. '''
  21. parser = ConfigParser()
  22. parser.read((config_filename,))
  23. section_names = parser.sections()
  24. expected_section_names = CONFIG_FORMAT.keys()
  25. if set(section_names) != set(expected_section_names):
  26. raise ValueError(
  27. 'Expected config sections {} but found sections: {}'.format(
  28. ', '.join(expected_section_names),
  29. ', '.join(section_names)
  30. )
  31. )
  32. for section_name in section_names:
  33. option_names = parser.options(section_name)
  34. expected_option_names = CONFIG_FORMAT[section_name]
  35. if set(option_names) != set(expected_option_names):
  36. raise ValueError(
  37. 'Expected options {} in config section {} but found options: {}'.format(
  38. ', '.join(expected_option_names),
  39. section_name,
  40. ', '.join(option_names)
  41. )
  42. )
  43. return (
  44. LocationConfig(*(
  45. parser.get(CONFIG_SECTION_LOCATION, option_name)
  46. for option_name in CONFIG_FORMAT[CONFIG_SECTION_LOCATION]
  47. )),
  48. RetentionConfig(*(
  49. parser.getint(CONFIG_SECTION_RETENTION, option_name)
  50. for option_name in CONFIG_FORMAT[CONFIG_SECTION_RETENTION]
  51. ))
  52. )