main.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. """
  2. futurize: automatic conversion to clean 2/3 code using ``python-future``
  3. ======================================================================
  4. Like Armin Ronacher's modernize.py, ``futurize`` attempts to produce clean
  5. standard Python 3 code that runs on both Py2 and Py3.
  6. One pass
  7. --------
  8. Use it like this on Python 2 code:
  9. $ futurize --verbose mypython2script.py
  10. This will attempt to port the code to standard Py3 code that also
  11. provides Py2 compatibility with the help of the right imports from
  12. ``future``.
  13. To write changes to the files, use the -w flag.
  14. Two stages
  15. ----------
  16. The ``futurize`` script can also be called in two separate stages. First:
  17. $ futurize --stage1 mypython2script.py
  18. This produces more modern Python 2 code that is not yet compatible with Python
  19. 3. The tests should still run and the diff should be uncontroversial to apply to
  20. most Python projects that are willing to drop support for Python 2.5 and lower.
  21. After this, the recommended approach is to explicitly mark all strings that must
  22. be byte-strings with a b'' prefix and all text (unicode) strings with a u''
  23. prefix, and then invoke the second stage of Python 2 to 2/3 conversion with::
  24. $ futurize --stage2 mypython2script.py
  25. Stage 2 adds a dependency on ``future``. It converts most remaining Python
  26. 2-specific code to Python 3 code and adds appropriate imports from ``future``
  27. to restore Py2 support.
  28. The command above leaves all unadorned string literals as native strings
  29. (byte-strings on Py2, unicode strings on Py3). If instead you would like all
  30. unadorned string literals to be promoted to unicode, you can also pass this
  31. flag:
  32. $ futurize --stage2 --unicode-literals mypython2script.py
  33. This adds the declaration ``from __future__ import unicode_literals`` to the
  34. top of each file, which implicitly declares all unadorned string literals to be
  35. unicode strings (``unicode`` on Py2).
  36. All imports
  37. -----------
  38. The --all-imports option forces adding all ``__future__`` imports,
  39. ``builtins`` imports, and standard library aliases, even if they don't
  40. seem necessary for the current state of each module. (This can simplify
  41. testing, and can reduce the need to think about Py2 compatibility when editing
  42. the code further.)
  43. """
  44. from __future__ import (absolute_import, print_function, unicode_literals)
  45. import future.utils
  46. from future import __version__
  47. import sys
  48. import logging
  49. import optparse
  50. import os
  51. from lib2to3.main import warn, StdoutRefactoringTool
  52. from lib2to3 import refactor
  53. from libfuturize.fixes import (lib2to3_fix_names_stage1,
  54. lib2to3_fix_names_stage2,
  55. libfuturize_fix_names_stage1,
  56. libfuturize_fix_names_stage2)
  57. fixer_pkg = 'libfuturize.fixes'
  58. def main(args=None):
  59. """Main program.
  60. Args:
  61. fixer_pkg: the name of a package where the fixers are located.
  62. args: optional; a list of command line arguments. If omitted,
  63. sys.argv[1:] is used.
  64. Returns a suggested exit status (0, 1, 2).
  65. """
  66. # Set up option parser
  67. parser = optparse.OptionParser(usage="futurize [options] file|dir ...")
  68. parser.add_option("-V", "--version", action="store_true",
  69. help="Report the version number of futurize")
  70. parser.add_option("-a", "--all-imports", action="store_true",
  71. help="Add all __future__ and future imports to each module")
  72. parser.add_option("-1", "--stage1", action="store_true",
  73. help="Modernize Python 2 code only; no compatibility with Python 3 (or dependency on ``future``)")
  74. parser.add_option("-2", "--stage2", action="store_true",
  75. help="Take modernized (stage1) code and add a dependency on ``future`` to provide Py3 compatibility.")
  76. parser.add_option("-0", "--both-stages", action="store_true",
  77. help="Apply both stages 1 and 2")
  78. parser.add_option("-u", "--unicode-literals", action="store_true",
  79. help="Add ``from __future__ import unicode_literals`` to implicitly convert all unadorned string literals '' into unicode strings")
  80. parser.add_option("-f", "--fix", action="append", default=[],
  81. help="Each FIX specifies a transformation; default: all.\nEither use '-f division -f metaclass' etc. or use the fully-qualified module name: '-f lib2to3.fixes.fix_types -f libfuturize.fixes.fix_unicode_keep_u'")
  82. parser.add_option("-j", "--processes", action="store", default=1,
  83. type="int", help="Run 2to3 concurrently")
  84. parser.add_option("-x", "--nofix", action="append", default=[],
  85. help="Prevent a fixer from being run.")
  86. parser.add_option("-l", "--list-fixes", action="store_true",
  87. help="List available transformations")
  88. parser.add_option("-p", "--print-function", action="store_true",
  89. help="Modify the grammar so that print() is a function")
  90. parser.add_option("-v", "--verbose", action="store_true",
  91. help="More verbose logging")
  92. parser.add_option("--no-diffs", action="store_true",
  93. help="Don't show diffs of the refactoring")
  94. parser.add_option("-w", "--write", action="store_true",
  95. help="Write back modified files")
  96. parser.add_option("-n", "--nobackups", action="store_true", default=False,
  97. help="Don't write backups for modified files.")
  98. parser.add_option("-o", "--output-dir", action="store", type="str",
  99. default="", help="Put output files in this directory "
  100. "instead of overwriting the input files. Requires -n. "
  101. "For Python >= 2.7 only.")
  102. parser.add_option("-W", "--write-unchanged-files", action="store_true",
  103. help="Also write files even if no changes were required"
  104. " (useful with --output-dir); implies -w.")
  105. parser.add_option("--add-suffix", action="store", type="str", default="",
  106. help="Append this string to all output filenames."
  107. " Requires -n if non-empty. For Python >= 2.7 only."
  108. "ex: --add-suffix='3' will generate .py3 files.")
  109. # Parse command line arguments
  110. flags = {}
  111. refactor_stdin = False
  112. options, args = parser.parse_args(args)
  113. if options.write_unchanged_files:
  114. flags["write_unchanged_files"] = True
  115. if not options.write:
  116. warn("--write-unchanged-files/-W implies -w.")
  117. options.write = True
  118. # If we allowed these, the original files would be renamed to backup names
  119. # but not replaced.
  120. if options.output_dir and not options.nobackups:
  121. parser.error("Can't use --output-dir/-o without -n.")
  122. if options.add_suffix and not options.nobackups:
  123. parser.error("Can't use --add-suffix without -n.")
  124. if not options.write and options.no_diffs:
  125. warn("not writing files and not printing diffs; that's not very useful")
  126. if not options.write and options.nobackups:
  127. parser.error("Can't use -n without -w")
  128. if "-" in args:
  129. refactor_stdin = True
  130. if options.write:
  131. print("Can't write to stdin.", file=sys.stderr)
  132. return 2
  133. # Is this ever necessary?
  134. if options.print_function:
  135. flags["print_function"] = True
  136. # Set up logging handler
  137. level = logging.DEBUG if options.verbose else logging.INFO
  138. logging.basicConfig(format='%(name)s: %(message)s', level=level)
  139. logger = logging.getLogger('libfuturize.main')
  140. if options.stage1 or options.stage2:
  141. assert options.both_stages is None
  142. options.both_stages = False
  143. else:
  144. options.both_stages = True
  145. avail_fixes = set()
  146. if options.stage1 or options.both_stages:
  147. avail_fixes.update(lib2to3_fix_names_stage1)
  148. avail_fixes.update(libfuturize_fix_names_stage1)
  149. if options.stage2 or options.both_stages:
  150. avail_fixes.update(lib2to3_fix_names_stage2)
  151. avail_fixes.update(libfuturize_fix_names_stage2)
  152. if options.unicode_literals:
  153. avail_fixes.add('libfuturize.fixes.fix_unicode_literals_import')
  154. if options.version:
  155. print(__version__)
  156. return 0
  157. if options.list_fixes:
  158. print("Available transformations for the -f/--fix option:")
  159. # for fixname in sorted(refactor.get_all_fix_names(fixer_pkg)):
  160. for fixname in sorted(avail_fixes):
  161. print(fixname)
  162. if not args:
  163. return 0
  164. if not args:
  165. print("At least one file or directory argument required.",
  166. file=sys.stderr)
  167. print("Use --help to show usage.", file=sys.stderr)
  168. return 2
  169. unwanted_fixes = set()
  170. for fix in options.nofix:
  171. if ".fix_" in fix:
  172. unwanted_fixes.add(fix)
  173. else:
  174. # Infer the full module name for the fixer.
  175. # First ensure that no names clash (e.g.
  176. # lib2to3.fixes.fix_blah and libfuturize.fixes.fix_blah):
  177. found = [f for f in avail_fixes
  178. if f.endswith('fix_{0}'.format(fix))]
  179. if len(found) > 1:
  180. print("Ambiguous fixer name. Choose a fully qualified "
  181. "module name instead from these:\n" +
  182. "\n".join(" " + myf for myf in found),
  183. file=sys.stderr)
  184. return 2
  185. elif len(found) == 0:
  186. print("Unknown fixer. Use --list-fixes or -l for a list.",
  187. file=sys.stderr)
  188. return 2
  189. unwanted_fixes.add(found[0])
  190. extra_fixes = set()
  191. if options.all_imports:
  192. if options.stage1:
  193. prefix = 'libfuturize.fixes.'
  194. extra_fixes.add(prefix +
  195. 'fix_add__future__imports_except_unicode_literals')
  196. else:
  197. # In case the user hasn't run stage1 for some reason:
  198. prefix = 'libpasteurize.fixes.'
  199. extra_fixes.add(prefix + 'fix_add_all__future__imports')
  200. extra_fixes.add(prefix + 'fix_add_future_standard_library_import')
  201. extra_fixes.add(prefix + 'fix_add_all_future_builtins')
  202. explicit = set()
  203. if options.fix:
  204. all_present = False
  205. for fix in options.fix:
  206. if fix == 'all':
  207. all_present = True
  208. else:
  209. if ".fix_" in fix:
  210. explicit.add(fix)
  211. else:
  212. # Infer the full module name for the fixer.
  213. # First ensure that no names clash (e.g.
  214. # lib2to3.fixes.fix_blah and libfuturize.fixes.fix_blah):
  215. found = [f for f in avail_fixes
  216. if f.endswith('fix_{0}'.format(fix))]
  217. if len(found) > 1:
  218. print("Ambiguous fixer name. Choose a fully qualified "
  219. "module name instead from these:\n" +
  220. "\n".join(" " + myf for myf in found),
  221. file=sys.stderr)
  222. return 2
  223. elif len(found) == 0:
  224. print("Unknown fixer. Use --list-fixes or -l for a list.",
  225. file=sys.stderr)
  226. return 2
  227. explicit.add(found[0])
  228. if len(explicit & unwanted_fixes) > 0:
  229. print("Conflicting usage: the following fixers have been "
  230. "simultaneously requested and disallowed:\n" +
  231. "\n".join(" " + myf for myf in (explicit & unwanted_fixes)),
  232. file=sys.stderr)
  233. return 2
  234. requested = avail_fixes.union(explicit) if all_present else explicit
  235. else:
  236. requested = avail_fixes.union(explicit)
  237. fixer_names = (requested | extra_fixes) - unwanted_fixes
  238. input_base_dir = os.path.commonprefix(args)
  239. if (input_base_dir and not input_base_dir.endswith(os.sep)
  240. and not os.path.isdir(input_base_dir)):
  241. # One or more similar names were passed, their directory is the base.
  242. # os.path.commonprefix() is ignorant of path elements, this corrects
  243. # for that weird API.
  244. input_base_dir = os.path.dirname(input_base_dir)
  245. if options.output_dir:
  246. input_base_dir = input_base_dir.rstrip(os.sep)
  247. logger.info('Output in %r will mirror the input directory %r layout.',
  248. options.output_dir, input_base_dir)
  249. # Initialize the refactoring tool
  250. if future.utils.PY26:
  251. extra_kwargs = {}
  252. else:
  253. extra_kwargs = {
  254. 'append_suffix': options.add_suffix,
  255. 'output_dir': options.output_dir,
  256. 'input_base_dir': input_base_dir,
  257. }
  258. rt = StdoutRefactoringTool(
  259. sorted(fixer_names), flags, sorted(explicit),
  260. options.nobackups, not options.no_diffs,
  261. **extra_kwargs)
  262. # Refactor all files and directories passed as arguments
  263. if not rt.errors:
  264. if refactor_stdin:
  265. rt.refactor_stdin()
  266. else:
  267. try:
  268. rt.refactor(args, options.write, None,
  269. options.processes)
  270. except refactor.MultiprocessingUnsupported:
  271. assert options.processes > 1
  272. print("Sorry, -j isn't " \
  273. "supported on this platform.", file=sys.stderr)
  274. return 1
  275. rt.summarize()
  276. # Return error status (0 if rt.errors is zero)
  277. return int(bool(rt.errors))