|
2 | 2 |
|
3 | 3 | from __future__ import print_function
|
4 | 4 |
|
| 5 | +import ast |
5 | 6 | import collections
|
6 | 7 | import errno
|
7 | 8 | import os
|
8 | 9 | import sys
|
9 | 10 | import tokenize as std_tokenize
|
| 11 | +from tokenize_rt import reversed_enumerate |
| 12 | +from tokenize_rt import src_to_tokens |
| 13 | +from tokenize_rt import tokens_to_src |
10 | 14 |
|
11 | 15 | from setuptools.command import build_py as orig
|
12 | 16 |
|
@@ -74,11 +78,33 @@ def _unasync_file(self, filepath):
|
74 | 78 | tokens = _tokenize(f)
|
75 | 79 | tokens = self._unasync_tokens(tokens)
|
76 | 80 | result = _untokenize(tokens)
|
| 81 | + result = self._unasync_remove(contents=result, filename=filepath) |
77 | 82 | outfilepath = filepath.replace(self.fromdir, self.todir)
|
78 | 83 | _makedirs_existok(os.path.dirname(outfilepath))
|
79 | 84 | with open(outfilepath, "w", **write_kwargs) as f:
|
80 | 85 | print(result, file=f, end="")
|
81 | 86 |
|
| 87 | + def _unasync_remove(self, contents, filename): |
| 88 | + tree = ast.parse(contents, filename=filename) |
| 89 | + tokens = src_to_tokens(contents) |
| 90 | + comment_lines_locations = [] |
| 91 | + for tok in tokens: |
| 92 | + # find line numbers where "unasync: remove" comments are found |
| 93 | + if tok.name == 'COMMENT' and 'unasync: remove' in tok.src: # XXX: maybe make this a little more strict |
| 94 | + comment_lines_locations.append(tok.line) |
| 95 | + lines_to_remove = set() |
| 96 | + for node in ast.walk(tree): |
| 97 | + # find nodes whose line number (start line) intersect with unasync: remove comments |
| 98 | + if hasattr(node, 'lineno') and node.lineno in comment_lines_locations: |
| 99 | + for lineno in range(node.lineno, node.end_lineno + 1): |
| 100 | + # find all lines related to each node and mark those lines for removal |
| 101 | + lines_to_remove.add(lineno) |
| 102 | + for i, tok in reversed_enumerate(tokens): |
| 103 | + if tok.line in lines_to_remove: |
| 104 | + tokens.pop(i) |
| 105 | + new_contents = tokens_to_src(tokens) |
| 106 | + return new_contents |
| 107 | + |
82 | 108 | def _unasync_tokens(self, tokens):
|
83 | 109 | # TODO __await__, ...?
|
84 | 110 | used_space = None
|
|
0 commit comments