blob: d37fe9e0f3e56c22a8edcbfe95bfffeca0e80693 [file] [log] [blame]
Benjamin Peterson8951b612008-09-03 02:27:16 +00001"""
2Main program for 2to3.
3"""
4
5import sys
6import os
7import logging
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +00008import shutil
Benjamin Peterson8951b612008-09-03 02:27:16 +00009import optparse
10
11from . import refactor
12
13
Benjamin Petersond61de7f2008-09-27 22:17:35 +000014class StdoutRefactoringTool(refactor.RefactoringTool):
15 """
16 Prints output to stdout.
17 """
18
Benjamin Peterson206e3072008-10-19 14:07:49 +000019 def __init__(self, fixers, options, explicit, nobackups):
20 self.nobackups = nobackups
21 super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
22
Benjamin Petersond61de7f2008-09-27 22:17:35 +000023 def log_error(self, msg, *args, **kwargs):
24 self.errors.append((msg, args, kwargs))
25 self.logger.error(msg, *args, **kwargs)
26
Benjamin Peterson206e3072008-10-19 14:07:49 +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 as err:
35 self.log_message("Can't remove backup %s", backup)
36 try:
37 os.rename(filename, backup)
38 except os.error as 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 Peterson92035012008-12-27 16:00:54 +000043 if not self.nobackups:
Benjamin Peterson8bcddca2009-01-03 16:53:14 +000044 shutil.copymode(backup, filename)
Benjamin Peterson206e3072008-10-19 14:07:49 +000045
Benjamin Petersond61de7f2008-09-27 22:17:35 +000046 def print_output(self, lines):
47 for line in lines:
48 print(line)
49
50
Benjamin Peterson8951b612008-09-03 02:27:16 +000051def main(fixer_pkg, args=None):
52 """Main program.
53
54 Args:
55 fixer_pkg: the name of a package where the fixers are located.
56 args: optional; a list of command line arguments. If omitted,
57 sys.argv[1:] is used.
58
59 Returns a suggested exit status (0, 1, 2).
60 """
61 # Set up option parser
Benjamin Peterson0b24b3d2008-12-16 03:57:54 +000062 parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
Benjamin Peterson8951b612008-09-03 02:27:16 +000063 parser.add_option("-d", "--doctests_only", action="store_true",
64 help="Fix up doctests only")
65 parser.add_option("-f", "--fix", action="append", default=[],
Benjamin Peterson206e3072008-10-19 14:07:49 +000066 help="Each FIX specifies a transformation; default: all")
67 parser.add_option("-x", "--nofix", action="append", default=[],
68 help="Prevent a fixer from being run.")
Benjamin Peterson8951b612008-09-03 02:27:16 +000069 parser.add_option("-l", "--list-fixes", action="store_true",
70 help="List available transformations (fixes/fix_*.py)")
71 parser.add_option("-p", "--print-function", action="store_true",
72 help="Modify the grammar so that print() is a function")
73 parser.add_option("-v", "--verbose", action="store_true",
74 help="More verbose logging")
75 parser.add_option("-w", "--write", action="store_true",
76 help="Write back modified files")
Benjamin Peterson206e3072008-10-19 14:07:49 +000077 parser.add_option("-n", "--nobackups", action="store_true", default=False,
78 help="Don't write backups for modified files.")
Benjamin Peterson8951b612008-09-03 02:27:16 +000079
80 # Parse command line arguments
81 refactor_stdin = False
82 options, args = parser.parse_args(args)
Benjamin Peterson206e3072008-10-19 14:07:49 +000083 if not options.write and options.nobackups:
84 parser.error("Can't use -n without -w")
Benjamin Peterson8951b612008-09-03 02:27:16 +000085 if options.list_fixes:
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +000086 print("Available transformations for the -f/--fix option:")
Benjamin Peterson8951b612008-09-03 02:27:16 +000087 for fixname in refactor.get_all_fix_names(fixer_pkg):
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +000088 print(fixname)
Benjamin Peterson8951b612008-09-03 02:27:16 +000089 if not args:
90 return 0
91 if not args:
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +000092 print("At least one file or directory argument required.", file=sys.stderr)
93 print("Use --help to show usage.", file=sys.stderr)
Benjamin Peterson8951b612008-09-03 02:27:16 +000094 return 2
95 if "-" in args:
96 refactor_stdin = True
97 if options.write:
Benjamin Petersonc0a40ab2008-09-11 21:05:25 +000098 print("Can't write to stdin.", file=sys.stderr)
Benjamin Peterson8951b612008-09-03 02:27:16 +000099 return 2
100
101 # Set up logging handler
102 level = logging.DEBUG if options.verbose else logging.INFO
103 logging.basicConfig(format='%(name)s: %(message)s', level=level)
104
105 # Initialize the refactoring tool
106 rt_opts = {"print_function" : options.print_function}
Benjamin Peterson206e3072008-10-19 14:07:49 +0000107 avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
108 unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
109 explicit = set()
Benjamin Peterson8951b612008-09-03 02:27:16 +0000110 if options.fix:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000111 all_present = False
112 for fix in options.fix:
113 if fix == "all":
114 all_present = True
115 else:
116 explicit.add(fixer_pkg + ".fix_" + fix)
117 requested = avail_fixes.union(explicit) if all_present else explicit
Benjamin Peterson8951b612008-09-03 02:27:16 +0000118 else:
Benjamin Peterson206e3072008-10-19 14:07:49 +0000119 requested = avail_fixes.union(explicit)
120 fixer_names = requested.difference(unwanted_fixes)
121 rt = StdoutRefactoringTool(sorted(fixer_names), rt_opts, sorted(explicit),
122 options.nobackups)
Benjamin Peterson8951b612008-09-03 02:27:16 +0000123
124 # Refactor all files and directories passed as arguments
125 if not rt.errors:
126 if refactor_stdin:
127 rt.refactor_stdin()
128 else:
129 rt.refactor(args, options.write, options.doctests_only)
130 rt.summarize()
131
132 # Return error status (0 if rt.errors is zero)
133 return int(bool(rt.errors))