blob: 84f0f840a4cf775fb63b0dc11e631347c5ead044 [file] [log] [blame]
Benjamin Petersoneb55fd82008-09-03 00:21:32 +00001"""
2Main program for 2to3.
3"""
4
5import sys
6import os
7import logging
8import optparse
9
10from . import refactor
11
12
Benjamin Peterson08be2912008-09-27 21:09:10 +000013class StdoutRefactoringTool(refactor.RefactoringTool):
14 """
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 Peterson6ae94ee2008-10-15 23:10:28 +000026 def write_file(self, new_text, filename, old_text):
27 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
40 super(StdoutRefactoringTool, self).write_file(new_text,
41 filename, old_text)
42
Benjamin Peterson08be2912008-09-27 21:09:10 +000043 def print_output(self, lines):
44 for line in lines:
45 print line
46
47
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000048def main(fixer_pkg, args=None):
49 """Main program.
50
51 Args:
52 fixer_pkg: the name of a package where the fixers are located.
53 args: optional; a list of command line arguments. If omitted,
54 sys.argv[1:] is used.
55
56 Returns a suggested exit status (0, 1, 2).
57 """
58 # Set up option parser
59 parser = optparse.OptionParser(usage="refactor.py [options] file|dir ...")
60 parser.add_option("-d", "--doctests_only", action="store_true",
61 help="Fix up doctests only")
62 parser.add_option("-f", "--fix", action="append", default=[],
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000063 help="Each FIX specifies a transformation; default: all")
64 parser.add_option("-x", "--nofix", action="append", default=[],
65 help="Prevent a fixer from being run.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000066 parser.add_option("-l", "--list-fixes", action="store_true",
67 help="List available transformations (fixes/fix_*.py)")
68 parser.add_option("-p", "--print-function", action="store_true",
69 help="Modify the grammar so that print() is a function")
70 parser.add_option("-v", "--verbose", action="store_true",
71 help="More verbose logging")
72 parser.add_option("-w", "--write", action="store_true",
73 help="Write back modified files")
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000074 parser.add_option("-n", "--nobackups", action="store_true", default=False,
75 help="Don't write backups for modified files.")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000076
77 # Parse command line arguments
78 refactor_stdin = False
79 options, args = parser.parse_args(args)
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +000080 if not options.write and options.nobackups:
81 parser.error("Can't use -n without -w")
Benjamin Petersoneb55fd82008-09-03 00:21:32 +000082 if options.list_fixes:
83 print "Available transformations for the -f/--fix option:"
84 for fixname in refactor.get_all_fix_names(fixer_pkg):
85 print fixname
86 if not args:
87 return 0
88 if not args:
89 print >>sys.stderr, "At least one file or directory argument required."
90 print >>sys.stderr, "Use --help to show usage."
91 return 2
92 if "-" in args:
93 refactor_stdin = True
94 if options.write:
95 print >>sys.stderr, "Can't write to stdin."
96 return 2
97
98 # Set up logging handler
99 level = logging.DEBUG if options.verbose else logging.INFO
100 logging.basicConfig(format='%(name)s: %(message)s', level=level)
101
102 # Initialize the refactoring tool
103 rt_opts = {"print_function" : options.print_function}
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000104 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
105 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
106 explicit = set()
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000107 if options.fix:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000108 all_present = False
109 for fix in options.fix:
110 if fix == "all":
111 all_present = True
112 else:
113 explicit.add(fixer_pkg + ".fix_" + fix)
114 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000115 else:
Benjamin Peterson6ae94ee2008-10-15 23:10:28 +0000116 requested = avail_fixes.union(explicit)
117 fixer_names = requested.difference(unwanted_fixes)
118 rt = StdoutRefactoringTool(sorted(fixer_names), rt_opts, sorted(explicit),
119 options.nobackups)
Benjamin Petersoneb55fd82008-09-03 00:21:32 +0000120
121 # Refactor all files and directories passed as arguments
122 if not rt.errors:
123 if refactor_stdin:
124 rt.refactor_stdin()
125 else:
126 rt.refactor(args, options.write, options.doctests_only)
127 rt.summarize()
128
129 # Return error status (0 if rt.errors is zero)
130 return int(bool(rt.errors))