Add the brief founded with the autobrief doxygen syntax
[bertos.git] / wizard / bertos_utils.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
5 # All rights reserved.
6 #
7 # $Id:$
8 #
9 # Author: Lorenzo Berni <duplo@develer.com>
10 #
11
12 import os
13 import fnmatch
14 import glob
15 import re
16 import shutil
17
18 import const
19 import DefineException
20
21 def isBertosDir(directory):
22    return os.path.exists(directory + "/VERSION")
23
24 def bertosVersion(directory):
25    return open(directory + "/VERSION").readline().strip()
26
27 def createBertosProject(projectInfo):
28     directory = projectInfo.info("PROJECT_PATH")
29     sourcesDir = projectInfo.info("SOURCES_PATH")
30     if not os.path.isdir(directory):
31         os.mkdir(directory)
32     f = open(directory + "/project.bertos", "w")
33     f.write(repr(projectInfo))
34     f.close()
35     ## Destination source dir
36     srcdir = directory + "/bertos"
37     shutil.rmtree(srcdir, True)
38     shutil.copytree(sourcesDir + "/bertos", srcdir)
39     ## Destination makefile
40     makefile = directory + "/Makefile"
41     if os.path.exists(makefile):
42         os.remove(makefile)
43     makefile = open("mktemplates/Makefile").read()
44     makefile = makefileGenerator(projectInfo, makefile)
45     open(directory + "/Makefile", "w").write(makefile)
46     ## Destination project dir
47     prjdir = directory + "/" + os.path.basename(directory)
48     shutil.rmtree(prjdir, True)
49     os.mkdir(prjdir)
50     ## Destination configurations files
51     cfgdir = prjdir + "/cfg"
52     shutil.rmtree(cfgdir, True)
53     os.mkdir(cfgdir)
54     for key, value in projectInfo.info("CONFIGURATIONS").items():
55         string = open(sourcesDir + "/" + key, "r").read()
56         for parameter, infos in value.items():
57             value = infos["value"]
58             if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
59                 value += "U"
60             if "long" in infos["informations"].keys() and infos["informations"]["long"]:
61                 value += "L"
62             string = sub(string, parameter, value)
63         f = open(cfgdir + "/" + os.path.basename(key), "w")
64         f.write(string)
65         f.close()
66     ## Destinatio mk file
67     makefile = open("mktemplates/template.mk", "r").read()
68     makefile = mkGenerator(projectInfo, makefile)
69     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
70
71 def mkGenerator(projectInfo, makefile):
72     """
73     Generates the mk file for the current project.
74     """
75     mkData = {}
76     mkData["$pname"] = os.path.basename(projectInfo.info("PROJECT_PATH"))
77     mkData["$cpuname"] = projectInfo.info("CPU_INFOS")["CPU_NAME"]
78     mkData["$cflags"] = " ".join(projectInfo.info("CPU_INFOS")["C_FLAGS"])
79     mkData["$ldflags"] = " ".join(projectInfo.info("CPU_INFOS")["LD_FLAGS"])
80     mkData["$csrc"] = csrcGenerator(projectInfo)
81     for key in mkData:
82         while makefile.find(key) != -1:
83             makefile = makefile.replace(key, mkData[key])
84     return makefile
85
86 def makefileGenerator(projectInfo, makefile):
87     """
88     Generate the Makefile for the current project.
89     """
90     # TODO: write a general function that works for both the mk file and the Makefile
91     while makefile.find("project_name") != -1:
92         makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
93     return makefile
94
95 def csrcGenerator(projectInfo):
96     modules = projectInfo.info("MODULES")
97     files = []
98     for module, information in modules.items():
99         if information["enabled"]:
100             for filename, path in findDefinitions(module + ".c", projectInfo):
101                 files.append(path + "/" + filename)
102             for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
103                 files.append(path + "/" + filename)
104             for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
105                 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
106                     files.append(path + "/" + filename)
107     csrc = " \\\n\t".join(files)
108     return csrc
109     
110 def getSystemPath():
111     path = os.environ["PATH"]
112     if os.name == "nt":
113         path = path.split(";")
114     else:
115         path = path.split(":")
116     return path
117
118 def findToolchains(pathList):
119     toolchains = []
120     for element in pathList:
121         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
122             if not os.path.islink(toolchain):
123                 toolchains.append(toolchain)
124     return list(set(toolchains))
125
126 def getToolchainInfo(output):
127     info = {}
128     expr = re.compile("Target: .*")
129     target = expr.findall(output)
130     if len(target) == 1:
131         info["target"] = target[0].split("Target: ")[1]
132     expr = re.compile("gcc version [0-9,.]*")
133     version = expr.findall(output)
134     if len(version) == 1:
135         info["version"] = version[0].split("gcc version ")[1]
136     expr = re.compile("gcc version [0-9,.]* \(.*\)")
137     build = expr.findall(output)
138     if len(build) == 1:
139         build = build[0].split("gcc version ")[1]
140         build = build[build.find("(") + 1 : build.find(")")]
141         info["build"] = build
142     expr = re.compile("Configured with: .*")
143     configured = expr.findall(output)
144     if len(configured) == 1:
145         info["configured"] = configured[0].split("Configured with: ")[1]
146     expr = re.compile("Thread model: .*")
147     thread = expr.findall(output)
148     if len(thread) == 1:
149         info["thread"] = thread[0].split("Thread model: ")[1]
150     return info
151
152 def loadSourceTree(project):
153     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
154     project.setInfo("FILE_LIST", fileList)
155
156 def findDefinitions(ftype, project):
157     L = project.info("FILE_LIST")
158     definitions = []
159     for element in L:
160         for filename in element[2]:
161             if fnmatch.fnmatch(filename, ftype):
162                 definitions.append((filename, element[0]))
163     return definitions
164
165 def loadCpuInfos(project):
166     cpuInfos = []
167     for definition in findDefinitions(const.CPU_DEFINITION, project):
168         cpuInfos.append(getInfos(definition))
169     return cpuInfos
170
171 def getInfos(definition):
172     D = {}
173     D.update(const.CPU_DEF)
174     def include(filename, dict = D, directory=definition[1]):
175         execfile(directory + "/" + filename, {}, D)
176     D["include"] = include
177     include(definition[0], D)
178     D["CPU_NAME"] = definition[0].split(".")[0]
179     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
180     del D["include"]
181     return D
182
183 def getCommentList(string):
184     commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
185     commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
186     return commentList
187
188 def loadModuleDefinition(first_comment):
189     toBeParsed = False
190     moduleDefinition = {}
191     for num, line in enumerate(first_comment):
192         index = line.find("$WIZ$")
193         if index != -1:
194             toBeParsed = True
195             try:
196                 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
197             except:
198                 raise ParseError(num, line[index:])
199         elif line.find("\\brief") != -1:
200             moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
201     moduleDict = {}
202     if "module_name" in moduleDefinition.keys():
203         moduleDict[moduleDefinition["module_name"]] = {}
204         if "module_depends" in moduleDefinition.keys():
205             if type(moduleDefinition["module_depends"]) == str:
206                 moduleDefinition["module_depends"] = (moduleDefinition["module_depends"],)
207             moduleDict[moduleDefinition["module_name"]]["depends"] = moduleDefinition["module_depends"]
208         else:
209             moduleDict[moduleDefinition["module_name"]]["depends"] = ()
210         if "module_configuration" in moduleDefinition.keys():
211             moduleDict[moduleDefinition["module_name"]]["configuration"] = moduleDefinition["module_configuration"]
212         else:
213             moduleDict[moduleDefinition["module_name"]]["configuration"] = ""
214         if "module_description" in moduleDefinition.keys():
215             moduleDict[moduleDefinition["module_name"]]["description"] = moduleDefinition["module_description"]
216         moduleDict[moduleDefinition["module_name"]]["enabled"] = False
217     return toBeParsed, moduleDict
218
219 def loadDefineLists(commentList):
220     defineList = {}
221     for comment in commentList:
222         for num, line in enumerate(comment):
223             index = line.find("$WIZ$")
224             if index != -1:
225                 try:
226                     exec line[index + len("$WIZ$ "):] in {}, defineList
227                 except:
228                     raise ParseError(num, line[index:])
229     for key, value in defineList.items():
230         if type(value) == str:
231             defineList[key] = (value,)
232     return defineList
233
234 def getDescriptionInformations(comment): 
235     """ 
236     Take the doxygen comment and strip the wizard informations, returning the tuple 
237     (comment, wizard_information) 
238     """
239     brief = ""
240     description = ""
241     information = {}
242     for num, line in enumerate(comment):
243         index = line.find("$WIZ$")
244         if index != -1:
245             if len(brief) == 0:
246                 brief += line[:index].strip()
247             else:
248                 description += " " + line[:index]
249             try:
250                 exec line[index + len("$WIZ$ "):] in {}, information
251             except:
252                 raise ParseError(num, line[index:])
253         else:
254             if len(brief) == 0:
255                 brief += line.strip()
256             else:
257                 description += " " + line
258                 description = description.strip()
259     return brief.strip(), description.strip(), information
260
261 def getDefinitionBlocks(text):
262     """
263     Take a text and return a list of tuple (description, name-value).
264     """
265     block = []
266     block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
267     for comment, define in block_tmp:
268         # Only the first element is needed
269         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
270     for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
271         block.append(([comment], define))
272     for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
273         block.append(([comment], define))
274     return block
275
276 def loadModuleData(project):
277     moduleInfoDict = {}
278     listInfoDict = {}
279     configurationInfoDict = {}
280     for filename, path in findDefinitions("*.h", project):
281         commentList = getCommentList(open(path + "/" + filename, "r").read())
282         if len(commentList) > 0:
283             moduleInfo = {}
284             configurationInfo = {}
285             try:
286                 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
287             except ParseError, err:
288                 print "error in file %s. line: %d - statement %s" % (path + "/" + filename, err.line_number, err.line)
289                 print err.args
290                 print err.message
291                 raise Exception
292             for module, information in moduleDict.items():
293                 if "configuration" in information.keys() and len(information["configuration"]):
294                     configuration = moduleDict[module]["configuration"]
295                     configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
296             moduleInfoDict.update(moduleDict)
297             configurationInfoDict.update(configurationInfo)
298             if toBeParsed:
299                 try:
300                     listDict = loadDefineLists(commentList[1:])
301                     listInfoDict.update(listDict)
302                 except ParseError, err:
303                     print "error in file %s. line: %d - statement %s" % (path + "/" + filename, err.line_number, err.line)
304                     print err.args
305                     print err.message
306                     raise Exception
307     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
308         commentList = getCommentList(open(path + "/" + filename, "r").read())
309         listInfoDict.update(loadDefineLists(commentList))
310     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
311         for filename, path in findDefinitions("*_" + tag + ".h", project):
312             commentList = getCommentList(open(path + "/" + filename, "r").read())
313             listInfoDict.update(loadDefineLists(commentList))
314     project.setInfo("MODULES", moduleInfoDict)
315     project.setInfo("LISTS", listInfoDict)
316     project.setInfo("CONFIGURATIONS", configurationInfoDict)
317     
318 def formatParamNameValue(text):
319     """
320     Take the given string and return a tuple with the name of the parameter in the first position
321     and the value in the second.
322     """
323     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
324     return block[0]
325
326 def loadConfigurationInfos(path):
327     """
328     Return the module configurations found in the given file as a dict with the
329     parameter name as key and a dict containig the fields above as value:
330         "value": the value of the parameter
331         "description": the description of the parameter
332         "informations": a dict containig optional informations:
333             "type": "int" | "boolean" | "enum"
334             "min": the minimum value for integer parameters
335             "max": the maximum value for integer parameters
336             "long": boolean indicating if the num is a long
337             "value_list": the name of the enum for enum parameters
338     """
339     try:
340         configurationInfos = {}
341         for comment, define in getDefinitionBlocks(open(path, "r").read()):
342             name, value = formatParamNameValue(define)
343             brief, description, informations = getDescriptionInformations(comment)
344             configurationInfos[name] = {}
345             configurationInfos[name]["value"] = value
346             configurationInfos[name]["informations"] = informations
347             if ("type" in configurationInfos[name]["informations"].keys() and
348                     configurationInfos[name]["informations"]["type"] == "int" and
349                     configurationInfos[name]["value"].find("L") != -1):
350                 configurationInfos[name]["informations"]["long"] = True
351                 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
352             if ("type" in configurationInfos[name]["informations"].keys() and
353                     configurationInfos[name]["informations"]["type"] == "int" and
354                     configurationInfos[name]["value"].find("U") != -1):
355                 configurationInfos[name]["informations"]["unsigned"] = True
356                 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
357             configurationInfos[name]["description"] = description
358             configurationInfos[name]["brief"] = brief
359         return configurationInfos
360     except ParseError, err:
361         print "error in file %s. line: %d - statement %s" % (path, err.line_number, err.line)
362         print err.args
363         print err.message
364         raise Exception
365
366 def sub(string, parameter, value):
367     """
368     Substitute the given value at the given parameter define in the given string
369     """
370     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
371
372 def isInt(informations):
373     """
374     Return True if the value is a simple int.
375     """
376     if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
377         return True
378     else:
379         return False
380
381 def isLong(informations):
382     """
383     Return True if the value is a long.
384     """
385     if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
386         return True
387     else:
388         return False
389
390 def isUnsigned(informations):
391     """
392     Return True if the value is an unsigned.
393     """
394     if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
395         return True
396     else:
397         return False
398
399 def isUnsignedLong(informations):
400     """
401     Return True if the value is an unsigned long.
402     """
403     if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
404         return True
405     else:
406         return False
407
408 class ParseError(Exception):
409     def __init__(self, line_number, line):
410         Exception.__init__(self)
411         self.line_number = line_number
412         self.line = line