Add the new parsing exception infrastructure
[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(projectInfos):
28     directory = projectInfos.info("PROJECT_PATH")
29     sourcesDir = projectInfos.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(projectInfos))
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(projectInfos, 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 projectInfos.info("CONFIGURATIONS").items():
55         string = open(sourcesDir + "/" + key, "r").read()
56         for parameter, infos in value.items():
57             value = infos["value"]
58             if "long" in infos["informations"].keys() and infos["informations"]["long"]:
59                 value += "L"
60             string = sub(string, parameter, value)
61         f = open(cfgdir + "/" + os.path.basename(key), "w")
62         f.write(string)
63         f.close()
64     ## Destinatio mk file
65     makefile = open("mktemplates/template.mk", "r").read()
66     makefile = mkGenerator(projectInfos, makefile)
67     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
68
69 def mkGenerator(projectInfos, makefile):
70     """
71     Generates the mk file for the current project.
72     """
73     mkData = {}
74     mkData["pname"] = os.path.basename(projectInfos.info("PROJECT_PATH"))
75     mkData["cpuname"] = projectInfos.info("CPU_INFOS")["CPU_NAME"]
76     mkData["cflags"] = " ".join(projectInfos.info("CPU_INFOS")["C_FLAGS"])
77     mkData["ldflags"] = " ".join(projectInfos.info("CPU_INFOS")["LD_FLAGS"])
78     for key in mkData:
79         while makefile.find(key) != -1:
80             makefile = makefile.replace(key, mkData[key])
81     return makefile
82
83 def makefileGenerator(projectInfos, makefile):
84     """
85     Generate the Makefile for the current project.
86     """
87     # TODO: write a general function that works for both the mk file and the Makefile
88     while makefile.find("project_name") != -1:
89         makefile = makefile.replace("project_name", os.path.basename(projectInfos.info("PROJECT_PATH")))
90     return makefile
91
92 def getSystemPath():
93     path = os.environ["PATH"]
94     if os.name == "nt":
95         path = path.split(";")
96     else:
97         path = path.split(":")
98     return path
99
100 def findToolchains(pathList):
101     toolchains = []
102     for element in pathList:
103         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
104             if not os.path.islink(toolchain):
105                 toolchains.append(toolchain)
106     return list(set(toolchains))
107
108 def getToolchainInfo(output):
109     info = {}
110     expr = re.compile("Target: .*")
111     target = expr.findall(output)
112     if len(target) == 1:
113         info["target"] = target[0].split("Target: ")[1]
114     expr = re.compile("gcc version [0-9,.]*")
115     version = expr.findall(output)
116     if len(version) == 1:
117         info["version"] = version[0].split("gcc version ")[1]
118     expr = re.compile("gcc version [0-9,.]* \(.*\)")
119     build = expr.findall(output)
120     if len(build) == 1:
121         build = build[0].split("gcc version ")[1]
122         build = build[build.find("(") + 1 : build.find(")")]
123         info["build"] = build
124     expr = re.compile("Configured with: .*")
125     configured = expr.findall(output)
126     if len(configured) == 1:
127         info["configured"] = configured[0].split("Configured with: ")[1]
128     expr = re.compile("Thread model: .*")
129     thread = expr.findall(output)
130     if len(thread) == 1:
131         info["thread"] = thread[0].split("Thread model: ")[1]
132     return info
133
134 def findDefinitions(ftype, path):
135     L = os.walk(path)
136     for element in L:
137         for filename in element[2]:
138             if fnmatch.fnmatch(filename, ftype):
139                 yield (filename, element[0])
140
141 def loadCpuInfos(path):
142     cpuInfos = []
143     for definition in findDefinitions(const.CPU_DEFINITION, path):
144         cpuInfos.append(getInfos(definition))
145     return cpuInfos
146
147 def getInfos(definition):
148     D = {}
149     D.update(const.CPU_DEF)
150     def include(filename, dict = D, directory=definition[1]):
151         execfile(directory + "/" + filename, {}, D)
152     D["include"] = include
153     include(definition[0], D)
154     D["CPU_NAME"] = definition[0].split(".")[0]
155     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
156     del D["include"]
157     return D
158
159 def getDefinitionBlocks(text):
160     """
161     Take a text and return a list of tuple (description, name-value).
162     """
163     block = []
164     block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
165     for comment, define in block_tmp:
166         block.append((" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip(), define))
167     block += re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
168     block += [(comment, define) for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)]
169     return block
170
171 def formatParamNameValue(text):
172     """
173     Take the given string and return a tuple with the name of the parameter in the first position
174     and the value in the second.
175     """
176     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
177     return block[0]
178
179 def getDescriptionInformations(text): 
180     """ 
181     Take the doxygen comment and strip the wizard informations, returning the tuple 
182     (comment, wizard_informations) 
183     """ 
184     index = text.find("$WIZARD") 
185     if index != -1: 
186         exec(text[index + 1:]) 
187         informations = WIZARD 
188         return text[:index].strip(), informations
189     else:
190         return text.strip(), {}
191
192 def loadConfigurationInfos(path):
193     """
194     Return the module configurations found in the given file as a dict with the
195     parameter name as key and a dict containig the fields above as value:
196         "value": the value of the parameter
197         "description": the description of the parameter
198         "informations": a dict containig optional informations:
199             "type": "int" | "boolean" | "enum"
200             "min": the minimum value for integer parameters
201             "max": the maximum value for integer parameters
202             "long": boolean indicating if the num is a long
203             "value_list": the name of the enum for enum parameters
204     """
205     try:
206         configurationInfos = {}
207         for comment, define in getDefinitionBlocks(open(path, "r").read()):
208             name, value = formatParamNameValue(define)
209             description, informations = getDescriptionInformations(comment)
210             configurationInfos[name] = {}
211             configurationInfos[name]["value"] = value
212             configurationInfos[name]["informations"] = informations
213             configurationInfos[name]["description"] = description
214         return configurationInfos
215     except SyntaxError:
216         raise DefineException.ConfigurationDefineException(path)
217
218 def loadModuleInfos(path):
219     """
220     Return the module infos found in the given file as a dict with the module
221     name as key and a dict containig the fields above as value or an empty dict
222     if the given file is not a BeRTOS module:
223         "depends": a list of modules needed by this module
224         "configuration": the cfg_*.h with the module configurations
225         "description": a string containing the brief description of doxygen
226         "enabled": contains False but the wizard will change if the user select
227         the module
228     """
229     try:
230         moduleInfos = {}
231         string = open(path, "r").read()
232         commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
233         commentList = [" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip() for comment in commentList]
234         for comment in commentList:
235             index = comment.find("$WIZARD_MODULE")
236             if index != -1:
237                 exec(comment[index + 1:])
238                 moduleInfos[WIZARD_MODULE["name"]] = {"depends": WIZARD_MODULE["depends"],
239                                                         "configuration": WIZARD_MODULE["configuration"],
240                                                         "description": "",
241                                                         "enabled": False}
242                 return moduleInfos
243         return {}
244     except SyntaxError:
245         raise DefineException.ModuleDefineException(path)
246
247 def loadModuleInfosDict(path):
248     """
249     Return the dict containig all the modules
250     """
251     moduleInfosDict = {}
252     for filename, path in findDefinitions("*.h", path):
253         moduleInfosDict.update(loadModuleInfos(path + "/" + filename))
254     return moduleInfosDict
255
256 def loadDefineLists(path):
257     """
258     Return a dict with the name of the list as key and a list of string as value
259     """
260     try:
261         string = open(path, "r").read()
262         commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
263         commentList = [" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip() for comment in commentList]
264         listDict = {}
265         for comment in commentList:
266             index = comment.find("$WIZARD_LIST")
267             if index != -1:
268                 exec(comment[index + 1:])
269                 listDict.update(WIZARD_LIST)
270         return listDict
271     except SyntaxError:
272         raise DefineException.EnumDefineException(path)
273
274 def loadDefineListsDict(path):
275     """
276     Return the dict containing all the define lists
277     """
278     defineListsDict = {}
279     for filename, path in findDefinitions("*.h", path):
280         defineListsDict.update(loadDefineLists(path + "/" + filename))
281     return defineListsDict
282
283 def sub(string, parameter, value):
284     """
285     Substitute the given value at the given parameter define in the given string
286     """
287     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)