Пример #1
0
def main(bind_host: str, bind_port: int) -> None:
    logging.basicConfig(level=logging.INFO)
    app = make_app()
    ver = black.__version__
    black.out(
        f"blackd version {ver} listening on {bind_host} port {bind_port}")
    web.run_app(app,
                host=bind_host,
                port=bind_port,
                handle_signals=True,
                print=None)
Пример #2
0
 def assertFormatEqual(self, expected: str, actual: str) -> None:
     if actual != expected:
         black.out('Expected tree:', fg='green')
         try:
             exp_node = black.lib2to3_parse(expected)
             bdv = black.DebugVisitor()
             list(bdv.visit(exp_node))
         except Exception as ve:
             black.err(str(ve))
         black.out('Actual tree:', fg='red')
         try:
             exp_node = black.lib2to3_parse(actual)
             bdv = black.DebugVisitor()
             list(bdv.visit(exp_node))
         except Exception as ve:
             black.err(str(ve))
     self.assertEqual(expected, actual)
Пример #3
0
 def assertFormatEqual(self, expected: str, actual: str) -> None:
     if actual != expected and not os.environ.get("SKIP_AST_PRINT"):
         bdv: black.DebugVisitor[Any]
         black.out("Expected tree:", fg="green")
         try:
             exp_node = black.lib2to3_parse(expected)
             bdv = black.DebugVisitor()
             list(bdv.visit(exp_node))
         except Exception as ve:
             black.err(str(ve))
         black.out("Actual tree:", fg="red")
         try:
             exp_node = black.lib2to3_parse(actual)
             bdv = black.DebugVisitor()
             list(bdv.visit(exp_node))
         except Exception as ve:
             black.err(str(ve))
     self.assertEqual(expected, actual)
Пример #4
0
 def assertFormatEqual(self, expected: str, actual: str) -> None:
     if actual != expected and not os.environ.get("SKIP_AST_PRINT"):
         bdv: black.DebugVisitor[Any]
         black.out("Expected tree:", fg="green")
         try:
             exp_node = black.lib2to3_parse(expected)
             bdv = black.DebugVisitor()
             list(bdv.visit(exp_node))
         except Exception as ve:
             black.err(str(ve))
         black.out("Actual tree:", fg="red")
         try:
             exp_node = black.lib2to3_parse(actual)
             bdv = black.DebugVisitor()
             list(bdv.visit(exp_node))
         except Exception as ve:
             black.err(str(ve))
     self.assertEqual(expected, actual)
Пример #5
0
def main(
    ctx: click.Context,
    code: Optional[str],
    line_length: int,
    target_version: List[TargetVersion],
    check: bool,
    diff: bool,
    fast: bool,
    pyi: bool,
    py36: bool,
    skip_string_normalization: bool,
    single_quotes: bool,
    quiet: bool,
    verbose: bool,
    include: str,
    exclude: str,
    src: Tuple[str],
    config: Optional[str],
) -> None:
    """The uncompromising code formatter."""
    write_back = WriteBack.from_configuration(check=check, diff=diff)
    if target_version:
        if py36:
            err('Cannot use both --target-version and --py36')
            ctx.exit(2)
        else:
            versions = set(target_version)
    elif py36:
        err('--py36 is deprecated and will be removed in a future version. '
            'Use --target-version py36 instead.')
        versions = PY36_VERSIONS
    else:
        # We'll autodetect later.
        versions = set()
    mode = FileMode(
        target_versions=versions,
        line_length=line_length,
        is_pyi=pyi,
        string_normalization=not skip_string_normalization,
    )

    if single_quotes:
        black.normalize_string_quotes = patched_normalize_string_quotes

    if config and verbose:
        out(f'Using configuration from {config}.', bold=False, fg='blue')
    if code is not None:
        print(format_str(code, mode=mode))
        ctx.exit(0)
    try:
        include_regex = re_compile_maybe_verbose(include)
    except re.error:
        err(f'Invalid regular expression for include given: {include!r}')
        ctx.exit(2)
    try:
        exclude_regex = re_compile_maybe_verbose(exclude)
    except re.error:
        err(f'Invalid regular expression for exclude given: {exclude!r}')
        ctx.exit(2)
    report = Report(check=check, quiet=quiet, verbose=verbose)
    root = find_project_root(src)
    sources: Set[Path] = set()
    path_empty(src=src, quiet=quiet, verbose=verbose, ctx=ctx, msg=None)
    for s in src:
        p = Path(s)
        if p.is_dir():
            sources.update(
                gen_python_files_in_dir(
                    p,
                    root,
                    include_regex,
                    exclude_regex,
                    report,
                    get_gitignore(root),
                ))
        elif p.is_file() or s == '-':
            # if a file was explicitly given, we don't care about its extension
            sources.add(p)
        else:
            err(f'invalid path: {s}')
    if len(sources) == 0:
        if verbose or not quiet:
            out('No Python files are present to be formatted. Nothing to do 😴')
        ctx.exit(0)

    reformat_many(
        sources=sources,
        fast=fast,
        write_back=write_back,
        mode=mode,
        report=report,
    )

    if verbose or not quiet:
        out('Oh no! 💥 💔 💥' if report.return_code else 'All done! ✨ 🍰 ✨')
        click.secho(str(report), err=True)
    ctx.exit(report.return_code)
