-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
497 lines (386 loc) · 13.1 KB
/
__init__.py
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#!/usr/bin/env python3
#
# __init__.py
"""
Parser for ``pyproject.toml``.
"""
#
# Copyright © 2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# PyProjectTomlEncoder.dumps based on https://github.com/hukkin/tomli-w
# MIT Licensed
# Copyright (c) 2021 Taneli Hukkinen
#
# 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.
#
# stdlib
from typing import (
Any,
ClassVar,
Dict,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Tuple,
Type,
TypeVar,
Union
)
# 3rd party
import attr
import dom_toml
from dom_toml.decoder import InlineTableDict
from dom_toml.encoder import TomlEncoder
from dom_toml.parser import AbstractConfigParser, BadConfigError
from domdf_python_tools.paths import PathPlus, in_directory
from domdf_python_tools.typing import PathLike
from domdf_python_tools.words import word_join
from packaging.markers import Marker
from packaging.requirements import Requirement
from packaging.specifiers import SpecifierSet
from packaging.version import Version
from shippinglabel import normalize
# this package
from pyproject_parser.classes import License, Readme, _NormalisedName
from pyproject_parser.parsers import BuildSystemParser, PEP621Parser
from pyproject_parser.type_hints import ( # noqa: F401
Author,
BuildSystemDict,
ContentTypes,
ProjectDict,
_PyProjectAsTomlDict
)
from pyproject_parser.utils import _load_toml
__author__: str = "Dominic Davis-Foster"
__copyright__: str = "2021 Dominic Davis-Foster"
__license__: str = "MIT License"
__version__: str = "0.10.0"
__email__: str = "dominic@davis-foster.co.uk"
__all__ = ["PyProject", "PyProjectTomlEncoder", "_PP"]
_PP = TypeVar("_PP", bound="PyProject")
_translation_table = {
8: "\\b",
9: "\\t",
10: "\\n",
12: "\\f",
13: "\\r",
92: "\\\\",
}
def _dump_str(v: str) -> str:
v = str(v).translate(_translation_table)
if "'" in v and '"' not in v:
quote_char = '"'
elif '"' in v and "'" not in v:
quote_char = "'"
else:
quote_char = '"'
v = v.replace('"', '\\"')
return f"{quote_char}{v}{quote_char}"
class PyProjectTomlEncoder(dom_toml.TomlEncoder):
"""
Custom TOML encoder supporting types in :mod:`pyproject_parser.classes` and packaging_.
.. _packaging: https://packaging.pypa.io/en/latest/
.. autosummary-widths:: 23/64
"""
def __init__(self, preserve: bool = False) -> None:
super().__init__(preserve=preserve)
def dumps(
self,
table: Mapping[str, Any],
*,
name: str,
inside_aot: bool = False,
) -> Iterator[str]:
"""
Serialise the given table.
:param name: The table name.
:param inside_aot:
:rtype:
.. versionadded:: 0.11.0
"""
yielded = False
literals = []
tables: List[Tuple[str, Any, bool]] = []
for k, v in table.items():
if v is None:
continue
if self.preserve and isinstance(v, InlineTableDict):
literals.append((k, v))
elif isinstance(v, dict):
tables.append((k, v, False))
elif self._is_aot(v):
tables.extend((k, t, True) for t in v)
else:
literals.append((k, v))
if inside_aot or name and (literals or not tables):
yielded = True
yield f"[[{name}]]\n" if inside_aot else f"[{name}]\n"
if literals:
yielded = True
for k, v in literals:
yield f"{self.format_key_part(k)} = {self.format_literal(v)}\n"
for k, v, in_aot in tables:
if yielded:
yield '\n'
else:
yielded = True
key_part = self.format_key_part(k)
display_name = f"{name}.{key_part}" if name else key_part
yield from self.dumps(v, name=display_name, inside_aot=in_aot)
def format_literal(self, obj: object, *, nest_level: int = 0) -> str:
"""
Format a literal value.
:param obj:
:param nest_level:
:rtype:
.. versionadded:: 0.11.0
"""
if isinstance(obj, (str, _NormalisedName)):
return _dump_str(obj)
elif isinstance(obj, (Version, Requirement, Marker, SpecifierSet)):
return self.dump_packaging_types(obj)
else:
return super().format_literal(obj, nest_level=nest_level)
def format_inline_array(self, obj: Union[Tuple, List], nest_level: int) -> str:
"""
Format an inline array.
:param obj:
:param nest_level:
:rtype:
.. versionadded:: 0.11.0
"""
if not len(obj):
return "[]"
item_indent = " " * (1 + nest_level)
closing_bracket_indent = " " * nest_level
single_line = "[ " + ", ".join(
self.format_literal(item, nest_level=nest_level + 1) for item in obj
) + f",]"
if len(single_line) <= self.max_width:
return single_line
else:
start = "[\n"
body = ",\n".join(item_indent + self.format_literal(item, nest_level=nest_level + 1) for item in obj)
end = f",\n{closing_bracket_indent}]"
return start + body + end
@staticmethod
def dump_packaging_types(obj: Union[Version, Requirement, Marker, SpecifierSet]) -> str:
"""
Convert types in packaging_ to TOML.
.. _packaging: https://packaging.pypa.io/en/latest/
:param obj:
"""
return _dump_str(str(obj))
@attr.s
class PyProject:
"""
Represents a ``pyproject.toml`` file.
:param build_system:
.. autosummary-widths:: 23/64
.. autoclasssumm:: PyProject
:autosummary-sections: Methods
:autosummary-exclude-members: __ge__,__gt__,__le__,__lt__,__ne__,__init__
.. latex:clearpage::
.. autoclasssumm:: PyProject
:autosummary-sections: Attributes
.. latex:vspace:: 10px
"""
#: Represents the :pep:`build-system table <518#build-system-table>` defined in :pep:`517` and :pep:`518`.
build_system: Optional[BuildSystemDict] = attr.ib(default=None)
#: Represents the :pep621:`project table <table-name>` defined in :pep:`621`.
project: Optional[ProjectDict] = attr.ib(default=None)
#: Represents the :pep:`tool table <518#tool-table>` defined in :pep:`518`.
tool: Dict[str, Dict[str, Any]] = attr.ib(factory=dict)
build_system_table_parser: ClassVar[BuildSystemParser] = BuildSystemParser()
"""
The :class:`~dom_toml.parser.AbstractConfigParser`
to parse the :pep:`build-system table <518#build-system-table>` with.
"""
project_table_parser: ClassVar[PEP621Parser] = PEP621Parser()
"""
The :class:`~dom_toml.parser.AbstractConfigParser`
to parse the :pep621:`project table <table-name>` with.
"""
tool_parsers: ClassVar[Mapping[str, AbstractConfigParser]] = {}
"""
A mapping of subtable names to :class:`~dom_toml.parser.AbstractConfigParser` objects
to parse the :pep:`tool table <518#tool-table>` with.
For example, to parse ``[tool.whey]``:
.. code-block:: python
class WheyParser(AbstractConfigParser):
pass
class CustomPyProject(PyProject):
tool_parsers = {"whey": WheyParser()}
"""
@classmethod
def load(
cls: Type[_PP],
filename: PathLike,
set_defaults: bool = False,
) -> _PP:
"""
Load the ``pyproject.toml`` configuration mapping from the given file.
:param filename:
:param set_defaults: If :py:obj:`True`, passes ``set_defaults=True``
the :meth:`parse() <dom_toml.parser.AbstractConfigParser.parse>` method on
:attr:`~.build_system_table_parser` and :attr:`~.project_table_parser`.
"""
filename = PathPlus(filename)
project_dir = filename.parent
config = _load_toml(filename)
keys = set(config.keys())
build_system_table: Optional[BuildSystemDict] = None
project_table: Optional[ProjectDict] = None
tool_table: Dict[str, Dict[str, Any]] = {}
with in_directory(project_dir):
if "build-system" in config:
build_system_table = cls.build_system_table_parser.parse(
config["build-system"], set_defaults=set_defaults
)
keys.remove("build-system")
if "project" in config:
project_table = cls.project_table_parser.parse(config["project"], set_defaults=set_defaults)
keys.remove("project")
if "tool" in config:
tool_table = config["tool"]
keys.remove("tool")
for tool_name, tool_subtable in tool_table.items():
if tool_name in cls.tool_parsers:
tool_table[tool_name] = cls.tool_parsers[tool_name].parse(tool_subtable)
if keys:
allowed_top_level = ("build-system", "project", "tool")
for top_level_key in sorted(keys):
if top_level_key in allowed_top_level:
continue
if normalize(top_level_key) in allowed_top_level:
raise BadConfigError(
f"Unexpected top-level key {top_level_key!r}. "
f"Did you mean {normalize(top_level_key)!r}?",
)
raise BadConfigError(
f"Unexpected top-level key {top_level_key!r}. "
f"Only {word_join(allowed_top_level, use_repr=True)} are allowed.",
)
return cls(
build_system=build_system_table,
project=project_table,
tool=tool_table,
)
def dumps(
self,
encoder: Union[Type[TomlEncoder], TomlEncoder] = PyProjectTomlEncoder,
) -> str:
"""
Serialise to TOML.
:param encoder: The :class:`~dom_toml.encoder.TomlEncoder` to use for constructing the output string.
"""
# TODO: filter out default values (lists and dicts)
toml_dict: _PyProjectAsTomlDict = {
"build-system": self.build_system,
"project": self.project,
"tool": self.tool,
}
if toml_dict["project"] is not None:
if "license" in toml_dict["project"] and toml_dict["project"]["license"] is not None:
toml_dict["project"] = { # type: ignore[typeddict-item]
**toml_dict["project"], # type: ignore[misc,arg-type]
"license": toml_dict["project"]["license"].to_pep621_dict()
}
if "readme" in toml_dict["project"] and toml_dict["project"]["readme"] is not None:
readme_dict = toml_dict["project"]["readme"].to_pep621_dict()
_project: Dict[str, Any]
if set(readme_dict.keys()) == {"file"}:
_project = {**toml_dict["project"], "readme": readme_dict["file"]}
else:
_project = {**toml_dict["project"], "readme": readme_dict}
toml_dict["project"] = _project # type: ignore[typeddict-item]
return dom_toml.dumps(toml_dict, encoder)
def dump(
self,
filename: PathLike,
encoder: Union[Type[TomlEncoder], TomlEncoder] = PyProjectTomlEncoder,
) -> str:
"""
Write as TOML to the given file.
:param filename: The filename to write to.
:param encoder: The :class:`~dom_toml.encoder.TomlEncoder` to use for constructing the output string.
:returns: A string containing the TOML representation.
"""
filename = PathPlus(filename)
as_toml = self.dumps(encoder=encoder)
filename.write_clean(as_toml)
return as_toml
@classmethod
def reformat(
cls: Type[_PP],
filename: PathLike,
encoder: Union[Type[TomlEncoder], TomlEncoder] = PyProjectTomlEncoder,
) -> str:
"""
Reformat the given ``pyproject.toml`` file.
:param filename: The file to reformat.
:param encoder: The :class:`~dom_toml.encoder.TomlEncoder` to use for constructing the output string.
:returns: A string containing the reformatted TOML.
.. versionchanged:: 0.2.0
* Added the ``encoder`` argument.
* The parser configured as :attr:`~.project_table_parser` is now used to parse
the :pep621:`project table <table-name>`, rather than always using :class:`~.PEP621Parser`.
"""
config = cls.load(filename, set_defaults=False)
if config.project is not None and isinstance(config.project["name"], _NormalisedName):
config.project["name"] = config.project["name"].unnormalized
return config.dump(filename, encoder=encoder)
def resolve_files(self) -> None:
"""
Resolve the ``file`` key in :pep621:`readme` and :pep621:`license`
(if present) to retrieve the content of the file.
Calling this method may mean it is no longer possible to recreate
the original ``TOML`` file from this object.
""" # noqa: D400
if self.project is not None:
readme = self.project.get("readme", None)
if readme is not None and isinstance(readme, Readme):
readme.resolve(inplace=True)
lic = self.project.get("license", None)
if lic is not None and isinstance(lic, License):
lic.resolve(inplace=True)
@classmethod
def from_dict(cls: Type[_PP], d: Mapping[str, Any]) -> _PP:
"""
Construct an instance of :class:`~.PyProject` from a dictionary.
:param d: The dictionary.
"""
kwargs = {}
for key, value in d.items():
if key == "build-system":
key = "build_system"
kwargs[key] = value
return cls(**kwargs)
def to_dict(self) -> MutableMapping[str, Any]:
"""
Returns a dictionary containing the contents of the class.
.. seealso:: :func:`attr.asdict`
"""
return {
"build_system": self.build_system,
"project": self.project,
"tool": self.tool,
}