def codemod(path): """`hypothesis codemod` refactors deprecated or inefficient code. It adapts `python -m libcst.tool`, removing many features and config options which are rarely relevant for this purpose. If you need more control, we encourage you to use the libcst CLI directly; if not this one is easier. PATH is the file(s) or directories of files to format in place, or "-" to read from stdin and write to stdout. """ try: from libcst.codemod import gather_files from hypothesis.extra import codemods except ImportError: sys.stderr.write( "You are missing required dependencies for this option. Run:\n\n" " python -m pip install --upgrade hypothesis[codemods]\n\n" "and try again." ) sys.exit(1) # Special case for stdin/stdout usage if "-" in path: if len(path) > 1: raise Exception( "Cannot specify multiple paths when reading from stdin!" ) print("Codemodding from stdin", file=sys.stderr) print(codemods.refactor(sys.stdin.read())) return 0 # Find all the files to refactor, and then codemod them files = gather_files(path) errors = set() if len(files) <= 1: errors.add(_refactor(codemods.refactor, *files)) else: with Pool() as pool: for msg in pool.imap_unordered( partial(_refactor, codemods.refactor), files ): errors.add(msg) errors.discard(None) for msg in errors: print(msg, file=sys.stderr) return 1 if errors else 0
def test_refactor_function_is_idempotent(): before = ("from hypothesis.strategies import complex_numbers\n\n" + "complex_numbers(None)\n") after = codemods.refactor(before) assert before.replace("None", "min_magnitude=0") == after assert codemods.refactor(after) == after