Remove codelite specific functions from bertos_utils module
[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 import pickle
18
19 import const
20 import codelite_project
21 import DefineException
22
23 def isBertosDir(directory):
24    return os.path.exists(directory + "/VERSION")
25
26 def bertosVersion(directory):
27    return open(directory + "/VERSION").readline().strip()
28
29 def createBertosProject(project_info):
30     directory = project_info.info("PROJECT_PATH")
31     sources_dir = project_info.info("SOURCES_PATH")
32     if not os.path.isdir(directory):
33         os.mkdir(directory)
34     f = open(directory + "/project.bertos", "w")
35     f.write(pickle.dumps(project_info))
36     f.close()
37     ## Destination source dir
38     srcdir = directory + "/bertos"
39     shutil.rmtree(srcdir, True)
40     shutil.copytree(sources_dir + "/bertos", srcdir)
41     ## Destination makefile
42     makefile = directory + "/Makefile"
43     if os.path.exists(makefile):
44         os.remove(makefile)
45     makefile = open("mktemplates/Makefile").read()
46     makefile = makefileGenerator(project_info, makefile)
47     open(directory + "/Makefile", "w").write(makefile)
48     ## Destination project dir
49     prjdir = directory + "/" + os.path.basename(directory)
50     shutil.rmtree(prjdir, True)
51     os.mkdir(prjdir)
52     ## Destination configurations files
53     cfgdir = prjdir + "/cfg"
54     shutil.rmtree(cfgdir, True)
55     os.mkdir(cfgdir)
56     for configuration, information in project_info.info("CONFIGURATIONS").items():
57         string = open(sources_dir + "/" + configuration, "r").read()
58         for start, parameter in information["paramlist"]:
59             infos = information[parameter]
60             value = infos["value"]
61             if "type" in infos["informations"] and infos["informations"]["type"] == "autoenabled":
62                 value = "1"
63             if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
64                 value += "U"
65             if "long" in infos["informations"].keys() and infos["informations"]["long"]:
66                 value += "L"
67             string = sub(string, parameter, value)
68         f = open(cfgdir + "/" + os.path.basename(configuration), "w")
69         f.write(string)
70         f.close()
71     ## Destinatio mk file
72     makefile = open("mktemplates/template.mk", "r").read()
73     makefile = mkGenerator(project_info, makefile)
74     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
75     ## Destination main.c file
76     main = open("srctemplates/main.c", "r").read()
77     open(prjdir + "/main.c", "w").write(main)
78     ## Codelite project files
79     if "codelite" in project_info.info("OUTPUT"):
80         workspace = codelite_project.codeliteWorkspaceGenerator(project_info)
81         open(directory + "/" + os.path.basename(prjdir) + ".workspace", "w").write(workspace)
82         project = codelite_project.codeliteProjectGenerator(project_info)
83         open(directory + "/" + os.path.basename(prjdir) + ".project", "w").write(project)
84
85 def mkGenerator(project_info, makefile):
86     """
87     Generates the mk file for the current project.
88     """
89     mk_data = {}
90     mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
91     mk_data["$cpuname"] = project_info.info("CPU_INFOS")["CORE_CPU"]
92     mk_data["$cflags"] = " ".join(project_info.info("CPU_INFOS")["C_FLAGS"])
93     mk_data["$ldflags"] = " ".join(project_info.info("CPU_INFOS")["LD_FLAGS"])
94     mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
95     mk_data["$prefix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
96     mk_data["$suffix"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[1]
97     mk_data["$cross"] = project_info.info("TOOLCHAIN")["path"].split("gcc")[0]
98     mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
99     for key in mk_data:
100         while makefile.find(key) != -1:
101             makefile = makefile.replace(key, mk_data[key])
102     return makefile
103
104 def makefileGenerator(project_info, makefile):
105     """
106     Generate the Makefile for the current project.
107     """
108     # TODO: write a general function that works for both the mk file and the Makefile
109     while makefile.find("project_name") != -1:
110         makefile = makefile.replace("project_name", os.path.basename(project_info.info("PROJECT_PATH")))
111     return makefile
112
113 def csrcGenerator(project_info):
114     modules = project_info.info("MODULES")
115     files = project_info.info("FILES")
116     if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
117         harvard = True
118     else:
119         harvard = False
120     ## file to be included in CSRC variable
121     csrc = []
122     ## file to be included in PCSRC variable
123     pcsrc = []
124     ## files to be included in CPPASRC variable
125     asrc = []
126     ## constants to be included at the beginning of the makefile
127     constants = {}
128     for module, information in modules.items():
129         module_files = set([])
130         dependency_files = set([])
131         ## assembly sources
132         asm_files = set([])
133         if information["enabled"]:
134             if "constants" in information:
135                 constants.update(information["constants"])
136             cfiles, sfiles = findModuleFiles(module, project_info)
137             module_files |= set(cfiles)
138             asm_files |= set(sfiles)
139             for file_dependency in information["depends"]:
140                 if file_dependency in files:
141                     dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
142                     dependency_files |= set(dependencyCFiles)
143                     asm_files |= set(dependencySFiles)
144             for file in module_files:
145                 if not harvard or "harvard" not in information or information["harvard"] == "both":
146                     csrc.append(os.path.normpath(file))
147                 if harvard and "harvard" in information:
148                     pcsrc.append(os.path.normpath(file))
149             for file in dependency_files:
150                 csrc.append(os.path.normpath(file))
151             for file in asm_files:
152                 asrc.append(os.path.normpath(file))
153     csrc = " \\\n\t".join(csrc) + " \\"
154     pcsrc = " \\\n\t".join(pcsrc) + " \\"
155     asrc = " \\\n\t".join(asrc) + " \\"
156     constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
157     return csrc, pcsrc, asrc, constants
158     
159 def findModuleFiles(module, project_info):
160     ## Find the files related to the selected module
161     cfiles = []
162     sfiles = []
163     ## .c files related to the module and the cpu architecture
164     for filename, path in findDefinitions(module + ".c", project_info) + \
165             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
166         path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
167         cfiles.append(path + "/" + filename)
168     ## .s files related to the module and the cpu architecture
169     for filename, path in findDefinitions(module + ".s", project_info) + \
170             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
171             findDefinitions(module + ".S", project_info) + \
172             findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
173         path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
174         sfiles.append(path + "/" + filename)
175     ## .c and .s files related to the module and the cpu tags
176     for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
177         for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
178             path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
179             cfiles.append(path + "/" + filename)
180         for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
181                 findDefinitions(module + "_" + tag + ".S", project_info):
182             path = path.replace(project_info.info("SOURCES_PATH") + "/", "")
183             sfiles.append(path + "/" + filename)
184     return cfiles, sfiles
185
186 def getSystemPath():
187     path = os.environ["PATH"]
188     if os.name == "nt":
189         path = path.split(";")
190     else:
191         path = path.split(":")
192     return path
193
194 def findToolchains(path_list):
195     toolchains = []
196     for element in path_list:
197         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
198             toolchains.append(toolchain)
199     return list(set(toolchains))
200
201 def getToolchainInfo(output):
202     info = {}
203     expr = re.compile("Target: .*")
204     target = expr.findall(output)
205     if len(target) == 1:
206         info["target"] = target[0].split("Target: ")[1]
207     expr = re.compile("gcc version [0-9,.]*")
208     version = expr.findall(output)
209     if len(version) == 1:
210         info["version"] = version[0].split("gcc version ")[1]
211     expr = re.compile("gcc version [0-9,.]* \(.*\)")
212     build = expr.findall(output)
213     if len(build) == 1:
214         build = build[0].split("gcc version ")[1]
215         build = build[build.find("(") + 1 : build.find(")")]
216         info["build"] = build
217     expr = re.compile("Configured with: .*")
218     configured = expr.findall(output)
219     if len(configured) == 1:
220         info["configured"] = configured[0].split("Configured with: ")[1]
221     expr = re.compile("Thread model: .*")
222     thread = expr.findall(output)
223     if len(thread) == 1:
224         info["thread"] = thread[0].split("Thread model: ")[1]
225     return info
226
227 def loadSourceTree(project):
228     fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
229     project.setInfo("FILE_LIST", fileList)
230
231 def findDefinitions(ftype, project):
232     L = project.info("FILE_LIST")
233     definitions = []
234     for element in L:
235         for filename in element[2]:
236             if fnmatch.fnmatch(filename, ftype):
237                 definitions.append((filename, element[0]))
238     return definitions
239
240 def loadCpuInfos(project):
241     cpuInfos = []
242     for definition in findDefinitions(const.CPU_DEFINITION, project):
243         cpuInfos.append(getInfos(definition))
244     return cpuInfos
245
246 def getInfos(definition):
247     D = {}
248     D.update(const.CPU_DEF)
249     def include(filename, dict = D, directory=definition[1]):
250         execfile(directory + "/" + filename, {}, D)
251     D["include"] = include
252     include(definition[0], D)
253     D["CPU_NAME"] = definition[0].split(".")[0]
254     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
255     del D["include"]
256     return D
257
258 def getCommentList(string):
259     comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
260     comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
261     return comment_list
262
263 def loadModuleDefinition(first_comment):
264     to_be_parsed = False
265     module_definition = {}
266     for num, line in enumerate(first_comment):
267         index = line.find("$WIZ$")
268         if index != -1:
269             to_be_parsed = True
270             try:
271                 exec line[index + len("$WIZ$ "):] in {}, module_definition
272             except:
273                 raise ParseError(num, line[index:])
274         elif line.find("\\brief") != -1:
275             module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
276     module_dict = {}
277     if "module_name" in module_definition.keys():
278         module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
279         del module_definition[const.MODULE_DEFINITION["module_name"]]
280         module_dict[module_name] = {}
281         if const.MODULE_DEFINITION["module_depends"] in module_definition.keys():
282             if type(module_definition[const.MODULE_DEFINITION["module_depends"]]) == str:
283                 module_definition[const.MODULE_DEFINITION["module_depends"]] = (module_definition[const.MODULE_DEFINITION["module_depends"]],)
284             module_dict[module_name]["depends"] = module_definition[const.MODULE_DEFINITION["module_depends"]]
285             del module_definition[const.MODULE_DEFINITION["module_depends"]]
286         else:
287             module_dict[module_name]["depends"] = ()
288         if const.MODULE_DEFINITION["module_configuration"] in module_definition.keys():
289             module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
290             del module_definition[const.MODULE_DEFINITION["module_configuration"]]
291         else:
292             module_dict[module_name]["configuration"] = ""
293         if "module_description" in module_definition.keys():
294             module_dict[module_name]["description"] = module_definition["module_description"]
295             del module_definition["module_description"]
296         if const.MODULE_DEFINITION["module_harvard"] in module_definition.keys():
297             harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
298             if harvard == "both" or harvard == "pgm_memory":
299                 module_dict[module_name]["harvard"] = harvard
300             del module_definition[const.MODULE_DEFINITION["module_harvard"]]
301         module_dict[module_name]["constants"] = module_definition
302         module_dict[module_name]["enabled"] = False
303     return to_be_parsed, module_dict
304
305 def loadDefineLists(comment_list):
306     define_list = {}
307     for comment in comment_list:
308         for num, line in enumerate(comment):
309             index = line.find("$WIZ$")
310             if index != -1:
311                 try:
312                     exec line[index + len("$WIZ$ "):] in {}, define_list
313                 except:
314                     raise ParseError(num, line[index:])
315     for key, value in define_list.items():
316         if type(value) == str:
317             define_list[key] = (value,)
318     return define_list
319
320 def getDescriptionInformations(comment): 
321     """ 
322     Take the doxygen comment and strip the wizard informations, returning the tuple 
323     (comment, wizard_information) 
324     """
325     brief = ""
326     description = ""
327     information = {}
328     for num, line in enumerate(comment):
329         index = line.find("$WIZ$")
330         if index != -1:
331             if len(brief) == 0:
332                 brief += line[:index].strip()
333             else:
334                 description += " " + line[:index]
335             try:
336                 exec line[index + len("$WIZ$ "):] in {}, information
337             except:
338                 raise ParseError(num, line[index:])
339         else:
340             if len(brief) == 0:
341                 brief += line.strip()
342             else:
343                 description += " " + line
344                 description = description.strip()
345     return brief.strip(), description.strip(), information
346
347 def getDefinitionBlocks(text):
348     """
349     Take a text and return a list of tuple (description, name-value).
350     """
351     block = []
352     block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
353     for match in block_tmp:
354         # Only the first element is needed
355         comment = match.group(1)
356         define = match.group(2)
357         start = match.start()
358         block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
359     for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
360         comment = match.group(1)
361         define = match.group(2)
362         start = match.start()
363         block.append(([comment], define, start))
364     for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
365         comment = match.group(2)
366         define = match.group(1)
367         start = match.start()
368         block.append(([comment], define, start))
369     return block
370
371 def loadModuleData(project):
372     module_info_dict = {}
373     list_info_dict = {}
374     configuration_info_dict = {}
375     file_dict = {}
376     for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
377         comment_list = getCommentList(open(path + "/" + filename, "r").read())
378         if len(comment_list) > 0:
379             module_info = {}
380             configuration_info = {}
381             try:
382                 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
383             except ParseError, err:
384                 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
385             for module, information in module_dict.items():
386                 if "depends" not in information:
387                     information["depends"] = ()
388                 information["depends"] += (filename.split(".")[0],)
389                 information["category"] = os.path.basename(path)
390                 if "configuration" in information.keys() and len(information["configuration"]):
391                     configuration = module_dict[module]["configuration"]
392                     try:
393                         configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
394                     except ParseError, err:
395                         raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
396             module_info_dict.update(module_dict)
397             configuration_info_dict.update(configuration_info)
398             if to_be_parsed:
399                 try:
400                     list_dict = loadDefineLists(comment_list[1:])
401                     list_info_dict.update(list_dict)
402                 except ParseError, err:
403                     raise DefineException.EnumDefineException(path, err.line_number, err.line)
404     for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
405         comment_list = getCommentList(open(path + "/" + filename, "r").read())
406         list_info_dict.update(loadDefineLists(comment_list))
407     for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
408         for filename, path in findDefinitions("*_" + tag + ".h", project):
409             comment_list = getCommentList(open(path + "/" + filename, "r").read())
410             list_info_dict.update(loadDefineLists(comment_list))
411     project.setInfo("MODULES", module_info_dict)
412     project.setInfo("LISTS", list_info_dict)
413     project.setInfo("CONFIGURATIONS", configuration_info_dict)
414     project.setInfo("FILES", file_dict)
415     
416 def formatParamNameValue(text):
417     """
418     Take the given string and return a tuple with the name of the parameter in the first position
419     and the value in the second.
420     """
421     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
422     return block[0]
423
424 def loadConfigurationInfos(path):
425     """
426     Return the module configurations found in the given file as a dict with the
427     parameter name as key and a dict containig the fields above as value:
428         "value": the value of the parameter
429         "description": the description of the parameter
430         "informations": a dict containig optional informations:
431             "type": "int" | "boolean" | "enum"
432             "min": the minimum value for integer parameters
433             "max": the maximum value for integer parameters
434             "long": boolean indicating if the num is a long
435             "unsigned": boolean indicating if the num is an unsigned
436             "value_list": the name of the enum for enum parameters
437     """
438     configuration_infos = {}
439     configuration_infos["paramlist"] = []
440     for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
441         name, value = formatParamNameValue(define)
442         brief, description, informations = getDescriptionInformations(comment)
443         configuration_infos["paramlist"].append((start, name))
444         configuration_infos[name] = {}
445         configuration_infos[name]["value"] = value
446         configuration_infos[name]["informations"] = informations
447         if not "type" in configuration_infos[name]["informations"]:
448             configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
449         if ("type" in configuration_infos[name]["informations"].keys() and
450                 configuration_infos[name]["informations"]["type"] == "int" and
451                 configuration_infos[name]["value"].find("L") != -1):
452             configuration_infos[name]["informations"]["long"] = True
453             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
454         if ("type" in configuration_infos[name]["informations"].keys() and
455                 configuration_infos[name]["informations"]["type"] == "int" and
456                 configuration_infos[name]["value"].find("U") != -1):
457             configuration_infos[name]["informations"]["unsigned"] = True
458             configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
459         configuration_infos[name]["description"] = description
460         configuration_infos[name]["brief"] = brief
461     return configuration_infos
462
463 def findParameterType(parameter):
464     if "value_list" in parameter["informations"]:
465         return "enum"
466     if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
467         return "int"
468
469 def sub(string, parameter, value):
470     """
471     Substitute the given value at the given parameter define in the given string
472     """
473     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
474
475 def isInt(informations):
476     """
477     Return True if the value is a simple int.
478     """
479     if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
480         return True
481     else:
482         return False
483
484 def isLong(informations):
485     """
486     Return True if the value is a long.
487     """
488     if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
489         return True
490     else:
491         return False
492
493 def isUnsigned(informations):
494     """
495     Return True if the value is an unsigned.
496     """
497     if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
498         return True
499     else:
500         return False
501
502 def isUnsignedLong(informations):
503     """
504     Return True if the value is an unsigned long.
505     """
506     if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
507         return True
508     else:
509         return False
510
511 class ParseError(Exception):
512     def __init__(self, line_number, line):
513         Exception.__init__(self)
514         self.line_number = line_number
515         self.line = line