forked from facebookincubator/Bowler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtool.py
executable file
·372 lines (312 loc) · 12.9 KB
/
tool.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
#!/usr/bin/env python3
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import difflib
import logging
import multiprocessing
import os
import sys
import time
from queue import Empty
from typing import Any, Iterator, List, Optional, Sequence, Tuple
import click
from fissix import pygram
from fissix.pgen2.parse import ParseError
from fissix.refactor import RefactoringTool, _detect_future_features
from moreorless.patch import PatchException, apply_single_file
from .helpers import filename_endswith
from .types import (
BadTransform,
BowlerException,
BowlerQuit,
Filename,
FilenameMatcher,
Fixers,
Hunk,
Processor,
RetryFile,
)
PROMPT_HELP = {
"y": "apply this hunk",
"n": "skip this hunk",
"a": "apply this hunk and all remaining hunks for this file",
"d": "skip this hunk and all remaining hunks for this file",
"q": "quit; do not apply this hunk or any remaining hunks",
"?": "show help",
}
log = logging.getLogger(__name__)
def diff_texts(a: str, b: str, filename: str) -> Iterator[str]:
lines_a = a.splitlines()
lines_b = b.splitlines()
return difflib.unified_diff(lines_a, lines_b, filename, filename, lineterm="")
def prompt_user(question: str, options: str, default: str = "") -> str:
options = options.lower()
default = default.lower()
assert len(default) < 2 and default in options
if "?" not in options:
options += "?"
prompt_options = ",".join(o.upper() if o == default else o for o in options)
prompt = f"{question} [{prompt_options}]? "
result = ""
while True:
result = input(prompt).strip().lower()
if result == "?":
for option in PROMPT_HELP:
click.secho(f"{option} - {PROMPT_HELP[option]}", fg="red", bold=True)
elif len(result) == 1 and result in options:
return result
elif result:
click.echo(f'invalid response "{result}"')
elif default:
return default
class BowlerTool(RefactoringTool):
NUM_PROCESSES = os.cpu_count() or 1
IN_PROCESS = False # set when run DEBUG mode from command line
def __init__(
self,
fixers: Fixers,
*args,
interactive: bool = True,
write: bool = False,
silent: bool = False,
in_process: Optional[bool] = None,
hunk_processor: Processor = None,
filename_matcher: Optional[FilenameMatcher] = None,
**kwargs,
) -> None:
options = kwargs.pop("options", {})
super().__init__(fixers, *args, options=options, **kwargs)
self.queue_count = 0
self.queue = multiprocessing.JoinableQueue() # type: ignore
self.results = multiprocessing.Queue() # type: ignore
self.semaphore = multiprocessing.Semaphore(self.NUM_PROCESSES)
self.interactive = interactive
self.write = write
self.silent = silent
if in_process is None:
in_process = self.IN_PROCESS
# pick the most restrictive of flags; we can pickle fixers when
# using spawn.
if sys.platform == "win32" or sys.version_info > (3, 7):
in_process = True
self.in_process = in_process
self.exceptions: List[BowlerException] = []
if hunk_processor is not None:
self.hunk_processor = hunk_processor
else:
self.hunk_processor = lambda f, h: True
self.filename_matcher = filename_matcher or filename_endswith(".py")
def log_error(self, msg: str, *args: Any, **kwds: Any) -> None:
self.logger.error(msg, *args, **kwds)
def get_fixers(self) -> Tuple[Fixers, Fixers]:
fixers = [f(self.options, self.fixer_log) for f in self.fixers]
pre: Fixers = [f for f in fixers if f.order == "pre"]
post: Fixers = [f for f in fixers if f.order == "post"]
return pre, post
def processed_file(
self, new_text: str, filename: str, old_text: str = "", *args, **kwargs
) -> List[Hunk]:
self.files.append(filename)
hunks: List[Hunk] = []
if old_text != new_text:
a, b, *lines = list(diff_texts(old_text, new_text, filename))
hunk: Hunk = []
for line in lines:
if line.startswith("@@"):
if hunk:
hunks.append([a, b, *hunk])
hunk = []
hunk.append(line)
if hunk:
hunks.append([a, b, *hunk])
original_grammar = self.driver.grammar
if "print_function" in _detect_future_features(new_text):
self.driver.grammar = pygram.python_grammar_no_print_statement
try:
new_tree = self.driver.parse_string(new_text)
if new_tree is None:
raise AssertionError("Re-parsed CST is None")
except Exception as e:
raise BadTransform(
f"Transforms generated invalid CST for {filename}",
filename=filename,
hunks=hunks,
) from e
finally:
self.driver.grammar = original_grammar
return hunks
def refactor_file(self, filename: str, *a, **k) -> List[Hunk]:
try:
hunks: List[Hunk] = []
input, encoding = self._read_python_source(filename)
if input is None:
# Reading the file failed.
return hunks
except (OSError, UnicodeDecodeError) as e:
log.error(f"Skipping {filename}: failed to read because {e}")
return hunks
try:
if not input.endswith("\n"):
input += "\n"
tree = self.refactor_string(input, filename)
if tree:
hunks = self.processed_file(str(tree), filename, input)
except ParseError as e:
log.exception("Skipping {filename}: failed to parse ({e})")
return hunks
def refactor_dir(self, dir_name: str, *a, **k) -> None:
"""Descends down a directory and refactor every Python file found.
Python files are those for which `self.filename_matcher(filename)`
returns true, to allow for custom extensions.
Files and subdirectories starting with '.' are skipped.
"""
for dirpath, dirnames, filenames in os.walk(dir_name):
self.log_debug("Descending into %s", dirpath)
dirnames.sort()
filenames.sort()
for name in filenames:
fullname = os.path.join(dirpath, name)
if not name.startswith(".") and self.filename_matcher(
Filename(fullname)
):
self.queue_work(Filename(fullname))
# Modify dirnames in-place to remove subdirs with leading dots
dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")]
def refactor_queue(self) -> None:
self.semaphore.acquire()
while True:
filename = self.queue.get()
if filename is None:
break
try:
hunks = self.refactor_file(filename)
self.results.put((filename, hunks, None))
except RetryFile:
self.log_debug(f"Retrying {filename} later...")
self.queue.put(filename)
except BowlerException as e:
log.exception(f"Bowler exception during transform of {filename}: {e}")
self.results.put((filename, e.hunks, e))
except Exception as e:
log.exception(f"Skipping {filename}: failed to transform because {e}")
self.results.put((filename, [], e))
finally:
self.queue.task_done()
self.semaphore.release()
def queue_work(self, filename: Filename) -> None:
self.queue.put(filename)
self.queue_count += 1
def refactor(self, items: Sequence[str], *a, **k) -> None:
"""Refactor a list of files and directories."""
for dir_or_file in sorted(items):
if os.path.isdir(dir_or_file):
self.refactor_dir(dir_or_file)
else:
self.queue_work(Filename(dir_or_file))
children: List[multiprocessing.Process] = []
if self.in_process:
self.queue.put(None)
self.refactor_queue()
else:
child_count = max(1, min(self.NUM_PROCESSES, self.queue_count))
self.log_debug(f"starting {child_count} processes")
for i in range(child_count):
child = multiprocessing.Process(target=self.refactor_queue)
child.start()
children.append(child)
self.queue.put(None)
results_count = 0
while True:
try:
filename, hunks, exc = self.results.get_nowait()
results_count += 1
if exc:
self.log_error(f"{type(exc).__name__}: {exc}")
if exc.__cause__:
self.log_error(
f" {type(exc.__cause__).__name__}: {exc.__cause__}"
)
if isinstance(exc, BowlerException) and exc.hunks:
diff = "\n".join("\n".join(hunk) for hunk in exc.hunks)
self.log_error(f"Generated transform:\n{diff}")
self.exceptions.append(exc)
else:
self.log_debug(f"results: got {len(hunks)} hunks for {filename}")
self.process_hunks(filename, hunks)
except Empty:
if self.queue.empty() and results_count == self.queue_count:
break
elif not self.in_process and not any(
child.is_alive() for child in children
):
self.log_debug(f"child processes stopped without consuming work")
break
else:
time.sleep(0.05)
except BowlerQuit:
for child in children:
child.terminate()
break
self.log_debug(f"all children stopped and all diff hunks processed")
def process_hunks(self, filename: Filename, hunks: List[Hunk]) -> None:
auto_yes = False
result = ""
accepted_hunks = ""
for hunk in hunks:
if self.hunk_processor(filename, hunk) is False:
continue
if not self.silent:
for line in hunk:
if line.startswith("---"):
click.secho(line, fg="red", bold=True)
elif line.startswith("+++"):
click.secho(line, fg="green", bold=True)
elif line.startswith("-"):
click.secho(line, fg="red")
elif line.startswith("+"):
click.secho(line, fg="green")
else:
click.echo(line)
if self.interactive:
if auto_yes:
click.echo(f"Applying remaining hunks to {filename}")
result = "y"
else:
result = prompt_user("Apply this hunk", "ynqad", "n")
self.log_debug(f"result = {result}")
if result == "q":
self.apply_hunks(accepted_hunks, filename)
raise BowlerQuit()
elif result == "d":
self.apply_hunks(accepted_hunks, filename)
return # skip all remaining hunks
elif result == "n":
continue
elif result == "a":
auto_yes = True
result = "y"
elif result != "y":
raise ValueError("unknown response")
if result == "y" or self.write:
accepted_hunks += "\n".join(hunk[2:]) + "\n"
self.apply_hunks(accepted_hunks, filename)
def apply_hunks(self, accepted_hunks, filename):
if accepted_hunks:
with open(filename) as f:
data = f.read()
try:
accepted_hunks = f"--- {filename}\n+++ {filename}\n{accepted_hunks}"
new_data = apply_single_file(data, accepted_hunks)
except PatchException as err:
log.exception(f"failed to apply patch hunk: {err}")
return
with open(filename, "w") as f:
f.write(new_data)
def run(self, paths: Sequence[str]) -> int:
if not self.errors:
self.refactor(paths)
self.summarize()
return int(bool(self.errors or self.exceptions))