config.py 21 KB

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