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