4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
9 # Author: Lorenzo Berni <duplo@develer.com>
19 import DefineException
21 def isBertosDir(directory):
22 return os.path.exists(directory + "/VERSION")
24 def bertosVersion(directory):
25 return open(directory + "/VERSION").readline().strip()
27 def createBertosProject(projectInfo):
28 directory = projectInfo.info("PROJECT_PATH")
29 sourcesDir = projectInfo.info("SOURCES_PATH")
30 if not os.path.isdir(directory):
32 f = open(directory + "/project.bertos", "w")
33 f.write(repr(projectInfo))
35 ## Destination source dir
36 srcdir = directory + "/bertos"
37 shutil.rmtree(srcdir, True)
38 shutil.copytree(sourcesDir + "/bertos", srcdir)
39 ## Destination makefile
40 makefile = directory + "/Makefile"
41 if os.path.exists(makefile):
43 makefile = open("mktemplates/Makefile").read()
44 makefile = makefileGenerator(projectInfo, makefile)
45 open(directory + "/Makefile", "w").write(makefile)
46 ## Destination project dir
47 prjdir = directory + "/" + os.path.basename(directory)
48 shutil.rmtree(prjdir, True)
50 ## Destination configurations files
51 cfgdir = prjdir + "/cfg"
52 shutil.rmtree(cfgdir, True)
54 for key, value in projectInfo.info("CONFIGURATIONS").items():
55 string = open(sourcesDir + "/" + key, "r").read()
56 for parameter, infos in value.items():
57 value = infos["value"]
58 if "unsigned" in infos["informations"].keys() and infos["informations"]["unsigned"]:
60 if "long" in infos["informations"].keys() and infos["informations"]["long"]:
62 string = sub(string, parameter, value)
63 f = open(cfgdir + "/" + os.path.basename(key), "w")
67 makefile = open("mktemplates/template.mk", "r").read()
68 makefile = mkGenerator(projectInfo, makefile)
69 open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
71 def mkGenerator(projectInfo, makefile):
73 Generates the mk file for the current project.
76 mkData["$pname"] = os.path.basename(projectInfo.info("PROJECT_PATH"))
77 mkData["$cpuname"] = projectInfo.info("CPU_INFOS")["CPU_NAME"]
78 mkData["$cflags"] = " ".join(projectInfo.info("CPU_INFOS")["C_FLAGS"])
79 mkData["$ldflags"] = " ".join(projectInfo.info("CPU_INFOS")["LD_FLAGS"])
80 mkData["$csrc"] = csrcGenerator(projectInfo)
82 while makefile.find(key) != -1:
83 makefile = makefile.replace(key, mkData[key])
86 def makefileGenerator(projectInfo, makefile):
88 Generate the Makefile for the current project.
90 # TODO: write a general function that works for both the mk file and the Makefile
91 while makefile.find("project_name") != -1:
92 makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
95 def csrcGenerator(projectInfo):
96 modules = projectInfo.info("MODULES")
98 for module, information in modules.items():
99 if information["enabled"]:
100 for filename, path in findDefinitions(module + ".c", projectInfo):
101 files.append(path + "/" + filename)
102 for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
103 files.append(path + "/" + filename)
104 for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
105 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
106 files.append(path + "/" + filename)
107 csrc = " \\\n\t".join(files)
111 path = os.environ["PATH"]
113 path = path.split(";")
115 path = path.split(":")
118 def findToolchains(pathList):
120 for element in pathList:
121 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
122 if not os.path.islink(toolchain):
123 toolchains.append(toolchain)
124 return list(set(toolchains))
126 def getToolchainInfo(output):
128 expr = re.compile("Target: .*")
129 target = expr.findall(output)
131 info["target"] = target[0].split("Target: ")[1]
132 expr = re.compile("gcc version [0-9,.]*")
133 version = expr.findall(output)
134 if len(version) == 1:
135 info["version"] = version[0].split("gcc version ")[1]
136 expr = re.compile("gcc version [0-9,.]* \(.*\)")
137 build = expr.findall(output)
139 build = build[0].split("gcc version ")[1]
140 build = build[build.find("(") + 1 : build.find(")")]
141 info["build"] = build
142 expr = re.compile("Configured with: .*")
143 configured = expr.findall(output)
144 if len(configured) == 1:
145 info["configured"] = configured[0].split("Configured with: ")[1]
146 expr = re.compile("Thread model: .*")
147 thread = expr.findall(output)
149 info["thread"] = thread[0].split("Thread model: ")[1]
152 def loadSourceTree(project):
153 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
154 project.setInfo("FILE_LIST", fileList)
156 def findDefinitions(ftype, project):
157 L = project.info("FILE_LIST")
160 for filename in element[2]:
161 if fnmatch.fnmatch(filename, ftype):
162 definitions.append((filename, element[0]))
165 def loadCpuInfos(project):
167 for definition in findDefinitions(const.CPU_DEFINITION, project):
168 cpuInfos.append(getInfos(definition))
171 def getInfos(definition):
173 D.update(const.CPU_DEF)
174 def include(filename, dict = D, directory=definition[1]):
175 execfile(directory + "/" + filename, {}, D)
176 D["include"] = include
177 include(definition[0], D)
178 D["CPU_NAME"] = definition[0].split(".")[0]
179 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
183 def getCommentList(string):
184 commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
185 commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
188 def loadModuleDefinition(first_comment):
190 moduleDefinition = {}
191 for num, line in enumerate(first_comment):
192 index = line.find("$WIZ$")
196 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
198 raise ParseError(num, line[index:])
199 elif line.find("\\brief") != -1:
200 moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
202 if "module_name" in moduleDefinition.keys():
203 moduleDict[moduleDefinition["module_name"]] = {}
204 if "module_depends" in moduleDefinition.keys():
205 if type(moduleDefinition["module_depends"]) == str:
206 moduleDefinition["module_depends"] = (moduleDefinition["module_depends"],)
207 moduleDict[moduleDefinition["module_name"]]["depends"] = moduleDefinition["module_depends"]
209 moduleDict[moduleDefinition["module_name"]]["depends"] = ()
210 if "module_configuration" in moduleDefinition.keys():
211 moduleDict[moduleDefinition["module_name"]]["configuration"] = moduleDefinition["module_configuration"]
213 moduleDict[moduleDefinition["module_name"]]["configuration"] = ""
214 if "module_description" in moduleDefinition.keys():
215 moduleDict[moduleDefinition["module_name"]]["description"] = moduleDefinition["module_description"]
216 moduleDict[moduleDefinition["module_name"]]["enabled"] = False
217 return toBeParsed, moduleDict
219 def loadDefineLists(commentList):
221 for comment in commentList:
222 for num, line in enumerate(comment):
223 index = line.find("$WIZ$")
226 exec line[index + len("$WIZ$ "):] in {}, defineList
228 raise ParseError(num, line[index:])
229 for key, value in defineList.items():
230 if type(value) == str:
231 defineList[key] = (value,)
234 def getDescriptionInformations(comment):
236 Take the doxygen comment and strip the wizard informations, returning the tuple
237 (comment, wizard_information)
242 for num, line in enumerate(comment):
243 index = line.find("$WIZ$")
246 brief += line[:index].strip()
248 description += " " + line[:index]
250 exec line[index + len("$WIZ$ "):] in {}, information
252 raise ParseError(num, line[index:])
255 brief += line.strip()
257 description += " " + line
258 description = description.strip()
259 return brief.strip(), description.strip(), information
261 def getDefinitionBlocks(text):
263 Take a text and return a list of tuple (description, name-value).
266 block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
267 for comment, define in block_tmp:
268 # Only the first element is needed
269 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
270 for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
271 block.append(([comment], define))
272 for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
273 block.append(([comment], define))
276 def loadModuleData(project):
279 configurationInfoDict = {}
280 for filename, path in findDefinitions("*.h", project):
281 commentList = getCommentList(open(path + "/" + filename, "r").read())
282 if len(commentList) > 0:
284 configurationInfo = {}
286 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
287 except ParseError, err:
288 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
289 for module, information in moduleDict.items():
290 information["category"] = os.path.basename(path)
291 if "configuration" in information.keys() and len(information["configuration"]):
292 configuration = moduleDict[module]["configuration"]
294 configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
295 except ParseError, err:
296 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
297 moduleInfoDict.update(moduleDict)
298 configurationInfoDict.update(configurationInfo)
301 listDict = loadDefineLists(commentList[1:])
302 listInfoDict.update(listDict)
303 except ParseError, err:
304 raise DefineException.EnumDefineException(path, err.line_number, err.line)
305 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
306 commentList = getCommentList(open(path + "/" + filename, "r").read())
307 listInfoDict.update(loadDefineLists(commentList))
308 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
309 for filename, path in findDefinitions("*_" + tag + ".h", project):
310 commentList = getCommentList(open(path + "/" + filename, "r").read())
311 listInfoDict.update(loadDefineLists(commentList))
312 project.setInfo("MODULES", moduleInfoDict)
313 project.setInfo("LISTS", listInfoDict)
314 project.setInfo("CONFIGURATIONS", configurationInfoDict)
316 def formatParamNameValue(text):
318 Take the given string and return a tuple with the name of the parameter in the first position
319 and the value in the second.
321 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
324 def loadConfigurationInfos(path):
326 Return the module configurations found in the given file as a dict with the
327 parameter name as key and a dict containig the fields above as value:
328 "value": the value of the parameter
329 "description": the description of the parameter
330 "informations": a dict containig optional informations:
331 "type": "int" | "boolean" | "enum"
332 "min": the minimum value for integer parameters
333 "max": the maximum value for integer parameters
334 "long": boolean indicating if the num is a long
335 "value_list": the name of the enum for enum parameters
337 configurationInfos = {}
338 for comment, define in getDefinitionBlocks(open(path, "r").read()):
339 name, value = formatParamNameValue(define)
340 brief, description, informations = getDescriptionInformations(comment)
341 configurationInfos[name] = {}
342 configurationInfos[name]["value"] = value
343 configurationInfos[name]["informations"] = informations
344 if ("type" in configurationInfos[name]["informations"].keys() and
345 configurationInfos[name]["informations"]["type"] == "int" and
346 configurationInfos[name]["value"].find("L") != -1):
347 configurationInfos[name]["informations"]["long"] = True
348 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
349 if ("type" in configurationInfos[name]["informations"].keys() and
350 configurationInfos[name]["informations"]["type"] == "int" and
351 configurationInfos[name]["value"].find("U") != -1):
352 configurationInfos[name]["informations"]["unsigned"] = True
353 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
354 configurationInfos[name]["description"] = description
355 configurationInfos[name]["brief"] = brief
356 return configurationInfos
358 def sub(string, parameter, value):
360 Substitute the given value at the given parameter define in the given string
362 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
364 def isInt(informations):
366 Return True if the value is a simple int.
368 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
373 def isLong(informations):
375 Return True if the value is a long.
377 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
382 def isUnsigned(informations):
384 Return True if the value is an unsigned.
386 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
391 def isUnsignedLong(informations):
393 Return True if the value is an unsigned long.
395 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
400 class ParseError(Exception):
401 def __init__(self, line_number, line):
402 Exception.__init__(self)
403 self.line_number = line_number