b71d3aac35d1b4eedbce12863e23365f6bf72202
[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 = {
93                     "boolean"      : "_BOOL",
94                     "list"         : "_LIST",
95                     "string"       : "_STRING",
96                     "integer"      : "_INTEGER",
97                     "enum"         : "_INTEGER",
98                     "char"         : "_CHAR",
99                     "boolean-auto" : "_INTEGER",
100                     "cmdlist"      : "_LIST",
101                     "bytes"        : "_INTEGER",
102                     "octal"        : "_INTEGER",
103                     "ustring"      : "_STRING",
104                   }
105
106 def generate_functions(path_in, path_out):
107     f = open(path_out, 'w')
108     try:
109        f.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
110        for parameter in iterate_all(options.filename):
111             # filter out parameteric options
112             if ':' in parameter['name']:
113                 continue
114             if parameter['synonym'] == "1":
115                 continue
116             if parameter['generated'] == "0":
117                 continue
118
119             output_string = "FN"
120             temp = context_dict.get(parameter['context'])
121             if temp is None: 
122                 raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
123             output_string += temp
124             if parameter['constant']:
125                 output_string += "_CONST"
126             if parameter['parm']: 
127                 output_string += "_PARM"
128             temp = param_type_dict.get(parameter['type'])
129             if temp is None:
130                 raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
131             output_string += temp
132             f.write(output_string + "(" + parameter['function'] +", " + parameter['function'] + ')\n')
133     finally:
134         f.close()
135
136 mapping = {
137             'boolean'      : 'bool ',
138             'string'       : 'char *',
139             'integer'      : 'int ',
140             'char'         : 'char ',
141             'list'         : 'const char **',
142             'enum'         : 'int ',
143             'boolean-auto' : 'int ',
144             'cmdlist'      : 'const char **',
145             'bytes'        : 'int ',
146             'octal'        : 'int ',
147             'ustring'      : 'char *',
148           }
149
150 def make_s3_param_proto(path_in, path_out):
151     file_out = open(path_out, 'w')
152     try:
153         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
154         header = get_header(path_out)
155         file_out.write("#ifndef %s\n" % header)
156         file_out.write("#define %s\n\n" % header)
157         for parameter in iterate_all(path_in):
158             # filter out parameteric options
159             if ':' in parameter['name']:
160                 continue
161             if parameter['synonym'] == "1":
162                 continue
163             if parameter['generated'] == "0":
164                 continue
165
166             output_string = ""
167             if parameter['constant']:
168                 output_string += 'const '
169             param_type = mapping.get(parameter['type'])
170             if param_type is None:
171                raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
172             output_string += param_type
173             output_string += "lp_%s" % parameter['function']
174
175             param = None
176             if parameter['parm']:
177                 param = "const struct share_params *p"
178             else:
179                 param = "int"
180
181             if parameter['type'] == 'string' and not parameter['constant']:
182                 if parameter['context'] == 'G':
183                     output_string += '(TALLOC_CTX *ctx);\n'
184                 elif parameter['context'] == 'S':
185                     output_string += '(TALLOC_CTX *ctx, %s);\n' % param
186                 else:
187                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
188             else:
189                 if parameter['context'] == 'G':
190                     output_string += '(void);\n'
191                 elif parameter['context'] == 'S':
192                     output_string += '(%s);\n' % param
193                 else:
194                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
195
196             file_out.write(output_string)
197
198         file_out.write("\n#endif /* %s */\n\n" % header)
199     finally:
200         file_out.close()
201
202
203 def make_lib_proto(path_in, path_out):
204     file_out = open(path_out, 'w')
205     try:
206         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
207         for parameter in iterate_all(path_in):
208             # filter out parameteric options
209             if ':' in parameter['name']:
210                 continue
211             if parameter['synonym'] == "1":
212                 continue
213             if parameter['generated'] == "0":
214                 continue
215
216             output_string = ""
217             if parameter['constant']:
218                 output_string += 'const '
219             param_type = mapping.get(parameter['type'])
220             if param_type is None:
221                raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
222             output_string += param_type
223
224             output_string += "lpcfg_%s" % parameter['function']
225
226             if parameter['type'] == 'string' and not parameter['constant']:
227                 if parameter['context'] == 'G':
228                     output_string += '(struct loadparm_context *, TALLOC_CTX *ctx);\n'
229                 elif parameter['context'] == 'S':
230                     output_string += '(struct loadparm_service *, struct loadparm_service *, TALLOC_CTX *ctx);\n'
231                 else:
232                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
233             else:
234                 if parameter['context'] == 'G':
235                     output_string += '(struct loadparm_context *);\n'
236                 elif parameter['context'] == 'S':
237                     output_string += '(struct loadparm_service *, struct loadparm_service *);\n'
238                 else:
239                     raise Exception(parameter['name'] + " has an invalid param type " + parameter['type'])
240
241             
242             file_out.write(output_string)
243     finally:
244         file_out.close()
245
246 def get_header(path):
247     header = os.path.basename(path).upper()
248     header = header.replace(".", "_").replace("\\", "_").replace("-", "_")
249     return "__%s__" % header
250
251 def make_param_defs(path_in, path_out, scope):
252     file_out = open(path_out, 'w')
253     try:
254         file_out.write('/* This file was automatically generated by generate_param.py. DO NOT EDIT */\n\n')
255         header = get_header(path_out)
256         file_out.write("#ifndef %s\n" % header)
257         file_out.write("#define %s\n\n" % header)
258         if scope == "GLOBAL": 
259             file_out.write("/**\n")
260             file_out.write(" * This structure describes global (ie., server-wide) parameters.\n")
261             file_out.write(" */\n")
262             file_out.write("struct loadparm_global \n")
263             file_out.write("{\n")
264             file_out.write("\tTALLOC_CTX *ctx; /* Context for talloced members */\n")
265         elif scope == "LOCAL":
266             file_out.write("/**\n")
267             file_out.write(" * This structure describes a single service.\n")
268             file_out.write(" */\n")
269             file_out.write("struct loadparm_service \n")
270             file_out.write("{\n")
271             file_out.write("\tbool   autoloaded;\n")
272  
273         for parameter in iterate_all(path_in):
274             # filter out parameteric options
275             if ':' in parameter['name']:
276                 continue
277             if parameter['synonym'] == "1":
278                 continue
279
280             if (scope == "GLOBAL" and parameter['context'] != "G" or
281                 scope == "LOCAL" and parameter['context'] != "S"):
282                 continue
283
284             output_string = "\t"
285             param_type = mapping.get(parameter['type'])
286             if param_type is None:
287                raise Exception(parameter['name'] + " has an invalid context " + parameter['context'])
288             output_string += param_type
289
290             output_string += "  %s;\n" % parameter['function']
291             file_out.write(output_string)
292
293         file_out.write("LOADPARM_EXTRA_%sS\n" % scope)
294         file_out.write("};\n")
295         file_out.write("\n#endif /* %s */\n\n" % header)
296     finally:
297         file_out.close()
298
299 if options.mode == 'FUNCTIONS':
300     generate_functions(options.filename, options.output)
301 elif options.mode == 'S3PROTO':
302     make_s3_param_proto(options.filename, options.output)
303 elif options.mode == 'LIBPROTO':
304     make_lib_proto(options.filename, options.output)
305 elif options.mode == 'PARAMDEFS':
306     make_param_defs(options.filename, options.output, options.scope)