generate_copts.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env python3
  2. """Generate Abseil compile compile option configs.
  3. Usage: <path_to_absl>/copts/generate_copts.py
  4. The configs are generated from copts.py.
  5. """
  6. from os import path
  7. import sys
  8. from copts import COPT_VARS
  9. # Helper functions
  10. def file_header_lines():
  11. return [
  12. "GENERATED! DO NOT MANUALLY EDIT THIS FILE.", "",
  13. "(1) Edit absl/copts/copts.py.",
  14. "(2) Run `python <path_to_absl>/copts/generate_copts.py`."
  15. ]
  16. def flatten(*lists):
  17. return [item for sublist in lists for item in sublist]
  18. def relative_filename(filename):
  19. return path.join(path.dirname(__file__), filename)
  20. # Style classes. These contain all the syntactic styling needed to generate a
  21. # copt file for different build tools.
  22. class CMakeStyle(object):
  23. """Style object for CMake copts file."""
  24. def separator(self):
  25. return ""
  26. def list_introducer(self, name):
  27. return "list(APPEND " + name
  28. def list_closer(self):
  29. return ")\n"
  30. def docstring(self):
  31. return "\n".join((("# " + line).strip() for line in file_header_lines()))
  32. def filename(self):
  33. return "GENERATED_AbseilCopts.cmake"
  34. class StarlarkStyle(object):
  35. """Style object for Starlark copts file."""
  36. def separator(self):
  37. return ","
  38. def list_introducer(self, name):
  39. return name + " = ["
  40. def list_closer(self):
  41. return "]\n"
  42. def docstring(self):
  43. docstring_quotes = "\"\"\""
  44. return docstring_quotes + "\n".join(
  45. flatten(file_header_lines(), [docstring_quotes]))
  46. def filename(self):
  47. return "GENERATED_copts.bzl"
  48. def copt_list(name, arg_list, style):
  49. """Copt file generation."""
  50. make_line = lambda s: " \"" + s + "\"" + style.separator()
  51. external_str_list = [make_line(s) for s in arg_list]
  52. return "\n".join(
  53. flatten(
  54. [style.list_introducer(name)],
  55. external_str_list,
  56. [style.list_closer()]))
  57. def generate_copt_file(style):
  58. """Creates a generated copt file using the given style object.
  59. Args:
  60. style: either StarlarkStyle() or CMakeStyle()
  61. """
  62. with open(relative_filename(style.filename()), "w") as f:
  63. f.write(style.docstring())
  64. f.write("\n")
  65. for var_name, arg_list in sorted(COPT_VARS.items()):
  66. f.write("\n")
  67. f.write(copt_list(var_name, arg_list, style))
  68. def main(argv):
  69. if len(argv) > 1:
  70. raise RuntimeError("generate_copts needs no command line args")
  71. generate_copt_file(StarlarkStyle())
  72. generate_copt_file(CMakeStyle())
  73. if __name__ == "__main__":
  74. main(sys.argv)