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
|
#!/usr/bin/env python3
#
# __main__.py
"""
CLI entry point.
.. versionadded:: 0.2.0
"""
#
# Copyright © 2021-2023 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 sys
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Type, TypeVar
# 3rd party
import click # nodep
from consolekit import click_group # nodep
from consolekit.commands import MarkdownHelpCommand # nodep
from consolekit.options import ( # nodep
DescribedArgument,
auto_default_argument,
auto_default_option,
colour_option,
flag_option
)
from consolekit.tracebacks import handle_tracebacks, traceback_option # nodep
# this package
from pyproject_parser import License
from pyproject_parser.cli import prettify_deprecation_warning
if TYPE_CHECKING:
# 3rd party
from consolekit.terminal_colours import ColourTrilean
from dom_toml.encoder import TomlEncoder
from domdf_python_tools.typing import PathLike
__all__ = ["main", "reformat", "check"]
@click_group()
def main() -> None: # pragma: no cover # noqa: D103
pass
_C = TypeVar("_C", bound=click.Command)
def options(c: _C) -> _C:
pyproject_file_option = auto_default_argument(
"pyproject_file",
type=click.STRING,
description="The ``pyproject.toml`` file.",
cls=DescribedArgument,
)
parser_class_option = auto_default_option(
"-P",
"--parser-class",
type=click.STRING,
help="The class to parse the 'pyproject.toml' file with.",
show_default=True,
)
pyproject_file_option(c)
parser_class_option(c)
traceback_option()(c)
return c
@options
@main.command(cls=MarkdownHelpCommand)
def check(
pyproject_file: "PathLike" = "pyproject.toml",
parser_class: str = "pyproject_parser:PyProject",
show_traceback: bool = False,
) -> None:
"""
Validate the given ``pyproject.toml`` file.
"""
# 3rd party
from dom_toml.parser import BadConfigError
from domdf_python_tools.paths import PathPlus
from domdf_python_tools.words import Plural, word_join
# this package
from pyproject_parser import PyProject
from pyproject_parser.cli import ConfigTracebackHandler, resolve_class
from pyproject_parser.parsers import BuildSystemParser, PEP621Parser
from pyproject_parser.utils import _load_toml
if not show_traceback:
prettify_deprecation_warning()
pyproject_file = PathPlus(pyproject_file)
click.echo(f"Validating {str(pyproject_file)!r}")
with handle_tracebacks(show_traceback, ConfigTracebackHandler):
parser: Type[PyProject] = resolve_class(parser_class, "parser-class")
parser.load(filename=pyproject_file)
raw_config = _load_toml(pyproject_file)
_keys = Plural("key", "keys")
def error_on_unknown(
keys: Iterable[str],
expected_keys: Iterable[str],
table_name: str,
) -> None:
unknown_keys = set(keys) - set(expected_keys)
if unknown_keys:
raise BadConfigError(
f"Unknown {_keys(len(unknown_keys))} in '[{table_name}]': "
f"{word_join(sorted(unknown_keys), use_repr=True)}",
)
# Implements PEPs 517 and 518
error_on_unknown(raw_config.get("build-system", {}).keys(), BuildSystemParser.keys, "build-system")
# Implements PEP 621
error_on_unknown(raw_config.get("project", {}).keys(), {*PEP621Parser.keys, "dynamic"}, "project")
_resolve_help = "Resolve file key in project.readme and project.license (if present) to retrieve the content of the file."
@traceback_option()
@auto_default_option(
"-P",
"--parser-class",
type=click.STRING,
help="The class to parse the 'pyproject.toml' file with.",
show_default=True,
)
@auto_default_option(
"-f",
"--file",
"pyproject_file",
type=click.STRING,
help="The ``pyproject.toml`` file.",
)
@auto_default_option(
"-i",
"--indent",
help="Add indentation to the JSON output.",
type=click.INT,
)
@flag_option(
"-r",
"--resolve",
help=_resolve_help,
show_default=True,
)
@auto_default_argument(
"field",
type=click.STRING,
description="The field to retrieve from the ``pyproject.toml`` file.",
cls=DescribedArgument,
)
@main.command(cls=MarkdownHelpCommand)
def info(
field: Optional[str] = None,
pyproject_file: "PathLike" = "pyproject.toml",
parser_class: str = "pyproject_parser:PyProject",
resolve: bool = False,
show_traceback: bool = False,
indent: Optional[int] = None,
) -> None:
"""
Extract information from the given ``pyproject.toml`` file and print the JSON representation.
"""
# stdlib
import os
import re
# 3rd party
import sdjson # nodep
from domdf_python_tools.paths import PathPlus, in_directory
# this package
from pyproject_parser import PyProject
from pyproject_parser.cli import _json_encoders # noqa: F401
from pyproject_parser.cli import ConfigTracebackHandler, resolve_class
from pyproject_parser.type_hints import Readme
from pyproject_parser.utils import _load_toml
if not show_traceback:
prettify_deprecation_warning()
pyproject_file = PathPlus(pyproject_file)
with handle_tracebacks(show_traceback, ConfigTracebackHandler):
parser: Type[PyProject] = resolve_class(parser_class, "parser-class")
check_readme = os.getenv("CHECK_README")
try:
if field is not None and not field.startswith("project.readme"):
os.environ["CHECK_README"] = '0'
config = parser.load(filename=pyproject_file)
if resolve:
with in_directory(pyproject_file.parent):
config.resolve_files()
raw_config = _load_toml(pyproject_file)
output: Any
if not field:
print(sdjson.dumps(config, indent=indent))
sys.exit(0)
field_parts = field.split('.')
if field_parts[0] == "build-system":
output = config.build_system
elif field_parts[0] == "project":
output = config.project
else:
output = raw_config[field_parts[0]]
for part in field_parts[1:]:
# TODO: slice?
m = re.match(r"^\[(\d)]$", part)
if m:
# array index
output = output[int(m.group(1))]
elif isinstance(output, (Readme, License)):
output = getattr(output, part)
else:
# field name
output = output[part]
print(sdjson.dumps(output, indent=indent))
finally:
if check_readme is None:
if "CHECK_README" in os.environ:
del os.environ["CHECK_README"]
else:
os.environ["CHECK_README"] = check_readme
@options
@colour_option()
@flag_option("-d", "--show-diff", help="Show a (coloured) diff of changes.")
@auto_default_option(
"-E",
"--encoder-class",
type=click.STRING,
help="The class to encode the config to TOML with.",
show_default=True,
)
@main.command(cls=MarkdownHelpCommand)
def reformat(
pyproject_file: "PathLike" = "pyproject.toml",
encoder_class: str = "pyproject_parser:PyProjectTomlEncoder",
parser_class: str = "pyproject_parser:PyProject",
show_traceback: bool = False,
show_diff: bool = False,
colour: "ColourTrilean" = None,
) -> None:
"""
Reformat the given ``pyproject.toml`` file.
"""
# 3rd party
from consolekit.terminal_colours import resolve_color_default # nodep
from consolekit.utils import coloured_diff # nodep
from domdf_python_tools.paths import PathPlus
# this package
from pyproject_parser import PyProject, _NormalisedName
from pyproject_parser.cli import ConfigTracebackHandler, resolve_class
if not show_traceback:
prettify_deprecation_warning()
pyproject_file = PathPlus(pyproject_file)
click.echo(f"Reformatting {str(pyproject_file)!r}")
with handle_tracebacks(show_traceback, ConfigTracebackHandler):
parser: Type[PyProject] = resolve_class(parser_class, "parser-class")
encoder: Type["TomlEncoder"] = resolve_class(encoder_class, "encoder-class")
original_content: List[str] = pyproject_file.read_lines()
config = parser.load(filename=pyproject_file, set_defaults=False)
if config.project is not None and isinstance(config.project["name"], _NormalisedName):
config.project["name"] = config.project["name"].unnormalized
reformatted_content: List[str] = config.dump(filename=pyproject_file, encoder=encoder).split('\n')
changed = reformatted_content != original_content
if show_diff and changed:
diff = coloured_diff(
original_content,
reformatted_content,
str(pyproject_file),
str(pyproject_file),
"(original)",
"(reformatted)",
lineterm='',
)
click.echo(diff, color=resolve_color_default(colour))
sys.exit(int(changed))
if __name__ == "__main__":
sys.exit(main())
|