metadata.py 32 KB

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