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
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.5b0"
48 DEFAULT_LINE_LENGTH = 88
49 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
60 LN = Union[Leaf, Node]
61 SplitFunc = Callable[["Line", bool], Iterator["Line"]]
64 CacheInfo = Tuple[Timestamp, FileSize]
65 Cache = Dict[Path, CacheInfo]
66 out = partial(click.secho, bold=True, err=True)
67 err = partial(click.secho, fg="red", err=True)
69 pygram.initialize(CACHE_DIR)
70 syms = pygram.python_symbols
73 class NothingChanged(UserWarning):
74 """Raised by :func:`format_file` when reformatted code is the same as source."""
77 class CannotSplit(Exception):
78 """A readable split that fits the allotted line length is impossible.
80 Raised by :func:`left_hand_split`, :func:`right_hand_split`, and
81 :func:`delimiter_split`.
85 class FormatError(Exception):
86 """Base exception for `# fmt: on` and `# fmt: off` handling.
88 It holds the number of bytes of the prefix consumed before the format
89 control comment appeared.
92 def __init__(self, consumed: int) -> None:
93 super().__init__(consumed)
94 self.consumed = consumed
96 def trim_prefix(self, leaf: Leaf) -> None:
97 leaf.prefix = leaf.prefix[self.consumed :]
99 def leaf_from_consumed(self, leaf: Leaf) -> Leaf:
100 """Returns a new Leaf from the consumed part of the prefix."""
101 unformatted_prefix = leaf.prefix[: self.consumed]
102 return Leaf(token.NEWLINE, unformatted_prefix)
105 class FormatOn(FormatError):
106 """Found a comment like `# fmt: on` in the file."""
109 class FormatOff(FormatError):
110 """Found a comment like `# fmt: off` in the file."""
113 class WriteBack(Enum):
130 default=DEFAULT_LINE_LENGTH,
131 help="How many character per line to allow.",
138 "Don't write the files back, just return the status. Return code 0 "
139 "means nothing would change. Return code 1 means some files would be "
140 "reformatted. Return code 123 means there was an internal error."
146 help="Don't write the files back, just output a diff for each file on stdout.",
151 help="If --fast given, skip temporary sanity checks. [default: --safe]",
158 "Don't emit non-error messages to stderr. Errors are still emitted, "
159 "silence those with 2>/dev/null."
162 @click.version_option(version=__version__)
167 exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
180 """The uncompromising code formatter."""
181 sources: List[Path] = []
185 sources.extend(gen_python_files_in_dir(p))
187 # if a file was explicitly given, we don't care about its extension
190 sources.append(Path("-"))
192 err(f"invalid path: {s}")
194 if check and not diff:
195 write_back = WriteBack.NO
197 write_back = WriteBack.DIFF
199 write_back = WriteBack.YES
200 report = Report(check=check, quiet=quiet)
201 if len(sources) == 0:
202 out("No paths given. Nothing to do 😴")
206 elif len(sources) == 1:
207 reformat_one(sources[0], line_length, fast, write_back, report)
209 loop = asyncio.get_event_loop()
210 executor = ProcessPoolExecutor(max_workers=os.cpu_count())
212 loop.run_until_complete(
214 sources, line_length, fast, write_back, report, loop, executor
220 out("All done! ✨ 🍰 ✨")
221 click.echo(str(report))
222 ctx.exit(report.return_code)
226 src: Path, line_length: int, fast: bool, write_back: WriteBack, report: "Report"
228 """Reformat a single file under `src` without spawning child processes.
230 If `quiet` is True, non-error messages are not output. `line_length`,
231 `write_back`, and `fast` options are passed to :func:`format_file_in_place`.
235 if not src.is_file() and str(src) == "-":
236 if format_stdin_to_stdout(
237 line_length=line_length, fast=fast, write_back=write_back
239 changed = Changed.YES
242 if write_back != WriteBack.DIFF:
243 cache = read_cache(line_length)
245 if src in cache and cache[src] == get_cache_info(src):
246 changed = Changed.CACHED
247 if changed is not Changed.CACHED and format_file_in_place(
248 src, line_length=line_length, fast=fast, write_back=write_back
250 changed = Changed.YES
251 if write_back == WriteBack.YES and changed is not Changed.NO:
252 write_cache(cache, [src], line_length)
253 report.done(src, changed)
254 except Exception as exc:
255 report.failed(src, str(exc))
258 async def schedule_formatting(
262 write_back: WriteBack,
267 """Run formatting of `sources` in parallel using the provided `executor`.
269 (Use ProcessPoolExecutors for actual parallelism.)
271 `line_length`, `write_back`, and `fast` options are passed to
272 :func:`format_file_in_place`.
275 if write_back != WriteBack.DIFF:
276 cache = read_cache(line_length)
277 sources, cached = filter_cached(cache, sources)
279 report.done(src, Changed.CACHED)
284 if write_back == WriteBack.DIFF:
285 # For diff output, we need locks to ensure we don't interleave output
286 # from different processes.
288 lock = manager.Lock()
290 loop.run_in_executor(
291 executor, format_file_in_place, src, line_length, fast, write_back, lock
293 for src in sorted(sources)
295 pending: Iterable[asyncio.Task] = tasks.keys()
297 loop.add_signal_handler(signal.SIGINT, cancel, pending)
298 loop.add_signal_handler(signal.SIGTERM, cancel, pending)
299 except NotImplementedError:
300 # There are no good alternatives for these on Windows
303 done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
305 src = tasks.pop(task)
307 cancelled.append(task)
308 elif task.exception():
309 report.failed(src, str(task.exception()))
311 formatted.append(src)
312 report.done(src, Changed.YES if task.result() else Changed.NO)
314 await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
315 if write_back == WriteBack.YES and formatted:
316 write_cache(cache, formatted, line_length)
319 def format_file_in_place(
323 write_back: WriteBack = WriteBack.NO,
324 lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
326 """Format file under `src` path. Return True if changed.
328 If `write_back` is True, write reformatted code back to stdout.
329 `line_length` and `fast` options are passed to :func:`format_file_contents`.
331 is_pyi = src.suffix == ".pyi"
333 with tokenize.open(src) as src_buffer:
334 src_contents = src_buffer.read()
336 dst_contents = format_file_contents(
337 src_contents, line_length=line_length, fast=fast, is_pyi=is_pyi
339 except NothingChanged:
342 if write_back == write_back.YES:
343 with open(src, "w", encoding=src_buffer.encoding) as f:
344 f.write(dst_contents)
345 elif write_back == write_back.DIFF:
346 src_name = f"{src} (original)"
347 dst_name = f"{src} (formatted)"
348 diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
352 sys.stdout.write(diff_contents)
359 def format_stdin_to_stdout(
360 line_length: int, fast: bool, write_back: WriteBack = WriteBack.NO
362 """Format file on stdin. Return True if changed.
364 If `write_back` is True, write reformatted code back to stdout.
365 `line_length` and `fast` arguments are passed to :func:`format_file_contents`.
367 src = sys.stdin.read()
370 dst = format_file_contents(src, line_length=line_length, fast=fast)
373 except NothingChanged:
377 if write_back == WriteBack.YES:
378 sys.stdout.write(dst)
379 elif write_back == WriteBack.DIFF:
380 src_name = "<stdin> (original)"
381 dst_name = "<stdin> (formatted)"
382 sys.stdout.write(diff(src, dst, src_name, dst_name))
385 def format_file_contents(
386 src_contents: str, *, line_length: int, fast: bool, is_pyi: bool = False
388 """Reformat contents a file and return new contents.
390 If `fast` is False, additionally confirm that the reformatted code is
391 valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
392 `line_length` is passed to :func:`format_str`.
394 if src_contents.strip() == "":
397 dst_contents = format_str(src_contents, line_length=line_length, is_pyi=is_pyi)
398 if src_contents == dst_contents:
402 assert_equivalent(src_contents, dst_contents)
404 src_contents, dst_contents, line_length=line_length, is_pyi=is_pyi
410 src_contents: str, line_length: int, *, is_pyi: bool = False
412 """Reformat a string and return new contents.
414 `line_length` determines how many characters per line are allowed.
416 src_node = lib2to3_parse(src_contents)
418 future_imports = get_future_imports(src_node)
419 elt = EmptyLineTracker(is_pyi=is_pyi)
420 py36 = is_python36(src_node)
421 lines = LineGenerator(
422 remove_u_prefix=py36 or "unicode_literals" in future_imports, is_pyi=is_pyi
426 for current_line in lines.visit(src_node):
427 for _ in range(after):
428 dst_contents += str(empty_line)
429 before, after = elt.maybe_empty_lines(current_line)
430 for _ in range(before):
431 dst_contents += str(empty_line)
432 for line in split_line(current_line, line_length=line_length, py36=py36):
433 dst_contents += str(line)
438 pygram.python_grammar_no_print_statement_no_exec_statement,
439 pygram.python_grammar_no_print_statement,
440 pygram.python_grammar,
444 def lib2to3_parse(src_txt: str) -> Node:
445 """Given a string with source, return the lib2to3 Node."""
446 grammar = pygram.python_grammar_no_print_statement
447 if src_txt[-1] != "\n":
448 nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
450 for grammar in GRAMMARS:
451 drv = driver.Driver(grammar, pytree.convert)
453 result = drv.parse_string(src_txt, True)
456 except ParseError as pe:
457 lineno, column = pe.context[1]
458 lines = src_txt.splitlines()
460 faulty_line = lines[lineno - 1]
462 faulty_line = "<line number missing in source>"
463 exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}")
467 if isinstance(result, Leaf):
468 result = Node(syms.file_input, [result])
472 def lib2to3_unparse(node: Node) -> str:
473 """Given a lib2to3 node, return its string representation."""
481 class Visitor(Generic[T]):
482 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
484 def visit(self, node: LN) -> Iterator[T]:
485 """Main method to visit `node` and its children.
487 It tries to find a `visit_*()` method for the given `node.type`, like
488 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
489 If no dedicated `visit_*()` method is found, chooses `visit_default()`
492 Then yields objects of type `T` from the selected visitor.
495 name = token.tok_name[node.type]
497 name = type_repr(node.type)
498 yield from getattr(self, f"visit_{name}", self.visit_default)(node)
500 def visit_default(self, node: LN) -> Iterator[T]:
501 """Default `visit_*()` implementation. Recurses to children of `node`."""
502 if isinstance(node, Node):
503 for child in node.children:
504 yield from self.visit(child)
508 class DebugVisitor(Visitor[T]):
511 def visit_default(self, node: LN) -> Iterator[T]:
512 indent = " " * (2 * self.tree_depth)
513 if isinstance(node, Node):
514 _type = type_repr(node.type)
515 out(f"{indent}{_type}", fg="yellow")
517 for child in node.children:
518 yield from self.visit(child)
521 out(f"{indent}/{_type}", fg="yellow", bold=False)
523 _type = token.tok_name.get(node.type, str(node.type))
524 out(f"{indent}{_type}", fg="blue", nl=False)
526 # We don't have to handle prefixes for `Node` objects since
527 # that delegates to the first child anyway.
528 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
529 out(f" {node.value!r}", fg="blue", bold=False)
532 def show(cls, code: str) -> None:
533 """Pretty-print the lib2to3 AST of a given string of `code`.
535 Convenience method for debugging.
537 v: DebugVisitor[None] = DebugVisitor()
538 list(v.visit(lib2to3_parse(code)))
541 KEYWORDS = set(keyword.kwlist)
542 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
543 FLOW_CONTROL = {"return", "raise", "break", "continue"}
554 STANDALONE_COMMENT = 153
555 LOGIC_OPERATORS = {"and", "or"}
580 STARS = {token.STAR, token.DOUBLESTAR}
583 syms.argument, # double star in arglist
584 syms.trailer, # single argument to call
586 syms.varargslist, # lambdas
588 UNPACKING_PARENTS = {
589 syms.atom, # single element of a list or set literal
627 COMPREHENSION_PRIORITY = 20
629 TERNARY_PRIORITY = 16
632 COMPARATOR_PRIORITY = 10
643 token.DOUBLESLASH: 4,
653 class BracketTracker:
654 """Keeps track of brackets on a line."""
657 bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
658 delimiters: Dict[LeafID, Priority] = Factory(dict)
659 previous: Optional[Leaf] = None
660 _for_loop_variable: int = 0
661 _lambda_arguments: int = 0
663 def mark(self, leaf: Leaf) -> None:
664 """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
666 All leaves receive an int `bracket_depth` field that stores how deep
667 within brackets a given leaf is. 0 means there are no enclosing brackets
668 that started on this line.
670 If a leaf is itself a closing bracket, it receives an `opening_bracket`
671 field that it forms a pair with. This is a one-directional link to
672 avoid reference cycles.
674 If a leaf is a delimiter (a token on which Black can split the line if
675 needed) and it's on depth 0, its `id()` is stored in the tracker's
678 if leaf.type == token.COMMENT:
681 self.maybe_decrement_after_for_loop_variable(leaf)
682 self.maybe_decrement_after_lambda_arguments(leaf)
683 if leaf.type in CLOSING_BRACKETS:
685 opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
686 leaf.opening_bracket = opening_bracket
687 leaf.bracket_depth = self.depth
689 delim = is_split_before_delimiter(leaf, self.previous)
690 if delim and self.previous is not None:
691 self.delimiters[id(self.previous)] = delim
693 delim = is_split_after_delimiter(leaf, self.previous)
695 self.delimiters[id(leaf)] = delim
696 if leaf.type in OPENING_BRACKETS:
697 self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
700 self.maybe_increment_lambda_arguments(leaf)
701 self.maybe_increment_for_loop_variable(leaf)
703 def any_open_brackets(self) -> bool:
704 """Return True if there is an yet unmatched open bracket on the line."""
705 return bool(self.bracket_match)
707 def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
708 """Return the highest priority of a delimiter found on the line.
710 Values are consistent with what `is_split_*_delimiter()` return.
711 Raises ValueError on no delimiters.
713 return max(v for k, v in self.delimiters.items() if k not in exclude)
715 def delimiter_count_with_priority(self, priority: int = 0) -> int:
716 """Return the number of delimiters with the given `priority`.
718 If no `priority` is passed, defaults to max priority on the line.
720 if not self.delimiters:
723 priority = priority or self.max_delimiter_priority()
724 return sum(1 for p in self.delimiters.values() if p == priority)
726 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
727 """In a for loop, or comprehension, the variables are often unpacks.
729 To avoid splitting on the comma in this situation, increase the depth of
730 tokens between `for` and `in`.
732 if leaf.type == token.NAME and leaf.value == "for":
734 self._for_loop_variable += 1
739 def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
740 """See `maybe_increment_for_loop_variable` above for explanation."""
741 if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
743 self._for_loop_variable -= 1
748 def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
749 """In a lambda expression, there might be more than one argument.
751 To avoid splitting on the comma in this situation, increase the depth of
752 tokens between `lambda` and `:`.
754 if leaf.type == token.NAME and leaf.value == "lambda":
756 self._lambda_arguments += 1
761 def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
762 """See `maybe_increment_lambda_arguments` above for explanation."""
763 if self._lambda_arguments and leaf.type == token.COLON:
765 self._lambda_arguments -= 1
770 def get_open_lsqb(self) -> Optional[Leaf]:
771 """Return the most recent opening square bracket (if any)."""
772 return self.bracket_match.get((self.depth - 1, token.RSQB))
777 """Holds leaves and comments. Can be printed with `str(line)`."""
780 leaves: List[Leaf] = Factory(list)
781 comments: List[Tuple[Index, Leaf]] = Factory(list)
782 bracket_tracker: BracketTracker = Factory(BracketTracker)
783 inside_brackets: bool = False
784 should_explode: bool = False
786 def append(self, leaf: Leaf, preformatted: bool = False) -> None:
787 """Add a new `leaf` to the end of the line.
789 Unless `preformatted` is True, the `leaf` will receive a new consistent
790 whitespace prefix and metadata applied by :class:`BracketTracker`.
791 Trailing commas are maybe removed, unpacked for loop variables are
792 demoted from being delimiters.
794 Inline comments are put aside.
796 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
800 if token.COLON == leaf.type and self.is_class_paren_empty:
802 if self.leaves and not preformatted:
803 # Note: at this point leaf.prefix should be empty except for
804 # imports, for which we only preserve newlines.
805 leaf.prefix += whitespace(
806 leaf, complex_subscript=self.is_complex_subscript(leaf)
808 if self.inside_brackets or not preformatted:
809 self.bracket_tracker.mark(leaf)
810 self.maybe_remove_trailing_comma(leaf)
811 if not self.append_comment(leaf):
812 self.leaves.append(leaf)
814 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
815 """Like :func:`append()` but disallow invalid standalone comment structure.
817 Raises ValueError when any `leaf` is appended after a standalone comment
818 or when a standalone comment is not the first leaf on the line.
820 if self.bracket_tracker.depth == 0:
822 raise ValueError("cannot append to standalone comments")
824 if self.leaves and leaf.type == STANDALONE_COMMENT:
826 "cannot append standalone comments to a populated line"
829 self.append(leaf, preformatted=preformatted)
832 def is_comment(self) -> bool:
833 """Is this line a standalone comment?"""
834 return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
837 def is_decorator(self) -> bool:
838 """Is this line a decorator?"""
839 return bool(self) and self.leaves[0].type == token.AT
842 def is_import(self) -> bool:
843 """Is this an import line?"""
844 return bool(self) and is_import(self.leaves[0])
847 def is_class(self) -> bool:
848 """Is this line a class definition?"""
851 and self.leaves[0].type == token.NAME
852 and self.leaves[0].value == "class"
856 def is_stub_class(self) -> bool:
857 """Is this line a class definition with a body consisting only of "..."?"""
858 return self.is_class and self.leaves[-3:] == [
859 Leaf(token.DOT, ".") for _ in range(3)
863 def is_def(self) -> bool:
864 """Is this a function definition? (Also returns True for async defs.)"""
866 first_leaf = self.leaves[0]
871 second_leaf: Optional[Leaf] = self.leaves[1]
874 return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
875 first_leaf.type == token.ASYNC
876 and second_leaf is not None
877 and second_leaf.type == token.NAME
878 and second_leaf.value == "def"
882 def is_flow_control(self) -> bool:
883 """Is this line a flow control statement?
885 Those are `return`, `raise`, `break`, and `continue`.
889 and self.leaves[0].type == token.NAME
890 and self.leaves[0].value in FLOW_CONTROL
894 def is_yield(self) -> bool:
895 """Is this line a yield statement?"""
898 and self.leaves[0].type == token.NAME
899 and self.leaves[0].value == "yield"
903 def is_class_paren_empty(self) -> bool:
904 """Is this a class with no base classes but using parentheses?
906 Those are unnecessary and should be removed.
910 and len(self.leaves) == 4
912 and self.leaves[2].type == token.LPAR
913 and self.leaves[2].value == "("
914 and self.leaves[3].type == token.RPAR
915 and self.leaves[3].value == ")"
918 def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
919 """If so, needs to be split before emitting."""
920 for leaf in self.leaves:
921 if leaf.type == STANDALONE_COMMENT:
922 if leaf.bracket_depth <= depth_limit:
927 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
928 """Remove trailing comma if there is one and it's safe."""
931 and self.leaves[-1].type == token.COMMA
932 and closing.type in CLOSING_BRACKETS
936 if closing.type == token.RBRACE:
937 self.remove_trailing_comma()
940 if closing.type == token.RSQB:
941 comma = self.leaves[-1]
942 if comma.parent and comma.parent.type == syms.listmaker:
943 self.remove_trailing_comma()
946 # For parens let's check if it's safe to remove the comma.
947 # Imports are always safe.
949 self.remove_trailing_comma()
952 # Otheriwsse, if the trailing one is the only one, we might mistakenly
953 # change a tuple into a different type by removing the comma.
954 depth = closing.bracket_depth + 1
956 opening = closing.opening_bracket
957 for _opening_index, leaf in enumerate(self.leaves):
964 for leaf in self.leaves[_opening_index + 1 :]:
968 bracket_depth = leaf.bracket_depth
969 if bracket_depth == depth and leaf.type == token.COMMA:
971 if leaf.parent and leaf.parent.type == syms.arglist:
976 self.remove_trailing_comma()
981 def append_comment(self, comment: Leaf) -> bool:
982 """Add an inline or standalone comment to the line."""
984 comment.type == STANDALONE_COMMENT
985 and self.bracket_tracker.any_open_brackets()
990 if comment.type != token.COMMENT:
993 after = len(self.leaves) - 1
995 comment.type = STANDALONE_COMMENT
1000 self.comments.append((after, comment))
1003 def comments_after(self, leaf: Leaf, _index: int = -1) -> Iterator[Leaf]:
1004 """Generate comments that should appear directly after `leaf`.
1006 Provide a non-negative leaf `_index` to speed up the function.
1009 for _index, _leaf in enumerate(self.leaves):
1016 for index, comment_after in self.comments:
1020 def remove_trailing_comma(self) -> None:
1021 """Remove the trailing comma and moves the comments attached to it."""
1022 comma_index = len(self.leaves) - 1
1023 for i in range(len(self.comments)):
1024 comment_index, comment = self.comments[i]
1025 if comment_index == comma_index:
1026 self.comments[i] = (comma_index - 1, comment)
1029 def is_complex_subscript(self, leaf: Leaf) -> bool:
1030 """Return True iff `leaf` is part of a slice with non-trivial exprs."""
1032 leaf if leaf.type == token.LSQB else self.bracket_tracker.get_open_lsqb()
1034 if open_lsqb is None:
1037 subscript_start = open_lsqb.next_sibling
1039 isinstance(subscript_start, Node)
1040 and subscript_start.type == syms.subscriptlist
1042 subscript_start = child_towards(subscript_start, leaf)
1043 return subscript_start is not None and any(
1044 n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
1047 def __str__(self) -> str:
1048 """Render the line."""
1052 indent = " " * self.depth
1053 leaves = iter(self.leaves)
1054 first = next(leaves)
1055 res = f"{first.prefix}{indent}{first.value}"
1058 for _, comment in self.comments:
1062 def __bool__(self) -> bool:
1063 """Return True if the line has leaves or comments."""
1064 return bool(self.leaves or self.comments)
1067 class UnformattedLines(Line):
1068 """Just like :class:`Line` but stores lines which aren't reformatted."""
1070 def append(self, leaf: Leaf, preformatted: bool = True) -> None:
1071 """Just add a new `leaf` to the end of the lines.
1073 The `preformatted` argument is ignored.
1075 Keeps track of indentation `depth`, which is useful when the user
1076 says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`.
1079 list(generate_comments(leaf))
1080 except FormatOn as f_on:
1081 self.leaves.append(f_on.leaf_from_consumed(leaf))
1084 self.leaves.append(leaf)
1085 if leaf.type == token.INDENT:
1087 elif leaf.type == token.DEDENT:
1090 def __str__(self) -> str:
1091 """Render unformatted lines from leaves which were added with `append()`.
1093 `depth` is not used for indentation in this case.
1099 for leaf in self.leaves:
1103 def append_comment(self, comment: Leaf) -> bool:
1104 """Not implemented in this class. Raises `NotImplementedError`."""
1105 raise NotImplementedError("Unformatted lines don't store comments separately.")
1107 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1108 """Does nothing and returns False."""
1111 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
1112 """Does nothing and returns False."""
1117 class EmptyLineTracker:
1118 """Provides a stateful method that returns the number of potential extra
1119 empty lines needed before and after the currently processed line.
1121 Note: this tracker works on lines that haven't been split yet. It assumes
1122 the prefix of the first leaf consists of optional newlines. Those newlines
1123 are consumed by `maybe_empty_lines()` and included in the computation.
1125 is_pyi: bool = False
1126 previous_line: Optional[Line] = None
1127 previous_after: int = 0
1128 previous_defs: List[int] = Factory(list)
1130 def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1131 """Return the number of extra empty lines before and after the `current_line`.
1133 This is for separating `def`, `async def` and `class` with extra empty
1134 lines (two on module-level), as well as providing an extra empty line
1135 after flow control keywords to make them more prominent.
1137 if isinstance(current_line, UnformattedLines):
1140 before, after = self._maybe_empty_lines(current_line)
1141 before -= self.previous_after
1142 self.previous_after = after
1143 self.previous_line = current_line
1144 return before, after
1146 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1148 if current_line.depth == 0:
1149 max_allowed = 1 if self.is_pyi else 2
1150 if current_line.leaves:
1151 # Consume the first leaf's extra newlines.
1152 first_leaf = current_line.leaves[0]
1153 before = first_leaf.prefix.count("\n")
1154 before = min(before, max_allowed)
1155 first_leaf.prefix = ""
1158 depth = current_line.depth
1159 while self.previous_defs and self.previous_defs[-1] >= depth:
1160 self.previous_defs.pop()
1162 before = 0 if depth else 1
1164 before = 1 if depth else 2
1165 is_decorator = current_line.is_decorator
1166 if is_decorator or current_line.is_def or current_line.is_class:
1167 if not is_decorator:
1168 self.previous_defs.append(depth)
1169 if self.previous_line is None:
1170 # Don't insert empty lines before the first line in the file.
1173 if self.previous_line.is_decorator:
1177 self.previous_line.is_comment
1178 and self.previous_line.depth == current_line.depth
1184 if self.previous_line.depth > current_line.depth:
1186 elif current_line.is_class or self.previous_line.is_class:
1187 if current_line.is_stub_class and self.previous_line.is_stub_class:
1195 if current_line.depth and newlines:
1201 and self.previous_line.is_import
1202 and not current_line.is_import
1203 and depth == self.previous_line.depth
1205 return (before or 1), 0
1211 class LineGenerator(Visitor[Line]):
1212 """Generates reformatted Line objects. Empty lines are not emitted.
1214 Note: destroys the tree it's visiting by mutating prefixes of its leaves
1215 in ways that will no longer stringify to valid Python code on the tree.
1217 is_pyi: bool = False
1218 current_line: Line = Factory(Line)
1219 remove_u_prefix: bool = False
1221 def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
1224 If the line is empty, only emit if it makes sense.
1225 If the line is too long, split it first and then generate.
1227 If any lines were generated, set up a new current_line.
1229 if not self.current_line:
1230 if self.current_line.__class__ == type:
1231 self.current_line.depth += indent
1233 self.current_line = type(depth=self.current_line.depth + indent)
1234 return # Line is empty, don't emit. Creating a new one unnecessary.
1236 complete_line = self.current_line
1237 self.current_line = type(depth=complete_line.depth + indent)
1240 def visit(self, node: LN) -> Iterator[Line]:
1241 """Main method to visit `node` and its children.
1243 Yields :class:`Line` objects.
1245 if isinstance(self.current_line, UnformattedLines):
1246 # File contained `# fmt: off`
1247 yield from self.visit_unformatted(node)
1250 yield from super().visit(node)
1252 def visit_default(self, node: LN) -> Iterator[Line]:
1253 """Default `visit_*()` implementation. Recurses to children of `node`."""
1254 if isinstance(node, Leaf):
1255 any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
1257 for comment in generate_comments(node):
1258 if any_open_brackets:
1259 # any comment within brackets is subject to splitting
1260 self.current_line.append(comment)
1261 elif comment.type == token.COMMENT:
1262 # regular trailing comment
1263 self.current_line.append(comment)
1264 yield from self.line()
1267 # regular standalone comment
1268 yield from self.line()
1270 self.current_line.append(comment)
1271 yield from self.line()
1273 except FormatOff as f_off:
1274 f_off.trim_prefix(node)
1275 yield from self.line(type=UnformattedLines)
1276 yield from self.visit(node)
1278 except FormatOn as f_on:
1279 # This only happens here if somebody says "fmt: on" multiple
1281 f_on.trim_prefix(node)
1282 yield from self.visit_default(node)
1285 normalize_prefix(node, inside_brackets=any_open_brackets)
1286 if node.type == token.STRING:
1287 normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
1288 normalize_string_quotes(node)
1289 if node.type not in WHITESPACE:
1290 self.current_line.append(node)
1291 yield from super().visit_default(node)
1293 def visit_INDENT(self, node: Node) -> Iterator[Line]:
1294 """Increase indentation level, maybe yield a line."""
1295 # In blib2to3 INDENT never holds comments.
1296 yield from self.line(+1)
1297 yield from self.visit_default(node)
1299 def visit_DEDENT(self, node: Node) -> Iterator[Line]:
1300 """Decrease indentation level, maybe yield a line."""
1301 # The current line might still wait for trailing comments. At DEDENT time
1302 # there won't be any (they would be prefixes on the preceding NEWLINE).
1303 # Emit the line then.
1304 yield from self.line()
1306 # While DEDENT has no value, its prefix may contain standalone comments
1307 # that belong to the current indentation level. Get 'em.
1308 yield from self.visit_default(node)
1310 # Finally, emit the dedent.
1311 yield from self.line(-1)
1314 self, node: Node, keywords: Set[str], parens: Set[str]
1315 ) -> Iterator[Line]:
1316 """Visit a statement.
1318 This implementation is shared for `if`, `while`, `for`, `try`, `except`,
1319 `def`, `with`, `class`, `assert` and assignments.
1321 The relevant Python language `keywords` for a given statement will be
1322 NAME leaves within it. This methods puts those on a separate line.
1324 `parens` holds a set of string leaf values immediately after which
1325 invisible parens should be put.
1327 normalize_invisible_parens(node, parens_after=parens)
1328 for child in node.children:
1329 if child.type == token.NAME and child.value in keywords: # type: ignore
1330 yield from self.line()
1332 yield from self.visit(child)
1334 def visit_suite(self, node: Node) -> Iterator[Line]:
1335 """Visit a suite."""
1336 if self.is_pyi and is_stub_suite(node):
1337 yield from self.visit(node.children[2])
1339 yield from self.visit_default(node)
1341 def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
1342 """Visit a statement without nested statements."""
1343 is_suite_like = node.parent and node.parent.type in STATEMENT
1345 if self.is_pyi and is_stub_body(node):
1346 yield from self.visit_default(node)
1348 yield from self.line(+1)
1349 yield from self.visit_default(node)
1350 yield from self.line(-1)
1353 if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
1354 yield from self.line()
1355 yield from self.visit_default(node)
1357 def visit_async_stmt(self, node: Node) -> Iterator[Line]:
1358 """Visit `async def`, `async for`, `async with`."""
1359 yield from self.line()
1361 children = iter(node.children)
1362 for child in children:
1363 yield from self.visit(child)
1365 if child.type == token.ASYNC:
1368 internal_stmt = next(children)
1369 for child in internal_stmt.children:
1370 yield from self.visit(child)
1372 def visit_decorators(self, node: Node) -> Iterator[Line]:
1373 """Visit decorators."""
1374 for child in node.children:
1375 yield from self.line()
1376 yield from self.visit(child)
1378 def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
1379 """Remove a semicolon and put the other statement on a separate line."""
1380 yield from self.line()
1382 def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
1383 """End of file. Process outstanding comments and end with a newline."""
1384 yield from self.visit_default(leaf)
1385 yield from self.line()
1387 def visit_unformatted(self, node: LN) -> Iterator[Line]:
1388 """Used when file contained a `# fmt: off`."""
1389 if isinstance(node, Node):
1390 for child in node.children:
1391 yield from self.visit(child)
1395 self.current_line.append(node)
1396 except FormatOn as f_on:
1397 f_on.trim_prefix(node)
1398 yield from self.line()
1399 yield from self.visit(node)
1401 if node.type == token.ENDMARKER:
1402 # somebody decided not to put a final `# fmt: on`
1403 yield from self.line()
1405 def __attrs_post_init__(self) -> None:
1406 """You are in a twisty little maze of passages."""
1409 self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
1410 self.visit_if_stmt = partial(
1411 v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
1413 self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
1414 self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
1415 self.visit_try_stmt = partial(
1416 v, keywords={"try", "except", "else", "finally"}, parens=Ø
1418 self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
1419 self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
1420 self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
1421 self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
1422 self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
1423 self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
1424 self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
1425 self.visit_async_funcdef = self.visit_async_stmt
1426 self.visit_decorated = self.visit_decorators
1429 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
1430 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
1431 OPENING_BRACKETS = set(BRACKET.keys())
1432 CLOSING_BRACKETS = set(BRACKET.values())
1433 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
1434 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
1437 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa C901
1438 """Return whitespace prefix if needed for the given `leaf`.
1440 `complex_subscript` signals whether the given leaf is part of a subscription
1441 which has non-trivial arguments, like arithmetic expressions or function calls.
1449 if t in ALWAYS_NO_SPACE:
1452 if t == token.COMMENT:
1455 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
1456 if t == token.COLON and p.type not in {
1463 prev = leaf.prev_sibling
1465 prevp = preceding_leaf(p)
1466 if not prevp or prevp.type in OPENING_BRACKETS:
1469 if t == token.COLON:
1470 if prevp.type == token.COLON:
1473 elif prevp.type != token.COMMA and not complex_subscript:
1478 if prevp.type == token.EQUAL:
1480 if prevp.parent.type in {
1488 elif prevp.parent.type == syms.typedargslist:
1489 # A bit hacky: if the equal sign has whitespace, it means we
1490 # previously found it's a typed argument. So, we're using
1494 elif prevp.type in STARS:
1495 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1498 elif prevp.type == token.COLON:
1499 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
1500 return SPACE if complex_subscript else NO
1504 and prevp.parent.type == syms.factor
1505 and prevp.type in MATH_OPERATORS
1510 prevp.type == token.RIGHTSHIFT
1512 and prevp.parent.type == syms.shift_expr
1513 and prevp.prev_sibling
1514 and prevp.prev_sibling.type == token.NAME
1515 and prevp.prev_sibling.value == "print" # type: ignore
1517 # Python 2 print chevron
1520 elif prev.type in OPENING_BRACKETS:
1523 if p.type in {syms.parameters, syms.arglist}:
1524 # untyped function signatures or calls
1525 if not prev or prev.type != token.COMMA:
1528 elif p.type == syms.varargslist:
1530 if prev and prev.type != token.COMMA:
1533 elif p.type == syms.typedargslist:
1534 # typed function signatures
1538 if t == token.EQUAL:
1539 if prev.type != syms.tname:
1542 elif prev.type == token.EQUAL:
1543 # A bit hacky: if the equal sign has whitespace, it means we
1544 # previously found it's a typed argument. So, we're using that, too.
1547 elif prev.type != token.COMMA:
1550 elif p.type == syms.tname:
1553 prevp = preceding_leaf(p)
1554 if not prevp or prevp.type != token.COMMA:
1557 elif p.type == syms.trailer:
1558 # attributes and calls
1559 if t == token.LPAR or t == token.RPAR:
1564 prevp = preceding_leaf(p)
1565 if not prevp or prevp.type != token.NUMBER:
1568 elif t == token.LSQB:
1571 elif prev.type != token.COMMA:
1574 elif p.type == syms.argument:
1576 if t == token.EQUAL:
1580 prevp = preceding_leaf(p)
1581 if not prevp or prevp.type == token.LPAR:
1584 elif prev.type in {token.EQUAL} | STARS:
1587 elif p.type == syms.decorator:
1591 elif p.type == syms.dotted_name:
1595 prevp = preceding_leaf(p)
1596 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
1599 elif p.type == syms.classdef:
1603 if prev and prev.type == token.LPAR:
1606 elif p.type in {syms.subscript, syms.sliceop}:
1609 assert p.parent is not None, "subscripts are always parented"
1610 if p.parent.type == syms.subscriptlist:
1615 elif not complex_subscript:
1618 elif p.type == syms.atom:
1619 if prev and t == token.DOT:
1620 # dots, but not the first one.
1623 elif p.type == syms.dictsetmaker:
1625 if prev and prev.type == token.DOUBLESTAR:
1628 elif p.type in {syms.factor, syms.star_expr}:
1631 prevp = preceding_leaf(p)
1632 if not prevp or prevp.type in OPENING_BRACKETS:
1635 prevp_parent = prevp.parent
1636 assert prevp_parent is not None
1637 if prevp.type == token.COLON and prevp_parent.type in {
1643 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
1646 elif t == token.NAME or t == token.NUMBER:
1649 elif p.type == syms.import_from:
1651 if prev and prev.type == token.DOT:
1654 elif t == token.NAME:
1658 if prev and prev.type == token.DOT:
1661 elif p.type == syms.sliceop:
1667 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
1668 """Return the first leaf that precedes `node`, if any."""
1670 res = node.prev_sibling
1672 if isinstance(res, Leaf):
1676 return list(res.leaves())[-1]
1685 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
1686 """Return the child of `ancestor` that contains `descendant`."""
1687 node: Optional[LN] = descendant
1688 while node and node.parent != ancestor:
1693 def is_split_after_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1694 """Return the priority of the `leaf` delimiter, given a line break after it.
1696 The delimiter priorities returned here are from those delimiters that would
1697 cause a line break after themselves.
1699 Higher numbers are higher priority.
1701 if leaf.type == token.COMMA:
1702 return COMMA_PRIORITY
1707 def is_split_before_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1708 """Return the priority of the `leaf` delimiter, given a line before after it.
1710 The delimiter priorities returned here are from those delimiters that would
1711 cause a line break before themselves.
1713 Higher numbers are higher priority.
1715 if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1716 # * and ** might also be MATH_OPERATORS but in this case they are not.
1717 # Don't treat them as a delimiter.
1721 leaf.type == token.DOT
1723 and leaf.parent.type not in {syms.import_from, syms.dotted_name}
1724 and (previous is None or previous.type in CLOSING_BRACKETS)
1729 leaf.type in MATH_OPERATORS
1731 and leaf.parent.type not in {syms.factor, syms.star_expr}
1733 return MATH_PRIORITIES[leaf.type]
1735 if leaf.type in COMPARATORS:
1736 return COMPARATOR_PRIORITY
1739 leaf.type == token.STRING
1740 and previous is not None
1741 and previous.type == token.STRING
1743 return STRING_PRIORITY
1745 if leaf.type != token.NAME:
1751 and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
1753 return COMPREHENSION_PRIORITY
1758 and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
1760 return COMPREHENSION_PRIORITY
1762 if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
1763 return TERNARY_PRIORITY
1765 if leaf.value == "is":
1766 return COMPARATOR_PRIORITY
1771 and leaf.parent.type in {syms.comp_op, syms.comparison}
1773 previous is not None
1774 and previous.type == token.NAME
1775 and previous.value == "not"
1778 return COMPARATOR_PRIORITY
1783 and leaf.parent.type == syms.comp_op
1785 previous is not None
1786 and previous.type == token.NAME
1787 and previous.value == "is"
1790 return COMPARATOR_PRIORITY
1792 if leaf.value in LOGIC_OPERATORS and leaf.parent:
1793 return LOGIC_PRIORITY
1798 def generate_comments(leaf: LN) -> Iterator[Leaf]:
1799 """Clean the prefix of the `leaf` and generate comments from it, if any.
1801 Comments in lib2to3 are shoved into the whitespace prefix. This happens
1802 in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
1803 move because it does away with modifying the grammar to include all the
1804 possible places in which comments can be placed.
1806 The sad consequence for us though is that comments don't "belong" anywhere.
1807 This is why this function generates simple parentless Leaf objects for
1808 comments. We simply don't know what the correct parent should be.
1810 No matter though, we can live without this. We really only need to
1811 differentiate between inline and standalone comments. The latter don't
1812 share the line with any code.
1814 Inline comments are emitted as regular token.COMMENT leaves. Standalone
1815 are emitted with a fake STANDALONE_COMMENT token identifier.
1826 for index, line in enumerate(p.split("\n")):
1827 consumed += len(line) + 1 # adding the length of the split '\n'
1828 line = line.lstrip()
1831 if not line.startswith("#"):
1834 if index == 0 and leaf.type != token.ENDMARKER:
1835 comment_type = token.COMMENT # simple trailing comment
1837 comment_type = STANDALONE_COMMENT
1838 comment = make_comment(line)
1839 yield Leaf(comment_type, comment, prefix="\n" * nlines)
1841 if comment in {"# fmt: on", "# yapf: enable"}:
1842 raise FormatOn(consumed)
1844 if comment in {"# fmt: off", "# yapf: disable"}:
1845 if comment_type == STANDALONE_COMMENT:
1846 raise FormatOff(consumed)
1848 prev = preceding_leaf(leaf)
1849 if not prev or prev.type in WHITESPACE: # standalone comment in disguise
1850 raise FormatOff(consumed)
1855 def make_comment(content: str) -> str:
1856 """Return a consistently formatted comment from the given `content` string.
1858 All comments (except for "##", "#!", "#:") should have a single space between
1859 the hash sign and the content.
1861 If `content` didn't start with a hash sign, one is provided.
1863 content = content.rstrip()
1867 if content[0] == "#":
1868 content = content[1:]
1869 if content and content[0] not in " !:#":
1870 content = " " + content
1871 return "#" + content
1875 line: Line, line_length: int, inner: bool = False, py36: bool = False
1876 ) -> Iterator[Line]:
1877 """Split a `line` into potentially many lines.
1879 They should fit in the allotted `line_length` but might not be able to.
1880 `inner` signifies that there were a pair of brackets somewhere around the
1881 current `line`, possibly transitively. This means we can fallback to splitting
1882 by delimiters if the LHS/RHS don't yield any results.
1884 If `py36` is True, splitting may generate syntax that is only compatible
1885 with Python 3.6 and later.
1887 if isinstance(line, UnformattedLines) or line.is_comment:
1891 line_str = str(line).strip("\n")
1892 if not line.should_explode and is_line_short_enough(
1893 line, line_length=line_length, line_str=line_str
1898 split_funcs: List[SplitFunc]
1900 split_funcs = [left_hand_split]
1903 def rhs(line: Line, py36: bool = False) -> Iterator[Line]:
1904 for omit in generate_trailers_to_omit(line, line_length):
1905 lines = list(right_hand_split(line, line_length, py36, omit=omit))
1906 if is_line_short_enough(lines[0], line_length=line_length):
1910 # All splits failed, best effort split with no omits.
1911 # This mostly happens to multiline strings that are by definition
1912 # reported as not fitting a single line.
1913 yield from right_hand_split(line, py36)
1915 if line.inside_brackets:
1916 split_funcs = [delimiter_split, standalone_comment_split, rhs]
1919 for split_func in split_funcs:
1920 # We are accumulating lines in `result` because we might want to abort
1921 # mission and return the original line in the end, or attempt a different
1923 result: List[Line] = []
1925 for l in split_func(line, py36):
1926 if str(l).strip("\n") == line_str:
1927 raise CannotSplit("Split function returned an unchanged result")
1930 split_line(l, line_length=line_length, inner=True, py36=py36)
1932 except CannotSplit as cs:
1943 def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
1944 """Split line into many lines, starting with the first matching bracket pair.
1946 Note: this usually looks weird, only use this for function definitions.
1947 Prefer RHS otherwise. This is why this function is not symmetrical with
1948 :func:`right_hand_split` which also handles optional parentheses.
1950 head = Line(depth=line.depth)
1951 body = Line(depth=line.depth + 1, inside_brackets=True)
1952 tail = Line(depth=line.depth)
1953 tail_leaves: List[Leaf] = []
1954 body_leaves: List[Leaf] = []
1955 head_leaves: List[Leaf] = []
1956 current_leaves = head_leaves
1957 matching_bracket = None
1958 for leaf in line.leaves:
1960 current_leaves is body_leaves
1961 and leaf.type in CLOSING_BRACKETS
1962 and leaf.opening_bracket is matching_bracket
1964 current_leaves = tail_leaves if body_leaves else head_leaves
1965 current_leaves.append(leaf)
1966 if current_leaves is head_leaves:
1967 if leaf.type in OPENING_BRACKETS:
1968 matching_bracket = leaf
1969 current_leaves = body_leaves
1970 # Since body is a new indent level, remove spurious leading whitespace.
1972 normalize_prefix(body_leaves[0], inside_brackets=True)
1973 # Build the new lines.
1974 for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
1976 result.append(leaf, preformatted=True)
1977 for comment_after in line.comments_after(leaf):
1978 result.append(comment_after, preformatted=True)
1979 bracket_split_succeeded_or_raise(head, body, tail)
1980 for result in (head, body, tail):
1985 def right_hand_split(
1986 line: Line, line_length: int, py36: bool = False, omit: Collection[LeafID] = ()
1987 ) -> Iterator[Line]:
1988 """Split line into many lines, starting with the last matching bracket pair.
1990 If the split was by optional parentheses, attempt splitting without them, too.
1991 `omit` is a collection of closing bracket IDs that shouldn't be considered for
1994 Note: running this function modifies `bracket_depth` on the leaves of `line`.
1996 head = Line(depth=line.depth)
1997 body = Line(depth=line.depth + 1, inside_brackets=True)
1998 tail = Line(depth=line.depth)
1999 tail_leaves: List[Leaf] = []
2000 body_leaves: List[Leaf] = []
2001 head_leaves: List[Leaf] = []
2002 current_leaves = tail_leaves
2003 opening_bracket = None
2004 closing_bracket = None
2005 for leaf in reversed(line.leaves):
2006 if current_leaves is body_leaves:
2007 if leaf is opening_bracket:
2008 current_leaves = head_leaves if body_leaves else tail_leaves
2009 current_leaves.append(leaf)
2010 if current_leaves is tail_leaves:
2011 if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
2012 opening_bracket = leaf.opening_bracket
2013 closing_bracket = leaf
2014 current_leaves = body_leaves
2015 tail_leaves.reverse()
2016 body_leaves.reverse()
2017 head_leaves.reverse()
2018 # Since body is a new indent level, remove spurious leading whitespace.
2020 normalize_prefix(body_leaves[0], inside_brackets=True)
2022 # No `head` means the split failed. Either `tail` has all content or
2023 # the matching `opening_bracket` wasn't available on `line` anymore.
2024 raise CannotSplit("No brackets found")
2026 # Build the new lines.
2027 for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2029 result.append(leaf, preformatted=True)
2030 for comment_after in line.comments_after(leaf):
2031 result.append(comment_after, preformatted=True)
2032 bracket_split_succeeded_or_raise(head, body, tail)
2033 assert opening_bracket and closing_bracket
2035 # the opening bracket is an optional paren
2036 opening_bracket.type == token.LPAR
2037 and not opening_bracket.value
2038 # the closing bracket is an optional paren
2039 and closing_bracket.type == token.RPAR
2040 and not closing_bracket.value
2041 # there are no standalone comments in the body
2042 and not line.contains_standalone_comments(0)
2043 # and it's not an import (optional parens are the only thing we can split
2044 # on in this case; attempting a split without them is a waste of time)
2045 and not line.is_import
2047 omit = {id(closing_bracket), *omit}
2048 if can_omit_invisible_parens(body, line_length):
2050 yield from right_hand_split(line, line_length, py36=py36, omit=omit)
2055 ensure_visible(opening_bracket)
2056 ensure_visible(closing_bracket)
2057 body.should_explode = should_explode(body, opening_bracket)
2058 for result in (head, body, tail):
2063 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
2064 """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
2066 Do nothing otherwise.
2068 A left- or right-hand split is based on a pair of brackets. Content before
2069 (and including) the opening bracket is left on one line, content inside the
2070 brackets is put on a separate line, and finally content starting with and
2071 following the closing bracket is put on a separate line.
2073 Those are called `head`, `body`, and `tail`, respectively. If the split
2074 produced the same line (all content in `head`) or ended up with an empty `body`
2075 and the `tail` is just the closing bracket, then it's considered failed.
2077 tail_len = len(str(tail).strip())
2080 raise CannotSplit("Splitting brackets produced the same line")
2084 f"Splitting brackets on an empty body to save "
2085 f"{tail_len} characters is not worth it"
2089 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
2090 """Normalize prefix of the first leaf in every line returned by `split_func`.
2092 This is a decorator over relevant split functions.
2096 def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
2097 for l in split_func(line, py36):
2098 normalize_prefix(l.leaves[0], inside_brackets=True)
2101 return split_wrapper
2104 @dont_increase_indentation
2105 def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
2106 """Split according to delimiters of the highest priority.
2108 If `py36` is True, the split will add trailing commas also in function
2109 signatures that contain `*` and `**`.
2112 last_leaf = line.leaves[-1]
2114 raise CannotSplit("Line empty")
2116 bt = line.bracket_tracker
2118 delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
2120 raise CannotSplit("No delimiters found")
2122 if delimiter_priority == DOT_PRIORITY:
2123 if bt.delimiter_count_with_priority(delimiter_priority) == 1:
2124 raise CannotSplit("Splitting a single attribute from its owner looks wrong")
2126 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2127 lowest_depth = sys.maxsize
2128 trailing_comma_safe = True
2130 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2131 """Append `leaf` to current line or to new line if appending impossible."""
2132 nonlocal current_line
2134 current_line.append_safe(leaf, preformatted=True)
2135 except ValueError as ve:
2138 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2139 current_line.append(leaf)
2141 for index, leaf in enumerate(line.leaves):
2142 yield from append_to_line(leaf)
2144 for comment_after in line.comments_after(leaf, index):
2145 yield from append_to_line(comment_after)
2147 lowest_depth = min(lowest_depth, leaf.bracket_depth)
2148 if leaf.bracket_depth == lowest_depth and is_vararg(
2149 leaf, within=VARARGS_PARENTS
2151 trailing_comma_safe = trailing_comma_safe and py36
2152 leaf_priority = bt.delimiters.get(id(leaf))
2153 if leaf_priority == delimiter_priority:
2156 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2160 and delimiter_priority == COMMA_PRIORITY
2161 and current_line.leaves[-1].type != token.COMMA
2162 and current_line.leaves[-1].type != STANDALONE_COMMENT
2164 current_line.append(Leaf(token.COMMA, ","))
2168 @dont_increase_indentation
2169 def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
2170 """Split standalone comments from the rest of the line."""
2171 if not line.contains_standalone_comments(0):
2172 raise CannotSplit("Line does not have any standalone comments")
2174 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2176 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2177 """Append `leaf` to current line or to new line if appending impossible."""
2178 nonlocal current_line
2180 current_line.append_safe(leaf, preformatted=True)
2181 except ValueError as ve:
2184 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2185 current_line.append(leaf)
2187 for index, leaf in enumerate(line.leaves):
2188 yield from append_to_line(leaf)
2190 for comment_after in line.comments_after(leaf, index):
2191 yield from append_to_line(comment_after)
2197 def is_import(leaf: Leaf) -> bool:
2198 """Return True if the given leaf starts an import statement."""
2205 (v == "import" and p and p.type == syms.import_name)
2206 or (v == "from" and p and p.type == syms.import_from)
2211 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
2212 """Leave existing extra newlines if not `inside_brackets`. Remove everything
2215 Note: don't use backslashes for formatting or you'll lose your voting rights.
2217 if not inside_brackets:
2218 spl = leaf.prefix.split("#")
2219 if "\\" not in spl[0]:
2220 nl_count = spl[-1].count("\n")
2223 leaf.prefix = "\n" * nl_count
2229 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
2230 """Make all string prefixes lowercase.
2232 If remove_u_prefix is given, also removes any u prefix from the string.
2234 Note: Mutates its argument.
2236 match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
2237 assert match is not None, f"failed to match string {leaf.value!r}"
2238 orig_prefix = match.group(1)
2239 new_prefix = orig_prefix.lower()
2241 new_prefix = new_prefix.replace("u", "")
2242 leaf.value = f"{new_prefix}{match.group(2)}"
2245 def normalize_string_quotes(leaf: Leaf) -> None:
2246 """Prefer double quotes but only if it doesn't cause more escaping.
2248 Adds or removes backslashes as appropriate. Doesn't parse and fix
2249 strings nested in f-strings (yet).
2251 Note: Mutates its argument.
2253 value = leaf.value.lstrip("furbFURB")
2254 if value[:3] == '"""':
2257 elif value[:3] == "'''":
2260 elif value[0] == '"':
2266 first_quote_pos = leaf.value.find(orig_quote)
2267 if first_quote_pos == -1:
2268 return # There's an internal error
2270 prefix = leaf.value[:first_quote_pos]
2271 unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
2272 escaped_new_quote = re.compile(rf"([^\\]|^)\\(\\\\)*{new_quote}")
2273 escaped_orig_quote = re.compile(rf"([^\\]|^)\\(\\\\)*{orig_quote}")
2274 body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
2275 if "r" in prefix.casefold():
2276 if unescaped_new_quote.search(body):
2277 # There's at least one unescaped new_quote in this raw string
2278 # so converting is impossible
2281 # Do not introduce or remove backslashes in raw strings
2284 # remove unnecessary quotes
2285 new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
2286 if body != new_body:
2287 # Consider the string without unnecessary quotes as the original
2289 leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
2290 new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
2291 new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
2292 if new_quote == '"""' and new_body[-1] == '"':
2294 new_body = new_body[:-1] + '\\"'
2295 orig_escape_count = body.count("\\")
2296 new_escape_count = new_body.count("\\")
2297 if new_escape_count > orig_escape_count:
2298 return # Do not introduce more escaping
2300 if new_escape_count == orig_escape_count and orig_quote == '"':
2301 return # Prefer double quotes
2303 leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
2306 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
2307 """Make existing optional parentheses invisible or create new ones.
2309 `parens_after` is a set of string leaf values immeditely after which parens
2312 Standardizes on visible parentheses for single-element tuples, and keeps
2313 existing visible parentheses for other tuples and generator expressions.
2316 list(generate_comments(node))
2318 return # This `node` has a prefix with `# fmt: off`, don't mess with parens.
2321 for index, child in enumerate(list(node.children)):
2323 if child.type == syms.atom:
2324 maybe_make_parens_invisible_in_atom(child)
2325 elif is_one_tuple(child):
2326 # wrap child in visible parentheses
2327 lpar = Leaf(token.LPAR, "(")
2328 rpar = Leaf(token.RPAR, ")")
2330 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2331 elif node.type == syms.import_from:
2332 # "import from" nodes store parentheses directly as part of
2334 if child.type == token.LPAR:
2335 # make parentheses invisible
2336 child.value = "" # type: ignore
2337 node.children[-1].value = "" # type: ignore
2338 elif child.type != token.STAR:
2339 # insert invisible parentheses
2340 node.insert_child(index, Leaf(token.LPAR, ""))
2341 node.append_child(Leaf(token.RPAR, ""))
2344 elif not (isinstance(child, Leaf) and is_multiline_string(child)):
2345 # wrap child in invisible parentheses
2346 lpar = Leaf(token.LPAR, "")
2347 rpar = Leaf(token.RPAR, "")
2348 index = child.remove() or 0
2349 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2351 check_lpar = isinstance(child, Leaf) and child.value in parens_after
2354 def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
2355 """If it's safe, make the parens in the atom `node` invisible, recusively."""
2357 node.type != syms.atom
2358 or is_empty_tuple(node)
2359 or is_one_tuple(node)
2361 or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
2365 first = node.children[0]
2366 last = node.children[-1]
2367 if first.type == token.LPAR and last.type == token.RPAR:
2368 # make parentheses invisible
2369 first.value = "" # type: ignore
2370 last.value = "" # type: ignore
2371 if len(node.children) > 1:
2372 maybe_make_parens_invisible_in_atom(node.children[1])
2378 def is_empty_tuple(node: LN) -> bool:
2379 """Return True if `node` holds an empty tuple."""
2381 node.type == syms.atom
2382 and len(node.children) == 2
2383 and node.children[0].type == token.LPAR
2384 and node.children[1].type == token.RPAR
2388 def is_one_tuple(node: LN) -> bool:
2389 """Return True if `node` holds a tuple with one element, with or without parens."""
2390 if node.type == syms.atom:
2391 if len(node.children) != 3:
2394 lpar, gexp, rpar = node.children
2396 lpar.type == token.LPAR
2397 and gexp.type == syms.testlist_gexp
2398 and rpar.type == token.RPAR
2402 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
2405 node.type in IMPLICIT_TUPLE
2406 and len(node.children) == 2
2407 and node.children[1].type == token.COMMA
2411 def is_yield(node: LN) -> bool:
2412 """Return True if `node` holds a `yield` or `yield from` expression."""
2413 if node.type == syms.yield_expr:
2416 if node.type == token.NAME and node.value == "yield": # type: ignore
2419 if node.type != syms.atom:
2422 if len(node.children) != 3:
2425 lpar, expr, rpar = node.children
2426 if lpar.type == token.LPAR and rpar.type == token.RPAR:
2427 return is_yield(expr)
2432 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
2433 """Return True if `leaf` is a star or double star in a vararg or kwarg.
2435 If `within` includes VARARGS_PARENTS, this applies to function signatures.
2436 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
2437 extended iterable unpacking (PEP 3132) and additional unpacking
2438 generalizations (PEP 448).
2440 if leaf.type not in STARS or not leaf.parent:
2444 if p.type == syms.star_expr:
2445 # Star expressions are also used as assignment targets in extended
2446 # iterable unpacking (PEP 3132). See what its parent is instead.
2452 return p.type in within
2455 def is_multiline_string(leaf: Leaf) -> bool:
2456 """Return True if `leaf` is a multiline string that actually spans many lines."""
2457 value = leaf.value.lstrip("furbFURB")
2458 return value[:3] in {'"""', "'''"} and "\n" in value
2461 def is_stub_suite(node: Node) -> bool:
2462 """Return True if `node` is a suite with a stub body."""
2464 len(node.children) != 4
2465 or node.children[0].type != token.NEWLINE
2466 or node.children[1].type != token.INDENT
2467 or node.children[3].type != token.DEDENT
2471 return is_stub_body(node.children[2])
2474 def is_stub_body(node: LN) -> bool:
2475 """Return True if `node` is a simple statement containing an ellipsis."""
2476 if not isinstance(node, Node) or node.type != syms.simple_stmt:
2479 if len(node.children) != 2:
2482 child = node.children[0]
2484 child.type == syms.atom
2485 and len(child.children) == 3
2486 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
2490 def max_delimiter_priority_in_atom(node: LN) -> int:
2491 """Return maximum delimiter priority inside `node`.
2493 This is specific to atoms with contents contained in a pair of parentheses.
2494 If `node` isn't an atom or there are no enclosing parentheses, returns 0.
2496 if node.type != syms.atom:
2499 first = node.children[0]
2500 last = node.children[-1]
2501 if not (first.type == token.LPAR and last.type == token.RPAR):
2504 bt = BracketTracker()
2505 for c in node.children[1:-1]:
2506 if isinstance(c, Leaf):
2509 for leaf in c.leaves():
2512 return bt.max_delimiter_priority()
2518 def ensure_visible(leaf: Leaf) -> None:
2519 """Make sure parentheses are visible.
2521 They could be invisible as part of some statements (see
2522 :func:`normalize_invible_parens` and :func:`visit_import_from`).
2524 if leaf.type == token.LPAR:
2526 elif leaf.type == token.RPAR:
2530 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
2531 """Should `line` immediately be split with `delimiter_split()` after RHS?"""
2533 opening_bracket.parent
2534 and opening_bracket.parent.type in {syms.atom, syms.import_from}
2535 and opening_bracket.value in "[{("
2540 last_leaf = line.leaves[-1]
2541 exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
2542 max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
2543 except (IndexError, ValueError):
2546 return max_priority == COMMA_PRIORITY
2549 def is_python36(node: Node) -> bool:
2550 """Return True if the current file is using Python 3.6+ features.
2552 Currently looking for:
2554 - trailing commas after * or ** in function signatures and calls.
2556 for n in node.pre_order():
2557 if n.type == token.STRING:
2558 value_head = n.value[:2] # type: ignore
2559 if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
2563 n.type in {syms.typedargslist, syms.arglist}
2565 and n.children[-1].type == token.COMMA
2567 for ch in n.children:
2568 if ch.type in STARS:
2571 if ch.type == syms.argument:
2572 for argch in ch.children:
2573 if argch.type in STARS:
2579 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
2580 """Generate sets of closing bracket IDs that should be omitted in a RHS.
2582 Brackets can be omitted if the entire trailer up to and including
2583 a preceding closing bracket fits in one line.
2585 Yielded sets are cumulative (contain results of previous yields, too). First
2589 omit: Set[LeafID] = set()
2592 length = 4 * line.depth
2593 opening_bracket = None
2594 closing_bracket = None
2595 optional_brackets: Set[LeafID] = set()
2596 inner_brackets: Set[LeafID] = set()
2597 for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
2598 length += leaf_length
2599 if length > line_length:
2602 if leaf.type == STANDALONE_COMMENT:
2605 optional_brackets.discard(id(leaf))
2607 if leaf is opening_bracket:
2608 opening_bracket = None
2609 elif leaf.type in CLOSING_BRACKETS:
2610 inner_brackets.add(id(leaf))
2611 elif leaf.type in CLOSING_BRACKETS:
2613 optional_brackets.add(id(opening_bracket))
2616 if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
2617 # Empty brackets would fail a split so treat them as "inner"
2618 # brackets (e.g. only add them to the `omit` set if another
2619 # pair of brackets was good enough.
2620 inner_brackets.add(id(leaf))
2623 opening_bracket = leaf.opening_bracket
2625 omit.add(id(closing_bracket))
2626 omit.update(inner_brackets)
2627 inner_brackets.clear()
2629 closing_bracket = leaf
2632 def get_future_imports(node: Node) -> Set[str]:
2633 """Return a set of __future__ imports in the file."""
2635 for child in node.children:
2636 if child.type != syms.simple_stmt:
2638 first_child = child.children[0]
2639 if isinstance(first_child, Leaf):
2640 # Continue looking if we see a docstring; otherwise stop.
2642 len(child.children) == 2
2643 and first_child.type == token.STRING
2644 and child.children[1].type == token.NEWLINE
2649 elif first_child.type == syms.import_from:
2650 module_name = first_child.children[1]
2651 if not isinstance(module_name, Leaf) or module_name.value != "__future__":
2653 for import_from_child in first_child.children[3:]:
2654 if isinstance(import_from_child, Leaf):
2655 if import_from_child.type == token.NAME:
2656 imports.add(import_from_child.value)
2658 assert import_from_child.type == syms.import_as_names
2659 for leaf in import_from_child.children:
2660 if isinstance(leaf, Leaf) and leaf.type == token.NAME:
2661 imports.add(leaf.value)
2667 PYTHON_EXTENSIONS = {".py", ".pyi"}
2668 BLACKLISTED_DIRECTORIES = {
2681 def gen_python_files_in_dir(path: Path) -> Iterator[Path]:
2682 """Generate all files under `path` which aren't under BLACKLISTED_DIRECTORIES
2683 and have one of the PYTHON_EXTENSIONS.
2685 for child in path.iterdir():
2687 if child.name in BLACKLISTED_DIRECTORIES:
2690 yield from gen_python_files_in_dir(child)
2692 elif child.is_file() and child.suffix in PYTHON_EXTENSIONS:
2698 """Provides a reformatting counter. Can be rendered with `str(report)`."""
2701 change_count: int = 0
2703 failure_count: int = 0
2705 def done(self, src: Path, changed: Changed) -> None:
2706 """Increment the counter for successful reformatting. Write out a message."""
2707 if changed is Changed.YES:
2708 reformatted = "would reformat" if self.check else "reformatted"
2710 out(f"{reformatted} {src}")
2711 self.change_count += 1
2714 if changed is Changed.NO:
2715 msg = f"{src} already well formatted, good job."
2717 msg = f"{src} wasn't modified on disk since last run."
2718 out(msg, bold=False)
2719 self.same_count += 1
2721 def failed(self, src: Path, message: str) -> None:
2722 """Increment the counter for failed reformatting. Write out a message."""
2723 err(f"error: cannot format {src}: {message}")
2724 self.failure_count += 1
2727 def return_code(self) -> int:
2728 """Return the exit code that the app should use.
2730 This considers the current state of changed files and failures:
2731 - if there were any failures, return 123;
2732 - if any files were changed and --check is being used, return 1;
2733 - otherwise return 0.
2735 # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
2736 # 126 we have special returncodes reserved by the shell.
2737 if self.failure_count:
2740 elif self.change_count and self.check:
2745 def __str__(self) -> str:
2746 """Render a color report of the current state.
2748 Use `click.unstyle` to remove colors.
2751 reformatted = "would be reformatted"
2752 unchanged = "would be left unchanged"
2753 failed = "would fail to reformat"
2755 reformatted = "reformatted"
2756 unchanged = "left unchanged"
2757 failed = "failed to reformat"
2759 if self.change_count:
2760 s = "s" if self.change_count > 1 else ""
2762 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
2765 s = "s" if self.same_count > 1 else ""
2766 report.append(f"{self.same_count} file{s} {unchanged}")
2767 if self.failure_count:
2768 s = "s" if self.failure_count > 1 else ""
2770 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
2772 return ", ".join(report) + "."
2775 def assert_equivalent(src: str, dst: str) -> None:
2776 """Raise AssertionError if `src` and `dst` aren't equivalent."""
2781 def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
2782 """Simple visitor generating strings to compare ASTs by content."""
2783 yield f"{' ' * depth}{node.__class__.__name__}("
2785 for field in sorted(node._fields):
2787 value = getattr(node, field)
2788 except AttributeError:
2791 yield f"{' ' * (depth+1)}{field}="
2793 if isinstance(value, list):
2795 if isinstance(item, ast.AST):
2796 yield from _v(item, depth + 2)
2798 elif isinstance(value, ast.AST):
2799 yield from _v(value, depth + 2)
2802 yield f"{' ' * (depth+2)}{value!r}, # {value.__class__.__name__}"
2804 yield f"{' ' * depth}) # /{node.__class__.__name__}"
2807 src_ast = ast.parse(src)
2808 except Exception as exc:
2809 major, minor = sys.version_info[:2]
2810 raise AssertionError(
2811 f"cannot use --safe with this file; failed to parse source file "
2812 f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
2813 f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
2817 dst_ast = ast.parse(dst)
2818 except Exception as exc:
2819 log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
2820 raise AssertionError(
2821 f"INTERNAL ERROR: Black produced invalid code: {exc}. "
2822 f"Please report a bug on https://github.com/ambv/black/issues. "
2823 f"This invalid output might be helpful: {log}"
2826 src_ast_str = "\n".join(_v(src_ast))
2827 dst_ast_str = "\n".join(_v(dst_ast))
2828 if src_ast_str != dst_ast_str:
2829 log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
2830 raise AssertionError(
2831 f"INTERNAL ERROR: Black produced code that is not equivalent to "
2833 f"Please report a bug on https://github.com/ambv/black/issues. "
2834 f"This diff might be helpful: {log}"
2838 def assert_stable(src: str, dst: str, line_length: int, is_pyi: bool = False) -> None:
2839 """Raise AssertionError if `dst` reformats differently the second time."""
2840 newdst = format_str(dst, line_length=line_length, is_pyi=is_pyi)
2843 diff(src, dst, "source", "first pass"),
2844 diff(dst, newdst, "first pass", "second pass"),
2846 raise AssertionError(
2847 f"INTERNAL ERROR: Black produced different code on the second pass "
2848 f"of the formatter. "
2849 f"Please report a bug on https://github.com/ambv/black/issues. "
2850 f"This diff might be helpful: {log}"
2854 def dump_to_file(*output: str) -> str:
2855 """Dump `output` to a temporary file. Return path to the file."""
2858 with tempfile.NamedTemporaryFile(
2859 mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
2861 for lines in output:
2863 if lines and lines[-1] != "\n":
2868 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
2869 """Return a unified diff string between strings `a` and `b`."""
2872 a_lines = [line + "\n" for line in a.split("\n")]
2873 b_lines = [line + "\n" for line in b.split("\n")]
2875 difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
2879 def cancel(tasks: Iterable[asyncio.Task]) -> None:
2880 """asyncio signal handler that cancels all `tasks` and reports to stderr."""
2886 def shutdown(loop: BaseEventLoop) -> None:
2887 """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
2889 # This part is borrowed from asyncio/runners.py in Python 3.7b2.
2890 to_cancel = [task for task in asyncio.Task.all_tasks(loop) if not task.done()]
2894 for task in to_cancel:
2896 loop.run_until_complete(
2897 asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
2900 # `concurrent.futures.Future` objects cannot be cancelled once they
2901 # are already running. There might be some when the `shutdown()` happened.
2902 # Silence their logger's spew about the event loop being closed.
2903 cf_logger = logging.getLogger("concurrent.futures")
2904 cf_logger.setLevel(logging.CRITICAL)
2908 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
2909 """Replace `regex` with `replacement` twice on `original`.
2911 This is used by string normalization to perform replaces on
2912 overlapping matches.
2914 return regex.sub(replacement, regex.sub(replacement, original))
2917 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
2918 """Like `reversed(enumerate(sequence))` if that were possible."""
2919 index = len(sequence) - 1
2920 for element in reversed(sequence):
2921 yield (index, element)
2925 def enumerate_with_length(
2926 line: Line, reversed: bool = False
2927 ) -> Iterator[Tuple[Index, Leaf, int]]:
2928 """Return an enumeration of leaves with their length.
2930 Stops prematurely on multiline strings and standalone comments.
2933 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
2934 enumerate_reversed if reversed else enumerate,
2936 for index, leaf in op(line.leaves):
2937 length = len(leaf.prefix) + len(leaf.value)
2938 if "\n" in leaf.value:
2939 return # Multiline strings, we can't continue.
2941 comment: Optional[Leaf]
2942 for comment in line.comments_after(leaf, index):
2943 if "\n" in comment.prefix:
2944 return # Oops, standalone comment!
2946 length += len(comment.value)
2948 yield index, leaf, length
2951 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
2952 """Return True if `line` is no longer than `line_length`.
2954 Uses the provided `line_str` rendering, if any, otherwise computes a new one.
2957 line_str = str(line).strip("\n")
2959 len(line_str) <= line_length
2960 and "\n" not in line_str # multiline strings
2961 and not line.contains_standalone_comments()
2965 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
2966 """Does `line` have a shape safe to reformat without optional parens around it?
2968 Returns True for only a subset of potentially nice looking formattings but
2969 the point is to not return false positives that end up producing lines that
2972 bt = line.bracket_tracker
2973 if not bt.delimiters:
2974 # Without delimiters the optional parentheses are useless.
2977 max_priority = bt.max_delimiter_priority()
2978 if bt.delimiter_count_with_priority(max_priority) > 1:
2979 # With more than one delimiter of a kind the optional parentheses read better.
2982 if max_priority == DOT_PRIORITY:
2983 # A single stranded method call doesn't require optional parentheses.
2986 assert len(line.leaves) >= 2, "Stranded delimiter"
2988 first = line.leaves[0]
2989 second = line.leaves[1]
2990 penultimate = line.leaves[-2]
2991 last = line.leaves[-1]
2993 # With a single delimiter, omit if the expression starts or ends with
2995 if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
2997 length = 4 * line.depth
2998 for _index, leaf, leaf_length in enumerate_with_length(line):
2999 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
3002 length += leaf_length
3003 if length > line_length:
3006 if leaf.type in OPENING_BRACKETS:
3007 # There are brackets we can further split on.
3011 # checked the entire string and line length wasn't exceeded
3012 if len(line.leaves) == _index + 1:
3015 # Note: we are not returning False here because a line might have *both*
3016 # a leading opening bracket and a trailing closing bracket. If the
3017 # opening bracket doesn't match our rule, maybe the closing will.
3020 last.type == token.RPAR
3021 or last.type == token.RBRACE
3023 # don't use indexing for omitting optional parentheses;
3025 last.type == token.RSQB
3027 and last.parent.type != syms.trailer
3030 if penultimate.type in OPENING_BRACKETS:
3031 # Empty brackets don't help.
3034 if is_multiline_string(first):
3035 # Additional wrapping of a multiline string in this situation is
3039 length = 4 * line.depth
3040 seen_other_brackets = False
3041 for _index, leaf, leaf_length in enumerate_with_length(line):
3042 length += leaf_length
3043 if leaf is last.opening_bracket:
3044 if seen_other_brackets or length <= line_length:
3047 elif leaf.type in OPENING_BRACKETS:
3048 # There are brackets we can further split on.
3049 seen_other_brackets = True
3054 def get_cache_file(line_length: int) -> Path:
3055 return CACHE_DIR / f"cache.{line_length}.pickle"
3058 def read_cache(line_length: int) -> Cache:
3059 """Read the cache if it exists and is well formed.
3061 If it is not well formed, the call to write_cache later should resolve the issue.
3063 cache_file = get_cache_file(line_length)
3064 if not cache_file.exists():
3067 with cache_file.open("rb") as fobj:
3069 cache: Cache = pickle.load(fobj)
3070 except pickle.UnpicklingError:
3076 def get_cache_info(path: Path) -> CacheInfo:
3077 """Return the information used to check if a file is already formatted or not."""
3079 return stat.st_mtime, stat.st_size
3083 cache: Cache, sources: Iterable[Path]
3084 ) -> Tuple[List[Path], List[Path]]:
3085 """Split a list of paths into two.
3087 The first list contains paths of files that modified on disk or are not in the
3088 cache. The other list contains paths to non-modified files.
3093 if cache.get(src) != get_cache_info(src):
3100 def write_cache(cache: Cache, sources: List[Path], line_length: int) -> None:
3101 """Update the cache file."""
3102 cache_file = get_cache_file(line_length)
3104 if not CACHE_DIR.exists():
3105 CACHE_DIR.mkdir(parents=True)
3106 new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
3107 with cache_file.open("wb") as fobj:
3108 pickle.dump(new_cache, fobj, protocol=pickle.HIGHEST_PROTOCOL)
3113 if __name__ == "__main__":