1
0

config.py 21 KB

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