All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
3 from asyncio.base_events import BaseEventLoop
4 from concurrent.futures import Executor, ProcessPoolExecutor
5 from enum import Enum, Flag
6 from functools import partial, wraps
9 from multiprocessing import Manager
11 from pathlib import Path
36 from appdirs import user_cache_dir
37 from attr import dataclass, Factory
41 from blib2to3.pytree import Node, Leaf, type_repr
42 from blib2to3 import pygram, pytree
43 from blib2to3.pgen2 import driver, token
44 from blib2to3.pgen2.parse import ParseError
47 __version__ = "18.5b1"
48 DEFAULT_LINE_LENGTH = 88
50 r"/(\.git|\.hg|\.mypy_cache|\.tox|\.venv|_build|buck-out|build|dist)/"
52 DEFAULT_INCLUDES = r"\.pyi?$"
53 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
64 LN = Union[Leaf, Node]
65 SplitFunc = Callable[["Line", bool], Iterator["Line"]]
68 CacheInfo = Tuple[Timestamp, FileSize]
69 Cache = Dict[Path, CacheInfo]
70 out = partial(click.secho, bold=True, err=True)
71 err = partial(click.secho, fg="red", err=True)
73 pygram.initialize(CACHE_DIR)
74 syms = pygram.python_symbols
77 class NothingChanged(UserWarning):
78 """Raised by :func:`format_file` when reformatted code is the same as source."""
81 class CannotSplit(Exception):
82 """A readable split that fits the allotted line length is impossible.
84 Raised by :func:`left_hand_split`, :func:`right_hand_split`, and
85 :func:`delimiter_split`.
89 class FormatError(Exception):
90 """Base exception for `# fmt: on` and `# fmt: off` handling.
92 It holds the number of bytes of the prefix consumed before the format
93 control comment appeared.
96 def __init__(self, consumed: int) -> None:
97 super().__init__(consumed)
98 self.consumed = consumed
100 def trim_prefix(self, leaf: Leaf) -> None:
101 leaf.prefix = leaf.prefix[self.consumed :]
103 def leaf_from_consumed(self, leaf: Leaf) -> Leaf:
104 """Returns a new Leaf from the consumed part of the prefix."""
105 unformatted_prefix = leaf.prefix[: self.consumed]
106 return Leaf(token.NEWLINE, unformatted_prefix)
109 class FormatOn(FormatError):
110 """Found a comment like `# fmt: on` in the file."""
113 class FormatOff(FormatError):
114 """Found a comment like `# fmt: off` in the file."""
117 class WriteBack(Enum):
129 class FileMode(Flag):
133 NO_STRING_NORMALIZATION = 4
141 default=DEFAULT_LINE_LENGTH,
142 help="How many character per line to allow.",
149 "Allow using Python 3.6-only syntax on all input files. This will put "
150 "trailing commas in function signatures and calls also after *args and "
151 "**kwargs. [default: per-file auto-detection]"
158 "Format all input files like typing stubs regardless of file extension "
159 "(useful when piping source on standard input)."
164 "--skip-string-normalization",
166 help="Don't normalize string quotes or prefixes.",
172 "Don't write the files back, just return the status. Return code 0 "
173 "means nothing would change. Return code 1 means some files would be "
174 "reformatted. Return code 123 means there was an internal error."
180 help="Don't write the files back, just output a diff for each file on stdout.",
185 help="If --fast given, skip temporary sanity checks. [default: --safe]",
190 default=DEFAULT_INCLUDES,
192 "A regular expression that matches files and directories that should be "
193 "included on recursive searches. An empty value means all files are "
194 "included regardless of the name. Use forward slashes for directories on "
195 "all platforms (Windows, too). Exclusions are calculated first, inclusions "
203 default=DEFAULT_EXCLUDES,
205 "A regular expression that matches files and directories that should be "
206 "excluded on recursive searches. An empty value means no paths are excluded. "
207 "Use forward slashes for directories on all platforms (Windows, too). "
208 "Exclusions are calculated first, inclusions later."
217 "Don't emit non-error messages to stderr. Errors are still emitted, "
218 "silence those with 2>/dev/null."
221 @click.version_option(version=__version__)
226 exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
238 skip_string_normalization: bool,
244 """The uncompromising code formatter."""
245 sources: List[Path] = []
247 include_regex = re.compile(include)
249 err(f"Invalid regular expression for include given: {include!r}")
252 exclude_regex = re.compile(exclude)
254 err(f"Invalid regular expression for exclude given: {exclude!r}")
256 root = find_project_root(src)
261 gen_python_files_in_dir(p, root, include_regex, exclude_regex)
263 elif p.is_file() or s == "-":
264 # if a file was explicitly given, we don't care about its extension
267 err(f"invalid path: {s}")
269 if check and not diff:
270 write_back = WriteBack.NO
272 write_back = WriteBack.DIFF
274 write_back = WriteBack.YES
275 mode = FileMode.AUTO_DETECT
277 mode |= FileMode.PYTHON36
280 if skip_string_normalization:
281 mode |= FileMode.NO_STRING_NORMALIZATION
282 report = Report(check=check, quiet=quiet)
283 if len(sources) == 0:
284 out("No paths given. Nothing to do 😴")
288 elif len(sources) == 1:
291 line_length=line_length,
293 write_back=write_back,
298 loop = asyncio.get_event_loop()
299 executor = ProcessPoolExecutor(max_workers=os.cpu_count())
301 loop.run_until_complete(
304 line_length=line_length,
306 write_back=write_back,
316 out("All done! ✨ 🍰 ✨")
317 click.echo(str(report))
318 ctx.exit(report.return_code)
325 write_back: WriteBack,
329 """Reformat a single file under `src` without spawning child processes.
331 If `quiet` is True, non-error messages are not output. `line_length`,
332 `write_back`, `fast` and `pyi` options are passed to
333 :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
337 if not src.is_file() and str(src) == "-":
338 if format_stdin_to_stdout(
339 line_length=line_length, fast=fast, write_back=write_back, mode=mode
341 changed = Changed.YES
344 if write_back != WriteBack.DIFF:
345 cache = read_cache(line_length, mode)
346 res_src = src.resolve()
347 if res_src in cache and cache[res_src] == get_cache_info(res_src):
348 changed = Changed.CACHED
349 if changed is not Changed.CACHED and format_file_in_place(
351 line_length=line_length,
353 write_back=write_back,
356 changed = Changed.YES
357 if write_back == WriteBack.YES and changed is not Changed.NO:
358 write_cache(cache, [src], line_length, mode)
359 report.done(src, changed)
360 except Exception as exc:
361 report.failed(src, str(exc))
364 async def schedule_formatting(
368 write_back: WriteBack,
374 """Run formatting of `sources` in parallel using the provided `executor`.
376 (Use ProcessPoolExecutors for actual parallelism.)
378 `line_length`, `write_back`, `fast`, and `pyi` options are passed to
379 :func:`format_file_in_place`.
382 if write_back != WriteBack.DIFF:
383 cache = read_cache(line_length, mode)
384 sources, cached = filter_cached(cache, sources)
386 report.done(src, Changed.CACHED)
391 if write_back == WriteBack.DIFF:
392 # For diff output, we need locks to ensure we don't interleave output
393 # from different processes.
395 lock = manager.Lock()
397 loop.run_in_executor(
399 format_file_in_place,
407 for src in sorted(sources)
409 pending: Iterable[asyncio.Task] = tasks.keys()
411 loop.add_signal_handler(signal.SIGINT, cancel, pending)
412 loop.add_signal_handler(signal.SIGTERM, cancel, pending)
413 except NotImplementedError:
414 # There are no good alternatives for these on Windows
417 done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
419 src = tasks.pop(task)
421 cancelled.append(task)
422 elif task.exception():
423 report.failed(src, str(task.exception()))
425 formatted.append(src)
426 report.done(src, Changed.YES if task.result() else Changed.NO)
428 await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
429 if write_back == WriteBack.YES and formatted:
430 write_cache(cache, formatted, line_length, mode)
433 def format_file_in_place(
437 write_back: WriteBack = WriteBack.NO,
438 mode: FileMode = FileMode.AUTO_DETECT,
439 lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
441 """Format file under `src` path. Return True if changed.
443 If `write_back` is True, write reformatted code back to stdout.
444 `line_length` and `fast` options are passed to :func:`format_file_contents`.
446 if src.suffix == ".pyi":
448 with tokenize.open(src) as src_buffer:
449 src_contents = src_buffer.read()
451 dst_contents = format_file_contents(
452 src_contents, line_length=line_length, fast=fast, mode=mode
454 except NothingChanged:
457 if write_back == write_back.YES:
458 with open(src, "w", encoding=src_buffer.encoding) as f:
459 f.write(dst_contents)
460 elif write_back == write_back.DIFF:
461 src_name = f"{src} (original)"
462 dst_name = f"{src} (formatted)"
463 diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
467 sys.stdout.write(diff_contents)
474 def format_stdin_to_stdout(
477 write_back: WriteBack = WriteBack.NO,
478 mode: FileMode = FileMode.AUTO_DETECT,
480 """Format file on stdin. Return True if changed.
482 If `write_back` is True, write reformatted code back to stdout.
483 `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
484 :func:`format_file_contents`.
486 src = sys.stdin.read()
489 dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode)
492 except NothingChanged:
496 if write_back == WriteBack.YES:
497 sys.stdout.write(dst)
498 elif write_back == WriteBack.DIFF:
499 src_name = "<stdin> (original)"
500 dst_name = "<stdin> (formatted)"
501 sys.stdout.write(diff(src, dst, src_name, dst_name))
504 def format_file_contents(
509 mode: FileMode = FileMode.AUTO_DETECT,
511 """Reformat contents a file and return new contents.
513 If `fast` is False, additionally confirm that the reformatted code is
514 valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
515 `line_length` is passed to :func:`format_str`.
517 if src_contents.strip() == "":
520 dst_contents = format_str(src_contents, line_length=line_length, mode=mode)
521 if src_contents == dst_contents:
525 assert_equivalent(src_contents, dst_contents)
526 assert_stable(src_contents, dst_contents, line_length=line_length, mode=mode)
531 src_contents: str, line_length: int, *, mode: FileMode = FileMode.AUTO_DETECT
533 """Reformat a string and return new contents.
535 `line_length` determines how many characters per line are allowed.
537 src_node = lib2to3_parse(src_contents)
539 future_imports = get_future_imports(src_node)
540 is_pyi = bool(mode & FileMode.PYI)
541 py36 = bool(mode & FileMode.PYTHON36) or is_python36(src_node)
542 normalize_strings = not bool(mode & FileMode.NO_STRING_NORMALIZATION)
543 lines = LineGenerator(
544 remove_u_prefix=py36 or "unicode_literals" in future_imports,
546 normalize_strings=normalize_strings,
548 elt = EmptyLineTracker(is_pyi=is_pyi)
551 for current_line in lines.visit(src_node):
552 for _ in range(after):
553 dst_contents += str(empty_line)
554 before, after = elt.maybe_empty_lines(current_line)
555 for _ in range(before):
556 dst_contents += str(empty_line)
557 for line in split_line(current_line, line_length=line_length, py36=py36):
558 dst_contents += str(line)
563 pygram.python_grammar_no_print_statement_no_exec_statement,
564 pygram.python_grammar_no_print_statement,
565 pygram.python_grammar,
569 def lib2to3_parse(src_txt: str) -> Node:
570 """Given a string with source, return the lib2to3 Node."""
571 grammar = pygram.python_grammar_no_print_statement
572 if src_txt[-1] != "\n":
573 nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
575 for grammar in GRAMMARS:
576 drv = driver.Driver(grammar, pytree.convert)
578 result = drv.parse_string(src_txt, True)
581 except ParseError as pe:
582 lineno, column = pe.context[1]
583 lines = src_txt.splitlines()
585 faulty_line = lines[lineno - 1]
587 faulty_line = "<line number missing in source>"
588 exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}")
592 if isinstance(result, Leaf):
593 result = Node(syms.file_input, [result])
597 def lib2to3_unparse(node: Node) -> str:
598 """Given a lib2to3 node, return its string representation."""
606 class Visitor(Generic[T]):
607 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
609 def visit(self, node: LN) -> Iterator[T]:
610 """Main method to visit `node` and its children.
612 It tries to find a `visit_*()` method for the given `node.type`, like
613 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
614 If no dedicated `visit_*()` method is found, chooses `visit_default()`
617 Then yields objects of type `T` from the selected visitor.
620 name = token.tok_name[node.type]
622 name = type_repr(node.type)
623 yield from getattr(self, f"visit_{name}", self.visit_default)(node)
625 def visit_default(self, node: LN) -> Iterator[T]:
626 """Default `visit_*()` implementation. Recurses to children of `node`."""
627 if isinstance(node, Node):
628 for child in node.children:
629 yield from self.visit(child)
633 class DebugVisitor(Visitor[T]):
636 def visit_default(self, node: LN) -> Iterator[T]:
637 indent = " " * (2 * self.tree_depth)
638 if isinstance(node, Node):
639 _type = type_repr(node.type)
640 out(f"{indent}{_type}", fg="yellow")
642 for child in node.children:
643 yield from self.visit(child)
646 out(f"{indent}/{_type}", fg="yellow", bold=False)
648 _type = token.tok_name.get(node.type, str(node.type))
649 out(f"{indent}{_type}", fg="blue", nl=False)
651 # We don't have to handle prefixes for `Node` objects since
652 # that delegates to the first child anyway.
653 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
654 out(f" {node.value!r}", fg="blue", bold=False)
657 def show(cls, code: str) -> None:
658 """Pretty-print the lib2to3 AST of a given string of `code`.
660 Convenience method for debugging.
662 v: DebugVisitor[None] = DebugVisitor()
663 list(v.visit(lib2to3_parse(code)))
666 KEYWORDS = set(keyword.kwlist)
667 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
668 FLOW_CONTROL = {"return", "raise", "break", "continue"}
679 STANDALONE_COMMENT = 153
680 LOGIC_OPERATORS = {"and", "or"}
705 STARS = {token.STAR, token.DOUBLESTAR}
708 syms.argument, # double star in arglist
709 syms.trailer, # single argument to call
711 syms.varargslist, # lambdas
713 UNPACKING_PARENTS = {
714 syms.atom, # single element of a list or set literal
752 COMPREHENSION_PRIORITY = 20
754 TERNARY_PRIORITY = 16
757 COMPARATOR_PRIORITY = 10
768 token.DOUBLESLASH: 4,
778 class BracketTracker:
779 """Keeps track of brackets on a line."""
782 bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
783 delimiters: Dict[LeafID, Priority] = Factory(dict)
784 previous: Optional[Leaf] = None
785 _for_loop_variable: int = 0
786 _lambda_arguments: int = 0
788 def mark(self, leaf: Leaf) -> None:
789 """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
791 All leaves receive an int `bracket_depth` field that stores how deep
792 within brackets a given leaf is. 0 means there are no enclosing brackets
793 that started on this line.
795 If a leaf is itself a closing bracket, it receives an `opening_bracket`
796 field that it forms a pair with. This is a one-directional link to
797 avoid reference cycles.
799 If a leaf is a delimiter (a token on which Black can split the line if
800 needed) and it's on depth 0, its `id()` is stored in the tracker's
803 if leaf.type == token.COMMENT:
806 self.maybe_decrement_after_for_loop_variable(leaf)
807 self.maybe_decrement_after_lambda_arguments(leaf)
808 if leaf.type in CLOSING_BRACKETS:
810 opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
811 leaf.opening_bracket = opening_bracket
812 leaf.bracket_depth = self.depth
814 delim = is_split_before_delimiter(leaf, self.previous)
815 if delim and self.previous is not None:
816 self.delimiters[id(self.previous)] = delim
818 delim = is_split_after_delimiter(leaf, self.previous)
820 self.delimiters[id(leaf)] = delim
821 if leaf.type in OPENING_BRACKETS:
822 self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
825 self.maybe_increment_lambda_arguments(leaf)
826 self.maybe_increment_for_loop_variable(leaf)
828 def any_open_brackets(self) -> bool:
829 """Return True if there is an yet unmatched open bracket on the line."""
830 return bool(self.bracket_match)
832 def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
833 """Return the highest priority of a delimiter found on the line.
835 Values are consistent with what `is_split_*_delimiter()` return.
836 Raises ValueError on no delimiters.
838 return max(v for k, v in self.delimiters.items() if k not in exclude)
840 def delimiter_count_with_priority(self, priority: int = 0) -> int:
841 """Return the number of delimiters with the given `priority`.
843 If no `priority` is passed, defaults to max priority on the line.
845 if not self.delimiters:
848 priority = priority or self.max_delimiter_priority()
849 return sum(1 for p in self.delimiters.values() if p == priority)
851 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
852 """In a for loop, or comprehension, the variables are often unpacks.
854 To avoid splitting on the comma in this situation, increase the depth of
855 tokens between `for` and `in`.
857 if leaf.type == token.NAME and leaf.value == "for":
859 self._for_loop_variable += 1
864 def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
865 """See `maybe_increment_for_loop_variable` above for explanation."""
866 if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
868 self._for_loop_variable -= 1
873 def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
874 """In a lambda expression, there might be more than one argument.
876 To avoid splitting on the comma in this situation, increase the depth of
877 tokens between `lambda` and `:`.
879 if leaf.type == token.NAME and leaf.value == "lambda":
881 self._lambda_arguments += 1
886 def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
887 """See `maybe_increment_lambda_arguments` above for explanation."""
888 if self._lambda_arguments and leaf.type == token.COLON:
890 self._lambda_arguments -= 1
895 def get_open_lsqb(self) -> Optional[Leaf]:
896 """Return the most recent opening square bracket (if any)."""
897 return self.bracket_match.get((self.depth - 1, token.RSQB))
902 """Holds leaves and comments. Can be printed with `str(line)`."""
905 leaves: List[Leaf] = Factory(list)
906 comments: List[Tuple[Index, Leaf]] = Factory(list)
907 bracket_tracker: BracketTracker = Factory(BracketTracker)
908 inside_brackets: bool = False
909 should_explode: bool = False
911 def append(self, leaf: Leaf, preformatted: bool = False) -> None:
912 """Add a new `leaf` to the end of the line.
914 Unless `preformatted` is True, the `leaf` will receive a new consistent
915 whitespace prefix and metadata applied by :class:`BracketTracker`.
916 Trailing commas are maybe removed, unpacked for loop variables are
917 demoted from being delimiters.
919 Inline comments are put aside.
921 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
925 if token.COLON == leaf.type and self.is_class_paren_empty:
927 if self.leaves and not preformatted:
928 # Note: at this point leaf.prefix should be empty except for
929 # imports, for which we only preserve newlines.
930 leaf.prefix += whitespace(
931 leaf, complex_subscript=self.is_complex_subscript(leaf)
933 if self.inside_brackets or not preformatted:
934 self.bracket_tracker.mark(leaf)
935 self.maybe_remove_trailing_comma(leaf)
936 if not self.append_comment(leaf):
937 self.leaves.append(leaf)
939 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
940 """Like :func:`append()` but disallow invalid standalone comment structure.
942 Raises ValueError when any `leaf` is appended after a standalone comment
943 or when a standalone comment is not the first leaf on the line.
945 if self.bracket_tracker.depth == 0:
947 raise ValueError("cannot append to standalone comments")
949 if self.leaves and leaf.type == STANDALONE_COMMENT:
951 "cannot append standalone comments to a populated line"
954 self.append(leaf, preformatted=preformatted)
957 def is_comment(self) -> bool:
958 """Is this line a standalone comment?"""
959 return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
962 def is_decorator(self) -> bool:
963 """Is this line a decorator?"""
964 return bool(self) and self.leaves[0].type == token.AT
967 def is_import(self) -> bool:
968 """Is this an import line?"""
969 return bool(self) and is_import(self.leaves[0])
972 def is_class(self) -> bool:
973 """Is this line a class definition?"""
976 and self.leaves[0].type == token.NAME
977 and self.leaves[0].value == "class"
981 def is_stub_class(self) -> bool:
982 """Is this line a class definition with a body consisting only of "..."?"""
983 return self.is_class and self.leaves[-3:] == [
984 Leaf(token.DOT, ".") for _ in range(3)
988 def is_def(self) -> bool:
989 """Is this a function definition? (Also returns True for async defs.)"""
991 first_leaf = self.leaves[0]
996 second_leaf: Optional[Leaf] = self.leaves[1]
999 return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
1000 first_leaf.type == token.ASYNC
1001 and second_leaf is not None
1002 and second_leaf.type == token.NAME
1003 and second_leaf.value == "def"
1007 def is_class_paren_empty(self) -> bool:
1008 """Is this a class with no base classes but using parentheses?
1010 Those are unnecessary and should be removed.
1014 and len(self.leaves) == 4
1016 and self.leaves[2].type == token.LPAR
1017 and self.leaves[2].value == "("
1018 and self.leaves[3].type == token.RPAR
1019 and self.leaves[3].value == ")"
1023 def is_triple_quoted_string(self) -> bool:
1024 """Is the line a triple quoted string?"""
1027 and self.leaves[0].type == token.STRING
1028 and self.leaves[0].value.startswith(('"""', "'''"))
1031 def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
1032 """If so, needs to be split before emitting."""
1033 for leaf in self.leaves:
1034 if leaf.type == STANDALONE_COMMENT:
1035 if leaf.bracket_depth <= depth_limit:
1040 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1041 """Remove trailing comma if there is one and it's safe."""
1044 and self.leaves[-1].type == token.COMMA
1045 and closing.type in CLOSING_BRACKETS
1049 if closing.type == token.RBRACE:
1050 self.remove_trailing_comma()
1053 if closing.type == token.RSQB:
1054 comma = self.leaves[-1]
1055 if comma.parent and comma.parent.type == syms.listmaker:
1056 self.remove_trailing_comma()
1059 # For parens let's check if it's safe to remove the comma.
1060 # Imports are always safe.
1062 self.remove_trailing_comma()
1065 # Otheriwsse, if the trailing one is the only one, we might mistakenly
1066 # change a tuple into a different type by removing the comma.
1067 depth = closing.bracket_depth + 1
1069 opening = closing.opening_bracket
1070 for _opening_index, leaf in enumerate(self.leaves):
1077 for leaf in self.leaves[_opening_index + 1 :]:
1081 bracket_depth = leaf.bracket_depth
1082 if bracket_depth == depth and leaf.type == token.COMMA:
1084 if leaf.parent and leaf.parent.type == syms.arglist:
1089 self.remove_trailing_comma()
1094 def append_comment(self, comment: Leaf) -> bool:
1095 """Add an inline or standalone comment to the line."""
1097 comment.type == STANDALONE_COMMENT
1098 and self.bracket_tracker.any_open_brackets()
1103 if comment.type != token.COMMENT:
1106 after = len(self.leaves) - 1
1108 comment.type = STANDALONE_COMMENT
1113 self.comments.append((after, comment))
1116 def comments_after(self, leaf: Leaf, _index: int = -1) -> Iterator[Leaf]:
1117 """Generate comments that should appear directly after `leaf`.
1119 Provide a non-negative leaf `_index` to speed up the function.
1122 for _index, _leaf in enumerate(self.leaves):
1129 for index, comment_after in self.comments:
1133 def remove_trailing_comma(self) -> None:
1134 """Remove the trailing comma and moves the comments attached to it."""
1135 comma_index = len(self.leaves) - 1
1136 for i in range(len(self.comments)):
1137 comment_index, comment = self.comments[i]
1138 if comment_index == comma_index:
1139 self.comments[i] = (comma_index - 1, comment)
1142 def is_complex_subscript(self, leaf: Leaf) -> bool:
1143 """Return True iff `leaf` is part of a slice with non-trivial exprs."""
1145 leaf if leaf.type == token.LSQB else self.bracket_tracker.get_open_lsqb()
1147 if open_lsqb is None:
1150 subscript_start = open_lsqb.next_sibling
1152 isinstance(subscript_start, Node)
1153 and subscript_start.type == syms.subscriptlist
1155 subscript_start = child_towards(subscript_start, leaf)
1156 return subscript_start is not None and any(
1157 n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
1160 def __str__(self) -> str:
1161 """Render the line."""
1165 indent = " " * self.depth
1166 leaves = iter(self.leaves)
1167 first = next(leaves)
1168 res = f"{first.prefix}{indent}{first.value}"
1171 for _, comment in self.comments:
1175 def __bool__(self) -> bool:
1176 """Return True if the line has leaves or comments."""
1177 return bool(self.leaves or self.comments)
1180 class UnformattedLines(Line):
1181 """Just like :class:`Line` but stores lines which aren't reformatted."""
1183 def append(self, leaf: Leaf, preformatted: bool = True) -> None:
1184 """Just add a new `leaf` to the end of the lines.
1186 The `preformatted` argument is ignored.
1188 Keeps track of indentation `depth`, which is useful when the user
1189 says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`.
1192 list(generate_comments(leaf))
1193 except FormatOn as f_on:
1194 self.leaves.append(f_on.leaf_from_consumed(leaf))
1197 self.leaves.append(leaf)
1198 if leaf.type == token.INDENT:
1200 elif leaf.type == token.DEDENT:
1203 def __str__(self) -> str:
1204 """Render unformatted lines from leaves which were added with `append()`.
1206 `depth` is not used for indentation in this case.
1212 for leaf in self.leaves:
1216 def append_comment(self, comment: Leaf) -> bool:
1217 """Not implemented in this class. Raises `NotImplementedError`."""
1218 raise NotImplementedError("Unformatted lines don't store comments separately.")
1220 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1221 """Does nothing and returns False."""
1224 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
1225 """Does nothing and returns False."""
1230 class EmptyLineTracker:
1231 """Provides a stateful method that returns the number of potential extra
1232 empty lines needed before and after the currently processed line.
1234 Note: this tracker works on lines that haven't been split yet. It assumes
1235 the prefix of the first leaf consists of optional newlines. Those newlines
1236 are consumed by `maybe_empty_lines()` and included in the computation.
1239 is_pyi: bool = False
1240 previous_line: Optional[Line] = None
1241 previous_after: int = 0
1242 previous_defs: List[int] = Factory(list)
1244 def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1245 """Return the number of extra empty lines before and after the `current_line`.
1247 This is for separating `def`, `async def` and `class` with extra empty
1248 lines (two on module-level).
1250 if isinstance(current_line, UnformattedLines):
1253 before, after = self._maybe_empty_lines(current_line)
1254 before -= self.previous_after
1255 self.previous_after = after
1256 self.previous_line = current_line
1257 return before, after
1259 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1261 if current_line.depth == 0:
1262 max_allowed = 1 if self.is_pyi else 2
1263 if current_line.leaves:
1264 # Consume the first leaf's extra newlines.
1265 first_leaf = current_line.leaves[0]
1266 before = first_leaf.prefix.count("\n")
1267 before = min(before, max_allowed)
1268 first_leaf.prefix = ""
1271 depth = current_line.depth
1272 while self.previous_defs and self.previous_defs[-1] >= depth:
1273 self.previous_defs.pop()
1275 before = 0 if depth else 1
1277 before = 1 if depth else 2
1278 is_decorator = current_line.is_decorator
1279 if is_decorator or current_line.is_def or current_line.is_class:
1280 if not is_decorator:
1281 self.previous_defs.append(depth)
1282 if self.previous_line is None:
1283 # Don't insert empty lines before the first line in the file.
1286 if self.previous_line.is_decorator:
1289 if self.previous_line.depth < current_line.depth and (
1290 self.previous_line.is_class or self.previous_line.is_def
1295 self.previous_line.is_comment
1296 and self.previous_line.depth == current_line.depth
1302 if self.previous_line.depth > current_line.depth:
1304 elif current_line.is_class or self.previous_line.is_class:
1305 if current_line.is_stub_class and self.previous_line.is_stub_class:
1313 if current_line.depth and newlines:
1319 and self.previous_line.is_import
1320 and not current_line.is_import
1321 and depth == self.previous_line.depth
1323 return (before or 1), 0
1327 and self.previous_line.is_class
1328 and current_line.is_triple_quoted_string
1336 class LineGenerator(Visitor[Line]):
1337 """Generates reformatted Line objects. Empty lines are not emitted.
1339 Note: destroys the tree it's visiting by mutating prefixes of its leaves
1340 in ways that will no longer stringify to valid Python code on the tree.
1343 is_pyi: bool = False
1344 normalize_strings: bool = True
1345 current_line: Line = Factory(Line)
1346 remove_u_prefix: bool = False
1348 def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
1351 If the line is empty, only emit if it makes sense.
1352 If the line is too long, split it first and then generate.
1354 If any lines were generated, set up a new current_line.
1356 if not self.current_line:
1357 if self.current_line.__class__ == type:
1358 self.current_line.depth += indent
1360 self.current_line = type(depth=self.current_line.depth + indent)
1361 return # Line is empty, don't emit. Creating a new one unnecessary.
1363 complete_line = self.current_line
1364 self.current_line = type(depth=complete_line.depth + indent)
1367 def visit(self, node: LN) -> Iterator[Line]:
1368 """Main method to visit `node` and its children.
1370 Yields :class:`Line` objects.
1372 if isinstance(self.current_line, UnformattedLines):
1373 # File contained `# fmt: off`
1374 yield from self.visit_unformatted(node)
1377 yield from super().visit(node)
1379 def visit_default(self, node: LN) -> Iterator[Line]:
1380 """Default `visit_*()` implementation. Recurses to children of `node`."""
1381 if isinstance(node, Leaf):
1382 any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
1384 for comment in generate_comments(node):
1385 if any_open_brackets:
1386 # any comment within brackets is subject to splitting
1387 self.current_line.append(comment)
1388 elif comment.type == token.COMMENT:
1389 # regular trailing comment
1390 self.current_line.append(comment)
1391 yield from self.line()
1394 # regular standalone comment
1395 yield from self.line()
1397 self.current_line.append(comment)
1398 yield from self.line()
1400 except FormatOff as f_off:
1401 f_off.trim_prefix(node)
1402 yield from self.line(type=UnformattedLines)
1403 yield from self.visit(node)
1405 except FormatOn as f_on:
1406 # This only happens here if somebody says "fmt: on" multiple
1408 f_on.trim_prefix(node)
1409 yield from self.visit_default(node)
1412 normalize_prefix(node, inside_brackets=any_open_brackets)
1413 if self.normalize_strings and node.type == token.STRING:
1414 normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
1415 normalize_string_quotes(node)
1416 if node.type not in WHITESPACE:
1417 self.current_line.append(node)
1418 yield from super().visit_default(node)
1420 def visit_INDENT(self, node: Node) -> Iterator[Line]:
1421 """Increase indentation level, maybe yield a line."""
1422 # In blib2to3 INDENT never holds comments.
1423 yield from self.line(+1)
1424 yield from self.visit_default(node)
1426 def visit_DEDENT(self, node: Node) -> Iterator[Line]:
1427 """Decrease indentation level, maybe yield a line."""
1428 # The current line might still wait for trailing comments. At DEDENT time
1429 # there won't be any (they would be prefixes on the preceding NEWLINE).
1430 # Emit the line then.
1431 yield from self.line()
1433 # While DEDENT has no value, its prefix may contain standalone comments
1434 # that belong to the current indentation level. Get 'em.
1435 yield from self.visit_default(node)
1437 # Finally, emit the dedent.
1438 yield from self.line(-1)
1441 self, node: Node, keywords: Set[str], parens: Set[str]
1442 ) -> Iterator[Line]:
1443 """Visit a statement.
1445 This implementation is shared for `if`, `while`, `for`, `try`, `except`,
1446 `def`, `with`, `class`, `assert` and assignments.
1448 The relevant Python language `keywords` for a given statement will be
1449 NAME leaves within it. This methods puts those on a separate line.
1451 `parens` holds a set of string leaf values immediately after which
1452 invisible parens should be put.
1454 normalize_invisible_parens(node, parens_after=parens)
1455 for child in node.children:
1456 if child.type == token.NAME and child.value in keywords: # type: ignore
1457 yield from self.line()
1459 yield from self.visit(child)
1461 def visit_suite(self, node: Node) -> Iterator[Line]:
1462 """Visit a suite."""
1463 if self.is_pyi and is_stub_suite(node):
1464 yield from self.visit(node.children[2])
1466 yield from self.visit_default(node)
1468 def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
1469 """Visit a statement without nested statements."""
1470 is_suite_like = node.parent and node.parent.type in STATEMENT
1472 if self.is_pyi and is_stub_body(node):
1473 yield from self.visit_default(node)
1475 yield from self.line(+1)
1476 yield from self.visit_default(node)
1477 yield from self.line(-1)
1480 if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
1481 yield from self.line()
1482 yield from self.visit_default(node)
1484 def visit_async_stmt(self, node: Node) -> Iterator[Line]:
1485 """Visit `async def`, `async for`, `async with`."""
1486 yield from self.line()
1488 children = iter(node.children)
1489 for child in children:
1490 yield from self.visit(child)
1492 if child.type == token.ASYNC:
1495 internal_stmt = next(children)
1496 for child in internal_stmt.children:
1497 yield from self.visit(child)
1499 def visit_decorators(self, node: Node) -> Iterator[Line]:
1500 """Visit decorators."""
1501 for child in node.children:
1502 yield from self.line()
1503 yield from self.visit(child)
1505 def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
1506 """Remove a semicolon and put the other statement on a separate line."""
1507 yield from self.line()
1509 def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
1510 """End of file. Process outstanding comments and end with a newline."""
1511 yield from self.visit_default(leaf)
1512 yield from self.line()
1514 def visit_unformatted(self, node: LN) -> Iterator[Line]:
1515 """Used when file contained a `# fmt: off`."""
1516 if isinstance(node, Node):
1517 for child in node.children:
1518 yield from self.visit(child)
1522 self.current_line.append(node)
1523 except FormatOn as f_on:
1524 f_on.trim_prefix(node)
1525 yield from self.line()
1526 yield from self.visit(node)
1528 if node.type == token.ENDMARKER:
1529 # somebody decided not to put a final `# fmt: on`
1530 yield from self.line()
1532 def __attrs_post_init__(self) -> None:
1533 """You are in a twisty little maze of passages."""
1536 self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
1537 self.visit_if_stmt = partial(
1538 v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
1540 self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
1541 self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
1542 self.visit_try_stmt = partial(
1543 v, keywords={"try", "except", "else", "finally"}, parens=Ø
1545 self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
1546 self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
1547 self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
1548 self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
1549 self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
1550 self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
1551 self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
1552 self.visit_async_funcdef = self.visit_async_stmt
1553 self.visit_decorated = self.visit_decorators
1556 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
1557 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
1558 OPENING_BRACKETS = set(BRACKET.keys())
1559 CLOSING_BRACKETS = set(BRACKET.values())
1560 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
1561 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
1564 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa C901
1565 """Return whitespace prefix if needed for the given `leaf`.
1567 `complex_subscript` signals whether the given leaf is part of a subscription
1568 which has non-trivial arguments, like arithmetic expressions or function calls.
1576 if t in ALWAYS_NO_SPACE:
1579 if t == token.COMMENT:
1582 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
1583 if t == token.COLON and p.type not in {
1590 prev = leaf.prev_sibling
1592 prevp = preceding_leaf(p)
1593 if not prevp or prevp.type in OPENING_BRACKETS:
1596 if t == token.COLON:
1597 if prevp.type == token.COLON:
1600 elif prevp.type != token.COMMA and not complex_subscript:
1605 if prevp.type == token.EQUAL:
1607 if prevp.parent.type in {
1615 elif prevp.parent.type == syms.typedargslist:
1616 # A bit hacky: if the equal sign has whitespace, it means we
1617 # previously found it's a typed argument. So, we're using
1621 elif prevp.type in STARS:
1622 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1625 elif prevp.type == token.COLON:
1626 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
1627 return SPACE if complex_subscript else NO
1631 and prevp.parent.type == syms.factor
1632 and prevp.type in MATH_OPERATORS
1637 prevp.type == token.RIGHTSHIFT
1639 and prevp.parent.type == syms.shift_expr
1640 and prevp.prev_sibling
1641 and prevp.prev_sibling.type == token.NAME
1642 and prevp.prev_sibling.value == "print" # type: ignore
1644 # Python 2 print chevron
1647 elif prev.type in OPENING_BRACKETS:
1650 if p.type in {syms.parameters, syms.arglist}:
1651 # untyped function signatures or calls
1652 if not prev or prev.type != token.COMMA:
1655 elif p.type == syms.varargslist:
1657 if prev and prev.type != token.COMMA:
1660 elif p.type == syms.typedargslist:
1661 # typed function signatures
1665 if t == token.EQUAL:
1666 if prev.type != syms.tname:
1669 elif prev.type == token.EQUAL:
1670 # A bit hacky: if the equal sign has whitespace, it means we
1671 # previously found it's a typed argument. So, we're using that, too.
1674 elif prev.type != token.COMMA:
1677 elif p.type == syms.tname:
1680 prevp = preceding_leaf(p)
1681 if not prevp or prevp.type != token.COMMA:
1684 elif p.type == syms.trailer:
1685 # attributes and calls
1686 if t == token.LPAR or t == token.RPAR:
1691 prevp = preceding_leaf(p)
1692 if not prevp or prevp.type != token.NUMBER:
1695 elif t == token.LSQB:
1698 elif prev.type != token.COMMA:
1701 elif p.type == syms.argument:
1703 if t == token.EQUAL:
1707 prevp = preceding_leaf(p)
1708 if not prevp or prevp.type == token.LPAR:
1711 elif prev.type in {token.EQUAL} | STARS:
1714 elif p.type == syms.decorator:
1718 elif p.type == syms.dotted_name:
1722 prevp = preceding_leaf(p)
1723 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
1726 elif p.type == syms.classdef:
1730 if prev and prev.type == token.LPAR:
1733 elif p.type in {syms.subscript, syms.sliceop}:
1736 assert p.parent is not None, "subscripts are always parented"
1737 if p.parent.type == syms.subscriptlist:
1742 elif not complex_subscript:
1745 elif p.type == syms.atom:
1746 if prev and t == token.DOT:
1747 # dots, but not the first one.
1750 elif p.type == syms.dictsetmaker:
1752 if prev and prev.type == token.DOUBLESTAR:
1755 elif p.type in {syms.factor, syms.star_expr}:
1758 prevp = preceding_leaf(p)
1759 if not prevp or prevp.type in OPENING_BRACKETS:
1762 prevp_parent = prevp.parent
1763 assert prevp_parent is not None
1764 if prevp.type == token.COLON and prevp_parent.type in {
1770 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
1773 elif t == token.NAME or t == token.NUMBER:
1776 elif p.type == syms.import_from:
1778 if prev and prev.type == token.DOT:
1781 elif t == token.NAME:
1785 if prev and prev.type == token.DOT:
1788 elif p.type == syms.sliceop:
1794 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
1795 """Return the first leaf that precedes `node`, if any."""
1797 res = node.prev_sibling
1799 if isinstance(res, Leaf):
1803 return list(res.leaves())[-1]
1812 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
1813 """Return the child of `ancestor` that contains `descendant`."""
1814 node: Optional[LN] = descendant
1815 while node and node.parent != ancestor:
1820 def is_split_after_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1821 """Return the priority of the `leaf` delimiter, given a line break after it.
1823 The delimiter priorities returned here are from those delimiters that would
1824 cause a line break after themselves.
1826 Higher numbers are higher priority.
1828 if leaf.type == token.COMMA:
1829 return COMMA_PRIORITY
1834 def is_split_before_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1835 """Return the priority of the `leaf` delimiter, given a line before after it.
1837 The delimiter priorities returned here are from those delimiters that would
1838 cause a line break before themselves.
1840 Higher numbers are higher priority.
1842 if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1843 # * and ** might also be MATH_OPERATORS but in this case they are not.
1844 # Don't treat them as a delimiter.
1848 leaf.type == token.DOT
1850 and leaf.parent.type not in {syms.import_from, syms.dotted_name}
1851 and (previous is None or previous.type in CLOSING_BRACKETS)
1856 leaf.type in MATH_OPERATORS
1858 and leaf.parent.type not in {syms.factor, syms.star_expr}
1860 return MATH_PRIORITIES[leaf.type]
1862 if leaf.type in COMPARATORS:
1863 return COMPARATOR_PRIORITY
1866 leaf.type == token.STRING
1867 and previous is not None
1868 and previous.type == token.STRING
1870 return STRING_PRIORITY
1872 if leaf.type != token.NAME:
1878 and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
1880 return COMPREHENSION_PRIORITY
1885 and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
1887 return COMPREHENSION_PRIORITY
1889 if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
1890 return TERNARY_PRIORITY
1892 if leaf.value == "is":
1893 return COMPARATOR_PRIORITY
1898 and leaf.parent.type in {syms.comp_op, syms.comparison}
1900 previous is not None
1901 and previous.type == token.NAME
1902 and previous.value == "not"
1905 return COMPARATOR_PRIORITY
1910 and leaf.parent.type == syms.comp_op
1912 previous is not None
1913 and previous.type == token.NAME
1914 and previous.value == "is"
1917 return COMPARATOR_PRIORITY
1919 if leaf.value in LOGIC_OPERATORS and leaf.parent:
1920 return LOGIC_PRIORITY
1925 def generate_comments(leaf: LN) -> Iterator[Leaf]:
1926 """Clean the prefix of the `leaf` and generate comments from it, if any.
1928 Comments in lib2to3 are shoved into the whitespace prefix. This happens
1929 in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
1930 move because it does away with modifying the grammar to include all the
1931 possible places in which comments can be placed.
1933 The sad consequence for us though is that comments don't "belong" anywhere.
1934 This is why this function generates simple parentless Leaf objects for
1935 comments. We simply don't know what the correct parent should be.
1937 No matter though, we can live without this. We really only need to
1938 differentiate between inline and standalone comments. The latter don't
1939 share the line with any code.
1941 Inline comments are emitted as regular token.COMMENT leaves. Standalone
1942 are emitted with a fake STANDALONE_COMMENT token identifier.
1953 for index, line in enumerate(p.split("\n")):
1954 consumed += len(line) + 1 # adding the length of the split '\n'
1955 line = line.lstrip()
1958 if not line.startswith("#"):
1961 if index == 0 and leaf.type != token.ENDMARKER:
1962 comment_type = token.COMMENT # simple trailing comment
1964 comment_type = STANDALONE_COMMENT
1965 comment = make_comment(line)
1966 yield Leaf(comment_type, comment, prefix="\n" * nlines)
1968 if comment in {"# fmt: on", "# yapf: enable"}:
1969 raise FormatOn(consumed)
1971 if comment in {"# fmt: off", "# yapf: disable"}:
1972 if comment_type == STANDALONE_COMMENT:
1973 raise FormatOff(consumed)
1975 prev = preceding_leaf(leaf)
1976 if not prev or prev.type in WHITESPACE: # standalone comment in disguise
1977 raise FormatOff(consumed)
1982 def make_comment(content: str) -> str:
1983 """Return a consistently formatted comment from the given `content` string.
1985 All comments (except for "##", "#!", "#:") should have a single space between
1986 the hash sign and the content.
1988 If `content` didn't start with a hash sign, one is provided.
1990 content = content.rstrip()
1994 if content[0] == "#":
1995 content = content[1:]
1996 if content and content[0] not in " !:#":
1997 content = " " + content
1998 return "#" + content
2002 line: Line, line_length: int, inner: bool = False, py36: bool = False
2003 ) -> Iterator[Line]:
2004 """Split a `line` into potentially many lines.
2006 They should fit in the allotted `line_length` but might not be able to.
2007 `inner` signifies that there were a pair of brackets somewhere around the
2008 current `line`, possibly transitively. This means we can fallback to splitting
2009 by delimiters if the LHS/RHS don't yield any results.
2011 If `py36` is True, splitting may generate syntax that is only compatible
2012 with Python 3.6 and later.
2014 if isinstance(line, UnformattedLines) or line.is_comment:
2018 line_str = str(line).strip("\n")
2019 if not line.should_explode and is_line_short_enough(
2020 line, line_length=line_length, line_str=line_str
2025 split_funcs: List[SplitFunc]
2027 split_funcs = [left_hand_split]
2030 def rhs(line: Line, py36: bool = False) -> Iterator[Line]:
2031 for omit in generate_trailers_to_omit(line, line_length):
2032 lines = list(right_hand_split(line, line_length, py36, omit=omit))
2033 if is_line_short_enough(lines[0], line_length=line_length):
2037 # All splits failed, best effort split with no omits.
2038 # This mostly happens to multiline strings that are by definition
2039 # reported as not fitting a single line.
2040 yield from right_hand_split(line, py36)
2042 if line.inside_brackets:
2043 split_funcs = [delimiter_split, standalone_comment_split, rhs]
2046 for split_func in split_funcs:
2047 # We are accumulating lines in `result` because we might want to abort
2048 # mission and return the original line in the end, or attempt a different
2050 result: List[Line] = []
2052 for l in split_func(line, py36):
2053 if str(l).strip("\n") == line_str:
2054 raise CannotSplit("Split function returned an unchanged result")
2057 split_line(l, line_length=line_length, inner=True, py36=py36)
2059 except CannotSplit as cs:
2070 def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
2071 """Split line into many lines, starting with the first matching bracket pair.
2073 Note: this usually looks weird, only use this for function definitions.
2074 Prefer RHS otherwise. This is why this function is not symmetrical with
2075 :func:`right_hand_split` which also handles optional parentheses.
2077 head = Line(depth=line.depth)
2078 body = Line(depth=line.depth + 1, inside_brackets=True)
2079 tail = Line(depth=line.depth)
2080 tail_leaves: List[Leaf] = []
2081 body_leaves: List[Leaf] = []
2082 head_leaves: List[Leaf] = []
2083 current_leaves = head_leaves
2084 matching_bracket = None
2085 for leaf in line.leaves:
2087 current_leaves is body_leaves
2088 and leaf.type in CLOSING_BRACKETS
2089 and leaf.opening_bracket is matching_bracket
2091 current_leaves = tail_leaves if body_leaves else head_leaves
2092 current_leaves.append(leaf)
2093 if current_leaves is head_leaves:
2094 if leaf.type in OPENING_BRACKETS:
2095 matching_bracket = leaf
2096 current_leaves = body_leaves
2097 # Since body is a new indent level, remove spurious leading whitespace.
2099 normalize_prefix(body_leaves[0], inside_brackets=True)
2100 # Build the new lines.
2101 for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2103 result.append(leaf, preformatted=True)
2104 for comment_after in line.comments_after(leaf):
2105 result.append(comment_after, preformatted=True)
2106 bracket_split_succeeded_or_raise(head, body, tail)
2107 for result in (head, body, tail):
2112 def right_hand_split(
2113 line: Line, line_length: int, py36: bool = False, omit: Collection[LeafID] = ()
2114 ) -> Iterator[Line]:
2115 """Split line into many lines, starting with the last matching bracket pair.
2117 If the split was by optional parentheses, attempt splitting without them, too.
2118 `omit` is a collection of closing bracket IDs that shouldn't be considered for
2121 Note: running this function modifies `bracket_depth` on the leaves of `line`.
2123 head = Line(depth=line.depth)
2124 body = Line(depth=line.depth + 1, inside_brackets=True)
2125 tail = Line(depth=line.depth)
2126 tail_leaves: List[Leaf] = []
2127 body_leaves: List[Leaf] = []
2128 head_leaves: List[Leaf] = []
2129 current_leaves = tail_leaves
2130 opening_bracket = None
2131 closing_bracket = None
2132 for leaf in reversed(line.leaves):
2133 if current_leaves is body_leaves:
2134 if leaf is opening_bracket:
2135 current_leaves = head_leaves if body_leaves else tail_leaves
2136 current_leaves.append(leaf)
2137 if current_leaves is tail_leaves:
2138 if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
2139 opening_bracket = leaf.opening_bracket
2140 closing_bracket = leaf
2141 current_leaves = body_leaves
2142 tail_leaves.reverse()
2143 body_leaves.reverse()
2144 head_leaves.reverse()
2145 # Since body is a new indent level, remove spurious leading whitespace.
2147 normalize_prefix(body_leaves[0], inside_brackets=True)
2149 # No `head` means the split failed. Either `tail` has all content or
2150 # the matching `opening_bracket` wasn't available on `line` anymore.
2151 raise CannotSplit("No brackets found")
2153 # Build the new lines.
2154 for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2156 result.append(leaf, preformatted=True)
2157 for comment_after in line.comments_after(leaf):
2158 result.append(comment_after, preformatted=True)
2159 bracket_split_succeeded_or_raise(head, body, tail)
2160 assert opening_bracket and closing_bracket
2162 # the opening bracket is an optional paren
2163 opening_bracket.type == token.LPAR
2164 and not opening_bracket.value
2165 # the closing bracket is an optional paren
2166 and closing_bracket.type == token.RPAR
2167 and not closing_bracket.value
2168 # there are no standalone comments in the body
2169 and not line.contains_standalone_comments(0)
2170 # and it's not an import (optional parens are the only thing we can split
2171 # on in this case; attempting a split without them is a waste of time)
2172 and not line.is_import
2174 omit = {id(closing_bracket), *omit}
2175 if can_omit_invisible_parens(body, line_length):
2177 yield from right_hand_split(line, line_length, py36=py36, omit=omit)
2182 ensure_visible(opening_bracket)
2183 ensure_visible(closing_bracket)
2184 body.should_explode = should_explode(body, opening_bracket)
2185 for result in (head, body, tail):
2190 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
2191 """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
2193 Do nothing otherwise.
2195 A left- or right-hand split is based on a pair of brackets. Content before
2196 (and including) the opening bracket is left on one line, content inside the
2197 brackets is put on a separate line, and finally content starting with and
2198 following the closing bracket is put on a separate line.
2200 Those are called `head`, `body`, and `tail`, respectively. If the split
2201 produced the same line (all content in `head`) or ended up with an empty `body`
2202 and the `tail` is just the closing bracket, then it's considered failed.
2204 tail_len = len(str(tail).strip())
2207 raise CannotSplit("Splitting brackets produced the same line")
2211 f"Splitting brackets on an empty body to save "
2212 f"{tail_len} characters is not worth it"
2216 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
2217 """Normalize prefix of the first leaf in every line returned by `split_func`.
2219 This is a decorator over relevant split functions.
2223 def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
2224 for l in split_func(line, py36):
2225 normalize_prefix(l.leaves[0], inside_brackets=True)
2228 return split_wrapper
2231 @dont_increase_indentation
2232 def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
2233 """Split according to delimiters of the highest priority.
2235 If `py36` is True, the split will add trailing commas also in function
2236 signatures that contain `*` and `**`.
2239 last_leaf = line.leaves[-1]
2241 raise CannotSplit("Line empty")
2243 bt = line.bracket_tracker
2245 delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
2247 raise CannotSplit("No delimiters found")
2249 if delimiter_priority == DOT_PRIORITY:
2250 if bt.delimiter_count_with_priority(delimiter_priority) == 1:
2251 raise CannotSplit("Splitting a single attribute from its owner looks wrong")
2253 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2254 lowest_depth = sys.maxsize
2255 trailing_comma_safe = True
2257 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2258 """Append `leaf` to current line or to new line if appending impossible."""
2259 nonlocal current_line
2261 current_line.append_safe(leaf, preformatted=True)
2262 except ValueError as ve:
2265 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2266 current_line.append(leaf)
2268 for index, leaf in enumerate(line.leaves):
2269 yield from append_to_line(leaf)
2271 for comment_after in line.comments_after(leaf, index):
2272 yield from append_to_line(comment_after)
2274 lowest_depth = min(lowest_depth, leaf.bracket_depth)
2275 if leaf.bracket_depth == lowest_depth and is_vararg(
2276 leaf, within=VARARGS_PARENTS
2278 trailing_comma_safe = trailing_comma_safe and py36
2279 leaf_priority = bt.delimiters.get(id(leaf))
2280 if leaf_priority == delimiter_priority:
2283 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2287 and delimiter_priority == COMMA_PRIORITY
2288 and current_line.leaves[-1].type != token.COMMA
2289 and current_line.leaves[-1].type != STANDALONE_COMMENT
2291 current_line.append(Leaf(token.COMMA, ","))
2295 @dont_increase_indentation
2296 def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
2297 """Split standalone comments from the rest of the line."""
2298 if not line.contains_standalone_comments(0):
2299 raise CannotSplit("Line does not have any standalone comments")
2301 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2303 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2304 """Append `leaf` to current line or to new line if appending impossible."""
2305 nonlocal current_line
2307 current_line.append_safe(leaf, preformatted=True)
2308 except ValueError as ve:
2311 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2312 current_line.append(leaf)
2314 for index, leaf in enumerate(line.leaves):
2315 yield from append_to_line(leaf)
2317 for comment_after in line.comments_after(leaf, index):
2318 yield from append_to_line(comment_after)
2324 def is_import(leaf: Leaf) -> bool:
2325 """Return True if the given leaf starts an import statement."""
2332 (v == "import" and p and p.type == syms.import_name)
2333 or (v == "from" and p and p.type == syms.import_from)
2338 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
2339 """Leave existing extra newlines if not `inside_brackets`. Remove everything
2342 Note: don't use backslashes for formatting or you'll lose your voting rights.
2344 if not inside_brackets:
2345 spl = leaf.prefix.split("#")
2346 if "\\" not in spl[0]:
2347 nl_count = spl[-1].count("\n")
2350 leaf.prefix = "\n" * nl_count
2356 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
2357 """Make all string prefixes lowercase.
2359 If remove_u_prefix is given, also removes any u prefix from the string.
2361 Note: Mutates its argument.
2363 match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
2364 assert match is not None, f"failed to match string {leaf.value!r}"
2365 orig_prefix = match.group(1)
2366 new_prefix = orig_prefix.lower()
2368 new_prefix = new_prefix.replace("u", "")
2369 leaf.value = f"{new_prefix}{match.group(2)}"
2372 def normalize_string_quotes(leaf: Leaf) -> None:
2373 """Prefer double quotes but only if it doesn't cause more escaping.
2375 Adds or removes backslashes as appropriate. Doesn't parse and fix
2376 strings nested in f-strings (yet).
2378 Note: Mutates its argument.
2380 value = leaf.value.lstrip("furbFURB")
2381 if value[:3] == '"""':
2384 elif value[:3] == "'''":
2387 elif value[0] == '"':
2393 first_quote_pos = leaf.value.find(orig_quote)
2394 if first_quote_pos == -1:
2395 return # There's an internal error
2397 prefix = leaf.value[:first_quote_pos]
2398 unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
2399 escaped_new_quote = re.compile(rf"([^\\]|^)\\(\\\\)*{new_quote}")
2400 escaped_orig_quote = re.compile(rf"([^\\]|^)\\(\\\\)*{orig_quote}")
2401 body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
2402 if "r" in prefix.casefold():
2403 if unescaped_new_quote.search(body):
2404 # There's at least one unescaped new_quote in this raw string
2405 # so converting is impossible
2408 # Do not introduce or remove backslashes in raw strings
2411 # remove unnecessary quotes
2412 new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
2413 if body != new_body:
2414 # Consider the string without unnecessary quotes as the original
2416 leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
2417 new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
2418 new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
2419 if new_quote == '"""' and new_body[-1] == '"':
2421 new_body = new_body[:-1] + '\\"'
2422 orig_escape_count = body.count("\\")
2423 new_escape_count = new_body.count("\\")
2424 if new_escape_count > orig_escape_count:
2425 return # Do not introduce more escaping
2427 if new_escape_count == orig_escape_count and orig_quote == '"':
2428 return # Prefer double quotes
2430 leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
2433 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
2434 """Make existing optional parentheses invisible or create new ones.
2436 `parens_after` is a set of string leaf values immeditely after which parens
2439 Standardizes on visible parentheses for single-element tuples, and keeps
2440 existing visible parentheses for other tuples and generator expressions.
2443 list(generate_comments(node))
2445 return # This `node` has a prefix with `# fmt: off`, don't mess with parens.
2448 for index, child in enumerate(list(node.children)):
2450 if child.type == syms.atom:
2451 maybe_make_parens_invisible_in_atom(child)
2452 elif is_one_tuple(child):
2453 # wrap child in visible parentheses
2454 lpar = Leaf(token.LPAR, "(")
2455 rpar = Leaf(token.RPAR, ")")
2457 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2458 elif node.type == syms.import_from:
2459 # "import from" nodes store parentheses directly as part of
2461 if child.type == token.LPAR:
2462 # make parentheses invisible
2463 child.value = "" # type: ignore
2464 node.children[-1].value = "" # type: ignore
2465 elif child.type != token.STAR:
2466 # insert invisible parentheses
2467 node.insert_child(index, Leaf(token.LPAR, ""))
2468 node.append_child(Leaf(token.RPAR, ""))
2471 elif not (isinstance(child, Leaf) and is_multiline_string(child)):
2472 # wrap child in invisible parentheses
2473 lpar = Leaf(token.LPAR, "")
2474 rpar = Leaf(token.RPAR, "")
2475 index = child.remove() or 0
2476 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2478 check_lpar = isinstance(child, Leaf) and child.value in parens_after
2481 def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
2482 """If it's safe, make the parens in the atom `node` invisible, recusively."""
2484 node.type != syms.atom
2485 or is_empty_tuple(node)
2486 or is_one_tuple(node)
2488 or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
2492 first = node.children[0]
2493 last = node.children[-1]
2494 if first.type == token.LPAR and last.type == token.RPAR:
2495 # make parentheses invisible
2496 first.value = "" # type: ignore
2497 last.value = "" # type: ignore
2498 if len(node.children) > 1:
2499 maybe_make_parens_invisible_in_atom(node.children[1])
2505 def is_empty_tuple(node: LN) -> bool:
2506 """Return True if `node` holds an empty tuple."""
2508 node.type == syms.atom
2509 and len(node.children) == 2
2510 and node.children[0].type == token.LPAR
2511 and node.children[1].type == token.RPAR
2515 def is_one_tuple(node: LN) -> bool:
2516 """Return True if `node` holds a tuple with one element, with or without parens."""
2517 if node.type == syms.atom:
2518 if len(node.children) != 3:
2521 lpar, gexp, rpar = node.children
2523 lpar.type == token.LPAR
2524 and gexp.type == syms.testlist_gexp
2525 and rpar.type == token.RPAR
2529 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
2532 node.type in IMPLICIT_TUPLE
2533 and len(node.children) == 2
2534 and node.children[1].type == token.COMMA
2538 def is_yield(node: LN) -> bool:
2539 """Return True if `node` holds a `yield` or `yield from` expression."""
2540 if node.type == syms.yield_expr:
2543 if node.type == token.NAME and node.value == "yield": # type: ignore
2546 if node.type != syms.atom:
2549 if len(node.children) != 3:
2552 lpar, expr, rpar = node.children
2553 if lpar.type == token.LPAR and rpar.type == token.RPAR:
2554 return is_yield(expr)
2559 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
2560 """Return True if `leaf` is a star or double star in a vararg or kwarg.
2562 If `within` includes VARARGS_PARENTS, this applies to function signatures.
2563 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
2564 extended iterable unpacking (PEP 3132) and additional unpacking
2565 generalizations (PEP 448).
2567 if leaf.type not in STARS or not leaf.parent:
2571 if p.type == syms.star_expr:
2572 # Star expressions are also used as assignment targets in extended
2573 # iterable unpacking (PEP 3132). See what its parent is instead.
2579 return p.type in within
2582 def is_multiline_string(leaf: Leaf) -> bool:
2583 """Return True if `leaf` is a multiline string that actually spans many lines."""
2584 value = leaf.value.lstrip("furbFURB")
2585 return value[:3] in {'"""', "'''"} and "\n" in value
2588 def is_stub_suite(node: Node) -> bool:
2589 """Return True if `node` is a suite with a stub body."""
2591 len(node.children) != 4
2592 or node.children[0].type != token.NEWLINE
2593 or node.children[1].type != token.INDENT
2594 or node.children[3].type != token.DEDENT
2598 return is_stub_body(node.children[2])
2601 def is_stub_body(node: LN) -> bool:
2602 """Return True if `node` is a simple statement containing an ellipsis."""
2603 if not isinstance(node, Node) or node.type != syms.simple_stmt:
2606 if len(node.children) != 2:
2609 child = node.children[0]
2611 child.type == syms.atom
2612 and len(child.children) == 3
2613 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
2617 def max_delimiter_priority_in_atom(node: LN) -> int:
2618 """Return maximum delimiter priority inside `node`.
2620 This is specific to atoms with contents contained in a pair of parentheses.
2621 If `node` isn't an atom or there are no enclosing parentheses, returns 0.
2623 if node.type != syms.atom:
2626 first = node.children[0]
2627 last = node.children[-1]
2628 if not (first.type == token.LPAR and last.type == token.RPAR):
2631 bt = BracketTracker()
2632 for c in node.children[1:-1]:
2633 if isinstance(c, Leaf):
2636 for leaf in c.leaves():
2639 return bt.max_delimiter_priority()
2645 def ensure_visible(leaf: Leaf) -> None:
2646 """Make sure parentheses are visible.
2648 They could be invisible as part of some statements (see
2649 :func:`normalize_invible_parens` and :func:`visit_import_from`).
2651 if leaf.type == token.LPAR:
2653 elif leaf.type == token.RPAR:
2657 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
2658 """Should `line` immediately be split with `delimiter_split()` after RHS?"""
2660 opening_bracket.parent
2661 and opening_bracket.parent.type in {syms.atom, syms.import_from}
2662 and opening_bracket.value in "[{("
2667 last_leaf = line.leaves[-1]
2668 exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
2669 max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
2670 except (IndexError, ValueError):
2673 return max_priority == COMMA_PRIORITY
2676 def is_python36(node: Node) -> bool:
2677 """Return True if the current file is using Python 3.6+ features.
2679 Currently looking for:
2681 - trailing commas after * or ** in function signatures and calls.
2683 for n in node.pre_order():
2684 if n.type == token.STRING:
2685 value_head = n.value[:2] # type: ignore
2686 if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
2690 n.type in {syms.typedargslist, syms.arglist}
2692 and n.children[-1].type == token.COMMA
2694 for ch in n.children:
2695 if ch.type in STARS:
2698 if ch.type == syms.argument:
2699 for argch in ch.children:
2700 if argch.type in STARS:
2706 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
2707 """Generate sets of closing bracket IDs that should be omitted in a RHS.
2709 Brackets can be omitted if the entire trailer up to and including
2710 a preceding closing bracket fits in one line.
2712 Yielded sets are cumulative (contain results of previous yields, too). First
2716 omit: Set[LeafID] = set()
2719 length = 4 * line.depth
2720 opening_bracket = None
2721 closing_bracket = None
2722 optional_brackets: Set[LeafID] = set()
2723 inner_brackets: Set[LeafID] = set()
2724 for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
2725 length += leaf_length
2726 if length > line_length:
2729 has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
2730 if leaf.type == STANDALONE_COMMENT or has_inline_comment:
2733 optional_brackets.discard(id(leaf))
2735 if leaf is opening_bracket:
2736 opening_bracket = None
2737 elif leaf.type in CLOSING_BRACKETS:
2738 inner_brackets.add(id(leaf))
2739 elif leaf.type in CLOSING_BRACKETS:
2741 optional_brackets.add(id(opening_bracket))
2744 if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
2745 # Empty brackets would fail a split so treat them as "inner"
2746 # brackets (e.g. only add them to the `omit` set if another
2747 # pair of brackets was good enough.
2748 inner_brackets.add(id(leaf))
2751 opening_bracket = leaf.opening_bracket
2753 omit.add(id(closing_bracket))
2754 omit.update(inner_brackets)
2755 inner_brackets.clear()
2757 closing_bracket = leaf
2760 def get_future_imports(node: Node) -> Set[str]:
2761 """Return a set of __future__ imports in the file."""
2763 for child in node.children:
2764 if child.type != syms.simple_stmt:
2766 first_child = child.children[0]
2767 if isinstance(first_child, Leaf):
2768 # Continue looking if we see a docstring; otherwise stop.
2770 len(child.children) == 2
2771 and first_child.type == token.STRING
2772 and child.children[1].type == token.NEWLINE
2777 elif first_child.type == syms.import_from:
2778 module_name = first_child.children[1]
2779 if not isinstance(module_name, Leaf) or module_name.value != "__future__":
2781 for import_from_child in first_child.children[3:]:
2782 if isinstance(import_from_child, Leaf):
2783 if import_from_child.type == token.NAME:
2784 imports.add(import_from_child.value)
2786 assert import_from_child.type == syms.import_as_names
2787 for leaf in import_from_child.children:
2788 if isinstance(leaf, Leaf) and leaf.type == token.NAME:
2789 imports.add(leaf.value)
2795 def gen_python_files_in_dir(
2796 path: Path, root: Path, include: Pattern[str], exclude: Pattern[str]
2797 ) -> Iterator[Path]:
2798 """Generate all files under `path` whose paths are not excluded by the
2799 `exclude` regex, but are included by the `include` regex.
2801 assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
2802 for child in path.iterdir():
2803 normalized_path = child.resolve().relative_to(root).as_posix()
2805 normalized_path += "/"
2806 exclude_match = exclude.search(normalized_path)
2807 if exclude_match and exclude_match.group(0):
2811 yield from gen_python_files_in_dir(child, root, include, exclude)
2813 elif child.is_file():
2814 include_match = include.search(normalized_path)
2819 def find_project_root(srcs: List[str]) -> Path:
2820 """Return a directory containing .git, .hg, or pyproject.toml.
2822 That directory can be one of the directories passed in `srcs` or their
2825 If no directory in the tree contains a marker that would specify it's the
2826 project root, the root of the file system is returned.
2829 return Path("/").resolve()
2831 common_base = min(Path(src).resolve() for src in srcs)
2832 if common_base.is_dir():
2833 # Append a fake file so `parents` below returns `common_base_dir`, too.
2834 common_base /= "fake-file"
2835 for directory in common_base.parents:
2836 if (directory / ".git").is_dir():
2839 if (directory / ".hg").is_dir():
2842 if (directory / "pyproject.toml").is_file():
2850 """Provides a reformatting counter. Can be rendered with `str(report)`."""
2854 change_count: int = 0
2856 failure_count: int = 0
2858 def done(self, src: Path, changed: Changed) -> None:
2859 """Increment the counter for successful reformatting. Write out a message."""
2860 if changed is Changed.YES:
2861 reformatted = "would reformat" if self.check else "reformatted"
2863 out(f"{reformatted} {src}")
2864 self.change_count += 1
2867 if changed is Changed.NO:
2868 msg = f"{src} already well formatted, good job."
2870 msg = f"{src} wasn't modified on disk since last run."
2871 out(msg, bold=False)
2872 self.same_count += 1
2874 def failed(self, src: Path, message: str) -> None:
2875 """Increment the counter for failed reformatting. Write out a message."""
2876 err(f"error: cannot format {src}: {message}")
2877 self.failure_count += 1
2880 def return_code(self) -> int:
2881 """Return the exit code that the app should use.
2883 This considers the current state of changed files and failures:
2884 - if there were any failures, return 123;
2885 - if any files were changed and --check is being used, return 1;
2886 - otherwise return 0.
2888 # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
2889 # 126 we have special returncodes reserved by the shell.
2890 if self.failure_count:
2893 elif self.change_count and self.check:
2898 def __str__(self) -> str:
2899 """Render a color report of the current state.
2901 Use `click.unstyle` to remove colors.
2904 reformatted = "would be reformatted"
2905 unchanged = "would be left unchanged"
2906 failed = "would fail to reformat"
2908 reformatted = "reformatted"
2909 unchanged = "left unchanged"
2910 failed = "failed to reformat"
2912 if self.change_count:
2913 s = "s" if self.change_count > 1 else ""
2915 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
2918 s = "s" if self.same_count > 1 else ""
2919 report.append(f"{self.same_count} file{s} {unchanged}")
2920 if self.failure_count:
2921 s = "s" if self.failure_count > 1 else ""
2923 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
2925 return ", ".join(report) + "."
2928 def assert_equivalent(src: str, dst: str) -> None:
2929 """Raise AssertionError if `src` and `dst` aren't equivalent."""
2934 def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
2935 """Simple visitor generating strings to compare ASTs by content."""
2936 yield f"{' ' * depth}{node.__class__.__name__}("
2938 for field in sorted(node._fields):
2940 value = getattr(node, field)
2941 except AttributeError:
2944 yield f"{' ' * (depth+1)}{field}="
2946 if isinstance(value, list):
2948 if isinstance(item, ast.AST):
2949 yield from _v(item, depth + 2)
2951 elif isinstance(value, ast.AST):
2952 yield from _v(value, depth + 2)
2955 yield f"{' ' * (depth+2)}{value!r}, # {value.__class__.__name__}"
2957 yield f"{' ' * depth}) # /{node.__class__.__name__}"
2960 src_ast = ast.parse(src)
2961 except Exception as exc:
2962 major, minor = sys.version_info[:2]
2963 raise AssertionError(
2964 f"cannot use --safe with this file; failed to parse source file "
2965 f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
2966 f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
2970 dst_ast = ast.parse(dst)
2971 except Exception as exc:
2972 log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
2973 raise AssertionError(
2974 f"INTERNAL ERROR: Black produced invalid code: {exc}. "
2975 f"Please report a bug on https://github.com/ambv/black/issues. "
2976 f"This invalid output might be helpful: {log}"
2979 src_ast_str = "\n".join(_v(src_ast))
2980 dst_ast_str = "\n".join(_v(dst_ast))
2981 if src_ast_str != dst_ast_str:
2982 log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
2983 raise AssertionError(
2984 f"INTERNAL ERROR: Black produced code that is not equivalent to "
2986 f"Please report a bug on https://github.com/ambv/black/issues. "
2987 f"This diff might be helpful: {log}"
2992 src: str, dst: str, line_length: int, mode: FileMode = FileMode.AUTO_DETECT
2994 """Raise AssertionError if `dst` reformats differently the second time."""
2995 newdst = format_str(dst, line_length=line_length, mode=mode)
2998 diff(src, dst, "source", "first pass"),
2999 diff(dst, newdst, "first pass", "second pass"),
3001 raise AssertionError(
3002 f"INTERNAL ERROR: Black produced different code on the second pass "
3003 f"of the formatter. "
3004 f"Please report a bug on https://github.com/ambv/black/issues. "
3005 f"This diff might be helpful: {log}"
3009 def dump_to_file(*output: str) -> str:
3010 """Dump `output` to a temporary file. Return path to the file."""
3013 with tempfile.NamedTemporaryFile(
3014 mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
3016 for lines in output:
3018 if lines and lines[-1] != "\n":
3023 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
3024 """Return a unified diff string between strings `a` and `b`."""
3027 a_lines = [line + "\n" for line in a.split("\n")]
3028 b_lines = [line + "\n" for line in b.split("\n")]
3030 difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
3034 def cancel(tasks: Iterable[asyncio.Task]) -> None:
3035 """asyncio signal handler that cancels all `tasks` and reports to stderr."""
3041 def shutdown(loop: BaseEventLoop) -> None:
3042 """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
3044 # This part is borrowed from asyncio/runners.py in Python 3.7b2.
3045 to_cancel = [task for task in asyncio.Task.all_tasks(loop) if not task.done()]
3049 for task in to_cancel:
3051 loop.run_until_complete(
3052 asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
3055 # `concurrent.futures.Future` objects cannot be cancelled once they
3056 # are already running. There might be some when the `shutdown()` happened.
3057 # Silence their logger's spew about the event loop being closed.
3058 cf_logger = logging.getLogger("concurrent.futures")
3059 cf_logger.setLevel(logging.CRITICAL)
3063 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
3064 """Replace `regex` with `replacement` twice on `original`.
3066 This is used by string normalization to perform replaces on
3067 overlapping matches.
3069 return regex.sub(replacement, regex.sub(replacement, original))
3072 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
3073 """Like `reversed(enumerate(sequence))` if that were possible."""
3074 index = len(sequence) - 1
3075 for element in reversed(sequence):
3076 yield (index, element)
3080 def enumerate_with_length(
3081 line: Line, reversed: bool = False
3082 ) -> Iterator[Tuple[Index, Leaf, int]]:
3083 """Return an enumeration of leaves with their length.
3085 Stops prematurely on multiline strings and standalone comments.
3088 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
3089 enumerate_reversed if reversed else enumerate,
3091 for index, leaf in op(line.leaves):
3092 length = len(leaf.prefix) + len(leaf.value)
3093 if "\n" in leaf.value:
3094 return # Multiline strings, we can't continue.
3096 comment: Optional[Leaf]
3097 for comment in line.comments_after(leaf, index):
3098 length += len(comment.value)
3100 yield index, leaf, length
3103 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
3104 """Return True if `line` is no longer than `line_length`.
3106 Uses the provided `line_str` rendering, if any, otherwise computes a new one.
3109 line_str = str(line).strip("\n")
3111 len(line_str) <= line_length
3112 and "\n" not in line_str # multiline strings
3113 and not line.contains_standalone_comments()
3117 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
3118 """Does `line` have a shape safe to reformat without optional parens around it?
3120 Returns True for only a subset of potentially nice looking formattings but
3121 the point is to not return false positives that end up producing lines that
3124 bt = line.bracket_tracker
3125 if not bt.delimiters:
3126 # Without delimiters the optional parentheses are useless.
3129 max_priority = bt.max_delimiter_priority()
3130 if bt.delimiter_count_with_priority(max_priority) > 1:
3131 # With more than one delimiter of a kind the optional parentheses read better.
3134 if max_priority == DOT_PRIORITY:
3135 # A single stranded method call doesn't require optional parentheses.
3138 assert len(line.leaves) >= 2, "Stranded delimiter"
3140 first = line.leaves[0]
3141 second = line.leaves[1]
3142 penultimate = line.leaves[-2]
3143 last = line.leaves[-1]
3145 # With a single delimiter, omit if the expression starts or ends with
3147 if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
3149 length = 4 * line.depth
3150 for _index, leaf, leaf_length in enumerate_with_length(line):
3151 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
3154 length += leaf_length
3155 if length > line_length:
3158 if leaf.type in OPENING_BRACKETS:
3159 # There are brackets we can further split on.
3163 # checked the entire string and line length wasn't exceeded
3164 if len(line.leaves) == _index + 1:
3167 # Note: we are not returning False here because a line might have *both*
3168 # a leading opening bracket and a trailing closing bracket. If the
3169 # opening bracket doesn't match our rule, maybe the closing will.
3172 last.type == token.RPAR
3173 or last.type == token.RBRACE
3175 # don't use indexing for omitting optional parentheses;
3177 last.type == token.RSQB
3179 and last.parent.type != syms.trailer
3182 if penultimate.type in OPENING_BRACKETS:
3183 # Empty brackets don't help.
3186 if is_multiline_string(first):
3187 # Additional wrapping of a multiline string in this situation is
3191 length = 4 * line.depth
3192 seen_other_brackets = False
3193 for _index, leaf, leaf_length in enumerate_with_length(line):
3194 length += leaf_length
3195 if leaf is last.opening_bracket:
3196 if seen_other_brackets or length <= line_length:
3199 elif leaf.type in OPENING_BRACKETS:
3200 # There are brackets we can further split on.
3201 seen_other_brackets = True
3206 def get_cache_file(line_length: int, mode: FileMode) -> Path:
3207 pyi = bool(mode & FileMode.PYI)
3208 py36 = bool(mode & FileMode.PYTHON36)
3211 / f"cache.{line_length}{'.pyi' if pyi else ''}{'.py36' if py36 else ''}.pickle"
3215 def read_cache(line_length: int, mode: FileMode) -> Cache:
3216 """Read the cache if it exists and is well formed.
3218 If it is not well formed, the call to write_cache later should resolve the issue.
3220 cache_file = get_cache_file(line_length, mode)
3221 if not cache_file.exists():
3224 with cache_file.open("rb") as fobj:
3226 cache: Cache = pickle.load(fobj)
3227 except pickle.UnpicklingError:
3233 def get_cache_info(path: Path) -> CacheInfo:
3234 """Return the information used to check if a file is already formatted or not."""
3236 return stat.st_mtime, stat.st_size
3240 cache: Cache, sources: Iterable[Path]
3241 ) -> Tuple[List[Path], List[Path]]:
3242 """Split a list of paths into two.
3244 The first list contains paths of files that modified on disk or are not in the
3245 cache. The other list contains paths to non-modified files.
3250 if cache.get(src) != get_cache_info(src):
3258 cache: Cache, sources: List[Path], line_length: int, mode: FileMode
3260 """Update the cache file."""
3261 cache_file = get_cache_file(line_length, mode)
3263 if not CACHE_DIR.exists():
3264 CACHE_DIR.mkdir(parents=True)
3265 new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
3266 with cache_file.open("wb") as fobj:
3267 pickle.dump(new_cache, fobj, protocol=pickle.HIGHEST_PROTOCOL)
3272 if __name__ == "__main__":