generate_param: make it possible to handle generated and synonym flags in iteration
[garming/samba-autobuild/.git] / script / generate_param.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) 2014 Catalyst.Net Ltd
3 #
4 # Auto generate param_functions.c
5 #
6 #   ** NOTE! The following LGPL license applies to the ldb
7 #   ** library. This does NOT imply that all of Samba is released
8 #   ** under the LGPL
9 #
10 #  This library is free software; you can redistribute it and/or
11 #  modify it under the terms of the GNU Lesser General Public
12 #  License as published by the Free Software Foundation; either
13 #  version 3 of the License, or (at your option) any later version.
14 #
15 #  This library is distributed in the hope that it will be useful,
16 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 #  Lesser General Public License for more details.
19 #
20 #  You should have received a copy of the GNU Lesser General Public
21 #  License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 #
23
24 import errno
25 import os
26 import re
27 import subprocess
28 import xml.etree.ElementTree as ET
29 import sys
30 import optparse
31
32 # parse command line arguments
33 parser = optparse.OptionParser()
34 parser.add_option("-f", "--file", dest="filename",
35                   help="input file", metavar="FILE")
36 parser.add_option("-o", "--output", dest="output",
37                   help='output file', metavar="FILE")
38 parser.add_option("--mode", type="choice", metavar="<FUNCTIONS|S3PROTO|LIBPROTO|PARAMDEFS>",
39                  choices=["FUNCTIONS", "S3PROTO", "LIBPROTO", "PARAMDEFS"], default="FUNCTIONS")
40 parser.add_option("--scope", metavar="<GLOBAL|LOCAL>",
41                   choices = ["GLOBAL", "LOCAL"], default="GLOBAL")
42
43 (options, args) = parser.parse_args()
44
45 if options.filename is None:
46     parser.error("No input file specified")
47 if options.output is None:
48     parser.error("No output file specified")
49
50 def iterate_all(path):
51     """Iterate and yield all the parameters. 
52
53     :param path: path to parameters xml file
54     """
55
56     try:
57         p = open(path, 'r')
58     except IOError, e:
59         raise Exception("Error opening parameters file")
60     out = p.read()
61
62     # parse the parameters xml file
63     root = ET.fromstring(out)
64     for parameter in root:
65         name = parameter.attrib.get("name")
66         param_type = parameter.attrib.get("type")
67         context = parameter.attrib.get("context")
68         func = parameter.attrib.get("function")
69         synonym = parameter.attrib.get("synonym")
70         removed = parameter.attrib.get("removed")
71         generated = parameter.attrib.get("generated_function")
72         if removed == "1":
73             continue
74
75         constant = parameter.attrib.get("constant")
76         parm = parameter.attrib.get("parm")
77         if name is None or param_type is None or context is None:
78             raise Exception("Error parsing parameter: " + name)
79         if func is None:
80             func = name.replace(" ", "_").lower()
81         yield {'name': name,
82                'type': param_type,
83                'context': context,
84                'function': func,
85                'constant': (constant == '1'),
86                'parm': (parm == '1'),
87                'synonym' : synonym,
88                'generated' : generated }
89
90 # map doc attributes to a section of the generated function
91 context_dict = {"G": "_GLOBAL", "S": "_LOCAL"}
92 param_type_dict = {"boolean": "_BOOL", "list": "_LIST", "string": "_STRING",
93                    "integer": "_INTEGER", "enum": "_INTEGER", "char" : "_CHAR",
94                    "boolean-auto": "_INTEGER"}
95
96 def generate_functions(path_in, path_out):
97     f = open(path_out, 'w')
98     try:
99        f.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
100        for parameter in iterate_all(options.filename):
101             # filter out parameteric options
102             if ':' in parameter['name']:
103                 continue
104             if parameter['synonym'] == "1":
105                 continue
106             if parameter['generated'] == "0":
107                 continue
108
109             output_string = "FN"
110             temp = context_dict.get(parameter['context'])
111             if temp is None: 
112                 raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
113             output_string += temp
114             if parameter['constant']:
115                 output_string += "_CONST"
116             if parameter['parm']: 
117                 output_string += "_PARM"
118             temp = param_type_dict.get(parameter['type'])
119             if temp is None:
120                 raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
121             output_string += temp
122             f.write(output_string + "(" + parameter['function'] +", " + parameter['function'] + ')\n')
123     finally:
124         f.close()
125
126 mapping = {'boolean': 'bool ', 'string': 'char *', 'integer': 'int ', 'char': 'char ',
127            'list': 'const char **', 'enum': 'int ', 'boolean-auto': 'int '}
128
129 def make_s3_param_proto(path_in, path_out):
130     file_out = open(path_out, 'w')
131     try:
132         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
133         header = get_header(path_out)
134         file_out.write("#ifndef %s\n" % header)
135         file_out.write("#define %s\n\n" % header)
136         for parameter in iterate_all(path_in):
137             # filter out parameteric options
138             if ':' in parameter['name']:
139                 continue
140             if parameter['synonym'] == "1":
141                 continue
142             if parameter['generated'] == "0":
143                 continue
144
145             output_string = ""
146             if parameter['constant']:
147                 output_string += 'const '
148             param_type = mapping.get(parameter['type'])
149             if param_type is None:
150                raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
151             output_string += param_type
152             output_string += "lp_%s" % parameter['function']
153
154             param = None
155             if parameter['parm']:
156                 param = "const struct share_params *p"
157             else:
158                 param = "int"
159
160             if parameter['type'] == 'string' and not parameter['constant']:
161                 if parameter['context'] == 'G':
162                     output_string += '(TALLOC_CTX *ctx);\n'
163                 elif parameter['context'] == 'S':
164                     output_string += '(TALLOC_CTX *ctx, %s);\n' % param
165                 else:
166                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
167             else:
168                 if parameter['context'] == 'G':
169                     output_string += '(void);\n'
170                 elif parameter['context'] == 'S':
171                     output_string += '(%s);\n' % param
172                 else:
173                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
174
175             file_out.write(output_string)
176
177         file_out.write("\n#endif /* %s */\n\n" % header)
178     finally:
179         file_out.close()
180
181
182 def make_lib_proto(path_in, path_out):
183     file_out = open(path_out, 'w')
184     try:
185         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
186         for parameter in iterate_all(path_in):
187             # filter out parameteric options
188             if ':' in parameter['name']:
189                 continue
190             if parameter['synonym'] == "1":
191                 continue
192             if parameter['generated'] == "0":
193                 continue
194
195             output_string = ""
196             if parameter['constant']:
197                 output_string += 'const '
198             param_type = mapping.get(parameter['type'])
199             if param_type is None:
200                raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
201             output_string += param_type
202
203             output_string += "lpcfg_%s" % parameter['function']
204
205             if parameter['type'] == 'string' and not parameter['constant']:
206                 if parameter['context'] == 'G':
207                     output_string += '(struct loadparm_context *, TALLOC_CTX *ctx);\n'
208                 elif parameter['context'] == 'S':
209                     output_string += '(struct loadparm_service *, struct loadparm_service *, TALLOC_CTX *ctx);\n'
210                 else:
211                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
212             else:
213                 if parameter['context'] == 'G':
214                     output_string += '(struct loadparm_context *);\n'
215                 elif parameter['context'] == 'S':
216                     output_string += '(struct loadparm_service *, struct loadparm_service *);\n'
217                 else:
218                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
219
220             
221             file_out.write(output_string)
222     finally:
223         file_out.close()
224
225 def get_header(path):
226     header = os.path.basename(path).upper()
227     header = header.replace(".", "_").replace("\\", "_").replace("-", "_")
228     return "__%s__" % header
229
230 def make_param_defs(path_in, path_out, scope):
231     file_out = open(path_out, 'w')
232     try:
233         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
234         header = get_header(path_out)
235         file_out.write("#ifndef %s\n" % header)
236         file_out.write("#define %s\n\n" % header)
237         if scope == "GLOBAL": 
238             file_out.write("/**\n")
239             file_out.write(" * This structure describes global (ie., server-wide) parameters.\n")
240             file_out.write(" */\n")
241             file_out.write("struct loadparm_global \n")
242             file_out.write("{\n")
243             file_out.write("\tTALLOC_CTX *ctx; /* Context for talloced members */\n")
244             file_out.write("\tchar *  dnsdomain;\n")
245         elif scope == "LOCAL":
246             file_out.write("/**\n")
247             file_out.write(" * This structure describes a single service.\n")
248             file_out.write(" */\n")
249             file_out.write("struct loadparm_service \n")
250             file_out.write("{\n")
251             file_out.write("\tbool   autoloaded;\n")
252  
253         for parameter in iterate_all(path_in):
254             # filter out parameteric options
255             if ':' in parameter['name']:
256                 continue
257             if parameter['synonym'] == "1":
258                 continue
259             if parameter['generated'] == "0":
260                 continue
261
262             if (scope == "GLOBAL" and parameter['context'] != "G" or
263                 scope == "LOCAL" and parameter['context'] != "S"):
264                 continue
265
266             output_string = "\t"
267             param_type = mapping.get(parameter['type'])
268             if param_type is None:
269                raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
270             output_string += param_type
271
272             output_string += "  %s;\n" % parameter['function']
273             file_out.write(output_string)
274
275         file_out.write("LOADPARM_EXTRA_%sS\n" % scope)
276         file_out.write("};\n")
277         file_out.write("\n#endif /* %s */\n\n" % header)
278     finally:
279         file_out.close()
280
281 if options.mode == 'FUNCTIONS':
282     generate_functions(options.filename, options.output)
283 elif options.mode == 'S3PROTO':
284     make_s3_param_proto(options.filename, options.output)
285 elif options.mode == 'LIBPROTO':
286     make_lib_proto(options.filename, options.output)
287 elif options.mode == 'PARAMDEFS':
288     make_param_defs(options.filename, options.output, options.scope)