config.py 21 KB

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