configreader.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. ('publisher', False),
  51. ('entry_point', False),
  52. ('script', False),
  53. ('target', False),
  54. ('parameters', False),
  55. ('icon', False),
  56. ('console', False),
  57. ('extra_preamble', False),
  58. ]),
  59. 'Build': SectionValidator([
  60. ('directory', False),
  61. ('installer_name', False),
  62. ('nsi_template', False),
  63. ]),
  64. 'Include': SectionValidator([
  65. ('packages', False),
  66. ('pypi_wheels', False),
  67. ('files', False),
  68. ('exclude', False),
  69. ]),
  70. 'Python': SectionValidator([
  71. ('version', False),
  72. ('bitness', False),
  73. ('format', False),
  74. ('include_msvcrt', False),
  75. ]),
  76. 'Shortcut': SectionValidator([
  77. ('entry_point', False),
  78. ('script', False),
  79. ('target', False),
  80. ('parameters', False),
  81. ('icon', False),
  82. ('console', False),
  83. ('extra_preamble', False),
  84. ]),
  85. 'Command': SectionValidator([
  86. ('entry_point', True),
  87. ('extra_preamble', False),
  88. ])
  89. }
  90. class InvalidConfig(ValueError):
  91. pass
  92. def read_and_validate(config_file):
  93. # Interpolation interferes with Windows-style environment variables, so
  94. # it's disabled for now.
  95. config = configparser.ConfigParser(interpolation=None)
  96. if config.read(config_file) == []:
  97. raise InvalidConfig("Config file not found: %r" % config_file)
  98. for section in config.sections():
  99. if section in CONFIG_VALIDATORS:
  100. CONFIG_VALIDATORS[section].check(config, section)
  101. elif section.startswith('Shortcut '):
  102. CONFIG_VALIDATORS['Shortcut'].check(config, section)
  103. elif section.startswith('Command '):
  104. CONFIG_VALIDATORS['Command'].check(config, section)
  105. else:
  106. valid_section_names = CONFIG_VALIDATORS.keys()
  107. err_msg = ("{0} is not a valid section header. Must "
  108. "be one of these: {1}").format(
  109. section,
  110. ', '.join(['"%s"' % n for n in valid_section_names]))
  111. raise InvalidConfig(err_msg)
  112. return config
  113. def read_extra_files(cfg):
  114. """Read the list of extra files from the config file.
  115. Returns a list of 2-tuples: (file, destination_directory), which can be
  116. passed as the ``extra_files`` parameter to :class:`nsist.InstallerBuilder`.
  117. """
  118. lines = cfg.get('Include', 'files', fallback='').splitlines()
  119. pairs = []
  120. for line in lines:
  121. if '>' in line:
  122. file, dest = line.rsplit('>', 1)
  123. pairs.append((file.strip(), dest.strip()))
  124. else:
  125. pairs.append((line, '$INSTDIR'))
  126. return pairs
  127. def read_shortcuts_config(cfg):
  128. """Read and verify the shortcut definitions from the config file.
  129. There is one shortcut per 'Shortcut <name>' section, and one for the
  130. Application section.
  131. Returns a dict of dicts with the fields from the shortcut sections.
  132. The optional 'icon' and 'console' fields will be filled with their
  133. default values if not supplied.
  134. """
  135. shortcuts = {}
  136. def _check_shortcut(name, sc, section):
  137. alternatives = ['entry_point', 'script', 'target']
  138. has_alternatives = sum(1 for k in alternatives if k in sc)
  139. if has_alternatives < 1:
  140. raise InvalidConfig('Section [{}] has none of {}.'.format(
  141. section, ', '.join(alternatives)))
  142. elif has_alternatives > 1:
  143. raise InvalidConfig('Section [{}] has more than one of {}.'.format(
  144. section, ', '.join(alternatives)))
  145. # Copy to a regular dict so it can hold a boolean value
  146. sc2 = dict(sc)
  147. if 'icon' not in sc2:
  148. from . import DEFAULT_ICON
  149. sc2['icon'] = DEFAULT_ICON
  150. sc2['console'] = sc.getboolean('console', fallback=False)
  151. sc2['parameters'] = sc.get('parameters', fallback='')
  152. if 'extra_preamble' in sc2:
  153. if 'entry_point' not in sc2:
  154. raise InvalidConfig('extra_preamble is only valid with entry_point')
  155. preamb_file = sc2['extra_preamble']
  156. if not os.path.isfile(preamb_file):
  157. raise InvalidConfig('extra_preamble file %r does not exist' %
  158. preamb_file)
  159. shortcuts[name] = sc2
  160. for section in cfg.sections():
  161. if section.startswith("Shortcut "):
  162. name = section[len("Shortcut "):]
  163. _check_shortcut(name, cfg[section], section)
  164. appcfg = cfg['Application']
  165. _check_shortcut(appcfg['name'], appcfg, 'Application')
  166. return shortcuts
  167. def read_commands_config(cfg):
  168. """Read and verify the command definitions from the config file.
  169. Returns a dict of dicts, keyed by command name, containing the values from
  170. the command sections of the config file.
  171. """
  172. commands = {}
  173. for section in cfg.sections():
  174. if section.startswith("Command "):
  175. name = section[len("Command "):]
  176. commands[name] = cc = dict(cfg[section])
  177. if ('extra_preamble' in cc) and \
  178. not os.path.isfile(cc['extra_preamble']):
  179. raise InvalidConfig('extra_preamble file %r does not exist' %
  180. cc['extra_preamble'])
  181. return commands
  182. def get_installer_builder_args(config):
  183. from . import (DEFAULT_BITNESS,
  184. DEFAULT_BUILD_DIR,
  185. DEFAULT_ICON,
  186. DEFAULT_PY_VERSION)
  187. appcfg = config['Application']
  188. args = {}
  189. args['appname'] = appcfg['name']
  190. args['version'] = appcfg['version']
  191. args['shortcuts'] = read_shortcuts_config(config)
  192. args['commands'] = read_commands_config(config)
  193. args['publisher'] = appcfg.get('publisher', None)
  194. args['icon'] = appcfg.get('icon', DEFAULT_ICON)
  195. args['packages'] = config.get('Include', 'packages', fallback='').strip().splitlines()
  196. args['pypi_wheel_reqs'] = config.get('Include', 'pypi_wheels', fallback='').strip().splitlines()
  197. args['extra_files'] = read_extra_files(config)
  198. args['py_version'] = config.get('Python', 'version', fallback=DEFAULT_PY_VERSION)
  199. args['py_bitness'] = config.getint('Python', 'bitness', fallback=DEFAULT_BITNESS)
  200. args['py_format'] = config.get('Python', 'format', fallback=None)
  201. args['inc_msvcrt'] = config.getboolean('Python', 'include_msvcrt', fallback=True)
  202. args['build_dir'] = config.get('Build', 'directory', fallback=DEFAULT_BUILD_DIR)
  203. args['installer_name'] = config.get('Build', 'installer_name', fallback=None)
  204. args['nsi_template'] = config.get('Build', 'nsi_template', fallback=None)
  205. args['exclude'] = config.get('Include', 'exclude', fallback='').strip().splitlines()
  206. return args