Пример #6
0
def cli(
    ctx: click.Context,
    line_length: int,
    check: bool,
    include: str,
    exclude: str,
    quiet: bool,
    verbose: bool,
    clear_output: bool,
    src: Tuple[str],
    config: Optional[str],
) -> None:
    """
    The uncompromising code formatter, for Jupyter notebooks.
    """
    write_back = black.WriteBack.from_configuration(check=check, diff=False)
    mode = black.FileMode.from_configuration(
        py36=True,
        pyi=False,
        skip_string_normalization=False,
        skip_numeric_underscore_normalization=False,
    )

    if config and verbose:
        black.out(f"Using configuration from {config}.", bold=False, fg="blue")

    try:
        include_regex = black.re_compile_maybe_verbose(include)
    except re.error:
        black.err(f"Invalid regular expression for include given: {include!r}")
        ctx.exit(2)
    try:
        exclude_regex = black.re_compile_maybe_verbose(exclude)
    except re.error:
        black.err(f"Invalid regular expression for exclude given: {exclude!r}")
        ctx.exit(2)

    report = black.Report(check=check, quiet=quiet, verbose=verbose)
    root = black.find_project_root(src)
    sources: Set[Path] = set()
    for s in src:
        p = Path(s)
        if p.is_dir():
            sources.update(
                black.gen_python_files_in_dir(
                    p, root, include_regex, exclude_regex, report
                )
            )
        elif p.is_file() or s == "-":
            # if a file was explicitly given, we don't care about its extension
            sources.add(p)
        else:
            black.err(f"invalid path: {s}")
    if len(sources) == 0:
        if verbose or not quiet:
            black.out("No paths given. Nothing to do.")
        ctx.exit(0)

    for source in sources:
        reformat_one(
            src=source,
            line_length=line_length,
            write_back=write_back,
            mode=mode,
            clear_output=clear_output,
            report=report,
            quiet=quiet,
            verbose=verbose,
        )

    if verbose or not quiet:
        black.out(f"All done!")
        click.secho(str(report), err=True)
    ctx.exit(report.return_code)
