]>
jfr.im git - dlqueue.git/blob - venv/lib/python3.11/site-packages/setuptools/_vendor/packaging/metadata.py
1 import email
.feedparser
8 from typing
import Dict
, List
, Optional
, Tuple
, Union
, cast
10 if sys
.version_info
>= (3, 8): # pragma: no cover
11 from typing
import TypedDict
12 else: # pragma: no cover
13 if typing
.TYPE_CHECKING
:
14 from typing_extensions
import TypedDict
17 from typing_extensions
import TypedDict
21 def __init_subclass__(*_args
, **_kwargs
):
25 # The RawMetadata class attempts to make as few assumptions about the underlying
26 # serialization formats as possible. The idea is that as long as a serialization
27 # formats offer some very basic primitives in *some* way then we can support
28 # serializing to and from that format.
29 class RawMetadata(TypedDict
, total
=False):
30 """A dictionary of raw core metadata.
32 Each field in core metadata maps to a key of this dictionary (when data is
33 provided). The key is lower-case and underscores are used instead of dashes
34 compared to the equivalent core metadata field. Any core metadata field that
35 can be specified multiple times or can hold multiple values in a single
36 field have a key with a plural name.
38 Core metadata fields that can be specified multiple times are stored as a
39 list or dict depending on which is appropriate for the field. Any fields
40 which hold multiple values in a single field are stored as a list.
44 # Metadata 1.0 - PEP 241
57 # Metadata 1.1 - PEP 314
58 supported_platforms
: List
[str]
60 classifiers
: List
[str]
65 # Metadata 1.2 - PEP 345
68 requires_dist
: List
[str]
69 provides_dist
: List
[str]
70 obsoletes_dist
: List
[str]
72 requires_external
: List
[str]
73 project_urls
: Dict
[str, str]
76 # PEP 426 attempted to completely revamp the metadata format
77 # but got stuck without ever being able to build consensus on
78 # it and ultimately ended up withdrawn.
80 # However, a number of tools had started emiting METADATA with
81 # `2.0` Metadata-Version, so for historical reasons, this version
84 # Metadata 2.1 - PEP 566
85 description_content_type
: str
86 provides_extra
: List
[str]
88 # Metadata 2.2 - PEP 643
91 # Metadata 2.3 - PEP 685
92 # No new fields were added in PEP 685, just some edge case were
93 # tightened up to provide better interoptability.
100 "description_content_type",
113 _LIST_STRING_FIELDS
= {
125 "supported_platforms",
129 def _parse_keywords(data
: str) -> List
[str]:
130 """Split a string of comma-separate keyboards into a list of keywords."""
131 return [k
.strip() for k
in data
.split(",")]
134 def _parse_project_urls(data
: List
[str]) -> Dict
[str, str]:
135 """Parse a list of label/URL string pairings separated by a comma."""
138 # Our logic is slightly tricky here as we want to try and do
139 # *something* reasonable with malformed data.
141 # The main thing that we have to worry about, is data that does
142 # not have a ',' at all to split the label from the Value. There
143 # isn't a singular right answer here, and we will fail validation
144 # later on (if the caller is validating) so it doesn't *really*
145 # matter, but since the missing value has to be an empty str
146 # and our return value is dict[str, str], if we let the key
147 # be the missing value, then they'd have multiple '' values that
148 # overwrite each other in a accumulating dict.
150 # The other potentional issue is that it's possible to have the
151 # same label multiple times in the metadata, with no solid "right"
152 # answer with what to do in that case. As such, we'll do the only
153 # thing we can, which is treat the field as unparseable and add it
154 # to our list of unparsed fields.
155 parts
= [p
.strip() for p
in pair
.split(",", 1)]
156 parts
.extend([""] * (max(0, 2 - len(parts
)))) # Ensure 2 items
158 # TODO: The spec doesn't say anything about if the keys should be
159 # considered case sensitive or not... logically they should
160 # be case-preserving and case-insensitive, but doing that
161 # would open up more cases where we might have duplicate
165 # The label already exists in our set of urls, so this field
166 # is unparseable, and we can just add the whole thing to our
167 # unparseable data and stop processing it.
168 raise KeyError("duplicate labels in project urls")
174 def _get_payload(msg
: email
.message
.Message
, source
: Union
[bytes, str]) -> str:
175 """Get the body of the message."""
176 # If our source is a str, then our caller has managed encodings for us,
177 # and we don't need to deal with it.
178 if isinstance(source
, str):
179 payload
: str = msg
.get_payload()
181 # If our source is a bytes, then we're managing the encoding and we need
184 bpayload
: bytes = msg
.get_payload(decode
=True)
186 return bpayload
.decode("utf8", "strict")
187 except UnicodeDecodeError:
188 raise ValueError("payload in an invalid encoding")
191 # The various parse_FORMAT functions here are intended to be as lenient as
192 # possible in their parsing, while still returning a correctly typed
195 # To aid in this, we also generally want to do as little touching of the
196 # data as possible, except where there are possibly some historic holdovers
197 # that make valid data awkward to work with.
199 # While this is a lower level, intermediate format than our ``Metadata``
200 # class, some light touch ups can make a massive difference in usability.
202 # Map METADATA fields to RawMetadata.
203 _EMAIL_TO_RAW_MAPPING
= {
205 "author-email": "author_email",
206 "classifier": "classifiers",
207 "description": "description",
208 "description-content-type": "description_content_type",
209 "download-url": "download_url",
210 "dynamic": "dynamic",
211 "home-page": "home_page",
212 "keywords": "keywords",
213 "license": "license",
214 "maintainer": "maintainer",
215 "maintainer-email": "maintainer_email",
216 "metadata-version": "metadata_version",
218 "obsoletes": "obsoletes",
219 "obsoletes-dist": "obsoletes_dist",
220 "platform": "platforms",
221 "project-url": "project_urls",
222 "provides": "provides",
223 "provides-dist": "provides_dist",
224 "provides-extra": "provides_extra",
225 "requires": "requires",
226 "requires-dist": "requires_dist",
227 "requires-external": "requires_external",
228 "requires-python": "requires_python",
229 "summary": "summary",
230 "supported-platform": "supported_platforms",
231 "version": "version",
235 def parse_email(data
: Union
[bytes, str]) -> Tuple
[RawMetadata
, Dict
[str, List
[str]]]:
236 """Parse a distribution's metadata.
238 This function returns a two-item tuple of dicts. The first dict is of
239 recognized fields from the core metadata specification. Fields that can be
240 parsed and translated into Python's built-in types are converted
241 appropriately. All other fields are left as-is. Fields that are allowed to
242 appear multiple times are stored as lists.
244 The second dict contains all other fields from the metadata. This includes
245 any unrecognized fields. It also includes any fields which are expected to
246 be parsed into a built-in type but were not formatted appropriately. Finally,
247 any fields that are expected to appear only once but are repeated are
248 included in this dict.
251 raw
: Dict
[str, Union
[str, List
[str], Dict
[str, str]]] = {}
252 unparsed
: Dict
[str, List
[str]] = {}
254 if isinstance(data
, str):
255 parsed
= email
.parser
.Parser(policy
=email
.policy
.compat32
).parsestr(data
)
257 parsed
= email
.parser
.BytesParser(policy
=email
.policy
.compat32
).parsebytes(data
)
259 # We have to wrap parsed.keys() in a set, because in the case of multiple
260 # values for a key (a list), the key will appear multiple times in the
261 # list of keys, but we're avoiding that by using get_all().
262 for name
in frozenset(parsed
.keys()):
263 # Header names in RFC are case insensitive, so we'll normalize to all
264 # lower case to make comparisons easier.
267 # We use get_all() here, even for fields that aren't multiple use,
268 # because otherwise someone could have e.g. two Name fields, and we
269 # would just silently ignore it rather than doing something about it.
270 headers
= parsed
.get_all(name
)
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.
278 # As such, we'll look for those Header objects, and fix up the encoding.
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
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))
288 # If it's a header object, we need to do our little dance to get
289 # the real data out of it. In cases where there is invalid data
290 # we're going to end up with mojibake, but there's no obvious, good
291 # way around that without reimplementing parts of the Header object
294 # That should be fine since, if mojibacked happens, this key is
295 # going into the unparsed dict anyways.
296 if isinstance(h
, email
.header
.Header
):
297 # The Header object stores it's data as chunks, and each chunk
298 # can be independently encoded, so we'll need to check each
300 chunks
: List
[Tuple
[bytes, Optional
[str]]] = []
301 for bin
, encoding
in email
.header
.decode_header(h
):
303 bin
.decode("utf8", "strict")
304 except UnicodeDecodeError:
307 valid_encoding
= False
310 chunks
.append((bin
, encoding
))
312 # Turn our chunks back into a Header object, then let that
313 # Header object do the right thing to turn them into a
315 value
.append(str(email
.header
.make_header(chunks
)))
316 # This is already a string, so just add it.
320 # We've processed all of our values to get them into a list of str,
321 # but we may have mojibake data, in which case this is an unparsed
323 if not valid_encoding
:
324 unparsed
[name
] = value
327 raw_name
= _EMAIL_TO_RAW_MAPPING
.get(name
)
329 # This is a bit of a weird situation, we've encountered a key that
330 # we don't know what it means, so we don't know whether it's meant
331 # to be a list or not.
333 # Since we can't really tell one way or another, we'll just leave it
334 # as a list, even though it may be a single item list, because that's
335 # what makes the most sense for email headers.
336 unparsed
[name
] = value
339 # If this is one of our string fields, then we'll check to see if our
340 # value is a list of a single item. If it is then we'll assume that
341 # it was emitted as a single string, and unwrap the str from inside
344 # If it's any other kind of data, then we haven't the faintest clue
345 # what we should parse it as, and we have to just add it to our list
347 if raw_name
in _STRING_FIELDS
and len(value
) == 1:
348 raw
[raw_name
] = value
[0]
349 # If this is one of our list of string fields, then we can just assign
350 # the value, since email *only* has strings, and our get_all() call
351 # above ensures that this is a list.
352 elif raw_name
in _LIST_STRING_FIELDS
:
353 raw
[raw_name
] = value
354 # Special Case: Keywords
355 # The keywords field is implemented in the metadata spec as a str,
356 # but it conceptually is a list of strings, and is serialized using
357 # ", ".join(keywords), so we'll do some light data massaging to turn
358 # this into what it logically is.
359 elif raw_name
== "keywords" and len(value
) == 1:
360 raw
[raw_name
] = _parse_keywords(value
[0])
361 # Special Case: Project-URL
362 # The project urls is implemented in the metadata spec as a list of
363 # specially-formatted strings that represent a key and a value, which
364 # is fundamentally a mapping, however the email format doesn't support
365 # mappings in a sane way, so it was crammed into a list of strings
368 # We will do a little light data massaging to turn this into a map as
369 # it logically should be.
370 elif raw_name
== "project_urls":
372 raw
[raw_name
] = _parse_project_urls(value
)
374 unparsed
[name
] = value
375 # Nothing that we've done has managed to parse this, so it'll just
376 # throw it in our unparseable data and move on.
378 unparsed
[name
] = value
380 # We need to support getting the Description from the message payload in
381 # addition to getting it from the the headers. This does mean, though, there
382 # is the possibility of it being set both ways, in which case we put both
383 # in 'unparsed' since we don't know which is right.
385 payload
= _get_payload(parsed
, data
)
387 unparsed
.setdefault("description", []).append(
388 parsed
.get_payload(decode
=isinstance(data
, bytes))
392 # Check to see if we've already got a description, if so then both
393 # it, and this body move to unparseable.
394 if "description" in raw
:
395 description_header
= cast(str, raw
.pop("description"))
396 unparsed
.setdefault("description", []).extend(
397 [description_header
, payload
]
399 elif "description" in unparsed
:
400 unparsed
["description"].append(payload
)
402 raw
["description"] = payload
404 # We need to cast our `raw` to a metadata, because a TypedDict only support
405 # literal key names, but we're computing our key names on purpose, but the
406 # way this function is implemented, our `TypedDict` can only have valid key
408 return cast(RawMetadata
, raw
), unparsed