source: orange/Orange/orng/orange2to25.py @ 10341:f094470e9e68

Revision 10341:f094470e9e68, 6.8 KB checked in by Ales Erjavec <ales.erjavec@…>, 2 years ago (diff)

Fixed fixer_pkg for oarnge2to25 tool.

Line 
1#/bin/env python
2import sys, os
3
4from lib2to3 import refactor, main
5from lib2to3.main import StdoutRefactoringTool
6
7#fixes = refactor.get_fixers_from_package("lib2to3.fixes")   
8
9import optparse
10import logging
11import shutil
12import difflib
13
14
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   
23def warn(msg):
24    print >> sys.stderr, "WARNING: %s" % (msg,)
25
26class MyStdRefactoringTool(StdoutRefactoringTool):
27    def write_file(self, new_text, filename, old_text, encoding):
28        if not self.nobackups:
29            # Make backup
30           
31            filename = getattr(self, "outputfilename", filename)
32           
33            if hasattr(self, "outputfilename"):
34                self.nobackups = True
35            backup = filename + ".bak"
36            if os.path.lexists(backup):
37                try:
38                    os.remove(backup)
39                except os.error, err:
40                    self.log_message("Can't remove backup %s", backup)
41            if os.path.exists(filename):
42                try:
43                    os.rename(filename, backup)
44                except os.error, err:
45                    self.log_message("Can't rename %s to %s", filename, backup)
46        # Actually write the new file
47        write = super(StdoutRefactoringTool, self).write_file
48        write(new_text, filename, old_text, encoding)
49        if not self.nobackups:
50            try:
51                shutil.copymode(backup, filename)
52            except OSError, ex:
53                pass
54           
55def main(fixer_pkg, args=None):
56    """Main program.
57
58    Args:
59        fixer_pkg: the name of a package where the fixers are located.
60        args: optional; a list of command line arguments. If omitted,
61              sys.argv[1:] is used.
62
63    Returns a suggested exit status (0, 1, 2).
64    """
65    # Set up option parser
66    parser = optparse.OptionParser(usage="orange2to25 [options] file|dir ...")
67    parser.add_option("-d", "--doctests_only", action="store_true",
68                      help="Fix up doctests only")
69    parser.add_option("-f", "--fix", action="append", default=[],
70                      help="Each FIX specifies a transformation; default: all")
71    parser.add_option("-j", "--processes", action="store", default=1,
72                      type="int", help="Run orange2to25 concurrently")
73    parser.add_option("-x", "--nofix", action="append", default=[],
74                      help="Prevent a fixer from being run.")
75    parser.add_option("-l", "--list-fixes", action="store_true",
76                      help="List available transformations")
77#    parser.add_option("-p", "--print-function", action="store_true",
78#                      help="Modify the grammar so that print() is a function")
79    parser.add_option("-v", "--verbose", action="store_true",
80                      help="More verbose logging")
81    parser.add_option("--no-diffs", action="store_true",
82                      help="Don't show diffs of the refactoring")
83    parser.add_option("-w", "--write", action="store_true",
84                      help="Write back modified files")
85    parser.add_option("-n", "--nobackups", action="store_true", default=False,
86                      help="Don't write backups for modified files.")
87    parser.add_option("-a", "--aggressive", action="store_true", default=False,
88                      help="Aggressive name replace (without a module qualifier, e.g. replace ExampleTable with even if not preceded by orange.* )")
89    parser.add_option("-o", "--outfile", default = "",
90                      help="Output filename (if -w present and a single file on the command line)")
91
92    # Parse command line arguments
93    refactor_stdin = False
94    flags = {}
95    options, args = parser.parse_args(args)
96    if not options.write and options.no_diffs:
97        warn("not writing files and not printing diffs; that's not very useful")
98    if not options.write and options.nobackups:
99        parser.error("Can't use -n without -w")
100    if options.list_fixes:
101        print "Available transformations for the -f/--fix option:"
102        for fixname in refactor.get_all_fix_names(fixer_pkg):
103            print fixname
104        if not args:
105            return 0
106    if not args:
107        print >> sys.stderr, "At least one file or directory argument required."
108        print >> sys.stderr, "Use --help to show usage."
109        return 2
110    if "-" in args:
111        refactor_stdin = True
112        if options.write:
113            print >> sys.stderr, "Can't write to stdin."
114            return 2
115       
116#    if options.print_function:
117#        flags["print_function"] = True
118
119    # Set up logging handler
120    level = logging.DEBUG if options.verbose else logging.INFO
121    logging.basicConfig(format='%(name)s: %(message)s', level=level)
122
123    # Initialize the refactoring tool
124    avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
125    # Remove aggressive fixes if not requested
126    if not options.aggressive:
127        avail_fixes = set([fix for fix in avail_fixes if not fix.endswith("_aggressive")])
128       
129    unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
130    explicit = set()
131    if options.fix:
132        all_present = False
133        for fix in options.fix:
134            if fix == "all":
135                all_present = True
136            else:
137                explicit.add(fixer_pkg + ".fix_" + fix)
138        requested = avail_fixes.union(explicit) if all_present else explicit
139    else:
140        requested = avail_fixes.union(explicit)
141    fixer_names = requested.difference(unwanted_fixes)
142    rt = MyStdRefactoringTool(sorted(fixer_names), flags, sorted(explicit),
143                               options.nobackups, not options.no_diffs)
144    if options.outfile:
145        if len(args) > 2:
146            print >> sys.stderr, "-o, --outfile used but multiple script arguments"
147        elif not os.path.isfile(args[-1]):
148            print >> sys.stderr, "-o, --outfile used but argumnet is a directory"
149        else:
150            rt.outputfilename = options.outfile
151       
152    # Refactor all files and directories passed as arguments
153    if not rt.errors:
154        if refactor_stdin:
155            rt.refactor_stdin()
156        else:
157            try:
158                rt.refactor(args[1:], options.write, options.doctests_only,
159                            options.processes)
160            except refactor.MultiprocessingUnsupported:
161                assert options.processes > 1
162                print >> sys.stderr, "Sorry, -j isn't " \
163                    "supported on this platform."
164                return 1
165        rt.summarize()
166
167    # Return error status (0 if rt.errors is zero)
168    return int(bool(rt.errors))
169
170sys.exit(main("Orange.fixes", sys.argv))
171
172
173
174
Note: See TracBrowser for help on using the repository browser.