1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
|
#!/usr/bin/env python
#
# metadata_mapping.py
"""
:class:`collections.abc.MutableMapping` which supports duplicate, case-insensitive keys.
.. caution::
These are pretty low-level classes. You probably don't need to use these directly
unless you're customising the ``METADATA`` file creation or parsing.
"""
#
# Copyright © 2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# Based on CPython.
# Licensed under the Python Software Foundation License Version 2.
# Copyright © 2001-2021 Python Software Foundation. All rights reserved.
# Copyright © 2000 BeOpen.com. All rights reserved.
# Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
# Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
#
# stdlib
from typing import Iterator, List, MutableMapping, Optional, Tuple, TypeVar, Union, cast, overload
# 3rd party
from domdf_python_tools.stringlist import DelimitedList, StringList
__all__ = ("MetadataMapping", "MetadataEmitter")
_T = TypeVar("_T")
class MetadataMapping(MutableMapping[str, str]):
"""
Provides a :class:`~collections.abc.MutableMapping` interface to a list of fields,
such as those used for Python `core metadata`_.
.. _core metadata: https://packaging.python.org/specifications/core-metadata/
.. seealso:: :class:`email.message.Message` and :class:`email.message.EmailMessage`
Implements the :class:`~collections.abc.MutableMapping` interface,
which assumes there is exactly one occurrence of the field per mapping.
Some fields do in fact appear multiple times,
and for those fields you must use the :meth:`~.MetadataMapping.get_all` method
to obtain all values for that field.
""" # noqa: D400
def __init__(self):
self._fields: List[Tuple[str, str]] = []
#
# MAPPING INTERFACE (partial)
#
def __len__(self) -> int:
"""
Return the total number of keys, including duplicates.
"""
return len(self._fields)
def __getitem__(self, name: str) -> str:
"""
Get a field value.
.. latex:vspace:: -10px
.. note::
If the field appears multiple times, exactly which occurrence gets returned is undefined.
Use the :meth:`~.MetadataMapping.get_all` method to get all values matching a field name.
.. latex:vspace:: -20px
:param name:
"""
if name not in self:
raise KeyError(name)
return cast(str, self.get(name))
def __setitem__(self, name: str, val: str) -> None:
"""
Set the value of a field.
.. attention:
This does not overwrite existing fields with the same field name.
Use :meth:`MetadataMapping.__delitem__` first to delete any existing fields.
:param name:
:param val:
"""
self._fields.append((name, val))
def __delitem__(self, name: str) -> None:
"""
Delete all occurrences of a field, if present.
Does not raise an exception if the field is missing.
:param name:
"""
name = name.lower()
self._fields = [(k, v) for k, v in self._fields if k.lower() != name]
def __contains__(self, name: object) -> bool:
"""
Returns whether ``name`` is in the :class:`~.MetadataMapping`.
:param name:
"""
if not isinstance(name, str):
return False
name = name.lower()
for k, v in self._fields:
if k.lower() == name:
return True
return False
def __iter__(self) -> Iterator[str]:
"""
Returns an iterator over the keys in the :class:`~.MetadataMapping`.
"""
for field, value in self._fields:
yield field
def keys(self) -> List[str]: # type: ignore[override]
"""
Return a list of all field *names*.
These will be sorted by insertion order, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the field list.
"""
return [k for k, v in self._fields]
def values(self) -> List[str]: # type: ignore[override]
"""
Return a list of all field *values*.
These will be sorted by insertion order, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the field list.
"""
return [v for k, v in self._fields]
def items(self) -> List[Tuple[str, str]]: # type: ignore[override]
"""
Get all the fields and their values.
These will be sorted by insertion order, and may contain duplicates.
Any fields deleted and re-inserted are always appended to the field list.
"""
return self._fields[:]
@overload
def get(self, name: str) -> Optional[str]: ...
@overload
def get(self, name: str, default: Union[str, _T]) -> Union[str, _T]: ...
def get(self, name: str, default=None) -> str: # noqa: MAN001
"""
Get a field value.
Like :meth:`~.MetadataMapping.__getitem__`,
but returns ``default`` instead of :py:obj:`None` when the field is missing.
.. note::
If the field appears multiple times, exactly which occurrence gets returned is undefined.
Use the :meth:`~.MetadataMapping.get_all` method to get all values matching a field name.
.. latex:vspace:: -10px
:param name:
:param default:
"""
name = name.lower()
for key, val in self._fields:
if key.lower() == name:
return val
return default
#
# Additional useful stuff
#
@overload
def get_all(self, name: str) -> Optional[List[str]]: ...
@overload
def get_all(self, name: str, default: Union[str, _T]) -> Union[List[str], _T]: ...
def get_all(self, name: str, default=None): # noqa: MAN001,MAN002
"""
Return a list of all the values for the named field.
These will be sorted in the order they appeared in the original message,
and may contain duplicates.
Any fields deleted and re-inserted are always appended to the field list.
If no such fields exist, ``default`` is returned.
:param name:
:param default:
"""
name = name.lower()
values = [val for key, val in self._fields if key.lower() == name]
if not values:
return default
return values
def __repr__(self) -> str:
"""
Return a string representation of the :class:`~.MetadataMapping`.
"""
items = DelimitedList([f"{k!r}: {v!r}" for k, v in self.items()])
as_dict = f"{{{items:, }}}"
return f"<{self.__class__.__name__}({as_dict})>"
def replace(self, name: str, value: str) -> None:
"""
Replace the value of the first matching field, retaining header order and case.
:raises KeyError: If no matching field was found.
"""
for i, (key, val) in enumerate(self._fields):
if key.lower() == name.lower():
self._fields[i] = (name, value)
break
else:
raise KeyError(name)
class MetadataEmitter(StringList):
"""
Used to construct ``METADATA``, ``WHEEL`` and other email field-like files.
:param fields: The fields the file is being constructed from.
.. autosummary-widths:: 1/3
"""
def __init__(self, fields: MetadataMapping):
self.fields = fields
super().__init__()
def add_single(self, field_name: str) -> None:
"""
Add a single value for the field with the given name.
:param field_name:
"""
if field_name in self.fields:
self.append(f"{field_name}: {self.fields[field_name]}")
def add_multiple(self, field_name: str) -> None:
"""
Add all values for the "multiple use" field with the given name.
:param field_name:
"""
if field_name in self.fields:
for value in self.fields.get_all(field_name, ()): # pylint: disable=use-list-copy
self.append(f"{field_name}: {value}")
def add_body(self, body: str) -> None:
"""
Add a body to the file.
In an email message this is the message content itself.
:param body:
"""
self.blankline(ensure_single=True)
self.blankline()
self.append(body)
self.blankline(ensure_single=True)
|