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