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