metadata.py 38 KB

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