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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
|
#!/usr/bin/env python3
#
# parsers.py
"""
TOML configuration parsers.
"""
#
# 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.
#
# stdlib
import collections.abc
import functools
import os
import re
import warnings
from abc import ABCMeta
from typing import Any, Callable, ClassVar, Dict, Iterable, List, Mapping, Set, Union, cast
# 3rd party
from apeye_core import URL
from apeye_core.email_validator import EmailSyntaxError, validate_email
from dom_toml.parser import TOML_TYPES, AbstractConfigParser, BadConfigError, construct_path
from natsort import natsorted, ns
from packaging.requirements import InvalidRequirement
from packaging.specifiers import InvalidSpecifier, SpecifierSet
from packaging.version import InvalidVersion, Version
from shippinglabel import normalize
from shippinglabel.classifiers import validate_classifiers
from shippinglabel.requirements import ComparableRequirement, combine_requirements
# this package
from pyproject_parser.classes import License, Readme, _NormalisedName
from pyproject_parser.type_hints import Author, BuildSystemDict, DependencyGroupsDict, ProjectDict
from pyproject_parser.utils import PyProjectDeprecationWarning, content_type_from_filename, render_readme
__all__ = [
"RequiredKeysConfigParser",
"BuildSystemParser",
"DependencyGroupsParser",
"PEP621Parser",
]
name_re = re.compile("^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", flags=re.IGNORECASE)
extra_re = re.compile("^([a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9])$")
def _documentation_url(__documentation_url: str) -> Callable:
def deco(f) -> Callable: # noqa: MAN001
@functools.wraps(f)
def wrapper(*args, **kwds): # noqa: MAN002
try:
return f(*args, **kwds)
except Exception as e:
if getattr(e, "documentation", None) is None:
e.documentation = __documentation_url # type: ignore[attr-defined]
raise
return wrapper
return deco
class RequiredKeysConfigParser(AbstractConfigParser, metaclass=ABCMeta):
"""
Abstract base class for TOML configuration parsers which have required keys.
.. autosummary-widths:: 17/32
"""
required_keys: ClassVar[List[str]]
table_name: ClassVar[str]
def parse(
self,
config: Dict[str, TOML_TYPES],
set_defaults: bool = False,
) -> Dict[str, TOML_TYPES]:
"""
Parse the TOML configuration.
:param config:
:param set_defaults: If :py:obj:`True`, the values in
:attr:`self.defaults <dom_toml.parser.AbstractConfigParser.defaults>` and
:attr:`self.factories <dom_toml.parser.AbstractConfigParser.factories>`
will be set as defaults for the returned mapping.
"""
for key in self.required_keys:
if key in config:
continue
elif set_defaults and (key in self.defaults or key in self.factories):
continue # pragma: no cover https://github.com/nedbat/coveragepy/issues/198
else:
raise BadConfigError(f"The {construct_path([self.table_name, key])!r} field must be provided.")
return super().parse(config, set_defaults)
def assert_sequence_not_str(
self,
obj: Any,
path: Iterable[str],
what: str = "type",
) -> None:
"""
Assert that ``obj`` is a :class:`~typing.Sequence` and not a :class:`str`,
otherwise raise an error with a helpful message.
:param obj: The object to check the type of.
:param path: The elements of the path to ``obj`` in the TOML mapping.
:param what: What ``obj`` is, e.g. ``'type'``, ``'value type'``.
.. latex:clearpage::
""" # noqa: D400
if isinstance(obj, str):
name = construct_path(path)
raise TypeError(
f"Invalid {what} for {name!r}: "
f"expected <class 'collections.abc.Sequence'>, got {type(obj)!r}",
)
self.assert_type(obj, collections.abc.Sequence, path, what=what)
class BuildSystemParser(RequiredKeysConfigParser):
"""
Parser for the :pep:`build-system table <518#build-system-table>` table from ``pyproject.toml``.
.. autosummary-widths:: 17/32
""" # noqa: RST399
table_name: ClassVar[str] = "build-system"
required_keys: ClassVar[List[str]] = ["requires"]
keys: ClassVar[List[str]] = ["requires", "build-backend", "backend-path"]
factories: ClassVar[Dict[str, Callable[..., Any]]] = {"requires": list}
defaults: ClassVar[Dict[str, Any]] = {"build-backend": None, "backend-path": None}
@staticmethod
def normalize_requirement_name(name: str) -> str:
"""
Function to normalize a requirement name per e.g. :pep:`503` (where underscores are replaced by hyphens).
.. versionadded:: 0.9.0
"""
return normalize(name)
@_documentation_url("https://peps.python.org/pep-0518/")
def parse_requires(self, config: Dict[str, TOML_TYPES]) -> List[ComparableRequirement]:
"""
Parse the :pep:`requires <518#build-system-table>` key.
:param config: The unparsed TOML config for the :pep:`build-system table <518#build-system-table>`.
""" # noqa: RST399
parsed_dependencies = set()
key_path = [self.table_name, "requires"]
self.assert_sequence_not_str(config["requires"], key_path)
for idx, raw_requirement in enumerate(config["requires"]):
self.assert_indexed_type(raw_requirement, str, key_path, idx=idx)
try:
requirement = ComparableRequirement(raw_requirement)
except InvalidRequirement as e:
e.args = (f"{raw_requirement!r}\n {str(e)}", )
e.note = "requirements must follow PEP 508" # type: ignore[attr-defined]
e.documentation = "https://peps.python.org/pep-0508/" # type: ignore[attr-defined]
raise
parsed_dependencies.add(requirement)
return sorted(combine_requirements(parsed_dependencies, normalize_func=self.normalize_requirement_name))
@_documentation_url("https://peps.python.org/pep-0517/")
def parse_build_backend(self, config: Dict[str, TOML_TYPES]) -> str:
"""
Parse the ``build_backend`` key defined by :pep:`517`.
:param config: The unparsed TOML config for the :pep:`build-system table <518#build-system-table>`.
""" # noqa: RST399
build_backend = config["build-backend"]
self.assert_type(build_backend, str, [self.table_name, "build-backend"])
return build_backend
@_documentation_url("https://peps.python.org/pep-0517/")
def parse_backend_path(self, config: Dict[str, TOML_TYPES]) -> List[str]:
"""
Parse the ``backend-path`` key defined by :pep:`517`.
:param config: The unparsed TOML config for the :pep:`build-system table <518#build-system-table>`.
""" # noqa: RST399
parsed_backend_paths = []
key_path = [self.table_name, "backend-path"]
self.assert_sequence_not_str(config["backend-path"], key_path)
for idx, path in enumerate(config["backend-path"]):
self.assert_indexed_type(path, str, key_path, idx=idx)
parsed_backend_paths.append(path)
return parsed_backend_paths
def parse( # type: ignore[override]
self,
config: Dict[str, TOML_TYPES],
set_defaults: bool = False,
) -> BuildSystemDict:
"""
Parse the TOML configuration.
:param config:
:param set_defaults: If :py:obj:`True`, the values in
:attr:`self.defaults <dom_toml.parser.AbstractConfigParser.defaults>` and
:attr:`self.factories <dom_toml.parser.AbstractConfigParser.factories>`
will be set as defaults for the returned mapping.
:rtype:
.. latex:clearpage::
"""
parsed_config = super().parse(config, set_defaults)
if (
parsed_config.get("backend-path", None) is not None
and parsed_config.get("build-backend", None) is None
):
raise BadConfigError(
f"{construct_path([self.table_name, 'backend-path'])!r} "
f"cannot be specified without also specifying "
f"{construct_path([self.table_name, 'build-backend'])!r}"
)
return cast(BuildSystemDict, parsed_config)
class DependencyGroupsParser(AbstractConfigParser):
"""
Parser for the :pep:`dependency groups table <735#specification>` table from ``pyproject.toml``.
.. versionadded:: 0.13.0
""" # noqa: RST399
table_name: ClassVar[str] = "dependency-groups"
@property
def keys(self) -> List[str]:
"""
The keys to parse from the TOML file.
"""
return []
@staticmethod
def parse_group(config: TOML_TYPES) -> List[Union[str, Dict[str, str]]]:
"""
Parse a group from the TOML configuration.
:param config:
"""
if isinstance(config, list):
return config
raise BadConfigError("A dependency group must be an array.")
def parse(
self,
config: Dict[str, TOML_TYPES],
set_defaults: bool = False,
) -> DependencyGroupsDict:
"""
Parse the TOML configuration.
:param config:
:param set_defaults: If :py:obj:`True`, the values in
:attr:`self.defaults <dom_toml.parser.AbstractConfigParser.defaults>` and
:attr:`self.factories <dom_toml.parser.AbstractConfigParser.factories>`
will be set as defaults for the returned mapping.
:rtype:
.. latex:clearpage::
"""
parsed_config = {key: self.parse_group(value) for key, value in config.items()}
return cast(DependencyGroupsDict, parsed_config)
class PEP621Parser(RequiredKeysConfigParser):
"""
Parser for :pep:`621` metadata from ``pyproject.toml``.
.. autosummary-widths:: 1/2
"""
table_name: ClassVar[str] = "project"
keys: List[str] = [
"name",
"version",
"description",
"readme",
"requires-python",
"license",
"authors",
"maintainers",
"keywords",
"classifiers",
"urls",
"scripts",
"gui-scripts",
"entry-points",
"dependencies",
"optional-dependencies",
]
required_keys: ClassVar[List[str]] = ["name"]
defaults: ClassVar[Dict[str, Any]] = {
"version": None,
"description": None,
"readme": None,
"requires-python": None,
"license": None,
}
factories: ClassVar[Dict[str, Callable[..., Any]]] = {
"authors": list,
"maintainers": list,
"keywords": list,
"classifiers": list,
"urls": dict,
"scripts": dict,
"gui-scripts": dict,
"entry-points": dict,
"dependencies": list,
"optional-dependencies": dict,
}
@staticmethod
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.name")
def parse_name(config: Dict[str, TOML_TYPES]) -> str:
"""
Parse the :pep621:`name` key, giving the name of the project.
* **Format**: :toml:`String`
* **Core Metadata**: :core-meta:`Name`
This key is required, and must be defined statically.
Tools SHOULD normalize this name, as specified by :pep:`503`,
as soon as it is read for internal consistency.
:bold-title:`Example:`
.. code-block:: TOML
[project]
name = "spam"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
name = config["name"]
normalized_name = _NormalisedName(normalize(name))
normalized_name.unnormalized = name
# https://packaging.python.org/specifications/core-metadata/#name
if not name_re.match(normalized_name):
raise BadConfigError(f"The value {name!r} for 'project.name' is invalid.")
return normalized_name
@staticmethod
def parse_version(config: Dict[str, TOML_TYPES]) -> Version:
"""
Parse the :pep621:`version` key, giving the version of the project as supported by :pep:`440`.
* **Format**: :toml:`String`
* **Core Metadata**: :core-meta:`Version`
Users SHOULD prefer to specify normalized versions.
:bold-title:`Example:`
.. code-block:: TOML
[project]
version = "2020.0.0"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
version = str(config["version"])
try:
return Version(str(version))
except InvalidVersion as e:
e.note = "versions must follow PEP 440" # type: ignore[attr-defined]
e.documentation = "https://peps.python.org/pep-0440/" # type: ignore[attr-defined]
raise
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.description")
def parse_description(self, config: Dict[str, TOML_TYPES]) -> str:
"""
Parse the :pep621:`description` key, giving a summary description of the project.
* **Format**: :toml:`String`
* **Core Metadata**: :core-meta:`Summary`
:bold-title:`Example:`
.. code-block:: TOML
[project]
description = "Lovely Spam! Wonderful Spam!"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
description = config["description"]
self.assert_type(description, str, ["project", "description"])
return description.strip()
@staticmethod
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.readme")
def parse_readme(config: Dict[str, TOML_TYPES]) -> Readme:
"""
Parse the :pep621:`readme` key, giving the full description of the project (i.e. the README).
* **Format**: :toml:`String` or :toml:`table`
* **Core Metadata**: :core-meta:`Description`
This field accepts either a string or a table.
If it is a string then it is the relative path to a text file containing the full description.
The file's encoding MUST be UTF-8, and have one of the following content types:
* ``text/markdown``, with a case-insensitive ``.md`` suffix.
* ``text/x-rst``, with a case-insensitive ``.rst`` suffix.
* ``text/plain``, with a case-insensitive ``.txt`` suffix.
If a tool recognizes more extensions than this PEP, they MAY infer the content-type for the user
without specifying this field as dynamic.
For all unrecognized suffixes when a content-type is not provided, tools MUST raise an error.
.. space::
.. latex:clearpage::
The readme field may instead be a table with the following keys:
* ``file`` -- a string value representing a relative path to a file containing the full description.
* ``text`` -- a string value which is the full description.
* ``content-type`` -- (required) a string specifying the content-type of the full description.
* ``charset`` -- (optional, default UTF-8) the encoding of the ``file``.
Tools MAY support other encodings if they choose to.
The ``file`` and ``text`` keys are mutually exclusive, but one must be provided in the table.
:bold-title:`Examples:`
.. code-block:: TOML
[project]
readme = "README.rst"
[project.readme]
file = "README.rst"
content-type = "text/x-rst"
encoding = "UTF-8"
[project.readme]
text = "Spam is a brand of canned cooked pork made by Hormel Foods Corporation."
content-type = "text/x-rst"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
readme: Union[Dict, str] = config["readme"]
if isinstance(readme, str):
# path to readme_file
readme_content_type = content_type_from_filename(readme)
render_readme(readme, readme_content_type)
return Readme(file=readme, content_type=readme_content_type)
elif isinstance(readme, dict):
if not readme:
raise BadConfigError("The 'project.readme' table cannot be empty.")
if "file" in readme and "text" in readme:
raise BadConfigError(
"The 'project.readme.file' and 'project.readme.text' keys "
"are mutually exclusive."
)
elif set(readme.keys()) in ({"file"}, {"file", "charset"}):
readme_encoding = readme.get("charset", "UTF-8")
render_readme(readme["file"], encoding=readme_encoding)
readme_content_type = content_type_from_filename(readme["file"])
return Readme(file=readme["file"], content_type=readme_content_type, charset=readme_encoding)
elif set(readme.keys()) in ({"file", "content-type"}, {"file", "charset", "content-type"}):
readme_encoding = readme.get("charset", "UTF-8")
render_readme(readme["file"], encoding=readme_encoding)
return Readme(file=readme["file"], content_type=readme["content-type"], charset=readme_encoding)
elif "content-type" in readme and "text" not in readme:
raise BadConfigError(
"The 'project.readme.content-type' key cannot be provided on its own; "
"Please provide the 'project.readme.text' key too."
)
elif "charset" in readme and "text" not in readme:
raise BadConfigError(
"The 'project.readme.charset' key cannot be provided on its own; "
"Please provide the 'project.readme.text' key too."
)
elif "text" in readme:
if "content-type" not in readme:
raise BadConfigError(
"The 'project.readme.content-type' key must be provided "
"when 'project.readme.text' is given."
)
elif readme["content-type"] not in {"text/markdown", "text/x-rst", "text/plain"}:
raise BadConfigError(
f"Unrecognised value for 'project.readme.content-type': {readme['content-type']!r}"
)
if "charset" in readme:
raise BadConfigError(
"The 'project.readme.charset' key cannot be provided "
"when 'project.readme.text' is given."
)
return Readme(text=readme["text"], content_type=readme["content-type"])
else:
raise BadConfigError(f"Unknown format for 'project.readme': {readme!r}")
raise TypeError(f"Unsupported type for 'project.readme': {type(readme)!r}")
@staticmethod
def parse_requires_python(config: Dict[str, TOML_TYPES]) -> SpecifierSet:
"""
Parse the :pep621:`requires-python` key, giving the Python version requirements of the project.
The requirement should be in the form of a :pep:`508` marker.
* **Format**: :toml:`String`
* **Core Metadata**: :core-meta:`Requires-Python`
:bold-title:`Example:`
.. code-block:: TOML
[project]
requires-python = ">=3.6"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
:rtype:
.. latex:clearpage::
"""
version = str(config["requires-python"])
try:
return SpecifierSet(str(version))
except InvalidSpecifier as e:
e.note = "specifiers must follow PEP 508" # type: ignore[attr-defined]
e.documentation = "https://peps.python.org/pep-0508/" # type: ignore[attr-defined]
raise
@staticmethod
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.license")
def parse_license(config: Dict[str, TOML_TYPES]) -> License:
"""
Parse the :pep621:`license` key.
* **Format**: :toml:`Table`
* **Core Metadata**: :core-meta:`License`
The table may have one of two keys:
* ``file`` -- a string value that is a relative file path to the file which contains
the license for the project. The file's encoding MUST be UTF-8.
* ``text`` -- string value which is the license of the project.
These keys are mutually exclusive, so a tool MUST raise an error if the metadata specifies both keys.
:bold-title:`Example:`
.. code-block:: TOML
[project.license]
file = "LICENSE.rst"
[project.license]
file = "COPYING"
[project.license]
text = \"\"\"
This software may only be obtained by sending the author a postcard,
and then the user promises not to redistribute it.
\"\"\"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
""" # noqa: D300,D301
project_license = config["license"]
if "text" in project_license and "file" in project_license:
raise BadConfigError(
"The 'project.license.file' and 'project.license.text' keys "
"are mutually exclusive."
)
elif "text" in project_license:
return License(text=str(project_license["text"]))
elif "file" in project_license:
os.stat(project_license["file"])
return License(project_license["file"])
else:
raise BadConfigError("The 'project.license' table should contain one of 'text' or 'file'.")
@staticmethod
def _parse_authors(config: Dict[str, TOML_TYPES], key_name: str = "authors") -> List[Author]:
all_authors: List[Author] = []
for idx, author in enumerate(config[key_name]):
name = author.get("name", None)
email = author.get("email", None)
if name is not None and ',' in name:
raise BadConfigError(f"The 'project.{key_name}[{idx}].name' key cannot contain commas.")
if email is not None:
try:
email = validate_email(email).email
except EmailSyntaxError as e:
raise BadConfigError(f"Invalid email {email!r}: {e} ")
all_authors.append({"name": name, "email": email})
# TODO: error/warn on extra keys
return all_authors
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.authors")
def parse_authors(self, config: Dict[str, TOML_TYPES]) -> List[Author]:
"""
Parse the :pep621:`authors` key.
* **Format**: :toml:`Array` of :toml:`inline tables <inline table>` with string keys and values
* **Core Metadata**: :core-meta:`Author/Author-email`
The tables list the people or organizations considered to be the "authors" of the project.
Each table has 2 keys: ``name`` and ``email``.
Both values must be strings.
* The ``name`` value MUST be a valid email name (i.e. whatever can be put as a name,
before an email, in :rfc:`822`) and not contain commas.
* The ``email`` value MUST be a valid email address.
Both keys are optional.
Using the data to fill in core metadata is as follows:
1. If only ``name`` is provided, the value goes in :core-meta:`Author`.
2. If only ``email`` is provided, the value goes in :core-meta:`Author-email`.
3. If both ``email`` and ``name`` are provided, the value goes in :core-meta:`Author-email`.
The value should be formatted as ``{name} <{email}>``
(with appropriate quoting, e.g. using :class:`email.headerregistry.Address`).
4. Multiple values should be separated by commas.
:bold-title:`Example:`
.. code-block:: TOML
[project]
authors = [
{email = "hi@pradyunsg.me"},
{name = "Tzu-Ping Chung"}
]
[[project.authors]]
name = "Tzu-Ping Chung"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
return self._parse_authors(config, "authors")
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.maintainers")
def parse_maintainers(self, config: Dict[str, TOML_TYPES]) -> List[Author]:
"""
Parse the :pep621:`maintainers` key.
* **Format**: :toml:`Array` of :toml:`inline tables <inline table>` with string keys and values
* **Core Metadata**: :core-meta:`Maintainer/Maintainer-email`
The tables list the people or organizations considered to be the "maintainers" of the project.
Each table has 2 keys: ``name`` and ``email``.
Both values must be strings.
* The ``name`` value MUST be a valid email name (i.e. whatever can be put as a name,
before an email, in :rfc:`822`) and not contain commas.
* The ``email`` value MUST be a valid email address.
Both keys are optional.
1. If only ``name`` is provided, the value goes in :core-meta:`Maintainer`.
2. If only ``email`` is provided, the value goes in :core-meta:`Maintainer-email`.
3. If both ``email`` and ``name`` are provided, the value goes in :core-meta:`Maintainer-email`,
with the format ``{name} <{email}>``
(with appropriate quoting, e.g. using :class:`email.headerregistry.Address`).
4. Multiple values should be separated by commas.
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
return self._parse_authors(config, "maintainers")
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.keywords")
def parse_keywords(self, config: Dict[str, TOML_TYPES]) -> List[str]:
"""
Parse the :pep621:`keywords` key, giving the keywords for the project.
* **Format**: :toml:`Array` of :toml:`strings <string>`
* **Core Metadata**: :core-meta:`Keywords`
.. latex:vspace:: -5px
:bold-title:`Example:`
.. code-block:: TOML
[project]
keywords = ["egg", "bacon", "sausage", "tomatoes", "Lobster Thermidor"]
.. latex:vspace:: -5px
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
parsed_keywords = set()
key_path = [self.table_name, "keywords"]
self.assert_sequence_not_str(config["keywords"], key_path)
for idx, keyword in enumerate(config["keywords"]):
self.assert_indexed_type(keyword, str, key_path, idx=idx)
parsed_keywords.add(keyword)
return natsorted(parsed_keywords, alg=ns.GROUPLETTERS)
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.classifiers")
def parse_classifiers(self, config: Dict[str, TOML_TYPES]) -> List[str]:
"""
Parse the :pep621:`classifiers` key, giving the `trove classifiers`_ which apply to the project.
.. _trove classifiers: https://pypi.org/classifiers/
* **Format**: :toml:`Array` of :toml:`strings <string>`
* **Core Metadata**: :core-meta:`Classifiers`
:bold-title:`Example:`
.. code-block:: TOML
[project]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python"
]
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
parsed_classifiers = set()
key_path = [self.table_name, "classifiers"]
self.assert_sequence_not_str(config["classifiers"], key_path)
for idx, keyword in enumerate(config["classifiers"]):
self.assert_indexed_type(keyword, str, key_path, idx=idx)
parsed_classifiers.add(keyword)
validate_classifiers(parsed_classifiers)
return natsorted(parsed_classifiers)
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.urls")
def parse_urls(self, config: Dict[str, TOML_TYPES]) -> Dict[str, str]:
"""
Parse the :pep621:`urls` table.
* **Format**: :toml:`Table`, with keys and values of :toml:`strings <string>`
* **Core Metadata**: :core-meta:`Project-URL`
A table of URLs where the key is the URL label and the value is the URL itself.
:bold-title:`Example:`
.. code-block:: TOML
[project.urls]
homepage = "https://example.com"
documentation = "https://readthedocs.org"
repository = "https://github.com"
changelog = "https://github.com/me/spam/blob/master/CHANGELOG.md"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
parsed_urls = {}
project_urls = config["urls"]
self.assert_type(project_urls, dict, ["project", "urls"])
for category, url in project_urls.items():
path = ("project", "urls", category)
self.assert_value_type(url, str, path)
if len(category) > 32:
name = construct_path(path)
raise ValueError(f"{name!r}: label too long (max 32 characters)")
parsed_urls[category] = str(URL(url))
return parsed_urls
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.scripts")
def parse_scripts(self, config: Dict[str, TOML_TYPES]) -> Dict[str, str]:
"""
Parse the :pep621:`scripts` table.
**Format**: :toml:`Table`, with keys and values of :toml:`strings <string>`
The console scripts provided by the project.
The keys are the names of the scripts and the values are the object references
in the form ``module.submodule:object``.
.. latex:vspace:: -5px
:bold-title:`Example:`
.. code-block:: TOML
[project.scripts]
spam-cli = "spam:main_cli"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
scripts = config["scripts"]
self.assert_type(scripts, dict, ["project", "scripts"])
for name, func in scripts.items():
self.assert_value_type(func, str, ["project", "scripts", name])
return scripts
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.gui-scripts")
def parse_gui_scripts(self, config: Dict[str, TOML_TYPES]) -> Dict[str, str]:
"""
Parse the :pep621:`gui-scripts` table.
**Format**: table, with keys and values of strings
The graphical application scripts provided by the project.
The keys are the names of the scripts and the values are the object references
in the form ``module.submodule:object``.
:bold-title:`Example:`
.. code-block:: TOML
[project.gui-scripts]
spam-gui = "spam.gui:main_gui"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
gui_scripts = config["gui-scripts"]
self.assert_type(gui_scripts, dict, ["project", "gui-scripts"])
for name, func in gui_scripts.items():
self.assert_value_type(func, str, ["project", "gui-scripts", name])
return gui_scripts
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.entry-points")
def parse_entry_points(self, config: Dict[str, TOML_TYPES]) -> Dict[str, Dict[str, str]]:
"""
Parse the :pep621:`entry-points` table.
**Format**: :toml:`Table` of :toml:`tables <table>`, with keys and values of :toml:`strings <string>`
Each sub-table's name is an entry point group.
* Users MUST NOT create nested sub-tables but instead keep the entry point groups to only one level deep.
* Users MUST NOT created sub-tables for ``console_scripts`` or ``gui_scripts``.
Use ``[project.scripts]`` and ``[project.gui-scripts]`` instead.
See the `entry point specification`_ for more details.
.. _entry point specification: https://packaging.python.org/specifications/entry-points/
:bold-title:`Example:`
.. code-block:: TOML
[project.entry-points."spam.magical"]
tomatoes = "spam:main_tomatoes"
# pytest plugins refer to a module, so there is no ':obj'
[project.entry-points.pytest11]
nbval = "nbval.plugin"
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
entry_points = config["entry-points"]
self.assert_type(entry_points, dict, ["project", "entry-points"])
for group, sub_table in entry_points.items():
self.assert_value_type(sub_table, dict, ["project", "entry-points", group])
if normalize(group) in "console-scripts":
name = construct_path(["project", "entry-points"])
suggested_name = construct_path(["project", "scripts"])
raise BadConfigError(
f"{name!r} may not contain a {group!r} sub-table. Use {suggested_name!r} instead."
)
elif normalize(group) in "gui-scripts":
name = construct_path(["project", "entry-points"])
suggested_name = construct_path(["project", "gui-scripts"])
raise BadConfigError(
f"{name!r} may not contain a {group!r} sub-table. Use {suggested_name!r} instead."
)
for name, func in sub_table.items():
self.assert_value_type(func, str, ["project", "entry-points", group, name])
return entry_points
@staticmethod
def normalize_requirement_name(name: str) -> str:
"""
Function to normalize a requirement name per e.g. :pep:`503` (where underscores are replaced by hyphens).
.. versionadded:: 0.9.0
"""
return normalize(name)
@_documentation_url("https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.dependencies")
def parse_dependencies(self, config: Dict[str, TOML_TYPES]) -> List[ComparableRequirement]:
"""
Parse the :pep621:`dependencies` key, giving the dependencies of the project.
* **Format**: :toml:`Array` of :pep:`508` strings
* **Core Metadata**: :core-meta:`Requires-Dist`
Each string MUST be formatted as a valid :pep:`508` string.
:bold-title:`Example:`
.. code-block:: TOML
[project]
dependencies = [
"httpx",
"gidgethub[httpx]>4.0.0",
"django>2.1; os_name != 'nt'",
"django>2.0; os_name == 'nt'"
]
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
"""
parsed_dependencies = set()
key_path = [self.table_name, "dependencies"]
self.assert_sequence_not_str(config["dependencies"], key_path)
for idx, raw_requirement in enumerate(config["dependencies"]):
self.assert_indexed_type(raw_requirement, str, key_path, idx=idx)
try:
requirement = ComparableRequirement(raw_requirement)
except InvalidRequirement as e:
e.args = (f"{raw_requirement!r}\n {str(e)}", )
e.note = "requirements must follow PEP 508" # type: ignore[attr-defined]
e.documentation = "https://peps.python.org/pep-0508/" # type: ignore[attr-defined]
raise
parsed_dependencies.add(requirement)
return sorted(combine_requirements(
parsed_dependencies,
normalize_func=self.normalize_requirement_name,
))
@_documentation_url(
"https://whey.readthedocs.io/en/latest/configuration.html#tconf-project.optional-dependencies"
)
def parse_optional_dependencies(
self,
config: Dict[str, TOML_TYPES],
) -> Dict[str, List[ComparableRequirement]]:
"""
Parse the :pep621:`optional-dependencies` table, giving the optional dependencies of the project.
* **Format**: :toml:`Table` with values of :toml:`arrays <Array>` of :pep:`508` strings
* **Core Metadata**: :core-meta:`Requires-Dist` and :core-meta:`Provides-Extra`
.. raw:: html
</br>
* The keys specify an extra, and must be valid Python identifiers.
* The values are arrays of strings, which must be valid :pep:`508` strings.
:bold-title:`Example:`
.. code-block:: TOML
[project.optional-dependencies]
test = [
"pytest < 5.0.0",
"pytest-cov[all]"
]
:param config: The unparsed TOML config for the :pep621:`project table <table-name>`.
:rtype:
.. versionchanged:: 0.5.0
Extra names with hyphens are now considered valid.
If two extra names would normalize to the same string per :pep:`685` a warning is emitted.
In a future version this will become an error.
.. attention::
A future version of `pyproject-parser` will normalize all extra names
and write them to ``METADATA`` in this normalized form.
"""
parsed_optional_dependencies: Dict[str, Set[ComparableRequirement]] = dict()
normalized_names: Set[str] = set() # remove for part 2
optional_dependencies: Mapping[str, Any] = config["optional-dependencies"]
if not isinstance(optional_dependencies, dict):
raise TypeError(
"Invalid type for 'project.optional-dependencies': "
f"expected {dict!r}, got {type(optional_dependencies)!r}",
)
for extra, dependencies in optional_dependencies.items():
# Normalize per PEP 685
normalized_extra = normalize(extra)
path = ("project", "optional-dependencies", extra)
if normalized_extra in normalized_names: # parsed_optional_dependencies for part 2
warnings.warn(
f"{construct_path(path)!r}: "
f"Multiple extras were defined with the same normalized name of {normalized_extra!r}",
PyProjectDeprecationWarning,
)
# For part 2
# raise BadConfigError(
# f"{construct_path(path)!r}: "
# f"Multiple extras were defined with the same normalized name of {normalized_extra!r}",
# )
# https://packaging.python.org/specifications/core-metadata/#provides-extra-multiple-use
# if not extra_re.match(normalized_extra):
if not (extra.isidentifier() or extra_re.match(normalized_extra)):
raise TypeError(f"Invalid extra name {extra!r} ({extra_re.match(normalized_extra)})")
self.assert_sequence_not_str(dependencies, path=path)
parsed_optional_dependencies[extra] = set() # normalized_extra for part 2
normalized_names.add(normalized_extra) # Remove for part 2
for idx, dep in enumerate(dependencies):
if isinstance(dep, str):
try:
requirement = ComparableRequirement(dep)
except InvalidRequirement as e:
e.args = (f"{dep!r}\n {str(e)}", )
e.note = "requirements must follow PEP 508" # type: ignore[attr-defined]
e.documentation = "https://peps.python.org/pep-0508/" # type: ignore[attr-defined]
raise
# normalized_extra for part 2
parsed_optional_dependencies[extra].add(requirement)
else:
raise TypeError(
f"Invalid type for 'project.optional-dependencies.{extra}[{idx}]': "
f"expected {str!r}, got {type(dep)!r}"
)
combined_requirements = {}
for extra, deps in parsed_optional_dependencies.items():
combined_requirements[extra] = sorted(
combine_requirements(deps, normalize_func=self.normalize_requirement_name)
)
return combined_requirements
def parse( # type: ignore[override]
self,
config: Dict[str, TOML_TYPES],
set_defaults: bool = False,
) -> ProjectDict:
"""
Parse the TOML configuration.
:param config:
:param set_defaults: If :py:obj:`True`, the values in
:attr:`self.defaults <dom_toml.parser.AbstractConfigParser.defaults>` and
:attr:`self.factories <dom_toml.parser.AbstractConfigParser.factories>`
will be set as defaults for the returned mapping.
"""
dynamic_fields = config.get("dynamic", [])
if "name" in dynamic_fields:
raise BadConfigError("The 'project.name' field may not be dynamic.")
super_parsed_config = super().parse(config, set_defaults=set_defaults)
return {
**super_parsed_config, # type: ignore[misc]
"dynamic": dynamic_fields,
}
|