blob: a4d148d45588f3fe70158c5efeae7442be5eef54 [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
13
Benjamin Peterson08be2912008-09-27 21:09:10 +000014class StdoutRefactoringTool(refactor.RefactoringTool):
15 """
16 Prints output to stdout.
17 """
18
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000019 def __init__(self, fixers, options, explicit, nobackups):
20 self.nobackups = nobackups
21 super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
22
Benjamin Peterson08be2912008-09-27 21:09:10 +000023 def log_error(self, msg, *args, **kwargs):
24 self.errors.append((msg, args, kwargs))
25 self.logger.error(msg, *args, **kwargs)
26
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000027 def write_file(self, new_text, filename, old_text):
28 if not self.nobackups:
29 # Make backup
30 backup = filename + ".bak"
31 if os.path.lexists(backup):
32 try:
33 os.remove(backup)
34 except os.error, err:
35 self.log_message("Can't remove backup %s", backup)
36 try:
37 os.rename(filename, backup)
38 except os.error, err:
39 self.log_message("Can't rename %s to %s", filename, backup)
40 # Actually write the new file
41 super(StdoutRefactoringTool, self).write_file(new_text,
42 filename, old_text)
Benjamin Peterson43caaa02008-12-16 03:35:28 +000043 shutil.copymode(filename, backup)
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")
66 parser.add_option("-x", "--nofix", action="append", default=[],
67 help="Prevent a fixer from being run.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000068 parser.add_option("-l", "--list-fixes", action="store_true",
69 help="List available transformations (fixes/fix_*.py)")
70 parser.add_option("-p", "--print-function", action="store_true",
71 help="Modify the grammar so that print() is a function")
72 parser.add_option("-v", "--verbose", action="store_true",
73 help="More verbose logging")
74 parser.add_option("-w", "--write", action="store_true",
75 help="Write back modified files")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000076 parser.add_option("-n", "--nobackups", action="store_true", default=False,
77 help="Don't write backups for modified files.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000078
79 # Parse command line arguments
80 refactor_stdin = False
81 options, args = parser.parse_args(args)
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000082 if not options.write and options.nobackups:
83 parser.error("Can't use -n without -w")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000084 if options.list_fixes:
85 print "Available transformations for the -f/--fix option:"
86 for fixname in refactor.get_all_fix_names(fixer_pkg):
87 print fixname
88 if not args:
89 return 0
90 if not args:
91 print >>sys.stderr, "At least one file or directory argument required."
92 print >>sys.stderr, "Use --help to show usage."
93 return 2
94 if "-" in args:
95 refactor_stdin = True
96 if options.write:
97 print >>sys.stderr, "Can't write to stdin."
98 return 2
99
100 # Set up logging handler
101 level = logging.DEBUG if options.verbose else logging.INFO
102 logging.basicConfig(format='%(name)s: %(message)s', level=level)
103
104 # Initialize the refactoring tool
105 rt_opts = {"print_function" : options.print_function}
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000106 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
107 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
108 explicit = set()
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000109 if options.fix:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000110 all_present = False
111 for fix in options.fix:
112 if fix == "all":
113 all_present = True
114 else:
115 explicit.add(fixer_pkg + ".fix_" + fix)
116 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000117 else:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000118 requested = avail_fixes.union(explicit)
119 fixer_names = requested.difference(unwanted_fixes)
120 rt = StdoutRefactoringTool(sorted(fixer_names), rt_opts, sorted(explicit),
121 options.nobackups)
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000122
123 # Refactor all files and directories passed as arguments
124 if not rt.errors:
125 if refactor_stdin:
126 rt.refactor_stdin()
127 else:
128 rt.refactor(args, options.write, options.doctests_only)
129 rt.summarize()
130
131 # Return error status (0 if rt.errors is zero)
132 return int(bool(rt.errors))