4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
9 # Author: Lorenzo Berni <duplo@develer.com>
19 import codelite_project
20 import DefineException
22 def isBertosDir(directory):
23 return os.path.exists(directory + "/VERSION")
25 def bertosVersion(directory):
26 return open(directory + "/VERSION").readline().strip()
28 def createBertosProject(projectInfo):
29 directory = projectInfo.info("PROJECT_PATH")
30 sourcesDir = projectInfo.info("SOURCES_PATH")
31 if not os.path.isdir(directory):
33 f = open(directory + "/project.bertos", "w")
34 f.write(repr(projectInfo))
36 ## Destination source dir
37 srcdir = directory + "/bertos"
38 shutil.rmtree(srcdir, True)
39 shutil.copytree(sourcesDir + "/bertos", srcdir)
40 ## Destination makefile
41 makefile = directory + "/Makefile"
42 if os.path.exists(makefile):
44 makefile = open("mktemplates/Makefile").read()
45 makefile = makefileGenerator(projectInfo, makefile)
46 open(directory + "/Makefile", "w").write(makefile)
47 ## Destination project dir
48 prjdir = directory + "/" + os.path.basename(directory)
49 shutil.rmtree(prjdir, True)
51 ## Destination configurations files
52 cfgdir = prjdir + "/cfg"
53 shutil.rmtree(cfgdir, True)
55 for key, value in projectInfo.info("CONFIGURATIONS").items():
56 string = open(sourcesDir + "/" + key, "r").read()
57 for parameter, infos in value.items():
58 value = infos["value"]
59 if "type" in infos["informations"] and infos["informations"]["type"] == "autoenabled":
61 if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
63 if "long" in infos["informations"].keys() and infos["informations"]["long"]:
65 string = sub(string, parameter, value)
66 f = open(cfgdir + "/" + os.path.basename(key), "w")
70 makefile = open("mktemplates/template.mk", "r").read()
71 makefile = mkGenerator(projectInfo, makefile)
72 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
73 ## Destination main.c file
74 main = open("srctemplates/main.c", "r").read()
75 open(prjdir + "/main.c", "w").write(main)
76 if "codelite" in projectInfo.info("OUTPUT"):
77 workspace = codeliteWorkspaceGenerator(projectInfo)
78 open(directory + "/" + os.path.basename(prjdir) + ".workspace", "w").write(workspace)
79 project = codeliteProjectGenerator(projectInfo)
80 open(directory + "/" + os.path.basename(prjdir) + ".project", "w").write(project)
82 def mkGenerator(projectInfo, makefile):
84 Generates the mk file for the current project.
87 mkData["$pname"] = os.path.basename(projectInfo.info("PROJECT_PATH"))
88 mkData["$cpuname"] = projectInfo.info("CPU_INFOS")["CORE_CPU"]
89 mkData["$cflags"] = " ".join(projectInfo.info("CPU_INFOS")["C_FLAGS"])
90 mkData["$ldflags"] = " ".join(projectInfo.info("CPU_INFOS")["LD_FLAGS"])
91 mkData["$csrc"], mkData["$pcsrc"], mkData["$constants"] = csrcGenerator(projectInfo)
92 mkData["$prefix"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[0]
93 mkData["$suffix"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[1]
94 mkData["$cross"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[0]
95 mkData["$main"] = os.path.basename(projectInfo.info("PROJECT_PATH")) + "/main.c"
97 while makefile.find(key) != -1:
98 makefile = makefile.replace(key, mkData[key])
101 def makefileGenerator(projectInfo, makefile):
103 Generate the Makefile for the current project.
105 # TODO: write a general function that works for both the mk file and the Makefile
106 while makefile.find("project_name") != -1:
107 makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
110 def csrcGenerator(projectInfo):
111 modules = projectInfo.info("MODULES")
112 files = projectInfo.info("FILES")
113 if "harvard" in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
120 moduleFiles = set([])
121 for module, information in modules.items():
122 if information["enabled"]:
123 if "constants" in information:
124 constants.update(information["constants"])
125 moduleFiles |= set(findModuleFiles(module, projectInfo))
126 for fileDependency in information["depends"]:
127 if fileDependency in files:
128 moduleFiles |= set(findModuleFiles(fileDependency, projectInfo))
129 for file in moduleFiles:
130 if not harvard or "harvard" not in information or information["harvard"] == "both":
132 if harvard and "harvard" in information:
134 csrc = " \\\n\t".join(csrc) + " \\"
135 pcsrc = " \\\n\t".join(pcsrc) + " \\"
136 constants = "\n".join([os.path.basename(projectInfo.info("PROJECT_PATH")) + "_" + key + " = " + str(value) for key, value in constants.items()])
137 return csrc, pcsrc, constants
139 def findModuleFiles(module, projectInfo):
141 for filename, path in findDefinitions(module + ".c", projectInfo):
142 path = path.replace(projectInfo.info("SOURCES_PATH") + "/", "")
143 files.append(path + "/" + filename)
144 for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
145 path = path.replace(projectInfo.info("SOURCES_PATH") + "/", "")
146 files.append(path + "/" + filename)
147 for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
148 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
149 path = path.replace(projectInfo.info("SOURCES_PATH") + "/", "")
150 files.append(path + "/" + filename)
153 def codeliteProjectGenerator(projectInfo):
154 template = open("cltemplates/bertos.project").read()
155 filelist = "\n".join(codelite_project.clFiles(codelite_project.findSources(projectInfo.info("PROJECT_PATH")), projectInfo.info("PROJECT_PATH")))
156 while template.find("$filelist") != -1:
157 template = template.replace("$filelist", filelist)
158 projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
159 while template.find("$project") != -1:
160 template = template.replace("$project", projectName)
163 def codeliteWorkspaceGenerator(projectInfo):
164 template = open("cltemplates/bertos.workspace").read()
165 projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
166 while template.find("$project") != -1:
167 template = template.replace("$project", projectName)
171 path = os.environ["PATH"]
173 path = path.split(";")
175 path = path.split(":")
178 def findToolchains(pathList):
180 for element in pathList:
181 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
182 toolchains.append(toolchain)
183 return list(set(toolchains))
185 def getToolchainInfo(output):
187 expr = re.compile("Target: .*")
188 target = expr.findall(output)
190 info["target"] = target[0].split("Target: ")[1]
191 expr = re.compile("gcc version [0-9,.]*")
192 version = expr.findall(output)
193 if len(version) == 1:
194 info["version"] = version[0].split("gcc version ")[1]
195 expr = re.compile("gcc version [0-9,.]* \(.*\)")
196 build = expr.findall(output)
198 build = build[0].split("gcc version ")[1]
199 build = build[build.find("(") + 1 : build.find(")")]
200 info["build"] = build
201 expr = re.compile("Configured with: .*")
202 configured = expr.findall(output)
203 if len(configured) == 1:
204 info["configured"] = configured[0].split("Configured with: ")[1]
205 expr = re.compile("Thread model: .*")
206 thread = expr.findall(output)
208 info["thread"] = thread[0].split("Thread model: ")[1]
211 def loadSourceTree(project):
212 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
213 project.setInfo("FILE_LIST", fileList)
215 def findDefinitions(ftype, project):
216 L = project.info("FILE_LIST")
219 for filename in element[2]:
220 if fnmatch.fnmatch(filename, ftype):
221 definitions.append((filename, element[0]))
224 def loadCpuInfos(project):
226 for definition in findDefinitions(const.CPU_DEFINITION, project):
227 cpuInfos.append(getInfos(definition))
230 def getInfos(definition):
232 D.update(const.CPU_DEF)
233 def include(filename, dict = D, directory=definition[1]):
234 execfile(directory + "/" + filename, {}, D)
235 D["include"] = include
236 include(definition[0], D)
237 D["CPU_NAME"] = definition[0].split(".")[0]
238 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
242 def getCommentList(string):
243 commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
244 commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
247 def loadModuleDefinition(first_comment):
249 moduleDefinition = {}
250 for num, line in enumerate(first_comment):
251 index = line.find("$WIZ$")
255 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
257 raise ParseError(num, line[index:])
258 elif line.find("\\brief") != -1:
259 moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
261 if "module_name" in moduleDefinition.keys():
262 moduleName = moduleDefinition[const.MODULE_DEFINITION["module_name"]]
263 del moduleDefinition[const.MODULE_DEFINITION["module_name"]]
264 moduleDict[moduleName] = {}
265 if const.MODULE_DEFINITION["module_depends"] in moduleDefinition.keys():
266 if type(moduleDefinition[const.MODULE_DEFINITION["module_depends"]]) == str:
267 moduleDefinition[const.MODULE_DEFINITION["module_depends"]] = (moduleDefinition[const.MODULE_DEFINITION["module_depends"]],)
268 moduleDict[moduleName]["depends"] = moduleDefinition[const.MODULE_DEFINITION["module_depends"]]
269 del moduleDefinition[const.MODULE_DEFINITION["module_depends"]]
271 moduleDict[moduleName]["depends"] = ()
272 if const.MODULE_DEFINITION["module_configuration"] in moduleDefinition.keys():
273 moduleDict[moduleName]["configuration"] = moduleDefinition[const.MODULE_DEFINITION["module_configuration"]]
274 del moduleDefinition[const.MODULE_DEFINITION["module_configuration"]]
276 moduleDict[moduleName]["configuration"] = ""
277 if "module_description" in moduleDefinition.keys():
278 moduleDict[moduleName]["description"] = moduleDefinition["module_description"]
279 del moduleDefinition["module_description"]
280 if const.MODULE_DEFINITION["module_harvard"] in moduleDefinition.keys():
281 harvard = moduleDefinition[const.MODULE_DEFINITION["module_harvard"]]
282 if harvard == "both" or harvard == "pgm_memory":
283 moduleDict[moduleName]["harvard"] = harvard
284 del moduleDefinition[const.MODULE_DEFINITION["module_harvard"]]
285 moduleDict[moduleName]["constants"] = moduleDefinition
286 moduleDict[moduleName]["enabled"] = False
287 return toBeParsed, moduleDict
289 def loadDefineLists(commentList):
291 for comment in commentList:
292 for num, line in enumerate(comment):
293 index = line.find("$WIZ$")
296 exec line[index + len("$WIZ$ "):] in {}, defineList
298 raise ParseError(num, line[index:])
299 for key, value in defineList.items():
300 if type(value) == str:
301 defineList[key] = (value,)
304 def getDescriptionInformations(comment):
306 Take the doxygen comment and strip the wizard informations, returning the tuple
307 (comment, wizard_information)
312 for num, line in enumerate(comment):
313 index = line.find("$WIZ$")
316 brief += line[:index].strip()
318 description += " " + line[:index]
320 exec line[index + len("$WIZ$ "):] in {}, information
322 raise ParseError(num, line[index:])
325 brief += line.strip()
327 description += " " + line
328 description = description.strip()
329 return brief.strip(), description.strip(), information
331 def getDefinitionBlocks(text):
333 Take a text and return a list of tuple (description, name-value).
336 block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
337 for comment, define in block_tmp:
338 # Only the first element is needed
339 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
340 for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
341 block.append(([comment], define))
342 for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
343 block.append(([comment], define))
346 def loadModuleData(project):
349 configurationInfoDict = {}
351 for filename, path in findDefinitions("*.h", project):
352 commentList = getCommentList(open(path + "/" + filename, "r").read())
353 if len(commentList) > 0:
355 configurationInfo = {}
357 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
358 except ParseError, err:
359 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
360 for module, information in moduleDict.items():
361 information["category"] = os.path.basename(path)
362 if "configuration" in information.keys() and len(information["configuration"]):
363 configuration = moduleDict[module]["configuration"]
365 configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
366 except ParseError, err:
367 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
368 moduleInfoDict.update(moduleDict)
369 configurationInfoDict.update(configurationInfo)
372 listDict = loadDefineLists(commentList[1:])
373 listInfoDict.update(listDict)
374 except ParseError, err:
375 raise DefineException.EnumDefineException(path, err.line_number, err.line)
376 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
377 commentList = getCommentList(open(path + "/" + filename, "r").read())
378 listInfoDict.update(loadDefineLists(commentList))
379 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
380 for filename, path in findDefinitions("*_" + tag + ".h", project):
381 commentList = getCommentList(open(path + "/" + filename, "r").read())
382 listInfoDict.update(loadDefineLists(commentList))
383 project.setInfo("MODULES", moduleInfoDict)
384 project.setInfo("LISTS", listInfoDict)
385 project.setInfo("CONFIGURATIONS", configurationInfoDict)
386 project.setInfo("FILES", fileDict)
388 def formatParamNameValue(text):
390 Take the given string and return a tuple with the name of the parameter in the first position
391 and the value in the second.
393 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
396 def loadConfigurationInfos(path):
398 Return the module configurations found in the given file as a dict with the
399 parameter name as key and a dict containig the fields above as value:
400 "value": the value of the parameter
401 "description": the description of the parameter
402 "informations": a dict containig optional informations:
403 "type": "int" | "boolean" | "enum"
404 "min": the minimum value for integer parameters
405 "max": the maximum value for integer parameters
406 "long": boolean indicating if the num is a long
407 "value_list": the name of the enum for enum parameters
409 configurationInfos = {}
410 for comment, define in getDefinitionBlocks(open(path, "r").read()):
411 name, value = formatParamNameValue(define)
412 brief, description, informations = getDescriptionInformations(comment)
413 configurationInfos[name] = {}
414 configurationInfos[name]["value"] = value
415 configurationInfos[name]["informations"] = informations
416 if ("type" in configurationInfos[name]["informations"].keys() and
417 configurationInfos[name]["informations"]["type"] == "int" and
418 configurationInfos[name]["value"].find("L") != -1):
419 configurationInfos[name]["informations"]["long"] = True
420 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
421 if ("type" in configurationInfos[name]["informations"].keys() and
422 configurationInfos[name]["informations"]["type"] == "int" and
423 configurationInfos[name]["value"].find("U") != -1):
424 configurationInfos[name]["informations"]["unsigned"] = True
425 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
426 configurationInfos[name]["description"] = description
427 configurationInfos[name]["brief"] = brief
428 return configurationInfos
430 def sub(string, parameter, value):
432 Substitute the given value at the given parameter define in the given string
434 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
436 def isInt(informations):
438 Return True if the value is a simple int.
440 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
445 def isLong(informations):
447 Return True if the value is a long.
449 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
454 def isUnsigned(informations):
456 Return True if the value is an unsigned.
458 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
463 def isUnsignedLong(informations):
465 Return True if the value is an unsigned long.
467 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
472 class ParseError(Exception):
473 def __init__(self, line_number, line):
474 Exception.__init__(self)
475 self.line_number = line_number