Add the prefix and the suffix for the selected toolchain
[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     mkData["$prefix"] = os.path.basename(projectInfo.info("TOOLCHAIN")["path"]).split("gcc")[0]
82     mkData["$suffix"] = os.path.basename(projectInfo.info("TOOLCHAIN")["path"]).split("gcc")[1]
83     for key in mkData:
84         while makefile.find(key) != -1:
85             makefile = makefile.replace(key, mkData[key])
86     return makefile
87
88 def makefileGenerator(projectInfo, makefile):
89     """
90     Generate the Makefile for the current project.
91     """
92     # TODO: write a general function that works for both the mk file and the Makefile
93     while makefile.find("project_name") != -1:
94         makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
95     return makefile
96
97 def csrcGenerator(projectInfo):
98     modules = projectInfo.info("MODULES")
99     files = []
100     for module, information in modules.items():
101         if information["enabled"]:
102             for filename, path in findDefinitions(module + ".c", projectInfo):
103                 files.append(path + "/" + filename)
104             for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
105                 files.append(path + "/" + filename)
106             for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
107                 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
108                     files.append(path + "/" + filename)
109     csrc = " \\\n\t".join(files)
110     return csrc
111     
112 def getSystemPath():
113     path = os.environ["PATH"]
114     if os.name == "nt":
115         path = path.split(";")
116     else:
117         path = path.split(":")
118     return path
119
120 def findToolchains(pathList):
121     toolchains = []
122     for element in pathList:
123         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
124             toolchains.append(toolchain)
125     return list(set(toolchains))
126
127 def getToolchainInfo(output):
128     info = {}
129     expr = re.compile("Target: .*")
130     target = expr.findall(output)
131     if len(target) == 1:
132         info["target"] = target[0].split("Target: ")[1]
133     expr = re.compile("gcc version [0-9,.]*")
134     version = expr.findall(output)
135     if len(version) == 1:
136         info["version"] = version[0].split("gcc version ")[1]
137     expr = re.compile("gcc version [0-9,.]* \(.*\)")
138     build = expr.findall(output)
139     if len(build) == 1:
140         build = build[0].split("gcc version ")[1]
141         build = build[build.find("(") + 1 : build.find(")")]
142         info["build"] = build
143     expr = re.compile("Configured with: .*")
144     configured = expr.findall(output)
145     if len(configured) == 1:
146         info["configured"] = configured[0].split("Configured with: ")[1]
147     expr = re.compile("Thread model: .*")
148     thread = expr.findall(output)
149     if len(thread) == 1:
150         info["thread"] = thread[0].split("Thread model: ")[1]
151     return info
152
153 def loadSourceTree(project):
154     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
155     project.setInfo("FILE_LIST", fileList)
156
157 def findDefinitions(ftype, project):
158     L = project.info("FILE_LIST")
159     definitions = []
160     for element in L:
161         for filename in element[2]:
162             if fnmatch.fnmatch(filename, ftype):
163                 definitions.append((filename, element[0]))
164     return definitions
165
166 def loadCpuInfos(project):
167     cpuInfos = []
168     for definition in findDefinitions(const.CPU_DEFINITION, project):
169         cpuInfos.append(getInfos(definition))
170     return cpuInfos
171
172 def getInfos(definition):
173     D = {}
174     D.update(const.CPU_DEF)
175     def include(filename, dict = D, directory=definition[1]):
176         execfile(directory + "/" + filename, {}, D)
177     D["include"] = include
178     include(definition[0], D)
179     D["CPU_NAME"] = definition[0].split(".")[0]
180     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
181     del D["include"]
182     return D
183
184 def getCommentList(string):
185     commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
186     commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
187     return commentList
188
189 def loadModuleDefinition(first_comment):
190     toBeParsed = False
191     moduleDefinition = {}
192     for num, line in enumerate(first_comment):
193         index = line.find("$WIZ$")
194         if index != -1:
195             toBeParsed = True
196             try:
197                 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
198             except:
199                 raise ParseError(num, line[index:])
200         elif line.find("\\brief") != -1:
201             moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
202     moduleDict = {}
203     if "module_name" in moduleDefinition.keys():
204         moduleDict[moduleDefinition["module_name"]] = {}
205         if "module_depends" in moduleDefinition.keys():
206             if type(moduleDefinition["module_depends"]) == str:
207                 moduleDefinition["module_depends"] = (moduleDefinition["module_depends"],)
208             moduleDict[moduleDefinition["module_name"]]["depends"] = moduleDefinition["module_depends"]
209         else:
210             moduleDict[moduleDefinition["module_name"]]["depends"] = ()
211         if "module_configuration" in moduleDefinition.keys():
212             moduleDict[moduleDefinition["module_name"]]["configuration"] = moduleDefinition["module_configuration"]
213         else:
214             moduleDict[moduleDefinition["module_name"]]["configuration"] = ""
215         if "module_description" in moduleDefinition.keys():
216             moduleDict[moduleDefinition["module_name"]]["description"] = moduleDefinition["module_description"]
217         moduleDict[moduleDefinition["module_name"]]["enabled"] = False
218     return toBeParsed, moduleDict
219
220 def loadDefineLists(commentList):
221     defineList = {}
222     for comment in commentList:
223         for num, line in enumerate(comment):
224             index = line.find("$WIZ$")
225             if index != -1:
226                 try:
227                     exec line[index + len("$WIZ$ "):] in {}, defineList
228                 except:
229                     raise ParseError(num, line[index:])
230     for key, value in defineList.items():
231         if type(value) == str:
232             defineList[key] = (value,)
233     return defineList
234
235 def getDescriptionInformations(comment): 
236     """ 
237     Take the doxygen comment and strip the wizard informations, returning the tuple 
238     (comment, wizard_information) 
239     """
240     brief = ""
241     description = ""
242     information = {}
243     for num, line in enumerate(comment):
244         index = line.find("$WIZ$")
245         if index != -1:
246             if len(brief) == 0:
247                 brief += line[:index].strip()
248             else:
249                 description += " " + line[:index]
250             try:
251                 exec line[index + len("$WIZ$ "):] in {}, information
252             except:
253                 raise ParseError(num, line[index:])
254         else:
255             if len(brief) == 0:
256                 brief += line.strip()
257             else:
258                 description += " " + line
259                 description = description.strip()
260     return brief.strip(), description.strip(), information
261
262 def getDefinitionBlocks(text):
263     """
264     Take a text and return a list of tuple (description, name-value).
265     """
266     block = []
267     block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
268     for comment, define in block_tmp:
269         # Only the first element is needed
270         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
271     for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
272         block.append(([comment], define))
273     for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
274         block.append(([comment], define))
275     return block
276
277 def loadModuleData(project):
278     moduleInfoDict = {}
279     listInfoDict = {}
280     configurationInfoDict = {}
281     for filename, path in findDefinitions("*.h", project):
282         commentList = getCommentList(open(path + "/" + filename, "r").read())
283         if len(commentList) > 0:
284             moduleInfo = {}
285             configurationInfo = {}
286             try:
287                 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
288             except ParseError, err:
289                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
290             for module, information in moduleDict.items():
291                 information["category"] = os.path.basename(path)
292                 if "configuration" in information.keys() and len(information["configuration"]):
293                     configuration = moduleDict[module]["configuration"]
294                     try:
295                         configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
296                     except ParseError, err:
297                         raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
298             moduleInfoDict.update(moduleDict)
299             configurationInfoDict.update(configurationInfo)
300             if toBeParsed:
301                 try:
302                     listDict = loadDefineLists(commentList[1:])
303                     listInfoDict.update(listDict)
304                 except ParseError, err:
305                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
306     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
307         commentList = getCommentList(open(path + "/" + filename, "r").read())
308         listInfoDict.update(loadDefineLists(commentList))
309     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
310         for filename, path in findDefinitions("*_" + tag + ".h", project):
311             commentList = getCommentList(open(path + "/" + filename, "r").read())
312             listInfoDict.update(loadDefineLists(commentList))
313     project.setInfo("MODULES", moduleInfoDict)
314     project.setInfo("LISTS", listInfoDict)
315     project.setInfo("CONFIGURATIONS", configurationInfoDict)
316     
317 def formatParamNameValue(text):
318     """
319     Take the given string and return a tuple with the name of the parameter in the first position
320     and the value in the second.
321     """
322     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
323     return block[0]
324
325 def loadConfigurationInfos(path):
326     """
327     Return the module configurations found in the given file as a dict with the
328     parameter name as key and a dict containig the fields above as value:
329         "value": the value of the parameter
330         "description": the description of the parameter
331         "informations": a dict containig optional informations:
332             "type": "int" | "boolean" | "enum"
333             "min": the minimum value for integer parameters
334             "max": the maximum value for integer parameters
335             "long": boolean indicating if the num is a long
336             "value_list": the name of the enum for enum parameters
337     """
338     configurationInfos = {}
339     for comment, define in getDefinitionBlocks(open(path, "r").read()):
340         name, value = formatParamNameValue(define)
341         brief, description, informations = getDescriptionInformations(comment)
342         configurationInfos[name] = {}
343         configurationInfos[name]["value"] = value
344         configurationInfos[name]["informations"] = informations
345         if ("type" in configurationInfos[name]["informations"].keys() and
346                 configurationInfos[name]["informations"]["type"] == "int" and
347                 configurationInfos[name]["value"].find("L") != -1):
348             configurationInfos[name]["informations"]["long"] = True
349             configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
350         if ("type" in configurationInfos[name]["informations"].keys() and
351                 configurationInfos[name]["informations"]["type"] == "int" and
352                 configurationInfos[name]["value"].find("U") != -1):
353             configurationInfos[name]["informations"]["unsigned"] = True
354             configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
355         configurationInfos[name]["description"] = description
356         configurationInfos[name]["brief"] = brief
357     return configurationInfos
358
359 def sub(string, parameter, value):
360     """
361     Substitute the given value at the given parameter define in the given string
362     """
363     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
364
365 def isInt(informations):
366     """
367     Return True if the value is a simple int.
368     """
369     if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
370         return True
371     else:
372         return False
373
374 def isLong(informations):
375     """
376     Return True if the value is a long.
377     """
378     if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
379         return True
380     else:
381         return False
382
383 def isUnsigned(informations):
384     """
385     Return True if the value is an unsigned.
386     """
387     if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
388         return True
389     else:
390         return False
391
392 def isUnsignedLong(informations):
393     """
394     Return True if the value is an unsigned long.
395     """
396     if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
397         return True
398     else:
399         return False
400
401 class ParseError(Exception):
402     def __init__(self, line_number, line):
403         Exception.__init__(self)
404         self.line_number = line_number
405         self.line = line