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