You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.py 20KB

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