metadata.py 38 KB

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