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 "Don't write the files back, just return the status. Return code 0 "
150 "means nothing would change. Return code 1 means some files would be "
151 "reformatted. Return code 123 means there was an internal error."
157 help="Don't write the files back, just output a diff for each file on stdout.",
162 help="If --fast given, skip temporary sanity checks. [default: --safe]",
169 "Don't emit non-error messages to stderr. Errors are still emitted, "
170 "silence those with 2>/dev/null."
177 "Consider all input files typing stubs regardless of file extension "
178 "(useful when piping source on standard input)."
185 "Allow using Python 3.6-only syntax on all input files. This will put "
186 "trailing commas in function signatures and calls also after *args and "
187 "**kwargs. [default: per-file auto-detection]"
192 "--skip-string-normalization",
194 help="Don't normalize string quotes or prefixes.",
199 default=DEFAULT_INCLUDES,
201 "A regular expression that matches files and directories that should be "
202 "included on recursive searches. On Windows, use forward slashes for "
210 default=DEFAULT_EXCLUDES,
212 "A regular expression that matches files and directories that should be "
213 "excluded on recursive searches. On Windows, use forward slashes for "
218 @click.version_option(version=__version__)
223 exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
235 skip_string_normalization: bool,
241 """The uncompromising code formatter."""
242 sources: List[Path] = []
244 include_regex = re.compile(include)
246 err(f"Invalid regular expression for include given: {include!r}")
249 exclude_regex = re.compile(exclude)
251 err(f"Invalid regular expression for exclude given: {exclude!r}")
256 sources.extend(gen_python_files_in_dir(p, include_regex, exclude_regex))
258 # if a file was explicitly given, we don't care about its extension
261 sources.append(Path("-"))
263 err(f"invalid path: {s}")
265 if check and not diff:
266 write_back = WriteBack.NO
268 write_back = WriteBack.DIFF
270 write_back = WriteBack.YES
271 mode = FileMode.AUTO_DETECT
273 mode |= FileMode.PYTHON36
276 if skip_string_normalization:
277 mode |= FileMode.NO_STRING_NORMALIZATION
278 report = Report(check=check, quiet=quiet)
279 if len(sources) == 0:
280 out("No paths given. Nothing to do 😴")
284 elif len(sources) == 1:
287 line_length=line_length,
289 write_back=write_back,
294 loop = asyncio.get_event_loop()
295 executor = ProcessPoolExecutor(max_workers=os.cpu_count())
297 loop.run_until_complete(
300 line_length=line_length,
302 write_back=write_back,
312 out("All done! ✨ 🍰 ✨")
313 click.echo(str(report))
314 ctx.exit(report.return_code)
321 write_back: WriteBack,
325 """Reformat a single file under `src` without spawning child processes.
327 If `quiet` is True, non-error messages are not output. `line_length`,
328 `write_back`, `fast` and `pyi` options are passed to
329 :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
333 if not src.is_file() and str(src) == "-":
334 if format_stdin_to_stdout(
335 line_length=line_length, fast=fast, write_back=write_back, mode=mode
337 changed = Changed.YES
340 if write_back != WriteBack.DIFF:
341 cache = read_cache(line_length, mode)
343 if src in cache and cache[src] == get_cache_info(src):
344 changed = Changed.CACHED
345 if changed is not Changed.CACHED and format_file_in_place(
347 line_length=line_length,
349 write_back=write_back,
352 changed = Changed.YES
353 if write_back == WriteBack.YES and changed is not Changed.NO:
354 write_cache(cache, [src], line_length, mode)
355 report.done(src, changed)
356 except Exception as exc:
357 report.failed(src, str(exc))
360 async def schedule_formatting(
364 write_back: WriteBack,
370 """Run formatting of `sources` in parallel using the provided `executor`.
372 (Use ProcessPoolExecutors for actual parallelism.)
374 `line_length`, `write_back`, `fast`, and `pyi` options are passed to
375 :func:`format_file_in_place`.
378 if write_back != WriteBack.DIFF:
379 cache = read_cache(line_length, mode)
380 sources, cached = filter_cached(cache, sources)
382 report.done(src, Changed.CACHED)
387 if write_back == WriteBack.DIFF:
388 # For diff output, we need locks to ensure we don't interleave output
389 # from different processes.
391 lock = manager.Lock()
393 loop.run_in_executor(
395 format_file_in_place,
403 for src in sorted(sources)
405 pending: Iterable[asyncio.Task] = tasks.keys()
407 loop.add_signal_handler(signal.SIGINT, cancel, pending)
408 loop.add_signal_handler(signal.SIGTERM, cancel, pending)
409 except NotImplementedError:
410 # There are no good alternatives for these on Windows
413 done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
415 src = tasks.pop(task)
417 cancelled.append(task)
418 elif task.exception():
419 report.failed(src, str(task.exception()))
421 formatted.append(src)
422 report.done(src, Changed.YES if task.result() else Changed.NO)
424 await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
425 if write_back == WriteBack.YES and formatted:
426 write_cache(cache, formatted, line_length, mode)
429 def format_file_in_place(
433 write_back: WriteBack = WriteBack.NO,
434 mode: FileMode = FileMode.AUTO_DETECT,
435 lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
437 """Format file under `src` path. Return True if changed.
439 If `write_back` is True, write reformatted code back to stdout.
440 `line_length` and `fast` options are passed to :func:`format_file_contents`.
442 if src.suffix == ".pyi":
444 with tokenize.open(src) as src_buffer:
445 src_contents = src_buffer.read()
447 dst_contents = format_file_contents(
448 src_contents, line_length=line_length, fast=fast, mode=mode
450 except NothingChanged:
453 if write_back == write_back.YES:
454 with open(src, "w", encoding=src_buffer.encoding) as f:
455 f.write(dst_contents)
456 elif write_back == write_back.DIFF:
457 src_name = f"{src} (original)"
458 dst_name = f"{src} (formatted)"
459 diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
463 sys.stdout.write(diff_contents)
470 def format_stdin_to_stdout(
473 write_back: WriteBack = WriteBack.NO,
474 mode: FileMode = FileMode.AUTO_DETECT,
476 """Format file on stdin. Return True if changed.
478 If `write_back` is True, write reformatted code back to stdout.
479 `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
480 :func:`format_file_contents`.
482 src = sys.stdin.read()
485 dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode)
488 except NothingChanged:
492 if write_back == WriteBack.YES:
493 sys.stdout.write(dst)
494 elif write_back == WriteBack.DIFF:
495 src_name = "<stdin> (original)"
496 dst_name = "<stdin> (formatted)"
497 sys.stdout.write(diff(src, dst, src_name, dst_name))
500 def format_file_contents(
505 mode: FileMode = FileMode.AUTO_DETECT,
507 """Reformat contents a file and return new contents.
509 If `fast` is False, additionally confirm that the reformatted code is
510 valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
511 `line_length` is passed to :func:`format_str`.
513 if src_contents.strip() == "":
516 dst_contents = format_str(src_contents, line_length=line_length, mode=mode)
517 if src_contents == dst_contents:
521 assert_equivalent(src_contents, dst_contents)
522 assert_stable(src_contents, dst_contents, line_length=line_length, mode=mode)
527 src_contents: str, line_length: int, *, mode: FileMode = FileMode.AUTO_DETECT
529 """Reformat a string and return new contents.
531 `line_length` determines how many characters per line are allowed.
533 src_node = lib2to3_parse(src_contents)
535 future_imports = get_future_imports(src_node)
536 is_pyi = bool(mode & FileMode.PYI)
537 py36 = bool(mode & FileMode.PYTHON36) or is_python36(src_node)
538 normalize_strings = not bool(mode & FileMode.NO_STRING_NORMALIZATION)
539 lines = LineGenerator(
540 remove_u_prefix=py36 or "unicode_literals" in future_imports,
542 normalize_strings=normalize_strings,
544 elt = EmptyLineTracker(is_pyi=is_pyi)
547 for current_line in lines.visit(src_node):
548 for _ in range(after):
549 dst_contents += str(empty_line)
550 before, after = elt.maybe_empty_lines(current_line)
551 for _ in range(before):
552 dst_contents += str(empty_line)
553 for line in split_line(current_line, line_length=line_length, py36=py36):
554 dst_contents += str(line)
559 pygram.python_grammar_no_print_statement_no_exec_statement,
560 pygram.python_grammar_no_print_statement,
561 pygram.python_grammar,
565 def lib2to3_parse(src_txt: str) -> Node:
566 """Given a string with source, return the lib2to3 Node."""
567 grammar = pygram.python_grammar_no_print_statement
568 if src_txt[-1] != "\n":
569 nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
571 for grammar in GRAMMARS:
572 drv = driver.Driver(grammar, pytree.convert)
574 result = drv.parse_string(src_txt, True)
577 except ParseError as pe:
578 lineno, column = pe.context[1]
579 lines = src_txt.splitlines()
581 faulty_line = lines[lineno - 1]
583 faulty_line = "<line number missing in source>"
584 exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}")
588 if isinstance(result, Leaf):
589 result = Node(syms.file_input, [result])
593 def lib2to3_unparse(node: Node) -> str:
594 """Given a lib2to3 node, return its string representation."""
602 class Visitor(Generic[T]):
603 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
605 def visit(self, node: LN) -> Iterator[T]:
606 """Main method to visit `node` and its children.
608 It tries to find a `visit_*()` method for the given `node.type`, like
609 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
610 If no dedicated `visit_*()` method is found, chooses `visit_default()`
613 Then yields objects of type `T` from the selected visitor.
616 name = token.tok_name[node.type]
618 name = type_repr(node.type)
619 yield from getattr(self, f"visit_{name}", self.visit_default)(node)
621 def visit_default(self, node: LN) -> Iterator[T]:
622 """Default `visit_*()` implementation. Recurses to children of `node`."""
623 if isinstance(node, Node):
624 for child in node.children:
625 yield from self.visit(child)
629 class DebugVisitor(Visitor[T]):
632 def visit_default(self, node: LN) -> Iterator[T]:
633 indent = " " * (2 * self.tree_depth)
634 if isinstance(node, Node):
635 _type = type_repr(node.type)
636 out(f"{indent}{_type}", fg="yellow")
638 for child in node.children:
639 yield from self.visit(child)
642 out(f"{indent}/{_type}", fg="yellow", bold=False)
644 _type = token.tok_name.get(node.type, str(node.type))
645 out(f"{indent}{_type}", fg="blue", nl=False)
647 # We don't have to handle prefixes for `Node` objects since
648 # that delegates to the first child anyway.
649 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
650 out(f" {node.value!r}", fg="blue", bold=False)
653 def show(cls, code: str) -> None:
654 """Pretty-print the lib2to3 AST of a given string of `code`.
656 Convenience method for debugging.
658 v: DebugVisitor[None] = DebugVisitor()
659 list(v.visit(lib2to3_parse(code)))
662 KEYWORDS = set(keyword.kwlist)
663 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
664 FLOW_CONTROL = {"return", "raise", "break", "continue"}
675 STANDALONE_COMMENT = 153
676 LOGIC_OPERATORS = {"and", "or"}
701 STARS = {token.STAR, token.DOUBLESTAR}
704 syms.argument, # double star in arglist
705 syms.trailer, # single argument to call
707 syms.varargslist, # lambdas
709 UNPACKING_PARENTS = {
710 syms.atom, # single element of a list or set literal
748 COMPREHENSION_PRIORITY = 20
750 TERNARY_PRIORITY = 16
753 COMPARATOR_PRIORITY = 10
764 token.DOUBLESLASH: 4,
774 class BracketTracker:
775 """Keeps track of brackets on a line."""
778 bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
779 delimiters: Dict[LeafID, Priority] = Factory(dict)
780 previous: Optional[Leaf] = None
781 _for_loop_variable: int = 0
782 _lambda_arguments: int = 0
784 def mark(self, leaf: Leaf) -> None:
785 """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
787 All leaves receive an int `bracket_depth` field that stores how deep
788 within brackets a given leaf is. 0 means there are no enclosing brackets
789 that started on this line.
791 If a leaf is itself a closing bracket, it receives an `opening_bracket`
792 field that it forms a pair with. This is a one-directional link to
793 avoid reference cycles.
795 If a leaf is a delimiter (a token on which Black can split the line if
796 needed) and it's on depth 0, its `id()` is stored in the tracker's
799 if leaf.type == token.COMMENT:
802 self.maybe_decrement_after_for_loop_variable(leaf)
803 self.maybe_decrement_after_lambda_arguments(leaf)
804 if leaf.type in CLOSING_BRACKETS:
806 opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
807 leaf.opening_bracket = opening_bracket
808 leaf.bracket_depth = self.depth
810 delim = is_split_before_delimiter(leaf, self.previous)
811 if delim and self.previous is not None:
812 self.delimiters[id(self.previous)] = delim
814 delim = is_split_after_delimiter(leaf, self.previous)
816 self.delimiters[id(leaf)] = delim
817 if leaf.type in OPENING_BRACKETS:
818 self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
821 self.maybe_increment_lambda_arguments(leaf)
822 self.maybe_increment_for_loop_variable(leaf)
824 def any_open_brackets(self) -> bool:
825 """Return True if there is an yet unmatched open bracket on the line."""
826 return bool(self.bracket_match)
828 def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
829 """Return the highest priority of a delimiter found on the line.
831 Values are consistent with what `is_split_*_delimiter()` return.
832 Raises ValueError on no delimiters.
834 return max(v for k, v in self.delimiters.items() if k not in exclude)
836 def delimiter_count_with_priority(self, priority: int = 0) -> int:
837 """Return the number of delimiters with the given `priority`.
839 If no `priority` is passed, defaults to max priority on the line.
841 if not self.delimiters:
844 priority = priority or self.max_delimiter_priority()
845 return sum(1 for p in self.delimiters.values() if p == priority)
847 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
848 """In a for loop, or comprehension, the variables are often unpacks.
850 To avoid splitting on the comma in this situation, increase the depth of
851 tokens between `for` and `in`.
853 if leaf.type == token.NAME and leaf.value == "for":
855 self._for_loop_variable += 1
860 def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
861 """See `maybe_increment_for_loop_variable` above for explanation."""
862 if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
864 self._for_loop_variable -= 1
869 def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
870 """In a lambda expression, there might be more than one argument.
872 To avoid splitting on the comma in this situation, increase the depth of
873 tokens between `lambda` and `:`.
875 if leaf.type == token.NAME and leaf.value == "lambda":
877 self._lambda_arguments += 1
882 def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
883 """See `maybe_increment_lambda_arguments` above for explanation."""
884 if self._lambda_arguments and leaf.type == token.COLON:
886 self._lambda_arguments -= 1
891 def get_open_lsqb(self) -> Optional[Leaf]:
892 """Return the most recent opening square bracket (if any)."""
893 return self.bracket_match.get((self.depth - 1, token.RSQB))
898 """Holds leaves and comments. Can be printed with `str(line)`."""
901 leaves: List[Leaf] = Factory(list)
902 comments: List[Tuple[Index, Leaf]] = Factory(list)
903 bracket_tracker: BracketTracker = Factory(BracketTracker)
904 inside_brackets: bool = False
905 should_explode: bool = False
907 def append(self, leaf: Leaf, preformatted: bool = False) -> None:
908 """Add a new `leaf` to the end of the line.
910 Unless `preformatted` is True, the `leaf` will receive a new consistent
911 whitespace prefix and metadata applied by :class:`BracketTracker`.
912 Trailing commas are maybe removed, unpacked for loop variables are
913 demoted from being delimiters.
915 Inline comments are put aside.
917 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
921 if token.COLON == leaf.type and self.is_class_paren_empty:
923 if self.leaves and not preformatted:
924 # Note: at this point leaf.prefix should be empty except for
925 # imports, for which we only preserve newlines.
926 leaf.prefix += whitespace(
927 leaf, complex_subscript=self.is_complex_subscript(leaf)
929 if self.inside_brackets or not preformatted:
930 self.bracket_tracker.mark(leaf)
931 self.maybe_remove_trailing_comma(leaf)
932 if not self.append_comment(leaf):
933 self.leaves.append(leaf)
935 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
936 """Like :func:`append()` but disallow invalid standalone comment structure.
938 Raises ValueError when any `leaf` is appended after a standalone comment
939 or when a standalone comment is not the first leaf on the line.
941 if self.bracket_tracker.depth == 0:
943 raise ValueError("cannot append to standalone comments")
945 if self.leaves and leaf.type == STANDALONE_COMMENT:
947 "cannot append standalone comments to a populated line"
950 self.append(leaf, preformatted=preformatted)
953 def is_comment(self) -> bool:
954 """Is this line a standalone comment?"""
955 return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
958 def is_decorator(self) -> bool:
959 """Is this line a decorator?"""
960 return bool(self) and self.leaves[0].type == token.AT
963 def is_import(self) -> bool:
964 """Is this an import line?"""
965 return bool(self) and is_import(self.leaves[0])
968 def is_class(self) -> bool:
969 """Is this line a class definition?"""
972 and self.leaves[0].type == token.NAME
973 and self.leaves[0].value == "class"
977 def is_stub_class(self) -> bool:
978 """Is this line a class definition with a body consisting only of "..."?"""
979 return self.is_class and self.leaves[-3:] == [
980 Leaf(token.DOT, ".") for _ in range(3)
984 def is_def(self) -> bool:
985 """Is this a function definition? (Also returns True for async defs.)"""
987 first_leaf = self.leaves[0]
992 second_leaf: Optional[Leaf] = self.leaves[1]
995 return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
996 first_leaf.type == token.ASYNC
997 and second_leaf is not None
998 and second_leaf.type == token.NAME
999 and second_leaf.value == "def"
1003 def is_class_paren_empty(self) -> bool:
1004 """Is this a class with no base classes but using parentheses?
1006 Those are unnecessary and should be removed.
1010 and len(self.leaves) == 4
1012 and self.leaves[2].type == token.LPAR
1013 and self.leaves[2].value == "("
1014 and self.leaves[3].type == token.RPAR
1015 and self.leaves[3].value == ")"
1019 def is_triple_quoted_string(self) -> bool:
1020 """Is the line a triple quoted string?"""
1023 and self.leaves[0].type == token.STRING
1024 and self.leaves[0].value.startswith(('"""', "'''"))
1027 def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
1028 """If so, needs to be split before emitting."""
1029 for leaf in self.leaves:
1030 if leaf.type == STANDALONE_COMMENT:
1031 if leaf.bracket_depth <= depth_limit:
1036 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1037 """Remove trailing comma if there is one and it's safe."""
1040 and self.leaves[-1].type == token.COMMA
1041 and closing.type in CLOSING_BRACKETS
1045 if closing.type == token.RBRACE:
1046 self.remove_trailing_comma()
1049 if closing.type == token.RSQB:
1050 comma = self.leaves[-1]
1051 if comma.parent and comma.parent.type == syms.listmaker:
1052 self.remove_trailing_comma()
1055 # For parens let's check if it's safe to remove the comma.
1056 # Imports are always safe.
1058 self.remove_trailing_comma()
1061 # Otheriwsse, if the trailing one is the only one, we might mistakenly
1062 # change a tuple into a different type by removing the comma.
1063 depth = closing.bracket_depth + 1
1065 opening = closing.opening_bracket
1066 for _opening_index, leaf in enumerate(self.leaves):
1073 for leaf in self.leaves[_opening_index + 1 :]:
1077 bracket_depth = leaf.bracket_depth
1078 if bracket_depth == depth and leaf.type == token.COMMA:
1080 if leaf.parent and leaf.parent.type == syms.arglist:
1085 self.remove_trailing_comma()
1090 def append_comment(self, comment: Leaf) -> bool:
1091 """Add an inline or standalone comment to the line."""
1093 comment.type == STANDALONE_COMMENT
1094 and self.bracket_tracker.any_open_brackets()
1099 if comment.type != token.COMMENT:
1102 after = len(self.leaves) - 1
1104 comment.type = STANDALONE_COMMENT
1109 self.comments.append((after, comment))
1112 def comments_after(self, leaf: Leaf, _index: int = -1) -> Iterator[Leaf]:
1113 """Generate comments that should appear directly after `leaf`.
1115 Provide a non-negative leaf `_index` to speed up the function.
1118 for _index, _leaf in enumerate(self.leaves):
1125 for index, comment_after in self.comments:
1129 def remove_trailing_comma(self) -> None:
1130 """Remove the trailing comma and moves the comments attached to it."""
1131 comma_index = len(self.leaves) - 1
1132 for i in range(len(self.comments)):
1133 comment_index, comment = self.comments[i]
1134 if comment_index == comma_index:
1135 self.comments[i] = (comma_index - 1, comment)
1138 def is_complex_subscript(self, leaf: Leaf) -> bool:
1139 """Return True iff `leaf` is part of a slice with non-trivial exprs."""
1141 leaf if leaf.type == token.LSQB else self.bracket_tracker.get_open_lsqb()
1143 if open_lsqb is None:
1146 subscript_start = open_lsqb.next_sibling
1148 isinstance(subscript_start, Node)
1149 and subscript_start.type == syms.subscriptlist
1151 subscript_start = child_towards(subscript_start, leaf)
1152 return subscript_start is not None and any(
1153 n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
1156 def __str__(self) -> str:
1157 """Render the line."""
1161 indent = " " * self.depth
1162 leaves = iter(self.leaves)
1163 first = next(leaves)
1164 res = f"{first.prefix}{indent}{first.value}"
1167 for _, comment in self.comments:
1171 def __bool__(self) -> bool:
1172 """Return True if the line has leaves or comments."""
1173 return bool(self.leaves or self.comments)
1176 class UnformattedLines(Line):
1177 """Just like :class:`Line` but stores lines which aren't reformatted."""
1179 def append(self, leaf: Leaf, preformatted: bool = True) -> None:
1180 """Just add a new `leaf` to the end of the lines.
1182 The `preformatted` argument is ignored.
1184 Keeps track of indentation `depth`, which is useful when the user
1185 says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`.
1188 list(generate_comments(leaf))
1189 except FormatOn as f_on:
1190 self.leaves.append(f_on.leaf_from_consumed(leaf))
1193 self.leaves.append(leaf)
1194 if leaf.type == token.INDENT:
1196 elif leaf.type == token.DEDENT:
1199 def __str__(self) -> str:
1200 """Render unformatted lines from leaves which were added with `append()`.
1202 `depth` is not used for indentation in this case.
1208 for leaf in self.leaves:
1212 def append_comment(self, comment: Leaf) -> bool:
1213 """Not implemented in this class. Raises `NotImplementedError`."""
1214 raise NotImplementedError("Unformatted lines don't store comments separately.")
1216 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1217 """Does nothing and returns False."""
1220 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
1221 """Does nothing and returns False."""
1226 class EmptyLineTracker:
1227 """Provides a stateful method that returns the number of potential extra
1228 empty lines needed before and after the currently processed line.
1230 Note: this tracker works on lines that haven't been split yet. It assumes
1231 the prefix of the first leaf consists of optional newlines. Those newlines
1232 are consumed by `maybe_empty_lines()` and included in the computation.
1235 is_pyi: bool = False
1236 previous_line: Optional[Line] = None
1237 previous_after: int = 0
1238 previous_defs: List[int] = Factory(list)
1240 def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1241 """Return the number of extra empty lines before and after the `current_line`.
1243 This is for separating `def`, `async def` and `class` with extra empty
1244 lines (two on module-level).
1246 if isinstance(current_line, UnformattedLines):
1249 before, after = self._maybe_empty_lines(current_line)
1250 before -= self.previous_after
1251 self.previous_after = after
1252 self.previous_line = current_line
1253 return before, after
1255 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1257 if current_line.depth == 0:
1258 max_allowed = 1 if self.is_pyi else 2
1259 if current_line.leaves:
1260 # Consume the first leaf's extra newlines.
1261 first_leaf = current_line.leaves[0]
1262 before = first_leaf.prefix.count("\n")
1263 before = min(before, max_allowed)
1264 first_leaf.prefix = ""
1267 depth = current_line.depth
1268 while self.previous_defs and self.previous_defs[-1] >= depth:
1269 self.previous_defs.pop()
1271 before = 0 if depth else 1
1273 before = 1 if depth else 2
1274 is_decorator = current_line.is_decorator
1275 if is_decorator or current_line.is_def or current_line.is_class:
1276 if not is_decorator:
1277 self.previous_defs.append(depth)
1278 if self.previous_line is None:
1279 # Don't insert empty lines before the first line in the file.
1282 if self.previous_line.is_decorator:
1285 if self.previous_line.depth < current_line.depth and (
1286 self.previous_line.is_class or self.previous_line.is_def
1291 self.previous_line.is_comment
1292 and self.previous_line.depth == current_line.depth
1298 if self.previous_line.depth > current_line.depth:
1300 elif current_line.is_class or self.previous_line.is_class:
1301 if current_line.is_stub_class and self.previous_line.is_stub_class:
1309 if current_line.depth and newlines:
1315 and self.previous_line.is_import
1316 and not current_line.is_import
1317 and depth == self.previous_line.depth
1319 return (before or 1), 0
1323 and self.previous_line.is_class
1324 and current_line.is_triple_quoted_string
1332 class LineGenerator(Visitor[Line]):
1333 """Generates reformatted Line objects. Empty lines are not emitted.
1335 Note: destroys the tree it's visiting by mutating prefixes of its leaves
1336 in ways that will no longer stringify to valid Python code on the tree.
1339 is_pyi: bool = False
1340 normalize_strings: bool = True
1341 current_line: Line = Factory(Line)
1342 remove_u_prefix: bool = False
1344 def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
1347 If the line is empty, only emit if it makes sense.
1348 If the line is too long, split it first and then generate.
1350 If any lines were generated, set up a new current_line.
1352 if not self.current_line:
1353 if self.current_line.__class__ == type:
1354 self.current_line.depth += indent
1356 self.current_line = type(depth=self.current_line.depth + indent)
1357 return # Line is empty, don't emit. Creating a new one unnecessary.
1359 complete_line = self.current_line
1360 self.current_line = type(depth=complete_line.depth + indent)
1363 def visit(self, node: LN) -> Iterator[Line]:
1364 """Main method to visit `node` and its children.
1366 Yields :class:`Line` objects.
1368 if isinstance(self.current_line, UnformattedLines):
1369 # File contained `# fmt: off`
1370 yield from self.visit_unformatted(node)
1373 yield from super().visit(node)
1375 def visit_default(self, node: LN) -> Iterator[Line]:
1376 """Default `visit_*()` implementation. Recurses to children of `node`."""
1377 if isinstance(node, Leaf):
1378 any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
1380 for comment in generate_comments(node):
1381 if any_open_brackets:
1382 # any comment within brackets is subject to splitting
1383 self.current_line.append(comment)
1384 elif comment.type == token.COMMENT:
1385 # regular trailing comment
1386 self.current_line.append(comment)
1387 yield from self.line()
1390 # regular standalone comment
1391 yield from self.line()
1393 self.current_line.append(comment)
1394 yield from self.line()
1396 except FormatOff as f_off:
1397 f_off.trim_prefix(node)
1398 yield from self.line(type=UnformattedLines)
1399 yield from self.visit(node)
1401 except FormatOn as f_on:
1402 # This only happens here if somebody says "fmt: on" multiple
1404 f_on.trim_prefix(node)
1405 yield from self.visit_default(node)
1408 normalize_prefix(node, inside_brackets=any_open_brackets)
1409 if self.normalize_strings and node.type == token.STRING:
1410 normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
1411 normalize_string_quotes(node)
1412 if node.type not in WHITESPACE:
1413 self.current_line.append(node)
1414 yield from super().visit_default(node)
1416 def visit_INDENT(self, node: Node) -> Iterator[Line]:
1417 """Increase indentation level, maybe yield a line."""
1418 # In blib2to3 INDENT never holds comments.
1419 yield from self.line(+1)
1420 yield from self.visit_default(node)
1422 def visit_DEDENT(self, node: Node) -> Iterator[Line]:
1423 """Decrease indentation level, maybe yield a line."""
1424 # The current line might still wait for trailing comments. At DEDENT time
1425 # there won't be any (they would be prefixes on the preceding NEWLINE).
1426 # Emit the line then.
1427 yield from self.line()
1429 # While DEDENT has no value, its prefix may contain standalone comments
1430 # that belong to the current indentation level. Get 'em.
1431 yield from self.visit_default(node)
1433 # Finally, emit the dedent.
1434 yield from self.line(-1)
1437 self, node: Node, keywords: Set[str], parens: Set[str]
1438 ) -> Iterator[Line]:
1439 """Visit a statement.
1441 This implementation is shared for `if`, `while`, `for`, `try`, `except`,
1442 `def`, `with`, `class`, `assert` and assignments.
1444 The relevant Python language `keywords` for a given statement will be
1445 NAME leaves within it. This methods puts those on a separate line.
1447 `parens` holds a set of string leaf values immediately after which
1448 invisible parens should be put.
1450 normalize_invisible_parens(node, parens_after=parens)
1451 for child in node.children:
1452 if child.type == token.NAME and child.value in keywords: # type: ignore
1453 yield from self.line()
1455 yield from self.visit(child)
1457 def visit_suite(self, node: Node) -> Iterator[Line]:
1458 """Visit a suite."""
1459 if self.is_pyi and is_stub_suite(node):
1460 yield from self.visit(node.children[2])
1462 yield from self.visit_default(node)
1464 def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
1465 """Visit a statement without nested statements."""
1466 is_suite_like = node.parent and node.parent.type in STATEMENT
1468 if self.is_pyi and is_stub_body(node):
1469 yield from self.visit_default(node)
1471 yield from self.line(+1)
1472 yield from self.visit_default(node)
1473 yield from self.line(-1)
1476 if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
1477 yield from self.line()
1478 yield from self.visit_default(node)
1480 def visit_async_stmt(self, node: Node) -> Iterator[Line]:
1481 """Visit `async def`, `async for`, `async with`."""
1482 yield from self.line()
1484 children = iter(node.children)
1485 for child in children:
1486 yield from self.visit(child)
1488 if child.type == token.ASYNC:
1491 internal_stmt = next(children)
1492 for child in internal_stmt.children:
1493 yield from self.visit(child)
1495 def visit_decorators(self, node: Node) -> Iterator[Line]:
1496 """Visit decorators."""
1497 for child in node.children:
1498 yield from self.line()
1499 yield from self.visit(child)
1501 def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
1502 """Remove a semicolon and put the other statement on a separate line."""
1503 yield from self.line()
1505 def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
1506 """End of file. Process outstanding comments and end with a newline."""
1507 yield from self.visit_default(leaf)
1508 yield from self.line()
1510 def visit_unformatted(self, node: LN) -> Iterator[Line]:
1511 """Used when file contained a `# fmt: off`."""
1512 if isinstance(node, Node):
1513 for child in node.children:
1514 yield from self.visit(child)
1518 self.current_line.append(node)
1519 except FormatOn as f_on:
1520 f_on.trim_prefix(node)
1521 yield from self.line()
1522 yield from self.visit(node)
1524 if node.type == token.ENDMARKER:
1525 # somebody decided not to put a final `# fmt: on`
1526 yield from self.line()
1528 def __attrs_post_init__(self) -> None:
1529 """You are in a twisty little maze of passages."""
1532 self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
1533 self.visit_if_stmt = partial(
1534 v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
1536 self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
1537 self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
1538 self.visit_try_stmt = partial(
1539 v, keywords={"try", "except", "else", "finally"}, parens=Ø
1541 self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
1542 self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
1543 self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
1544 self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
1545 self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
1546 self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
1547 self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
1548 self.visit_async_funcdef = self.visit_async_stmt
1549 self.visit_decorated = self.visit_decorators
1552 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
1553 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
1554 OPENING_BRACKETS = set(BRACKET.keys())
1555 CLOSING_BRACKETS = set(BRACKET.values())
1556 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
1557 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
1560 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa C901
1561 """Return whitespace prefix if needed for the given `leaf`.
1563 `complex_subscript` signals whether the given leaf is part of a subscription
1564 which has non-trivial arguments, like arithmetic expressions or function calls.
1572 if t in ALWAYS_NO_SPACE:
1575 if t == token.COMMENT:
1578 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
1579 if t == token.COLON and p.type not in {
1586 prev = leaf.prev_sibling
1588 prevp = preceding_leaf(p)
1589 if not prevp or prevp.type in OPENING_BRACKETS:
1592 if t == token.COLON:
1593 if prevp.type == token.COLON:
1596 elif prevp.type != token.COMMA and not complex_subscript:
1601 if prevp.type == token.EQUAL:
1603 if prevp.parent.type in {
1611 elif prevp.parent.type == syms.typedargslist:
1612 # A bit hacky: if the equal sign has whitespace, it means we
1613 # previously found it's a typed argument. So, we're using
1617 elif prevp.type in STARS:
1618 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1621 elif prevp.type == token.COLON:
1622 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
1623 return SPACE if complex_subscript else NO
1627 and prevp.parent.type == syms.factor
1628 and prevp.type in MATH_OPERATORS
1633 prevp.type == token.RIGHTSHIFT
1635 and prevp.parent.type == syms.shift_expr
1636 and prevp.prev_sibling
1637 and prevp.prev_sibling.type == token.NAME
1638 and prevp.prev_sibling.value == "print" # type: ignore
1640 # Python 2 print chevron
1643 elif prev.type in OPENING_BRACKETS:
1646 if p.type in {syms.parameters, syms.arglist}:
1647 # untyped function signatures or calls
1648 if not prev or prev.type != token.COMMA:
1651 elif p.type == syms.varargslist:
1653 if prev and prev.type != token.COMMA:
1656 elif p.type == syms.typedargslist:
1657 # typed function signatures
1661 if t == token.EQUAL:
1662 if prev.type != syms.tname:
1665 elif prev.type == token.EQUAL:
1666 # A bit hacky: if the equal sign has whitespace, it means we
1667 # previously found it's a typed argument. So, we're using that, too.
1670 elif prev.type != token.COMMA:
1673 elif p.type == syms.tname:
1676 prevp = preceding_leaf(p)
1677 if not prevp or prevp.type != token.COMMA:
1680 elif p.type == syms.trailer:
1681 # attributes and calls
1682 if t == token.LPAR or t == token.RPAR:
1687 prevp = preceding_leaf(p)
1688 if not prevp or prevp.type != token.NUMBER:
1691 elif t == token.LSQB:
1694 elif prev.type != token.COMMA:
1697 elif p.type == syms.argument:
1699 if t == token.EQUAL:
1703 prevp = preceding_leaf(p)
1704 if not prevp or prevp.type == token.LPAR:
1707 elif prev.type in {token.EQUAL} | STARS:
1710 elif p.type == syms.decorator:
1714 elif p.type == syms.dotted_name:
1718 prevp = preceding_leaf(p)
1719 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
1722 elif p.type == syms.classdef:
1726 if prev and prev.type == token.LPAR:
1729 elif p.type in {syms.subscript, syms.sliceop}:
1732 assert p.parent is not None, "subscripts are always parented"
1733 if p.parent.type == syms.subscriptlist:
1738 elif not complex_subscript:
1741 elif p.type == syms.atom:
1742 if prev and t == token.DOT:
1743 # dots, but not the first one.
1746 elif p.type == syms.dictsetmaker:
1748 if prev and prev.type == token.DOUBLESTAR:
1751 elif p.type in {syms.factor, syms.star_expr}:
1754 prevp = preceding_leaf(p)
1755 if not prevp or prevp.type in OPENING_BRACKETS:
1758 prevp_parent = prevp.parent
1759 assert prevp_parent is not None
1760 if prevp.type == token.COLON and prevp_parent.type in {
1766 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
1769 elif t == token.NAME or t == token.NUMBER:
1772 elif p.type == syms.import_from:
1774 if prev and prev.type == token.DOT:
1777 elif t == token.NAME:
1781 if prev and prev.type == token.DOT:
1784 elif p.type == syms.sliceop:
1790 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
1791 """Return the first leaf that precedes `node`, if any."""
1793 res = node.prev_sibling
1795 if isinstance(res, Leaf):
1799 return list(res.leaves())[-1]
1808 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
1809 """Return the child of `ancestor` that contains `descendant`."""
1810 node: Optional[LN] = descendant
1811 while node and node.parent != ancestor:
1816 def is_split_after_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1817 """Return the priority of the `leaf` delimiter, given a line break after it.
1819 The delimiter priorities returned here are from those delimiters that would
1820 cause a line break after themselves.
1822 Higher numbers are higher priority.
1824 if leaf.type == token.COMMA:
1825 return COMMA_PRIORITY
1830 def is_split_before_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1831 """Return the priority of the `leaf` delimiter, given a line before after it.
1833 The delimiter priorities returned here are from those delimiters that would
1834 cause a line break before themselves.
1836 Higher numbers are higher priority.
1838 if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1839 # * and ** might also be MATH_OPERATORS but in this case they are not.
1840 # Don't treat them as a delimiter.
1844 leaf.type == token.DOT
1846 and leaf.parent.type not in {syms.import_from, syms.dotted_name}
1847 and (previous is None or previous.type in CLOSING_BRACKETS)
1852 leaf.type in MATH_OPERATORS
1854 and leaf.parent.type not in {syms.factor, syms.star_expr}
1856 return MATH_PRIORITIES[leaf.type]
1858 if leaf.type in COMPARATORS:
1859 return COMPARATOR_PRIORITY
1862 leaf.type == token.STRING
1863 and previous is not None
1864 and previous.type == token.STRING
1866 return STRING_PRIORITY
1868 if leaf.type != token.NAME:
1874 and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
1876 return COMPREHENSION_PRIORITY
1881 and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
1883 return COMPREHENSION_PRIORITY
1885 if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
1886 return TERNARY_PRIORITY
1888 if leaf.value == "is":
1889 return COMPARATOR_PRIORITY
1894 and leaf.parent.type in {syms.comp_op, syms.comparison}
1896 previous is not None
1897 and previous.type == token.NAME
1898 and previous.value == "not"
1901 return COMPARATOR_PRIORITY
1906 and leaf.parent.type == syms.comp_op
1908 previous is not None
1909 and previous.type == token.NAME
1910 and previous.value == "is"
1913 return COMPARATOR_PRIORITY
1915 if leaf.value in LOGIC_OPERATORS and leaf.parent:
1916 return LOGIC_PRIORITY
1921 def generate_comments(leaf: LN) -> Iterator[Leaf]:
1922 """Clean the prefix of the `leaf` and generate comments from it, if any.
1924 Comments in lib2to3 are shoved into the whitespace prefix. This happens
1925 in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
1926 move because it does away with modifying the grammar to include all the
1927 possible places in which comments can be placed.
1929 The sad consequence for us though is that comments don't "belong" anywhere.
1930 This is why this function generates simple parentless Leaf objects for
1931 comments. We simply don't know what the correct parent should be.
1933 No matter though, we can live without this. We really only need to
1934 differentiate between inline and standalone comments. The latter don't
1935 share the line with any code.
1937 Inline comments are emitted as regular token.COMMENT leaves. Standalone
1938 are emitted with a fake STANDALONE_COMMENT token identifier.
1949 for index, line in enumerate(p.split("\n")):
1950 consumed += len(line) + 1 # adding the length of the split '\n'
1951 line = line.lstrip()
1954 if not line.startswith("#"):
1957 if index == 0 and leaf.type != token.ENDMARKER:
1958 comment_type = token.COMMENT # simple trailing comment
1960 comment_type = STANDALONE_COMMENT
1961 comment = make_comment(line)
1962 yield Leaf(comment_type, comment, prefix="\n" * nlines)
1964 if comment in {"# fmt: on", "# yapf: enable"}:
1965 raise FormatOn(consumed)
1967 if comment in {"# fmt: off", "# yapf: disable"}:
1968 if comment_type == STANDALONE_COMMENT:
1969 raise FormatOff(consumed)
1971 prev = preceding_leaf(leaf)
1972 if not prev or prev.type in WHITESPACE: # standalone comment in disguise
1973 raise FormatOff(consumed)
1978 def make_comment(content: str) -> str:
1979 """Return a consistently formatted comment from the given `content` string.
1981 All comments (except for "##", "#!", "#:") should have a single space between
1982 the hash sign and the content.
1984 If `content` didn't start with a hash sign, one is provided.
1986 content = content.rstrip()
1990 if content[0] == "#":
1991 content = content[1:]
1992 if content and content[0] not in " !:#":
1993 content = " " + content
1994 return "#" + content
1998 line: Line, line_length: int, inner: bool = False, py36: bool = False
1999 ) -> Iterator[Line]:
2000 """Split a `line` into potentially many lines.
2002 They should fit in the allotted `line_length` but might not be able to.
2003 `inner` signifies that there were a pair of brackets somewhere around the
2004 current `line`, possibly transitively. This means we can fallback to splitting
2005 by delimiters if the LHS/RHS don't yield any results.
2007 If `py36` is True, splitting may generate syntax that is only compatible
2008 with Python 3.6 and later.
2010 if isinstance(line, UnformattedLines) or line.is_comment:
2014 line_str = str(line).strip("\n")
2015 if not line.should_explode and is_line_short_enough(
2016 line, line_length=line_length, line_str=line_str
2021 split_funcs: List[SplitFunc]
2023 split_funcs = [left_hand_split]
2026 def rhs(line: Line, py36: bool = False) -> Iterator[Line]:
2027 for omit in generate_trailers_to_omit(line, line_length):
2028 lines = list(right_hand_split(line, line_length, py36, omit=omit))
2029 if is_line_short_enough(lines[0], line_length=line_length):
2033 # All splits failed, best effort split with no omits.
2034 # This mostly happens to multiline strings that are by definition
2035 # reported as not fitting a single line.
2036 yield from right_hand_split(line, py36)
2038 if line.inside_brackets:
2039 split_funcs = [delimiter_split, standalone_comment_split, rhs]
2042 for split_func in split_funcs:
2043 # We are accumulating lines in `result` because we might want to abort
2044 # mission and return the original line in the end, or attempt a different
2046 result: List[Line] = []
2048 for l in split_func(line, py36):
2049 if str(l).strip("\n") == line_str:
2050 raise CannotSplit("Split function returned an unchanged result")
2053 split_line(l, line_length=line_length, inner=True, py36=py36)
2055 except CannotSplit as cs:
2066 def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
2067 """Split line into many lines, starting with the first matching bracket pair.
2069 Note: this usually looks weird, only use this for function definitions.
2070 Prefer RHS otherwise. This is why this function is not symmetrical with
2071 :func:`right_hand_split` which also handles optional parentheses.
2073 head = Line(depth=line.depth)
2074 body = Line(depth=line.depth + 1, inside_brackets=True)
2075 tail = Line(depth=line.depth)
2076 tail_leaves: List[Leaf] = []
2077 body_leaves: List[Leaf] = []
2078 head_leaves: List[Leaf] = []
2079 current_leaves = head_leaves
2080 matching_bracket = None
2081 for leaf in line.leaves:
2083 current_leaves is body_leaves
2084 and leaf.type in CLOSING_BRACKETS
2085 and leaf.opening_bracket is matching_bracket
2087 current_leaves = tail_leaves if body_leaves else head_leaves
2088 current_leaves.append(leaf)
2089 if current_leaves is head_leaves:
2090 if leaf.type in OPENING_BRACKETS:
2091 matching_bracket = leaf
2092 current_leaves = body_leaves
2093 # Since body is a new indent level, remove spurious leading whitespace.
2095 normalize_prefix(body_leaves[0], inside_brackets=True)
2096 # Build the new lines.
2097 for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2099 result.append(leaf, preformatted=True)
2100 for comment_after in line.comments_after(leaf):
2101 result.append(comment_after, preformatted=True)
2102 bracket_split_succeeded_or_raise(head, body, tail)
2103 for result in (head, body, tail):
2108 def right_hand_split(
2109 line: Line, line_length: int, py36: bool = False, omit: Collection[LeafID] = ()
2110 ) -> Iterator[Line]:
2111 """Split line into many lines, starting with the last matching bracket pair.
2113 If the split was by optional parentheses, attempt splitting without them, too.
2114 `omit` is a collection of closing bracket IDs that shouldn't be considered for
2117 Note: running this function modifies `bracket_depth` on the leaves of `line`.
2119 head = Line(depth=line.depth)
2120 body = Line(depth=line.depth + 1, inside_brackets=True)
2121 tail = Line(depth=line.depth)
2122 tail_leaves: List[Leaf] = []
2123 body_leaves: List[Leaf] = []
2124 head_leaves: List[Leaf] = []
2125 current_leaves = tail_leaves
2126 opening_bracket = None
2127 closing_bracket = None
2128 for leaf in reversed(line.leaves):
2129 if current_leaves is body_leaves:
2130 if leaf is opening_bracket:
2131 current_leaves = head_leaves if body_leaves else tail_leaves
2132 current_leaves.append(leaf)
2133 if current_leaves is tail_leaves:
2134 if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
2135 opening_bracket = leaf.opening_bracket
2136 closing_bracket = leaf
2137 current_leaves = body_leaves
2138 tail_leaves.reverse()
2139 body_leaves.reverse()
2140 head_leaves.reverse()
2141 # Since body is a new indent level, remove spurious leading whitespace.
2143 normalize_prefix(body_leaves[0], inside_brackets=True)
2145 # No `head` means the split failed. Either `tail` has all content or
2146 # the matching `opening_bracket` wasn't available on `line` anymore.
2147 raise CannotSplit("No brackets found")
2149 # Build the new lines.
2150 for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2152 result.append(leaf, preformatted=True)
2153 for comment_after in line.comments_after(leaf):
2154 result.append(comment_after, preformatted=True)
2155 bracket_split_succeeded_or_raise(head, body, tail)
2156 assert opening_bracket and closing_bracket
2158 # the opening bracket is an optional paren
2159 opening_bracket.type == token.LPAR
2160 and not opening_bracket.value
2161 # the closing bracket is an optional paren
2162 and closing_bracket.type == token.RPAR
2163 and not closing_bracket.value
2164 # there are no standalone comments in the body
2165 and not line.contains_standalone_comments(0)
2166 # and it's not an import (optional parens are the only thing we can split
2167 # on in this case; attempting a split without them is a waste of time)
2168 and not line.is_import
2170 omit = {id(closing_bracket), *omit}
2171 if can_omit_invisible_parens(body, line_length):
2173 yield from right_hand_split(line, line_length, py36=py36, omit=omit)
2178 ensure_visible(opening_bracket)
2179 ensure_visible(closing_bracket)
2180 body.should_explode = should_explode(body, opening_bracket)
2181 for result in (head, body, tail):
2186 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
2187 """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
2189 Do nothing otherwise.
2191 A left- or right-hand split is based on a pair of brackets. Content before
2192 (and including) the opening bracket is left on one line, content inside the
2193 brackets is put on a separate line, and finally content starting with and
2194 following the closing bracket is put on a separate line.
2196 Those are called `head`, `body`, and `tail`, respectively. If the split
2197 produced the same line (all content in `head`) or ended up with an empty `body`
2198 and the `tail` is just the closing bracket, then it's considered failed.
2200 tail_len = len(str(tail).strip())
2203 raise CannotSplit("Splitting brackets produced the same line")
2207 f"Splitting brackets on an empty body to save "
2208 f"{tail_len} characters is not worth it"
2212 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
2213 """Normalize prefix of the first leaf in every line returned by `split_func`.
2215 This is a decorator over relevant split functions.
2219 def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
2220 for l in split_func(line, py36):
2221 normalize_prefix(l.leaves[0], inside_brackets=True)
2224 return split_wrapper
2227 @dont_increase_indentation
2228 def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
2229 """Split according to delimiters of the highest priority.
2231 If `py36` is True, the split will add trailing commas also in function
2232 signatures that contain `*` and `**`.
2235 last_leaf = line.leaves[-1]
2237 raise CannotSplit("Line empty")
2239 bt = line.bracket_tracker
2241 delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
2243 raise CannotSplit("No delimiters found")
2245 if delimiter_priority == DOT_PRIORITY:
2246 if bt.delimiter_count_with_priority(delimiter_priority) == 1:
2247 raise CannotSplit("Splitting a single attribute from its owner looks wrong")
2249 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2250 lowest_depth = sys.maxsize
2251 trailing_comma_safe = True
2253 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2254 """Append `leaf` to current line or to new line if appending impossible."""
2255 nonlocal current_line
2257 current_line.append_safe(leaf, preformatted=True)
2258 except ValueError as ve:
2261 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2262 current_line.append(leaf)
2264 for index, leaf in enumerate(line.leaves):
2265 yield from append_to_line(leaf)
2267 for comment_after in line.comments_after(leaf, index):
2268 yield from append_to_line(comment_after)
2270 lowest_depth = min(lowest_depth, leaf.bracket_depth)
2271 if leaf.bracket_depth == lowest_depth and is_vararg(
2272 leaf, within=VARARGS_PARENTS
2274 trailing_comma_safe = trailing_comma_safe and py36
2275 leaf_priority = bt.delimiters.get(id(leaf))
2276 if leaf_priority == delimiter_priority:
2279 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2283 and delimiter_priority == COMMA_PRIORITY
2284 and current_line.leaves[-1].type != token.COMMA
2285 and current_line.leaves[-1].type != STANDALONE_COMMENT
2287 current_line.append(Leaf(token.COMMA, ","))
2291 @dont_increase_indentation
2292 def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
2293 """Split standalone comments from the rest of the line."""
2294 if not line.contains_standalone_comments(0):
2295 raise CannotSplit("Line does not have any standalone comments")
2297 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2299 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2300 """Append `leaf` to current line or to new line if appending impossible."""
2301 nonlocal current_line
2303 current_line.append_safe(leaf, preformatted=True)
2304 except ValueError as ve:
2307 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2308 current_line.append(leaf)
2310 for index, leaf in enumerate(line.leaves):
2311 yield from append_to_line(leaf)
2313 for comment_after in line.comments_after(leaf, index):
2314 yield from append_to_line(comment_after)
2320 def is_import(leaf: Leaf) -> bool:
2321 """Return True if the given leaf starts an import statement."""
2328 (v == "import" and p and p.type == syms.import_name)
2329 or (v == "from" and p and p.type == syms.import_from)
2334 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
2335 """Leave existing extra newlines if not `inside_brackets`. Remove everything
2338 Note: don't use backslashes for formatting or you'll lose your voting rights.
2340 if not inside_brackets:
2341 spl = leaf.prefix.split("#")
2342 if "\\" not in spl[0]:
2343 nl_count = spl[-1].count("\n")
2346 leaf.prefix = "\n" * nl_count
2352 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
2353 """Make all string prefixes lowercase.
2355 If remove_u_prefix is given, also removes any u prefix from the string.
2357 Note: Mutates its argument.
2359 match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
2360 assert match is not None, f"failed to match string {leaf.value!r}"
2361 orig_prefix = match.group(1)
2362 new_prefix = orig_prefix.lower()
2364 new_prefix = new_prefix.replace("u", "")
2365 leaf.value = f"{new_prefix}{match.group(2)}"
2368 def normalize_string_quotes(leaf: Leaf) -> None:
2369 """Prefer double quotes but only if it doesn't cause more escaping.
2371 Adds or removes backslashes as appropriate. Doesn't parse and fix
2372 strings nested in f-strings (yet).
2374 Note: Mutates its argument.
2376 value = leaf.value.lstrip("furbFURB")
2377 if value[:3] == '"""':
2380 elif value[:3] == "'''":
2383 elif value[0] == '"':
2389 first_quote_pos = leaf.value.find(orig_quote)
2390 if first_quote_pos == -1:
2391 return # There's an internal error
2393 prefix = leaf.value[:first_quote_pos]
2394 unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
2395 escaped_new_quote = re.compile(rf"([^\\]|^)\\(\\\\)*{new_quote}")
2396 escaped_orig_quote = re.compile(rf"([^\\]|^)\\(\\\\)*{orig_quote}")
2397 body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
2398 if "r" in prefix.casefold():
2399 if unescaped_new_quote.search(body):
2400 # There's at least one unescaped new_quote in this raw string
2401 # so converting is impossible
2404 # Do not introduce or remove backslashes in raw strings
2407 # remove unnecessary quotes
2408 new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
2409 if body != new_body:
2410 # Consider the string without unnecessary quotes as the original
2412 leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
2413 new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
2414 new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
2415 if new_quote == '"""' and new_body[-1] == '"':
2417 new_body = new_body[:-1] + '\\"'
2418 orig_escape_count = body.count("\\")
2419 new_escape_count = new_body.count("\\")
2420 if new_escape_count > orig_escape_count:
2421 return # Do not introduce more escaping
2423 if new_escape_count == orig_escape_count and orig_quote == '"':
2424 return # Prefer double quotes
2426 leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
2429 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
2430 """Make existing optional parentheses invisible or create new ones.
2432 `parens_after` is a set of string leaf values immeditely after which parens
2435 Standardizes on visible parentheses for single-element tuples, and keeps
2436 existing visible parentheses for other tuples and generator expressions.
2439 list(generate_comments(node))
2441 return # This `node` has a prefix with `# fmt: off`, don't mess with parens.
2444 for index, child in enumerate(list(node.children)):
2446 if child.type == syms.atom:
2447 maybe_make_parens_invisible_in_atom(child)
2448 elif is_one_tuple(child):
2449 # wrap child in visible parentheses
2450 lpar = Leaf(token.LPAR, "(")
2451 rpar = Leaf(token.RPAR, ")")
2453 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2454 elif node.type == syms.import_from:
2455 # "import from" nodes store parentheses directly as part of
2457 if child.type == token.LPAR:
2458 # make parentheses invisible
2459 child.value = "" # type: ignore
2460 node.children[-1].value = "" # type: ignore
2461 elif child.type != token.STAR:
2462 # insert invisible parentheses
2463 node.insert_child(index, Leaf(token.LPAR, ""))
2464 node.append_child(Leaf(token.RPAR, ""))
2467 elif not (isinstance(child, Leaf) and is_multiline_string(child)):
2468 # wrap child in invisible parentheses
2469 lpar = Leaf(token.LPAR, "")
2470 rpar = Leaf(token.RPAR, "")
2471 index = child.remove() or 0
2472 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2474 check_lpar = isinstance(child, Leaf) and child.value in parens_after
2477 def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
2478 """If it's safe, make the parens in the atom `node` invisible, recusively."""
2480 node.type != syms.atom
2481 or is_empty_tuple(node)
2482 or is_one_tuple(node)
2484 or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
2488 first = node.children[0]
2489 last = node.children[-1]
2490 if first.type == token.LPAR and last.type == token.RPAR:
2491 # make parentheses invisible
2492 first.value = "" # type: ignore
2493 last.value = "" # type: ignore
2494 if len(node.children) > 1:
2495 maybe_make_parens_invisible_in_atom(node.children[1])
2501 def is_empty_tuple(node: LN) -> bool:
2502 """Return True if `node` holds an empty tuple."""
2504 node.type == syms.atom
2505 and len(node.children) == 2
2506 and node.children[0].type == token.LPAR
2507 and node.children[1].type == token.RPAR
2511 def is_one_tuple(node: LN) -> bool:
2512 """Return True if `node` holds a tuple with one element, with or without parens."""
2513 if node.type == syms.atom:
2514 if len(node.children) != 3:
2517 lpar, gexp, rpar = node.children
2519 lpar.type == token.LPAR
2520 and gexp.type == syms.testlist_gexp
2521 and rpar.type == token.RPAR
2525 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
2528 node.type in IMPLICIT_TUPLE
2529 and len(node.children) == 2
2530 and node.children[1].type == token.COMMA
2534 def is_yield(node: LN) -> bool:
2535 """Return True if `node` holds a `yield` or `yield from` expression."""
2536 if node.type == syms.yield_expr:
2539 if node.type == token.NAME and node.value == "yield": # type: ignore
2542 if node.type != syms.atom:
2545 if len(node.children) != 3:
2548 lpar, expr, rpar = node.children
2549 if lpar.type == token.LPAR and rpar.type == token.RPAR:
2550 return is_yield(expr)
2555 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
2556 """Return True if `leaf` is a star or double star in a vararg or kwarg.
2558 If `within` includes VARARGS_PARENTS, this applies to function signatures.
2559 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
2560 extended iterable unpacking (PEP 3132) and additional unpacking
2561 generalizations (PEP 448).
2563 if leaf.type not in STARS or not leaf.parent:
2567 if p.type == syms.star_expr:
2568 # Star expressions are also used as assignment targets in extended
2569 # iterable unpacking (PEP 3132). See what its parent is instead.
2575 return p.type in within
2578 def is_multiline_string(leaf: Leaf) -> bool:
2579 """Return True if `leaf` is a multiline string that actually spans many lines."""
2580 value = leaf.value.lstrip("furbFURB")
2581 return value[:3] in {'"""', "'''"} and "\n" in value
2584 def is_stub_suite(node: Node) -> bool:
2585 """Return True if `node` is a suite with a stub body."""
2587 len(node.children) != 4
2588 or node.children[0].type != token.NEWLINE
2589 or node.children[1].type != token.INDENT
2590 or node.children[3].type != token.DEDENT
2594 return is_stub_body(node.children[2])
2597 def is_stub_body(node: LN) -> bool:
2598 """Return True if `node` is a simple statement containing an ellipsis."""
2599 if not isinstance(node, Node) or node.type != syms.simple_stmt:
2602 if len(node.children) != 2:
2605 child = node.children[0]
2607 child.type == syms.atom
2608 and len(child.children) == 3
2609 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
2613 def max_delimiter_priority_in_atom(node: LN) -> int:
2614 """Return maximum delimiter priority inside `node`.
2616 This is specific to atoms with contents contained in a pair of parentheses.
2617 If `node` isn't an atom or there are no enclosing parentheses, returns 0.
2619 if node.type != syms.atom:
2622 first = node.children[0]
2623 last = node.children[-1]
2624 if not (first.type == token.LPAR and last.type == token.RPAR):
2627 bt = BracketTracker()
2628 for c in node.children[1:-1]:
2629 if isinstance(c, Leaf):
2632 for leaf in c.leaves():
2635 return bt.max_delimiter_priority()
2641 def ensure_visible(leaf: Leaf) -> None:
2642 """Make sure parentheses are visible.
2644 They could be invisible as part of some statements (see
2645 :func:`normalize_invible_parens` and :func:`visit_import_from`).
2647 if leaf.type == token.LPAR:
2649 elif leaf.type == token.RPAR:
2653 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
2654 """Should `line` immediately be split with `delimiter_split()` after RHS?"""
2656 opening_bracket.parent
2657 and opening_bracket.parent.type in {syms.atom, syms.import_from}
2658 and opening_bracket.value in "[{("
2663 last_leaf = line.leaves[-1]
2664 exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
2665 max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
2666 except (IndexError, ValueError):
2669 return max_priority == COMMA_PRIORITY
2672 def is_python36(node: Node) -> bool:
2673 """Return True if the current file is using Python 3.6+ features.
2675 Currently looking for:
2677 - trailing commas after * or ** in function signatures and calls.
2679 for n in node.pre_order():
2680 if n.type == token.STRING:
2681 value_head = n.value[:2] # type: ignore
2682 if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
2686 n.type in {syms.typedargslist, syms.arglist}
2688 and n.children[-1].type == token.COMMA
2690 for ch in n.children:
2691 if ch.type in STARS:
2694 if ch.type == syms.argument:
2695 for argch in ch.children:
2696 if argch.type in STARS:
2702 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
2703 """Generate sets of closing bracket IDs that should be omitted in a RHS.
2705 Brackets can be omitted if the entire trailer up to and including
2706 a preceding closing bracket fits in one line.
2708 Yielded sets are cumulative (contain results of previous yields, too). First
2712 omit: Set[LeafID] = set()
2715 length = 4 * line.depth
2716 opening_bracket = None
2717 closing_bracket = None
2718 optional_brackets: Set[LeafID] = set()
2719 inner_brackets: Set[LeafID] = set()
2720 for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
2721 length += leaf_length
2722 if length > line_length:
2725 has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
2726 if leaf.type == STANDALONE_COMMENT or has_inline_comment:
2729 optional_brackets.discard(id(leaf))
2731 if leaf is opening_bracket:
2732 opening_bracket = None
2733 elif leaf.type in CLOSING_BRACKETS:
2734 inner_brackets.add(id(leaf))
2735 elif leaf.type in CLOSING_BRACKETS:
2737 optional_brackets.add(id(opening_bracket))
2740 if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
2741 # Empty brackets would fail a split so treat them as "inner"
2742 # brackets (e.g. only add them to the `omit` set if another
2743 # pair of brackets was good enough.
2744 inner_brackets.add(id(leaf))
2747 opening_bracket = leaf.opening_bracket
2749 omit.add(id(closing_bracket))
2750 omit.update(inner_brackets)
2751 inner_brackets.clear()
2753 closing_bracket = leaf
2756 def get_future_imports(node: Node) -> Set[str]:
2757 """Return a set of __future__ imports in the file."""
2759 for child in node.children:
2760 if child.type != syms.simple_stmt:
2762 first_child = child.children[0]
2763 if isinstance(first_child, Leaf):
2764 # Continue looking if we see a docstring; otherwise stop.
2766 len(child.children) == 2
2767 and first_child.type == token.STRING
2768 and child.children[1].type == token.NEWLINE
2773 elif first_child.type == syms.import_from:
2774 module_name = first_child.children[1]
2775 if not isinstance(module_name, Leaf) or module_name.value != "__future__":
2777 for import_from_child in first_child.children[3:]:
2778 if isinstance(import_from_child, Leaf):
2779 if import_from_child.type == token.NAME:
2780 imports.add(import_from_child.value)
2782 assert import_from_child.type == syms.import_as_names
2783 for leaf in import_from_child.children:
2784 if isinstance(leaf, Leaf) and leaf.type == token.NAME:
2785 imports.add(leaf.value)
2791 def gen_python_files_in_dir(
2792 path: Path, include: Pattern[str], exclude: Pattern[str]
2793 ) -> Iterator[Path]:
2794 """Generate all files under `path` whose paths are not excluded by the
2795 `exclude` regex, but are included by the `include` regex.
2798 for child in path.iterdir():
2799 searchable_path = str(child.as_posix())
2800 if Path(child.parts[0]).is_dir():
2801 searchable_path = "/" + searchable_path
2803 searchable_path = searchable_path + "/"
2804 exclude_match = exclude.search(searchable_path)
2805 if exclude_match and len(exclude_match.group()) > 0:
2808 yield from gen_python_files_in_dir(child, include, exclude)
2811 include_match = include.search(searchable_path)
2812 exclude_match = exclude.search(searchable_path)
2816 and len(include_match.group()) > 0
2817 and (not exclude_match or len(exclude_match.group()) == 0)
2824 """Provides a reformatting counter. Can be rendered with `str(report)`."""
2828 change_count: int = 0
2830 failure_count: int = 0
2832 def done(self, src: Path, changed: Changed) -> None:
2833 """Increment the counter for successful reformatting. Write out a message."""
2834 if changed is Changed.YES:
2835 reformatted = "would reformat" if self.check else "reformatted"
2837 out(f"{reformatted} {src}")
2838 self.change_count += 1
2841 if changed is Changed.NO:
2842 msg = f"{src} already well formatted, good job."
2844 msg = f"{src} wasn't modified on disk since last run."
2845 out(msg, bold=False)
2846 self.same_count += 1
2848 def failed(self, src: Path, message: str) -> None:
2849 """Increment the counter for failed reformatting. Write out a message."""
2850 err(f"error: cannot format {src}: {message}")
2851 self.failure_count += 1
2854 def return_code(self) -> int:
2855 """Return the exit code that the app should use.
2857 This considers the current state of changed files and failures:
2858 - if there were any failures, return 123;
2859 - if any files were changed and --check is being used, return 1;
2860 - otherwise return 0.
2862 # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
2863 # 126 we have special returncodes reserved by the shell.
2864 if self.failure_count:
2867 elif self.change_count and self.check:
2872 def __str__(self) -> str:
2873 """Render a color report of the current state.
2875 Use `click.unstyle` to remove colors.
2878 reformatted = "would be reformatted"
2879 unchanged = "would be left unchanged"
2880 failed = "would fail to reformat"
2882 reformatted = "reformatted"
2883 unchanged = "left unchanged"
2884 failed = "failed to reformat"
2886 if self.change_count:
2887 s = "s" if self.change_count > 1 else ""
2889 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
2892 s = "s" if self.same_count > 1 else ""
2893 report.append(f"{self.same_count} file{s} {unchanged}")
2894 if self.failure_count:
2895 s = "s" if self.failure_count > 1 else ""
2897 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
2899 return ", ".join(report) + "."
2902 def assert_equivalent(src: str, dst: str) -> None:
2903 """Raise AssertionError if `src` and `dst` aren't equivalent."""
2908 def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
2909 """Simple visitor generating strings to compare ASTs by content."""
2910 yield f"{' ' * depth}{node.__class__.__name__}("
2912 for field in sorted(node._fields):
2914 value = getattr(node, field)
2915 except AttributeError:
2918 yield f"{' ' * (depth+1)}{field}="
2920 if isinstance(value, list):
2922 if isinstance(item, ast.AST):
2923 yield from _v(item, depth + 2)
2925 elif isinstance(value, ast.AST):
2926 yield from _v(value, depth + 2)
2929 yield f"{' ' * (depth+2)}{value!r}, # {value.__class__.__name__}"
2931 yield f"{' ' * depth}) # /{node.__class__.__name__}"
2934 src_ast = ast.parse(src)
2935 except Exception as exc:
2936 major, minor = sys.version_info[:2]
2937 raise AssertionError(
2938 f"cannot use --safe with this file; failed to parse source file "
2939 f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
2940 f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
2944 dst_ast = ast.parse(dst)
2945 except Exception as exc:
2946 log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
2947 raise AssertionError(
2948 f"INTERNAL ERROR: Black produced invalid code: {exc}. "
2949 f"Please report a bug on https://github.com/ambv/black/issues. "
2950 f"This invalid output might be helpful: {log}"
2953 src_ast_str = "\n".join(_v(src_ast))
2954 dst_ast_str = "\n".join(_v(dst_ast))
2955 if src_ast_str != dst_ast_str:
2956 log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
2957 raise AssertionError(
2958 f"INTERNAL ERROR: Black produced code that is not equivalent to "
2960 f"Please report a bug on https://github.com/ambv/black/issues. "
2961 f"This diff might be helpful: {log}"
2966 src: str, dst: str, line_length: int, mode: FileMode = FileMode.AUTO_DETECT
2968 """Raise AssertionError if `dst` reformats differently the second time."""
2969 newdst = format_str(dst, line_length=line_length, mode=mode)
2972 diff(src, dst, "source", "first pass"),
2973 diff(dst, newdst, "first pass", "second pass"),
2975 raise AssertionError(
2976 f"INTERNAL ERROR: Black produced different code on the second pass "
2977 f"of the formatter. "
2978 f"Please report a bug on https://github.com/ambv/black/issues. "
2979 f"This diff might be helpful: {log}"
2983 def dump_to_file(*output: str) -> str:
2984 """Dump `output` to a temporary file. Return path to the file."""
2987 with tempfile.NamedTemporaryFile(
2988 mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
2990 for lines in output:
2992 if lines and lines[-1] != "\n":
2997 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
2998 """Return a unified diff string between strings `a` and `b`."""
3001 a_lines = [line + "\n" for line in a.split("\n")]
3002 b_lines = [line + "\n" for line in b.split("\n")]
3004 difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
3008 def cancel(tasks: Iterable[asyncio.Task]) -> None:
3009 """asyncio signal handler that cancels all `tasks` and reports to stderr."""
3015 def shutdown(loop: BaseEventLoop) -> None:
3016 """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
3018 # This part is borrowed from asyncio/runners.py in Python 3.7b2.
3019 to_cancel = [task for task in asyncio.Task.all_tasks(loop) if not task.done()]
3023 for task in to_cancel:
3025 loop.run_until_complete(
3026 asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
3029 # `concurrent.futures.Future` objects cannot be cancelled once they
3030 # are already running. There might be some when the `shutdown()` happened.
3031 # Silence their logger's spew about the event loop being closed.
3032 cf_logger = logging.getLogger("concurrent.futures")
3033 cf_logger.setLevel(logging.CRITICAL)
3037 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
3038 """Replace `regex` with `replacement` twice on `original`.
3040 This is used by string normalization to perform replaces on
3041 overlapping matches.
3043 return regex.sub(replacement, regex.sub(replacement, original))
3046 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
3047 """Like `reversed(enumerate(sequence))` if that were possible."""
3048 index = len(sequence) - 1
3049 for element in reversed(sequence):
3050 yield (index, element)
3054 def enumerate_with_length(
3055 line: Line, reversed: bool = False
3056 ) -> Iterator[Tuple[Index, Leaf, int]]:
3057 """Return an enumeration of leaves with their length.
3059 Stops prematurely on multiline strings and standalone comments.
3062 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
3063 enumerate_reversed if reversed else enumerate,
3065 for index, leaf in op(line.leaves):
3066 length = len(leaf.prefix) + len(leaf.value)
3067 if "\n" in leaf.value:
3068 return # Multiline strings, we can't continue.
3070 comment: Optional[Leaf]
3071 for comment in line.comments_after(leaf, index):
3072 length += len(comment.value)
3074 yield index, leaf, length
3077 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
3078 """Return True if `line` is no longer than `line_length`.
3080 Uses the provided `line_str` rendering, if any, otherwise computes a new one.
3083 line_str = str(line).strip("\n")
3085 len(line_str) <= line_length
3086 and "\n" not in line_str # multiline strings
3087 and not line.contains_standalone_comments()
3091 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
3092 """Does `line` have a shape safe to reformat without optional parens around it?
3094 Returns True for only a subset of potentially nice looking formattings but
3095 the point is to not return false positives that end up producing lines that
3098 bt = line.bracket_tracker
3099 if not bt.delimiters:
3100 # Without delimiters the optional parentheses are useless.
3103 max_priority = bt.max_delimiter_priority()
3104 if bt.delimiter_count_with_priority(max_priority) > 1:
3105 # With more than one delimiter of a kind the optional parentheses read better.
3108 if max_priority == DOT_PRIORITY:
3109 # A single stranded method call doesn't require optional parentheses.
3112 assert len(line.leaves) >= 2, "Stranded delimiter"
3114 first = line.leaves[0]
3115 second = line.leaves[1]
3116 penultimate = line.leaves[-2]
3117 last = line.leaves[-1]
3119 # With a single delimiter, omit if the expression starts or ends with
3121 if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
3123 length = 4 * line.depth
3124 for _index, leaf, leaf_length in enumerate_with_length(line):
3125 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
3128 length += leaf_length
3129 if length > line_length:
3132 if leaf.type in OPENING_BRACKETS:
3133 # There are brackets we can further split on.
3137 # checked the entire string and line length wasn't exceeded
3138 if len(line.leaves) == _index + 1:
3141 # Note: we are not returning False here because a line might have *both*
3142 # a leading opening bracket and a trailing closing bracket. If the
3143 # opening bracket doesn't match our rule, maybe the closing will.
3146 last.type == token.RPAR
3147 or last.type == token.RBRACE
3149 # don't use indexing for omitting optional parentheses;
3151 last.type == token.RSQB
3153 and last.parent.type != syms.trailer
3156 if penultimate.type in OPENING_BRACKETS:
3157 # Empty brackets don't help.
3160 if is_multiline_string(first):
3161 # Additional wrapping of a multiline string in this situation is
3165 length = 4 * line.depth
3166 seen_other_brackets = False
3167 for _index, leaf, leaf_length in enumerate_with_length(line):
3168 length += leaf_length
3169 if leaf is last.opening_bracket:
3170 if seen_other_brackets or length <= line_length:
3173 elif leaf.type in OPENING_BRACKETS:
3174 # There are brackets we can further split on.
3175 seen_other_brackets = True
3180 def get_cache_file(line_length: int, mode: FileMode) -> Path:
3181 pyi = bool(mode & FileMode.PYI)
3182 py36 = bool(mode & FileMode.PYTHON36)
3185 / f"cache.{line_length}{'.pyi' if pyi else ''}{'.py36' if py36 else ''}.pickle"
3189 def read_cache(line_length: int, mode: FileMode) -> Cache:
3190 """Read the cache if it exists and is well formed.
3192 If it is not well formed, the call to write_cache later should resolve the issue.
3194 cache_file = get_cache_file(line_length, mode)
3195 if not cache_file.exists():
3198 with cache_file.open("rb") as fobj:
3200 cache: Cache = pickle.load(fobj)
3201 except pickle.UnpicklingError:
3207 def get_cache_info(path: Path) -> CacheInfo:
3208 """Return the information used to check if a file is already formatted or not."""
3210 return stat.st_mtime, stat.st_size
3214 cache: Cache, sources: Iterable[Path]
3215 ) -> Tuple[List[Path], List[Path]]:
3216 """Split a list of paths into two.
3218 The first list contains paths of files that modified on disk or are not in the
3219 cache. The other list contains paths to non-modified files.
3224 if cache.get(src) != get_cache_info(src):
3232 cache: Cache, sources: List[Path], line_length: int, mode: FileMode
3234 """Update the cache file."""
3235 cache_file = get_cache_file(line_length, mode)
3237 if not CACHE_DIR.exists():
3238 CACHE_DIR.mkdir(parents=True)
3239 new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
3240 with cache_file.open("wb") as fobj:
3241 pickle.dump(new_cache, fobj, protocol=pickle.HIGHEST_PROTOCOL)
3246 if __name__ == "__main__":