import shlex
import sys
from pathlib import Path
-from subprocess import run, PIPE, STDOUT
+from subprocess import PIPE, STDOUT, run
ACTION_PATH = Path(os.environ["GITHUB_ACTION_PATH"])
ENV_PATH = ACTION_PATH / ".black-env"
import re
import hypothesmith
-from hypothesis import HealthCheck, given, settings, strategies as st
+from hypothesis import HealthCheck, given, settings
+from hypothesis import strategies as st
import black
from blib2to3.pgen2.tokenize import TokenError
# (if you want only bounded fuzzing, just use `pytest fuzz.py`)
try:
import sys
+
import atheris
except ImportError:
pass
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache, partial
from pathlib import Path
-from typing import (
- Generator,
- List,
- NamedTuple,
- Optional,
- Tuple,
- Union,
- cast,
-)
+from typing import Generator, List, NamedTuple, Optional, Tuple, Union, cast
from urllib.request import urlopen, urlretrieve
PYPI_INSTANCE = "https://pypi.org/pypi"
import logging
import os
import sys
-from subprocess import check_output, run, Popen, PIPE
+from subprocess import PIPE, Popen, check_output, run
def git(*args: str) -> str:
# Copyright (C) 2020 Łukasz Langa
-from setuptools import setup, find_packages
-import sys
import os
+import sys
+
+from setuptools import find_packages, setup
assert sys.version_info >= (3, 6, 2), "black requires Python 3.6.2+"
from pathlib import Path # noqa E402
import asyncio
-from json.decoder import JSONDecodeError
-import json
-from contextlib import contextmanager
-from datetime import datetime
-from enum import Enum
import io
-from multiprocessing import Manager, freeze_support
+import json
import os
-from pathlib import Path
-from pathspec.patterns.gitwildmatch import GitWildMatchPatternError
import platform
import re
import signal
import sys
import tokenize
import traceback
+from contextlib import contextmanager
+from dataclasses import replace
+from datetime import datetime
+from enum import Enum
+from json.decoder import JSONDecodeError
+from multiprocessing import Manager, freeze_support
+from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
import click
from click.core import ParameterSource
-from dataclasses import replace
from mypy_extensions import mypyc_attr
+from pathspec.patterns.gitwildmatch import GitWildMatchPatternError
-from black.const import DEFAULT_LINE_LENGTH, DEFAULT_INCLUDES, DEFAULT_EXCLUDES
-from black.const import STDIN_PLACEHOLDER
-from black.nodes import STARS, syms, is_simple_decorator_expression
-from black.nodes import is_string_token, is_number_token
-from black.lines import Line, EmptyLineTracker
-from black.linegen import transform_line, LineGenerator, LN
+from _black_version import version as __version__
+from black.cache import Cache, filter_cached, get_cache_info, read_cache, write_cache
from black.comments import normalize_fmt_off
-from black.mode import FUTURE_FLAG_TO_FEATURE, Mode, TargetVersion
-from black.mode import Feature, supports_feature, VERSION_TO_FEATURES
-from black.cache import read_cache, write_cache, get_cache_info, filter_cached, Cache
-from black.concurrency import cancel, shutdown, maybe_install_uvloop
-from black.output import dump_to_file, ipynb_diff, diff, color_diff, out, err
-from black.report import Report, Changed, NothingChanged
+from black.concurrency import cancel, maybe_install_uvloop, shutdown
+from black.const import (
+ DEFAULT_EXCLUDES,
+ DEFAULT_INCLUDES,
+ DEFAULT_LINE_LENGTH,
+ STDIN_PLACEHOLDER,
+)
from black.files import (
find_project_root,
find_pyproject_toml,
- parse_pyproject_toml,
find_user_pyproject_toml,
+ gen_python_files,
+ get_gitignore,
+ normalize_path_maybe_ignore,
+ parse_pyproject_toml,
+ wrap_stream_for_windows,
)
-from black.files import gen_python_files, get_gitignore, normalize_path_maybe_ignore
-from black.files import wrap_stream_for_windows
-from black.parsing import InvalidInput # noqa F401
-from black.parsing import lib2to3_parse, parse_ast, stringify_ast
from black.handle_ipynb_magics import (
- mask_cell,
- unmask_cell,
- remove_trailing_semicolon,
- put_trailing_semicolon_back,
- TRANSFORMED_MAGICS,
PYTHON_CELL_MAGICS,
+ TRANSFORMED_MAGICS,
jupyter_dependencies_are_installed,
+ mask_cell,
+ put_trailing_semicolon_back,
+ remove_trailing_semicolon,
+ unmask_cell,
)
-
-
-# lib2to3 fork
-from blib2to3.pytree import Node, Leaf
+from black.linegen import LN, LineGenerator, transform_line
+from black.lines import EmptyLineTracker, Line
+from black.mode import (
+ FUTURE_FLAG_TO_FEATURE,
+ VERSION_TO_FEATURES,
+ Feature,
+ Mode,
+ TargetVersion,
+ supports_feature,
+)
+from black.nodes import (
+ STARS,
+ is_number_token,
+ is_simple_decorator_expression,
+ is_string_token,
+ syms,
+)
+from black.output import color_diff, diff, dump_to_file, err, ipynb_diff, out
+from black.parsing import InvalidInput # noqa F401
+from black.parsing import lib2to3_parse, parse_ast, stringify_ast
+from black.report import Changed, NothingChanged, Report
from blib2to3.pgen2 import token
-
-from _black_version import version as __version__
+from blib2to3.pytree import Leaf, Node
if TYPE_CHECKING:
from concurrent.futures import Executor
workers: Optional[int],
) -> None:
"""Reformat multiple files using a ProcessPoolExecutor."""
- from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
+ from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor
executor: Executor
worker_count = workers if workers is not None else DEFAULT_WORKERS
"""Builds on top of nodes.py to track brackets."""
-from dataclasses import dataclass, field
import sys
+from dataclasses import dataclass, field
from typing import Dict, Iterable, List, Optional, Tuple, Union
if sys.version_info < (3, 8):
else:
from typing import Final
-from blib2to3.pytree import Leaf, Node
+from black.nodes import (
+ BRACKET,
+ CLOSING_BRACKETS,
+ COMPARATORS,
+ LOGIC_OPERATORS,
+ MATH_OPERATORS,
+ OPENING_BRACKETS,
+ UNPACKING_PARENTS,
+ VARARGS_PARENTS,
+ is_vararg,
+ syms,
+)
from blib2to3.pgen2 import token
-
-from black.nodes import syms, is_vararg, VARARGS_PARENTS, UNPACKING_PARENTS
-from black.nodes import BRACKET, OPENING_BRACKETS, CLOSING_BRACKETS
-from black.nodes import MATH_OPERATORS, COMPARATORS, LOGIC_OPERATORS
+from blib2to3.pytree import Leaf, Node
# types
LN = Union[Leaf, Node]
import os
import pickle
-from pathlib import Path
import tempfile
+from pathlib import Path
from typing import Dict, Iterable, Set, Tuple
from platformdirs import user_cache_dir
-from black.mode import Mode
-
from _black_version import version as __version__
-
+from black.mode import Mode
# types
Timestamp = float
+import re
import sys
from dataclasses import dataclass
from functools import lru_cache
-import re
from typing import Iterator, List, Optional, Union
if sys.version_info >= (3, 8):
else:
from typing_extensions import Final
-from blib2to3.pytree import Node, Leaf, type_repr
+from black.nodes import (
+ CLOSING_BRACKETS,
+ STANDALONE_COMMENT,
+ WHITESPACE,
+ container_of,
+ first_leaf_column,
+ preceding_leaf,
+)
from blib2to3.pgen2 import token
-
-from black.nodes import first_leaf_column, preceding_leaf, container_of
-from black.nodes import CLOSING_BRACKETS, STANDALONE_COMMENT, WHITESPACE
+from blib2to3.pytree import Leaf, Node, type_repr
# types
LN = Union[Leaf, Node]
from dataclasses import dataclass
from typing import Iterator, TypeVar, Union
-from blib2to3.pytree import Node, Leaf, type_repr
-from blib2to3.pgen2 import token
-
from black.nodes import Visitor
from black.output import out
from black.parsing import lib2to3_parse
+from blib2to3.pgen2 import token
+from blib2to3.pytree import Leaf, Node, type_repr
LN = Union[Leaf, Node]
T = TypeVar("T")
-from functools import lru_cache
import io
import os
-from pathlib import Path
import sys
+from functools import lru_cache
+from pathlib import Path
from typing import (
+ TYPE_CHECKING,
Any,
Dict,
Iterable,
Sequence,
Tuple,
Union,
- TYPE_CHECKING,
)
from mypy_extensions import mypyc_attr
else:
import tomli as tomllib
+from black.handle_ipynb_magics import jupyter_dependencies_are_installed
from black.output import err
from black.report import Report
-from black.handle_ipynb_magics import jupyter_dependencies_are_installed
if TYPE_CHECKING:
import colorama # noqa: F401
"""Functions to process IPython magics with."""
-from functools import lru_cache
-import dataclasses
import ast
-from typing import Dict, List, Tuple, Optional
-
+import collections
+import dataclasses
import secrets
import sys
-import collections
+from functools import lru_cache
+from typing import Dict, List, Optional, Tuple
if sys.version_info >= (3, 10):
from typing import TypeGuard
else:
from typing_extensions import TypeGuard
-from black.report import NothingChanged
from black.output import out
-
+from black.report import NothingChanged
TRANSFORMED_MAGICS = frozenset(
(
Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses
``tokenize_rt`` so that round-tripping works fine.
"""
- from tokenize_rt import (
- src_to_tokens,
- tokens_to_src,
- reversed_enumerate,
- )
+ from tokenize_rt import reversed_enumerate, src_to_tokens, tokens_to_src
tokens = src_to_tokens(src)
trailing_semicolon = False
"""
if not has_trailing_semicolon:
return src
- from tokenize_rt import src_to_tokens, tokens_to_src, reversed_enumerate
+ from tokenize_rt import reversed_enumerate, src_to_tokens, tokens_to_src
tokens = src_to_tokens(src)
for idx, token in reversed_enumerate(tokens):
"""
Generating lines of code.
"""
-from functools import partial, wraps
import sys
+from functools import partial, wraps
from typing import Collection, Iterator, List, Optional, Set, Union, cast
-from black.nodes import WHITESPACE, RARROW, STATEMENT, STANDALONE_COMMENT
-from black.nodes import ASSIGNMENTS, OPENING_BRACKETS, CLOSING_BRACKETS
-from black.nodes import Visitor, syms, is_arith_like, ensure_visible
+from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, max_delimiter_priority_in_atom
+from black.comments import FMT_OFF, generate_comments, list_comments
+from black.lines import (
+ Line,
+ append_leaves,
+ can_be_split,
+ can_omit_invisible_parens,
+ is_line_short_enough,
+ line_to_string,
+)
+from black.mode import Feature, Mode, Preview
from black.nodes import (
+ ASSIGNMENTS,
+ CLOSING_BRACKETS,
+ OPENING_BRACKETS,
+ RARROW,
+ STANDALONE_COMMENT,
+ STATEMENT,
+ WHITESPACE,
+ Visitor,
+ ensure_visible,
+ is_arith_like,
+ is_atom_with_invisible_parens,
is_docstring,
is_empty_tuple,
- is_one_tuple,
+ is_lpar_token,
+ is_multiline_string,
+ is_name_token,
is_one_sequence_between,
+ is_one_tuple,
+ is_rpar_token,
+ is_stub_body,
+ is_stub_suite,
+ is_vararg,
+ is_walrus_assignment,
+ is_yield,
+ syms,
+ wrap_in_parentheses,
)
-from black.nodes import is_name_token, is_lpar_token, is_rpar_token
-from black.nodes import is_walrus_assignment, is_yield, is_vararg, is_multiline_string
-from black.nodes import is_stub_suite, is_stub_body, is_atom_with_invisible_parens
-from black.nodes import wrap_in_parentheses
-from black.brackets import max_delimiter_priority_in_atom
-from black.brackets import DOT_PRIORITY, COMMA_PRIORITY
-from black.lines import Line, line_to_string, is_line_short_enough
-from black.lines import can_omit_invisible_parens, can_be_split, append_leaves
-from black.comments import generate_comments, list_comments, FMT_OFF
from black.numerics import normalize_numeric_literal
-from black.strings import get_string_prefix, fix_docstring
-from black.strings import normalize_string_prefix, normalize_string_quotes
-from black.trans import Transformer, CannotTransform, StringMerger, StringSplitter
-from black.trans import StringParenWrapper, StringParenStripper, hug_power_op
-from black.mode import Mode, Feature, Preview
-
-from blib2to3.pytree import Node, Leaf
+from black.strings import (
+ fix_docstring,
+ get_string_prefix,
+ normalize_string_prefix,
+ normalize_string_quotes,
+)
+from black.trans import (
+ CannotTransform,
+ StringMerger,
+ StringParenStripper,
+ StringParenWrapper,
+ StringSplitter,
+ Transformer,
+ hug_power_op,
+)
from blib2to3.pgen2 import token
-
+from blib2to3.pytree import Leaf, Node
# types
LeafID = int
-from dataclasses import dataclass, field
import itertools
import sys
+from dataclasses import dataclass, field
from typing import (
Callable,
Dict,
cast,
)
-from blib2to3.pytree import Node, Leaf
-from blib2to3.pgen2 import token
-
-from black.brackets import BracketTracker, DOT_PRIORITY
+from black.brackets import DOT_PRIORITY, BracketTracker
from black.mode import Mode, Preview
-from black.nodes import STANDALONE_COMMENT, TEST_DESCENDANTS
-from black.nodes import BRACKETS, OPENING_BRACKETS, CLOSING_BRACKETS
-from black.nodes import syms, whitespace, replace_child, child_towards
-from black.nodes import is_multiline_string, is_import, is_type_comment
-from black.nodes import is_one_sequence_between
+from black.nodes import (
+ BRACKETS,
+ CLOSING_BRACKETS,
+ OPENING_BRACKETS,
+ STANDALONE_COMMENT,
+ TEST_DESCENDANTS,
+ child_towards,
+ is_import,
+ is_multiline_string,
+ is_one_sequence_between,
+ is_type_comment,
+ replace_child,
+ syms,
+ whitespace,
+)
+from blib2to3.pgen2 import token
+from blib2to3.pytree import Leaf, Node
# types
T = TypeVar("T")
chosen by the user.
"""
-from hashlib import sha256
import sys
-
from dataclasses import dataclass, field
from enum import Enum, auto
+from hashlib import sha256
from operator import attrgetter
from typing import Dict, Set
from warnings import warn
"""
import sys
-from typing import (
- Generic,
- Iterator,
- List,
- Optional,
- Set,
- Tuple,
- TypeVar,
- Union,
-)
+from typing import Generic, Iterator, List, Optional, Set, Tuple, TypeVar, Union
if sys.version_info >= (3, 8):
from typing import Final
from mypy_extensions import mypyc_attr
-# lib2to3 fork
-from blib2to3.pytree import Node, Leaf, type_repr, NL
-from blib2to3 import pygram
-from blib2to3.pgen2 import token
-
from black.cache import CACHE_DIR
from black.strings import has_triple_quotes
-
+from blib2to3 import pygram
+from blib2to3.pgen2 import token
+from blib2to3.pytree import NL, Leaf, Node, type_repr
pygram.initialize(CACHE_DIR)
syms: Final = pygram.python_symbols
"""
import json
-from typing import Any, Optional
-from mypy_extensions import mypyc_attr
import tempfile
+from typing import Any, Optional
from click import echo, style
+from mypy_extensions import mypyc_attr
@mypyc_attr(patchable=True)
else:
from typing import Final
-# lib2to3 fork
-from blib2to3.pytree import Node, Leaf
+from black.mode import Feature, TargetVersion, supports_feature
+from black.nodes import syms
from blib2to3 import pygram
from blib2to3.pgen2 import driver
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
from blib2to3.pgen2.tokenize import TokenError
-
-from black.mode import TargetVersion, Feature, supports_feature
-from black.nodes import syms
+from blib2to3.pytree import Leaf, Node
ast3: Any
from click import style
-from black.output import out, err
+from black.output import err, out
class Changed(Enum):
"""
from typing import Generic, TypeVar, Union
-
T = TypeVar("T")
E = TypeVar("E", bound=Exception)
"""
String transformers that can split and merge strings.
"""
+import re
+import sys
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass
-import re
from typing import (
Any,
Callable,
TypeVar,
Union,
)
-import sys
if sys.version_info < (3, 8):
- from typing_extensions import Literal, Final
+ from typing_extensions import Final, Literal
else:
from typing import Literal, Final
from mypy_extensions import trait
-from black.rusty import Result, Ok, Err
-
-from black.mode import Feature
-from black.nodes import syms, replace_child, parent_type
-from black.nodes import is_empty_par, is_empty_lpar, is_empty_rpar
-from black.nodes import OPENING_BRACKETS, CLOSING_BRACKETS, STANDALONE_COMMENT
-from black.lines import Line, append_leaves
from black.brackets import BracketMatchError
from black.comments import contains_pragma_comment
-from black.strings import has_triple_quotes, get_string_prefix, assert_is_leaf_string
-from black.strings import normalize_string_quotes
-
-from blib2to3.pytree import Leaf, Node
+from black.lines import Line, append_leaves
+from black.mode import Feature
+from black.nodes import (
+ CLOSING_BRACKETS,
+ OPENING_BRACKETS,
+ STANDALONE_COMMENT,
+ is_empty_lpar,
+ is_empty_par,
+ is_empty_rpar,
+ parent_type,
+ replace_child,
+ syms,
+)
+from black.rusty import Err, Ok, Result
+from black.strings import (
+ assert_is_leaf_string,
+ get_string_prefix,
+ has_triple_quotes,
+ normalize_string_quotes,
+)
from blib2to3.pgen2 import token
+from blib2to3.pytree import Leaf, Node
class CannotTransform(Exception):
try:
from aiohttp import web
+
from .middlewares import cors
except ImportError as ie:
raise ImportError(
+ "to obtain aiohttp_cors: `pip install black[d]`"
) from None
-import black
-from black.concurrency import maybe_install_uvloop
import click
+import black
from _black_version import version as __version__
+from black.concurrency import maybe_install_uvloop
# This is used internally by tests to shut down the server prematurely
_stop_signal = asyncio.Event()
-from typing import Iterable, Awaitable, Callable
-from aiohttp.web_response import StreamResponse
-from aiohttp.web_request import Request
+from typing import Awaitable, Callable, Iterable
+
from aiohttp.web_middlewares import middleware
+from aiohttp.web_request import Request
+from aiohttp.web_response import StreamResponse
Handler = Callable[[Request], Awaitable[StreamResponse]]
Middleware = Callable[[Request, Handler], Awaitable[StreamResponse]]
Adapted from https://pypi.org/project/pytest-optional-tests/, (c) 2019 Reece Hart
"""
-from functools import lru_cache
import itertools
import logging
import re
-from typing import FrozenSet, List, Set, TYPE_CHECKING
+from functools import lru_cache
+from typing import TYPE_CHECKING, FrozenSet, List, Set
import pytest
if TYPE_CHECKING:
- from _pytest.config.argparsing import Parser
from _pytest.config import Config
+ from _pytest.config.argparsing import Parser
from _pytest.mark.structures import MarkDecorator
from _pytest.nodes import Node
import logging
import multiprocessing
import os
+import re
import sys
import types
import unittest
import click
import pytest
-import re
from click import unstyle
from click.testing import CliRunner
from pathspec import PathSpec
dump_to_stderr,
ff,
fs,
- read_data,
get_case_path,
+ read_data,
read_data_from_file,
)
from typing import Any
from unittest.mock import patch
-from click.testing import CliRunner
import pytest
+from click.testing import CliRunner
-from tests.util import read_data, DETERMINISTIC_HEADER
+from tests.util import DETERMINISTIC_HEADER, read_data
try:
- import blackd
- from aiohttp.test_utils import AioHTTPTestCase
from aiohttp import web
+ from aiohttp.test_utils import AioHTTPTestCase
+
+ import blackd
except ImportError as e:
raise RuntimeError("Please install Black with the 'd' extra") from e
from tests.util import (
DEFAULT_MODE,
PY36_VERSIONS,
+ all_data_cases,
assert_format,
dump_to_stderr,
read_data,
- all_data_cases,
)
import contextlib
-from dataclasses import replace
import pathlib
import re
from contextlib import ExitStack as does_not_raise
+from dataclasses import replace
from typing import ContextManager
+import pytest
+from _pytest.monkeypatch import MonkeyPatch
from click.testing import CliRunner
-from black.handle_ipynb_magics import jupyter_dependencies_are_installed
+
from black import (
- main,
+ Mode,
NothingChanged,
format_cell,
format_file_contents,
format_file_in_place,
+ main,
)
-import pytest
-from black import Mode
-from _pytest.monkeypatch import MonkeyPatch
-from tests.util import DATA_DIR, read_jupyter_notebook, get_case_path
+from black.handle_ipynb_magics import jupyter_dependencies_are_installed
+from tests.util import DATA_DIR, get_case_path, read_jupyter_notebook
with contextlib.suppress(ModuleNotFoundError):
import IPython
-import pytest
import pathlib
-from tests.util import get_case_path
-from black import main, jupyter_dependencies_are_installed
+import pytest
from click.testing import CliRunner
+from black import jupyter_dependencies_are_installed, main
+from tests.util import get_case_path
+
pytestmark = pytest.mark.no_jupyter
runner = CliRunner()
from typing import List, Tuple
+
from black.trans import iter_fexpr_spans