/Lib/lib2to3/main.py

http://unladen-swallow.googlecode.com/ · Python · 133 lines · 95 code · 15 blank · 23 comment · 29 complexity · 85da2f9b910a7b8af322a872949da4e1 MD5 · raw file

  1. """
  2. Main program for 2to3.
  3. """
  4. import sys
  5. import os
  6. import logging
  7. import shutil
  8. import optparse
  9. from . import refactor
  10. class StdoutRefactoringTool(refactor.RefactoringTool):
  11. """
  12. Prints output to stdout.
  13. """
  14. def __init__(self, fixers, options, explicit, nobackups):
  15. self.nobackups = nobackups
  16. super(StdoutRefactoringTool, self).__init__(fixers, options, explicit)
  17. def log_error(self, msg, *args, **kwargs):
  18. self.errors.append((msg, args, kwargs))
  19. self.logger.error(msg, *args, **kwargs)
  20. def write_file(self, new_text, filename, old_text):
  21. if not self.nobackups:
  22. # Make backup
  23. backup = filename + ".bak"
  24. if os.path.lexists(backup):
  25. try:
  26. os.remove(backup)
  27. except os.error, err:
  28. self.log_message("Can't remove backup %s", backup)
  29. try:
  30. os.rename(filename, backup)
  31. except os.error, err:
  32. self.log_message("Can't rename %s to %s", filename, backup)
  33. # Actually write the new file
  34. super(StdoutRefactoringTool, self).write_file(new_text,
  35. filename, old_text)
  36. if not self.nobackups:
  37. shutil.copymode(backup, filename)
  38. def print_output(self, lines):
  39. for line in lines:
  40. print line
  41. def main(fixer_pkg, args=None):
  42. """Main program.
  43. Args:
  44. fixer_pkg: the name of a package where the fixers are located.
  45. args: optional; a list of command line arguments. If omitted,
  46. sys.argv[1:] is used.
  47. Returns a suggested exit status (0, 1, 2).
  48. """
  49. # Set up option parser
  50. parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
  51. parser.add_option("-d", "--doctests_only", action="store_true",
  52. help="Fix up doctests only")
  53. parser.add_option("-f", "--fix", action="append", default=[],
  54. help="Each FIX specifies a transformation; default: all")
  55. parser.add_option("-x", "--nofix", action="append", default=[],
  56. help="Prevent a fixer from being run.")
  57. parser.add_option("-l", "--list-fixes", action="store_true",
  58. help="List available transformations (fixes/fix_*.py)")
  59. parser.add_option("-p", "--print-function", action="store_true",
  60. help="Modify the grammar so that print() is a function")
  61. parser.add_option("-v", "--verbose", action="store_true",
  62. help="More verbose logging")
  63. parser.add_option("-w", "--write", action="store_true",
  64. help="Write back modified files")
  65. parser.add_option("-n", "--nobackups", action="store_true", default=False,
  66. help="Don't write backups for modified files.")
  67. # Parse command line arguments
  68. refactor_stdin = False
  69. options, args = parser.parse_args(args)
  70. if not options.write and options.nobackups:
  71. parser.error("Can't use -n without -w")
  72. if options.list_fixes:
  73. print "Available transformations for the -f/--fix option:"
  74. for fixname in refactor.get_all_fix_names(fixer_pkg):
  75. print fixname
  76. if not args:
  77. return 0
  78. if not args:
  79. print >>sys.stderr, "At least one file or directory argument required."
  80. print >>sys.stderr, "Use --help to show usage."
  81. return 2
  82. if "-" in args:
  83. refactor_stdin = True
  84. if options.write:
  85. print >>sys.stderr, "Can't write to stdin."
  86. return 2
  87. # Set up logging handler
  88. level = logging.DEBUG if options.verbose else logging.INFO
  89. logging.basicConfig(format='%(name)s: %(message)s', level=level)
  90. # Initialize the refactoring tool
  91. rt_opts = {"print_function" : options.print_function}
  92. avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
  93. unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
  94. explicit = set()
  95. if options.fix:
  96. all_present = False
  97. for fix in options.fix:
  98. if fix == "all":
  99. all_present = True
  100. else:
  101. explicit.add(fixer_pkg + ".fix_" + fix)
  102. requested = avail_fixes.union(explicit) if all_present else explicit
  103. else:
  104. requested = avail_fixes.union(explicit)
  105. fixer_names = requested.difference(unwanted_fixes)
  106. rt = StdoutRefactoringTool(sorted(fixer_names), rt_opts, sorted(explicit),
  107. options.nobackups)
  108. # Refactor all files and directories passed as arguments
  109. if not rt.errors:
  110. if refactor_stdin:
  111. rt.refactor_stdin()
  112. else:
  113. rt.refactor(args, options.write, options.doctests_only)
  114. rt.summarize()
  115. # Return error status (0 if rt.errors is zero)
  116. return int(bool(rt.errors))