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 "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
61 if "long" in infos["informations"].keys() and infos["informations"]["long"]:
63 string = sub(string, parameter, value)
64 f = open(cfgdir + "/" + os.path.basename(key), "w")
68 makefile = open("mktemplates/template.mk", "r").read()
69 makefile = mkGenerator(projectInfo, makefile)
70 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
71 if "codelite" in projectInfo.info("OUTPUT"):
72 workspace = codeliteWorkspaceGenerator(projectInfo)
73 open(directory + "/" + os.path.basename(prjdir) + ".workspace", "w").write(workspace)
74 project = codeliteProjectGenerator(projectInfo)
75 open(directory + "/" + os.path.basename(prjdir) + ".project", "w").write(project)
77 def mkGenerator(projectInfo, makefile):
79 Generates the mk file for the current project.
82 mkData["$pname"] = os.path.basename(projectInfo.info("PROJECT_PATH"))
83 mkData["$cpuname"] = projectInfo.info("CPU_INFOS")["CORE_CPU"]
84 mkData["$cflags"] = " ".join(projectInfo.info("CPU_INFOS")["C_FLAGS"])
85 mkData["$ldflags"] = " ".join(projectInfo.info("CPU_INFOS")["LD_FLAGS"])
86 mkData["$csrc"], mkData["$pcsrc"] = csrcGenerator(projectInfo)
87 mkData["$prefix"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[0]
88 mkData["$suffix"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[1]
89 mkData["$cross"] = projectInfo.info("TOOLCHAIN")["path"].split("gcc")[0]
91 while makefile.find(key) != -1:
92 makefile = makefile.replace(key, mkData[key])
95 def makefileGenerator(projectInfo, makefile):
97 Generate the Makefile for the current project.
99 # TODO: write a general function that works for both the mk file and the Makefile
100 while makefile.find("project_name") != -1:
101 makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
104 def csrcGenerator(projectInfo):
105 modules = projectInfo.info("MODULES")
106 if "harvard" in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
107 pcsrc_need = projectInfo.info("CPU_INFOS")["PC_SRC"]
112 for module, information in modules.items():
113 if information["enabled"]:
114 for filename, path in findDefinitions(module + ".c", projectInfo):
115 path = path.replace(projectInfo.info("SOURCES_PATH"), projectInfo.info("PROJECT_PATH"))
117 csrc.append(path + "/" + filename)
118 if module in pcsrc_need:
119 pcsrc.append(path + "/" + filename)
120 for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
121 path = path.replace(projectInfo.info("SOURCES_PATH"), projectInfo.info("PROJECT_PATH"))
123 csrc.append(path + "/" + filename)
124 if module in pcsrc_need:
125 pcsrc.append(path + "/" + filename)
126 for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
127 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
128 path = path.replace(projectInfo.info("SOURCES_PATH"), projectInfo.info("PROJECT_PATH"))
130 csrc.append(path + "/" + filename)
131 if module in pcsrc_need:
132 pcsrc.append(path + "/" + filename)
133 csrc = " \\\n\t".join(csrc) + " \\"
134 pcsrc = " \\\n\t".join(pcsrc) + " \\"
137 def codeliteProjectGenerator(projectInfo):
138 template = open("cltemplates/bertos.project").read()
139 filelist = "\n".join(codelite_project.clFiles(codelite_project.findSources(projectInfo.info("PROJECT_PATH")), projectInfo.info("PROJECT_PATH")))
140 while template.find("$filelist") != -1:
141 template = template.replace("$filelist", filelist)
142 projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
143 while template.find("$project") != -1:
144 template = template.replace("$project", projectName)
147 def codeliteWorkspaceGenerator(projectInfo):
148 template = open("cltemplates/bertos.workspace").read()
149 projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
150 while template.find("$project") != -1:
151 template = template.replace("$project", projectName)
155 path = os.environ["PATH"]
157 path = path.split(";")
159 path = path.split(":")
162 def findToolchains(pathList):
164 for element in pathList:
165 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
166 toolchains.append(toolchain)
167 return list(set(toolchains))
169 def getToolchainInfo(output):
171 expr = re.compile("Target: .*")
172 target = expr.findall(output)
174 info["target"] = target[0].split("Target: ")[1]
175 expr = re.compile("gcc version [0-9,.]*")
176 version = expr.findall(output)
177 if len(version) == 1:
178 info["version"] = version[0].split("gcc version ")[1]
179 expr = re.compile("gcc version [0-9,.]* \(.*\)")
180 build = expr.findall(output)
182 build = build[0].split("gcc version ")[1]
183 build = build[build.find("(") + 1 : build.find(")")]
184 info["build"] = build
185 expr = re.compile("Configured with: .*")
186 configured = expr.findall(output)
187 if len(configured) == 1:
188 info["configured"] = configured[0].split("Configured with: ")[1]
189 expr = re.compile("Thread model: .*")
190 thread = expr.findall(output)
192 info["thread"] = thread[0].split("Thread model: ")[1]
195 def loadSourceTree(project):
196 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
197 project.setInfo("FILE_LIST", fileList)
199 def findDefinitions(ftype, project):
200 L = project.info("FILE_LIST")
203 for filename in element[2]:
204 if fnmatch.fnmatch(filename, ftype):
205 definitions.append((filename, element[0]))
208 def loadCpuInfos(project):
210 for definition in findDefinitions(const.CPU_DEFINITION, project):
211 cpuInfos.append(getInfos(definition))
214 def getInfos(definition):
216 D.update(const.CPU_DEF)
217 def include(filename, dict = D, directory=definition[1]):
218 execfile(directory + "/" + filename, {}, D)
219 D["include"] = include
220 include(definition[0], D)
221 D["CPU_NAME"] = definition[0].split(".")[0]
222 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
226 def getCommentList(string):
227 commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
228 commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
231 def loadModuleDefinition(first_comment):
233 moduleDefinition = {}
234 for num, line in enumerate(first_comment):
235 index = line.find("$WIZ$")
239 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
241 raise ParseError(num, line[index:])
242 elif line.find("\\brief") != -1:
243 moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
245 if "module_name" in moduleDefinition.keys():
246 moduleDict[moduleDefinition["module_name"]] = {}
247 if "module_depends" in moduleDefinition.keys():
248 if type(moduleDefinition["module_depends"]) == str:
249 moduleDefinition["module_depends"] = (moduleDefinition["module_depends"],)
250 moduleDict[moduleDefinition["module_name"]]["depends"] = moduleDefinition["module_depends"]
252 moduleDict[moduleDefinition["module_name"]]["depends"] = ()
253 if "module_configuration" in moduleDefinition.keys():
254 moduleDict[moduleDefinition["module_name"]]["configuration"] = moduleDefinition["module_configuration"]
256 moduleDict[moduleDefinition["module_name"]]["configuration"] = ""
257 if "module_description" in moduleDefinition.keys():
258 moduleDict[moduleDefinition["module_name"]]["description"] = moduleDefinition["module_description"]
259 moduleDict[moduleDefinition["module_name"]]["enabled"] = False
260 return toBeParsed, moduleDict
262 def loadDefineLists(commentList):
264 for comment in commentList:
265 for num, line in enumerate(comment):
266 index = line.find("$WIZ$")
269 exec line[index + len("$WIZ$ "):] in {}, defineList
271 raise ParseError(num, line[index:])
272 for key, value in defineList.items():
273 if type(value) == str:
274 defineList[key] = (value,)
277 def getDescriptionInformations(comment):
279 Take the doxygen comment and strip the wizard informations, returning the tuple
280 (comment, wizard_information)
285 for num, line in enumerate(comment):
286 index = line.find("$WIZ$")
289 brief += line[:index].strip()
291 description += " " + line[:index]
293 exec line[index + len("$WIZ$ "):] in {}, information
295 raise ParseError(num, line[index:])
298 brief += line.strip()
300 description += " " + line
301 description = description.strip()
302 return brief.strip(), description.strip(), information
304 def getDefinitionBlocks(text):
306 Take a text and return a list of tuple (description, name-value).
309 block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
310 for comment, define in block_tmp:
311 # Only the first element is needed
312 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
313 for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
314 block.append(([comment], define))
315 for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
316 block.append(([comment], define))
319 def loadModuleData(project):
322 configurationInfoDict = {}
323 for filename, path in findDefinitions("*.h", project):
324 commentList = getCommentList(open(path + "/" + filename, "r").read())
325 if len(commentList) > 0:
327 configurationInfo = {}
329 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
330 except ParseError, err:
331 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
332 for module, information in moduleDict.items():
333 information["category"] = os.path.basename(path)
334 if "configuration" in information.keys() and len(information["configuration"]):
335 configuration = moduleDict[module]["configuration"]
337 configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
338 except ParseError, err:
339 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
340 moduleInfoDict.update(moduleDict)
341 configurationInfoDict.update(configurationInfo)
344 listDict = loadDefineLists(commentList[1:])
345 listInfoDict.update(listDict)
346 except ParseError, err:
347 raise DefineException.EnumDefineException(path, err.line_number, err.line)
348 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
349 commentList = getCommentList(open(path + "/" + filename, "r").read())
350 listInfoDict.update(loadDefineLists(commentList))
351 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
352 for filename, path in findDefinitions("*_" + tag + ".h", project):
353 commentList = getCommentList(open(path + "/" + filename, "r").read())
354 listInfoDict.update(loadDefineLists(commentList))
355 project.setInfo("MODULES", moduleInfoDict)
356 project.setInfo("LISTS", listInfoDict)
357 project.setInfo("CONFIGURATIONS", configurationInfoDict)
359 def formatParamNameValue(text):
361 Take the given string and return a tuple with the name of the parameter in the first position
362 and the value in the second.
364 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
367 def loadConfigurationInfos(path):
369 Return the module configurations found in the given file as a dict with the
370 parameter name as key and a dict containig the fields above as value:
371 "value": the value of the parameter
372 "description": the description of the parameter
373 "informations": a dict containig optional informations:
374 "type": "int" | "boolean" | "enum"
375 "min": the minimum value for integer parameters
376 "max": the maximum value for integer parameters
377 "long": boolean indicating if the num is a long
378 "value_list": the name of the enum for enum parameters
380 configurationInfos = {}
381 for comment, define in getDefinitionBlocks(open(path, "r").read()):
382 name, value = formatParamNameValue(define)
383 brief, description, informations = getDescriptionInformations(comment)
384 configurationInfos[name] = {}
385 configurationInfos[name]["value"] = value
386 configurationInfos[name]["informations"] = informations
387 if ("type" in configurationInfos[name]["informations"].keys() and
388 configurationInfos[name]["informations"]["type"] == "int" and
389 configurationInfos[name]["value"].find("L") != -1):
390 configurationInfos[name]["informations"]["long"] = True
391 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
392 if ("type" in configurationInfos[name]["informations"].keys() and
393 configurationInfos[name]["informations"]["type"] == "int" and
394 configurationInfos[name]["value"].find("U") != -1):
395 configurationInfos[name]["informations"]["unsigned"] = True
396 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
397 configurationInfos[name]["description"] = description
398 configurationInfos[name]["brief"] = brief
399 return configurationInfos
401 def sub(string, parameter, value):
403 Substitute the given value at the given parameter define in the given string
405 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
407 def isInt(informations):
409 Return True if the value is a simple int.
411 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
416 def isLong(informations):
418 Return True if the value is a long.
420 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
425 def isUnsigned(informations):
427 Return True if the value is an unsigned.
429 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
434 def isUnsignedLong(informations):
436 Return True if the value is an unsigned long.
438 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
443 class ParseError(Exception):
444 def __init__(self, line_number, line):
445 Exception.__init__(self)
446 self.line_number = line_number