config.py 2.0 KB

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