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