Make smarter the selection of the header to parse
[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(projectInfos):
28     directory = projectInfos.info("PROJECT_PATH")
29     sourcesDir = projectInfos.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(projectInfos))
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(projectInfos, 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 projectInfos.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(projectInfos, makefile)
69     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
70
71 def mkGenerator(projectInfos, makefile):
72     """
73     Generates the mk file for the current project.
74     """
75     mkData = {}
76     mkData["pname"] = os.path.basename(projectInfos.info("PROJECT_PATH"))
77     mkData["cpuname"] = projectInfos.info("CPU_INFOS")["CPU_NAME"]
78     mkData["cflags"] = " ".join(projectInfos.info("CPU_INFOS")["C_FLAGS"])
79     mkData["ldflags"] = " ".join(projectInfos.info("CPU_INFOS")["LD_FLAGS"])
80     for key in mkData:
81         while makefile.find(key) != -1:
82             makefile = makefile.replace(key, mkData[key])
83     return makefile
84
85 def makefileGenerator(projectInfos, makefile):
86     """
87     Generate the Makefile for the current project.
88     """
89     # TODO: write a general function that works for both the mk file and the Makefile
90     while makefile.find("project_name") != -1:
91         makefile = makefile.replace("project_name", os.path.basename(projectInfos.info("PROJECT_PATH")))
92     return makefile
93
94 def getSystemPath():
95     path = os.environ["PATH"]
96     if os.name == "nt":
97         path = path.split(";")
98     else:
99         path = path.split(":")
100     return path
101
102 def findToolchains(pathList):
103     toolchains = []
104     for element in pathList:
105         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
106             if not os.path.islink(toolchain):
107                 toolchains.append(toolchain)
108     return list(set(toolchains))
109
110 def getToolchainInfo(output):
111     info = {}
112     expr = re.compile("Target: .*")
113     target = expr.findall(output)
114     if len(target) == 1:
115         info["target"] = target[0].split("Target: ")[1]
116     expr = re.compile("gcc version [0-9,.]*")
117     version = expr.findall(output)
118     if len(version) == 1:
119         info["version"] = version[0].split("gcc version ")[1]
120     expr = re.compile("gcc version [0-9,.]* \(.*\)")
121     build = expr.findall(output)
122     if len(build) == 1:
123         build = build[0].split("gcc version ")[1]
124         build = build[build.find("(") + 1 : build.find(")")]
125         info["build"] = build
126     expr = re.compile("Configured with: .*")
127     configured = expr.findall(output)
128     if len(configured) == 1:
129         info["configured"] = configured[0].split("Configured with: ")[1]
130     expr = re.compile("Thread model: .*")
131     thread = expr.findall(output)
132     if len(thread) == 1:
133         info["thread"] = thread[0].split("Thread model: ")[1]
134     return info
135
136 def loadSourceTree(project):
137     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
138     project.setInfo("FILE_LIST", fileList)
139
140 def findDefinitions(ftype, project):
141     L = project.info("FILE_LIST")
142     definitions = []
143     for element in L:
144         for filename in element[2]:
145             if fnmatch.fnmatch(filename, ftype):
146                 definitions.append((filename, element[0]))
147     return definitions
148
149 def loadCpuInfos(project):
150     cpuInfos = []
151     for definition in findDefinitions(const.CPU_DEFINITION, project):
152         cpuInfos.append(getInfos(definition))
153     return cpuInfos
154
155 def getInfos(definition):
156     D = {}
157     D.update(const.CPU_DEF)
158     def include(filename, dict = D, directory=definition[1]):
159         execfile(directory + "/" + filename, {}, D)
160     D["include"] = include
161     include(definition[0], D)
162     D["CPU_NAME"] = definition[0].split(".")[0]
163     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
164     del D["include"]
165     return D
166
167 def loadModuleData(project):
168     moduleInfosDict = {}
169     listInfosDict = {}
170     configurationsInfoDict = {}
171     for filename, path in findDefinitions("*.h", project):
172         moduleInfos, listInfos, configurationInfos= loadModuleInfos(path + "/" + filename)
173         moduleInfosDict.update(moduleInfos)
174         listInfosDict.update(listInfos)
175         for configuration in configurationInfos.keys():
176             configurationsInfoDict[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
177     print "*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h"
178     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
179         listInfosDict.update(loadDefineLists(path + "/" + filename))
180     project.setInfo("MODULES", moduleInfosDict)
181     project.setInfo("LISTS", listInfosDict)
182     project.setInfo("CONFIGURATIONS", configurationsInfoDict)
183
184 def getDefinitionBlocks(text):
185     """
186     Take a text and return a list of tuple (description, name-value).
187     """
188     block = []
189     block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
190     for comment, define in block_tmp:
191         block.append((" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip(), define))
192     block += re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
193     block += [(comment, define) for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)]
194     return block
195
196 def formatParamNameValue(text):
197     """
198     Take the given string and return a tuple with the name of the parameter in the first position
199     and the value in the second.
200     """
201     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
202     return block[0]
203
204 def getDescriptionInformations(text): 
205     """ 
206     Take the doxygen comment and strip the wizard informations, returning the tuple 
207     (comment, wizard_informations) 
208     """ 
209     index = text.find("$WIZARD") 
210     if index != -1: 
211         exec(text[index + 1:]) 
212         informations = WIZARD 
213         return text[:index].strip(), informations
214     else:
215         return text.strip(), {}
216
217 def loadConfigurationInfos(path):
218     """
219     Return the module configurations found in the given file as a dict with the
220     parameter name as key and a dict containig the fields above as value:
221         "value": the value of the parameter
222         "description": the description of the parameter
223         "informations": a dict containig optional informations:
224             "type": "int" | "boolean" | "enum"
225             "min": the minimum value for integer parameters
226             "max": the maximum value for integer parameters
227             "long": boolean indicating if the num is a long
228             "value_list": the name of the enum for enum parameters
229     """
230     try:
231         configurationInfos = {}
232         for comment, define in getDefinitionBlocks(open(path, "r").read()):
233             name, value = formatParamNameValue(define)
234             description, informations = getDescriptionInformations(comment)
235             configurationInfos[name] = {}
236             configurationInfos[name]["value"] = value
237             configurationInfos[name]["informations"] = informations
238             if ("type" in configurationInfos[name]["informations"].keys() and
239                     configurationInfos[name]["informations"]["type"] == "int" and
240                     configurationInfos[name]["value"].find("L") != -1):
241                 configurationInfos[name]["informations"]["long"] = True
242                 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
243             if ("type" in configurationInfos[name]["informations"].keys() and
244                     configurationInfos[name]["informations"]["type"] == "int" and
245                     configurationInfos[name]["value"].find("U") != -1):
246                 configurationInfos[name]["informations"]["unsigned"] = True
247                 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
248             configurationInfos[name]["description"] = description
249         return configurationInfos
250     except SyntaxError:
251         raise DefineException.ConfigurationDefineException(path, name)
252
253 def loadConfigurationInfosDict(project):
254     """
255     Store in the project the configuration infos as a dict.
256     """
257     modules = project.info("MODULES")
258     configurations = {}
259     for module, informations in modules.items():
260         if len(informations["configuration"]) > 0:
261             configurations[informations["configuration"]] = loadConfigurationInfos(project.info("SOURCES_PATH") +
262                                                                                     "/" + informations["configuration"])
263     project.setInfo("CONFIGURATIONS", configurations)
264
265 def loadModuleInfos(path):
266     """
267     Return the module infos found in the given file as a dict with the module
268     name as key and a dict containig the fields above as value or an empty dict
269     if the given file is not a BeRTOS module:
270         "depends": a list of modules needed by this module
271         "configuration": the cfg_*.h with the module configurations
272         "description": a string containing the brief description of doxygen
273         "enabled": contains False but the wizard will change if the user select
274         the module
275     """
276     try:
277         moduleInfos = {}
278         listInfos = {}
279         configurationsInfos = {}
280         string = open(path, "r").read()
281         commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
282         commentList = [" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip() for comment in commentList]
283         if len(commentList) > 0:
284             comment = commentList[0]
285             if comment.find("$WIZARD_MODULE") != -1:
286                 index = comment.find("$WIZARD_MODULE")
287                 if index != -1:
288                     # 14 is the length of "$WIZARD_MODULE"
289                     if len(comment[index + 14:].strip()) > 0:
290                         exec(comment[index + 1:])
291                         moduleInfos[WIZARD_MODULE["name"]] = {"depends": WIZARD_MODULE["depends"],
292                                                                 "configuration": WIZARD_MODULE["configuration"],
293                                                                 "description": "",
294                                                                 "enabled": False}
295                         index = comment.find("\\brief")
296                         if index != -1:
297                             description = comment[index + 7:]
298                             description = description[:description.find(" * ")]
299                             moduleInfos[WIZARD_MODULE["name"]]["description"] = description
300                         if "configuration" in WIZARD_MODULE.keys() and len(WIZARD_MODULE["configuration"]) > 0:
301                             configurationsInfos[WIZARD_MODULE["configuration"]] = {}
302                     listInfos.update(loadDefineLists(path))
303         return moduleInfos, listInfos, configurationsInfos
304     except SyntaxError:
305         raise DefineException.ModuleDefineException(path)
306
307 def loadModuleInfosDict(project):
308     """
309     Store in the project the dict containig all the modules
310     """
311     moduleInfosDict = {}
312     for filename, path in findDefinitions("*.h", project):
313         moduleInfosDict.update(loadModuleInfos(path + "/" + filename))
314     project.setInfo("MODULES", moduleInfosDict)
315
316 def loadDefineLists(path):
317     """
318     Return a dict with the name of the list as key and a list of string as value
319     """
320     try:
321         string = open(path, "r").read()
322         commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
323         commentList = [" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip() for comment in commentList]
324         listDict = {}
325         for comment in commentList:
326             index = comment.find("$WIZARD_LIST")
327             if index != -1:
328                 exec(comment[index + 1:])
329                 listDict.update(WIZARD_LIST)
330         return listDict
331     except SyntaxError:
332         raise DefineException.EnumDefineException(path)
333
334 def loadDefineListsDict(project):
335     """
336     Store in the project the dict containing all the define lists
337     """
338     defineListsDict = {}
339     for filename, path in findDefinitions("*.h", project):
340         defineListsDict.update(loadDefineLists(path + "/" + filename))
341     lists = project.info("LISTS")
342     if lists is not None:
343         defineListsDict.update(lists)
344     project.setInfo("LISTS", defineListsDict)
345
346 def sub(string, parameter, value):
347     """
348     Substitute the given value at the given parameter define in the given string
349     """
350     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
351
352 def isInt(informations):
353     """
354     Return True if the value is a simple int.
355     """
356     if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
357         return True
358     else:
359         return False
360
361 def isLong(informations):
362     """
363     Return True if the value is a long.
364     """
365     if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
366         return True
367     else:
368         return False
369
370 def isUnsigned(informations):
371     """
372     Return True if the value is an unsigned.
373     """
374     if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
375         return True
376     else:
377         return False
378
379 def isUnsignedLong(informations):
380     """
381     Return True if the value is an unsigned long.
382     """
383     if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
384         return True
385     else:
386         return False