metadata.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import email.feedparser
  2. import email.header
  3. import email.message
  4. import email.parser
  5. import email.policy
  6. import sys
  7. import typing
  8. from typing import (
  9. Any,
  10. Callable,
  11. Dict,
  12. Generic,
  13. List,
  14. Optional,
  15. Tuple,
  16. Type,
  17. Union,
  18. cast,
  19. )
  20. from . import requirements, specifiers, utils, version as version_module
  21. T = typing.TypeVar("T")
  22. if sys.version_info[:2] >= (3, 8): # pragma: no cover
  23. from typing import Literal, TypedDict
  24. else: # pragma: no cover
  25. if typing.TYPE_CHECKING:
  26. from typing_extensions import Literal, TypedDict
  27. else:
  28. try:
  29. from typing_extensions import Literal, TypedDict
  30. except ImportError:
  31. class Literal:
  32. def __init_subclass__(*_args, **_kwargs):
  33. pass
  34. class TypedDict:
  35. def __init_subclass__(*_args, **_kwargs):
  36. pass
  37. try:
  38. ExceptionGroup = __builtins__.ExceptionGroup # type: ignore[attr-defined]
  39. except AttributeError:
  40. class ExceptionGroup(Exception): # type: ignore[no-redef] # noqa: N818
  41. """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
  42. If :external:exc:`ExceptionGroup` is already defined by Python itself,
  43. that version is used instead.
  44. """
  45. message: str
  46. exceptions: List[Exception]
  47. def __init__(self, message: str, exceptions: List[Exception]) -> None:
  48. self.message = message
  49. self.exceptions = exceptions
  50. def __repr__(self) -> str:
  51. return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})"
  52. class InvalidMetadata(ValueError):
  53. """A metadata field contains invalid data."""
  54. field: str
  55. """The name of the field that contains invalid data."""
  56. def __init__(self, field: str, message: str) -> None:
  57. self.field = field
  58. super().__init__(message)
  59. # The RawMetadata class attempts to make as few assumptions about the underlying
  60. # serialization formats as possible. The idea is that as long as a serialization
  61. # formats offer some very basic primitives in *some* way then we can support
  62. # serializing to and from that format.
  63. class RawMetadata(TypedDict, total=False):
  64. """A dictionary of raw core metadata.
  65. Each field in core metadata maps to a key of this dictionary (when data is
  66. provided). The key is lower-case and underscores are used instead of dashes
  67. compared to the equivalent core metadata field. Any core metadata field that
  68. can be specified multiple times or can hold multiple values in a single
  69. field have a key with a plural name. See :class:`Metadata` whose attributes
  70. match the keys of this dictionary.
  71. Core metadata fields that can be specified multiple times are stored as a
  72. list or dict depending on which is appropriate for the field. Any fields
  73. which hold multiple values in a single field are stored as a list.
  74. """
  75. # Metadata 1.0 - PEP 241
  76. metadata_version: str
  77. name: str
  78. version: str
  79. platforms: List[str]
  80. summary: str
  81. description: str
  82. keywords: List[str]
  83. home_page: str
  84. author: str
  85. author_email: str
  86. license: str
  87. # Metadata 1.1 - PEP 314
  88. supported_platforms: List[str]
  89. download_url: str
  90. classifiers: List[str]
  91. requires: List[str]
  92. provides: List[str]
  93. obsoletes: List[str]
  94. # Metadata 1.2 - PEP 345
  95. maintainer: str
  96. maintainer_email: str
  97. requires_dist: List[str]
  98. provides_dist: List[str]
  99. obsoletes_dist: List[str]
  100. requires_python: str
  101. requires_external: List[str]
  102. project_urls: Dict[str, str]
  103. # Metadata 2.0
  104. # PEP 426 attempted to completely revamp the metadata format
  105. # but got stuck without ever being able to build consensus on
  106. # it and ultimately ended up withdrawn.
  107. #
  108. # However, a number of tools had started emitting METADATA with
  109. # `2.0` Metadata-Version, so for historical reasons, this version
  110. # was skipped.
  111. # Metadata 2.1 - PEP 566
  112. description_content_type: str
  113. provides_extra: List[str]
  114. # Metadata 2.2 - PEP 643
  115. dynamic: List[str]
  116. # Metadata 2.3 - PEP 685
  117. # No new fields were added in PEP 685, just some edge case were
  118. # tightened up to provide better interoptability.
  119. _STRING_FIELDS = {
  120. "author",
  121. "author_email",
  122. "description",
  123. "description_content_type",
  124. "download_url",
  125. "home_page",
  126. "license",
  127. "maintainer",
  128. "maintainer_email",
  129. "metadata_version",
  130. "name",
  131. "requires_python",
  132. "summary",
  133. "version",
  134. }
  135. _LIST_FIELDS = {
  136. "classifiers",
  137. "dynamic",
  138. "obsoletes",
  139. "obsoletes_dist",
  140. "platforms",
  141. "provides",
  142. "provides_dist",
  143. "provides_extra",
  144. "requires",
  145. "requires_dist",
  146. "requires_external",
  147. "supported_platforms",
  148. }
  149. _DICT_FIELDS = {
  150. "project_urls",
  151. }
  152. def _parse_keywords(data: str) -> List[str]:
  153. """Split a string of comma-separate keyboards into a list of keywords."""
  154. return [k.strip() for k in data.split(",")]
  155. def _parse_project_urls(data: List[str]) -> Dict[str, str]:
  156. """Parse a list of label/URL string pairings separated by a comma."""
  157. urls = {}
  158. for pair in data:
  159. # Our logic is slightly tricky here as we want to try and do
  160. # *something* reasonable with malformed data.
  161. #
  162. # The main thing that we have to worry about, is data that does
  163. # not have a ',' at all to split the label from the Value. There
  164. # isn't a singular right answer here, and we will fail validation
  165. # later on (if the caller is validating) so it doesn't *really*
  166. # matter, but since the missing value has to be an empty str
  167. # and our return value is dict[str, str], if we let the key
  168. # be the missing value, then they'd have multiple '' values that
  169. # overwrite each other in a accumulating dict.
  170. #
  171. # The other potentional issue is that it's possible to have the
  172. # same label multiple times in the metadata, with no solid "right"
  173. # answer with what to do in that case. As such, we'll do the only
  174. # thing we can, which is treat the field as unparseable and add it
  175. # to our list of unparsed fields.
  176. parts = [p.strip() for p in pair.split(",", 1)]
  177. parts.extend([""] * (max(0, 2 - len(parts)))) # Ensure 2 items
  178. # TODO: The spec doesn't say anything about if the keys should be
  179. # considered case sensitive or not... logically they should
  180. # be case-preserving and case-insensitive, but doing that
  181. # would open up more cases where we might have duplicate
  182. # entries.
  183. label, url = parts
  184. if label in urls:
  185. # The label already exists in our set of urls, so this field
  186. # is unparseable, and we can just add the whole thing to our
  187. # unparseable data and stop processing it.
  188. raise KeyError("duplicate labels in project urls")
  189. urls[label] = url
  190. return urls
  191. def _get_payload(msg: email.message.Message, source: Union[bytes, str]) -> str:
  192. """Get the body of the message."""
  193. # If our source is a str, then our caller has managed encodings for us,
  194. # and we don't need to deal with it.
  195. if isinstance(source, str):
  196. payload: str = msg.get_payload()
  197. return payload
  198. # If our source is a bytes, then we're managing the encoding and we need
  199. # to deal with it.
  200. else:
  201. bpayload: bytes = msg.get_payload(decode=True)
  202. try:
  203. return bpayload.decode("utf8", "strict")
  204. except UnicodeDecodeError:
  205. raise ValueError("payload in an invalid encoding")
  206. # The various parse_FORMAT functions here are intended to be as lenient as
  207. # possible in their parsing, while still returning a correctly typed
  208. # RawMetadata.
  209. #
  210. # To aid in this, we also generally want to do as little touching of the
  211. # data as possible, except where there are possibly some historic holdovers
  212. # that make valid data awkward to work with.
  213. #
  214. # While this is a lower level, intermediate format than our ``Metadata``
  215. # class, some light touch ups can make a massive difference in usability.
  216. # Map METADATA fields to RawMetadata.
  217. _EMAIL_TO_RAW_MAPPING = {
  218. "author": "author",
  219. "author-email": "author_email",
  220. "classifier": "classifiers",
  221. "description": "description",
  222. "description-content-type": "description_content_type",
  223. "download-url": "download_url",
  224. "dynamic": "dynamic",
  225. "home-page": "home_page",
  226. "keywords": "keywords",
  227. "license": "license",
  228. "maintainer": "maintainer",
  229. "maintainer-email": "maintainer_email",
  230. "metadata-version": "metadata_version",
  231. "name": "name",
  232. "obsoletes": "obsoletes",
  233. "obsoletes-dist": "obsoletes_dist",
  234. "platform": "platforms",
  235. "project-url": "project_urls",
  236. "provides": "provides",
  237. "provides-dist": "provides_dist",
  238. "provides-extra": "provides_extra",
  239. "requires": "requires",
  240. "requires-dist": "requires_dist",
  241. "requires-external": "requires_external",
  242. "requires-python": "requires_python",
  243. "summary": "summary",
  244. "supported-platform": "supported_platforms",
  245. "version": "version",
  246. }
  247. _RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()}
  248. def parse_email(data: Union[bytes, str]) -> Tuple[RawMetadata, Dict[str, List[str]]]:
  249. """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``).
  250. This function returns a two-item tuple of dicts. The first dict is of
  251. recognized fields from the core metadata specification. Fields that can be
  252. parsed and translated into Python's built-in types are converted
  253. appropriately. All other fields are left as-is. Fields that are allowed to
  254. appear multiple times are stored as lists.
  255. The second dict contains all other fields from the metadata. This includes
  256. any unrecognized fields. It also includes any fields which are expected to
  257. be parsed into a built-in type but were not formatted appropriately. Finally,
  258. any fields that are expected to appear only once but are repeated are
  259. included in this dict.
  260. """
  261. raw: Dict[str, Union[str, List[str], Dict[str, str]]] = {}
  262. unparsed: Dict[str, List[str]] = {}
  263. if isinstance(data, str):
  264. parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data)
  265. else:
  266. parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data)
  267. # We have to wrap parsed.keys() in a set, because in the case of multiple
  268. # values for a key (a list), the key will appear multiple times in the
  269. # list of keys, but we're avoiding that by using get_all().
  270. for name in frozenset(parsed.keys()):
  271. # Header names in RFC are case insensitive, so we'll normalize to all
  272. # lower case to make comparisons easier.
  273. name = name.lower()
  274. # We use get_all() here, even for fields that aren't multiple use,
  275. # because otherwise someone could have e.g. two Name fields, and we
  276. # would just silently ignore it rather than doing something about it.
  277. headers = parsed.get_all(name) or []
  278. # The way the email module works when parsing bytes is that it
  279. # unconditionally decodes the bytes as ascii using the surrogateescape
  280. # handler. When you pull that data back out (such as with get_all() ),
  281. # it looks to see if the str has any surrogate escapes, and if it does
  282. # it wraps it in a Header object instead of returning the string.
  283. #
  284. # As such, we'll look for those Header objects, and fix up the encoding.
  285. value = []
  286. # Flag if we have run into any issues processing the headers, thus
  287. # signalling that the data belongs in 'unparsed'.
  288. valid_encoding = True
  289. for h in headers:
  290. # It's unclear if this can return more types than just a Header or
  291. # a str, so we'll just assert here to make sure.
  292. assert isinstance(h, (email.header.Header, str))
  293. # If it's a header object, we need to do our little dance to get
  294. # the real data out of it. In cases where there is invalid data
  295. # we're going to end up with mojibake, but there's no obvious, good
  296. # way around that without reimplementing parts of the Header object
  297. # ourselves.
  298. #
  299. # That should be fine since, if mojibacked happens, this key is
  300. # going into the unparsed dict anyways.
  301. if isinstance(h, email.header.Header):
  302. # The Header object stores it's data as chunks, and each chunk
  303. # can be independently encoded, so we'll need to check each
  304. # of them.
  305. chunks: List[Tuple[bytes, Optional[str]]] = []
  306. for bin, encoding in email.header.decode_header(h):
  307. try:
  308. bin.decode("utf8", "strict")
  309. except UnicodeDecodeError:
  310. # Enable mojibake.
  311. encoding = "latin1"
  312. valid_encoding = False
  313. else:
  314. encoding = "utf8"
  315. chunks.append((bin, encoding))
  316. # Turn our chunks back into a Header object, then let that
  317. # Header object do the right thing to turn them into a
  318. # string for us.
  319. value.append(str(email.header.make_header(chunks)))
  320. # This is already a string, so just add it.
  321. else:
  322. value.append(h)
  323. # We've processed all of our values to get them into a list of str,
  324. # but we may have mojibake data, in which case this is an unparsed
  325. # field.
  326. if not valid_encoding:
  327. unparsed[name] = value
  328. continue
  329. raw_name = _EMAIL_TO_RAW_MAPPING.get(name)
  330. if raw_name is None:
  331. # This is a bit of a weird situation, we've encountered a key that
  332. # we don't know what it means, so we don't know whether it's meant
  333. # to be a list or not.
  334. #
  335. # Since we can't really tell one way or another, we'll just leave it
  336. # as a list, even though it may be a single item list, because that's
  337. # what makes the most sense for email headers.
  338. unparsed[name] = value
  339. continue
  340. # If this is one of our string fields, then we'll check to see if our
  341. # value is a list of a single item. If it is then we'll assume that
  342. # it was emitted as a single string, and unwrap the str from inside
  343. # the list.
  344. #
  345. # If it's any other kind of data, then we haven't the faintest clue
  346. # what we should parse it as, and we have to just add it to our list
  347. # of unparsed stuff.
  348. if raw_name in _STRING_FIELDS and len(value) == 1:
  349. raw[raw_name] = value[0]
  350. # If this is one of our list of string fields, then we can just assign
  351. # the value, since email *only* has strings, and our get_all() call
  352. # above ensures that this is a list.
  353. elif raw_name in _LIST_FIELDS:
  354. raw[raw_name] = value
  355. # Special Case: Keywords
  356. # The keywords field is implemented in the metadata spec as a str,
  357. # but it conceptually is a list of strings, and is serialized using
  358. # ", ".join(keywords), so we'll do some light data massaging to turn
  359. # this into what it logically is.
  360. elif raw_name == "keywords" and len(value) == 1:
  361. raw[raw_name] = _parse_keywords(value[0])
  362. # Special Case: Project-URL
  363. # The project urls is implemented in the metadata spec as a list of
  364. # specially-formatted strings that represent a key and a value, which
  365. # is fundamentally a mapping, however the email format doesn't support
  366. # mappings in a sane way, so it was crammed into a list of strings
  367. # instead.
  368. #
  369. # We will do a little light data massaging to turn this into a map as
  370. # it logically should be.
  371. elif raw_name == "project_urls":
  372. try:
  373. raw[raw_name] = _parse_project_urls(value)
  374. except KeyError:
  375. unparsed[name] = value
  376. # Nothing that we've done has managed to parse this, so it'll just
  377. # throw it in our unparseable data and move on.
  378. else:
  379. unparsed[name] = value
  380. # We need to support getting the Description from the message payload in
  381. # addition to getting it from the the headers. This does mean, though, there
  382. # is the possibility of it being set both ways, in which case we put both
  383. # in 'unparsed' since we don't know which is right.
  384. try:
  385. payload = _get_payload(parsed, data)
  386. except ValueError:
  387. unparsed.setdefault("description", []).append(
  388. parsed.get_payload(decode=isinstance(data, bytes))
  389. )
  390. else:
  391. if payload:
  392. # Check to see if we've already got a description, if so then both
  393. # it, and this body move to unparseable.
  394. if "description" in raw:
  395. description_header = cast(str, raw.pop("description"))
  396. unparsed.setdefault("description", []).extend(
  397. [description_header, payload]
  398. )
  399. elif "description" in unparsed:
  400. unparsed["description"].append(payload)
  401. else:
  402. raw["description"] = payload
  403. # We need to cast our `raw` to a metadata, because a TypedDict only support
  404. # literal key names, but we're computing our key names on purpose, but the
  405. # way this function is implemented, our `TypedDict` can only have valid key
  406. # names.
  407. return cast(RawMetadata, raw), unparsed
  408. _NOT_FOUND = object()
  409. # Keep the two values in sync.
  410. _VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"]
  411. _MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"]
  412. _REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"])
  413. class _Validator(Generic[T]):
  414. """Validate a metadata field.
  415. All _process_*() methods correspond to a core metadata field. The method is
  416. called with the field's raw value. If the raw value is valid it is returned
  417. in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field).
  418. If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause
  419. as appropriate).
  420. """
  421. name: str
  422. raw_name: str
  423. added: _MetadataVersion
  424. def __init__(
  425. self,
  426. *,
  427. added: _MetadataVersion = "1.0",
  428. ) -> None:
  429. self.added = added
  430. def __set_name__(self, _owner: "Metadata", name: str) -> None:
  431. self.name = name
  432. self.raw_name = _RAW_TO_EMAIL_MAPPING[name]
  433. def __get__(self, instance: "Metadata", _owner: Type["Metadata"]) -> T:
  434. # With Python 3.8, the caching can be replaced with functools.cached_property().
  435. # No need to check the cache as attribute lookup will resolve into the
  436. # instance's __dict__ before __get__ is called.
  437. cache = instance.__dict__
  438. try:
  439. value = instance._raw[self.name] # type: ignore[literal-required]
  440. except KeyError:
  441. if self.name in _STRING_FIELDS:
  442. value = ""
  443. elif self.name in _LIST_FIELDS:
  444. value = []
  445. elif self.name in _DICT_FIELDS:
  446. value = {}
  447. else: # pragma: no cover
  448. assert False
  449. try:
  450. converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}")
  451. except AttributeError:
  452. pass
  453. else:
  454. value = converter(value)
  455. cache[self.name] = value
  456. try:
  457. del instance._raw[self.name] # type: ignore[misc]
  458. except KeyError:
  459. pass
  460. return cast(T, value)
  461. def _invalid_metadata(
  462. self, msg: str, cause: Optional[Exception] = None
  463. ) -> InvalidMetadata:
  464. exc = InvalidMetadata(
  465. self.raw_name, msg.format_map({"field": repr(self.raw_name)})
  466. )
  467. exc.__cause__ = cause
  468. return exc
  469. def _process_metadata_version(self, value: str) -> _MetadataVersion:
  470. # Implicitly makes Metadata-Version required.
  471. if value not in _VALID_METADATA_VERSIONS:
  472. raise self._invalid_metadata(f"{value!r} is not a valid metadata version")
  473. return cast(_MetadataVersion, value)
  474. def _process_name(self, value: str) -> str:
  475. if not value:
  476. raise self._invalid_metadata("{field} is a required field")
  477. # Validate the name as a side-effect.
  478. try:
  479. utils.canonicalize_name(value, validate=True)
  480. except utils.InvalidName as exc:
  481. raise self._invalid_metadata(
  482. f"{value!r} is invalid for {{field}}", cause=exc
  483. )
  484. else:
  485. return value
  486. def _process_version(self, value: str) -> version_module.Version:
  487. if not value:
  488. raise self._invalid_metadata("{field} is a required field")
  489. try:
  490. return version_module.parse(value)
  491. except version_module.InvalidVersion as exc:
  492. raise self._invalid_metadata(
  493. f"{value!r} is invalid for {{field}}", cause=exc
  494. )
  495. def _process_summary(self, value: str) -> str:
  496. """Check the field contains no newlines."""
  497. if "\n" in value:
  498. raise self._invalid_metadata("{field} must be a single line")
  499. return value
  500. def _process_description_content_type(self, value: str) -> str:
  501. content_types = {"text/plain", "text/x-rst", "text/markdown"}
  502. message = email.message.EmailMessage()
  503. message["content-type"] = value
  504. content_type, parameters = (
  505. # Defaults to `text/plain` if parsing failed.
  506. message.get_content_type().lower(),
  507. message["content-type"].params,
  508. )
  509. # Check if content-type is valid or defaulted to `text/plain` and thus was
  510. # not parseable.
  511. if content_type not in content_types or content_type not in value.lower():
  512. raise self._invalid_metadata(
  513. f"{{field}} must be one of {list(content_types)}, not {value!r}"
  514. )
  515. charset = parameters.get("charset", "UTF-8")
  516. if charset != "UTF-8":
  517. raise self._invalid_metadata(
  518. f"{{field}} can only specify the UTF-8 charset, not {list(charset)}"
  519. )
  520. markdown_variants = {"GFM", "CommonMark"}
  521. variant = parameters.get("variant", "GFM") # Use an acceptable default.
  522. if content_type == "text/markdown" and variant not in markdown_variants:
  523. raise self._invalid_metadata(
  524. f"valid Markdown variants for {{field}} are {list(markdown_variants)}, "
  525. f"not {variant!r}",
  526. )
  527. return value
  528. def _process_dynamic(self, value: List[str]) -> List[str]:
  529. for dynamic_field in map(str.lower, value):
  530. if dynamic_field in {"name", "version", "metadata-version"}:
  531. raise self._invalid_metadata(
  532. f"{value!r} is not allowed as a dynamic field"
  533. )
  534. elif dynamic_field not in _EMAIL_TO_RAW_MAPPING:
  535. raise self._invalid_metadata(f"{value!r} is not a valid dynamic field")
  536. return list(map(str.lower, value))
  537. def _process_provides_extra(
  538. self,
  539. value: List[str],
  540. ) -> List[utils.NormalizedName]:
  541. normalized_names = []
  542. try:
  543. for name in value:
  544. normalized_names.append(utils.canonicalize_name(name, validate=True))
  545. except utils.InvalidName as exc:
  546. raise self._invalid_metadata(
  547. f"{name!r} is invalid for {{field}}", cause=exc
  548. )
  549. else:
  550. return normalized_names
  551. def _process_requires_python(self, value: str) -> specifiers.SpecifierSet:
  552. try:
  553. return specifiers.SpecifierSet(value)
  554. except specifiers.InvalidSpecifier as exc:
  555. raise self._invalid_metadata(
  556. f"{value!r} is invalid for {{field}}", cause=exc
  557. )
  558. def _process_requires_dist(
  559. self,
  560. value: List[str],
  561. ) -> List[requirements.Requirement]:
  562. reqs = []
  563. try:
  564. for req in value:
  565. reqs.append(requirements.Requirement(req))
  566. except requirements.InvalidRequirement as exc:
  567. raise self._invalid_metadata(f"{req!r} is invalid for {{field}}", cause=exc)
  568. else:
  569. return reqs
  570. class Metadata:
  571. """Representation of distribution metadata.
  572. Compared to :class:`RawMetadata`, this class provides objects representing
  573. metadata fields instead of only using built-in types. Any invalid metadata
  574. will cause :exc:`InvalidMetadata` to be raised (with a
  575. :py:attr:`~BaseException.__cause__` attribute as appropriate).
  576. """
  577. _raw: RawMetadata
  578. @classmethod
  579. def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> "Metadata":
  580. """Create an instance from :class:`RawMetadata`.
  581. If *validate* is true, all metadata will be validated. All exceptions
  582. related to validation will be gathered and raised as an :class:`ExceptionGroup`.
  583. """
  584. ins = cls()
  585. ins._raw = data.copy() # Mutations occur due to caching enriched values.
  586. if validate:
  587. exceptions: List[InvalidMetadata] = []
  588. try:
  589. metadata_version = ins.metadata_version
  590. metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version)
  591. except InvalidMetadata as metadata_version_exc:
  592. exceptions.append(metadata_version_exc)
  593. metadata_version = None
  594. # Make sure to check for the fields that are present, the required
  595. # fields (so their absence can be reported).
  596. fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS
  597. # Remove fields that have already been checked.
  598. fields_to_check -= {"metadata_version"}
  599. for key in fields_to_check:
  600. try:
  601. if metadata_version:
  602. # Can't use getattr() as that triggers descriptor protocol which
  603. # will fail due to no value for the instance argument.
  604. try:
  605. field_metadata_version = cls.__dict__[key].added
  606. except KeyError:
  607. exc = InvalidMetadata(key, f"unrecognized field: {key!r}")
  608. exceptions.append(exc)
  609. continue
  610. field_age = _VALID_METADATA_VERSIONS.index(
  611. field_metadata_version
  612. )
  613. if field_age > metadata_age:
  614. field = _RAW_TO_EMAIL_MAPPING[key]
  615. exc = InvalidMetadata(
  616. field,
  617. "{field} introduced in metadata version "
  618. "{field_metadata_version}, not {metadata_version}",
  619. )
  620. exceptions.append(exc)
  621. continue
  622. getattr(ins, key)
  623. except InvalidMetadata as exc:
  624. exceptions.append(exc)
  625. if exceptions:
  626. raise ExceptionGroup("invalid metadata", exceptions)
  627. return ins
  628. @classmethod
  629. def from_email(
  630. cls, data: Union[bytes, str], *, validate: bool = True
  631. ) -> "Metadata":
  632. """Parse metadata from email headers.
  633. If *validate* is true, the metadata will be validated. All exceptions
  634. related to validation will be gathered and raised as an :class:`ExceptionGroup`.
  635. """
  636. exceptions: list[InvalidMetadata] = []
  637. raw, unparsed = parse_email(data)
  638. if validate:
  639. for unparsed_key in unparsed:
  640. if unparsed_key in _EMAIL_TO_RAW_MAPPING:
  641. message = f"{unparsed_key!r} has invalid data"
  642. else:
  643. message = f"unrecognized field: {unparsed_key!r}"
  644. exceptions.append(InvalidMetadata(unparsed_key, message))
  645. if exceptions:
  646. raise ExceptionGroup("unparsed", exceptions)
  647. try:
  648. return cls.from_raw(raw, validate=validate)
  649. except ExceptionGroup as exc_group:
  650. exceptions.extend(exc_group.exceptions)
  651. raise ExceptionGroup("invalid or unparsed metadata", exceptions) from None
  652. metadata_version: _Validator[_MetadataVersion] = _Validator()
  653. """:external:ref:`core-metadata-metadata-version`
  654. (required; validated to be a valid metadata version)"""
  655. name: _Validator[str] = _Validator()
  656. """:external:ref:`core-metadata-name`
  657. (required; validated using :func:`~packaging.utils.canonicalize_name` and its
  658. *validate* parameter)"""
  659. version: _Validator[version_module.Version] = _Validator()
  660. """:external:ref:`core-metadata-version` (required)"""
  661. dynamic: _Validator[List[str]] = _Validator(
  662. added="2.2",
  663. )
  664. """:external:ref:`core-metadata-dynamic`
  665. (validated against core metadata field names and lowercased)"""
  666. platforms: _Validator[List[str]] = _Validator()
  667. """:external:ref:`core-metadata-platform`"""
  668. supported_platforms: _Validator[List[str]] = _Validator(added="1.1")
  669. """:external:ref:`core-metadata-supported-platform`"""
  670. summary: _Validator[str] = _Validator()
  671. """:external:ref:`core-metadata-summary` (validated to contain no newlines)"""
  672. description: _Validator[str] = _Validator() # TODO 2.1: can be in body
  673. """:external:ref:`core-metadata-description`"""
  674. description_content_type: _Validator[str] = _Validator(added="2.1")
  675. """:external:ref:`core-metadata-description-content-type` (validated)"""
  676. keywords: _Validator[List[str]] = _Validator()
  677. """:external:ref:`core-metadata-keywords`"""
  678. home_page: _Validator[str] = _Validator()
  679. """:external:ref:`core-metadata-home-page`"""
  680. download_url: _Validator[str] = _Validator(added="1.1")
  681. """:external:ref:`core-metadata-download-url`"""
  682. author: _Validator[str] = _Validator()
  683. """:external:ref:`core-metadata-author`"""
  684. author_email: _Validator[str] = _Validator()
  685. """:external:ref:`core-metadata-author-email`"""
  686. maintainer: _Validator[str] = _Validator(added="1.2")
  687. """:external:ref:`core-metadata-maintainer`"""
  688. maintainer_email: _Validator[str] = _Validator(added="1.2")
  689. """:external:ref:`core-metadata-maintainer-email`"""
  690. license: _Validator[str] = _Validator()
  691. """:external:ref:`core-metadata-license`"""
  692. classifiers: _Validator[List[str]] = _Validator(added="1.1")
  693. """:external:ref:`core-metadata-classifier`"""
  694. requires_dist: _Validator[List[requirements.Requirement]] = _Validator(added="1.2")
  695. """:external:ref:`core-metadata-requires-dist`"""
  696. requires_python: _Validator[specifiers.SpecifierSet] = _Validator(added="1.2")
  697. """:external:ref:`core-metadata-requires-python`"""
  698. # Because `Requires-External` allows for non-PEP 440 version specifiers, we
  699. # don't do any processing on the values.
  700. requires_external: _Validator[List[str]] = _Validator(added="1.2")
  701. """:external:ref:`core-metadata-requires-external`"""
  702. project_urls: _Validator[Dict[str, str]] = _Validator(added="1.2")
  703. """:external:ref:`core-metadata-project-url`"""
  704. # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation
  705. # regardless of metadata version.
  706. provides_extra: _Validator[List[utils.NormalizedName]] = _Validator(
  707. added="2.1",
  708. )
  709. """:external:ref:`core-metadata-provides-extra`"""
  710. provides_dist: _Validator[List[str]] = _Validator(added="1.2")
  711. """:external:ref:`core-metadata-provides-dist`"""
  712. obsoletes_dist: _Validator[List[str]] = _Validator(added="1.2")
  713. """:external:ref:`core-metadata-obsoletes-dist`"""
  714. requires: _Validator[List[str]] = _Validator(added="1.1")
  715. """``Requires`` (deprecated)"""
  716. provides: _Validator[List[str]] = _Validator(added="1.1")
  717. """``Provides`` (deprecated)"""
  718. obsoletes: _Validator[List[str]] = _Validator(added="1.1")
  719. """``Obsoletes`` (deprecated)"""