configreader.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/python3
  2. import configparser
  3. class SectionValidator(object):
  4. def __init__(self, keys):
  5. """
  6. keys
  7. list of tuples containing the names and whether the
  8. key is mandatory
  9. """
  10. self.keys = keys
  11. def check(self, config, section_name):
  12. """
  13. validates the section, if this is the correct validator for it
  14. returns True if this is the correct validator for this section
  15. raises InvalidConfig if something inside the section is wrong
  16. """
  17. self._check_mandatory_fields(section_name, config[section_name])
  18. self._check_invalid_keys(section_name, config[section_name])
  19. def _check_mandatory_fields(self, section_name, key):
  20. for key_name, mandatory in self.keys:
  21. if mandatory:
  22. try:
  23. key[key_name]
  24. except KeyError:
  25. err_msg = ("The section '{0}' must contain a "
  26. "key '{1}'!").format(
  27. section_name,
  28. key_name)
  29. raise InvalidConfig(err_msg)
  30. def _check_invalid_keys(self, section_name, section):
  31. for key in section:
  32. key_name = str(key)
  33. valid_key_names = [s[0] for s in self.keys]
  34. is_valid_key = key_name in valid_key_names
  35. if not is_valid_key:
  36. err_msg = ("'{0}' is not a valid key name for '{1}'. Must "
  37. "be one of these: {2}").format(
  38. key_name,
  39. section_name,
  40. ', '.join(valid_key_names))
  41. raise InvalidConfig(err_msg)
  42. # contains all configuration sections and keys
  43. # the keys are a tuple with their name and a boolean, which
  44. # tells us whether the option is mandatory
  45. CONFIG_VALIDATORS = {
  46. 'Application': SectionValidator([
  47. ('name', True),
  48. ('version', True),
  49. ('entry_point', False),
  50. ('script', False),
  51. ('target', False),
  52. ('parameters', False),
  53. ('icon', False),
  54. ('console', False),
  55. ('extra_preamble', False),
  56. ]),
  57. 'Build': SectionValidator([
  58. ('directory', False),
  59. ('installer_name', False),
  60. ('nsi_template', False),
  61. ]),
  62. 'Include': SectionValidator([
  63. ('packages', False),
  64. ('files', False),
  65. ]),
  66. 'Python': SectionValidator([
  67. ('version', True),
  68. ('bitness', False),
  69. ]),
  70. 'Shortcut': SectionValidator([
  71. ('entry_point', False),
  72. ('script', False),
  73. ('target', False),
  74. ('parameters', False),
  75. ('icon', False),
  76. ('console', False),
  77. ('extra_preamble', False),
  78. ]),
  79. }
  80. class InvalidConfig(ValueError):
  81. pass
  82. def read_and_validate(config_file):
  83. # Interpolation interferes with Windows-style environment variables, so
  84. # it's disabled for now.
  85. config = configparser.ConfigParser(interpolation=None)
  86. config.read(config_file)
  87. for section in config.sections():
  88. if section in CONFIG_VALIDATORS:
  89. CONFIG_VALIDATORS[section].check(config, section)
  90. elif section.startswith('Shortcut '):
  91. CONFIG_VALIDATORS['Shortcut'].check(config, section)
  92. else:
  93. valid_section_names = CONFIG_VALIDATORS.keys()
  94. err_msg = ("{0} is not a valid section header. Must "
  95. "be one of these: {1}").format(
  96. section,
  97. ', '.join(['"%s"' % n for n in valid_section_names]))
  98. raise InvalidConfig(err_msg)
  99. return config
  100. def read_extra_files(cfg):
  101. """Read the list of extra files from the config file.
  102. Returns a list of 2-tuples: (file, destination_directory), which can be
  103. passed as the ``extra_files`` parameter to :class:`nsist.InstallerBuilder`.
  104. """
  105. lines = cfg.get('Include', 'files', fallback='').splitlines()
  106. pairs = []
  107. for line in lines:
  108. if '>' in line:
  109. file, dest = line.rsplit('>', 1)
  110. pairs.append((file.strip(), dest.strip()))
  111. else:
  112. pairs.append((line, '$INSTDIR'))
  113. return pairs
  114. def read_shortcuts_config(cfg):
  115. """Read and verify the shortcut definitions from the config file.
  116. There is one shortcut per 'Shortcut <name>' section, and one for the
  117. Application section.
  118. Returns a list of dictionaries with the fields from the shortcut sections.
  119. The optional 'icon' and 'console' fields will be filled with their
  120. default values if not supplied.
  121. """
  122. shortcuts = {}
  123. def _check_shortcut(name, sc, section):
  124. alternatives = ['entry_point', 'script', 'target']
  125. has_alternatives = sum(1 for k in alternatives if k in sc)
  126. if has_alternatives < 1:
  127. raise InvalidConfig('Section [{}] has none of {}.'.format(
  128. section, ', '.join(alternatives)))
  129. elif has_alternatives > 1:
  130. raise InvalidConfig('Section [{}] has more than one of {}.'.format(
  131. section, ', '.join(alternatives)))
  132. # Copy to a regular dict so it can hold a boolean value
  133. sc2 = dict(sc)
  134. if 'icon' not in sc2:
  135. from . import DEFAULT_ICON
  136. sc2['icon'] = DEFAULT_ICON
  137. sc2['console'] = sc.getboolean('console', fallback=False)
  138. sc2['parameters'] = sc.get('parameters', fallback='')
  139. if 'extra_preamble' in sc2 and 'entry_point' not in sc2:
  140. raise InvalidConfig('extra_preamble is only valid with entry_point')
  141. shortcuts[name] = sc2
  142. for section in cfg.sections():
  143. if section.startswith("Shortcut "):
  144. name = section[len("Shortcut "):]
  145. _check_shortcut(name, cfg[section], section)
  146. appcfg = cfg['Application']
  147. _check_shortcut(appcfg['name'], appcfg, 'Application')
  148. return shortcuts