config.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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).
  20. Raise IOError if the file cannot be read, or ValueError if the format is not as expected.
  21. '''
  22. parser = ConfigParser()
  23. parser.readfp(open(config_filename))
  24. section_names = parser.sections()
  25. expected_section_names = CONFIG_FORMAT.keys()
  26. if set(section_names) != set(expected_section_names):
  27. raise ValueError(
  28. 'Expected config sections {} but found sections: {}'.format(
  29. ', '.join(expected_section_names),
  30. ', '.join(section_names)
  31. )
  32. )
  33. for section_name in section_names:
  34. option_names = parser.options(section_name)
  35. expected_option_names = CONFIG_FORMAT[section_name]
  36. if set(option_names) != set(expected_option_names):
  37. raise ValueError(
  38. 'Expected options {} in config section {} but found options: {}'.format(
  39. ', '.join(expected_option_names),
  40. section_name,
  41. ', '.join(option_names)
  42. )
  43. )
  44. return (
  45. LocationConfig(*(
  46. parser.get(CONFIG_SECTION_LOCATION, option_name)
  47. for option_name in CONFIG_FORMAT[CONFIG_SECTION_LOCATION]
  48. )),
  49. RetentionConfig(*(
  50. parser.getint(CONFIG_SECTION_RETENTION, option_name)
  51. for option_name in CONFIG_FORMAT[CONFIG_SECTION_RETENTION]
  52. ))
  53. )