This repository has been archived by the owner on Apr 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsixer.py
executable file
·1552 lines (1268 loc) · 50.5 KB
/
sixer.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 collections
import functools
import optparse
import os
import re
import sys
import tokenize
# Maximum range which creates a list on Python 2. For example, xrange(10) can
# be replaced with range(10) without "from six.moves import range".
MAX_RANGE = 1024
# Modules of the Python standard library
STDLIB_MODULES = set((
"StringIO",
"copy",
"csv",
"datetime",
"glob",
"heapq",
"importlib",
"itertools",
"json",
"logging",
"os",
"re",
"socket",
"string",
"sys",
"textwrap",
"traceback",
"types",
"unittest",
"urlparse",
))
# Name of third-party modules
THIRD_PARTY_MODULES = [
"django",
"eventlet",
"iso8601",
"keystoneclient",
"numpy",
"mock",
"mox3",
"oslo_concurrency",
"oslo_config",
"oslo_db",
"oslo_i18n",
"oslo_log",
"oslo_messaging",
"oslo_middleware",
"oslo_rootwrap",
"oslo_serialization",
"oslo_utils",
"oslotest",
"selenium",
"six",
"subunit",
"testtools",
"webob",
"wsme",
]
# Modules of the application
APPLICATION_MODULES = set((
"ceilometer",
"cinder",
"congress",
"glance",
"glance_store",
"horizon",
"neutron",
"nova",
"openstack_dashboard",
"swift",
))
# Ugly regular expressions because I'm too lazy to write a real parser,
# and Match objects are convinient to modify code in-place
def import_regex(name):
# 'import test\n', 'import test\n\n'
# but not ony match 'import test\n' in 'import test\n\nimport test\n'
# (don't match the second newline if it's followed by an import)
regex = r"^import %s\n(?:\n(?!from|import))?" % name
return re.compile(regex, re.MULTILINE)
def from_import_regex(module, symbol):
# 'from test import symbol\n', 'from test import symbol\n\n'
# but not ony match 'from test import symbol\n' in 'from test import symbol\n\nimport test2'
# (don't match the second newline if it's followed by an import)
regex = r"^from %s import %s\n(?:\n(?!from|import))?" % (module, symbol)
return re.compile(regex, re.MULTILINE)
# 'identifier', 'var3', 'NameCamelCase'
IDENTIFIER_REGEX = r'[a-zA-Z_][a-zA-Z0-9_]*'
# 'name', 'module.name'
QUALNAME_REGEX = r'%s(?:\.%s)*' % (IDENTIFIER_REGEX, IDENTIFIER_REGEX)
# '[0]'
GETITEM_REGEX = r'\[[^]]+\]'
# '()' or '(obj, {})', don't support nested calls: 'f(g())'
CALL_REGEX = r'\([^()]*\)'
# '[0]' or '(obj, {})' or '()[key]'
SUFFIX_REGEX = r'(?:%s|%s)' % (GETITEM_REGEX, CALL_REGEX)
# 'var' or 'var[0]' or 'func()' or 'func()[0]'
SUBEXPR_REGEX = r'%s(?:%s)*' % (IDENTIFIER_REGEX, SUFFIX_REGEX)
# 'inst' or 'self.attr' or 'self.attr[0]'
EXPR_REGEX = r'%s(?:\.%s)*' % (SUBEXPR_REGEX, SUBEXPR_REGEX)
# '"hello"', "'hello'"
_QUOTE1_STRING_REGEX = r'"(?:[^"\\]|\\[tn"])*"'
_QUOTE2_STRING_REGEX = r"'(?:[^'\\]|\\[tn'])*'"
STRING_REGEX = r'(?:%s|%s)' % (_QUOTE1_STRING_REGEX, _QUOTE2_STRING_REGEX)
_EXPR_STRING_REGEX = '(?:%s|%s)' % (EXPR_REGEX, STRING_REGEX)
# [a, b, c]
LIST_REGEX = (r'\[ *%s *(?:, *%s *)*\]'
% (_EXPR_STRING_REGEX,
_EXPR_STRING_REGEX))
# (a,)
_TUPLE1_REGEX = r'\( *%s *, *\)' % _EXPR_STRING_REGEX
# (a, b, c)
_TUPLEN_REGEX = (r'\( *%s *(?:, *%s *)+\)'
% (_EXPR_STRING_REGEX, _EXPR_STRING_REGEX))
# expr, 'string', (a, b, c), [a, b, c]
EXPR_STRING_REGEX = ('(?:%s)'
% '|'.join((EXPR_REGEX, STRING_REGEX, LIST_REGEX,
_TUPLE1_REGEX, _TUPLEN_REGEX)))
# '(...)'
SUBPARENT_REGEX= r'\([^()]+\)'
# '(...)' or '(...(...)...)' (max: 1 level of nested parenthesis)
PARENT_REGEX = r'\([^()]*(?:%s)?[^()]*\)' % SUBPARENT_REGEX
IMPORT_GROUP_REGEX = re.compile(r"^(?:import|from) .*\n(?:(?:import|from) .*\n)*\n*",
re.MULTILINE)
IMPORT_NAME_REGEX = re.compile(r"^(?:import|from) (%s)" % IDENTIFIER_REGEX,
re.MULTILINE)
# 'abc', 'sym1, sym2'
FROM_IMPORT_SYMBOLS_REGEX = r"%s(?:, %s)*" % (IDENTIFIER_REGEX, IDENTIFIER_REGEX)
def parse_import_groups(content):
pos = 0
import_groups = []
while True:
match = IMPORT_GROUP_REGEX.search(content, pos)
if not match:
break
import_group = match.group(0)
imports = [match.group(1)
for match in IMPORT_NAME_REGEX.finditer(import_group)]
import_groups.append((match.start(), match.end(), set(imports)))
pos = match.end()
return import_groups
def parse_import(line):
line = line.strip()
if line.startswith("import "):
return line[7:].split(".")
elif line.startswith("from "):
pos = 5
pos2 = line.find(" import ", pos)
names = line[pos:pos2].split(".")
names.append(line[pos2+len(" import "):])
return names
else:
raise SyntaxError("unable to parse import %r" % line)
def get_line(content, pos):
eol = content.find("\n", pos)
return content[pos:eol + 1]
class Operation:
NAME = "<name>"
DOC = "<doc>"
def __init__(self, patcher):
self.patcher = patcher
self.options = patcher.options
def patch(self, content):
raise NotImplementedError
def check(self, content):
raise NotImplementedError
def warning(self, message):
message = ("[%s] %s: %s"
% (self.NAME, self.patcher.current_file, message))
self.patcher.warning(message)
def warn_line(self, line):
self.warning(line.strip())
class Iteritems(Operation):
NAME = "iteritems"
DOC = "replace dict.iteritems() with six.iteritems(dict)"
REGEX = re.compile(r"(%s)\.iteritems\(\)" % EXPR_REGEX)
CHECK_REGEX = re.compile(r"^.*\biteritems *\(.*$", re.MULTILINE)
def replace(self, regs):
return 'six.iteritems(%s)' % regs.group(1)
def patch(self, content):
new_content = self.REGEX.sub(self.replace, content)
if new_content == content:
return content
return self.patcher.add_import_six(new_content)
def check(self, content):
for match in self.CHECK_REGEX.finditer(content):
line = match.group(0)
if "six.iteritems" not in line:
self.warn_line(line)
class Itervalues(Operation):
NAME = "itervalues"
DOC = "replace dict.itervalues() with six.itervalues(dict)"
REGEX = re.compile(r"(%s)\.itervalues\(\)" % EXPR_REGEX)
CHECK_REGEX = re.compile(r"^.*\bitervalues *\(.*$", re.MULTILINE)
def replace(self, regs):
return 'six.itervalues(%s)' % regs.group(1)
def patch(self, content):
new_content = self.REGEX.sub(self.replace, content)
if new_content == content:
return content
return self.patcher.add_import_six(new_content)
def check(self, content):
for match in self.CHECK_REGEX.finditer(content):
line = match.group(0)
if "six.itervalues" not in line:
self.warn_line(line)
class HasKey(Operation):
NAME = "has_key"
DOC = "replace dict.has_key(key) with 'key in dict'"
REGEX = re.compile(r"(%s)\.has_key\((%s)\)" % (EXPR_REGEX, EXPR_REGEX))
CHECK_REGEX = re.compile(r"^.*\.has_key", re.MULTILINE)
def replace(self, regs):
return '%s in %s' % (regs.group(2), regs.group(1))
def patch(self, content):
return self.REGEX.sub(self.replace, content)
def check(self, content):
for match in self.CHECK_REGEX.finditer(content):
line = match.group(0)
if "six.iterkeys" not in line:
self.warn_line(line)
class Iterkeys(Operation):
NAME = "iterkeys"
DOC = ("replace 'for key in dict.iterkeys():' with 'for key in dict:',"
"replace dict.iterkeys() with six.iterkeys(dict)")
FOR_REGEX = re.compile(r"(for %s in %s)\.iterkeys\(\):"
% (EXPR_REGEX, EXPR_REGEX))
REGEX = re.compile(r"(%s)\.iterkeys\(\)" % EXPR_REGEX)
CHECK_REGEX = re.compile(r"^.*\biterkeys *\(.*$", re.MULTILINE)
def replace_for(self, regs):
return '%s:' % regs.group(1)
def replace(self, regs):
return 'six.iterkeys(%s)' % regs.group(1)
def patch(self, content):
content = self.FOR_REGEX.sub(self.replace_for, content)
new_content = self.REGEX.sub(self.replace, content)
if new_content != content:
content = self.patcher.add_import_six(new_content)
return content
def check(self, content):
for match in self.CHECK_REGEX.finditer(content):
line = match.group(0)
if "six.iterkeys" not in line:
self.warn_line(line)
class Next(Operation):
NAME = "next"
DOC = "replace it.next() with next(it)"
# Match 'gen.next()' and '(...).next()'
REGEX = re.compile(r"(%s|%s)\.next\(\)" % (EXPR_REGEX, PARENT_REGEX))
# '.next(' but not 'six.next('
CHECK_REGEX = re.compile(r"^.*(?<!six)\.next *\(.*$", re.MULTILINE)
# 'def next('
DEF_NEXT_LINE_REGEX = re.compile(r"^.*def next *\(.*$", re.MULTILINE)
def replace(self, regs):
expr = regs.group(1)
if expr.startswith('(') and expr.endswith(')'):
expr = expr[1:-1]
return 'next(%s)' % expr
def patch(self, content):
return self.REGEX.sub(self.replace, content)
def check(self, content):
for match in self.CHECK_REGEX.finditer(content):
self.warn_line(match.group(0))
for match in self.DEF_NEXT_LINE_REGEX.finditer(content):
self.warn_line(match.group(0))
class Long(Operation):
NAME = "long"
DOC = ("replace 123L with 123, "
"replace (int, long) with six.integer_types, "
"replace long(1) with 1")
# (int, long)
INT_LONG_REGEX = re.compile(r'\(int, *long\)')
# '123L', '0xFFL' but not '0123L'
REGEX_INT_L = re.compile(r"\b([1-9][0-9]*|0x[0-9A-Fa-f]+|0)[lL]")
# '0123L', '0600l'
OCTAL_REGEX = re.compile(r"\b0([0-9]*)[lL]")
# '0123L', '0600l'
LONG_INT_REGEX = re.compile(r"\blong *\(([0-9]*)\)")
# '123L', '123l', '0123L'
CHECK_REGEX = re.compile(r"^.*\b(?:Ox)?[0-9]+[lL].*$", re.MULTILINE)
def replace_int_l(self, regs):
return regs.group(1)
def replace_octal(self, regs):
return '0o%s' % regs.group(1)
def replace_long_int(self, regs):
return regs.group(1)
def patch(self, content):
content = self.REGEX_INT_L.sub(self.replace_int_l, content)
content = self.OCTAL_REGEX.sub(self.replace_octal, content)
content = self.LONG_INT_REGEX.sub(self.replace_long_int, content)
new_content = self.INT_LONG_REGEX.sub('six.integer_types', content)
if new_content != content:
content = self.patcher.add_import_six(new_content)
return content
def check(self, content):
for match in self.CHECK_REGEX.finditer(content):
self.warn_line(match.group(0))
class Unicode(Operation):
NAME = "unicode"
DOC = ("replace unicode with six.text_type,"
"replace (str, unicode) with six.string_types")
UNICODE_REGEX = re.compile(r'\bunicode\b')
STR_UNICODE_REGEX = re.compile(r'\(str, *unicode\)')
DEF_REGEX = re.compile(r'^ *def +%s *\(' % IDENTIFIER_REGEX, re.MULTILINE)
def _patch_line(self, line, start, end):
result = None
while True:
match = self.UNICODE_REGEX.search(line, start, end)
if not match:
return result
line = line[:match.start()] + "six.text_type" + line[match.end():]
result = line
start = match.start() + len("six.text_type")
end += len("six.text_type") - len("unicode")
def patch_unicode(self, content):
# replace unicode with six.text_type
lines = content.splitlines(True)
for index, line in enumerate(lines):
# Ugly heuristic to exclude "import ...", "from ... import ...",
# function name in "def ...(", comments and strings
# declared with """
if line.startswith(("import ", "from ")):
continue
start = 0
end = line.find("#")
if end < 0:
end = len(line)
pos = line.find('"""', start, end)
if pos != -1:
end = pos
match = self.DEF_REGEX.search(line, start, end)
if match:
start = match.end()
new_line = self._patch_line(line, start, end)
if new_line is not None:
lines[index] = new_line
return ''.join(lines)
def patch(self, content):
old_content = content
content = self.STR_UNICODE_REGEX.sub('six.string_types', content)
content = self.patch_unicode(content)
if content != old_content:
content = self.patcher.add_import_six(content)
return content
def check(self, content):
for line in content.splitlines():
end = line.find("#")
if end >= 0:
match = self.UNICODE_REGEX.search(line, 0, end)
else:
match = self.UNICODE_REGEX.search(line, 0)
if match:
self.warn_line(line)
class Xrange(Operation):
NAME = "xrange"
DOC = "replace xrange() with range() using 'from six import range'"
# 'xrange(' but not 'moves.xrange(' or 'from six.moves import xrange'
XRANGE_REGEX = re.compile("(?<!moves\.)xrange *\(")
# 'xrange(2)'
XRANGE1_REGEX = re.compile(r"(?<!moves\.)xrange\(([0-9]+)\)")
# 'xrange(1, 6)'
XRANGE2_REGEX = re.compile(r"(?<!moves\.)xrange\(([0-9]+), ([0-9]+)\)")
def patch(self, content):
need_six = False
def xrange1_replace(regs):
nonlocal need_six
end = int(regs.group(1))
if end > self.options.max_range:
need_six = True
return 'range(%s)' % end
def xrange2_replace(regs):
nonlocal need_six
start = int(regs.group(1))
end = int(regs.group(2))
if (end - start) > self.options.max_range:
need_six = True
return 'range(%s, %s)' % (start, end)
new_content = self.XRANGE1_REGEX.sub(xrange1_replace, content)
new_content = self.XRANGE2_REGEX.sub(xrange2_replace, new_content)
new_content2 = self.XRANGE_REGEX.sub("range(", new_content)
if new_content2 != new_content:
need_six = True
new_content = new_content2
if need_six:
new_content = self.patcher.add_import(new_content, 'from six.moves import range')
return new_content
def check(self, content):
for line in content.splitlines():
if self.XRANGE_REGEX.search(line):
self.warn_line(line)
class Basestring(Operation):
NAME = "basestring"
DOC = "replace basestring with six.string_types"
# match 'basestring' word
BASESTRING_REGEX = re.compile(r"\bbasestring\b")
def patch(self, content):
new_content = self.BASESTRING_REGEX.sub('six.string_types', content)
if new_content == content:
return content
return self.patcher.add_import_six(new_content)
def check(self, content):
for line in content.splitlines():
if 'basestring' in line:
self.warn_line(line)
class StringIO(Operation):
NAME = "stringio"
DOC = ("replace StringIO.StringIO with six.StringIO"
" and cStringIO.StringIO with six.moves.cStringIO")
# 'import StringIO'
IMPORT_STRINGIO_REGEX = import_regex(r"StringIO")
# 'from StringIO import StringIO'
FROM_IMPORT_STRINGIO_REGEX = from_import_regex(r"StringIO", r"StringIO")
# 'from StringIO import StringIO'
FROM_IMPORT_CSTRINGIO_REGEX = from_import_regex(r"cStringIO", r"StringIO")
# 'import cStringIO'
IMPORT_CSTRINGIO_REGEX = import_regex(r"cStringIO")
# 'import cStringIO as StringIO'
IMPORT_CSTRINGIO_AS_REGEX = import_regex(r"cStringIO as StringIO")
# 'StringIO.', 'cStringIO.', but not 'six.StringIO' or 'six.cStringIO'
CSTRINGIO_REGEX = re.compile(r'(?<!six\.)\bc?StringIO\.')
def _patch_stringio1(self, content):
# Replace 'from StringIO import StringIO'
# with 'from six import StringIO'
new_content = self.FROM_IMPORT_STRINGIO_REGEX.sub('', content)
if new_content == content:
return content
return self.patcher.add_import(new_content, 'from six import StringIO')
def _patch_stringio2(self, content):
# Replace 'import StringIO' + 'StringIO.StringIO'
# with 'import six' + 'six.StringIO'
new_content = self.IMPORT_STRINGIO_REGEX.sub('', content)
if new_content == content:
return content
new_content = self.patcher.add_import_six(new_content)
return new_content.replace("StringIO.StringIO", "six.StringIO")
def _patch_cstringio1(self, content):
# Replace 'from cStringIO import StringIO'
# with 'from six.moves import cStringIO as StringIO'
new_content = self.FROM_IMPORT_CSTRINGIO_REGEX.sub('', content)
if new_content == content:
return content
new_content = self.patcher.add_import(new_content,
"from six.moves import cStringIO as StringIO")
return new_content
def _patch_cstringio2(self, content):
# Replace 'import cStringIO' + 'cStringIO.StringIO'
# with 'from six import moves' + 'moves.cStringIO'
new_content = self.IMPORT_CSTRINGIO_REGEX.sub('', content)
if new_content == content:
return content
new_content = self.patcher.add_import(new_content, "from six import moves")
return new_content.replace("cStringIO.StringIO", "moves.cStringIO")
def _patch_cstringio3(self, content):
# Replace 'import cStringIO as StringIO' + 'StringIO.StringIO'
# with 'from six import moves' + 'moves.cStringIO'
new_content = self.IMPORT_CSTRINGIO_AS_REGEX.sub('', content)
if new_content == content:
return content
new_content = self.patcher.add_import(new_content, "from six import moves")
return new_content.replace("StringIO.StringIO", "moves.cStringIO")
def patch(self, content):
content = self._patch_stringio1(content)
content = self._patch_stringio2(content)
content = self._patch_cstringio1(content)
content = self._patch_cstringio2(content)
content = self._patch_cstringio3(content)
return content
def check(self, content):
for line in content.splitlines():
if 'StringIO.StringIO' in line or self.CSTRINGIO_REGEX.search(line):
self.warn_line(line)
class Urllib(Operation):
NAME = "urllib"
DOC = "replace urllib, urllib2 and urlparse with six.moves.urllib"
# 'import urllib', 'import urllib2', 'import urlparse'
IMPORT_URLLIB_REGEX = import_regex(r"\b(?:urllib2?|urlparse)\b")
# 'from urlparse import symbol, symbol2'
FROM_IMPORT_REGEX = from_import_regex('(urllib2?|urlparse)',
'(%s)' % FROM_IMPORT_SYMBOLS_REGEX)
# 'from urlparse import'
FROM_IMPORT_WARN_REGEX = re.compile(r"^from (?:urllib2?|urlparse) import",
re.MULTILINE)
# 'urllib.attr'
# 'urllib2.urlparse.attr'
# 'urllib2.attr'
# 'urlparse.attr'
URLLIB_ATTR_REGEX = re.compile(r"\b(?:urllib|urllib2(?:\.(?:urllib|urlparse))?|urlparse)\.(%s)"
% IDENTIFIER_REGEX)
SIX_MOVES_URLLIB = {
# six.moves.urllib submodule => Python 2 urllib/urllib2 symbols
'error': (
'HTTPError',
'URLError',
),
'request': (
'HTTPBasicAuthHandler',
'HTTPCookieProcessor',
'HTTPPasswordMgrWithDefaultRealm',
'HTTPSHandler',
'OpenerDirector',
'ProxyHandler',
'Request',
'build_opener',
'install_opener',
'pathname2url',
'urlopen',
),
'parse': (
'parse_qs',
'parse_qsl',
'quote',
'quote_plus',
'unquote',
'urlencode',
'urljoin',
'urlparse',
'urlsplit',
'urlunparse',
'urlunsplit',
),
}
URLLIB = {}
for submodule, symbols in SIX_MOVES_URLLIB.items():
for symbol in symbols:
URLLIB[symbol] = submodule
# 'urllib.error', 'urllib.parse', 'urllib.request'
URLLIB_UNCHANGED = set('urllib.%s' % submodule
for submodule in SIX_MOVES_URLLIB)
def replace(self, regs):
text = regs.group(0)
if text in self.URLLIB_UNCHANGED:
return text
name = regs.group(1)
if name == 'parse_http_list':
# six has no helper for parse_http_list() yet
return text
try:
submodule = self.URLLIB[name]
except KeyError:
self.warning("Unknown urllib symbol: %s" % text)
return text
return 'urllib.%s.%s' % (submodule, name)
def replace_import_from(self, add_imports, regs):
module = regs.group(1)
symbols = regs.group(2)
if 'parse_http_list' in symbols:
# six has no helper for parse_http_list() yet
return regs.group(0)
imports = collections.defaultdict(list)
for symbol in symbols.split(','):
name = symbol.strip()
try:
submodule = self.URLLIB[name]
except KeyError:
raise Exception("unknown urllib symbol: %s.%s"
% (module, name))
imports[submodule].append(name)
for submodule, names in imports.items():
line = ('from six.moves.urllib.%s import %s'
% (submodule, ', '.join(names)))
add_imports.add(line)
return ''
def patch_import(self, content):
new_content = self.IMPORT_URLLIB_REGEX.sub('', content)
if new_content == content:
return content
content = new_content
content = self.URLLIB_ATTR_REGEX.sub(self.replace, content)
return self.patcher.add_import(content,
"from six.moves import urllib")
def patch_from_import(self, content, add_imports):
replace_cb = functools.partial(self.replace_import_from, add_imports)
content = self.FROM_IMPORT_REGEX.sub(replace_cb, content)
return content
def patch(self, content):
add_imports = set()
content = self.patch_import(content)
content = self.patch_from_import(content, add_imports)
for line in sorted(add_imports):
content = self.patcher.add_import(content, line)
return content
def check(self, content):
for line in content.splitlines():
if 'urllib2.parse_http_list' in line:
self.warn_line(line)
elif self.FROM_IMPORT_WARN_REGEX.search(line):
self.warn_line(line)
class Raise(Operation):
NAME = "raise"
DOC = ("replace 'raise exc, msg' with 'raise exc(msg)'"
" and replace 'raise a, b, c' with 'six.reraise(a, b, c)'")
# 'raise a, b, c' expr
RAISE3_REGEX = re.compile(r"raise (%s), *(%s), *(%s)"
% (EXPR_REGEX, EXPR_REGEX, EXPR_REGEX))
# 'raise a, b' expr
RAISE2_REGEX = re.compile(r'''raise (%s), *(%s|'[^']+'|"[^"]+")$'''
% (EXPR_REGEX, EXPR_REGEX), re.MULTILINE)
# 'raise a,' line
RAISE_LINE_REGEX = re.compile(r"^.*raise %s,.*$" % EXPR_REGEX,
re.MULTILINE)
def raise2_replace(self, regs):
return 'raise %s(%s)' % (regs.group(1), regs.group(2))
def raise3_replace(self, regs):
exc_type = regs.group(1)
exc_value = regs.group(2)
exc_tb = regs.group(3)
# 'raise exc_info[0], exc_info[1], exc_inf[2]'
# => 'six.reraise(*exc_info)'
if (exc_type.endswith('[0]')
and exc_value.endswith('[1]')
and exc_tb.endswith('[2]')):
return ('six.reraise(*%s)' % exc_type[:-3])
return ('six.reraise(%s, %s, %s)'
% (exc_type, exc_value, exc_tb))
def patch(self, content):
old_content = content
content = self.RAISE2_REGEX.sub(self.raise2_replace, content)
new_content = self.RAISE3_REGEX.sub(self.raise3_replace, content)
if new_content != content:
content = self.patcher.add_import_six(new_content)
return content
def check(self, content):
for match in self.RAISE_LINE_REGEX.finditer(content):
self.warn_line(match.group(0))
class Except(Operation):
NAME = "except"
DOC = ("replace 'except ValueError, exc:' with "
"'except ValueError as exc:', replace "
"'except (TypeError, ValueError), exc:' with "
"'except (TypeError, ValueError) as exc:'.")
# 'except ValueError, exc:'
EXCEPT_REGEX = re.compile(r"except (%s), *(%s):"
% (QUALNAME_REGEX, IDENTIFIER_REGEX))
# 'except (ValueError, TypeError), exc:'
EXCEPT2_REGEX = re.compile(r"except (\(%s(?:, *%s)*\)), *(%s):"
% (QUALNAME_REGEX, IDENTIFIER_REGEX,
IDENTIFIER_REGEX))
EXCEPT_WARN_REGEX = re.compile(r"except [^,()]+, *[^:]+:")
EXCEPT_WARN2_REGEX = re.compile(r"except \([^()]+\), *[^:]+:")
def except_replace(self, regs):
return 'except %s as %s:' % (regs.group(1), regs.group(2))
def patch(self, content):
content = self.EXCEPT_REGEX.sub(self.except_replace, content)
return self.EXCEPT2_REGEX.sub(self.except_replace, content)
def check(self, content):
for line in content.splitlines():
if (self.EXCEPT_WARN_REGEX.search(line)
or self.EXCEPT_WARN2_REGEX.search(line)):
self.warn_line(line)
class SixMoves(Operation):
NAME = "six_moves"
DOC = ("replace Python 2 imports with six and six.moves imports")
SIX_MODULE_MOVES = {
# Python 2 import => six.moves import
'BaseHTTPServer': 'BaseHTTPServer',
'ConfigParser': 'configparser',
'Cookie': 'http_cookies',
'HTMLParser': 'html_parser',
'Queue': 'queue',
'SimpleHTTPServer': 'SimpleHTTPServer',
'SimpleXMLRPCServer': 'xmlrpc_server',
'__builtin__': 'builtins',
'cPickle': 'cPickle',
'cookielib': 'http_cookiejar',
'htmlentitydefs': 'html_entities',
'httplib': 'http_client',
'repr': 'reprlib',
# 'thread': '_thread',
'xmlrpclib': 'xmlrpc_client',
}
# 'BaseHTTPServer', '__builtin__', 'repr', ...
SIX_MOVES_REGEX = sorted(map(re.escape, SIX_MODULE_MOVES.keys()))
SIX_MOVES_REGEX = ("(?:%s)" % '|'.join(SIX_MOVES_REGEX))
# 'import BaseHTTPServer', 'import repr as reprlib'
IMPORT_REGEX = import_regex(r"(%s)( as %s)?"
% (SIX_MOVES_REGEX, IDENTIFIER_REGEX))
# 'from BaseHTTPServer import ...'
FROM_IMPORT_REGEX = from_import_regex(r"(%s)" % SIX_MOVES_REGEX,
r"(%s)" % FROM_IMPORT_SYMBOLS_REGEX)
# "patch('__builtin__."
MOCK_REGEX = re.compile(r"""(patch\(['"])(%s)\."""
% SIX_MOVES_REGEX, re.MULTILINE)
SIX_BUILTIN_MOVES = {
# Python 2 builtin function => six.moves import
'raw_input': 'input',
'reduce': 'reduce',
'reload': 'reload_module',
}
SIX_FUNCTIONS = {
# Python 2 builtin function => six function
'unichr': 'unichr',
}
# 'reduce(', 'reload('
# but not '.reduce(' (exclude 'moves.reduce(...)')
BUILTIN_REGEX = re.compile(r'(?<!\.)\b(%s)\b( *\()'
% '|'.join(SIX_BUILTIN_MOVES))
# 'unichr('
# but not '.unichr('
FUNCTION_REGEX = re.compile(r'(?<!\.)\b(%s)\b( *\()'
% '|'.join(SIX_FUNCTIONS))
def replace_mock(self, regs):
name = regs.group(2)
new_name = self.SIX_MODULE_MOVES[name]
return '%ssix.moves.%s.' % (regs.group(1), new_name)
def replace_import(self, add_imports, replace_names, regs):
name = regs.group(1)
as_name = regs.group(2)
new_name = self.SIX_MODULE_MOVES[name]
line = 'from six.moves import %s' % new_name
if as_name:
line += as_name
add_imports.add(line)
replace_names.add((name, new_name))
return ''
def replace_from(self, add_imports, regs):
new_name = self.SIX_MODULE_MOVES[regs.group(1)]
symbols = regs.group(2)
line = 'from six.moves.%s import %s' % (new_name, symbols)
add_imports.add(line)
return ''
def replace_builtin(self, add_imports, regs):
new_name = self.SIX_BUILTIN_MOVES[regs.group(1)]
suffix = regs.group(2)
line = 'from six.moves import %s' % new_name
add_imports.add(line)
return new_name + suffix
def replace_all_builtins(self, add_imports, content):
six_builtin_moves = dict(self.SIX_BUILTIN_MOVES)
for regs in self.BUILTIN_REGEX.finditer(content):
name = regs.group(1)
if name not in six_builtin_moves:
# already removed
continue
new_name = six_builtin_moves[name]
pattern = 'from six.moves import %s\n' % new_name
if pattern in content:
# the symbol comes from six.moves, no need to patch it
del six_builtin_moves[name]
builtin_regex2 = re.compile(r'(?<!\.)\b(%s)\b( *\()'
% '|'.join(six_builtin_moves))
replace_cb = functools.partial(self.replace_builtin, add_imports)
return builtin_regex2.sub(replace_cb, content)
def replace_function(self, add_imports, regs):
new_name = self.SIX_FUNCTIONS[regs.group(1)]
suffix = regs.group(2)
add_imports.add('import six')
return 'six.%s%s' % (new_name, suffix)
def replace_all_functions(self, add_imports, content):
replace_cb = functools.partial(self.replace_function, add_imports)
return self.FUNCTION_REGEX.sub(replace_cb, content)
def patch(self, content):
add_imports = set()
replace_names = set()
replace_cb = functools.partial(self.replace_import,
add_imports, replace_names)
content = self.IMPORT_REGEX.sub(replace_cb, content)
replace_cb = functools.partial(self.replace_from, add_imports)
content = self.FROM_IMPORT_REGEX.sub(replace_cb, content)
content = self.replace_all_builtins(add_imports, content)
content = self.replace_all_functions(add_imports, content)
for old_name, new_name in replace_names:
# Only match words
regex = r'\b(?<!\.)%s\b' % re.escape(old_name)
content = re.sub(regex, new_name, content)
for line in sorted(add_imports):
names = parse_import(line)
content = self.patcher.add_import_names(content, line, names)
content = self.MOCK_REGEX.sub(self.replace_mock, content)
return content
def check(self, content):
pass
class Itertools(Operation):
NAME = "itertools"
DOC = ("replace itertools.ifilter with six.moves.filter, "
"similar change for ifilterfalse, imap, izip and izip_longest")
FUNCTIONS = {
# itertools function => six.moves function
'ifilter': 'filter',
'ifilterfalse': 'filterfalse',
'imap': 'map',
'izip': 'zip',
'izip_longest': 'zip_longest',
}
FUNCTIONS_REGEX = '(?:%s)' % '|'.join(FUNCTIONS)
# 'from itertools import imap'
IFUNC_IMPORT_REGEX = from_import_regex(r"itertools", FUNCTIONS_REGEX)
# 'imap', 'ifilter'
IFUNC_REGEX = re.compile(r'\b(%s)\b' % FUNCTIONS_REGEX)
# 'itertools.imap'
ITERTOOLS_IFUNC_REGEX = re.compile(r'\bitertools\.(%s)\b' % FUNCTIONS_REGEX)
# 'itertools.'
ITERTOOLS_REGEX = re.compile(r'\bitertools\.')
# 'import itertools'
IMPORT_ITERTOOLS_REGEX = import_regex(r"itertools")
def replace(self, regs):
func = regs.group(1)
six_func = self.FUNCTIONS[func]
return 'six.moves.%s' % six_func
def patch_from_import(self, content):
# Replace itertools.imap with six.moves.map
new_content = self.IFUNC_IMPORT_REGEX.sub('', content)
if new_content == content:
return content
content = self.patcher.add_import_six(new_content)
content = self.IFUNC_REGEX.sub(self.replace, content)
return content
def patch_import(self, content):
# Replace itertools.imap with six.moves.map