config.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. from collections import OrderedDict, namedtuple
  2. try:
  3. # Python 2
  4. from ConfigParser import ConfigParser
  5. except ImportError:
  6. # Python 3
  7. from configparser import ConfigParser
  8. Section_format = namedtuple('Section_format', ('name', 'options'))
  9. Config_option = namedtuple('Config_option', ('name', 'value_type', 'required'))
  10. def option(name, value_type=str, required=True):
  11. '''
  12. Given a config file option name, an expected type for its value, and whether it's required,
  13. return a Config_option capturing that information.
  14. '''
  15. return Config_option(name, value_type, required)
  16. CONFIG_FORMAT = (
  17. Section_format(
  18. 'location',
  19. (
  20. option('source_directories'),
  21. option('repository'),
  22. ),
  23. ),
  24. Section_format(
  25. 'retention',
  26. (
  27. option('keep_within', required=False),
  28. option('keep_hourly', int, required=False),
  29. option('keep_daily', int, required=False),
  30. option('keep_weekly', int, required=False),
  31. option('keep_monthly', int, required=False),
  32. option('keep_yearly', int, required=False),
  33. option('prefix', required=False),
  34. ),
  35. ),
  36. Section_format(
  37. 'consistency',
  38. (
  39. option('checks', required=False),
  40. ),
  41. )
  42. )
  43. def validate_configuration_format(parser, config_format):
  44. '''
  45. Given an open ConfigParser and an expected config file format, validate that the parsed
  46. configuration file has the expected sections, that any required options are present in those
  47. sections, and that there aren't any unexpected options.
  48. A section is required if any of its contained options are required.
  49. Raise ValueError if anything is awry.
  50. '''
  51. section_names = set(parser.sections())
  52. required_section_names = tuple(
  53. section.name for section in config_format
  54. if any(option.required for option in section.options)
  55. )
  56. unknown_section_names = section_names - set(
  57. section_format.name for section_format in config_format
  58. )
  59. if unknown_section_names:
  60. raise ValueError(
  61. 'Unknown config sections found: {}'.format(', '.join(unknown_section_names))
  62. )
  63. missing_section_names = set(required_section_names) - section_names
  64. if missing_section_names:
  65. raise ValueError(
  66. 'Missing config sections: {}'.format(', '.join(missing_section_names))
  67. )
  68. for section_format in config_format:
  69. if section_format.name not in section_names:
  70. continue
  71. option_names = parser.options(section_format.name)
  72. expected_options = section_format.options
  73. unexpected_option_names = set(option_names) - set(option.name for option in expected_options)
  74. if unexpected_option_names:
  75. raise ValueError(
  76. 'Unexpected options found in config section {}: {}'.format(
  77. section_format.name,
  78. ', '.join(sorted(unexpected_option_names)),
  79. )
  80. )
  81. missing_option_names = tuple(
  82. option.name for option in expected_options if option.required
  83. if option.name not in option_names
  84. )
  85. if missing_option_names:
  86. raise ValueError(
  87. 'Required options missing from config section {}: {}'.format(
  88. section_format.name,
  89. ', '.join(missing_option_names)
  90. )
  91. )
  92. # Describes a parsed configuration, where each attribute is the name of a configuration file section
  93. # and each value is a dict of that section's parsed options.
  94. Parsed_config = namedtuple('Config', (section_format.name for section_format in CONFIG_FORMAT))
  95. def parse_section_options(parser, section_format):
  96. '''
  97. Given an open ConfigParser and an expected section format, return the option values from that
  98. section as a dict mapping from option name to value. Omit those options that are not present in
  99. the parsed options.
  100. Raise ValueError if any option values cannot be coerced to the expected Python data type.
  101. '''
  102. type_getter = {
  103. str: parser.get,
  104. int: parser.getint,
  105. }
  106. return OrderedDict(
  107. (option.name, type_getter[option.value_type](section_format.name, option.name))
  108. for option in section_format.options
  109. if parser.has_option(section_format.name, option.name)
  110. )
  111. def parse_configuration(config_filename):
  112. '''
  113. Given a config filename of the expected format, return the parsed configuration as Parsed_config
  114. data structure.
  115. Raise IOError if the file cannot be read, or ValueError if the format is not as expected.
  116. '''
  117. parser = ConfigParser()
  118. parser.readfp(open(config_filename))
  119. validate_configuration_format(parser, CONFIG_FORMAT)
  120. return Parsed_config(
  121. *(
  122. parse_section_options(parser, section_format)
  123. for section_format in CONFIG_FORMAT
  124. )
  125. )