configreader.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/python3
  2. import configparser
  3. # contains all configuration sections and subsections
  4. # the subsections are a tuple with their name and a boolean, which
  5. # tells us whether the option is mandatory
  6. VALID_CONFIG_SECTIONS = {
  7. 'Application': [
  8. ('name', True),
  9. ('version', True),
  10. ('entry_point', True),
  11. ('script', False),
  12. ('icon', False),
  13. ('console', False),
  14. ],
  15. 'Build': [
  16. ('directory', False),
  17. ('installer_name', False),
  18. ('nsi_template', False),
  19. ],
  20. 'Include': [
  21. ('packages', False),
  22. ('files', False),
  23. ],
  24. 'Python': [
  25. ('version', True),
  26. ('bitness', False),
  27. ],
  28. }
  29. class InvalidConfig(ValueError):
  30. pass
  31. def read_and_validate(config_file):
  32. cfg = configparser.ConfigParser()
  33. cfg.read(config_file)
  34. # check mandatory sections
  35. for section_name, subsection_list in VALID_CONFIG_SECTIONS.items():
  36. for subsection_name, mandatory in subsection_list:
  37. if mandatory:
  38. try:
  39. cfg[section_name][subsection_name]
  40. except KeyError:
  41. err_msg = ("The section '{0}' must contain a "
  42. "subsection '{1}'!").format(
  43. section_name,
  44. subsection_name)
  45. raise InvalidConfig(err_msg)
  46. # check for invalid sections and subsections
  47. for section in cfg:
  48. # check section names
  49. section_name = str(section)
  50. is_valid_section_name = section_name in VALID_CONFIG_SECTIONS.keys()
  51. if section_name == 'DEFAULT':
  52. # DEFAULT is always inside the config, so just jump over it
  53. continue
  54. if not is_valid_section_name:
  55. err_msg = ("{0} is not a valid section header. Must "
  56. "be one of these: {1}").format(
  57. section_name, ', '.join(valid_section_headers))
  58. raise InvalidConfig(err_msg)
  59. # check subsection names
  60. for subsection in cfg[section_name]:
  61. subsection_name = str(subsection)
  62. subsection_names = [s[0] for s in VALID_CONFIG_SECTIONS[section_name]]
  63. is_valid_subsection = subsection_name in subsection_names
  64. if not is_valid_subsection:
  65. err_msg = ("'{0}' is not a valid subsection name for '{1}'. Must "
  66. "be one of these: {2}").format(
  67. subsection_name,
  68. section_name,
  69. ', '.join(subsection_names))
  70. raise InvalidConfig(err_msg)
  71. return cfg