Пример #7
0
def cli(
    ctx: click.Context,
    line_length: int,
    check: bool,
    include: Pattern[str],
    exclude: Pattern[str],
    extend_exclude: Optional[Pattern[str]],
    force_exclude: Optional[Pattern[str]],
    stdin_filename: Optional[str],
    quiet: bool,
    verbose: bool,
    clear_output: bool,
    src: Tuple[str, ...],
    config: Optional[str],
) -> None:
    """
    The uncompromising code formatter, for Jupyter notebooks.
    """
    write_back = black.WriteBack.from_configuration(check=check, diff=False)
    mode = black.Mode(
        target_versions=TARGET_VERSIONS,
        line_length=line_length,
        is_pyi=False,
        string_normalization=True,
    )

    if config and verbose:
        black.out(f"Using configuration from {config}.", bold=False, fg="blue")

    report = black.Report(check=check, quiet=quiet, verbose=verbose)

    sources = black.get_sources(
        ctx=ctx,
        src=src,
        quiet=quiet,
        verbose=verbose,
        include=include,
        exclude=exclude,
        force_exclude=force_exclude,
        report=report,
        extend_exclude=extend_exclude,
        stdin_filename=stdin_filename,
    )

    black.path_empty(
        sources,
        "No Jupyter notebooks are present to be formatted. Nothing to do 😴",
        quiet,
        verbose,
        ctx,
    )

    for source in sources:
        reformat_one(
            src=source,
            write_back=write_back,
            mode=mode,
            clear_output=clear_output,
            report=report,
            quiet=quiet,
            verbose=verbose,
        )

    if verbose or not quiet:
        black.out("All done! ✨ 🍰 ✨")
        click.secho(str(report), err=True)
    ctx.exit(report.return_code)
Пример #8
0
async def api(
    *,
    src: Iterable[str],
    work_dir: str,
    line_length: int = black.DEFAULT_LINE_LENGTH,
    check: bool = False,
    diff: bool = False,
    fast: bool = False,
    pyi: bool = False,
    py36: bool = False,
    skip_string_normalization: bool = False,
    quiet: bool = False,
    verbose: bool = False,
    include: str = black.DEFAULT_INCLUDES,
    exclude: str = black.DEFAULT_EXCLUDES,
    config: Optional[str] = None,
) -> int:
    """The uncompromising code formatter."""
    src = tuple(src)
    work_dir = Path(work_dir)
    loop = asyncio.get_event_loop()
    write_back = black.WriteBack.from_configuration(check=check, diff=diff)
    mode = black.FileMode.from_configuration(
        py36=py36, pyi=pyi, skip_string_normalization=skip_string_normalization
    )
    if config and verbose:
        black.out(f"Using configuration from {config}.", bold=False, fg="blue")
    try:
        include_regex = black.re_compile_maybe_verbose(include)
    except re.error:
        black.err(f"Invalid regular expression for include given: {include!r}")
        return 2
    try:
        exclude_regex = black.re_compile_maybe_verbose(exclude)
    except re.error:
        black.err(f"Invalid regular expression for exclude given: {exclude!r}")
        return 2
    report = black.Report(check=check, quiet=quiet, verbose=verbose)
    root = black.find_project_root((work_dir,))
    sources: Set[Path] = set()
    for s in src:
        p = work_dir / Path(s)
        if p.is_dir():
            sources.update(
                black.gen_python_files_in_dir(
                    p, root, include_regex, exclude_regex, report
                )
            )
        elif p.is_file() or s == "-":
            # if a file was explicitly given, we don't care about its extension
            sources.add(p)
        else:
            black.err(f"invalid path: {s}")
    if len(sources) == 0:
        if verbose or not quiet:
            black.out("No paths given. Nothing to do 😴")
        return 0

    if len(sources) == 1:
        black.reformat_one(
            src=sources.pop(),
            line_length=line_length,
            fast=fast,
            write_back=write_back,
            mode=mode,
            report=report,
        )
    else:
        await black.schedule_formatting(
            sources=sources,
            line_length=line_length,
            fast=fast,
            write_back=write_back,
            mode=mode,
            report=report,
            executor=PROCESS_POOL,
            loop=loop,
        )
    if verbose or not quiet:
        bang = "💥 💔 💥" if report.return_code else "✨ 🍰 ✨"
        black.out(f"All done! {bang}")
        black.secho(str(report), err=True)
    return report.return_code