configreader.py 6.2 KB

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