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