blob: 3929db70d37568986ffc6dd10b18348ea17e2229 [file] [log] [blame]
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00001"""
2Main program for 2to3.
3"""
4
Benjamin Peterson5dfad9d2010-05-07 18:58:23 +00005from __future__ import with_statement
6
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00007import sys
8import os
Benjamin Peterson840077c2009-07-20 15:33:09 +00009import difflib
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000010import logging
Benjamin Peterson43caaa02008-12-16 03:35:28 +000011import shutil
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000012import optparse
13
14from . import refactor
15
Benjamin Peterson840077c2009-07-20 15:33:09 +000016
17def diff_texts(a, b, filename):
18 """Return a unified diff of two strings."""
19 a = a.splitlines()
20 b = b.splitlines()
21 return difflib.unified_diff(a, b, filename, filename,
22 "(original)", "(refactored)",
23 lineterm="")
24
25
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +000026class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
Benjamin Peterson08be2912008-09-27 21:09:10 +000027 """
28 Prints output to stdout.
29 """
30
Benjamin Peterson840077c2009-07-20 15:33:09 +000031 def __init__(self, fixers, options, explicit, nobackups, show_diffs):
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000032 self.nobackups = nobackups
Benjamin Peterson840077c2009-07-20 15:33:09 +000033 self.show_diffs = show_diffs
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000034 super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
35
Benjamin Peterson08be2912008-09-27 21:09:10 +000036 def log_error(self, msg, *args, **kwargs):
37 self.errors.append((msg, args, kwargs))
38 self.logger.error(msg, *args, **kwargs)
39
Benjamin Peterson84ad84e2009-05-09 01:01:14 +000040 def write_file(self, new_text, filename, old_text, encoding):
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000041 if not self.nobackups:
42 # Make backup
43 backup = filename + ".bak"
44 if os.path.lexists(backup):
45 try:
46 os.remove(backup)
47 except os.error, err:
48 self.log_message("Can't remove backup %s", backup)
49 try:
50 os.rename(filename, backup)
51 except os.error, err:
52 self.log_message("Can't rename %s to %s", filename, backup)
53 # Actually write the new file
Benjamin Peterson84ad84e2009-05-09 01:01:14 +000054 write = super(StdoutRefactoringTool, self).write_file
55 write(new_text, filename, old_text, encoding)
Benjamin Peterson03943d92008-12-21 01:29:32 +000056 if not self.nobackups:
Benjamin Peterson37fc8232009-01-03 16:34:02 +000057 shutil.copymode(backup, filename)
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000058
Benjamin Peterson840077c2009-07-20 15:33:09 +000059 def print_output(self, old, new, filename, equal):
60 if equal:
61 self.log_message("No changes to %s", filename)
62 else:
63 self.log_message("Refactored %s", filename)
64 if self.show_diffs:
Benjamin Petersonabb42742009-12-28 23:50:41 +000065 diff_lines = diff_texts(old, new, filename)
66 try:
Benjamin Peterson5dfad9d2010-05-07 18:58:23 +000067 if self.output_lock is not None:
68 with self.output_lock:
69 for line in diff_lines:
70 print line
71 sys.stdout.flush()
72 else:
73 for line in diff_lines:
74 print line
Benjamin Petersonabb42742009-12-28 23:50:41 +000075 except UnicodeEncodeError:
76 warn("couldn't encode %s's diff for your terminal" %
77 (filename,))
78 return
Benjamin Peterson840077c2009-07-20 15:33:09 +000079
80
81def warn(msg):
82 print >> sys.stderr, "WARNING: %s" % (msg,)
Benjamin Peterson08be2912008-09-27 21:09:10 +000083
84
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000085def main(fixer_pkg, args=None):
86 """Main program.
87
88 Args:
89 fixer_pkg: the name of a package where the fixers are located.
90 args: optional; a list of command line arguments. If omitted,
91 sys.argv[1:] is used.
92
93 Returns a suggested exit status (0, 1, 2).
94 """
95 # Set up option parser
Benjamin Peterson43caaa02008-12-16 03:35:28 +000096 parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000097 parser.add_option("-d", "--doctests_only", action="store_true",
98 help="Fix up doctests only")
99 parser.add_option("-f", "--fix", action="append", default=[],
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000100 help="Each FIX specifies a transformation; default: all")
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +0000101 parser.add_option("-j", "--processes", action="store", default=1,
102 type="int", help="Run 2to3 concurrently")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000103 parser.add_option("-x", "--nofix", action="append", default=[],
Benjamin Peterson848cfa22010-12-04 02:18:58 +0000104 help="Prevent a transformation from being run")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000105 parser.add_option("-l", "--list-fixes", action="store_true",
Benjamin Peterson5dfad9d2010-05-07 18:58:23 +0000106 help="List available transformations")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000107 parser.add_option("-p", "--print-function", action="store_true",
Benjamin Peterson42d26d92009-11-25 18:16:46 +0000108 help="Modify the grammar so that print() is a function")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000109 parser.add_option("-v", "--verbose", action="store_true",
110 help="More verbose logging")
Benjamin Peterson840077c2009-07-20 15:33:09 +0000111 parser.add_option("--no-diffs", action="store_true",
112 help="Don't show diffs of the refactoring")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000113 parser.add_option("-w", "--write", action="store_true",
114 help="Write back modified files")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000115 parser.add_option("-n", "--nobackups", action="store_true", default=False,
Benjamin Peterson848cfa22010-12-04 02:18:58 +0000116 help="Don't write backups for modified files")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000117
118 # Parse command line arguments
119 refactor_stdin = False
Benjamin Peterson42d26d92009-11-25 18:16:46 +0000120 flags = {}
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000121 options, args = parser.parse_args(args)
Benjamin Peterson840077c2009-07-20 15:33:09 +0000122 if not options.write and options.no_diffs:
123 warn("not writing files and not printing diffs; that's not very useful")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000124 if not options.write and options.nobackups:
125 parser.error("Can't use -n without -w")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000126 if options.list_fixes:
127 print "Available transformations for the -f/--fix option:"
128 for fixname in refactor.get_all_fix_names(fixer_pkg):
129 print fixname
130 if not args:
131 return 0
132 if not args:
Benjamin Peterson840077c2009-07-20 15:33:09 +0000133 print >> sys.stderr, "At least one file or directory argument required."
134 print >> sys.stderr, "Use --help to show usage."
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000135 return 2
136 if "-" in args:
137 refactor_stdin = True
138 if options.write:
Benjamin Peterson840077c2009-07-20 15:33:09 +0000139 print >> sys.stderr, "Can't write to stdin."
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000140 return 2
Benjamin Peterson42d26d92009-11-25 18:16:46 +0000141 if options.print_function:
142 flags["print_function"] = True
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000143
144 # Set up logging handler
145 level = logging.DEBUG if options.verbose else logging.INFO
146 logging.basicConfig(format='%(name)s: %(message)s', level=level)
147
148 # Initialize the refactoring tool
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000149 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
150 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
151 explicit = set()
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000152 if options.fix:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000153 all_present = False
154 for fix in options.fix:
155 if fix == "all":
156 all_present = True
157 else:
158 explicit.add(fixer_pkg + ".fix_" + fix)
159 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000160 else:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000161 requested = avail_fixes.union(explicit)
162 fixer_names = requested.difference(unwanted_fixes)
Benjamin Peterson42d26d92009-11-25 18:16:46 +0000163 rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit),
Benjamin Peterson840077c2009-07-20 15:33:09 +0000164 options.nobackups, not options.no_diffs)
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000165
166 # Refactor all files and directories passed as arguments
167 if not rt.errors:
168 if refactor_stdin:
169 rt.refactor_stdin()
170 else:
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +0000171 try:
172 rt.refactor(args, options.write, options.doctests_only,
173 options.processes)
174 except refactor.MultiprocessingUnsupported:
175 assert options.processes > 1
176 print >> sys.stderr, "Sorry, -j isn't " \
177 "supported on this platform."
178 return 1
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000179 rt.summarize()
180
181 # Return error status (0 if rt.errors is zero)
182 return int(bool(rt.errors))