config.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. from __future__ import absolute_import, unicode_literals
  2. import io
  3. import os
  4. import sys
  5. import warnings
  6. import functools
  7. from collections import defaultdict
  8. from functools import partial
  9. from functools import wraps
  10. from importlib import import_module
  11. from distutils.errors import DistutilsOptionError, DistutilsFileError
  12. from setuptools.extern.packaging.version import LegacyVersion, parse
  13. from setuptools.extern.packaging.specifiers import SpecifierSet
  14. from setuptools.extern.six import string_types, PY3
  15. __metaclass__ = type
  16. def read_configuration(
  17. filepath, find_others=False, ignore_option_errors=False):
  18. """Read given configuration file and returns options from it as a dict.
  19. :param str|unicode filepath: Path to configuration file
  20. to get options from.
  21. :param bool find_others: Whether to search for other configuration files
  22. which could be on in various places.
  23. :param bool ignore_option_errors: Whether to silently ignore
  24. options, values of which could not be resolved (e.g. due to exceptions
  25. in directives such as file:, attr:, etc.).
  26. If False exceptions are propagated as expected.
  27. :rtype: dict
  28. """
  29. from setuptools.dist import Distribution, _Distribution
  30. filepath = os.path.abspath(filepath)
  31. if not os.path.isfile(filepath):
  32. raise DistutilsFileError(
  33. 'Configuration file %s does not exist.' % filepath)
  34. current_directory = os.getcwd()
  35. os.chdir(os.path.dirname(filepath))
  36. try:
  37. dist = Distribution()
  38. filenames = dist.find_config_files() if find_others else []
  39. if filepath not in filenames:
  40. filenames.append(filepath)
  41. _Distribution.parse_config_files(dist, filenames=filenames)
  42. handlers = parse_configuration(
  43. dist, dist.command_options,
  44. ignore_option_errors=ignore_option_errors)
  45. finally:
  46. os.chdir(current_directory)
  47. return configuration_to_dict(handlers)
  48. def _get_option(target_obj, key):
  49. """
  50. Given a target object and option key, get that option from
  51. the target object, either through a get_{key} method or
  52. from an attribute directly.
  53. """
  54. getter_name = 'get_{key}'.format(**locals())
  55. by_attribute = functools.partial(getattr, target_obj, key)
  56. getter = getattr(target_obj, getter_name, by_attribute)
  57. return getter()
  58. def configuration_to_dict(handlers):
  59. """Returns configuration data gathered by given handlers as a dict.
  60. :param list[ConfigHandler] handlers: Handlers list,
  61. usually from parse_configuration()
  62. :rtype: dict
  63. """
  64. config_dict = defaultdict(dict)
  65. for handler in handlers:
  66. for option in handler.set_options:
  67. value = _get_option(handler.target_obj, option)
  68. config_dict[handler.section_prefix][option] = value
  69. return config_dict
  70. def parse_configuration(
  71. distribution, command_options, ignore_option_errors=False):
  72. """Performs additional parsing of configuration options
  73. for a distribution.
  74. Returns a list of used option handlers.
  75. :param Distribution distribution:
  76. :param dict command_options:
  77. :param bool ignore_option_errors: Whether to silently ignore
  78. options, values of which could not be resolved (e.g. due to exceptions
  79. in directives such as file:, attr:, etc.).
  80. If False exceptions are propagated as expected.
  81. :rtype: list
  82. """
  83. options = ConfigOptionsHandler(
  84. distribution, command_options, ignore_option_errors)
  85. options.parse()
  86. meta = ConfigMetadataHandler(
  87. distribution.metadata, command_options, ignore_option_errors,
  88. distribution.package_dir)
  89. meta.parse()
  90. return meta, options
  91. class ConfigHandler:
  92. """Handles metadata supplied in configuration files."""
  93. section_prefix = None
  94. """Prefix for config sections handled by this handler.
  95. Must be provided by class heirs.
  96. """
  97. aliases = {}
  98. """Options aliases.
  99. For compatibility with various packages. E.g.: d2to1 and pbr.
  100. Note: `-` in keys is replaced with `_` by config parser.
  101. """
  102. def __init__(self, target_obj, options, ignore_option_errors=False):
  103. sections = {}
  104. section_prefix = self.section_prefix
  105. for section_name, section_options in options.items():
  106. if not section_name.startswith(section_prefix):
  107. continue
  108. section_name = section_name.replace(section_prefix, '').strip('.')
  109. sections[section_name] = section_options
  110. self.ignore_option_errors = ignore_option_errors
  111. self.target_obj = target_obj
  112. self.sections = sections
  113. self.set_options = []
  114. @property
  115. def parsers(self):
  116. """Metadata item name to parser function mapping."""
  117. raise NotImplementedError(
  118. '%s must provide .parsers property' % self.__class__.__name__)
  119. def __setitem__(self, option_name, value):
  120. unknown = tuple()
  121. target_obj = self.target_obj
  122. # Translate alias into real name.
  123. option_name = self.aliases.get(option_name, option_name)
  124. current_value = getattr(target_obj, option_name, unknown)
  125. if current_value is unknown:
  126. raise KeyError(option_name)
  127. if current_value:
  128. # Already inhabited. Skipping.
  129. return
  130. skip_option = False
  131. parser = self.parsers.get(option_name)
  132. if parser:
  133. try:
  134. value = parser(value)
  135. except Exception:
  136. skip_option = True
  137. if not self.ignore_option_errors:
  138. raise
  139. if skip_option:
  140. return
  141. setter = getattr(target_obj, 'set_%s' % option_name, None)
  142. if setter is None:
  143. setattr(target_obj, option_name, value)
  144. else:
  145. setter(value)
  146. self.set_options.append(option_name)
  147. @classmethod
  148. def _parse_list(cls, value, separator=','):
  149. """Represents value as a list.
  150. Value is split either by separator (defaults to comma) or by lines.
  151. :param value:
  152. :param separator: List items separator character.
  153. :rtype: list
  154. """
  155. if isinstance(value, list): # _get_parser_compound case
  156. return value
  157. if '\n' in value:
  158. value = value.splitlines()
  159. else:
  160. value = value.split(separator)
  161. return [chunk.strip() for chunk in value if chunk.strip()]
  162. @classmethod
  163. def _parse_dict(cls, value):
  164. """Represents value as a dict.
  165. :param value:
  166. :rtype: dict
  167. """
  168. separator = '='
  169. result = {}
  170. for line in cls._parse_list(value):
  171. key, sep, val = line.partition(separator)
  172. if sep != separator:
  173. raise DistutilsOptionError(
  174. 'Unable to parse option value to dict: %s' % value)
  175. result[key.strip()] = val.strip()
  176. return result
  177. @classmethod
  178. def _parse_bool(cls, value):
  179. """Represents value as boolean.
  180. :param value:
  181. :rtype: bool
  182. """
  183. value = value.lower()
  184. return value in ('1', 'true', 'yes')
  185. @classmethod
  186. def _exclude_files_parser(cls, key):
  187. """Returns a parser function to make sure field inputs
  188. are not files.
  189. Parses a value after getting the key so error messages are
  190. more informative.
  191. :param key:
  192. :rtype: callable
  193. """
  194. def parser(value):
  195. exclude_directive = 'file:'
  196. if value.startswith(exclude_directive):
  197. raise ValueError(
  198. 'Only strings are accepted for the {0} field, '
  199. 'files are not accepted'.format(key))
  200. return value
  201. return parser
  202. @classmethod
  203. def _parse_file(cls, value):
  204. """Represents value as a string, allowing including text
  205. from nearest files using `file:` directive.
  206. Directive is sandboxed and won't reach anything outside
  207. directory with setup.py.
  208. Examples:
  209. file: README.rst, CHANGELOG.md, src/file.txt
  210. :param str value:
  211. :rtype: str
  212. """
  213. include_directive = 'file:'
  214. if not isinstance(value, string_types):
  215. return value
  216. if not value.startswith(include_directive):
  217. return value
  218. spec = value[len(include_directive):]
  219. filepaths = (os.path.abspath(path.strip()) for path in spec.split(','))
  220. return '\n'.join(
  221. cls._read_file(path)
  222. for path in filepaths
  223. if (cls._assert_local(path) or True)
  224. and os.path.isfile(path)
  225. )
  226. @staticmethod
  227. def _assert_local(filepath):
  228. if not filepath.startswith(os.getcwd()):
  229. raise DistutilsOptionError(
  230. '`file:` directive can not access %s' % filepath)
  231. @staticmethod
  232. def _read_file(filepath):
  233. with io.open(filepath, encoding='utf-8') as f:
  234. return f.read()
  235. @classmethod
  236. def _parse_attr(cls, value, package_dir=None):
  237. """Represents value as a module attribute.
  238. Examples:
  239. attr: package.attr
  240. attr: package.module.attr
  241. :param str value:
  242. :rtype: str
  243. """
  244. attr_directive = 'attr:'
  245. if not value.startswith(attr_directive):
  246. return value
  247. attrs_path = value.replace(attr_directive, '').strip().split('.')
  248. attr_name = attrs_path.pop()
  249. module_name = '.'.join(attrs_path)
  250. module_name = module_name or '__init__'
  251. parent_path = os.getcwd()
  252. if package_dir:
  253. if attrs_path[0] in package_dir:
  254. # A custom path was specified for the module we want to import
  255. custom_path = package_dir[attrs_path[0]]
  256. parts = custom_path.rsplit('/', 1)
  257. if len(parts) > 1:
  258. parent_path = os.path.join(os.getcwd(), parts[0])
  259. module_name = parts[1]
  260. else:
  261. module_name = custom_path
  262. elif '' in package_dir:
  263. # A custom parent directory was specified for all root modules
  264. parent_path = os.path.join(os.getcwd(), package_dir[''])
  265. sys.path.insert(0, parent_path)
  266. try:
  267. module = import_module(module_name)
  268. value = getattr(module, attr_name)
  269. finally:
  270. sys.path = sys.path[1:]
  271. return value
  272. @classmethod
  273. def _get_parser_compound(cls, *parse_methods):
  274. """Returns parser function to represents value as a list.
  275. Parses a value applying given methods one after another.
  276. :param parse_methods:
  277. :rtype: callable
  278. """
  279. def parse(value):
  280. parsed = value
  281. for method in parse_methods:
  282. parsed = method(parsed)
  283. return parsed
  284. return parse
  285. @classmethod
  286. def _parse_section_to_dict(cls, section_options, values_parser=None):
  287. """Parses section options into a dictionary.
  288. Optionally applies a given parser to values.
  289. :param dict section_options:
  290. :param callable values_parser:
  291. :rtype: dict
  292. """
  293. value = {}
  294. values_parser = values_parser or (lambda val: val)
  295. for key, (_, val) in section_options.items():
  296. value[key] = values_parser(val)
  297. return value
  298. def parse_section(self, section_options):
  299. """Parses configuration file section.
  300. :param dict section_options:
  301. """
  302. for (name, (_, value)) in section_options.items():
  303. try:
  304. self[name] = value
  305. except KeyError:
  306. pass # Keep silent for a new option may appear anytime.
  307. def parse(self):
  308. """Parses configuration file items from one
  309. or more related sections.
  310. """
  311. for section_name, section_options in self.sections.items():
  312. method_postfix = ''
  313. if section_name: # [section.option] variant
  314. method_postfix = '_%s' % section_name
  315. section_parser_method = getattr(
  316. self,
  317. # Dots in section names are translated into dunderscores.
  318. ('parse_section%s' % method_postfix).replace('.', '__'),
  319. None)
  320. if section_parser_method is None:
  321. raise DistutilsOptionError(
  322. 'Unsupported distribution option section: [%s.%s]' % (
  323. self.section_prefix, section_name))
  324. section_parser_method(section_options)
  325. def _deprecated_config_handler(self, func, msg, warning_class):
  326. """ this function will wrap around parameters that are deprecated
  327. :param msg: deprecation message
  328. :param warning_class: class of warning exception to be raised
  329. :param func: function to be wrapped around
  330. """
  331. @wraps(func)
  332. def config_handler(*args, **kwargs):
  333. warnings.warn(msg, warning_class)
  334. return func(*args, **kwargs)
  335. return config_handler
  336. class ConfigMetadataHandler(ConfigHandler):
  337. section_prefix = 'metadata'
  338. aliases = {
  339. 'home_page': 'url',
  340. 'summary': 'description',
  341. 'classifier': 'classifiers',
  342. 'platform': 'platforms',
  343. }
  344. strict_mode = False
  345. """We need to keep it loose, to be partially compatible with
  346. `pbr` and `d2to1` packages which also uses `metadata` section.
  347. """
  348. def __init__(self, target_obj, options, ignore_option_errors=False,
  349. package_dir=None):
  350. super(ConfigMetadataHandler, self).__init__(target_obj, options,
  351. ignore_option_errors)
  352. self.package_dir = package_dir
  353. @property
  354. def parsers(self):
  355. """Metadata item name to parser function mapping."""
  356. parse_list = self._parse_list
  357. parse_file = self._parse_file
  358. parse_dict = self._parse_dict
  359. exclude_files_parser = self._exclude_files_parser
  360. return {
  361. 'platforms': parse_list,
  362. 'keywords': parse_list,
  363. 'provides': parse_list,
  364. 'requires': self._deprecated_config_handler(
  365. parse_list,
  366. "The requires parameter is deprecated, please use "
  367. "install_requires for runtime dependencies.",
  368. DeprecationWarning),
  369. 'obsoletes': parse_list,
  370. 'classifiers': self._get_parser_compound(parse_file, parse_list),
  371. 'license': exclude_files_parser('license'),
  372. 'license_files': parse_list,
  373. 'description': parse_file,
  374. 'long_description': parse_file,
  375. 'version': self._parse_version,
  376. 'project_urls': parse_dict,
  377. }
  378. def _parse_version(self, value):
  379. """Parses `version` option value.
  380. :param value:
  381. :rtype: str
  382. """
  383. version = self._parse_file(value)
  384. if version != value:
  385. version = version.strip()
  386. # Be strict about versions loaded from file because it's easy to
  387. # accidentally include newlines and other unintended content
  388. if isinstance(parse(version), LegacyVersion):
  389. tmpl = (
  390. 'Version loaded from {value} does not '
  391. 'comply with PEP 440: {version}'
  392. )
  393. raise DistutilsOptionError(tmpl.format(**locals()))
  394. return version
  395. version = self._parse_attr(value, self.package_dir)
  396. if callable(version):
  397. version = version()
  398. if not isinstance(version, string_types):
  399. if hasattr(version, '__iter__'):
  400. version = '.'.join(map(str, version))
  401. else:
  402. version = '%s' % version
  403. return version
  404. class ConfigOptionsHandler(ConfigHandler):
  405. section_prefix = 'options'
  406. @property
  407. def parsers(self):
  408. """Metadata item name to parser function mapping."""
  409. parse_list = self._parse_list
  410. parse_list_semicolon = partial(self._parse_list, separator=';')
  411. parse_bool = self._parse_bool
  412. parse_dict = self._parse_dict
  413. return {
  414. 'zip_safe': parse_bool,
  415. 'use_2to3': parse_bool,
  416. 'include_package_data': parse_bool,
  417. 'package_dir': parse_dict,
  418. 'use_2to3_fixers': parse_list,
  419. 'use_2to3_exclude_fixers': parse_list,
  420. 'convert_2to3_doctests': parse_list,
  421. 'scripts': parse_list,
  422. 'eager_resources': parse_list,
  423. 'dependency_links': parse_list,
  424. 'namespace_packages': parse_list,
  425. 'install_requires': parse_list_semicolon,
  426. 'setup_requires': parse_list_semicolon,
  427. 'tests_require': parse_list_semicolon,
  428. 'packages': self._parse_packages,
  429. 'entry_points': self._parse_file,
  430. 'py_modules': parse_list,
  431. 'python_requires': SpecifierSet,
  432. }
  433. def _parse_packages(self, value):
  434. """Parses `packages` option value.
  435. :param value:
  436. :rtype: list
  437. """
  438. find_directives = ['find:', 'find_namespace:']
  439. trimmed_value = value.strip()
  440. if trimmed_value not in find_directives:
  441. return self._parse_list(value)
  442. findns = trimmed_value == find_directives[1]
  443. if findns and not PY3:
  444. raise DistutilsOptionError(
  445. 'find_namespace: directive is unsupported on Python < 3.3')
  446. # Read function arguments from a dedicated section.
  447. find_kwargs = self.parse_section_packages__find(
  448. self.sections.get('packages.find', {}))
  449. if findns:
  450. from setuptools import find_namespace_packages as find_packages
  451. else:
  452. from setuptools import find_packages
  453. return find_packages(**find_kwargs)
  454. def parse_section_packages__find(self, section_options):
  455. """Parses `packages.find` configuration file section.
  456. To be used in conjunction with _parse_packages().
  457. :param dict section_options:
  458. """
  459. section_data = self._parse_section_to_dict(
  460. section_options, self._parse_list)
  461. valid_keys = ['where', 'include', 'exclude']
  462. find_kwargs = dict(
  463. [(k, v) for k, v in section_data.items() if k in valid_keys and v])
  464. where = find_kwargs.get('where')
  465. if where is not None:
  466. find_kwargs['where'] = where[0] # cast list to single val
  467. return find_kwargs
  468. def parse_section_entry_points(self, section_options):
  469. """Parses `entry_points` configuration file section.
  470. :param dict section_options:
  471. """
  472. parsed = self._parse_section_to_dict(section_options, self._parse_list)
  473. self['entry_points'] = parsed
  474. def _parse_package_data(self, section_options):
  475. parsed = self._parse_section_to_dict(section_options, self._parse_list)
  476. root = parsed.get('*')
  477. if root:
  478. parsed[''] = root
  479. del parsed['*']
  480. return parsed
  481. def parse_section_package_data(self, section_options):
  482. """Parses `package_data` configuration file section.
  483. :param dict section_options:
  484. """
  485. self['package_data'] = self._parse_package_data(section_options)
  486. def parse_section_exclude_package_data(self, section_options):
  487. """Parses `exclude_package_data` configuration file section.
  488. :param dict section_options:
  489. """
  490. self['exclude_package_data'] = self._parse_package_data(
  491. section_options)
  492. def parse_section_extras_require(self, section_options):
  493. """Parses `extras_require` configuration file section.
  494. :param dict section_options:
  495. """
  496. parse_list = partial(self._parse_list, separator=';')
  497. self['extras_require'] = self._parse_section_to_dict(
  498. section_options, parse_list)
  499. def parse_section_data_files(self, section_options):
  500. """Parses `data_files` configuration file section.
  501. :param dict section_options:
  502. """
  503. parsed = self._parse_section_to_dict(section_options, self._parse_list)
  504. self['data_files'] = [(k, v) for k, v in parsed.items()]