blob: 6c57e67951ee5ee35eb0a0a508f04fe47a8f38f0 [file] [log] [blame]
Benjamin Peterson8951b612008-09-03 02:27:16 +00001"""
2Main program for 2to3.
3"""
4
5import sys
6import os
Benjamin Peterson3059b002009-07-20 16:42:03 +00007import difflib
Benjamin Peterson8951b612008-09-03 02:27:16 +00008import logging
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00009import shutil
Benjamin Peterson8951b612008-09-03 02:27:16 +000010import optparse
11
12from . import refactor
13
Benjamin Peterson3059b002009-07-20 16:42:03 +000014
15def diff_texts(a, b, filename):
16 """Return a unified diff of two strings."""
17 a = a.splitlines()
18 b = b.splitlines()
19 return difflib.unified_diff(a, b, filename, filename,
20 "(original)", "(refactored)",
21 lineterm="")
22
23
Benjamin Peterson608d8bc2009-05-05 23:23:31 +000024class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
Benjamin Petersond61de7f2008-09-27 22:17:35 +000025 """
26 Prints output to stdout.
27 """
28
Benjamin Peterson3059b002009-07-20 16:42:03 +000029 def __init__(self, fixers, options, explicit, nobackups, show_diffs):
Benjamin Peterson206e3072008-10-19 14:07:49 +000030 self.nobackups = nobackups
Benjamin Peterson3059b002009-07-20 16:42:03 +000031 self.show_diffs = show_diffs
Benjamin Peterson206e3072008-10-19 14:07:49 +000032 super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
33
Benjamin Petersond61de7f2008-09-27 22:17:35 +000034 def log_error(self, msg, *args, **kwargs):
35 self.errors.append((msg, args, kwargs))
36 self.logger.error(msg, *args, **kwargs)
37
Benjamin Petersond481e3d2009-05-09 19:42:23 +000038 def write_file(self, new_text, filename, old_text, encoding):
Benjamin Peterson206e3072008-10-19 14:07:49 +000039 if not self.nobackups:
40 # Make backup
41 backup = filename + ".bak"
42 if os.path.lexists(backup):
43 try:
44 os.remove(backup)
45 except os.error as err:
46 self.log_message("Can't remove backup %s", backup)
47 try:
48 os.rename(filename, backup)
49 except os.error as err:
50 self.log_message("Can't rename %s to %s", filename, backup)
51 # Actually write the new file
Benjamin Petersond481e3d2009-05-09 19:42:23 +000052 write = super(StdoutRefactoringTool, self).write_file
53 write(new_text, filename, old_text, encoding)
Benjamin Peterson92035012008-12-27 16:00:54 +000054 if not self.nobackups:
Benjamin Peterson8bcddca2009-01-03 16:53:14 +000055 shutil.copymode(backup, filename)
Benjamin Peterson206e3072008-10-19 14:07:49 +000056
Benjamin Peterson3059b002009-07-20 16:42:03 +000057 def print_output(self, old, new, filename, equal):
58 if equal:
59 self.log_message("No changes to %s", filename)
60 else:
61 self.log_message("Refactored %s", filename)
62 if self.show_diffs:
Benjamin Petersonffa94b02009-12-29 00:06:20 +000063 diff_lines = diff_texts(old, new, filename)
64 try:
65 for line in diff_lines:
66 print(line)
67 except UnicodeEncodeError:
68 warn("couldn't encode %s's diff for your terminal" %
69 (filename,))
70 return
Benjamin Peterson3059b002009-07-20 16:42:03 +000071
72def warn(msg):
Benjamin Peterson8fb00be2009-09-25 20:34:04 +000073 print("WARNING: %s" % (msg,), file=sys.stderr)
Benjamin Petersond61de7f2008-09-27 22:17:35 +000074
75
Benjamin Peterson8951b612008-09-03 02:27:16 +000076def main(fixer_pkg, args=None):
77 """Main program.
78
79 Args:
80 fixer_pkg: the name of a package where the fixers are located.
81 args: optional; a list of command line arguments. If omitted,
82 sys.argv[1:] is used.
83
84 Returns a suggested exit status (0, 1, 2).
85 """
86 # Set up option parser
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +000087 parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
Benjamin Peterson8951b612008-09-03 02:27:16 +000088 parser.add_option("-d", "--doctests_only", action="store_true",
89 help="Fix up doctests only")
90 parser.add_option("-f", "--fix", action="append", default=[],
Benjamin Peterson206e3072008-10-19 14:07:49 +000091 help="Each FIX specifies a transformation; default: all")
Benjamin Peterson608d8bc2009-05-05 23:23:31 +000092 parser.add_option("-j", "--processes", action="store", default=1,
93 type="int", help="Run 2to3 concurrently")
Benjamin Peterson206e3072008-10-19 14:07:49 +000094 parser.add_option("-x", "--nofix", action="append", default=[],
95 help="Prevent a fixer from being run.")
Benjamin Peterson8951b612008-09-03 02:27:16 +000096 parser.add_option("-l", "--list-fixes", action="store_true",
97 help="List available transformations (fixes/fix_*.py)")
98 parser.add_option("-p", "--print-function", action="store_true",
Benjamin Peterson20211002009-11-25 18:34:42 +000099 help="Modify the grammar so that print() is a function")
Benjamin Peterson8951b612008-09-03 02:27:16 +0000100 parser.add_option("-v", "--verbose", action="store_true",
101 help="More verbose logging")
Benjamin Peterson3059b002009-07-20 16:42:03 +0000102 parser.add_option("--no-diffs", action="store_true",
103 help="Don't show diffs of the refactoring")
Benjamin Peterson8951b612008-09-03 02:27:16 +0000104 parser.add_option("-w", "--write", action="store_true",
105 help="Write back modified files")
Benjamin Peterson206e3072008-10-19 14:07:49 +0000106 parser.add_option("-n", "--nobackups", action="store_true", default=False,
107 help="Don't write backups for modified files.")
Benjamin Peterson8951b612008-09-03 02:27:16 +0000108
109 # Parse command line arguments
110 refactor_stdin = False
Benjamin Peterson20211002009-11-25 18:34:42 +0000111 flags = {}
Benjamin Peterson8951b612008-09-03 02:27:16 +0000112 options, args = parser.parse_args(args)
Benjamin Peterson3059b002009-07-20 16:42:03 +0000113 if not options.write and options.no_diffs:
114 warn("not writing files and not printing diffs; that's not very useful")
Benjamin Peterson206e3072008-10-19 14:07:49 +0000115 if not options.write and options.nobackups:
116 parser.error("Can't use -n without -w")
Benjamin Peterson8951b612008-09-03 02:27:16 +0000117 if options.list_fixes:
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +0000118 print("Available transformations for the -f/--fix option:")
Benjamin Peterson8951b612008-09-03 02:27:16 +0000119 for fixname in refactor.get_all_fix_names(fixer_pkg):
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +0000120 print(fixname)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000121 if not args:
122 return 0
123 if not args:
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +0000124 print("At least one file or directory argument required.", file=sys.stderr)
125 print("Use --help to show usage.", file=sys.stderr)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000126 return 2
127 if "-" in args:
128 refactor_stdin = True
129 if options.write:
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +0000130 print("Can't write to stdin.", file=sys.stderr)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000131 return 2
Benjamin Peterson20211002009-11-25 18:34:42 +0000132 if options.print_function:
133 flags["print_function"] = True
Benjamin Peterson8951b612008-09-03 02:27:16 +0000134
135 # Set up logging handler
136 level = logging.DEBUG if options.verbose else logging.INFO
137 logging.basicConfig(format='%(name)s: %(message)s', level=level)
138
139 # Initialize the refactoring tool
Benjamin Peterson206e3072008-10-19 14:07:49 +0000140 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
141 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
142 explicit = set()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000143 if options.fix:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000144 all_present = False
145 for fix in options.fix:
146 if fix == "all":
147 all_present = True
148 else:
149 explicit.add(fixer_pkg + ".fix_" + fix)
150 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Peterson8951b612008-09-03 02:27:16 +0000151 else:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000152 requested = avail_fixes.union(explicit)
153 fixer_names = requested.difference(unwanted_fixes)
Benjamin Peterson20211002009-11-25 18:34:42 +0000154 rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit),
Benjamin Peterson3059b002009-07-20 16:42:03 +0000155 options.nobackups, not options.no_diffs)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000156
157 # Refactor all files and directories passed as arguments
158 if not rt.errors:
159 if refactor_stdin:
160 rt.refactor_stdin()
161 else:
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000162 try:
163 rt.refactor(args, options.write, options.doctests_only,
164 options.processes)
165 except refactor.MultiprocessingUnsupported:
166 assert options.processes > 1
Benjamin Peterson8fb00be2009-09-25 20:34:04 +0000167 print("Sorry, -j isn't supported on this platform.",
168 file=sys.stderr)
Benjamin Peterson608d8bc2009-05-05 23:23:31 +0000169 return 1
Benjamin Peterson8951b612008-09-03 02:27:16 +0000170 rt.summarize()
171
172 # Return error status (0 if rt.errors is zero)
173 return int(bool(rt.errors))