4 # This file is part of BeRTOS.
6 # Bertos is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 # As a special exception, you may use this file as part of a free software
21 # library without restriction. Specifically, if other files instantiate
22 # templates or use macros or inline functions from this file, or you compile
23 # this file and link it with other files to produce an executable, this
24 # file does not by itself cause the resulting executable to be covered by
25 # the GNU General Public License. This exception does not however
26 # invalidate any other reasons why the executable file might be covered by
27 # the GNU General Public License.
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
33 # Author: Lorenzo Berni <duplo@develer.com>
41 # Use custom copytree function
47 import DefineException
50 from _wizard_version import WIZARD_VERSION
52 from LoadException import VersionException, ToolchainException
54 def isBertosDir(directory):
55 return os.path.exists(directory + "/VERSION")
57 def bertosVersion(directory):
58 return open(directory + "/VERSION").readline().strip()
60 def loadBertosProject(project_file, info_dict):
61 project_data = pickle.loads(open(project_file, "r").read())
62 project_info = BProject.BProject()
63 project_info.setInfo("PROJECT_PATH", os.path.dirname(project_file))
64 # Check for the Wizard version
65 wizard_version = project_data.get("WIZARD_VERSION", 0)
66 if not wizard_version:
67 project_data["SOURCES_PATH"] = os.path.dirname(project_file)
68 if "SOURCES_PATH" in info_dict:
69 project_data["SOURCES_PATH"] = info_dict["SOURCES_PATH"]
70 if os.path.exists(project_data["SOURCES_PATH"]):
71 project_info.setInfo("SOURCES_PATH", project_data["SOURCES_PATH"])
73 raise VersionException(project_info)
74 loadSourceTree(project_info)
75 cpu_name = project_data["CPU_NAME"]
76 project_info.setInfo("CPU_NAME", cpu_name)
77 cpu_info = loadCpuInfos(project_info)
79 if cpu["CPU_NAME"] == cpu_name:
80 project_info.setInfo("CPU_INFOS", cpu)
82 tag_list = getTagSet(cpu_info)
83 # Create, fill and store the dict with the tags
85 for element in tag_list:
86 tag_dict[element] = False
87 infos = project_info.info("CPU_INFOS")
89 if tag in infos["CPU_TAGS"] + [infos["CPU_NAME"], infos["TOOLCHAIN"]]:
93 project_info.setInfo("ALL_CPU_TAGS", tag_dict)
94 if "TOOLCHAIN" in info_dict:
95 project_data["TOOLCHAIN"] = info_dict["TOOLCHAIN"]
96 if os.path.exists(project_data["TOOLCHAIN"]["path"]):
97 project_info.setInfo("TOOLCHAIN", project_data["TOOLCHAIN"])
99 raise ToolchainException(project_info)
100 project_info.setInfo("SELECTED_FREQ", project_data["SELECTED_FREQ"])
101 project_info.setInfo("OUTPUT", project_data["OUTPUT"])
102 loadModuleData(project_info, True)
103 setEnabledModules(project_info, project_data["ENABLED_MODULES"])
106 def setEnabledModules(project_info, enabled_modules):
107 modules = project_info.info("MODULES")
109 for module, information in modules.items():
110 information["enabled"] = module in enabled_modules
111 for dependency in information["depends"]:
112 if not dependency in modules:
113 if dependency in files:
114 files[dependency] += 1
116 files[dependency] = 1
117 project_info.setInfo("MODULES", modules)
118 project_info.setInfo("FILES", files)
120 def enabledModules(project_info):
122 for name, module in project_info.info("MODULES").items():
123 if module["enabled"]:
124 enabled_modules.append(name)
125 return enabled_modules
127 def mergeSources(srcdir, new_sources, old_sources):
128 # The current mergeSources function provide only a raw copy of the sources in the
131 # TODO: implement the three way merge algorithm
133 shutil.rmtree(srcdir, True)
134 copytree.copytree(os.path.join(new_sources, "bertos"), srcdir, ignore_list=const.IGNORE_LIST)
136 def projectFileGenerator(project_info):
137 directory = project_info.info("PROJECT_PATH")
140 for module, information in project_info.info("MODULES").items():
141 if information["enabled"]:
142 enabled_modules.append(module)
143 project_data["ENABLED_MODULES"] = enabled_modules
144 # Use the local BeRTOS version instead of the original one
145 # project_data["SOURCES_PATH"] = project_info.info("SOURCES_PATH")
146 project_data["SOURCES_PATH"] = directory
147 project_data["TOOLCHAIN"] = project_info.info("TOOLCHAIN")
148 project_data["CPU_NAME"] = project_info.info("CPU_NAME")
149 project_data["SELECTED_FREQ"] = project_info.info("SELECTED_FREQ")
150 project_data["OUTPUT"] = project_info.info("OUTPUT")
151 project_data["WIZARD_VERSION"] = WIZARD_VERSION
152 return pickle.dumps(project_data)
154 def createBertosProject(project_info, edit=False):
155 directory = project_info.info("PROJECT_PATH")
156 sources_dir = project_info.info("SOURCES_PATH")
157 old_sources_dir = project_info.info("OLD_SOURCES_PATH")
159 if os.path.isdir(directory):
160 shutil.rmtree(directory, True)
161 os.makedirs(directory)
162 # Write the project file
163 f = open(directory + "/project.bertos", "w")
164 f.write(projectFileGenerator(project_info))
167 version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
168 open(directory + "/VERSION", "w").write(versionFileGenerator(project_info, version_file))
169 # Destination source dir
170 srcdir = directory + "/bertos"
172 # If not in editing mode it copies all the bertos sources in the /bertos subdirectory of the project
173 shutil.rmtree(srcdir, True)
174 copytree.copytree(sources_dir + "/bertos", srcdir, ignore_list=const.IGNORE_LIST)
175 elif old_sources_dir:
176 # If in editing mode it merges the current bertos sources with the selected ones
177 # TODO: implement the three way merge algotihm
179 mergeSources(srcdir, sources_dir, old_sources_dir)
180 # Destination makefile
181 makefile = directory + "/Makefile"
182 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/Makefile"), 'r').read()
183 makefile = makefileGenerator(project_info, makefile)
184 open(directory + "/Makefile", "w").write(makefile)
185 # Destination project dir
186 prjdir = directory + "/" + os.path.basename(directory)
188 shutil.rmtree(prjdir, True)
190 # Destination hw files
191 hwdir = prjdir + "/hw"
193 shutil.rmtree(hwdir, True)
195 # Copy all the hw files
196 for module, information in project_info.info("MODULES").items():
197 for hwfile in information["hw"]:
198 string = open(sources_dir + "/" + hwfile, "r").read()
199 hwfile_path = hwdir + "/" + os.path.basename(hwfile)
200 if not edit or not os.path.exists(hwfile_path):
201 # If not in editing mode it copies all the hw files. If in
202 # editing mode it copies only the files that don't exist yet
203 open(hwdir + "/" + os.path.basename(hwfile), "w").write(string)
204 # Destination configurations files
205 cfgdir = prjdir + "/cfg"
207 shutil.rmtree(cfgdir, True)
209 # Set properly the autoenabled parameters
210 for module, information in project_info.info("MODULES").items():
211 if "configuration" in information and information["configuration"] != "":
212 configurations = project_info.info("CONFIGURATIONS")
213 configuration = configurations[information["configuration"]]
214 for start, parameter in configuration["paramlist"]:
215 if "type" in configuration[parameter]["informations"] and configuration[parameter]["informations"]["type"] == "autoenabled":
216 configuration[parameter]["value"] = "1" if information["enabled"] else "0"
217 project_info.setInfo("CONFIGURATIONS", configurations)
218 # Copy all the configuration files
219 for configuration, information in project_info.info("CONFIGURATIONS").items():
220 string = open(sources_dir + "/" + configuration, "r").read()
221 for start, parameter in information["paramlist"]:
222 infos = information[parameter]
223 value = infos["value"]
224 if "unsigned" in infos["informations"] and infos["informations"]["unsigned"]:
226 if "long" in infos["informations"] and infos["informations"]["long"]:
228 string = sub(string, parameter, value)
229 f = open(cfgdir + "/" + os.path.basename(configuration), "w")
233 # Destination user mk file (only on project creation)
234 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template.mk"), "r").read()
235 makefile = mkGenerator(project_info, makefile)
236 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
237 # Destination wizard mk file
238 makefile = open(os.path.join(const.DATA_DIR, "mktemplates/template_wiz.mk"), "r").read()
239 makefile = mkGenerator(project_info, makefile)
240 open(prjdir + "/" + os.path.basename(prjdir) + "_wiz.mk", "w").write(makefile)
241 # Destination main.c file
243 main = open(os.path.join(const.DATA_DIR, "srctemplates/main.c"), "r").read()
244 open(prjdir + "/main.c", "w").write(main)
245 # Files for selected plugins
247 for plugin in project_info.info("OUTPUT"):
248 module = loadPlugin(plugin)
249 relevants_files[plugin] = module.createProject(project_info)
250 project_info.setInfo("RELEVANT_FILES", relevants_files)
252 def loadPlugin(plugin):
254 Returns the given plugin module.
256 return getattr(__import__("plugins", {}, {}, [plugin]), plugin)
258 def versionFileGenerator(project_info, version_file):
259 version = bertosVersion(project_info.info("SOURCES_PATH"))
260 return version_file.replace('$version', version)
262 def mkGenerator(project_info, makefile):
264 Generates the mk file for the current project.
267 mk_data["$pname"] = os.path.basename(project_info.info("PROJECT_PATH"))
268 mk_data["$cpuclockfreq"] = project_info.info("SELECTED_FREQ")
269 cpu_mk_parameters = []
270 for key, value in project_info.info("CPU_INFOS").items():
271 if key.startswith(const.MK_PARAM_ID):
272 cpu_mk_parameters.append("%s = %s" %(key.replace("MK", mk_data["$pname"]), value))
273 mk_data["$cpuparameters"] = "\n".join(cpu_mk_parameters)
274 mk_data["$csrc"], mk_data["$pcsrc"], mk_data["$cppasrc"], mk_data["$cxxsrc"], mk_data["$asrc"], mk_data["$constants"] = csrcGenerator(project_info)
275 mk_data["$prefix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[0])
276 mk_data["$suffix"] = replaceSeparators(project_info.info("TOOLCHAIN")["path"].split("gcc")[1])
277 mk_data["$main"] = os.path.basename(project_info.info("PROJECT_PATH")) + "/main.c"
279 while makefile.find(key) != -1:
280 makefile = makefile.replace(key, mk_data[key])
283 def makefileGenerator(project_info, makefile):
285 Generate the Makefile for the current project.
287 # TODO write a general function that works for both the mk file and the Makefile
288 while makefile.find("$pname") != -1:
289 makefile = makefile.replace("$pname", os.path.basename(project_info.info("PROJECT_PATH")))
292 def csrcGenerator(project_info):
293 modules = project_info.info("MODULES")
294 files = project_info.info("FILES")
295 if "harvard" in project_info.info("CPU_INFOS")["CPU_TAGS"]:
299 # file to be included in CSRC variable
301 # file to be included in PCSRC variable
303 # files to be included in CPPASRC variable
305 # files to be included in CXXSRC variable
307 # files to be included in ASRC variable
309 # constants to be included at the beginning of the makefile
311 for module, information in modules.items():
312 module_files = set([])
313 dependency_files = set([])
316 hwdir = os.path.basename(project_info.info("PROJECT_PATH")) + "/hw"
317 if information["enabled"]:
318 if "constants" in information:
319 constants.update(information["constants"])
320 cfiles, sfiles = findModuleFiles(module, project_info)
321 module_files |= set(cfiles)
322 asm_files |= set(sfiles)
323 for file in information["hw"]:
324 if file.endswith(".c"):
325 module_files |= set([hwdir + "/" + os.path.basename(file)])
326 for file_dependency in information["depends"] + tuple(files.keys()):
327 dependencyCFiles, dependencySFiles = findModuleFiles(file_dependency, project_info)
328 dependency_files |= set(dependencyCFiles)
329 asm_files |= set(dependencySFiles)
330 for file in module_files:
331 if not harvard or information.get("harvard", "both") == "both":
333 if harvard and "harvard" in information:
335 for file in dependency_files:
337 for file in project_info.info("CPU_INFOS")["C_SRC"]:
339 for file in project_info.info("CPU_INFOS")["PC_SRC"]:
341 for file in asm_files:
343 for file in project_info.info("CPU_INFOS")["CPPA_SRC"]:
345 for file in project_info.info("CPU_INFOS")["CXX_SRC"]:
347 for file in project_info.info("CPU_INFOS")["ASRC"]:
350 csrc = " \\\n\t".join(csrc) + " \\"
352 pcsrc = " \\\n\t".join(pcsrc) + " \\"
353 cppasrc = set(cppasrc)
354 cppasrc = " \\\n\t".join(cppasrc) + " \\"
356 cxxsrc = " \\\n\t".join(cxxsrc) + " \\"
358 asrc = " \\\n\t".join(asrc) + " \\"
359 constants = "\n".join([os.path.basename(project_info.info("PROJECT_PATH")) + "_" + key + " = " + unicode(value) for key, value in constants.items()])
360 return csrc, pcsrc, cppasrc, cxxsrc, asrc, constants
362 def findModuleFiles(module, project_info):
363 # Find the files related to the selected module
366 # .c files related to the module and the cpu architecture
367 for filename, path in findDefinitions(module + ".c", project_info) + \
368 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".c", project_info):
369 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
370 path = replaceSeparators(path)
371 cfiles.append(path + "/" + filename)
372 # .s files related to the module and the cpu architecture
373 for filename, path in findDefinitions(module + ".s", project_info) + \
374 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".s", project_info) + \
375 findDefinitions(module + ".S", project_info) + \
376 findDefinitions(module + "_" + project_info.info("CPU_INFOS")["TOOLCHAIN"] + ".S", project_info):
377 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
378 path = replaceSeparators(path)
379 sfiles.append(path + "/" + filename)
380 # .c and .s files related to the module and the cpu tags
381 for tag in project_info.info("CPU_INFOS")["CPU_TAGS"]:
382 for filename, path in findDefinitions(module + "_" + tag + ".c", project_info):
383 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
385 path = replaceSeparators(path)
386 cfiles.append(path + "/" + filename)
387 for filename, path in findDefinitions(module + "_" + tag + ".s", project_info) + \
388 findDefinitions(module + "_" + tag + ".S", project_info):
389 path = path.replace(project_info.info("SOURCES_PATH") + os.sep, "")
390 path = replaceSeparators(path)
391 sfiles.append(path + "/" + filename)
392 return cfiles, sfiles
394 def replaceSeparators(path):
396 Replace the separators in the given path with unix standard separator.
399 while path.find(os.sep) != -1:
400 path = path.replace(os.sep, "/")
404 path = os.environ["PATH"]
406 path = path.split(";")
408 path = path.split(":")
411 def findToolchains(path_list):
413 for element in path_list:
414 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
415 toolchains.append(toolchain)
416 return list(set(toolchains))
418 def getToolchainInfo(output):
420 expr = re.compile("Target: .*")
421 target = expr.findall(output)
423 info["target"] = target[0].split("Target: ")[1]
424 expr = re.compile("gcc version [0-9,.]*")
425 version = expr.findall(output)
426 if len(version) == 1:
427 info["version"] = version[0].split("gcc version ")[1]
428 expr = re.compile("gcc version [0-9,.]* \(.*\)")
429 build = expr.findall(output)
431 build = build[0].split("gcc version ")[1]
432 build = build[build.find("(") + 1 : build.find(")")]
433 info["build"] = build
434 expr = re.compile("Configured with: .*")
435 configured = expr.findall(output)
436 if len(configured) == 1:
437 info["configured"] = configured[0].split("Configured with: ")[1]
438 expr = re.compile("Thread model: .*")
439 thread = expr.findall(output)
441 info["thread"] = thread[0].split("Thread model: ")[1]
444 def getToolchainName(toolchain_info):
445 name = "GCC " + toolchain_info["version"] + " - " + toolchain_info["target"].strip()
448 def loadSourceTree(project):
449 # Index only the SOURCES_PATH/bertos content
450 bertos_sources_dir = os.path.join(project.info("SOURCES_PATH"), 'bertos')
451 if os.path.exists(bertos_sources_dir):
452 fileList = [f for f in os.walk(bertos_sources_dir)]
455 project.setInfo("FILE_LIST", fileList)
457 def findDefinitions(ftype, project):
458 L = project.info("FILE_LIST")
461 for filename in element[2]:
462 if fnmatch.fnmatch(filename, ftype):
463 definitions.append((filename, element[0]))
466 def loadCpuInfos(project):
468 for definition in findDefinitions(const.CPU_DEFINITION, project):
469 cpuInfos.append(getInfos(definition))
472 def getTagSet(cpu_info):
475 tag_set |= set([cpu["CPU_NAME"]])
476 tag_set |= set(cpu["CPU_TAGS"])
477 tag_set |= set([cpu["TOOLCHAIN"]])
481 def getInfos(definition):
483 D.update(const.CPU_DEF)
484 def include(filename, dict = D, directory=definition[1]):
485 execfile(directory + "/" + filename, {}, D)
486 D["include"] = include
487 include(definition[0], D)
488 D["CPU_NAME"] = definition[0].split(".")[0]
489 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
493 def getCommentList(string):
494 comment_list = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
495 comment_list = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in comment_list]
498 def loadModuleDefinition(first_comment):
500 module_definition = {}
501 for num, line in enumerate(first_comment):
502 index = line.find("$WIZ$")
506 exec line[index + len("$WIZ$ "):] in {}, module_definition
508 raise ParseError(num, line[index:])
509 elif line.find("\\brief") != -1:
510 module_definition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
512 if "module_name" in module_definition:
513 module_name = module_definition[const.MODULE_DEFINITION["module_name"]]
514 del module_definition[const.MODULE_DEFINITION["module_name"]]
515 module_dict[module_name] = {}
516 if const.MODULE_DEFINITION["module_depends"] in module_definition:
517 depends = module_definition[const.MODULE_DEFINITION["module_depends"]]
518 del module_definition[const.MODULE_DEFINITION["module_depends"]]
519 if type(depends) == str:
521 module_dict[module_name]["depends"] = depends
523 module_dict[module_name]["depends"] = ()
524 if const.MODULE_DEFINITION["module_configuration"] in module_definition:
525 module_dict[module_name]["configuration"] = module_definition[const.MODULE_DEFINITION["module_configuration"]]
526 del module_definition[const.MODULE_DEFINITION["module_configuration"]]
528 module_dict[module_name]["configuration"] = ""
529 if "module_description" in module_definition:
530 module_dict[module_name]["description"] = module_definition["module_description"]
531 del module_definition["module_description"]
532 if const.MODULE_DEFINITION["module_harvard"] in module_definition:
533 harvard = module_definition[const.MODULE_DEFINITION["module_harvard"]]
534 module_dict[module_name]["harvard"] = harvard
535 del module_definition[const.MODULE_DEFINITION["module_harvard"]]
536 if const.MODULE_DEFINITION["module_hw"] in module_definition:
537 hw = module_definition[const.MODULE_DEFINITION["module_hw"]]
538 del module_definition[const.MODULE_DEFINITION["module_hw"]]
541 module_dict[module_name]["hw"] = hw
543 module_dict[module_name]["hw"] = ()
544 if const.MODULE_DEFINITION["module_supports"] in module_definition:
545 supports = module_definition[const.MODULE_DEFINITION["module_supports"]]
546 del module_definition[const.MODULE_DEFINITION["module_supports"]]
547 module_dict[module_name]["supports"] = supports
548 module_dict[module_name]["constants"] = module_definition
549 module_dict[module_name]["enabled"] = False
550 return to_be_parsed, module_dict
552 def isSupported(project, module=None, property_id=None):
553 if not module and property_id:
554 item = project.info("CONFIGURATIONS")[property_id[0]][property_id[1]]["informations"]
556 item = project.info("MODULES")[module]
557 tag_dict = project.info("ALL_CPU_TAGS")
558 if "supports" in item:
559 support_string = item["supports"]
562 exec "supported = " + support_string in tag_dict, supported
564 raise SupportedException(support_string)
565 return supported["supported"]
569 def loadDefineLists(comment_list):
571 for comment in comment_list:
572 for num, line in enumerate(comment):
573 index = line.find("$WIZ$")
576 exec line[index + len("$WIZ$ "):] in {}, define_list
578 raise ParseError(num, line[index:])
579 for key, value in define_list.items():
580 if type(value) == str:
581 define_list[key] = (value,)
584 def getDescriptionInformations(comment):
586 Take the doxygen comment and strip the wizard informations, returning the tuple
587 (comment, wizard_information)
592 for num, line in enumerate(comment):
593 index = line.find("$WIZ$")
596 brief += line[:index].strip()
598 description += " " + line[:index]
600 exec line[index + len("$WIZ$ "):] in {}, information
602 raise ParseError(num, line[index:])
605 brief += line.strip()
607 description += " " + line
608 description = description.strip()
609 return brief.strip(), description.strip(), information
611 def getDefinitionBlocks(text):
613 Take a text and return a list of tuple (description, name-value).
616 block_tmp = re.finditer(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
617 for match in block_tmp:
618 # Only the first element is needed
619 comment = match.group(1)
620 define = match.group(2)
621 start = match.start()
622 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define, start))
623 for match in re.finditer(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
624 comment = match.group(1)
625 define = match.group(2)
626 start = match.start()
627 block.append(([comment], define, start))
628 for match in re.finditer(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
629 comment = match.group(2)
630 define = match.group(1)
631 start = match.start()
632 block.append(([comment], define, start))
635 def loadModuleData(project, edit=False):
636 module_info_dict = {}
638 configuration_info_dict = {}
640 for filename, path in findDefinitions("*.h", project) + findDefinitions("*.c", project) + findDefinitions("*.s", project) + findDefinitions("*.S", project):
641 comment_list = getCommentList(open(path + "/" + filename, "r").read())
642 if len(comment_list) > 0:
644 configuration_info = {}
646 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
647 except ParseError, err:
648 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
649 for module, information in module_dict.items():
650 if "depends" not in information:
651 information["depends"] = ()
652 information["depends"] += (filename.split(".")[0],)
653 information["category"] = os.path.basename(path)
654 if "configuration" in information and len(information["configuration"]):
655 configuration = module_dict[module]["configuration"]
657 configuration_info[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
658 except ParseError, err:
659 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
662 path = os.path.basename(project.info("PROJECT_PATH"))
663 directory = project.info("PROJECT_PATH")
664 user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
665 configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
666 except ParseError, err:
667 raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
668 module_info_dict.update(module_dict)
669 configuration_info_dict.update(configuration_info)
672 list_dict = loadDefineLists(comment_list[1:])
673 list_info_dict.update(list_dict)
674 except ParseError, err:
675 raise DefineException.EnumDefineException(path, err.line_number, err.line)
676 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
677 comment_list = getCommentList(open(path + "/" + filename, "r").read())
678 list_info_dict.update(loadDefineLists(comment_list))
679 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
680 for filename, path in findDefinitions("*_" + tag + ".h", project):
681 comment_list = getCommentList(open(path + "/" + filename, "r").read())
682 list_info_dict.update(loadDefineLists(comment_list))
683 project.setInfo("MODULES", module_info_dict)
684 project.setInfo("LISTS", list_info_dict)
685 project.setInfo("CONFIGURATIONS", configuration_info_dict)
686 project.setInfo("FILES", file_dict)
688 def formatParamNameValue(text):
690 Take the given string and return a tuple with the name of the parameter in the first position
691 and the value in the second.
693 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
696 def loadConfigurationInfos(path):
698 Return the module configurations found in the given file as a dict with the
699 parameter name as key and a dict containig the fields above as value:
700 "value": the value of the parameter
701 "description": the description of the parameter
702 "informations": a dict containig optional informations:
703 "type": "int" | "boolean" | "enum"
704 "min": the minimum value for integer parameters
705 "max": the maximum value for integer parameters
706 "long": boolean indicating if the num is a long
707 "unsigned": boolean indicating if the num is an unsigned
708 "value_list": the name of the enum for enum parameters
709 "conditional_deps": the list of conditional dependencies for boolean parameters
711 configuration_infos = {}
712 configuration_infos["paramlist"] = []
713 for comment, define, start in getDefinitionBlocks(open(path, "r").read()):
714 name, value = formatParamNameValue(define)
715 brief, description, informations = getDescriptionInformations(comment)
716 configuration_infos["paramlist"].append((start, name))
717 configuration_infos[name] = {}
718 configuration_infos[name]["value"] = value
719 configuration_infos[name]["informations"] = informations
720 if not "type" in configuration_infos[name]["informations"]:
721 configuration_infos[name]["informations"]["type"] = findParameterType(configuration_infos[name])
722 if ("type" in configuration_infos[name]["informations"] and
723 configuration_infos[name]["informations"]["type"] == "int" and
724 configuration_infos[name]["value"].find("L") != -1):
725 configuration_infos[name]["informations"]["long"] = True
726 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("L", "")
727 if ("type" in configuration_infos[name]["informations"] and
728 configuration_infos[name]["informations"]["type"] == "int" and
729 configuration_infos[name]["value"].find("U") != -1):
730 configuration_infos[name]["informations"]["unsigned"] = True
731 configuration_infos[name]["value"] = configuration_infos[name]["value"].replace("U", "")
732 if "conditional_deps" in configuration_infos[name]["informations"]:
733 if (type(configuration_infos[name]["informations"]["conditional_deps"]) == str or
734 type(configuration_infos[name]["informations"]["conditional_deps"]) == unicode):
735 configuration_infos[name]["informations"]["conditional_deps"] = (configuration_infos[name]["informations"]["conditional_deps"], )
736 elif type(configuration_infos[name]["informations"]["conditional_deps"]) == tuple:
739 configuration_infos[name]["informations"]["conditional_deps"] = ()
740 configuration_infos[name]["description"] = description
741 configuration_infos[name]["brief"] = brief
742 return configuration_infos
744 def updateConfigurationValues(def_conf, user_conf):
745 for param in def_conf["paramlist"]:
746 if param[1] in user_conf and "value" in user_conf[param[1]]:
747 def_conf[param[1]]["value"] = user_conf[param[1]]["value"]
750 def findParameterType(parameter):
751 if "value_list" in parameter["informations"]:
753 if "min" in parameter["informations"] or "max" in parameter["informations"] or re.match(r"^\d+U?L?$", parameter["value"]) != None:
756 def sub(string, parameter, value):
758 Substitute the given value at the given parameter define in the given string
760 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
762 def isInt(informations):
764 Return True if the value is a simple int.
766 if ("long" not in informatios or not informations["long"]) and ("unsigned" not in informations or informations["unsigned"]):
771 def isLong(informations):
773 Return True if the value is a long.
775 if "long" in informations and informations["long"] and "unsigned" not in informations:
780 def isUnsigned(informations):
782 Return True if the value is an unsigned.
784 if "unsigned" in informations and informations["unsigned"] and "long" not in informations:
789 def isUnsignedLong(informations):
791 Return True if the value is an unsigned long.
793 if "unsigned" in informations and "long" in informations and informations["unsigned"] and informations["long"]:
798 class ParseError(Exception):
799 def __init__(self, line_number, line):
800 Exception.__init__(self)
801 self.line_number = line_number
804 class SupportedException(Exception):
805 def __init__(self, support_string):
806 Exception.__init__(self)
807 self.support_string = support_string