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)
81 mkData["$prefix"] = os.path.basename(projectInfo.info("TOOLCHAIN")["path"]).split("gcc")[0]
82 mkData["$suffix"] = os.path.basename(projectInfo.info("TOOLCHAIN")["path"]).split("gcc")[1]
84 while makefile.find(key) != -1:
85 makefile = makefile.replace(key, mkData[key])
88 def makefileGenerator(projectInfo, makefile):
90 Generate the Makefile for the current project.
92 # TODO: write a general function that works for both the mk file and the Makefile
93 while makefile.find("project_name") != -1:
94 makefile = makefile.replace("project_name", os.path.basename(projectInfo.info("PROJECT_PATH")))
97 def csrcGenerator(projectInfo):
98 modules = projectInfo.info("MODULES")
100 for module, information in modules.items():
101 if information["enabled"]:
102 for filename, path in findDefinitions(module + ".c", projectInfo):
103 files.append(path + "/" + filename)
104 for filename, path in findDefinitions(module + "_" + projectInfo.info("CPU_INFOS")["TOOLCHAIN"] + ".c", projectInfo):
105 files.append(path + "/" + filename)
106 for tag in projectInfo.info("CPU_INFOS")["CPU_TAGS"]:
107 for filename, path in findDefinitions(module + "_" + tag + ".c", projectInfo):
108 files.append(path + "/" + filename)
109 csrc = " \\\n\t".join(files) + " \\"
113 path = os.environ["PATH"]
115 path = path.split(";")
117 path = path.split(":")
120 def findToolchains(pathList):
122 for element in pathList:
123 for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
124 toolchains.append(toolchain)
125 return list(set(toolchains))
127 def getToolchainInfo(output):
129 expr = re.compile("Target: .*")
130 target = expr.findall(output)
132 info["target"] = target[0].split("Target: ")[1]
133 expr = re.compile("gcc version [0-9,.]*")
134 version = expr.findall(output)
135 if len(version) == 1:
136 info["version"] = version[0].split("gcc version ")[1]
137 expr = re.compile("gcc version [0-9,.]* \(.*\)")
138 build = expr.findall(output)
140 build = build[0].split("gcc version ")[1]
141 build = build[build.find("(") + 1 : build.find(")")]
142 info["build"] = build
143 expr = re.compile("Configured with: .*")
144 configured = expr.findall(output)
145 if len(configured) == 1:
146 info["configured"] = configured[0].split("Configured with: ")[1]
147 expr = re.compile("Thread model: .*")
148 thread = expr.findall(output)
150 info["thread"] = thread[0].split("Thread model: ")[1]
153 def loadSourceTree(project):
154 fileList = [f for f in os.walk(project.info("SOURCES_PATH"))]
155 project.setInfo("FILE_LIST", fileList)
157 def findDefinitions(ftype, project):
158 L = project.info("FILE_LIST")
161 for filename in element[2]:
162 if fnmatch.fnmatch(filename, ftype):
163 definitions.append((filename, element[0]))
166 def loadCpuInfos(project):
168 for definition in findDefinitions(const.CPU_DEFINITION, project):
169 cpuInfos.append(getInfos(definition))
172 def getInfos(definition):
174 D.update(const.CPU_DEF)
175 def include(filename, dict = D, directory=definition[1]):
176 execfile(directory + "/" + filename, {}, D)
177 D["include"] = include
178 include(definition[0], D)
179 D["CPU_NAME"] = definition[0].split(".")[0]
180 D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
184 def getCommentList(string):
185 commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
186 commentList = [re.findall(r"^\s*\* *(.*?)$", comment, re.MULTILINE) for comment in commentList]
189 def loadModuleDefinition(first_comment):
191 moduleDefinition = {}
192 for num, line in enumerate(first_comment):
193 index = line.find("$WIZ$")
197 exec line[index + len("$WIZ$ "):] in {}, moduleDefinition
199 raise ParseError(num, line[index:])
200 elif line.find("\\brief") != -1:
201 moduleDefinition["module_description"] = line[line.find("\\brief") + len("\\brief "):]
203 if "module_name" in moduleDefinition.keys():
204 moduleDict[moduleDefinition["module_name"]] = {}
205 if "module_depends" in moduleDefinition.keys():
206 if type(moduleDefinition["module_depends"]) == str:
207 moduleDefinition["module_depends"] = (moduleDefinition["module_depends"],)
208 moduleDict[moduleDefinition["module_name"]]["depends"] = moduleDefinition["module_depends"]
210 moduleDict[moduleDefinition["module_name"]]["depends"] = ()
211 if "module_configuration" in moduleDefinition.keys():
212 moduleDict[moduleDefinition["module_name"]]["configuration"] = moduleDefinition["module_configuration"]
214 moduleDict[moduleDefinition["module_name"]]["configuration"] = ""
215 if "module_description" in moduleDefinition.keys():
216 moduleDict[moduleDefinition["module_name"]]["description"] = moduleDefinition["module_description"]
217 moduleDict[moduleDefinition["module_name"]]["enabled"] = False
218 return toBeParsed, moduleDict
220 def loadDefineLists(commentList):
222 for comment in commentList:
223 for num, line in enumerate(comment):
224 index = line.find("$WIZ$")
227 exec line[index + len("$WIZ$ "):] in {}, defineList
229 raise ParseError(num, line[index:])
230 for key, value in defineList.items():
231 if type(value) == str:
232 defineList[key] = (value,)
235 def getDescriptionInformations(comment):
237 Take the doxygen comment and strip the wizard informations, returning the tuple
238 (comment, wizard_information)
243 for num, line in enumerate(comment):
244 index = line.find("$WIZ$")
247 brief += line[:index].strip()
249 description += " " + line[:index]
251 exec line[index + len("$WIZ$ "):] in {}, information
253 raise ParseError(num, line[index:])
256 brief += line.strip()
258 description += " " + line
259 description = description.strip()
260 return brief.strip(), description.strip(), information
262 def getDefinitionBlocks(text):
264 Take a text and return a list of tuple (description, name-value).
267 block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
268 for comment, define in block_tmp:
269 # Only the first element is needed
270 block.append(([re.findall(r"^\s*\* *(.*?)$", line, re.MULTILINE)[0] for line in comment.splitlines()], define))
271 for comment, define in re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
272 block.append(([comment], define))
273 for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE):
274 block.append(([comment], define))
277 def loadModuleData(project):
280 configurationInfoDict = {}
281 for filename, path in findDefinitions("*.h", project):
282 commentList = getCommentList(open(path + "/" + filename, "r").read())
283 if len(commentList) > 0:
285 configurationInfo = {}
287 toBeParsed, moduleDict = loadModuleDefinition(commentList[0])
288 except ParseError, err:
289 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
290 for module, information in moduleDict.items():
291 information["category"] = os.path.basename(path)
292 if "configuration" in information.keys() and len(information["configuration"]):
293 configuration = moduleDict[module]["configuration"]
295 configurationInfo[configuration] = loadConfigurationInfos(project.info("SOURCES_PATH") + "/" + configuration)
296 except ParseError, err:
297 raise DefineException.ConfigurationDefineException(project.info("SOURCES_PATH") + "/" + configuration, err.line_number, err.line)
298 moduleInfoDict.update(moduleDict)
299 configurationInfoDict.update(configurationInfo)
302 listDict = loadDefineLists(commentList[1:])
303 listInfoDict.update(listDict)
304 except ParseError, err:
305 raise DefineException.EnumDefineException(path, err.line_number, err.line)
306 for filename, path in findDefinitions("*_" + project.info("CPU_INFOS")["TOOLCHAIN"] + ".h", project):
307 commentList = getCommentList(open(path + "/" + filename, "r").read())
308 listInfoDict.update(loadDefineLists(commentList))
309 for tag in project.info("CPU_INFOS")["CPU_TAGS"]:
310 for filename, path in findDefinitions("*_" + tag + ".h", project):
311 commentList = getCommentList(open(path + "/" + filename, "r").read())
312 listInfoDict.update(loadDefineLists(commentList))
313 project.setInfo("MODULES", moduleInfoDict)
314 project.setInfo("LISTS", listInfoDict)
315 project.setInfo("CONFIGURATIONS", configurationInfoDict)
317 def formatParamNameValue(text):
319 Take the given string and return a tuple with the name of the parameter in the first position
320 and the value in the second.
322 block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
325 def loadConfigurationInfos(path):
327 Return the module configurations found in the given file as a dict with the
328 parameter name as key and a dict containig the fields above as value:
329 "value": the value of the parameter
330 "description": the description of the parameter
331 "informations": a dict containig optional informations:
332 "type": "int" | "boolean" | "enum"
333 "min": the minimum value for integer parameters
334 "max": the maximum value for integer parameters
335 "long": boolean indicating if the num is a long
336 "value_list": the name of the enum for enum parameters
338 configurationInfos = {}
339 for comment, define in getDefinitionBlocks(open(path, "r").read()):
340 name, value = formatParamNameValue(define)
341 brief, description, informations = getDescriptionInformations(comment)
342 configurationInfos[name] = {}
343 configurationInfos[name]["value"] = value
344 configurationInfos[name]["informations"] = informations
345 if ("type" in configurationInfos[name]["informations"].keys() and
346 configurationInfos[name]["informations"]["type"] == "int" and
347 configurationInfos[name]["value"].find("L") != -1):
348 configurationInfos[name]["informations"]["long"] = True
349 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("L", "")
350 if ("type" in configurationInfos[name]["informations"].keys() and
351 configurationInfos[name]["informations"]["type"] == "int" and
352 configurationInfos[name]["value"].find("U") != -1):
353 configurationInfos[name]["informations"]["unsigned"] = True
354 configurationInfos[name]["value"] = configurationInfos[name]["value"].replace("U", "")
355 configurationInfos[name]["description"] = description
356 configurationInfos[name]["brief"] = brief
357 return configurationInfos
359 def sub(string, parameter, value):
361 Substitute the given value at the given parameter define in the given string
363 return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)
365 def isInt(informations):
367 Return True if the value is a simple int.
369 if ("long" not in informatios.keys() or not informations["long"]) and ("unsigned" not in informations.keys() or informations["unsigned"]):
374 def isLong(informations):
376 Return True if the value is a long.
378 if "long" in informations.keys() and informations["long"] and "unsigned" not in informations.keys():
383 def isUnsigned(informations):
385 Return True if the value is an unsigned.
387 if "unsigned" in informations.keys() and informations["unsigned"] and "long" not in informations.keys():
392 def isUnsignedLong(informations):
394 Return True if the value is an unsigned long.
396 if "unsigned" in informations.keys() and "long" in informations.keys() and informations["unsigned"] and informations["long"]:
401 class ParseError(Exception):
402 def __init__(self, line_number, line):
403 Exception.__init__(self)
404 self.line_number = line_number