-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
black.py
2599 lines (2139 loc) · 84.2 KB
/
black.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import asyncio
import pickle
from asyncio.base_events import BaseEventLoop
from concurrent.futures import Executor, ProcessPoolExecutor
from enum import Enum
from functools import partial, wraps
import keyword
import logging
from multiprocessing import Manager
import os
from pathlib import Path
import re
import tokenize
import signal
import sys
from typing import (
Any,
Callable,
Collection,
Dict,
Generic,
Iterable,
Iterator,
List,
Optional,
Pattern,
Set,
Tuple,
Type,
TypeVar,
Union,
)
from appdirs import user_cache_dir
from attr import dataclass, Factory
import click
# lib2to3 fork
from blib2to3.pytree import Node, Leaf, type_repr
from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.parse import ParseError
__version__ = "18.4a4"
DEFAULT_LINE_LENGTH = 88
# types
syms = pygram.python_symbols
FileContent = str
Encoding = str
Depth = int
NodeType = int
LeafID = int
Priority = int
Index = int
LN = Union[Leaf, Node]
SplitFunc = Callable[["Line", bool], Iterator["Line"]]
Timestamp = float
FileSize = int
CacheInfo = Tuple[Timestamp, FileSize]
Cache = Dict[Path, CacheInfo]
out = partial(click.secho, bold=True, err=True)
err = partial(click.secho, fg="red", err=True)
class NothingChanged(UserWarning):
"""Raised by :func:`format_file` when reformatted code is the same as source."""
class CannotSplit(Exception):
"""A readable split that fits the allotted line length is impossible.
Raised by :func:`left_hand_split`, :func:`right_hand_split`, and
:func:`delimiter_split`.
"""
class FormatError(Exception):
"""Base exception for `# fmt: on` and `# fmt: off` handling.
It holds the number of bytes of the prefix consumed before the format
control comment appeared.
"""
def __init__(self, consumed: int) -> None:
super().__init__(consumed)
self.consumed = consumed
def trim_prefix(self, leaf: Leaf) -> None:
leaf.prefix = leaf.prefix[self.consumed :]
def leaf_from_consumed(self, leaf: Leaf) -> Leaf:
"""Returns a new Leaf from the consumed part of the prefix."""
unformatted_prefix = leaf.prefix[: self.consumed]
return Leaf(token.NEWLINE, unformatted_prefix)
class FormatOn(FormatError):
"""Found a comment like `# fmt: on` in the file."""
class FormatOff(FormatError):
"""Found a comment like `# fmt: off` in the file."""
class WriteBack(Enum):
NO = 0
YES = 1
DIFF = 2
class Changed(Enum):
NO = 0
CACHED = 1
YES = 2
@click.command()
@click.option(
"-l",
"--line-length",
type=int,
default=DEFAULT_LINE_LENGTH,
help="How many character per line to allow.",
show_default=True,
)
@click.option(
"--check",
is_flag=True,
help=(
"Don't write the files back, just return the status. Return code 0 "
"means nothing would change. Return code 1 means some files would be "
"reformatted. Return code 123 means there was an internal error."
),
)
@click.option(
"--diff",
is_flag=True,
help="Don't write the files back, just output a diff for each file on stdout.",
)
@click.option(
"--fast/--safe",
is_flag=True,
help="If --fast given, skip temporary sanity checks. [default: --safe]",
)
@click.option(
"-q",
"--quiet",
is_flag=True,
help=(
"Don't emit non-error messages to stderr. Errors are still emitted, "
"silence those with 2>/dev/null."
),
)
@click.version_option(version=__version__)
@click.argument(
"src",
nargs=-1,
type=click.Path(
exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
),
)
@click.pass_context
def main(
ctx: click.Context,
line_length: int,
check: bool,
diff: bool,
fast: bool,
quiet: bool,
src: List[str],
) -> None:
"""The uncompromising code formatter."""
sources: List[Path] = []
for s in src:
p = Path(s)
if p.is_dir():
sources.extend(gen_python_files_in_dir(p))
elif p.is_file():
# if a file was explicitly given, we don't care about its extension
sources.append(p)
elif s == "-":
sources.append(Path("-"))
else:
err(f"invalid path: {s}")
if check and not diff:
write_back = WriteBack.NO
elif diff:
write_back = WriteBack.DIFF
else:
write_back = WriteBack.YES
report = Report(check=check, quiet=quiet)
if len(sources) == 0:
ctx.exit(0)
return
elif len(sources) == 1:
reformat_one(sources[0], line_length, fast, write_back, report)
else:
loop = asyncio.get_event_loop()
executor = ProcessPoolExecutor(max_workers=os.cpu_count())
try:
loop.run_until_complete(
schedule_formatting(
sources, line_length, fast, write_back, report, loop, executor
)
)
finally:
shutdown(loop)
if not quiet:
out("All done! ✨ 🍰 ✨")
click.echo(str(report))
ctx.exit(report.return_code)
def reformat_one(
src: Path, line_length: int, fast: bool, write_back: WriteBack, report: "Report"
) -> None:
"""Reformat a single file under `src` without spawning child processes.
If `quiet` is True, non-error messages are not output. `line_length`,
`write_back`, and `fast` options are passed to :func:`format_file_in_place`.
"""
try:
changed = Changed.NO
if not src.is_file() and str(src) == "-":
if format_stdin_to_stdout(
line_length=line_length, fast=fast, write_back=write_back
):
changed = Changed.YES
else:
cache: Cache = {}
if write_back != WriteBack.DIFF:
cache = read_cache(line_length)
src = src.resolve()
if src in cache and cache[src] == get_cache_info(src):
changed = Changed.CACHED
if (
changed is not Changed.CACHED
and format_file_in_place(
src, line_length=line_length, fast=fast, write_back=write_back
)
):
changed = Changed.YES
if write_back == WriteBack.YES and changed is not Changed.NO:
write_cache(cache, [src], line_length)
report.done(src, changed)
except Exception as exc:
report.failed(src, str(exc))
async def schedule_formatting(
sources: List[Path],
line_length: int,
fast: bool,
write_back: WriteBack,
report: "Report",
loop: BaseEventLoop,
executor: Executor,
) -> None:
"""Run formatting of `sources` in parallel using the provided `executor`.
(Use ProcessPoolExecutors for actual parallelism.)
`line_length`, `write_back`, and `fast` options are passed to
:func:`format_file_in_place`.
"""
cache: Cache = {}
if write_back != WriteBack.DIFF:
cache = read_cache(line_length)
sources, cached = filter_cached(cache, sources)
for src in cached:
report.done(src, Changed.CACHED)
cancelled = []
formatted = []
if sources:
lock = None
if write_back == WriteBack.DIFF:
# For diff output, we need locks to ensure we don't interleave output
# from different processes.
manager = Manager()
lock = manager.Lock()
tasks = {
src: loop.run_in_executor(
executor, format_file_in_place, src, line_length, fast, write_back, lock
)
for src in sources
}
_task_values = list(tasks.values())
try:
loop.add_signal_handler(signal.SIGINT, cancel, _task_values)
loop.add_signal_handler(signal.SIGTERM, cancel, _task_values)
except NotImplementedError:
# There are no good alternatives for these on Windows
pass
await asyncio.wait(_task_values)
for src, task in tasks.items():
if not task.done():
report.failed(src, "timed out, cancelling")
task.cancel()
cancelled.append(task)
elif task.cancelled():
cancelled.append(task)
elif task.exception():
report.failed(src, str(task.exception()))
else:
formatted.append(src)
report.done(src, Changed.YES if task.result() else Changed.NO)
if cancelled:
await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
if write_back == WriteBack.YES and formatted:
write_cache(cache, formatted, line_length)
def format_file_in_place(
src: Path,
line_length: int,
fast: bool,
write_back: WriteBack = WriteBack.NO,
lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
) -> bool:
"""Format file under `src` path. Return True if changed.
If `write_back` is True, write reformatted code back to stdout.
`line_length` and `fast` options are passed to :func:`format_file_contents`.
"""
with tokenize.open(src) as src_buffer:
src_contents = src_buffer.read()
try:
dst_contents = format_file_contents(
src_contents, line_length=line_length, fast=fast
)
except NothingChanged:
return False
if write_back == write_back.YES:
with open(src, "w", encoding=src_buffer.encoding) as f:
f.write(dst_contents)
elif write_back == write_back.DIFF:
src_name = f"{src} (original)"
dst_name = f"{src} (formatted)"
diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
if lock:
lock.acquire()
try:
sys.stdout.write(diff_contents)
finally:
if lock:
lock.release()
return True
def format_stdin_to_stdout(
line_length: int, fast: bool, write_back: WriteBack = WriteBack.NO
) -> bool:
"""Format file on stdin. Return True if changed.
If `write_back` is True, write reformatted code back to stdout.
`line_length` and `fast` arguments are passed to :func:`format_file_contents`.
"""
src = sys.stdin.read()
dst = src
try:
dst = format_file_contents(src, line_length=line_length, fast=fast)
return True
except NothingChanged:
return False
finally:
if write_back == WriteBack.YES:
sys.stdout.write(dst)
elif write_back == WriteBack.DIFF:
src_name = "<stdin> (original)"
dst_name = "<stdin> (formatted)"
sys.stdout.write(diff(src, dst, src_name, dst_name))
def format_file_contents(
src_contents: str, line_length: int, fast: bool
) -> FileContent:
"""Reformat contents a file and return new contents.
If `fast` is False, additionally confirm that the reformatted code is
valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
`line_length` is passed to :func:`format_str`.
"""
if src_contents.strip() == "":
raise NothingChanged
dst_contents = format_str(src_contents, line_length=line_length)
if src_contents == dst_contents:
raise NothingChanged
if not fast:
assert_equivalent(src_contents, dst_contents)
assert_stable(src_contents, dst_contents, line_length=line_length)
return dst_contents
def format_str(src_contents: str, line_length: int) -> FileContent:
"""Reformat a string and return new contents.
`line_length` determines how many characters per line are allowed.
"""
src_node = lib2to3_parse(src_contents)
dst_contents = ""
lines = LineGenerator()
elt = EmptyLineTracker()
py36 = is_python36(src_node)
empty_line = Line()
after = 0
for current_line in lines.visit(src_node):
for _ in range(after):
dst_contents += str(empty_line)
before, after = elt.maybe_empty_lines(current_line)
for _ in range(before):
dst_contents += str(empty_line)
for line in split_line(current_line, line_length=line_length, py36=py36):
dst_contents += str(line)
return dst_contents
GRAMMARS = [
pygram.python_grammar_no_print_statement_no_exec_statement,
pygram.python_grammar_no_print_statement,
pygram.python_grammar,
]
def lib2to3_parse(src_txt: str) -> Node:
"""Given a string with source, return the lib2to3 Node."""
grammar = pygram.python_grammar_no_print_statement
if src_txt[-1] != "\n":
nl = "\r\n" if "\r\n" in src_txt[:1024] else "\n"
src_txt += nl
for grammar in GRAMMARS:
drv = driver.Driver(grammar, pytree.convert)
try:
result = drv.parse_string(src_txt, True)
break
except ParseError as pe:
lineno, column = pe.context[1]
lines = src_txt.splitlines()
try:
faulty_line = lines[lineno - 1]
except IndexError:
faulty_line = "<line number missing in source>"
exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}")
else:
raise exc from None
if isinstance(result, Leaf):
result = Node(syms.file_input, [result])
return result
def lib2to3_unparse(node: Node) -> str:
"""Given a lib2to3 node, return its string representation."""
code = str(node)
return code
T = TypeVar("T")
class Visitor(Generic[T]):
"""Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
def visit(self, node: LN) -> Iterator[T]:
"""Main method to visit `node` and its children.
It tries to find a `visit_*()` method for the given `node.type`, like
`visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
If no dedicated `visit_*()` method is found, chooses `visit_default()`
instead.
Then yields objects of type `T` from the selected visitor.
"""
if node.type < 256:
name = token.tok_name[node.type]
else:
name = type_repr(node.type)
yield from getattr(self, f"visit_{name}", self.visit_default)(node)
def visit_default(self, node: LN) -> Iterator[T]:
"""Default `visit_*()` implementation. Recurses to children of `node`."""
if isinstance(node, Node):
for child in node.children:
yield from self.visit(child)
@dataclass
class DebugVisitor(Visitor[T]):
tree_depth: int = 0
def visit_default(self, node: LN) -> Iterator[T]:
indent = " " * (2 * self.tree_depth)
if isinstance(node, Node):
_type = type_repr(node.type)
out(f"{indent}{_type}", fg="yellow")
self.tree_depth += 1
for child in node.children:
yield from self.visit(child)
self.tree_depth -= 1
out(f"{indent}/{_type}", fg="yellow", bold=False)
else:
_type = token.tok_name.get(node.type, str(node.type))
out(f"{indent}{_type}", fg="blue", nl=False)
if node.prefix:
# We don't have to handle prefixes for `Node` objects since
# that delegates to the first child anyway.
out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
out(f" {node.value!r}", fg="blue", bold=False)
@classmethod
def show(cls, code: str) -> None:
"""Pretty-print the lib2to3 AST of a given string of `code`.
Convenience method for debugging.
"""
v: DebugVisitor[None] = DebugVisitor()
list(v.visit(lib2to3_parse(code)))
KEYWORDS = set(keyword.kwlist)
WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
FLOW_CONTROL = {"return", "raise", "break", "continue"}
STATEMENT = {
syms.if_stmt,
syms.while_stmt,
syms.for_stmt,
syms.try_stmt,
syms.except_clause,
syms.with_stmt,
syms.funcdef,
syms.classdef,
}
STANDALONE_COMMENT = 153
LOGIC_OPERATORS = {"and", "or"}
COMPARATORS = {
token.LESS,
token.GREATER,
token.EQEQUAL,
token.NOTEQUAL,
token.LESSEQUAL,
token.GREATEREQUAL,
}
MATH_OPERATORS = {
token.PLUS,
token.MINUS,
token.STAR,
token.SLASH,
token.VBAR,
token.AMPER,
token.PERCENT,
token.CIRCUMFLEX,
token.TILDE,
token.LEFTSHIFT,
token.RIGHTSHIFT,
token.DOUBLESTAR,
token.DOUBLESLASH,
}
STARS = {token.STAR, token.DOUBLESTAR}
VARARGS_PARENTS = {
syms.arglist,
syms.argument, # double star in arglist
syms.trailer, # single argument to call
syms.typedargslist,
syms.varargslist, # lambdas
}
UNPACKING_PARENTS = {
syms.atom, # single element of a list or set literal
syms.dictsetmaker,
syms.listmaker,
syms.testlist_gexp,
}
EXPRS = {
syms.expr,
syms.xor_expr,
syms.and_expr,
syms.shift_expr,
syms.arith_expr,
syms.trailer,
syms.term,
syms.power,
}
COMPREHENSION_PRIORITY = 20
COMMA_PRIORITY = 10
TERNARY_PRIORITY = 7
LOGIC_PRIORITY = 5
STRING_PRIORITY = 4
COMPARATOR_PRIORITY = 3
MATH_PRIORITY = 1
@dataclass
class BracketTracker:
"""Keeps track of brackets on a line."""
depth: int = 0
bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
delimiters: Dict[LeafID, Priority] = Factory(dict)
previous: Optional[Leaf] = None
_for_loop_variable: bool = False
_lambda_arguments: bool = False
def mark(self, leaf: Leaf) -> None:
"""Mark `leaf` with bracket-related metadata. Keep track of delimiters.
All leaves receive an int `bracket_depth` field that stores how deep
within brackets a given leaf is. 0 means there are no enclosing brackets
that started on this line.
If a leaf is itself a closing bracket, it receives an `opening_bracket`
field that it forms a pair with. This is a one-directional link to
avoid reference cycles.
If a leaf is a delimiter (a token on which Black can split the line if
needed) and it's on depth 0, its `id()` is stored in the tracker's
`delimiters` field.
"""
if leaf.type == token.COMMENT:
return
self.maybe_decrement_after_for_loop_variable(leaf)
self.maybe_decrement_after_lambda_arguments(leaf)
if leaf.type in CLOSING_BRACKETS:
self.depth -= 1
opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
leaf.opening_bracket = opening_bracket
leaf.bracket_depth = self.depth
if self.depth == 0:
delim = is_split_before_delimiter(leaf, self.previous)
if delim and self.previous is not None:
self.delimiters[id(self.previous)] = delim
else:
delim = is_split_after_delimiter(leaf, self.previous)
if delim:
self.delimiters[id(leaf)] = delim
if leaf.type in OPENING_BRACKETS:
self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
self.depth += 1
self.previous = leaf
self.maybe_increment_lambda_arguments(leaf)
self.maybe_increment_for_loop_variable(leaf)
def any_open_brackets(self) -> bool:
"""Return True if there is an yet unmatched open bracket on the line."""
return bool(self.bracket_match)
def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
"""Return the highest priority of a delimiter found on the line.
Values are consistent with what `is_split_*_delimiter()` return.
Raises ValueError on no delimiters.
"""
return max(v for k, v in self.delimiters.items() if k not in exclude)
def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
"""In a for loop, or comprehension, the variables are often unpacks.
To avoid splitting on the comma in this situation, increase the depth of
tokens between `for` and `in`.
"""
if leaf.type == token.NAME and leaf.value == "for":
self.depth += 1
self._for_loop_variable = True
return True
return False
def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
"""See `maybe_increment_for_loop_variable` above for explanation."""
if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
self.depth -= 1
self._for_loop_variable = False
return True
return False
def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
"""In a lambda expression, there might be more than one argument.
To avoid splitting on the comma in this situation, increase the depth of
tokens between `lambda` and `:`.
"""
if leaf.type == token.NAME and leaf.value == "lambda":
self.depth += 1
self._lambda_arguments = True
return True
return False
def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
"""See `maybe_increment_lambda_arguments` above for explanation."""
if self._lambda_arguments and leaf.type == token.COLON:
self.depth -= 1
self._lambda_arguments = False
return True
return False
@dataclass
class Line:
"""Holds leaves and comments. Can be printed with `str(line)`."""
depth: int = 0
leaves: List[Leaf] = Factory(list)
comments: List[Tuple[Index, Leaf]] = Factory(list)
bracket_tracker: BracketTracker = Factory(BracketTracker)
inside_brackets: bool = False
def append(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Add a new `leaf` to the end of the line.
Unless `preformatted` is True, the `leaf` will receive a new consistent
whitespace prefix and metadata applied by :class:`BracketTracker`.
Trailing commas are maybe removed, unpacked for loop variables are
demoted from being delimiters.
Inline comments are put aside.
"""
has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
if not has_value:
return
if self.leaves and not preformatted:
# Note: at this point leaf.prefix should be empty except for
# imports, for which we only preserve newlines.
if leaf.type == token.LSQB:
lsqb_leaf = leaf
else:
lsqb_leaf = self.bracket_tracker.bracket_match.get(
(self.bracket_tracker.depth - 1, token.RSQB)
)
complex_subscript = False
if lsqb_leaf is not None:
subscript_start = lsqb_leaf.next_sibling
if subscript_start.type == syms.subscriptlist:
subscript_start = child_towards(subscript_start, leaf)
complex_subscript = subscript_start is not None and any(
map(lambda n: n.type in EXPRS, subscript_start.pre_order())
)
leaf.prefix += whitespace(leaf, complex_subscript=complex_subscript)
if self.inside_brackets or not preformatted:
self.bracket_tracker.mark(leaf)
self.maybe_remove_trailing_comma(leaf)
if not self.append_comment(leaf):
self.leaves.append(leaf)
def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
"""Like :func:`append()` but disallow invalid standalone comment structure.
Raises ValueError when any `leaf` is appended after a standalone comment
or when a standalone comment is not the first leaf on the line.
"""
if self.bracket_tracker.depth == 0:
if self.is_comment:
raise ValueError("cannot append to standalone comments")
if self.leaves and leaf.type == STANDALONE_COMMENT:
raise ValueError(
"cannot append standalone comments to a populated line"
)
self.append(leaf, preformatted=preformatted)
@property
def is_comment(self) -> bool:
"""Is this line a standalone comment?"""
return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
@property
def is_decorator(self) -> bool:
"""Is this line a decorator?"""
return bool(self) and self.leaves[0].type == token.AT
@property
def is_import(self) -> bool:
"""Is this an import line?"""
return bool(self) and is_import(self.leaves[0])
@property
def is_class(self) -> bool:
"""Is this line a class definition?"""
return (
bool(self)
and self.leaves[0].type == token.NAME
and self.leaves[0].value == "class"
)
@property
def is_def(self) -> bool:
"""Is this a function definition? (Also returns True for async defs.)"""
try:
first_leaf = self.leaves[0]
except IndexError:
return False
try:
second_leaf: Optional[Leaf] = self.leaves[1]
except IndexError:
second_leaf = None
return (
(first_leaf.type == token.NAME and first_leaf.value == "def")
or (
first_leaf.type == token.ASYNC
and second_leaf is not None
and second_leaf.type == token.NAME
and second_leaf.value == "def"
)
)
@property
def is_flow_control(self) -> bool:
"""Is this line a flow control statement?
Those are `return`, `raise`, `break`, and `continue`.
"""
return (
bool(self)
and self.leaves[0].type == token.NAME
and self.leaves[0].value in FLOW_CONTROL
)
@property
def is_yield(self) -> bool:
"""Is this line a yield statement?"""
return (
bool(self)
and self.leaves[0].type == token.NAME
and self.leaves[0].value == "yield"
)
def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
"""If so, needs to be split before emitting."""
for leaf in self.leaves:
if leaf.type == STANDALONE_COMMENT:
if leaf.bracket_depth <= depth_limit:
return True
return False
def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
"""Remove trailing comma if there is one and it's safe."""
if not (
self.leaves
and self.leaves[-1].type == token.COMMA
and closing.type in CLOSING_BRACKETS
):
return False
if closing.type == token.RBRACE:
self.remove_trailing_comma()
return True
if closing.type == token.RSQB:
comma = self.leaves[-1]
if comma.parent and comma.parent.type == syms.listmaker:
self.remove_trailing_comma()
return True
# For parens let's check if it's safe to remove the comma. If the
# trailing one is the only one, we might mistakenly change a tuple
# into a different type by removing the comma.
depth = closing.bracket_depth + 1
commas = 0
opening = closing.opening_bracket
for _opening_index, leaf in enumerate(self.leaves):
if leaf is opening:
break
else:
return False
for leaf in self.leaves[_opening_index + 1 :]:
if leaf is closing:
break
bracket_depth = leaf.bracket_depth
if bracket_depth == depth and leaf.type == token.COMMA:
commas += 1
if leaf.parent and leaf.parent.type == syms.arglist:
commas += 1
break
if commas > 1:
self.remove_trailing_comma()
return True
return False
def append_comment(self, comment: Leaf) -> bool:
"""Add an inline or standalone comment to the line."""
if (
comment.type == STANDALONE_COMMENT
and self.bracket_tracker.any_open_brackets()
):
comment.prefix = ""
return False
if comment.type != token.COMMENT:
return False
after = len(self.leaves) - 1
if after == -1:
comment.type = STANDALONE_COMMENT
comment.prefix = ""
return False
else:
self.comments.append((after, comment))
return True
def comments_after(self, leaf: Leaf) -> Iterator[Leaf]:
"""Generate comments that should appear directly after `leaf`."""
for _leaf_index, _leaf in enumerate(self.leaves):
if leaf is _leaf:
break
else:
return
for index, comment_after in self.comments:
if _leaf_index == index:
yield comment_after
def remove_trailing_comma(self) -> None:
"""Remove the trailing comma and moves the comments attached to it."""
comma_index = len(self.leaves) - 1
for i in range(len(self.comments)):
comment_index, comment = self.comments[i]
if comment_index == comma_index:
self.comments[i] = (comma_index - 1, comment)
self.leaves.pop()
def __str__(self) -> str:
"""Render the line."""
if not self:
return "\n"
indent = " " * self.depth
leaves = iter(self.leaves)
first = next(leaves)
res = f"{first.prefix}{indent}{first.value}"
for leaf in leaves:
res += str(leaf)
for _, comment in self.comments:
res += str(comment)
return res + "\n"
def __bool__(self) -> bool:
"""Return True if the line has leaves or comments."""
return bool(self.leaves or self.comments)
class UnformattedLines(Line):
"""Just like :class:`Line` but stores lines which aren't reformatted."""
def append(self, leaf: Leaf, preformatted: bool = True) -> None:
"""Just add a new `leaf` to the end of the lines.
The `preformatted` argument is ignored.
Keeps track of indentation `depth`, which is useful when the user
says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`.
"""
try:
list(generate_comments(leaf))
except FormatOn as f_on:
self.leaves.append(f_on.leaf_from_consumed(leaf))
raise
self.leaves.append(leaf)
if leaf.type == token.INDENT:
self.depth += 1
elif leaf.type == token.DEDENT:
self.depth -= 1
def __str__(self) -> str:
"""Render unformatted lines from leaves which were added with `append()`.
`depth` is not used for indentation in this case.
"""
if not self:
return "\n"
res = ""
for leaf in self.leaves:
res += str(leaf)