blob: 92388079b2cae819f1c9a5743cf5c90b23b71035 [file] [log] [blame]
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00001"""
2Main program for 2to3.
3"""
4
5import sys
6import os
Benjamin Peterson840077c2009-07-20 15:33:09 +00007import difflib
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00008import logging
Benjamin Peterson43caaa02008-12-16 03:35:28 +00009import shutil
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000010import optparse
11
12from . import refactor
13
Benjamin Peterson840077c2009-07-20 15:33:09 +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 Petersoneaeb4c62009-05-05 23:13:58 +000024class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
Benjamin Peterson08be2912008-09-27 21:09:10 +000025 """
26 Prints output to stdout.
27 """
28
Benjamin Peterson840077c2009-07-20 15:33:09 +000029 def __init__(self, fixers, options, explicit, nobackups, show_diffs):
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000030 self.nobackups = nobackups
Benjamin Peterson840077c2009-07-20 15:33:09 +000031 self.show_diffs = show_diffs
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000032 super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
33
Benjamin Peterson08be2912008-09-27 21:09:10 +000034 def log_error(self, msg, *args, **kwargs):
35 self.errors.append((msg, args, kwargs))
36 self.logger.error(msg, *args, **kwargs)
37
Benjamin Peterson84ad84e2009-05-09 01:01:14 +000038 def write_file(self, new_text, filename, old_text, encoding):
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +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, err:
46 self.log_message("Can't remove backup %s", backup)
47 try:
48 os.rename(filename, backup)
49 except os.error, err:
50 self.log_message("Can't rename %s to %s", filename, backup)
51 # Actually write the new file
Benjamin Peterson84ad84e2009-05-09 01:01:14 +000052 write = super(StdoutRefactoringTool, self).write_file
53 write(new_text, filename, old_text, encoding)
Benjamin Peterson03943d92008-12-21 01:29:32 +000054 if not self.nobackups:
Benjamin Peterson37fc8232009-01-03 16:34:02 +000055 shutil.copymode(backup, filename)
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000056
Benjamin Peterson840077c2009-07-20 15:33:09 +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:
63 for line in diff_texts(old, new, filename):
64 print line
65
66
67def warn(msg):
68 print >> sys.stderr, "WARNING: %s" % (msg,)
Benjamin Peterson08be2912008-09-27 21:09:10 +000069
70
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000071def main(fixer_pkg, args=None):
72 """Main program.
73
74 Args:
75 fixer_pkg: the name of a package where the fixers are located.
76 args: optional; a list of command line arguments. If omitted,
77 sys.argv[1:] is used.
78
79 Returns a suggested exit status (0, 1, 2).
80 """
81 # Set up option parser
Benjamin Peterson43caaa02008-12-16 03:35:28 +000082 parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000083 parser.add_option("-d", "--doctests_only", action="store_true",
84 help="Fix up doctests only")
85 parser.add_option("-f", "--fix", action="append", default=[],
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000086 help="Each FIX specifies a transformation; default: all")
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +000087 parser.add_option("-j", "--processes", action="store", default=1,
88 type="int", help="Run 2to3 concurrently")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000089 parser.add_option("-x", "--nofix", action="append", default=[],
90 help="Prevent a fixer from being run.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000091 parser.add_option("-l", "--list-fixes", action="store_true",
92 help="List available transformations (fixes/fix_*.py)")
93 parser.add_option("-p", "--print-function", action="store_true",
Benjamin Peterson840077c2009-07-20 15:33:09 +000094 help="DEPRECATED Modify the grammar so that print() is "
95 "a function")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000096 parser.add_option("-v", "--verbose", action="store_true",
97 help="More verbose logging")
Benjamin Peterson840077c2009-07-20 15:33:09 +000098 parser.add_option("--no-diffs", action="store_true",
99 help="Don't show diffs of the refactoring")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000100 parser.add_option("-w", "--write", action="store_true",
101 help="Write back modified files")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000102 parser.add_option("-n", "--nobackups", action="store_true", default=False,
103 help="Don't write backups for modified files.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000104
105 # Parse command line arguments
106 refactor_stdin = False
107 options, args = parser.parse_args(args)
Benjamin Peterson840077c2009-07-20 15:33:09 +0000108 if not options.write and options.no_diffs:
109 warn("not writing files and not printing diffs; that's not very useful")
110 if options.print_function:
111 warn("-p is deprecated; "
112 "detection of from __future__ import print_function is automatic")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000113 if not options.write and options.nobackups:
114 parser.error("Can't use -n without -w")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000115 if options.list_fixes:
116 print "Available transformations for the -f/--fix option:"
117 for fixname in refactor.get_all_fix_names(fixer_pkg):
118 print fixname
119 if not args:
120 return 0
121 if not args:
Benjamin Peterson840077c2009-07-20 15:33:09 +0000122 print >> sys.stderr, "At least one file or directory argument required."
123 print >> sys.stderr, "Use --help to show usage."
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000124 return 2
125 if "-" in args:
126 refactor_stdin = True
127 if options.write:
Benjamin Peterson840077c2009-07-20 15:33:09 +0000128 print >> sys.stderr, "Can't write to stdin."
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000129 return 2
130
131 # Set up logging handler
132 level = logging.DEBUG if options.verbose else logging.INFO
133 logging.basicConfig(format='%(name)s: %(message)s', level=level)
134
135 # Initialize the refactoring tool
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000136 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
137 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
138 explicit = set()
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000139 if options.fix:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000140 all_present = False
141 for fix in options.fix:
142 if fix == "all":
143 all_present = True
144 else:
145 explicit.add(fixer_pkg + ".fix_" + fix)
146 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000147 else:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000148 requested = avail_fixes.union(explicit)
149 fixer_names = requested.difference(unwanted_fixes)
Benjamin Peterson840077c2009-07-20 15:33:09 +0000150 rt = StdoutRefactoringTool(sorted(fixer_names), None, sorted(explicit),
151 options.nobackups, not options.no_diffs)
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000152
153 # Refactor all files and directories passed as arguments
154 if not rt.errors:
155 if refactor_stdin:
156 rt.refactor_stdin()
157 else:
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +0000158 try:
159 rt.refactor(args, options.write, options.doctests_only,
160 options.processes)
161 except refactor.MultiprocessingUnsupported:
162 assert options.processes > 1
163 print >> sys.stderr, "Sorry, -j isn't " \
164 "supported on this platform."
165 return 1
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000166 rt.summarize()
167
168 # Return error status (0 if rt.errors is zero)
169 return int(bool(rt.errors))