Esempio n. 1
0
def main(
    dest: PathLike = "venv",
    verbose: int = 0,
    colour: ColourTrilean = None,
    show_traceback: bool = False,
    upgrade: bool = False,
):
    """
	Create virtual environments using pyproject.toml metadata.
	"""

    # this package
    from pyproject_devenv import mkdevenv
    from pyproject_devenv.config import ConfigTracebackHandler

    with handle_tracebacks(show_traceback, ConfigTracebackHandler):
        ret = mkdevenv(PathPlus.cwd(),
                       dest,
                       verbosity=verbose,
                       upgrade=upgrade)

        if ret:
            sys.exit(ret)  # pragma: no cover
        else:
            click.echo(
                Fore.GREEN("Successfully created development virtualenv."),
                color=resolve_color_default(colour),
            )
Esempio n. 2
0
def main(
    project: "PathLike" = '.',
    outfile: str = "conda/meta.yaml",
    artifact_type: "Literal['sdist', 'wheel']" = "sdist",
    show_traceback: bool = False,
):
    """
	Make a conda recipe for the given project.
	"""

    # 3rd party
    from domdf_python_tools.paths import PathPlus
    from pyproject_parser.cli import ConfigTracebackHandler

    # this package
    from mkrecipe import MaryBerry

    with handle_tracebacks(show_traceback, ConfigTracebackHandler):
        recipe_file = PathPlus(outfile)
        recipe_file.parent.maybe_make(parents=True)

        if artifact_type == "sdist":
            recipe = MaryBerry(project).make()
        elif artifact_type == "wheel":
            recipe = MaryBerry(project).make_for_wheel()
        else:  # pragma: no cover
            # Click should handle this case for us
            raise click.BadOptionUsage(
                "type", f"Unknown value for '--type': {artifact_type}")

        recipe_file.write_clean(recipe)
        click.echo(f"Recipe written to {recipe_file.as_posix()!r}")
Esempio n. 3
0
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,
):
    """
	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
    from toml import TomlEncoder

    pyproject_file = PathPlus(pyproject_file)

    click.echo(f"Reformatting {str(pyproject_file)!r}")

    with handle_tracebacks(show_traceback, CustomTracebackHandler):
        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))
Esempio n. 4
0
def check(
    pyproject_file: "PathLike" = "pyproject.toml",
    parser_class: str = "pyproject_parser:PyProject",
    show_traceback: bool = False,
):
    """
	Validate the given ``pyproject.toml`` file.
	"""

    # 3rd party
    import dom_toml
    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.parsers import BuildSystemParser, PEP621Parser

    pyproject_file = PathPlus(pyproject_file)

    click.echo(f"Validating {str(pyproject_file)!r}")

    with handle_tracebacks(show_traceback, CustomTracebackHandler):
        parser: Type[PyProject] = resolve_class(parser_class, "parser-class")
        parser.load(filename=pyproject_file)

        raw_config = dom_toml.load(pyproject_file)

        _keys = Plural("key", "keys")

        def error_on_unknown(keys: Iterable[str], expected_keys: Iterable[str],
                             table_name: str):
            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")
Esempio n. 5
0
def main(
    filename: Iterable[PathLike],
    config_file: PathLike,
    exclude: "Optional[List[str]]",
    colour: "ColourTrilean" = None,
    verbose: bool = False,
    show_traceback: bool = False,
    show_diff: bool = False,
):
    """
	Reformat the given Python source files.
	"""

    # stdlib
    import fnmatch
    import re

    # 3rd party
    from domdf_python_tools.paths import PathPlus

    # this package
    from formate.config import load_toml
    from formate.utils import SyntaxTracebackHandler, syntaxerror_for_file

    retv = 0

    try:
        config = load_toml(config_file)
    except FileNotFoundError:
        raise click.UsageError(f"Config file '{config_file}' not found")

    for path in filename:
        for pattern in exclude or []:
            if re.match(fnmatch.translate(pattern), str(path)):
                continue

        path = PathPlus(path)

        if path.suffix not in {".py", ".pyi", ''} or path.is_dir():
            if verbose >= 2:
                click.echo(
                    f"Skipping {path} as it doesn't appear to be a Python file"
                )

            continue

        r = Reformatter(path, config=config)

        with handle_tracebacks(show_traceback, cls=SyntaxTracebackHandler):
            with syntaxerror_for_file(path):
                ret_for_file = r.run()

        if ret_for_file:
            if verbose:
                click.echo(f"Reformatting {path}")
            if show_diff:
                click.echo(r.get_diff(), color=resolve_color_default(colour))

            r.to_file()

        elif verbose >= 2:
            click.echo(f"Checking {path}")

        retv |= ret_for_file

    sys.exit(retv)
def test_handle_tracebacks_ignored_exceptions(exception, ):

	with pytest.raises(exception):  # noqa: PT012
		with handle_tracebacks(False, ConfigTracebackHandler):
			raise exception
	def demo():

		with handle_tracebacks(False, ConfigTracebackHandler):
			raise exception
Esempio n. 8
0
    def demo():

        with handle_tracebacks(show_traceback=True):
            raise exception
Esempio n. 9
0
    def demo():

        with handle_tracebacks(True, CustomTracebackHandler):
            raise exception