Refactor to use new protocol module and sipo.
[bertos.git] / wizard / bertos_utils.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # This file is part of BeRTOS.
5 #
6 # Bertos is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19 #
20 # As a special exception, you may use this file as part of a free software
21 # library without restriction.  Specifically, if other files instantiate
22 # templates or use macros or inline functions from this file, or you compile
23 # this file and link it with other files to produce an executable, this
24 # file does not by itself cause the resulting executable to be covered by
25 # the GNU General Public License.  This exception does not however
26 # invalidate any other reasons why the executable file might be covered by
27 # the GNU General Public License.
28 #
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
30 #
31 #
32 # Author: Lorenzo Berni <duplo@develer.com>
33 #
34
35 import os
36 import fnmatch
37 import glob
38 import re
39 import shutil
40 # Use custom copytree function
41 import copytree
42 import relpath
43 import pickle
44
45 import const
46 import plugins
47 import DefineException
48
49 from _wizard_version import WIZARD_VERSION
50
51 from LoadException import VersionException, ToolchainException
52
53 def _cmp(x, y):
54     result = cmp(x["info"].get('ord', 0), y["info"].get('ord', 0))
55     if result == 0:
56         result = cmp(
57             x["info"].get("name", x["info"]["filename"]).lower(),
58             y["info"].get("name", y["info"]["filename"]).lower()
59         )
60     return result
61
62 def isBertosDir(directory):
63    return os.path.exists(directory + "/VERSION")
64
65 def bertosVersion(directory):
66    return open(directory + "/VERSION").readline().strip()
67
68 def enabledModules(project_info):
69     enabled_modules = []
70     for name, module in project_info.info("MODULES").items():
71         if module["enabled"]:
72             enabled_modules.append(name)
73     return enabled_modules
74
75 def presetList(directory):
76     """
77     Return the list of the preset found in the selected BeRTOS Version.
78     """
79     abspath = os.path.join(directory, const.PREDEFINED_BOARDS_DIR)
80     preset_list = dict([
81         (os.path.join(abspath, preset_dir), presetInfo(os.path.join(abspath, preset_dir)))
82         for preset_dir in os.listdir(os.path.join(directory, const.PREDEFINED_BOARDS_DIR))
83     ])
84     return preset_list
85
86 def presetInfo(preset_dir):
87     """
88     Return the preset-relevant info contined into the project_file.
89     """
90     preset_info = pickle.loads(open(os.path.join(preset_dir, "project.bertos"), "r").read())
91     try:
92         description = open(os.path.join(preset_dir, "description"), "r").read()
93     except IOError:
94         # No description file found.
95         description = ""
96     relevant_info = {
97         "CPU_NAME": preset_info.get("CPU_NAME"),
98         "SELECTED_FREQ": preset_info.get("SELECTED_FREQ"),
99         "WIZARD_VERSION": preset_info.get("WIZARD_VERSION", None),
100         "PRESET_NAME": preset_info.get("PROJECT_NAME"),
101         "PRESET_DESCRIPTION": description.decode("utf-8"),
102     }
103     return relevant_info
104
105 def mergeSources(srcdir, new_sources, old_sources):
106     # The current mergeSources function provide only a raw copy of the sources in the
107     # created project.
108     #
109     # TODO: implement the three way merge algorithm
110     #
111     shutil.rmtree(srcdir, True)
112     copytree.copytree(os.path.join(new_sources, "bertos"), srcdir, ignore_list=const.IGNORE_LIST)
113
114 def projectFileGenerator(project_info):
115     directory = project_info.info("PROJECT_PATH")
116     project_data = {}
117     enabled_modules = []
118     for module, information in project_info.info("MODULES").items():
119         if information["enabled"]:
120             enabled_modules.append(module)
121     project_data["ENABLED_MODULES"] = sorted(enabled_modules)
122     if project_info.info("PRESET"):
123         # For presets save again the BERTOS_PATH into project file
124         project_data["PRESET"] = True
125         project_data["BERTOS_PATH"] = relpath.relpath(project_info.info("BERTOS_PATH"), directory)
126     elif project_info.edit:
127         # If in editing mode the BERTOS_PATH is maintained
128         project_data["BERTOS_PATH"] = relpath.relpath(project_info.info("BERTOS_PATH"), directory)
129     else:
130         # Use the local BeRTOS version instead of the original one
131         # project_data["BERTOS_PATH"] = project_info.info("BERTOS_PATH")
132         project_data["BERTOS_PATH"] = "."
133     project_data["PROJECT_NAME"] = project_info.info("PROJECT_NAME", os.path.basename(directory))
134     project_src_relpath = relpath.relpath(project_info.info("PROJECT_SRC_PATH"), directory)
135     project_data["PROJECT_SRC_PATH"] = project_src_relpath
136     project_data["PROJECT_SRC_PATH_FROM_MAKEFILE"] = project_info.info("PROJECT_SRC_PATH_FROM_MAKEFILE")
137     project_data["TOOLCHAIN"] = {'path': project_info.info("TOOLCHAIN")['path']}
138     project_data["CPU_NAME"] = project_info.info("CPU_NAME")
139     project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
140     project_data["OUTPUT"] = project_info.info("OUTPUT")
141     project_data["WIZARD_VERSION"] = WIZARD_VERSION
142     project_data["PRESET"] = project_info.info("PRESET")
143     project_data["PROJECT_HW_PATH"] = relpath.relpath(project_info.info("PROJECT_HW_PATH"), directory)
144     project_data["PROJECT_HW_PATH_FROM_MAKEFILE"] = project_info.info("PROJECT_HW_PATH_FROM_MAKEFILE")
145     return pickle.dumps(project_data)
146
147 def loadPlugin(plugin):
148     """
149     Returns the given plugin module.
150     """
151     return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
152
153 def versionFileGenerator(project_info, version_file):
154     version = bertosVersion(project_info.info("BERTOS_PATH"))
155     return version_file.replace('$version', version)
156
157 def userMkGeneratorFromPreset(project_info):
158     project_name = project_info.info("PROJECT_NAME")
159     preset_path = project_info.info("PRESET_PATH")
160     preset_name = project_info.info("PRESET_NAME")
161     preset_src_dir = project_info.info("PRESET_SRC_PATH")
162     makefile = open(os.path.join(preset_path, preset_src_dir, "%s_user.mk" %preset_name), 'r').read()
163     destination = os.path.join(project_info.prjdir, "%s_user.mk" %project_info.info("PROJECT_NAME"))
164     # Temporary code.
165     # TODO: write it using regular expressions to secure this function
166     makefile = makefile.replace(preset_name + "_", project_name + "_")
167     open(destination, "w").write(makefile)
168
169 def userMkGenerator(project_info):
170     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template_user.mk"), "r").read()
171     destination = os.path.join(project_info.prjdir, os.path.basename(project_info.prjdir) + "_user.mk")
172     # Deadly performances loss was here :(
173     mk_data = {}
174     mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
175     mk_data["$ppath"] = project_info.info("PROJECT_SRC_PATH_FROM_MAKEFILE")
176     mk_data["$main"] = "/".join(["$(%s_SRC_PATH)" %project_info.info("PROJECT_NAME"), "main.c"])
177     for key in mk_data:
178         makefile = makefile.replace(key, mk_data[key])
179     open(destination, "w").write(makefile)
180
181 def mkGenerator(project_info):
182     """
183     Generates the mk file for the current project.
184     """
185     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template.mk"), "r").read()
186     prjdir = os.path.abspath(project_info.prjdir)
187     destination = os.path.join(prjdir, os.path.basename(prjdir) + ".mk")
188     mk_data = {}
189     mk_data["$pname"] = project_info.info("PROJECT_NAME")
190     mk_data["$ppath"] = project_info.info("PROJECT_SRC_PATH_FROM_MAKEFILE")
191     mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
192     cpu_mk_parameters = []
193     for key, value in project_info.info("CPU_INFOS").items():
194         if key.startswith(const.MK_PARAM_ID):
195             cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
196     mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
197     mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
198     mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].rsplit("gcc", 1)[0])
199     mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].rsplit("gcc", 1)[1])
200     mk_data["$hwpath"] = project_info.info("PROJECT_HW_PATH_FROM_MAKEFILE")
201     for key in mk_data:
202         makefile = makefile.replace(key, mk_data[key])
203     open(destination, "w").write(makefile)
204
205 def makefileGenerator(project_info):
206     """
207     Generate the Makefile for the current project.
208     """
209     makefile = open(os.path.join(const.DATA_DIR, "mktemplates/Makefile"), "r").read()
210     destination = os.path.join(project_info.maindir, "Makefile")
211     # TODO write a general function that works for both the mk file and the Makefile
212     mk_data = {}
213     mk_data["$pname"] = project_info.info("PROJECT_NAME")
214     mk_data["$ppath"] = project_info.info("PROJECT_SRC_PATH_FROM_MAKEFILE")
215     for key in mk_data:
216         makefile = makefile.replace(key, mk_data[key])
217     open(destination, "w").write(makefile)
218
219 def csrcGenerator(project_info):
220     modules = project_info.info("MODULES")
221     files = project_info.info("FILES")
222     if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
223         harvard = True
224     else:
225         harvard = False
226     # file to be included in CSRC variable
227     csrc = []
228     # file to be included in PCSRC variable
229     pcsrc = []
230     # files to be included in CPPASRC variable
231     cppasrc = []
232     # files to be included in CXXSRC variable
233     cxxsrc = []
234     # files to be included in ASRC variable
235     asrc = []
236     # constants to be included at the beginning of the makefile
237     constants = {}
238     for module, information in modules.items():
239         module_files = set([])
240         dependency_files = set([])
241         # assembly sources
242         asm_files = set([])
243         hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
244         if information["enabled"]:
245             if "constants" in information:
246                 constants.update(information["constants"])
247             cfiles, sfiles = findModuleFiles(module, project_info)
248             module_files |= set(cfiles)
249             asm_files |= set(sfiles)
250             for file in information["hw"]:
251                 if file.endswith(".c"):
252                     module_files |= set([hwdir + "/" + os.path.basename(file)])
253             for file_dependency in information["depends"] + tuple(files.keys()):
254                     dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
255                     dependency_files |= set(dependencyCFiles)
256                     asm_files |= set(dependencySFiles)
257             for file in module_files:
258                 if not harvard or information.get("harvard", "both") == "both":
259                     csrc.append(file)
260                 if harvard and "harvard" in information:
261                     pcsrc.append(file)
262             for file in dependency_files:
263                 csrc.append(file)
264             for file in project_info.info("CPU_INFOS")["C_SRC"]:
265                 csrc.append(file)
266             for file in project_info.info("CPU_INFOS")["PC_SRC"]:
267                 pcsrc.append(file)
268             for file in asm_files:
269                 cppasrc.append(file)
270     for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
271         cppasrc.append(file)
272     for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
273         cxxsrc.append(file)
274     for file in project_info.info("CPU_INFOS")["ASRC"]:
275         asrc.append(file)
276     csrc = sorted(set(csrc))
277     csrc = " \\\n\t".join(csrc) + " \\"
278     pcsrc = sorted(set(pcsrc))
279     pcsrc = " \\\n\t".join(pcsrc) + " \\"
280     cppasrc = sorted(set(cppasrc))
281     cppasrc = " \\\n\t".join(cppasrc) + " \\"
282     cxxsrc = sorted(set(cxxsrc))
283     cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
284     asrc = sorted(set(asrc))
285     asrc = " \\\n\t".join(asrc) + " \\"
286     constants = "\n".join([project_info.info("PROJECT_NAME") + "_" + key + " = " + unicode(value) for key, value in constants.items()])
287     return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
288
289 def findModuleFiles(module, project_info):
290     # Find the files related to the selected module
291     cfiles = []
292     sfiles = []
293     # .c files related to the module and the cpu architecture
294     for filename, path in project_info.searchFiles(module + ".c"):
295         path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
296         path = replaceSeparators(path)
297         cfiles.append(path + "/" + filename)
298     # .s files related to the module and the cpu architecture
299     for filename, path in project_info.searchFiles(module + ".s") + \
300             project_info.searchFiles(module + ".S"):
301         path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
302         path = replaceSeparators(path)
303         sfiles.append(path + "/" + filename)
304     # .c and .s files related to the module and the cpu tags
305     tags = project_info.info("CPU_INFOS")["CPU_TAGS"]
306
307     # Awful, but secure check for version
308     # TODO: split me in a method/function
309     try:
310         version_string = bertosVersion(project_info.info("BERTOS_PATH"))
311         version_list = [int(i) for i in version_string.split()[1].split('.')]
312     except ValueError:
313         # If the version file hasn't a valid version number assume it's an older
314         # project.
315         version_list = [0, 0]
316     if version_list < [2, 5]:
317         # For older versions of BeRTOS add the toolchain to the tags
318         tags.append(project_info.info("CPU_INFOS")["TOOLCHAIN"])
319
320     for tag in tags:
321         for filename, path in project_info.searchFiles(module + "_" + tag + ".c"):
322             path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
323             if os.sep != "/":
324                 path = replaceSeparators(path)
325             cfiles.append(path + "/" + filename)
326         for filename, path in project_info.searchFiles(module + "_" + tag + ".s") + \
327                 project_info.searchFiles(module + "_" + tag + ".S"):
328             path = path.replace(project_info.info("BERTOS_PATH") + os.sep, "")
329             path = replaceSeparators(path)
330             sfiles.append(path + "/" + filename)
331     return cfiles, sfiles
332
333 def replaceSeparators(path):
334     """
335     Replace the separators in the given path with unix standard separator.
336     """
337     if os.sep != "/":
338         path = path.replace(os.sep, "/")
339     return path
340
341 def getSystemPath():
342     path = os.environ["PATH"]
343     path = path.split(os.pathsep)
344     return path
345
346 def findInPath(file, path=None):
347     if path is None:
348         path = os.environ.get('PATH', '')
349     if type(path) is type(''):
350         path = path.split(os.pathsep)
351     return filter(os.path.exists, map(lambda dir, file=file: os.path.join(dir, file), path))
352
353
354 def findToolchains(path_list):
355     toolchains = []
356     for element in path_list:
357         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
358             if not os.path.isdir(toolchain):
359                 toolchains.append(toolchain)
360     return list(set(toolchains))
361
362 def getToolchainInfo(output):
363     info = {}
364     expr = re.compile("Target: .*")
365     target = expr.findall(output)
366     if len(target) == 1:
367         info["target"] = target[0].split("Target: ")[1]
368     expr = re.compile("gcc version [0-9,.]*")
369     version = expr.findall(output)
370     if len(version) == 1:
371         info["version"] = version[0].split("gcc version ")[1]
372     expr = re.compile("gcc version [0-9,.]* \(.*\)")
373     build = expr.findall(output)
374     if len(build) == 1:
375         build = build[0].split("gcc version ")[1]
376         build = build[build.find("(") + 1 : build.find(")")]
377         info["build"] = build
378     expr = re.compile("Configured with: .*")
379     configured = expr.findall(output)
380     if len(configured) == 1:
381         info["configured"] = configured[0].split("Configured with: ")[1]
382     expr = re.compile("Thread model: .*")
383     thread = expr.findall(output)
384     if len(thread) == 1:
385         info["thread"] = thread[0].split("Thread model: ")[1]
386     return info
387
388 def getToolchainName(toolchain_info):
389     name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
390     return name
391
392 def getTagSet(cpu_info):
393     tag_set = set([])
394     for cpu in cpu_info:
395         tag_set |= set([cpu["CPU_NAME"]])
396         tag_set |= set(cpu["CPU_TAGS"])
397         tag_set |= set([cpu["TOOLCHAIN"]])
398     return tag_set
399
400
401 def getInfos(definition):
402     D = {}
403     D.update(const.CPU_DEF)
404     def include(filename, dict = D, directory=definition[1]):
405         execfile(directory + "/" + filename, {}, D)
406     D["include"] = include
407     include(definition[0], D)
408     D["CPU_NAME"] = definition[0].split(".")[0]
409     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
410     del D["include"]
411     return D
412
413 def getCommentList(string):
414     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
415     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
416     return comment_list
417
418 def loadModuleDefinition(first_comment):
419     to_be_parsed = False
420     module_definition = {}
421     for num, line in enumerate(first_comment):
422         index = line.find("$WIZ$")
423         if index != -1:
424             to_be_parsed = True
425             try:
426                 exec line[index + len("$WIZ$ "):] in {}, module_definition
427             except:
428                 raise ParseError(num, line[index:])
429         elif line.find("\\brief") != -1:
430             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
431     module_dict = {}
432     if "module_name" in module_definition:
433         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
434         del module_definition[const.MODULE_DEFINITION["module_name"]]
435         module_dict[module_name] = {}
436         if const.MODULE_DEFINITION["module_depends"] in module_definition:
437             depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
438             del module_definition[const.MODULE_DEFINITION["module_depends"]]
439             if type(depends) == str:
440                 depends = (depends,)
441             module_dict[module_name]["depends"] = depends
442         else:
443             module_dict[module_name]["depends"] = ()
444         if const.MODULE_DEFINITION["module_configuration"] in module_definition:
445             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
446             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
447         else:
448             module_dict[module_name]["configuration"] = ""
449         if "module_description" in module_definition:
450             module_dict[module_name]["description"] = module_definition["module_description"]
451             del module_definition["module_description"]
452         if const.MODULE_DEFINITION["module_harvard"] in module_definition:
453             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
454             module_dict[module_name]["harvard"] = harvard
455             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
456         if const.MODULE_DEFINITION["module_hw"] in module_definition:
457             hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
458             del module_definition[const.MODULE_DEFINITION["module_hw"]]
459             if type(hw) == str:
460                 hw = (hw, )
461             module_dict[module_name]["hw"] = hw
462         else:
463             module_dict[module_name]["hw"] = ()
464         if const.MODULE_DEFINITION["module_supports"] in module_definition:
465             supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
466             del module_definition[const.MODULE_DEFINITION["module_supports"]]
467             module_dict[module_name]["supports"] = supports
468         module_dict[module_name]["constants"] = module_definition
469         module_dict[module_name]["enabled"] = False
470     return to_be_parsed, module_dict
471
472 def isSupported(project, module=None, property_id=None):
473     if not module and property_id:
474         item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
475     else:
476         item = project.info("MODULES")[module]
477     tag_dict = project.info("ALL_CPU_TAGS")
478     if "supports" in item:
479         support_string = item["supports"]
480         supported = {}
481         try:
482             exec "supported = " + support_string in tag_dict, supported
483         except:
484             raise SupportedException(support_string)
485         return supported["supported"]
486     else:
487         return True
488
489 def loadDefineLists(comment_list):
490     define_list = {}
491     for comment in comment_list:
492         for num, line in enumerate(comment):
493             index = line.find("$WIZ$")
494             if index != -1:
495                 try:
496                     exec line[index + len("$WIZ$ "):] in {}, define_list
497                 except:
498                     raise ParseError(num, line[index:])
499     for key, value in define_list.items():
500         if type(value) == str:
501             define_list[key] = (value,)
502     return define_list
503
504 def getDescriptionInformations(comment):
505     """
506     Take the doxygen comment and strip the wizard informations, returning the tuple
507     (comment, wizard_information)
508     """
509     brief = ""
510     description = ""
511     information = {}
512     for num, line in enumerate(comment):
513         index = line.find("$WIZ$")
514         if index != -1:
515             if len(brief) == 0:
516                 brief += line[:index].strip()
517             else:
518                 description += " " + line[:index]
519             try:
520                 exec line[index + len("$WIZ$ "):] in {}, information
521             except:
522                 raise ParseError(num, line[index:])
523         else:
524             if len(brief) == 0:
525                 brief += line.strip()
526             else:
527                 description += " " + line
528                 description = description.strip()
529     return brief.strip(), description.strip(), information
530
531 def getDefinitionBlocks(text):
532     """
533     Take a text and return a list of tuple (description, name-value).
534     """
535     block = []
536     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
537     for match in block_tmp:
538         # Only the first element is needed
539         comment = match.group(1)
540         define = match.group(2)
541         start = match.start()
542         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
543     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
544         comment = match.group(1)
545         define = match.group(2)
546         start = match.start()
547         block.append(([comment], define, start))
548     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
549         comment = match.group(2)
550         define = match.group(1)
551         start = match.start()
552         block.append(([comment], define, start))
553     return block
554
555 def formatParamNameValue(text):
556     """
557     Take the given string and return a tuple with the name of the parameter in the first position
558     and the value in the second.
559     """
560     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
561     return block[0]
562
563 def loadConfigurationInfos(path):
564     """
565     Return the module configurations found in the given file as a dict with the
566     parameter name as key and a dict containig the fields above as value:
567         "value": the value of the parameter
568         "description": the description of the parameter
569         "informations": a dict containig optional informations:
570             "type": "int" | "boolean" | "enum"
571             "min": the minimum value for integer parameters
572             "max": the maximum value for integer parameters
573             "long": boolean indicating if the num is a long
574             "unsigned": boolean indicating if the num is an unsigned
575             "value_list": the name of the enum for enum parameters
576             "conditional_deps": the list of conditional dependencies for boolean parameters
577     """
578     configuration_infos = {}
579     configuration_infos["paramlist"] = []
580     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
581         name, value = formatParamNameValue(define)
582         brief, description, informations = getDescriptionInformations(comment)
583         configuration_infos["paramlist"].append((start, name))
584         configuration_infos[name] = {}
585         configuration_infos[name]["value"] = value
586         configuration_infos[name]["informations"] = informations
587         if not "type" in configuration_infos[name]["informations"]:
588             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
589         if ("type" in configuration_infos[name]["informations"] and
590                 configuration_infos[name]["informations"]["type"] == "int" and
591                 configuration_infos[name]["value"].find("L") != -1):
592             configuration_infos[name]["informations"]["long"] = True
593             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
594         if ("type" in configuration_infos[name]["informations"] and
595                 configuration_infos[name]["informations"]["type"] == "int" and
596                 configuration_infos[name]["value"].find("U") != -1):
597             configuration_infos[name]["informations"]["unsigned"] = True
598             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
599         if "conditional_deps" in configuration_infos[name]["informations"]:
600             if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
601                     type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
602                 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
603             elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
604                 pass
605             else:
606                 configuration_infos[name]["informations"]["conditional_deps"] = ()
607         configuration_infos[name]["description"] = description
608         configuration_infos[name]["brief"] = brief
609     return configuration_infos
610
611 def updateConfigurationValues(def_conf, user_conf):
612     for param in def_conf["paramlist"]:
613         if param[1] in user_conf and "value" in user_conf[param[1]]:
614             def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
615     return def_conf
616
617 def findParameterType(parameter):
618     if "value_list" in parameter["informations"]:
619         return "enum"
620     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
621         return "int"
622
623 def sub(string, parameter, value):
624     """
625     Substitute the given value at the given parameter define in the given string
626     """
627     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
628
629 def isInt(informations):
630     """
631     Return True if the value is a simple int.
632     """
633     if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
634         return True
635     else:
636         return False
637
638 def isLong(informations):
639     """
640     Return True if the value is a long.
641     """
642     if "long" in informations and informations["long"] and "unsigned" not in informations:
643         return True
644     else:
645         return False
646
647 def isUnsigned(informations):
648     """
649     Return True if the value is an unsigned.
650     """
651     if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
652         return True
653     else:
654         return False
655
656 def isUnsignedLong(informations):
657     """
658     Return True if the value is an unsigned long.
659     """
660     if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
661         return True
662     else:
663         return False
664
665 class ParseError(Exception):
666     def __init__(self, line_number, line):
667         Exception.__init__(self)
668         self.line_number = line_number
669         self.line = line
670
671 class SupportedException(Exception):
672     def __init__(self, support_string):
673         Exception.__init__(self)
674         self.support_string = support_string