metadata.py 38 KB

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