migrate_cpp.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Migrates C++ code to Carbon."""
  2. __copyright__ = """
  3. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  4. Exceptions. See /LICENSE for license information.
  5. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. """
  7. import argparse
  8. import glob
  9. import os
  10. import subprocess
  11. import sys
  12. _CLANG_TIDY = "../external/bootstrap_clang_toolchain/bin/clang-tidy"
  13. _CPP_REFACTORING = "./cpp_refactoring/cpp_refactoring"
  14. _CPP_EXTS = {".h", ".c", ".cc", ".cpp", ".cxx"}
  15. def _data_file(relative_path):
  16. """Returns the path to a data file."""
  17. return os.path.join(os.path.dirname(sys.argv[0]), relative_path)
  18. def _parse_args(args=None):
  19. """Parses command-line arguments and flags."""
  20. parser = argparse.ArgumentParser(description=__doc__)
  21. parser.add_argument(
  22. "dir",
  23. type=str,
  24. help="A directory containing C++ files to migrate to Carbon.",
  25. )
  26. parsed_args = parser.parse_args(args=args)
  27. return parsed_args
  28. def _gather_files(parsed_args):
  29. """Returns the list of C++ files to convert."""
  30. all_files = glob.glob(
  31. os.path.join(parsed_args.dir, "**/*.*"), recursive=True
  32. )
  33. cpp_files = [f for f in all_files if os.path.splitext(f)[1] in _CPP_EXTS]
  34. if not cpp_files:
  35. sys.exit(
  36. "%r doesn't contain any C++ files to convert." % parsed_args.dir
  37. )
  38. return sorted(cpp_files)
  39. def _clang_tidy(parsed_args, cpp_files):
  40. """Runs clang-tidy to fix C++ files in a directory."""
  41. print("Running clang-tidy...")
  42. clang_tidy = _data_file(_CLANG_TIDY)
  43. with open(_data_file("clang_tidy.yaml")) as f:
  44. config = f.read()
  45. subprocess.run([clang_tidy, "--fix", "--config", config] + cpp_files)
  46. def _cpp_refactoring(parsed_args, cpp_files):
  47. """Runs cpp_refactoring to migrate C++ files towards Carbon syntax."""
  48. print("Running cpp_refactoring...")
  49. cpp_refactoring = _data_file(_CPP_REFACTORING)
  50. subprocess.run([cpp_refactoring] + cpp_files)
  51. def _main():
  52. """Main program execution."""
  53. parsed_args = _parse_args()
  54. # Validate arguments.
  55. if not os.path.isdir(parsed_args.dir):
  56. sys.exit("%r must point to a directory." % parsed_args.dir)
  57. cpp_files = _gather_files(parsed_args)
  58. _clang_tidy(parsed_args, cpp_files)
  59. _cpp_refactoring(parsed_args, cpp_files)
  60. print("Done!")
  61. if __name__ == "__main__":
  62. _main()