migrate_cpp.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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_EXTS = {".h", ".c", ".cc", ".cpp", ".cxx"}
  14. def _data_file(relative_path):
  15. """Returns the path to a data file."""
  16. return os.path.join(os.path.dirname(sys.argv[0]), relative_path)
  17. def _parse_args(args=None):
  18. """Parses command-line arguments and flags."""
  19. parser = argparse.ArgumentParser(description=__doc__)
  20. parser.add_argument(
  21. "dir",
  22. type=str,
  23. help="A directory containing C++ files to migrate to Carbon.",
  24. )
  25. parsed_args = parser.parse_args(args=args)
  26. return parsed_args
  27. def _gather_files(parsed_args):
  28. """Returns the list of C++ files to convert."""
  29. all_files = glob.glob(
  30. os.path.join(parsed_args.dir, "**/*.*"), recursive=True
  31. )
  32. cpp_files = [f for f in all_files if os.path.splitext(f)[1] in _CPP_EXTS]
  33. if not cpp_files:
  34. sys.exit(
  35. "%r doesn't contain any C++ files to convert." % parsed_args.dir
  36. )
  37. return sorted(cpp_files)
  38. def _clang_tidy(parsed_args, cpp_files):
  39. """Runs clang-tidy to fix C++ files in a directory."""
  40. print("Running clang-tidy...")
  41. clang_tidy = _data_file(_CLANG_TIDY)
  42. with open(_data_file("clang_tidy.yaml")) as f:
  43. config = f.read()
  44. subprocess.run([clang_tidy, "--fix", "--config", config] + cpp_files)
  45. def _main():
  46. """Main program execution."""
  47. parsed_args = _parse_args()
  48. # Validate arguments.
  49. if not os.path.isdir(parsed_args.dir):
  50. sys.exit("%r must point to a directory." % parsed_args.dir)
  51. cpp_files = _gather_files(parsed_args)
  52. _clang_tidy(parsed_args, cpp_files)
  53. print("Done!")
  54. if __name__ == "__main__":
  55. _main()