1 | n/a | """ |
---|
2 | n/a | Main program for 2to3. |
---|
3 | n/a | """ |
---|
4 | n/a | |
---|
5 | n/a | from __future__ import with_statement, print_function |
---|
6 | n/a | |
---|
7 | n/a | import sys |
---|
8 | n/a | import os |
---|
9 | n/a | import difflib |
---|
10 | n/a | import logging |
---|
11 | n/a | import shutil |
---|
12 | n/a | import optparse |
---|
13 | n/a | |
---|
14 | n/a | from . import refactor |
---|
15 | n/a | |
---|
16 | n/a | |
---|
17 | n/a | def diff_texts(a, b, filename): |
---|
18 | n/a | """Return a unified diff of two strings.""" |
---|
19 | n/a | a = a.splitlines() |
---|
20 | n/a | b = b.splitlines() |
---|
21 | n/a | return difflib.unified_diff(a, b, filename, filename, |
---|
22 | n/a | "(original)", "(refactored)", |
---|
23 | n/a | lineterm="") |
---|
24 | n/a | |
---|
25 | n/a | |
---|
26 | n/a | class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): |
---|
27 | n/a | """ |
---|
28 | n/a | A refactoring tool that can avoid overwriting its input files. |
---|
29 | n/a | Prints output to stdout. |
---|
30 | n/a | |
---|
31 | n/a | Output files can optionally be written to a different directory and or |
---|
32 | n/a | have an extra file suffix appended to their name for use in situations |
---|
33 | n/a | where you do not want to replace the input files. |
---|
34 | n/a | """ |
---|
35 | n/a | |
---|
36 | n/a | def __init__(self, fixers, options, explicit, nobackups, show_diffs, |
---|
37 | n/a | input_base_dir='', output_dir='', append_suffix=''): |
---|
38 | n/a | """ |
---|
39 | n/a | Args: |
---|
40 | n/a | fixers: A list of fixers to import. |
---|
41 | n/a | options: A dict with RefactoringTool configuration. |
---|
42 | n/a | explicit: A list of fixers to run even if they are explicit. |
---|
43 | n/a | nobackups: If true no backup '.bak' files will be created for those |
---|
44 | n/a | files that are being refactored. |
---|
45 | n/a | show_diffs: Should diffs of the refactoring be printed to stdout? |
---|
46 | n/a | input_base_dir: The base directory for all input files. This class |
---|
47 | n/a | will strip this path prefix off of filenames before substituting |
---|
48 | n/a | it with output_dir. Only meaningful if output_dir is supplied. |
---|
49 | n/a | All files processed by refactor() must start with this path. |
---|
50 | n/a | output_dir: If supplied, all converted files will be written into |
---|
51 | n/a | this directory tree instead of input_base_dir. |
---|
52 | n/a | append_suffix: If supplied, all files output by this tool will have |
---|
53 | n/a | this appended to their filename. Useful for changing .py to |
---|
54 | n/a | .py3 for example by passing append_suffix='3'. |
---|
55 | n/a | """ |
---|
56 | n/a | self.nobackups = nobackups |
---|
57 | n/a | self.show_diffs = show_diffs |
---|
58 | n/a | if input_base_dir and not input_base_dir.endswith(os.sep): |
---|
59 | n/a | input_base_dir += os.sep |
---|
60 | n/a | self._input_base_dir = input_base_dir |
---|
61 | n/a | self._output_dir = output_dir |
---|
62 | n/a | self._append_suffix = append_suffix |
---|
63 | n/a | super(StdoutRefactoringTool, self).__init__(fixers, options, explicit) |
---|
64 | n/a | |
---|
65 | n/a | def log_error(self, msg, *args, **kwargs): |
---|
66 | n/a | self.errors.append((msg, args, kwargs)) |
---|
67 | n/a | self.logger.error(msg, *args, **kwargs) |
---|
68 | n/a | |
---|
69 | n/a | def write_file(self, new_text, filename, old_text, encoding): |
---|
70 | n/a | orig_filename = filename |
---|
71 | n/a | if self._output_dir: |
---|
72 | n/a | if filename.startswith(self._input_base_dir): |
---|
73 | n/a | filename = os.path.join(self._output_dir, |
---|
74 | n/a | filename[len(self._input_base_dir):]) |
---|
75 | n/a | else: |
---|
76 | n/a | raise ValueError('filename %s does not start with the ' |
---|
77 | n/a | 'input_base_dir %s' % ( |
---|
78 | n/a | filename, self._input_base_dir)) |
---|
79 | n/a | if self._append_suffix: |
---|
80 | n/a | filename += self._append_suffix |
---|
81 | n/a | if orig_filename != filename: |
---|
82 | n/a | output_dir = os.path.dirname(filename) |
---|
83 | n/a | if not os.path.isdir(output_dir): |
---|
84 | n/a | os.makedirs(output_dir) |
---|
85 | n/a | self.log_message('Writing converted %s to %s.', orig_filename, |
---|
86 | n/a | filename) |
---|
87 | n/a | if not self.nobackups: |
---|
88 | n/a | # Make backup |
---|
89 | n/a | backup = filename + ".bak" |
---|
90 | n/a | if os.path.lexists(backup): |
---|
91 | n/a | try: |
---|
92 | n/a | os.remove(backup) |
---|
93 | n/a | except OSError as err: |
---|
94 | n/a | self.log_message("Can't remove backup %s", backup) |
---|
95 | n/a | try: |
---|
96 | n/a | os.rename(filename, backup) |
---|
97 | n/a | except OSError as err: |
---|
98 | n/a | self.log_message("Can't rename %s to %s", filename, backup) |
---|
99 | n/a | # Actually write the new file |
---|
100 | n/a | write = super(StdoutRefactoringTool, self).write_file |
---|
101 | n/a | write(new_text, filename, old_text, encoding) |
---|
102 | n/a | if not self.nobackups: |
---|
103 | n/a | shutil.copymode(backup, filename) |
---|
104 | n/a | if orig_filename != filename: |
---|
105 | n/a | # Preserve the file mode in the new output directory. |
---|
106 | n/a | shutil.copymode(orig_filename, filename) |
---|
107 | n/a | |
---|
108 | n/a | def print_output(self, old, new, filename, equal): |
---|
109 | n/a | if equal: |
---|
110 | n/a | self.log_message("No changes to %s", filename) |
---|
111 | n/a | else: |
---|
112 | n/a | self.log_message("Refactored %s", filename) |
---|
113 | n/a | if self.show_diffs: |
---|
114 | n/a | diff_lines = diff_texts(old, new, filename) |
---|
115 | n/a | try: |
---|
116 | n/a | if self.output_lock is not None: |
---|
117 | n/a | with self.output_lock: |
---|
118 | n/a | for line in diff_lines: |
---|
119 | n/a | print(line) |
---|
120 | n/a | sys.stdout.flush() |
---|
121 | n/a | else: |
---|
122 | n/a | for line in diff_lines: |
---|
123 | n/a | print(line) |
---|
124 | n/a | except UnicodeEncodeError: |
---|
125 | n/a | warn("couldn't encode %s's diff for your terminal" % |
---|
126 | n/a | (filename,)) |
---|
127 | n/a | return |
---|
128 | n/a | |
---|
129 | n/a | def warn(msg): |
---|
130 | n/a | print("WARNING: %s" % (msg,), file=sys.stderr) |
---|
131 | n/a | |
---|
132 | n/a | |
---|
133 | n/a | def main(fixer_pkg, args=None): |
---|
134 | n/a | """Main program. |
---|
135 | n/a | |
---|
136 | n/a | Args: |
---|
137 | n/a | fixer_pkg: the name of a package where the fixers are located. |
---|
138 | n/a | args: optional; a list of command line arguments. If omitted, |
---|
139 | n/a | sys.argv[1:] is used. |
---|
140 | n/a | |
---|
141 | n/a | Returns a suggested exit status (0, 1, 2). |
---|
142 | n/a | """ |
---|
143 | n/a | # Set up option parser |
---|
144 | n/a | parser = optparse.OptionParser(usage="2to3 [options] file|dir ...") |
---|
145 | n/a | parser.add_option("-d", "--doctests_only", action="store_true", |
---|
146 | n/a | help="Fix up doctests only") |
---|
147 | n/a | parser.add_option("-f", "--fix", action="append", default=[], |
---|
148 | n/a | help="Each FIX specifies a transformation; default: all") |
---|
149 | n/a | parser.add_option("-j", "--processes", action="store", default=1, |
---|
150 | n/a | type="int", help="Run 2to3 concurrently") |
---|
151 | n/a | parser.add_option("-x", "--nofix", action="append", default=[], |
---|
152 | n/a | help="Prevent a transformation from being run") |
---|
153 | n/a | parser.add_option("-l", "--list-fixes", action="store_true", |
---|
154 | n/a | help="List available transformations") |
---|
155 | n/a | parser.add_option("-p", "--print-function", action="store_true", |
---|
156 | n/a | help="Modify the grammar so that print() is a function") |
---|
157 | n/a | parser.add_option("-v", "--verbose", action="store_true", |
---|
158 | n/a | help="More verbose logging") |
---|
159 | n/a | parser.add_option("--no-diffs", action="store_true", |
---|
160 | n/a | help="Don't show diffs of the refactoring") |
---|
161 | n/a | parser.add_option("-w", "--write", action="store_true", |
---|
162 | n/a | help="Write back modified files") |
---|
163 | n/a | parser.add_option("-n", "--nobackups", action="store_true", default=False, |
---|
164 | n/a | help="Don't write backups for modified files") |
---|
165 | n/a | parser.add_option("-o", "--output-dir", action="store", type="str", |
---|
166 | n/a | default="", help="Put output files in this directory " |
---|
167 | n/a | "instead of overwriting the input files. Requires -n.") |
---|
168 | n/a | parser.add_option("-W", "--write-unchanged-files", action="store_true", |
---|
169 | n/a | help="Also write files even if no changes were required" |
---|
170 | n/a | " (useful with --output-dir); implies -w.") |
---|
171 | n/a | parser.add_option("--add-suffix", action="store", type="str", default="", |
---|
172 | n/a | help="Append this string to all output filenames." |
---|
173 | n/a | " Requires -n if non-empty. " |
---|
174 | n/a | "ex: --add-suffix='3' will generate .py3 files.") |
---|
175 | n/a | |
---|
176 | n/a | # Parse command line arguments |
---|
177 | n/a | refactor_stdin = False |
---|
178 | n/a | flags = {} |
---|
179 | n/a | options, args = parser.parse_args(args) |
---|
180 | n/a | if options.write_unchanged_files: |
---|
181 | n/a | flags["write_unchanged_files"] = True |
---|
182 | n/a | if not options.write: |
---|
183 | n/a | warn("--write-unchanged-files/-W implies -w.") |
---|
184 | n/a | options.write = True |
---|
185 | n/a | # If we allowed these, the original files would be renamed to backup names |
---|
186 | n/a | # but not replaced. |
---|
187 | n/a | if options.output_dir and not options.nobackups: |
---|
188 | n/a | parser.error("Can't use --output-dir/-o without -n.") |
---|
189 | n/a | if options.add_suffix and not options.nobackups: |
---|
190 | n/a | parser.error("Can't use --add-suffix without -n.") |
---|
191 | n/a | |
---|
192 | n/a | if not options.write and options.no_diffs: |
---|
193 | n/a | warn("not writing files and not printing diffs; that's not very useful") |
---|
194 | n/a | if not options.write and options.nobackups: |
---|
195 | n/a | parser.error("Can't use -n without -w") |
---|
196 | n/a | if options.list_fixes: |
---|
197 | n/a | print("Available transformations for the -f/--fix option:") |
---|
198 | n/a | for fixname in refactor.get_all_fix_names(fixer_pkg): |
---|
199 | n/a | print(fixname) |
---|
200 | n/a | if not args: |
---|
201 | n/a | return 0 |
---|
202 | n/a | if not args: |
---|
203 | n/a | print("At least one file or directory argument required.", file=sys.stderr) |
---|
204 | n/a | print("Use --help to show usage.", file=sys.stderr) |
---|
205 | n/a | return 2 |
---|
206 | n/a | if "-" in args: |
---|
207 | n/a | refactor_stdin = True |
---|
208 | n/a | if options.write: |
---|
209 | n/a | print("Can't write to stdin.", file=sys.stderr) |
---|
210 | n/a | return 2 |
---|
211 | n/a | if options.print_function: |
---|
212 | n/a | flags["print_function"] = True |
---|
213 | n/a | |
---|
214 | n/a | # Set up logging handler |
---|
215 | n/a | level = logging.DEBUG if options.verbose else logging.INFO |
---|
216 | n/a | logging.basicConfig(format='%(name)s: %(message)s', level=level) |
---|
217 | n/a | logger = logging.getLogger('lib2to3.main') |
---|
218 | n/a | |
---|
219 | n/a | # Initialize the refactoring tool |
---|
220 | n/a | avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg)) |
---|
221 | n/a | unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix) |
---|
222 | n/a | explicit = set() |
---|
223 | n/a | if options.fix: |
---|
224 | n/a | all_present = False |
---|
225 | n/a | for fix in options.fix: |
---|
226 | n/a | if fix == "all": |
---|
227 | n/a | all_present = True |
---|
228 | n/a | else: |
---|
229 | n/a | explicit.add(fixer_pkg + ".fix_" + fix) |
---|
230 | n/a | requested = avail_fixes.union(explicit) if all_present else explicit |
---|
231 | n/a | else: |
---|
232 | n/a | requested = avail_fixes.union(explicit) |
---|
233 | n/a | fixer_names = requested.difference(unwanted_fixes) |
---|
234 | n/a | input_base_dir = os.path.commonprefix(args) |
---|
235 | n/a | if (input_base_dir and not input_base_dir.endswith(os.sep) |
---|
236 | n/a | and not os.path.isdir(input_base_dir)): |
---|
237 | n/a | # One or more similar names were passed, their directory is the base. |
---|
238 | n/a | # os.path.commonprefix() is ignorant of path elements, this corrects |
---|
239 | n/a | # for that weird API. |
---|
240 | n/a | input_base_dir = os.path.dirname(input_base_dir) |
---|
241 | n/a | if options.output_dir: |
---|
242 | n/a | input_base_dir = input_base_dir.rstrip(os.sep) |
---|
243 | n/a | logger.info('Output in %r will mirror the input directory %r layout.', |
---|
244 | n/a | options.output_dir, input_base_dir) |
---|
245 | n/a | rt = StdoutRefactoringTool( |
---|
246 | n/a | sorted(fixer_names), flags, sorted(explicit), |
---|
247 | n/a | options.nobackups, not options.no_diffs, |
---|
248 | n/a | input_base_dir=input_base_dir, |
---|
249 | n/a | output_dir=options.output_dir, |
---|
250 | n/a | append_suffix=options.add_suffix) |
---|
251 | n/a | |
---|
252 | n/a | # Refactor all files and directories passed as arguments |
---|
253 | n/a | if not rt.errors: |
---|
254 | n/a | if refactor_stdin: |
---|
255 | n/a | rt.refactor_stdin() |
---|
256 | n/a | else: |
---|
257 | n/a | try: |
---|
258 | n/a | rt.refactor(args, options.write, options.doctests_only, |
---|
259 | n/a | options.processes) |
---|
260 | n/a | except refactor.MultiprocessingUnsupported: |
---|
261 | n/a | assert options.processes > 1 |
---|
262 | n/a | print("Sorry, -j isn't supported on this platform.", |
---|
263 | n/a | file=sys.stderr) |
---|
264 | n/a | return 1 |
---|
265 | n/a | rt.summarize() |
---|
266 | n/a | |
---|
267 | n/a | # Return error status (0 if rt.errors is zero) |
---|
268 | n/a | return int(bool(rt.errors)) |
---|