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