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