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