metadata.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 The Python Software Foundation.
  4. # See LICENSE.txt and CONTRIBUTORS.txt.
  5. #
  6. """Implementation of the Metadata for Python packages PEPs.
  7. Supports all metadata formats (1.0, 1.1, 1.2, 1.3/2.1 and 2.2).
  8. """
  9. from __future__ import unicode_literals
  10. import codecs
  11. from email import message_from_file
  12. import json
  13. import logging
  14. import re
  15. from . import DistlibException, __version__
  16. from .compat import StringIO, string_types, text_type
  17. from .markers import interpret
  18. from .util import extract_by_key, get_extras
  19. from .version import get_scheme, PEP440_VERSION_RE
  20. logger = logging.getLogger(__name__)
  21. class MetadataMissingError(DistlibException):
  22. """A required metadata is missing"""
  23. class MetadataConflictError(DistlibException):
  24. """Attempt to read or write metadata fields that are conflictual."""
  25. class MetadataUnrecognizedVersionError(DistlibException):
  26. """Unknown metadata version number."""
  27. class MetadataInvalidError(DistlibException):
  28. """A metadata value is invalid"""
  29. # public API of this module
  30. __all__ = ['Metadata', 'PKG_INFO_ENCODING', 'PKG_INFO_PREFERRED_VERSION']
  31. # Encoding used for the PKG-INFO files
  32. PKG_INFO_ENCODING = 'utf-8'
  33. # preferred version. Hopefully will be changed
  34. # to 1.2 once PEP 345 is supported everywhere
  35. PKG_INFO_PREFERRED_VERSION = '1.1'
  36. _LINE_PREFIX_1_2 = re.compile('\n \\|')
  37. _LINE_PREFIX_PRE_1_2 = re.compile('\n ')
  38. _241_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
  39. 'Summary', 'Description',
  40. 'Keywords', 'Home-page', 'Author', 'Author-email',
  41. 'License')
  42. _314_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
  43. 'Supported-Platform', 'Summary', 'Description',
  44. 'Keywords', 'Home-page', 'Author', 'Author-email',
  45. 'License', 'Classifier', 'Download-URL', 'Obsoletes',
  46. 'Provides', 'Requires')
  47. _314_MARKERS = ('Obsoletes', 'Provides', 'Requires', 'Classifier',
  48. 'Download-URL')
  49. _345_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
  50. 'Supported-Platform', 'Summary', 'Description',
  51. 'Keywords', 'Home-page', 'Author', 'Author-email',
  52. 'Maintainer', 'Maintainer-email', 'License',
  53. 'Classifier', 'Download-URL', 'Obsoletes-Dist',
  54. 'Project-URL', 'Provides-Dist', 'Requires-Dist',
  55. 'Requires-Python', 'Requires-External')
  56. _345_MARKERS = ('Provides-Dist', 'Requires-Dist', 'Requires-Python',
  57. 'Obsoletes-Dist', 'Requires-External', 'Maintainer',
  58. 'Maintainer-email', 'Project-URL')
  59. _426_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',
  60. 'Supported-Platform', 'Summary', 'Description',
  61. 'Keywords', 'Home-page', 'Author', 'Author-email',
  62. 'Maintainer', 'Maintainer-email', 'License',
  63. 'Classifier', 'Download-URL', 'Obsoletes-Dist',
  64. 'Project-URL', 'Provides-Dist', 'Requires-Dist',
  65. 'Requires-Python', 'Requires-External', 'Private-Version',
  66. 'Obsoleted-By', 'Setup-Requires-Dist', 'Extension',
  67. 'Provides-Extra')
  68. _426_MARKERS = ('Private-Version', 'Provides-Extra', 'Obsoleted-By',
  69. 'Setup-Requires-Dist', 'Extension')
  70. # See issue #106: Sometimes 'Requires' and 'Provides' occur wrongly in
  71. # the metadata. Include them in the tuple literal below to allow them
  72. # (for now).
  73. # Ditto for Obsoletes - see issue #140.
  74. _566_FIELDS = _426_FIELDS + ('Description-Content-Type',
  75. 'Requires', 'Provides', 'Obsoletes')
  76. _566_MARKERS = ('Description-Content-Type',)
  77. _643_MARKERS = ('Dynamic', 'License-File')
  78. _643_FIELDS = _566_FIELDS + _643_MARKERS
  79. _ALL_FIELDS = set()
  80. _ALL_FIELDS.update(_241_FIELDS)
  81. _ALL_FIELDS.update(_314_FIELDS)
  82. _ALL_FIELDS.update(_345_FIELDS)
  83. _ALL_FIELDS.update(_426_FIELDS)
  84. _ALL_FIELDS.update(_566_FIELDS)
  85. _ALL_FIELDS.update(_643_FIELDS)
  86. EXTRA_RE = re.compile(r'''extra\s*==\s*("([^"]+)"|'([^']+)')''')
  87. def _version2fieldlist(version):
  88. if version == '1.0':
  89. return _241_FIELDS
  90. elif version == '1.1':
  91. return _314_FIELDS
  92. elif version == '1.2':
  93. return _345_FIELDS
  94. elif version in ('1.3', '2.1'):
  95. # avoid adding field names if already there
  96. return _345_FIELDS + tuple(f for f in _566_FIELDS if f not in _345_FIELDS)
  97. elif version == '2.0':
  98. raise ValueError('Metadata 2.0 is withdrawn and not supported')
  99. # return _426_FIELDS
  100. elif version == '2.2':
  101. return _643_FIELDS
  102. raise MetadataUnrecognizedVersionError(version)
  103. def _best_version(fields):
  104. """Detect the best version depending on the fields used."""
  105. def _has_marker(keys, markers):
  106. for marker in markers:
  107. if marker in keys:
  108. return True
  109. return False
  110. keys = []
  111. for key, value in fields.items():
  112. if value in ([], 'UNKNOWN', None):
  113. continue
  114. keys.append(key)
  115. possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.1', '2.2'] # 2.0 removed
  116. # first let's try to see if a field is not part of one of the version
  117. for key in keys:
  118. if key not in _241_FIELDS and '1.0' in possible_versions:
  119. possible_versions.remove('1.0')
  120. logger.debug('Removed 1.0 due to %s', key)
  121. if key not in _314_FIELDS and '1.1' in possible_versions:
  122. possible_versions.remove('1.1')
  123. logger.debug('Removed 1.1 due to %s', key)
  124. if key not in _345_FIELDS and '1.2' in possible_versions:
  125. possible_versions.remove('1.2')
  126. logger.debug('Removed 1.2 due to %s', key)
  127. if key not in _566_FIELDS and '1.3' in possible_versions:
  128. possible_versions.remove('1.3')
  129. logger.debug('Removed 1.3 due to %s', key)
  130. if key not in _566_FIELDS and '2.1' in possible_versions:
  131. if key != 'Description': # In 2.1, description allowed after headers
  132. possible_versions.remove('2.1')
  133. logger.debug('Removed 2.1 due to %s', key)
  134. if key not in _643_FIELDS and '2.2' in possible_versions:
  135. possible_versions.remove('2.2')
  136. logger.debug('Removed 2.2 due to %s', key)
  137. # if key not in _426_FIELDS and '2.0' in possible_versions:
  138. # possible_versions.remove('2.0')
  139. # logger.debug('Removed 2.0 due to %s', key)
  140. # possible_version contains qualified versions
  141. if len(possible_versions) == 1:
  142. return possible_versions[0] # found !
  143. elif len(possible_versions) == 0:
  144. logger.debug('Out of options - unknown metadata set: %s', fields)
  145. raise MetadataConflictError('Unknown metadata set')
  146. # let's see if one unique marker is found
  147. is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)
  148. is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)
  149. is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)
  150. # is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)
  151. is_2_2 = '2.2' in possible_versions and _has_marker(keys, _643_MARKERS)
  152. if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_2) > 1:
  153. raise MetadataConflictError('You used incompatible 1.1/1.2/2.1/2.2 fields')
  154. # we have the choice, 1.0, or 1.2, 2.1 or 2.2
  155. # - 1.0 has a broken Summary field but works with all tools
  156. # - 1.1 is to avoid
  157. # - 1.2 fixes Summary but has little adoption
  158. # - 2.1 adds more features
  159. # - 2.2 is the latest
  160. if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_2:
  161. # we couldn't find any specific marker
  162. if PKG_INFO_PREFERRED_VERSION in possible_versions:
  163. return PKG_INFO_PREFERRED_VERSION
  164. if is_1_1:
  165. return '1.1'
  166. if is_1_2:
  167. return '1.2'
  168. if is_2_1:
  169. return '2.1'
  170. # if is_2_2:
  171. # return '2.2'
  172. return '2.2'
  173. # This follows the rules about transforming keys as described in
  174. # https://www.python.org/dev/peps/pep-0566/#id17
  175. _ATTR2FIELD = {
  176. name.lower().replace("-", "_"): name for name in _ALL_FIELDS
  177. }
  178. _FIELD2ATTR = {field: attr for attr, field in _ATTR2FIELD.items()}
  179. _PREDICATE_FIELDS = ('Requires-Dist', 'Obsoletes-Dist', 'Provides-Dist')
  180. _VERSIONS_FIELDS = ('Requires-Python',)
  181. _VERSION_FIELDS = ('Version',)
  182. _LISTFIELDS = ('Platform', 'Classifier', 'Obsoletes',
  183. 'Requires', 'Provides', 'Obsoletes-Dist',
  184. 'Provides-Dist', 'Requires-Dist', 'Requires-External',
  185. 'Project-URL', 'Supported-Platform', 'Setup-Requires-Dist',
  186. 'Provides-Extra', 'Extension', 'License-File')
  187. _LISTTUPLEFIELDS = ('Project-URL',)
  188. _ELEMENTSFIELD = ('Keywords',)
  189. _UNICODEFIELDS = ('Author', 'Maintainer', 'Summary', 'Description')
  190. _MISSING = object()
  191. _FILESAFE = re.compile('[^A-Za-z0-9.]+')
  192. def _get_name_and_version(name, version, for_filename=False):
  193. """Return the distribution name with version.
  194. If for_filename is true, return a filename-escaped form."""
  195. if for_filename:
  196. # For both name and version any runs of non-alphanumeric or '.'
  197. # characters are replaced with a single '-'. Additionally any
  198. # spaces in the version string become '.'
  199. name = _FILESAFE.sub('-', name)
  200. version = _FILESAFE.sub('-', version.replace(' ', '.'))
  201. return '%s-%s' % (name, version)
  202. class LegacyMetadata(object):
  203. """The legacy metadata of a release.
  204. Supports versions 1.0, 1.1, 1.2, 2.0 and 1.3/2.1 (auto-detected). You can
  205. instantiate the class with one of these arguments (or none):
  206. - *path*, the path to a metadata file
  207. - *fileobj* give a file-like object with metadata as content
  208. - *mapping* is a dict-like object
  209. - *scheme* is a version scheme name
  210. """
  211. # TODO document the mapping API and UNKNOWN default key
  212. def __init__(self, path=None, fileobj=None, mapping=None,
  213. scheme='default'):
  214. if [path, fileobj, mapping].count(None) < 2:
  215. raise TypeError('path, fileobj and mapping are exclusive')
  216. self._fields = {}
  217. self.requires_files = []
  218. self._dependencies = None
  219. self.scheme = scheme
  220. if path is not None:
  221. self.read(path)
  222. elif fileobj is not None:
  223. self.read_file(fileobj)
  224. elif mapping is not None:
  225. self.update(mapping)
  226. self.set_metadata_version()
  227. def set_metadata_version(self):
  228. self._fields['Metadata-Version'] = _best_version(self._fields)
  229. def _write_field(self, fileobj, name, value):
  230. fileobj.write('%s: %s\n' % (name, value))
  231. def __getitem__(self, name):
  232. return self.get(name)
  233. def __setitem__(self, name, value):
  234. return self.set(name, value)
  235. def __delitem__(self, name):
  236. field_name = self._convert_name(name)
  237. try:
  238. del self._fields[field_name]
  239. except KeyError:
  240. raise KeyError(name)
  241. def __contains__(self, name):
  242. return (name in self._fields or
  243. self._convert_name(name) in self._fields)
  244. def _convert_name(self, name):
  245. if name in _ALL_FIELDS:
  246. return name
  247. name = name.replace('-', '_').lower()
  248. return _ATTR2FIELD.get(name, name)
  249. def _default_value(self, name):
  250. if name in _LISTFIELDS or name in _ELEMENTSFIELD:
  251. return []
  252. return 'UNKNOWN'
  253. def _remove_line_prefix(self, value):
  254. if self.metadata_version in ('1.0', '1.1'):
  255. return _LINE_PREFIX_PRE_1_2.sub('\n', value)
  256. else:
  257. return _LINE_PREFIX_1_2.sub('\n', value)
  258. def __getattr__(self, name):
  259. if name in _ATTR2FIELD:
  260. return self[name]
  261. raise AttributeError(name)
  262. #
  263. # Public API
  264. #
  265. # dependencies = property(_get_dependencies, _set_dependencies)
  266. def get_fullname(self, filesafe=False):
  267. """Return the distribution name with version.
  268. If filesafe is true, return a filename-escaped form."""
  269. return _get_name_and_version(self['Name'], self['Version'], filesafe)
  270. def is_field(self, name):
  271. """return True if name is a valid metadata key"""
  272. name = self._convert_name(name)
  273. return name in _ALL_FIELDS
  274. def is_multi_field(self, name):
  275. name = self._convert_name(name)
  276. return name in _LISTFIELDS
  277. def read(self, filepath):
  278. """Read the metadata values from a file path."""
  279. fp = codecs.open(filepath, 'r', encoding='utf-8')
  280. try:
  281. self.read_file(fp)
  282. finally:
  283. fp.close()
  284. def read_file(self, fileob):
  285. """Read the metadata values from a file object."""
  286. msg = message_from_file(fileob)
  287. self._fields['Metadata-Version'] = msg['metadata-version']
  288. # When reading, get all the fields we can
  289. for field in _ALL_FIELDS:
  290. if field not in msg:
  291. continue
  292. if field in _LISTFIELDS:
  293. # we can have multiple lines
  294. values = msg.get_all(field)
  295. if field in _LISTTUPLEFIELDS and values is not None:
  296. values = [tuple(value.split(',')) for value in values]
  297. self.set(field, values)
  298. else:
  299. # single line
  300. value = msg[field]
  301. if value is not None and value != 'UNKNOWN':
  302. self.set(field, value)
  303. # PEP 566 specifies that the body be used for the description, if
  304. # available
  305. body = msg.get_payload()
  306. self["Description"] = body if body else self["Description"]
  307. # logger.debug('Attempting to set metadata for %s', self)
  308. # self.set_metadata_version()
  309. def write(self, filepath, skip_unknown=False):
  310. """Write the metadata fields to filepath."""
  311. fp = codecs.open(filepath, 'w', encoding='utf-8')
  312. try:
  313. self.write_file(fp, skip_unknown)
  314. finally:
  315. fp.close()
  316. def write_file(self, fileobject, skip_unknown=False):
  317. """Write the PKG-INFO format data to a file object."""
  318. self.set_metadata_version()
  319. for field in _version2fieldlist(self['Metadata-Version']):
  320. values = self.get(field)
  321. if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
  322. continue
  323. if field in _ELEMENTSFIELD:
  324. self._write_field(fileobject, field, ','.join(values))
  325. continue
  326. if field not in _LISTFIELDS:
  327. if field == 'Description':
  328. if self.metadata_version in ('1.0', '1.1'):
  329. values = values.replace('\n', '\n ')
  330. else:
  331. values = values.replace('\n', '\n |')
  332. values = [values]
  333. if field in _LISTTUPLEFIELDS:
  334. values = [','.join(value) for value in values]
  335. for value in values:
  336. self._write_field(fileobject, field, value)
  337. def update(self, other=None, **kwargs):
  338. """Set metadata values from the given iterable `other` and kwargs.
  339. Behavior is like `dict.update`: If `other` has a ``keys`` method,
  340. they are looped over and ``self[key]`` is assigned ``other[key]``.
  341. Else, ``other`` is an iterable of ``(key, value)`` iterables.
  342. Keys that don't match a metadata field or that have an empty value are
  343. dropped.
  344. """
  345. def _set(key, value):
  346. if key in _ATTR2FIELD and value:
  347. self.set(self._convert_name(key), value)
  348. if not other:
  349. # other is None or empty container
  350. pass
  351. elif hasattr(other, 'keys'):
  352. for k in other.keys():
  353. _set(k, other[k])
  354. else:
  355. for k, v in other:
  356. _set(k, v)
  357. if kwargs:
  358. for k, v in kwargs.items():
  359. _set(k, v)
  360. def set(self, name, value):
  361. """Control then set a metadata field."""
  362. name = self._convert_name(name)
  363. if ((name in _ELEMENTSFIELD or name == 'Platform') and
  364. not isinstance(value, (list, tuple))):
  365. if isinstance(value, string_types):
  366. value = [v.strip() for v in value.split(',')]
  367. else:
  368. value = []
  369. elif (name in _LISTFIELDS and
  370. not isinstance(value, (list, tuple))):
  371. if isinstance(value, string_types):
  372. value = [value]
  373. else:
  374. value = []
  375. if logger.isEnabledFor(logging.WARNING):
  376. project_name = self['Name']
  377. scheme = get_scheme(self.scheme)
  378. if name in _PREDICATE_FIELDS and value is not None:
  379. for v in value:
  380. # check that the values are valid
  381. if not scheme.is_valid_matcher(v.split(';')[0]):
  382. logger.warning(
  383. "'%s': '%s' is not valid (field '%s')",
  384. project_name, v, name)
  385. # FIXME this rejects UNKNOWN, is that right?
  386. elif name in _VERSIONS_FIELDS and value is not None:
  387. if not scheme.is_valid_constraint_list(value):
  388. logger.warning("'%s': '%s' is not a valid version (field '%s')",
  389. project_name, value, name)
  390. elif name in _VERSION_FIELDS and value is not None:
  391. if not scheme.is_valid_version(value):
  392. logger.warning("'%s': '%s' is not a valid version (field '%s')",
  393. project_name, value, name)
  394. if name in _UNICODEFIELDS:
  395. if name == 'Description':
  396. value = self._remove_line_prefix(value)
  397. self._fields[name] = value
  398. def get(self, name, default=_MISSING):
  399. """Get a metadata field."""
  400. name = self._convert_name(name)
  401. if name not in self._fields:
  402. if default is _MISSING:
  403. default = self._default_value(name)
  404. return default
  405. if name in _UNICODEFIELDS:
  406. value = self._fields[name]
  407. return value
  408. elif name in _LISTFIELDS:
  409. value = self._fields[name]
  410. if value is None:
  411. return []
  412. res = []
  413. for val in value:
  414. if name not in _LISTTUPLEFIELDS:
  415. res.append(val)
  416. else:
  417. # That's for Project-URL
  418. res.append((val[0], val[1]))
  419. return res
  420. elif name in _ELEMENTSFIELD:
  421. value = self._fields[name]
  422. if isinstance(value, string_types):
  423. return value.split(',')
  424. return self._fields[name]
  425. def check(self, strict=False):
  426. """Check if the metadata is compliant. If strict is True then raise if
  427. no Name or Version are provided"""
  428. self.set_metadata_version()
  429. # XXX should check the versions (if the file was loaded)
  430. missing, warnings = [], []
  431. for attr in ('Name', 'Version'): # required by PEP 345
  432. if attr not in self:
  433. missing.append(attr)
  434. if strict and missing != []:
  435. msg = 'missing required metadata: %s' % ', '.join(missing)
  436. raise MetadataMissingError(msg)
  437. for attr in ('Home-page', 'Author'):
  438. if attr not in self:
  439. missing.append(attr)
  440. # checking metadata 1.2 (XXX needs to check 1.1, 1.0)
  441. if self['Metadata-Version'] != '1.2':
  442. return missing, warnings
  443. scheme = get_scheme(self.scheme)
  444. def are_valid_constraints(value):
  445. for v in value:
  446. if not scheme.is_valid_matcher(v.split(';')[0]):
  447. return False
  448. return True
  449. for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints),
  450. (_VERSIONS_FIELDS,
  451. scheme.is_valid_constraint_list),
  452. (_VERSION_FIELDS,
  453. scheme.is_valid_version)):
  454. for field in fields:
  455. value = self.get(field, None)
  456. if value is not None and not controller(value):
  457. warnings.append("Wrong value for '%s': %s" % (field, value))
  458. return missing, warnings
  459. def todict(self, skip_missing=False):
  460. """Return fields as a dict.
  461. Field names will be converted to use the underscore-lowercase style
  462. instead of hyphen-mixed case (i.e. home_page instead of Home-page).
  463. This is as per https://www.python.org/dev/peps/pep-0566/#id17.
  464. """
  465. self.set_metadata_version()
  466. fields = _version2fieldlist(self['Metadata-Version'])
  467. data = {}
  468. for field_name in fields:
  469. if not skip_missing or field_name in self._fields:
  470. key = _FIELD2ATTR[field_name]
  471. if key != 'project_url':
  472. data[key] = self[field_name]
  473. else:
  474. data[key] = [','.join(u) for u in self[field_name]]
  475. return data
  476. def add_requirements(self, requirements):
  477. if self['Metadata-Version'] == '1.1':
  478. # we can't have 1.1 metadata *and* Setuptools requires
  479. for field in ('Obsoletes', 'Requires', 'Provides'):
  480. if field in self:
  481. del self[field]
  482. self['Requires-Dist'] += requirements
  483. # Mapping API
  484. # TODO could add iter* variants
  485. def keys(self):
  486. return list(_version2fieldlist(self['Metadata-Version']))
  487. def __iter__(self):
  488. for key in self.keys():
  489. yield key
  490. def values(self):
  491. return [self[key] for key in self.keys()]
  492. def items(self):
  493. return [(key, self[key]) for key in self.keys()]
  494. def __repr__(self):
  495. return '<%s %s %s>' % (self.__class__.__name__, self.name,
  496. self.version)
  497. METADATA_FILENAME = 'pydist.json'
  498. WHEEL_METADATA_FILENAME = 'metadata.json'
  499. LEGACY_METADATA_FILENAME = 'METADATA'
  500. class Metadata(object):
  501. """
  502. The metadata of a release. This implementation uses 2.1
  503. metadata where possible. If not possible, it wraps a LegacyMetadata
  504. instance which handles the key-value metadata format.
  505. """
  506. METADATA_VERSION_MATCHER = re.compile(r'^\d+(\.\d+)*$')
  507. NAME_MATCHER = re.compile('^[0-9A-Z]([0-9A-Z_.-]*[0-9A-Z])?$', re.I)
  508. FIELDNAME_MATCHER = re.compile('^[A-Z]([0-9A-Z-]*[0-9A-Z])?$', re.I)
  509. VERSION_MATCHER = PEP440_VERSION_RE
  510. SUMMARY_MATCHER = re.compile('.{1,2047}')
  511. METADATA_VERSION = '2.0'
  512. GENERATOR = 'distlib (%s)' % __version__
  513. MANDATORY_KEYS = {
  514. 'name': (),
  515. 'version': (),
  516. 'summary': ('legacy',),
  517. }
  518. INDEX_KEYS = ('name version license summary description author '
  519. 'author_email keywords platform home_page classifiers '
  520. 'download_url')
  521. DEPENDENCY_KEYS = ('extras run_requires test_requires build_requires '
  522. 'dev_requires provides meta_requires obsoleted_by '
  523. 'supports_environments')
  524. SYNTAX_VALIDATORS = {
  525. 'metadata_version': (METADATA_VERSION_MATCHER, ()),
  526. 'name': (NAME_MATCHER, ('legacy',)),
  527. 'version': (VERSION_MATCHER, ('legacy',)),
  528. 'summary': (SUMMARY_MATCHER, ('legacy',)),
  529. 'dynamic': (FIELDNAME_MATCHER, ('legacy',)),
  530. }
  531. __slots__ = ('_legacy', '_data', 'scheme')
  532. def __init__(self, path=None, fileobj=None, mapping=None,
  533. scheme='default'):
  534. if [path, fileobj, mapping].count(None) < 2:
  535. raise TypeError('path, fileobj and mapping are exclusive')
  536. self._legacy = None
  537. self._data = None
  538. self.scheme = scheme
  539. #import pdb; pdb.set_trace()
  540. if mapping is not None:
  541. try:
  542. self._validate_mapping(mapping, scheme)
  543. self._data = mapping
  544. except MetadataUnrecognizedVersionError:
  545. self._legacy = LegacyMetadata(mapping=mapping, scheme=scheme)
  546. self.validate()
  547. else:
  548. data = None
  549. if path:
  550. with open(path, 'rb') as f:
  551. data = f.read()
  552. elif fileobj:
  553. data = fileobj.read()
  554. if data is None:
  555. # Initialised with no args - to be added
  556. self._data = {
  557. 'metadata_version': self.METADATA_VERSION,
  558. 'generator': self.GENERATOR,
  559. }
  560. else:
  561. if not isinstance(data, text_type):
  562. data = data.decode('utf-8')
  563. try:
  564. self._data = json.loads(data)
  565. self._validate_mapping(self._data, scheme)
  566. except ValueError:
  567. # Note: MetadataUnrecognizedVersionError does not
  568. # inherit from ValueError (it's a DistlibException,
  569. # which should not inherit from ValueError).
  570. # The ValueError comes from the json.load - if that
  571. # succeeds and we get a validation error, we want
  572. # that to propagate
  573. self._legacy = LegacyMetadata(fileobj=StringIO(data),
  574. scheme=scheme)
  575. self.validate()
  576. common_keys = set(('name', 'version', 'license', 'keywords', 'summary'))
  577. none_list = (None, list)
  578. none_dict = (None, dict)
  579. mapped_keys = {
  580. 'run_requires': ('Requires-Dist', list),
  581. 'build_requires': ('Setup-Requires-Dist', list),
  582. 'dev_requires': none_list,
  583. 'test_requires': none_list,
  584. 'meta_requires': none_list,
  585. 'extras': ('Provides-Extra', list),
  586. 'modules': none_list,
  587. 'namespaces': none_list,
  588. 'exports': none_dict,
  589. 'commands': none_dict,
  590. 'classifiers': ('Classifier', list),
  591. 'source_url': ('Download-URL', None),
  592. 'metadata_version': ('Metadata-Version', None),
  593. }
  594. del none_list, none_dict
  595. def __getattribute__(self, key):
  596. common = object.__getattribute__(self, 'common_keys')
  597. mapped = object.__getattribute__(self, 'mapped_keys')
  598. if key in mapped:
  599. lk, maker = mapped[key]
  600. if self._legacy:
  601. if lk is None:
  602. result = None if maker is None else maker()
  603. else:
  604. result = self._legacy.get(lk)
  605. else:
  606. value = None if maker is None else maker()
  607. if key not in ('commands', 'exports', 'modules', 'namespaces',
  608. 'classifiers'):
  609. result = self._data.get(key, value)
  610. else:
  611. # special cases for PEP 459
  612. sentinel = object()
  613. result = sentinel
  614. d = self._data.get('extensions')
  615. if d:
  616. if key == 'commands':
  617. result = d.get('python.commands', value)
  618. elif key == 'classifiers':
  619. d = d.get('python.details')
  620. if d:
  621. result = d.get(key, value)
  622. else:
  623. d = d.get('python.exports')
  624. if not d:
  625. d = self._data.get('python.exports')
  626. if d:
  627. result = d.get(key, value)
  628. if result is sentinel:
  629. result = value
  630. elif key not in common:
  631. result = object.__getattribute__(self, key)
  632. elif self._legacy:
  633. result = self._legacy.get(key)
  634. else:
  635. result = self._data.get(key)
  636. return result
  637. def _validate_value(self, key, value, scheme=None):
  638. if key in self.SYNTAX_VALIDATORS:
  639. pattern, exclusions = self.SYNTAX_VALIDATORS[key]
  640. if (scheme or self.scheme) not in exclusions:
  641. m = pattern.match(value)
  642. if not m:
  643. raise MetadataInvalidError("'%s' is an invalid value for "
  644. "the '%s' property" % (value,
  645. key))
  646. def __setattr__(self, key, value):
  647. self._validate_value(key, value)
  648. common = object.__getattribute__(self, 'common_keys')
  649. mapped = object.__getattribute__(self, 'mapped_keys')
  650. if key in mapped:
  651. lk, _ = mapped[key]
  652. if self._legacy:
  653. if lk is None:
  654. raise NotImplementedError
  655. self._legacy[lk] = value
  656. elif key not in ('commands', 'exports', 'modules', 'namespaces',
  657. 'classifiers'):
  658. self._data[key] = value
  659. else:
  660. # special cases for PEP 459
  661. d = self._data.setdefault('extensions', {})
  662. if key == 'commands':
  663. d['python.commands'] = value
  664. elif key == 'classifiers':
  665. d = d.setdefault('python.details', {})
  666. d[key] = value
  667. else:
  668. d = d.setdefault('python.exports', {})
  669. d[key] = value
  670. elif key not in common:
  671. object.__setattr__(self, key, value)
  672. else:
  673. if key == 'keywords':
  674. if isinstance(value, string_types):
  675. value = value.strip()
  676. if value:
  677. value = value.split()
  678. else:
  679. value = []
  680. if self._legacy:
  681. self._legacy[key] = value
  682. else:
  683. self._data[key] = value
  684. @property
  685. def name_and_version(self):
  686. return _get_name_and_version(self.name, self.version, True)
  687. @property
  688. def provides(self):
  689. if self._legacy:
  690. result = self._legacy['Provides-Dist']
  691. else:
  692. result = self._data.setdefault('provides', [])
  693. s = '%s (%s)' % (self.name, self.version)
  694. if s not in result:
  695. result.append(s)
  696. return result
  697. @provides.setter
  698. def provides(self, value):
  699. if self._legacy:
  700. self._legacy['Provides-Dist'] = value
  701. else:
  702. self._data['provides'] = value
  703. def get_requirements(self, reqts, extras=None, env=None):
  704. """
  705. Base method to get dependencies, given a set of extras
  706. to satisfy and an optional environment context.
  707. :param reqts: A list of sometimes-wanted dependencies,
  708. perhaps dependent on extras and environment.
  709. :param extras: A list of optional components being requested.
  710. :param env: An optional environment for marker evaluation.
  711. """
  712. if self._legacy:
  713. result = reqts
  714. else:
  715. result = []
  716. extras = get_extras(extras or [], self.extras)
  717. for d in reqts:
  718. if 'extra' not in d and 'environment' not in d:
  719. # unconditional
  720. include = True
  721. else:
  722. if 'extra' not in d:
  723. # Not extra-dependent - only environment-dependent
  724. include = True
  725. else:
  726. include = d.get('extra') in extras
  727. if include:
  728. # Not excluded because of extras, check environment
  729. marker = d.get('environment')
  730. if marker:
  731. include = interpret(marker, env)
  732. if include:
  733. result.extend(d['requires'])
  734. for key in ('build', 'dev', 'test'):
  735. e = ':%s:' % key
  736. if e in extras:
  737. extras.remove(e)
  738. # A recursive call, but it should terminate since 'test'
  739. # has been removed from the extras
  740. reqts = self._data.get('%s_requires' % key, [])
  741. result.extend(self.get_requirements(reqts, extras=extras,
  742. env=env))
  743. return result
  744. @property
  745. def dictionary(self):
  746. if self._legacy:
  747. return self._from_legacy()
  748. return self._data
  749. @property
  750. def dependencies(self):
  751. if self._legacy:
  752. raise NotImplementedError
  753. else:
  754. return extract_by_key(self._data, self.DEPENDENCY_KEYS)
  755. @dependencies.setter
  756. def dependencies(self, value):
  757. if self._legacy:
  758. raise NotImplementedError
  759. else:
  760. self._data.update(value)
  761. def _validate_mapping(self, mapping, scheme):
  762. if mapping.get('metadata_version') != self.METADATA_VERSION:
  763. raise MetadataUnrecognizedVersionError()
  764. missing = []
  765. for key, exclusions in self.MANDATORY_KEYS.items():
  766. if key not in mapping:
  767. if scheme not in exclusions:
  768. missing.append(key)
  769. if missing:
  770. msg = 'Missing metadata items: %s' % ', '.join(missing)
  771. raise MetadataMissingError(msg)
  772. for k, v in mapping.items():
  773. self._validate_value(k, v, scheme)
  774. def validate(self):
  775. if self._legacy:
  776. missing, warnings = self._legacy.check(True)
  777. if missing or warnings:
  778. logger.warning('Metadata: missing: %s, warnings: %s',
  779. missing, warnings)
  780. else:
  781. self._validate_mapping(self._data, self.scheme)
  782. def todict(self):
  783. if self._legacy:
  784. return self._legacy.todict(True)
  785. else:
  786. result = extract_by_key(self._data, self.INDEX_KEYS)
  787. return result
  788. def _from_legacy(self):
  789. assert self._legacy and not self._data
  790. result = {
  791. 'metadata_version': self.METADATA_VERSION,
  792. 'generator': self.GENERATOR,
  793. }
  794. lmd = self._legacy.todict(True) # skip missing ones
  795. for k in ('name', 'version', 'license', 'summary', 'description',
  796. 'classifier'):
  797. if k in lmd:
  798. if k == 'classifier':
  799. nk = 'classifiers'
  800. else:
  801. nk = k
  802. result[nk] = lmd[k]
  803. kw = lmd.get('Keywords', [])
  804. if kw == ['']:
  805. kw = []
  806. result['keywords'] = kw
  807. keys = (('requires_dist', 'run_requires'),
  808. ('setup_requires_dist', 'build_requires'))
  809. for ok, nk in keys:
  810. if ok in lmd and lmd[ok]:
  811. result[nk] = [{'requires': lmd[ok]}]
  812. result['provides'] = self.provides
  813. author = {}
  814. maintainer = {}
  815. return result
  816. LEGACY_MAPPING = {
  817. 'name': 'Name',
  818. 'version': 'Version',
  819. ('extensions', 'python.details', 'license'): 'License',
  820. 'summary': 'Summary',
  821. 'description': 'Description',
  822. ('extensions', 'python.project', 'project_urls', 'Home'): 'Home-page',
  823. ('extensions', 'python.project', 'contacts', 0, 'name'): 'Author',
  824. ('extensions', 'python.project', 'contacts', 0, 'email'): 'Author-email',
  825. 'source_url': 'Download-URL',
  826. ('extensions', 'python.details', 'classifiers'): 'Classifier',
  827. }
  828. def _to_legacy(self):
  829. def process_entries(entries):
  830. reqts = set()
  831. for e in entries:
  832. extra = e.get('extra')
  833. env = e.get('environment')
  834. rlist = e['requires']
  835. for r in rlist:
  836. if not env and not extra:
  837. reqts.add(r)
  838. else:
  839. marker = ''
  840. if extra:
  841. marker = 'extra == "%s"' % extra
  842. if env:
  843. if marker:
  844. marker = '(%s) and %s' % (env, marker)
  845. else:
  846. marker = env
  847. reqts.add(';'.join((r, marker)))
  848. return reqts
  849. assert self._data and not self._legacy
  850. result = LegacyMetadata()
  851. nmd = self._data
  852. # import pdb; pdb.set_trace()
  853. for nk, ok in self.LEGACY_MAPPING.items():
  854. if not isinstance(nk, tuple):
  855. if nk in nmd:
  856. result[ok] = nmd[nk]
  857. else:
  858. d = nmd
  859. found = True
  860. for k in nk:
  861. try:
  862. d = d[k]
  863. except (KeyError, IndexError):
  864. found = False
  865. break
  866. if found:
  867. result[ok] = d
  868. r1 = process_entries(self.run_requires + self.meta_requires)
  869. r2 = process_entries(self.build_requires + self.dev_requires)
  870. if self.extras:
  871. result['Provides-Extra'] = sorted(self.extras)
  872. result['Requires-Dist'] = sorted(r1)
  873. result['Setup-Requires-Dist'] = sorted(r2)
  874. # TODO: any other fields wanted
  875. return result
  876. def write(self, path=None, fileobj=None, legacy=False, skip_unknown=True):
  877. if [path, fileobj].count(None) != 1:
  878. raise ValueError('Exactly one of path and fileobj is needed')
  879. self.validate()
  880. if legacy:
  881. if self._legacy:
  882. legacy_md = self._legacy
  883. else:
  884. legacy_md = self._to_legacy()
  885. if path:
  886. legacy_md.write(path, skip_unknown=skip_unknown)
  887. else:
  888. legacy_md.write_file(fileobj, skip_unknown=skip_unknown)
  889. else:
  890. if self._legacy:
  891. d = self._from_legacy()
  892. else:
  893. d = self._data
  894. if fileobj:
  895. json.dump(d, fileobj, ensure_ascii=True, indent=2,
  896. sort_keys=True)
  897. else:
  898. with codecs.open(path, 'w', 'utf-8') as f:
  899. json.dump(d, f, ensure_ascii=True, indent=2,
  900. sort_keys=True)
  901. def add_requirements(self, requirements):
  902. if self._legacy:
  903. self._legacy.add_requirements(requirements)
  904. else:
  905. run_requires = self._data.setdefault('run_requires', [])
  906. always = None
  907. for entry in run_requires:
  908. if 'environment' not in entry and 'extra' not in entry:
  909. always = entry
  910. break
  911. if always is None:
  912. always = { 'requires': requirements }
  913. run_requires.insert(0, always)
  914. else:
  915. rset = set(always['requires']) | set(requirements)
  916. always['requires'] = sorted(rset)
  917. def __repr__(self):
  918. name = self.name or '(no name)'
  919. version = self.version or 'no version'
  920. return '<%s %s %s (%s)>' % (self.__class__.__name__,
  921. self.metadata_version, name, version)