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 workspace = codeliteWorkspaceGenerator(projectInfo)
72 open(directory + "/" + os.path.basename(prjdir) + ".workspace", "w").write(workspace)
73 project = codeliteProjectGenerator(projectInfo)
74 open(directory + "/" + os.path.basename(prjdir) + ".project", "w").write(project)
76 def mkGenerator(projectInfo, makefile):
78 Generates the mk file for the current project.
81 mkData["$pname"] = os.path.basename(projectInfo.info("PROJECT_PATH"))
82 mkData["$cpuname"] = projectInfo.info("CPU_INFOS")["CPU_NAME"]
83 mkData["$cflags"] = " ".join(projectInfo.info("CPU_INFOS")["C_FLAGS"])
84 mkData["$ldflags"] = " ".join(projectInfo.info("CPU_INFOS")["LD_FLAGS"])
85 mkData["$csrc"] = csrcGenerator(projectInfo)
86 mkData["$prefix"] = os.path.basename(projectInfo.info("TOOLCHAIN")["path"]).split("gcc")[0]
87 mkData["$suffix"] = os.path.basename(projectInfo.info("TOOLCHAIN")["path"]).split("gcc")[1]
89 while makefile.find(key) != -1:
90 makefile = makefile.replace(key, mkData[key])
93 def makefileGenerator(projectInfo, makefile):
95 Generate the Makefile for the current project.
97 # TODO: write a general function that works for both the mk file and the Makefile
98 while makefile.find("project_name") != -1:
99 makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
102 def csrcGenerator(projectInfo):
103 modules = projectInfo.info("MODULES")
105 for module, information in modules.items():
106 if information["enabled"]:
107 for filename, path in findDefinitions(module + ".c", projectInfo):
108 files.append(path + "/" + filename)
109 for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
110 files.append(path + "/" + filename)
111 for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
112 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
113 files.append(path + "/" + filename)
114 csrc = " \\\n\t".join(files) + " \\"
117 def codeliteProjectGenerator(projectInfo):
118 template = open("cltemplates/bertos.project").read()
119 filelist = "\n".join(codelite_project.clFiles(codelite_project.findSources(projectInfo.info("PROJECT_PATH")), projectInfo.info("PROJECT_PATH")))
120 while template.find("$filelist") != -1:
121 template = template.replace("$filelist", filelist)
124 def codeliteWorkspaceGenerator(projectInfo):
125 template = open("cltemplates/bertos.workspace").read()
126 projectName = os.path.basename(projectInfo.info("PROJECT_PATH"))
127 while template.find("$project") != -1:
128 template = template.replace("$project", projectName)
132 path = os.environ["PATH"]
134 path = path.split(";")
136 path = path.split(":")
139 def findToolchains(pathList):
141 for element in pathList:
142 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
143 toolchains.append(toolchain)
144 return list(set(toolchains))
146 def getToolchainInfo(output):
148 expr = re.compile("Target: .*")
149 target = expr.findall(output)
151 info["target"] = target[0].split("Target: ")[1]
152 expr = re.compile("gcc version [0-9,.]*")
153 version = expr.findall(output)
154 if len(version) == 1:
155 info["version"] = version[0].split("gcc version ")[1]
156 expr = re.compile("gcc version [0-9,.]* \(.*\)")
157 build = expr.findall(output)
159 build = build[0].split("gcc version ")[1]
160 build = build[build.find("(") + 1 : build.find(")")]
161 info["build"] = build
162 expr = re.compile("Configured with: .*")
163 configured = expr.findall(output)
164 if len(configured) == 1:
165 info["configured"] = configured[0].split("Configured with: ")[1]
166 expr = re.compile("Thread model: .*")
167 thread = expr.findall(output)
169 info["thread"] = thread[0].split("Thread model: ")[1]
172 def loadSourceTree(project):
173 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
174 project.setInfo("FILE_LIST", fileList)
176 def findDefinitions(ftype, project):
177 L = project.info("FILE_LIST")
180 for filename in element[2]:
181 if fnmatch.fnmatch(filename, ftype):
182 definitions.append((filename, element[0]))
185 def loadCpuInfos(project):
187 for definition in findDefinitions(const.CPU_DEFINITION, project):
188 cpuInfos.append(getInfos(definition))
191 def getInfos(definition):
193 D.update(const.CPU_DEF)
194 def include(filename, dict = D, directory=definition[1]):
195 execfile(directory + "/" + filename, {}, D)
196 D["include"] = include
197 include(definition[0], D)
198 D["CPU_NAME"] = definition[0].split(".")[0]
199 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
203 def getCommentList(string):
204 commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
205 commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
208 def loadModuleDefinition(first_comment):
210 moduleDefinition = {}
211 for num, line in enumerate(first_comment):
212 index = line.find("$WIZ$")
216 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
218 raise ParseError(num, line[index:])
219 elif line.find("\\brief") != -1:
220 moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
222 if "module_name" in moduleDefinition.keys():
223 moduleDict[moduleDefinition["module_name"]] = {}
224 if "module_depends" in moduleDefinition.keys():
225 if type(moduleDefinition["module_depends"]) == str:
226 moduleDefinition["module_depends"] = (moduleDefinition["module_depends"],)
227 moduleDict[moduleDefinition["module_name"]]["depends"] = moduleDefinition["module_depends"]
229 moduleDict[moduleDefinition["module_name"]]["depends"] = ()
230 if "module_configuration" in moduleDefinition.keys():
231 moduleDict[moduleDefinition["module_name"]]["configuration"] = moduleDefinition["module_configuration"]
233 moduleDict[moduleDefinition["module_name"]]["configuration"] = ""
234 if "module_description" in moduleDefinition.keys():
235 moduleDict[moduleDefinition["module_name"]]["description"] = moduleDefinition["module_description"]
236 moduleDict[moduleDefinition["module_name"]]["enabled"] = False
237 return toBeParsed, moduleDict
239 def loadDefineLists(commentList):
241 for comment in commentList:
242 for num, line in enumerate(comment):
243 index = line.find("$WIZ$")
246 exec line[index + len("$WIZ$ "):] in {}, defineList
248 raise ParseError(num, line[index:])
249 for key, value in defineList.items():
250 if type(value) == str:
251 defineList[key] = (value,)
254 def getDescriptionInformations(comment):
256 Take the doxygen comment and strip the wizard informations, returning the tuple
257 (comment, wizard_information)
262 for num, line in enumerate(comment):
263 index = line.find("$WIZ$")
266 brief += line[:index].strip()
268 description += " " + line[:index]
270 exec line[index + len("$WIZ$ "):] in {}, information
272 raise ParseError(num, line[index:])
275 brief += line.strip()
277 description += " " + line
278 description = description.strip()
279 return brief.strip(), description.strip(), information
281 def getDefinitionBlocks(text):
283 Take a text and return a list of tuple (description, name-value).
286 block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
287 for comment, define in block_tmp:
288 # Only the first element is needed
289 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
290 for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
291 block.append(([comment], define))
292 for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
293 block.append(([comment], define))
296 def loadModuleData(project):
299 configurationInfoDict = {}
300 for filename, path in findDefinitions("*.h", project):
301 commentList = getCommentList(open(path + "/" + filename, "r").read())
302 if len(commentList) > 0:
304 configurationInfo = {}
306 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
307 except ParseError, err:
308 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
309 for module, information in moduleDict.items():
310 information["category"] = os.path.basename(path)
311 if "configuration" in information.keys() and len(information["configuration"]):
312 configuration = moduleDict[module]["configuration"]
314 configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
315 except ParseError, err:
316 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
317 moduleInfoDict.update(moduleDict)
318 configurationInfoDict.update(configurationInfo)
321 listDict = loadDefineLists(commentList[1:])
322 listInfoDict.update(listDict)
323 except ParseError, err:
324 raise DefineException.EnumDefineException(path, err.line_number, err.line)
325 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
326 commentList = getCommentList(open(path + "/" + filename, "r").read())
327 listInfoDict.update(loadDefineLists(commentList))
328 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
329 for filename, path in findDefinitions("*_" + tag + ".h", project):
330 commentList = getCommentList(open(path + "/" + filename, "r").read())
331 listInfoDict.update(loadDefineLists(commentList))
332 project.setInfo("MODULES", moduleInfoDict)
333 project.setInfo("LISTS", listInfoDict)
334 project.setInfo("CONFIGURATIONS", configurationInfoDict)
336 def formatParamNameValue(text):
338 Take the given string and return a tuple with the name of the parameter in the first position
339 and the value in the second.
341 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
344 def loadConfigurationInfos(path):
346 Return the module configurations found in the given file as a dict with the
347 parameter name as key and a dict containig the fields above as value:
348 "value": the value of the parameter
349 "description": the description of the parameter
350 "informations": a dict containig optional informations:
351 "type": "int" | "boolean" | "enum"
352 "min": the minimum value for integer parameters
353 "max": the maximum value for integer parameters
354 "long": boolean indicating if the num is a long
355 "value_list": the name of the enum for enum parameters
357 configurationInfos = {}
358 for comment, define in getDefinitionBlocks(open(path, "r").read()):
359 name, value = formatParamNameValue(define)
360 brief, description, informations = getDescriptionInformations(comment)
361 configurationInfos[name] = {}
362 configurationInfos[name]["value"] = value
363 configurationInfos[name]["informations"] = informations
364 if ("type" in configurationInfos[name]["informations"].keys() and
365 configurationInfos[name]["informations"]["type"] == "int" and
366 configurationInfos[name]["value"].find("L") != -1):
367 configurationInfos[name]["informations"]["long"] = True
368 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
369 if ("type" in configurationInfos[name]["informations"].keys() and
370 configurationInfos[name]["informations"]["type"] == "int" and
371 configurationInfos[name]["value"].find("U") != -1):
372 configurationInfos[name]["informations"]["unsigned"] = True
373 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
374 configurationInfos[name]["description"] = description
375 configurationInfos[name]["brief"] = brief
376 return configurationInfos
378 def sub(string, parameter, value):
380 Substitute the given value at the given parameter define in the given string
382 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
384 def isInt(informations):
386 Return True if the value is a simple int.
388 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
393 def isLong(informations):
395 Return True if the value is a long.
397 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
402 def isUnsigned(informations):
404 Return True if the value is an unsigned.
406 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
411 def isUnsignedLong(informations):
413 Return True if the value is an unsigned long.
415 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
420 class ParseError(Exception):
421 def __init__(self, line_number, line):
422 Exception.__init__(self)
423 self.line_number = line_number