forked from hhatto/autopep8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autopep8.py
executable file
·1726 lines (1460 loc) · 59.8 KB
/
autopep8.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 python
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
A tool that automatically formats Python code to conform to the PEP 8 style
guide.
"""
from __future__ import print_function
import copy
import os
import re
import sys
import inspect
import codecs
import locale
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import token
import tokenize
from optparse import OptionParser
from subprocess import Popen, PIPE
from difflib import unified_diff
import tempfile
from distutils.version import StrictVersion
try:
import pep8
if StrictVersion(pep8.__version__) < StrictVersion('1.3a2'):
pep8 = None
except ImportError:
pep8 = None
__version__ = '0.8.1'
PEP8_BIN = 'pep8'
CR = '\r'
LF = '\n'
CRLF = '\r\n'
MAX_LINE_WIDTH = 79
def open_with_encoding(filename, encoding, mode='r'):
"""Return opened file with a specific encoding."""
try:
# Python 3
return open(filename, mode=mode, encoding=encoding)
except TypeError:
# Python 2
return codecs.open(filename, mode=mode, encoding=encoding)
def detect_encoding(filename):
"""Return file encoding."""
try:
# Python 3
try:
with open(filename, 'rb') as input_file:
encoding = tokenize.detect_encoding(input_file.readline)[0]
# Check for correctness of encoding
import io
with io.TextIOWrapper(input_file, encoding) as wrapper:
wrapper.read()
return encoding
except (SyntaxError, LookupError, UnicodeDecodeError):
return 'latin-1'
except AttributeError:
# Python 2
encoding = 'utf-8'
try:
# Check for correctness of encoding
with open_with_encoding(filename, encoding) as input_file:
input_file.read()
except UnicodeDecodeError:
encoding = 'latin-1'
return encoding
def read_from_filename(filename, readlines=False):
"""Return contents of file."""
with open_with_encoding(filename,
encoding=detect_encoding(filename)) as input_file:
return input_file.readlines() if readlines else input_file.read()
class FixPEP8(object):
"""Fix invalid code.
Fixer methods are prefixed "fix_". The _fix_source() method looks for these
automatically.
The fixer method can take either one or two arguments (in addition to
self). The first argument is "result", which is the error information from
pep8. The second argument, "logical", is required only for logical-line
fixes.
The fixer method can return the list of modified lines or None. An empty
list would mean that no changes were made. None would mean that only the
line reported in the pep8 error was modified. Note that the modified line
numbers that are returned are indexed at 1. This typically would correspond
with the line number reported in the pep8 error information.
[fixed method list]
- e111
- e121,e122,e123,e124,e125,e126,e127,e128
- e201,e202,e203
- e211
- e221,e222,e223,e224,e225
- e231
- e251
- e261,e262
- e271,e272,e273,e274
- e301,e302,e303
- e401
- e502
- e701,e702
- e711
- e721
- w291,w293
- w391
- w602,w603,w604
"""
def __init__(self, filename, options, contents=None):
self.filename = filename
if contents is None:
self.source = read_from_filename(filename, readlines=True)
else:
sio = StringIO(contents)
self.source = sio.readlines()
self.original_source = copy.copy(self.source)
self.newline = find_newline(self.source)
self.options = options
self.indent_word = _get_indentword(''.join(self.source))
self.logical_start = None
self.logical_end = None
# method definition
self.fix_e111 = self.fix_e101
self.fix_e128 = self.fix_e127
self.fix_e202 = self.fix_e201
self.fix_e203 = self.fix_e201
self.fix_e211 = self.fix_e201
self.fix_e221 = self.fix_e271
self.fix_e222 = self.fix_e271
self.fix_e223 = self.fix_e271
self.fix_e241 = self.fix_e271
self.fix_e242 = self.fix_e224
self.fix_e261 = self.fix_e262
self.fix_e272 = self.fix_e271
self.fix_e273 = self.fix_e271
self.fix_e274 = self.fix_e271
self.fix_w191 = self.fix_e101
def _fix_source(self, results):
completed_lines = set()
for result in sorted(results, key=_priority_key):
if result['line'] in completed_lines:
continue
fixed_methodname = 'fix_%s' % result['id'].lower()
if hasattr(self, fixed_methodname):
fix = getattr(self, fixed_methodname)
is_logical_fix = len(inspect.getargspec(fix).args) > 2
if is_logical_fix:
# Do not run logical fix if any lines have been modified.
if completed_lines:
continue
logical = self._get_logical(result)
if not logical:
continue
modified_lines = fix(result, logical)
else:
modified_lines = fix(result)
if modified_lines:
completed_lines.update(modified_lines)
elif modified_lines == []: # Empty list means no fix
if self.options.verbose >= 2:
print(
'Not fixing {f} on line {l}'.format(
f=result['id'], l=result['line']),
file=sys.stderr)
else: # We assume one-line fix when None
completed_lines.add(result['line'])
else:
if self.options.verbose >= 3:
print("'%s' is not defined." % fixed_methodname,
file=sys.stderr)
info = result['info'].strip()
print('%s:%s:%s:%s' % (self.filename,
result['line'],
result['column'],
info),
file=sys.stderr)
def fix(self):
"""Return a version of the source code with PEP 8 violations fixed."""
if pep8:
pep8_options = {
'ignore':
self.options.ignore and self.options.ignore.split(','),
'select':
self.options.select and self.options.select.split(','),
}
results = _execute_pep8(pep8_options, self.source)
else:
if self.options.verbose:
print('Running in compatibility mode. Consider '
'upgrading to the latest pep8.',
file=sys.stderr)
results = _spawn_pep8((['--ignore=' + self.options.ignore]
if self.options.ignore else []) +
(['--select=' + self.options.select]
if self.options.select else []) +
[self.filename])
if self.options.verbose:
print('{n} issues to fix'.format(
n=len(results)), file=sys.stderr)
self._fix_source(filter_results(source=''.join(self.source),
results=results))
return ''.join(self.source)
def fix_e101(self, _):
"""Reindent all lines."""
reindenter = Reindenter(self.source, self.newline)
modified_line_numbers = reindenter.run()
if modified_line_numbers:
self.source = reindenter.fixed_lines()
return modified_line_numbers
else:
return []
def find_logical(self, force=False):
# make a variable which is the index of all the starts of lines
if not force and self.logical_start is not None:
return
logical_start = []
logical_end = []
last_newline = True
sio = StringIO(''.join(self.source))
parens = 0
for t in tokenize.generate_tokens(sio.readline):
if t[0] in [tokenize.COMMENT, tokenize.DEDENT,
tokenize.INDENT, tokenize.NL,
tokenize.ENDMARKER]:
continue
if not parens and t[0] in [
tokenize.NEWLINE, tokenize.SEMI
]:
last_newline = True
logical_end.append((t[3][0] - 1, t[2][1]))
continue
if last_newline and not parens:
logical_start.append((t[2][0] - 1, t[2][1]))
last_newline = False
if t[0] == tokenize.OP:
if t[1] in '([{':
parens += 1
elif t[1] in '}])':
parens -= 1
self.logical_start = logical_start
self.logical_end = logical_end
def _get_logical(self, result):
"""Return the logical line corresponding to the result.
Assumes input is already E702-clean.
"""
try:
self.find_logical()
except (IndentationError, tokenize.TokenError):
return None
row = result['line'] - 1
col = result['column'] - 1
ls = None
le = None
for i in range(0, len(self.logical_start), 1):
x = self.logical_end[i]
if x[0] > row or (x[0] == row and x[1] > col):
le = x
ls = self.logical_start[i]
break
if ls is None:
return None
original = self.source[ls[0]:le[0] + 1]
return ls, le, original
def _fix_reindent(self, result, logical, fix_distinct=False):
"""Fix a badly indented line.
This is done by adding or removing from its initial indent only.
"""
if not logical:
return []
ls, _, original = logical
try:
rewrapper = Wrapper(original, hard_wrap=MAX_LINE_WIDTH)
except (tokenize.TokenError, IndentationError):
return []
valid_indents = rewrapper.pep8_expected()
if not rewrapper.rel_indent:
return []
if result['line'] > ls[0]:
# got a valid continuation line number from pep8
row = result['line'] - ls[0] - 1
# always pick the first option for this
valid = valid_indents[row]
got = rewrapper.rel_indent[row]
else:
# Line number from pep8 isn't a continuation line. Instead,
# compare our own function's result, look for the first mismatch,
# and just hope that we take fewer than 100 iterations to finish.
for row in range(0, len(original), 1):
valid = valid_indents[row]
got = rewrapper.rel_indent[row]
if valid != got:
break
line = ls[0] + row
# always pick the expected indent, for now.
indent_to = valid[0]
if fix_distinct and indent_to == 4:
if len(valid) == 1:
return []
else:
indent_to = valid[1]
if got != indent_to:
orig_line = self.source[line]
new_line = ' ' * (indent_to) + orig_line.lstrip()
if new_line == orig_line:
return []
else:
self.source[line] = new_line
return [line + 1] # Line indexed at 1
else:
return []
def fix_e121(self, result, logical):
"""Fix indentation to be a multiple of four."""
# Fix by adjusting initial indent level.
return self._fix_reindent(result, logical)
def fix_e122(self, result, logical):
"""Add absent indentation for hanging indentation."""
# Fix by adding an initial indent.
return self._fix_reindent(result, logical)
def fix_e123(self, result, logical):
"""Align closing bracket to match opening bracket."""
# Fix by deleting whitespace to the correct level.
if not logical:
return []
logical_lines = logical[2]
line_index = result['line'] - 1
original_line = self.source[line_index]
fixed_line = (_get_indentation(logical_lines[0]) +
original_line.lstrip())
if fixed_line == original_line:
# Fall back to slower method.
return self._fix_reindent(result, logical)
else:
self.source[line_index] = fixed_line
def fix_e124(self, result, logical):
"""Align closing bracket to match visual indentation."""
# Fix by inserting whitespace before the closing bracket.
return self._fix_reindent(result, logical)
def fix_e125(self, result, logical):
"""Indent to distinguish line from next logical line."""
# Fix by indenting the line in error to the next stop.
modified_lines = self._fix_reindent(result, logical, fix_distinct=True)
if modified_lines:
return modified_lines
else:
# Fallback
line_index = result['line'] - 1
original_line = self.source[line_index]
self.source[line_index] = self.indent_word + original_line
def fix_e126(self, result, logical):
"""Fix over-indented hanging indentation."""
# fix by deleting whitespace to the left
if not logical:
return []
logical_lines = logical[2]
line_index = result['line'] - 1
original = self.source[line_index]
fixed = (_get_indentation(logical_lines[0]) +
self.indent_word + original.lstrip())
if fixed == original:
# Fallback to slower method.
return self._fix_reindent(result, logical)
else:
self.source[line_index] = fixed
def fix_e127(self, result, logical):
"""Fix visual indentation."""
# Fix by inserting/deleting whitespace to the correct level.
modified_lines = self._align_visual_indent(result, logical)
if modified_lines:
return modified_lines
else:
# Fallback to slower method.
return self._fix_reindent(result, logical)
def _align_visual_indent(self, result, logical):
"""Correct visual indent.
This includes over (E127) and under (E128) indented lines.
"""
if not logical:
return []
logical_lines = logical[2]
line_index = result['line'] - 1
original = self.source[line_index]
fixed = original
if '(' in logical_lines[0]:
fixed = logical_lines[0].find('(') * ' ' + original.lstrip()
elif logical_lines[0].rstrip().endswith('\\'):
fixed = (_get_indentation(logical_lines[0]) +
self.indent_word + original.lstrip())
else:
return []
if fixed == original:
return []
else:
self.source[line_index] = fixed
def fix_e201(self, result):
"""Remove extraneous whitespace."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
# When multiline strings are involved, pep8 reports the error as
# being at the start of the multiline string, which doesn't work
# for us.
if '"""' in target or "'''" in target:
return []
fixed = fix_whitespace(target,
offset=offset,
replacement='')
if fixed == target:
return []
else:
self.source[line_index] = fixed
def fix_e224(self, result):
"""Remove extraneous whitespace around operator."""
target = self.source[result['line'] - 1]
offset = result['column'] - 1
fixed = target[:offset] + target[offset:].replace('\t', ' ')
self.source[result['line'] - 1] = fixed
def fix_e225(self, result):
"""Fix missing whitespace around operator."""
target = self.source[result['line'] - 1]
offset = result['column'] - 1
fixed = target[:offset] + ' ' + target[offset:]
# Only proceed if non-whitespace characters match.
# And make sure we don't break the indentation.
if (fixed.replace(' ', '') == target.replace(' ', '') and
_get_indentation(fixed) == _get_indentation(target)):
self.source[result['line'] - 1] = fixed
else:
return []
def fix_e231(self, result):
"""Add missing whitespace."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column']
fixed = target[:offset] + ' ' + target[offset:]
self.source[line_index] = fixed
def fix_e251(self, result):
"""Remove whitespace around parameter '=' sign."""
line_index = result['line'] - 1
target = self.source[line_index]
# This is necessary since pep8 sometimes reports columns that goes
# past the end of the physical line. This happens in cases like,
# foo(bar\n=None)
c = min(result['column'] - 1,
len(target) - 1)
if target[c].strip():
fixed = target
else:
fixed = target[:c].rstrip() + target[c:].lstrip()
# There could be an escaped newline
#
# def foo(a=\
# 1)
if (fixed.endswith('=\\\n') or
fixed.endswith('=\\\r\n') or
fixed.endswith('=\\\r')):
self.source[line_index] = fixed.rstrip('\n\r \t\\')
self.source[line_index + 1] = \
self.source[line_index + 1].lstrip()
return [line_index + 1, line_index + 2] # Line indexed at 1
self.source[result['line'] - 1] = fixed
def fix_e262(self, result):
"""Fix spacing after comment hash."""
target = self.source[result['line'] - 1]
offset = result['column']
code = target[:offset].rstrip(' \t#')
comment = target[offset:].lstrip(' \t#')
fixed = code + (' # ' + comment if comment.strip()
else self.newline)
self.source[result['line'] - 1] = fixed
def fix_e271(self, result):
"""Fix extraneous whitespace around keywords."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
fixed = fix_whitespace(target,
offset=offset,
replacement=' ')
if fixed == target:
return []
else:
self.source[line_index] = fixed
def fix_e301(self, result):
"""Add missing blank line."""
cr = self.newline
self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
def fix_e302(self, result):
"""Add missing 2 blank lines."""
add_linenum = 2 - int(result['info'].split()[-1])
cr = self.newline * add_linenum
self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
def fix_e303(self, result):
"""Remove extra blank lines."""
delete_linenum = int(result['info'].split('(')[1].split(')')[0]) - 2
delete_linenum = max(1, delete_linenum)
# We need to count because pep8 reports an offset line number if there
# are comments.
cnt = 0
line = result['line'] - 2
modified_lines = []
while cnt < delete_linenum:
if line < 0:
break
if not self.source[line].strip():
self.source[line] = ''
modified_lines.append(1 + line) # Line indexed at 1
cnt += 1
line -= 1
return modified_lines
def fix_e304(self, result):
"""Remove blank line following function decorator."""
line = result['line'] - 2
if not self.source[line].strip():
self.source[line] = ''
def fix_e401(self, result):
"""Put imports on separate lines."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
if not target.lstrip().startswith('import'):
return []
# pep8 (1.3.1) reports false positive if there is an import statement
# followed by a semicolon and some unrelated statement with commas in
# it.
if ';' in target:
return []
indentation = target.split('import ')[0]
fixed = (target[:offset].rstrip('\t ,') + self.newline +
indentation + 'import ' + target[offset:].lstrip('\t ,'))
self.source[line_index] = fixed
def fix_e501(self, result):
"""Try to make lines fit within 79 characters."""
line_index = result['line'] - 1
target = self.source[line_index]
indent = _get_indentation(target)
source = target[len(indent):]
sio = StringIO(target)
# Check for multiline string.
try:
tokens = list(tokenize.generate_tokens(sio.readline))
except (tokenize.TokenError, IndentationError):
multi_line_candidate = break_multi_line(
target, newline=self.newline, indent_word=self.indent_word)
if multi_line_candidate:
self.source[line_index] = multi_line_candidate
return
else:
return []
# Prefer
# my_long_function_name(
# x, y, z, ...)
#
# over
# my_long_function_name(x, y,
# z, ...)
candidate0 = _shorten_line(tokens, source, target, indent,
self.indent_word, newline=self.newline,
reverse=False)
candidate1 = _shorten_line(tokens, source, target, indent,
self.indent_word, newline=self.newline,
reverse=True)
if candidate0 and candidate1:
if candidate0.split(self.newline)[0].endswith('('):
self.source[line_index] = candidate0
else:
self.source[line_index] = candidate1
elif candidate0:
self.source[line_index] = candidate0
elif candidate1:
self.source[line_index] = candidate1
else:
# Otherwise both don't work
return []
def fix_e502(self, result):
"""Remove extraneous escape of newline."""
line_index = result['line'] - 1
target = self.source[line_index]
self.source[line_index] = target.rstrip('\n\r \t\\') + self.newline
def fix_e701(self, result):
"""Put colon-separated compound statement on separate lines."""
line_index = result['line'] - 1
target = self.source[line_index]
c = result['column']
fixed_source = (target[:c] + self.newline +
_get_indentation(target) + self.indent_word +
target[c:].lstrip('\n\r \t\\'))
self.source[result['line'] - 1] = fixed_source
def fix_e702(self, result, logical):
"""Put semicolon-separated compound statement on separate lines."""
logical_lines = logical[2]
line_index = result['line'] - 1
target = self.source[line_index]
if target.rstrip().endswith('\\'):
# Normalize '1; \\\n2' into '1; 2'.
self.source[line_index] = target.rstrip('\n \r\t\\')
self.source[line_index + 1] = self.source[line_index + 1].lstrip()
return [line_index + 1, line_index + 2]
if target.rstrip().endswith(';'):
self.source[line_index] = target.rstrip('\n \r\t;') + self.newline
return
offset = result['column'] - 1
first = target[:offset].rstrip(';').rstrip()
second = (_get_indentation(logical_lines[0]) +
target[offset:].lstrip(';').lstrip())
self.source[line_index] = first + self.newline + second
def fix_e711(self, result):
"""Fix comparison."""
line_index = result['line'] - 1
target = self.source[line_index]
offset = result['column'] - 1
right_offset = offset + 2
if right_offset >= len(target):
return []
left = target[:offset].rstrip()
center = target[offset:right_offset]
right = target[right_offset:].lstrip()
if not right.startswith('None'):
return []
if center.strip() == '==':
new_center = 'is'
elif center.strip() == '!=':
new_center = 'is not'
else:
return []
self.source[line_index] = ' '.join([left, new_center, right])
def fix_e721(self, _):
"""Switch to use isinstance()."""
return self.refactor('idioms')
def fix_w291(self, result):
"""Remove trailing whitespace."""
fixed_line = self.source[result['line'] - 1].rstrip()
self.source[result['line'] - 1] = '%s%s' % (fixed_line, self.newline)
def fix_w293(self, result):
"""Remove trailing whitespace on blank line."""
assert not self.source[result['line'] - 1].strip()
self.source[result['line'] - 1] = self.newline
def fix_w391(self, _):
"""Remove trailing blank lines."""
blank_count = 0
for line in reversed(self.source):
line = line.rstrip()
if line:
break
else:
blank_count += 1
original_length = len(self.source)
self.source = self.source[:original_length - blank_count]
return range(1, 1 + original_length)
def refactor(self, fixer_name, ignore=None):
"""Return refactored code using lib2to3.
Skip if ignore string is produced in the refactored code.
"""
from lib2to3 import pgen2
try:
new_text = refactor_with_2to3(''.join(self.source),
fixer_name=fixer_name)
except (pgen2.parse.ParseError,
UnicodeDecodeError, UnicodeEncodeError):
return []
try:
original = unicode(''.join(self.source).strip(), 'utf-8')
except (NameError, TypeError):
original = ''.join(self.source).strip()
if original == new_text.strip():
return []
else:
if ignore:
if ignore in new_text and ignore not in ''.join(self.source):
return []
original_length = len(self.source)
self.source = [new_text]
return range(1, 1 + original_length)
def fix_w601(self, _):
"""Replace the {}.has_key() form with 'in'."""
return self.refactor('has_key')
def fix_w602(self, _):
"""Fix deprecated form of raising exception."""
return self.refactor('raise',
ignore='with_traceback')
def fix_w603(self, _):
"""Replace <> with !=."""
return self.refactor('ne')
def fix_w604(self, _):
"""Replace backticks with repr()."""
return self.refactor('repr')
def find_newline(source):
"""Return type of newline used in source."""
cr, lf, crlf = 0, 0, 0
for s in source:
if CRLF in s:
crlf += 1
elif CR in s:
cr += 1
elif LF in s:
lf += 1
_max = max(cr, crlf, lf)
if _max == lf:
return LF
elif _max == crlf:
return CRLF
elif _max == cr:
return CR
else:
return LF
def _get_indentword(source):
"""Return indentation type."""
sio = StringIO(source)
indent_word = ' ' # Default in case source has no indentation
try:
for t in tokenize.generate_tokens(sio.readline):
if t[0] == token.INDENT:
indent_word = t[1]
break
except (tokenize.TokenError, IndentationError):
pass
return indent_word
def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return ''
def _analyze_pep8result(result):
tmp = result.split(':')
filename = tmp[0]
line = int(tmp[1])
column = int(tmp[2])
info = ' '.join(result.split()[1:])
pep8id = info.lstrip().split()[0]
return dict(id=pep8id, filename=filename, line=line,
column=column, info=info)
def _get_difftext(old, new, filename):
diff = unified_diff(old, new, 'original/' + filename, 'fixed/' + filename)
return ''.join(diff)
def _priority_key(pep8_result):
"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things
like indentation.
"""
priority = ['e101', 'e111', 'w191', # Global fixes
'e701', # Fix multiline colon-based before semicolon based
'e702', # Break multiline statements early
'e225', 'e231', # things that make lines longer
'e201', # Remove extraneous whitespace before breaking lines
'e501', # before we break lines
]
key = pep8_result['id'].lower()
if key in priority:
return priority.index(key)
else:
# Lowest priority
return len(priority)
def _shorten_line(tokens, source, target, indentation, indent_word, newline,
reverse=False):
"""Separate line at OPERATOR."""
max_line_width_minus_indentation = MAX_LINE_WIDTH - len(indentation)
if reverse:
tokens.reverse()
for tkn in tokens:
# Don't break on '=' after keyword as this violates PEP 8.
if token.OP == tkn[0] and tkn[1] != '=':
offset = tkn[2][1] + 1
if reverse:
if offset > (max_line_width_minus_indentation -
len(indent_word)):
continue
else:
if (len(target.rstrip()) - offset >
(max_line_width_minus_indentation -
len(indent_word))):
continue
first = source[:offset - len(indentation)]
second_indent = indentation
if first.rstrip().endswith('('):
second_indent += indent_word
elif '(' in first:
second_indent += ' ' * (1 + first.find('('))
else:
second_indent += indent_word
second = (second_indent +
source[offset - len(indentation):].lstrip())
if not second.strip():
continue
# Don't modify if lines are not short enough
if len(first) > max_line_width_minus_indentation:
continue
if len(second) > MAX_LINE_WIDTH: # Already includes indentation
continue
# Do not begin a line with a comma
if second.lstrip().startswith(','):
continue
# Do end a line with a dot
if first.rstrip().endswith('.'):
continue
if tkn[1] in '+-*/':
fixed = first + ' \\' + newline + second
else:
fixed = first + newline + second
if check_syntax(fixed):
return indentation + fixed
return None
def fix_whitespace(line, offset, replacement):
"""Replace whitespace at offset and return fixed line."""
# Replace escaped newlines too
left = line[:offset].rstrip('\n\r \t\\')
right = line[offset:].lstrip('\n\r \t\\')
if right.startswith('#'):
return line
else:
return left + replacement + right
def _spawn_pep8(pep8_options):
"""Execute pep8 via subprocess.Popen."""
for path in os.environ['PATH'].split(':'):
if os.path.exists(os.path.join(path, PEP8_BIN)):
cmd = ([os.path.join(path, PEP8_BIN)] +
pep8_options)
p = Popen(cmd, stdout=PIPE)
output = p.communicate()[0].decode('utf-8')
return [_analyze_pep8result(l)
for l in output.splitlines()]
raise Exception("'%s' is not found." % PEP8_BIN)
def _execute_pep8(pep8_options, source):
"""Execute pep8 via python method calls."""
class QuietReport(pep8.BaseReport):
"""Version of checker that does not print."""
def __init__(self, options):
super(QuietReport, self).__init__(options)
self.__full_error_results = []
def error(self, line_number, offset, text, _):
"""Collect errors."""
code = super(QuietReport, self).error(line_number, offset, text, _)
if code:
self.__full_error_results.append(
dict(id=code, line=line_number,
column=offset + 1, info=text))