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