PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/modified-2.7/lib2to3/main.py

https://bitbucket.org/dac_io/pypy
Python | 182 lines | 173 code | 5 blank | 4 comment | 5 complexity | 6910943f9b2d1b1a4eb5e04f4c70a52a MD5 | raw file
  1. """
  2. Main program for 2to3.
  3. """
  4. from __future__ import with_statement
  5. import sys
  6. import os
  7. import difflib
  8. import logging
  9. import shutil
  10. import optparse
  11. from . import refactor
  12. def diff_texts(a, b, filename):
  13. """Return a unified diff of two strings."""
  14. a = a.splitlines()
  15. b = b.splitlines()
  16. return difflib.unified_diff(a, b, filename, filename,
  17. "(original)", "(refactored)",
  18. lineterm="")
  19. class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
  20. """
  21. Prints output to stdout.
  22. """
  23. def __init__(self, fixers, options, explicit, nobackups, show_diffs):
  24. self.nobackups = nobackups
  25. self.show_diffs = show_diffs
  26. super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
  27. def log_error(self, msg, *args, **kwargs):
  28. self.errors.append((msg, args, kwargs))
  29. self.logger.error(msg, *args, **kwargs)
  30. def write_file(self, new_text, filename, old_text, encoding):
  31. if not self.nobackups:
  32. # Make backup
  33. backup = filename + ".bak"
  34. if os.path.lexists(backup):
  35. try:
  36. os.remove(backup)
  37. except os.error, err:
  38. self.log_message("Can't remove backup %s", backup)
  39. try:
  40. os.rename(filename, backup)
  41. except os.error, err:
  42. self.log_message("Can't rename %s to %s", filename, backup)
  43. # Actually write the new file
  44. write = super(StdoutRefactoringTool, self).write_file
  45. write(new_text, filename, old_text, encoding)
  46. if not self.nobackups:
  47. shutil.copymode(backup, filename)
  48. def print_output(self, old, new, filename, equal):
  49. if equal:
  50. self.log_message("No changes to %s", filename)
  51. else:
  52. self.log_message("Refactored %s", filename)
  53. if self.show_diffs:
  54. diff_lines = diff_texts(old, new, filename)
  55. try:
  56. if self.output_lock is not None:
  57. with self.output_lock:
  58. for line in diff_lines:
  59. print line
  60. sys.stdout.flush()
  61. else:
  62. for line in diff_lines:
  63. print line
  64. except UnicodeEncodeError:
  65. warn("couldn't encode %s's diff for your terminal" %
  66. (filename,))
  67. return
  68. def warn(msg):
  69. print >> sys.stderr, "WARNING: %s" % (msg,)
  70. def main(fixer_pkg, args=None):
  71. """Main program.
  72. Args:
  73. fixer_pkg: the name of a package where the fixers are located.
  74. args: optional; a list of command line arguments. If omitted,
  75. sys.argv[1:] is used.
  76. Returns a suggested exit status (0, 1, 2).
  77. """
  78. # Set up option parser
  79. parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
  80. parser.add_option("-d", "--doctests_only", action="store_true",
  81. help="Fix up doctests only")
  82. parser.add_option("-f", "--fix", action="append", default=[],
  83. help="Each FIX specifies a transformation; default: all")
  84. parser.add_option("-j", "--processes", action="store", default=1,
  85. type="int", help="Run 2to3 concurrently")
  86. parser.add_option("-x", "--nofix", action="append", default=[],
  87. help="Prevent a transformation from being run")
  88. parser.add_option("-l", "--list-fixes", action="store_true",
  89. help="List available transformations")
  90. parser.add_option("-p", "--print-function", action="store_true",
  91. help="Modify the grammar so that print() is a function")
  92. parser.add_option("-v", "--verbose", action="store_true",
  93. help="More verbose logging")
  94. parser.add_option("--no-diffs", action="store_true",
  95. help="Don't show diffs of the refactoring")
  96. parser.add_option("-w", "--write", action="store_true",
  97. help="Write back modified files")
  98. parser.add_option("-n", "--nobackups", action="store_true", default=False,
  99. help="Don't write backups for modified files")
  100. # Parse command line arguments
  101. refactor_stdin = False
  102. flags = {}
  103. options, args = parser.parse_args(args)
  104. if not options.write and options.no_diffs:
  105. warn("not writing files and not printing diffs; that's not very useful")
  106. if not options.write and options.nobackups:
  107. parser.error("Can't use -n without -w")
  108. if options.list_fixes:
  109. print "Available transformations for the -f/--fix option:"
  110. for fixname in refactor.get_all_fix_names(fixer_pkg):
  111. print fixname
  112. if not args:
  113. return 0
  114. if not args:
  115. print >> sys.stderr, "At least one file or directory argument required."
  116. print >> sys.stderr, "Use --help to show usage."
  117. return 2
  118. if "-" in args:
  119. refactor_stdin = True
  120. if options.write:
  121. print >> sys.stderr, "Can't write to stdin."
  122. return 2
  123. if options.print_function:
  124. flags["print_function"] = True
  125. # Set up logging handler
  126. level = logging.DEBUG if options.verbose else logging.INFO
  127. logging.basicConfig(format='%(name)s: %(message)s', level=level)
  128. # Initialize the refactoring tool
  129. avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
  130. unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
  131. explicit = set()
  132. if options.fix:
  133. all_present = False
  134. for fix in options.fix:
  135. if fix == "all":
  136. all_present = True
  137. else:
  138. explicit.add(fixer_pkg + ".fix_" + fix)
  139. requested = avail_fixes.union(explicit) if all_present else explicit
  140. else:
  141. requested = avail_fixes.union(explicit)
  142. fixer_names = requested.difference(unwanted_fixes)
  143. rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit),
  144. options.nobackups, not options.no_diffs)
  145. # Refactor all files and directories passed as arguments
  146. if not rt.errors:
  147. if refactor_stdin:
  148. rt.refactor_stdin()
  149. else:
  150. try:
  151. rt.refactor(args, options.write, options.doctests_only,
  152. options.processes)
  153. except refactor.MultiprocessingUnsupported:
  154. assert options.processes > 1
  155. print >> sys.stderr, "Sorry, -j isn't " \
  156. "supported on this platform."
  157. return 1
  158. rt.summarize()
  159. # Return error status (0 if rt.errors is zero)
  160. return int(bool(rt.errors))