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