blob: cf4adf7c0293a048b56773317051e92b76e70b10 [file] [log] [blame]
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00001"""
2Main program for 2to3.
3"""
4
5import sys
6import os
7import logging
Benjamin Peterson43caaa02008-12-16 03:35:28 +00008import shutil
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00009import optparse
10
11from . import refactor
12
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +000013class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
Benjamin Peterson08be2912008-09-27 21:09:10 +000014 """
15 Prints output to stdout.
16 """
17
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000018 def __init__(self, fixers, options, explicit, nobackups):
19 self.nobackups = nobackups
20 super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
21
Benjamin Peterson08be2912008-09-27 21:09:10 +000022 def log_error(self, msg, *args, **kwargs):
23 self.errors.append((msg, args, kwargs))
24 self.logger.error(msg, *args, **kwargs)
25
Benjamin Peterson84ad84e2009-05-09 01:01:14 +000026 def write_file(self, new_text, filename, old_text, encoding):
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000027 if not self.nobackups:
28 # Make backup
29 backup = filename + ".bak"
30 if os.path.lexists(backup):
31 try:
32 os.remove(backup)
33 except os.error, err:
34 self.log_message("Can't remove backup %s", backup)
35 try:
36 os.rename(filename, backup)
37 except os.error, err:
38 self.log_message("Can't rename %s to %s", filename, backup)
39 # Actually write the new file
Benjamin Peterson84ad84e2009-05-09 01:01:14 +000040 write = super(StdoutRefactoringTool, self).write_file
41 write(new_text, filename, old_text, encoding)
Benjamin Peterson03943d92008-12-21 01:29:32 +000042 if not self.nobackups:
Benjamin Peterson37fc8232009-01-03 16:34:02 +000043 shutil.copymode(backup, filename)
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000044
Benjamin Peterson08be2912008-09-27 21:09:10 +000045 def print_output(self, lines):
46 for line in lines:
47 print line
48
49
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000050def main(fixer_pkg, args=None):
51 """Main program.
52
53 Args:
54 fixer_pkg: the name of a package where the fixers are located.
55 args: optional; a list of command line arguments. If omitted,
56 sys.argv[1:] is used.
57
58 Returns a suggested exit status (0, 1, 2).
59 """
60 # Set up option parser
Benjamin Peterson43caaa02008-12-16 03:35:28 +000061 parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000062 parser.add_option("-d", "--doctests_only", action="store_true",
63 help="Fix up doctests only")
64 parser.add_option("-f", "--fix", action="append", default=[],
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000065 help="Each FIX specifies a transformation; default: all")
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +000066 parser.add_option("-j", "--processes", action="store", default=1,
67 type="int", help="Run 2to3 concurrently")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000068 parser.add_option("-x", "--nofix", action="append", default=[],
69 help="Prevent a fixer from being run.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000070 parser.add_option("-l", "--list-fixes", action="store_true",
71 help="List available transformations (fixes/fix_*.py)")
72 parser.add_option("-p", "--print-function", action="store_true",
73 help="Modify the grammar so that print() is a function")
74 parser.add_option("-v", "--verbose", action="store_true",
75 help="More verbose logging")
76 parser.add_option("-w", "--write", action="store_true",
77 help="Write back modified files")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000078 parser.add_option("-n", "--nobackups", action="store_true", default=False,
79 help="Don't write backups for modified files.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000080
81 # Parse command line arguments
82 refactor_stdin = False
83 options, args = parser.parse_args(args)
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000084 if not options.write and options.nobackups:
85 parser.error("Can't use -n without -w")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000086 if options.list_fixes:
87 print "Available transformations for the -f/--fix option:"
88 for fixname in refactor.get_all_fix_names(fixer_pkg):
89 print fixname
90 if not args:
91 return 0
92 if not args:
93 print >>sys.stderr, "At least one file or directory argument required."
94 print >>sys.stderr, "Use --help to show usage."
95 return 2
96 if "-" in args:
97 refactor_stdin = True
98 if options.write:
99 print >>sys.stderr, "Can't write to stdin."
100 return 2
101
102 # Set up logging handler
103 level = logging.DEBUG if options.verbose else logging.INFO
104 logging.basicConfig(format='%(name)s: %(message)s', level=level)
105
106 # Initialize the refactoring tool
107 rt_opts = {"print_function" : options.print_function}
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000108 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
109 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
110 explicit = set()
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000111 if options.fix:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000112 all_present = False
113 for fix in options.fix:
114 if fix == "all":
115 all_present = True
116 else:
117 explicit.add(fixer_pkg + ".fix_" + fix)
118 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000119 else:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000120 requested = avail_fixes.union(explicit)
121 fixer_names = requested.difference(unwanted_fixes)
122 rt = StdoutRefactoringTool(sorted(fixer_names), rt_opts, sorted(explicit),
123 options.nobackups)
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000124
125 # Refactor all files and directories passed as arguments
126 if not rt.errors:
127 if refactor_stdin:
128 rt.refactor_stdin()
129 else:
Benjamin Petersoneaeb4c62009-05-05 23:13:58 +0000130 try:
131 rt.refactor(args, options.write, options.doctests_only,
132 options.processes)
133 except refactor.MultiprocessingUnsupported:
134 assert options.processes > 1
135 print >> sys.stderr, "Sorry, -j isn't " \
136 "supported on this platform."
137 return 1
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000138 rt.summarize()
139
140 # Return error status (0 if rt.errors is zero)
141 return int(bool(rt.errors))