metadata.py 34 KB

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