Change the target mk file with the name of the project
[bertos.git] / wizard / bertos_utils.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
5 # All rights reserved.
6 #
7 # $Id:$
8 #
9 # Author: Lorenzo Berni <duplo@develer.com>
10 #
11
12 import os
13 import fnmatch
14 import glob
15 import re
16 import shutil
17
18 import const
19
20 def isBertosDir(directory):
21    return os.path.exists(directory + "/VERSION")
22
23 def bertosVersion(directory):
24    return open(directory + "/VERSION").readline().strip()
25
26 def createBertosProject(projectInfos):
27     directory = projectInfos.info("PROJECT_PATH")
28     sourcesDir = projectInfos.info("SOURCES_PATH")
29     if not os.path.isdir(directory):
30         os.mkdir(directory)
31     f = open(directory + "/project.bertos", "w")
32     f.write(repr(projectInfos))
33     f.close()
34     ## Destination source dir
35     srcdir = directory + "/bertos"
36     shutil.rmtree(srcdir, True)
37     shutil.copytree(sourcesDir + "/bertos", srcdir)
38     ## Destination makefile
39     makefile = directory + "/Makefile"
40     if os.path.exists(makefile):
41         os.remove(makefile)
42     makefile = open("mktemplates/Makefile").read()
43     makefile = makefileGenerator(projectInfos, makefile)
44     open(directory + "/Makefile", "w").write(makefile)
45     ## Destination project dir
46     prjdir = directory + "/" + os.path.basename(directory)
47     shutil.rmtree(prjdir, True)
48     os.mkdir(prjdir)
49     ## Destination configurations files
50     cfgdir = prjdir + "/cfg"
51     shutil.rmtree(cfgdir, True)
52     os.mkdir(cfgdir)
53     for key, value in projectInfos.info("CONFIGURATIONS").items():
54         string = open(sourcesDir + "/" + key, "r").read()
55         for parameter, infos in value.items():
56             value = infos["value"]
57             if "long" in infos["informations"].keys() and infos["informations"]["long"]:
58                 value += "L"
59             string = sub(string, parameter, value)
60         f = open(cfgdir + "/" + os.path.basename(key), "w")
61         f.write(string)
62         f.close()
63     ## Destinatio mk file
64     makefile = open("mktemplates/template.mk", "r").read()
65     makefile = mkGenerator(projectInfos, makefile)
66     open(prjdir + "/" + os.path.basename(prjdir) + ".mk", "w").write(makefile)
67
68 def mkGenerator(projectInfos, makefile):
69     """
70     Generates the mk file for the current project.
71     """
72     mkData = {}
73     mkData["pname"] = os.path.basename(projectInfos.info("PROJECT_PATH"))
74     mkData["cpuname"] = projectInfos.info("CPU_INFOS")["CPU_NAME"]
75     mkData["cflags"] = " ".join(projectInfos.info("CPU_INFOS")["C_FLAGS"])
76     mkData["ldflags"] = " ".join(projectInfos.info("CPU_INFOS")["LD_FLAGS"])
77     for key in mkData:
78         while makefile.find(key) != -1:
79             makefile = makefile.replace(key, mkData[key])
80     return makefile
81
82 def makefileGenerator(projectInfos, makefile):
83     """
84     Generate the Makefile for the current project.
85     """
86     # TODO: write a general function that works for both the mk file and the Makefile
87     while makefile.find("project_name") != -1:
88         makefile = makefile.replace("project_name", os.path.basename(projectInfos.info("PROJECT_PATH")))
89     return makefile
90
91 def getSystemPath():
92     path = os.environ["PATH"]
93     if os.name == "nt":
94         path = path.split(";")
95     else:
96         path = path.split(":")
97     return path
98
99 def findToolchains(pathList):
100     toolchains = []
101     for element in pathList:
102         for toolchain in glob.glob(element+ "/" + const.GCC_NAME):
103             if not os.path.islink(toolchain):
104                 toolchains.append(toolchain)
105     return list(set(toolchains))
106
107 def getToolchainInfo(output):
108     info = {}
109     expr = re.compile("Target: .*")
110     target = expr.findall(output)
111     if len(target) == 1:
112         info["target"] = target[0].split("Target: ")[1]
113     expr = re.compile("gcc version [0-9,.]*")
114     version = expr.findall(output)
115     if len(version) == 1:
116         info["version"] = version[0].split("gcc version ")[1]
117     expr = re.compile("gcc version [0-9,.]* \(.*\)")
118     build = expr.findall(output)
119     if len(build) == 1:
120         build = build[0].split("gcc version ")[1]
121         build = build[build.find("(") + 1 : build.find(")")]
122         info["build"] = build
123     expr = re.compile("Configured with: .*")
124     configured = expr.findall(output)
125     if len(configured) == 1:
126         info["configured"] = configured[0].split("Configured with: ")[1]
127     expr = re.compile("Thread model: .*")
128     thread = expr.findall(output)
129     if len(thread) == 1:
130         info["thread"] = thread[0].split("Thread model: ")[1]
131     return info
132
133 def findDefinitions(ftype, path):
134     L = os.walk(path)
135     for element in L:
136         for filename in element[2]:
137             if fnmatch.fnmatch(filename, ftype):
138                 yield (filename, element[0])
139
140 def loadCpuInfos(path):
141     cpuInfos = []
142     for definition in findDefinitions(const.CPU_DEFINITION, path):
143         cpuInfos.append(getInfos(definition))
144     return cpuInfos
145
146 def getInfos(definition):
147     D = {}
148     D.update(const.CPU_DEF)
149     def include(filename, dict = D, directory=definition[1]):
150         execfile(directory + "/" + filename, {}, D)
151     D["include"] = include
152     include(definition[0], D)
153     D["CPU_NAME"] = definition[0].split(".")[0]
154     D["DEFINITION_PATH"] = definition[1] + "/" + definition[0]
155     del D["include"]
156     return D
157
158 def getDefinitionBlocks(text):
159     """
160     Take a text and return a list of tuple (description, name-value).
161     """
162     block = []
163     block_tmp = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
164     for comment, define in block_tmp:
165         block.append((" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip(), define))
166     block += re.findall(r"/{3}\s*([^<].*?)\s*#define\s+((?:[^/]*?/?)+)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)
167     block += [(comment, define) for define, comment in re.findall(r"#define\s*(.*?)\s*/{3}<\s*(.+?)\s*?(?:/{2,3}[^<].*?)?$", text, re.MULTILINE)]
168     return block
169
170 def formatParamNameValue(text):
171     """
172     Take the given string and return a tuple with the name of the parameter in the first position
173     and the value in the second.
174     """
175     block = re.findall("\s*([^\s]+)\s*(.+?)\s*$", text, re.MULTILINE)
176     return block[0]
177
178 def getDescriptionInformations(text): 
179     """ 
180     Take the doxygen comment and strip the wizard informations, returning the tuple 
181     (comment, wizard_informations) 
182     """ 
183     index = text.find("$WIZARD") 
184     if index != -1: 
185         exec(text[index + 1:]) 
186         informations = WIZARD 
187         return text[:index].strip(), informations
188     else:
189         return text.strip(), {}
190
191 def loadConfigurationInfos(path):
192     """
193     Return the module configurations found in the given file as a dict with the
194     parameter name as key and a dict containig the fields above as value:
195         "value": the value of the parameter
196         "description": the description of the parameter
197         "informations": a dict containig optional informations:
198             "type": "int" | "boolean" | "enum"
199             "min": the minimum value for integer parameters
200             "max": the maximum value for integer parameters
201             "long": boolean indicating if the num is a long
202             "value_list": the name of the enum for enum parameters
203     """
204     configurationInfos = {}
205     for comment, define in getDefinitionBlocks(open(path, "r").read()):
206         name, value = formatParamNameValue(define)
207         description, informations = getDescriptionInformations(comment)
208         configurationInfos[name] = {}
209         configurationInfos[name]["value"] = value
210         configurationInfos[name]["informations"] = informations
211         configurationInfos[name]["description"] = description
212     return configurationInfos
213
214 def loadModuleInfos(path):
215     """
216     Return the module infos found in the given file as a dict with the module
217     name as key and a dict containig the fields above as value or an empty dict
218     if the given file is not a BeRTOS module:
219         "depends": a list of modules needed by this module
220         "configuration": the cfg_*.h with the module configurations
221         "description": a string containing the brief description of doxygen
222         "enabled": contains False but the wizard will change if the user select
223         the module
224     """
225     moduleInfos = {}
226     string = open(path, "r").read()
227     commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
228     commentList = [" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip() for comment in commentList]
229     for comment in commentList:
230         index = comment.find("$WIZARD_MODULE")
231         if index != -1:
232             exec(comment[index + 1:])
233             moduleInfos[WIZARD_MODULE["name"]] = {"depends": WIZARD_MODULE["depends"],
234                                                     "configuration": WIZARD_MODULE["configuration"],
235                                                     "description": "",
236                                                     "enabled": False}
237             return moduleInfos
238     return {}
239
240 def loadModuleInfosDict(path):
241     """
242     Return the dict containig all the modules
243     """
244     moduleInfosDict = {}
245     for filename, path in findDefinitions("*.h", path):
246         moduleInfosDict.update(loadModuleInfos(path + "/" + filename))
247     return moduleInfosDict
248
249 def loadDefineLists(path):
250     """
251     Return a dict with the name of the list as key and a list of string as value
252     """
253     string = open(path, "r").read()
254     commentList = re.findall(r"/\*{2}\s*([^*]*\*(?:[^/*][^*]*\*+)*)/", string)
255     commentList = [" ".join(re.findall(r"^\s*\*?\s*(.*?)\s*?(?:/{2}.*?)?$", comment, re.MULTILINE)).strip() for comment in commentList]
256     listDict = {}
257     for comment in commentList:
258         index = comment.find("$WIZARD_LIST")
259         if index != -1:
260             exec(comment[index + 1:])
261             listDict.update(WIZARD_LIST)
262     return listDict
263
264 def loadDefineListsDict(path):
265     """
266     Return the dict containing all the define lists
267     """
268     defineListsDict = {}
269     for filename, path in findDefinitions("*.h", path):
270         defineListsDict.update(loadDefineLists(path + "/" + filename))
271     return defineListsDict
272
273 def sub(string, parameter, value):
274     """
275     Substitute the given value at the given parameter define in the given string
276     """
277     return re.sub(r"(?P<define>#define\s+" + parameter + r"\s+)([^\s]+)", r"\g<define>" + value, string)