|
3 | 3 | from __future__ import unicode_literals |
4 | 4 |
|
5 | 5 | import argparse |
6 | | -import re |
| 6 | +import io |
7 | 7 | import tokenize |
8 | 8 |
|
9 | 9 |
|
10 | 10 | double_quote_starts = tuple(s for s in tokenize.single_quoted if '"' in s) |
11 | | -compiled_tokenize_string = re.compile('(?<!")' + tokenize.String + '(?!")') |
12 | 11 |
|
13 | 12 |
|
14 | | -def handle_match(m): |
15 | | - string = m.group(0) |
| 13 | +def handle_match(token_text): |
| 14 | + if '"""' in token_text or "'''" in token_text: |
| 15 | + return token_text |
16 | 16 |
|
17 | 17 | for double_quote_start in double_quote_starts: |
18 | | - if string.startswith(double_quote_start): |
19 | | - meat = string[len(double_quote_start):-1] |
| 18 | + if token_text.startswith(double_quote_start): |
| 19 | + meat = token_text[len(double_quote_start):-1] |
20 | 20 | if '"' in meat or "'" in meat: |
21 | 21 | break |
22 | 22 | return double_quote_start.replace('"', "'") + meat + "'" |
23 | | - return string |
| 23 | + return token_text |
| 24 | + |
| 25 | + |
| 26 | +def get_line_offsets_by_line_no(src): |
| 27 | + # Padded so we can index with line number |
| 28 | + offsets = [None, 0] |
| 29 | + for line in src.splitlines(): |
| 30 | + offsets.append(offsets[-1] + len(line) + 1) |
| 31 | + return offsets |
24 | 32 |
|
25 | 33 |
|
26 | 34 | def fix_strings(filename): |
27 | | - contents = open(filename).read() |
28 | | - new_contents = compiled_tokenize_string.sub(handle_match, contents) |
29 | | - retval = int(new_contents != contents) |
30 | | - if retval: |
31 | | - with open(filename, 'w') as write_handle: |
| 35 | + contents = io.open(filename).read() |
| 36 | + line_offsets = get_line_offsets_by_line_no(contents) |
| 37 | + |
| 38 | + # Basically a mutable string |
| 39 | + splitcontents = list(contents) |
| 40 | + |
| 41 | + # Iterate in reverse so the offsets are always correct |
| 42 | + tokens = reversed(list(tokenize.generate_tokens( |
| 43 | + io.StringIO(contents).readline, |
| 44 | + ))) |
| 45 | + for token_type, token_text, (srow, scol), (erow, ecol), _ in tokens: |
| 46 | + if token_type == tokenize.STRING: |
| 47 | + new_text = handle_match(token_text) |
| 48 | + splitcontents[ |
| 49 | + line_offsets[srow] + scol: |
| 50 | + line_offsets[erow] + ecol |
| 51 | + ] = new_text |
| 52 | + |
| 53 | + new_contents = ''.join(splitcontents) |
| 54 | + if contents != new_contents: |
| 55 | + with io.open(filename, 'w') as write_handle: |
32 | 56 | write_handle.write(new_contents) |
33 | | - return retval |
| 57 | + return 1 |
| 58 | + else: |
| 59 | + return 0 |
34 | 60 |
|
35 | 61 |
|
36 | 62 | def main(argv=None): |
|
0 commit comments