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