Add infrastructure for CPU reloading files.
[bertos.git] / wizard / BProject.py
1 #!/usr/bin/env python
2 # encoding: utf-8
3 #
4 # This file is part of BeRTOS.
5 #
6 # Bertos is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19 #
20 # As a special exception, you may use this file as part of a free software
21 # library without restriction.  Specifically, if other files instantiate
22 # templates or use macros or inline functions from this file, or you compile
23 # this file and link it with other files to produce an executable, this
24 # file does not by itself cause the resulting executable to be covered by
25 # the GNU General Public License.  This exception does not however
26 # invalidate any other reasons why the executable file might be covered by
27 # the GNU General Public License.
28 #
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
30 #
31 # $Id$
32 #
33 # Author: Lorenzo Berni <duplo@develer.com>
34 #
35
36 import os
37 import fnmatch
38 import copy
39 import pickle
40
41 import DefineException
42 import const
43
44 from bertos_utils import (
45                             # Utility functions
46                             isBertosDir, getTagSet, setEnabledModules, getInfos,
47                             loadConfigurationInfos, loadDefineLists, loadModuleDefinition,
48                             getCommentList, updateConfigurationValues,
49                             
50                             # Custom exceptions
51                             ParseError, SupportedException
52                         )
53
54 class BProject(object):
55     """
56     Simple class for store and retrieve project informations.
57     """
58     
59     def __init__(self, project_file="", info_dict={}):
60         self.infos = {}
61         self._cached_queries = {}
62         if project_file:
63             self.loadBertosProject(project_file, info_dict)
64
65     def loadBertosProject(self, project_file, info_dict):
66         project_dir = os.path.dirname(project_file)
67         project_data = pickle.loads(open(project_file, "r").read())
68         # If PROJECT_NAME is not defined it use the directory name as PROJECT_NAME
69         # NOTE: this can throw an Exception if the user has changed the directory containing the project
70         self.infos["PROJECT_NAME"] = project_data.get("PROJECT_NAME", os.path.basename(project_dir))
71         self.infos["PROJECT_PATH"] = os.path.dirname(project_file)
72         # Check for the Wizard version
73         wizard_version = project_data.get("WIZARD_VERSION", 0)
74         # Ignore the SOURCES_PATH inside the project file
75         project_data["SOURCES_PATH"] = project_dir
76         if "SOURCES_PATH" in info_dict:
77             project_data["SOURCES_PATH"] = info_dict["SOURCES_PATH"]
78         if os.path.exists(project_data["SOURCES_PATH"]):
79             self.infos["SOURCES_PATH"] = project_data["SOURCES_PATH"]
80         else:
81             raise VersionException(self)
82         if not isBertosDir(project_dir):
83             version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
84             open(os.path.join(project_dir, "VERSION"), "w").write(version_file.replace("$version", "").strip())
85         self.loadSourceTree()
86         cpu_name = project_data["CPU_NAME"]
87         self.infos["CPU_NAME"] = cpu_name
88         cpu_info = self.loadCpuInfos()
89         for cpu in cpu_info:
90             if cpu["CPU_NAME"] == cpu_name:
91                 self.infos["CPU_INFOS"] = cpu
92                 break
93         tag_list = getTagSet(cpu_info)
94         # Create, fill and store the dict with the tags
95         tag_dict = {}
96         for element in tag_list:
97             tag_dict[element] = False
98         infos = self.info("CPU_INFOS")
99         for tag in tag_dict:
100             if tag in infos["CPU_TAGS"] + [infos["CPU_NAME"], infos["TOOLCHAIN"]]:
101                 tag_dict[tag] = True
102             else:
103                 tag_dict[tag] = False
104         self.infos["ALL_CPU_TAGS"] = tag_dict
105         if "TOOLCHAIN" in info_dict:
106             project_data["TOOLCHAIN"] = info_dict["TOOLCHAIN"]
107         if os.path.exists(project_data["TOOLCHAIN"]["path"]):
108             self.infos["TOOLCHAIN"] = project_data["TOOLCHAIN"]
109         else:
110             raise ToolchainException(self)
111         self.infos["SELECTED_FREQ"] = project_data["SELECTED_FREQ"]
112         self.infos["OUTPUT"] = project_data["OUTPUT"]
113         self.loadModuleData(True)
114         setEnabledModules(self, project_data["ENABLED_MODULES"])
115
116     def loadModuleData(self, edit=False):
117         module_info_dict = {}
118         list_info_dict = {}
119         configuration_info_dict = {}
120         file_dict = {}
121         for filename, path in self.findDefinitions("*.h") + self.findDefinitions("*.c") + self.findDefinitions("*.s") + self.findDefinitions("*.S"):
122             comment_list = getCommentList(open(path + "/" + filename, "r").read())
123             if len(comment_list) > 0:
124                 module_info = {}
125                 configuration_info = {}
126                 try:
127                     to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
128                 except ParseError, err:
129                     raise DefineException.ModuleDefineException(path, err.line_number, err.line)
130                 for module, information in module_dict.items():
131                     if "depends" not in information:
132                         information["depends"] = ()
133                     information["depends"] += (filename.split(".")[0],)
134                     information["category"] = os.path.basename(path)
135                     if "configuration" in information and len(information["configuration"]):
136                         configuration = module_dict[module]["configuration"]
137                         try:
138                             configuration_info[configuration] = loadConfigurationInfos(self.infos["SOURCES_PATH"] + "/" + configuration)
139                         except ParseError, err:
140                             raise DefineException.ConfigurationDefineException(self.infos["SOURCES_PATH"] + "/" + configuration, err.line_number, err.line)
141                         if edit:
142                             try:
143                                 path = self.infos["PROJECT_NAME"]
144                                 directory = self.infos["PROJECT_PATH"]
145                                 user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
146                                 configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
147                             except ParseError, err:
148                                 raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
149                 module_info_dict.update(module_dict)
150                 configuration_info_dict.update(configuration_info)
151                 if to_be_parsed:
152                     try:
153                         list_dict = loadDefineLists(comment_list[1:])
154                         list_info_dict.update(list_dict)
155                     except ParseError, err:
156                         raise DefineException.EnumDefineException(path, err.line_number, err.line)
157         for filename, path in self.findDefinitions("*_" + self.infos["CPU_INFOS"]["TOOLCHAIN"] + ".h"):
158             comment_list = getCommentList(open(path + "/" + filename, "r").read())
159             list_info_dict.update(loadDefineLists(comment_list))
160         for tag in self.infos["CPU_INFOS"]["CPU_TAGS"]:
161             for filename, path in self.findDefinitions("*_" + tag + ".h"):
162                 comment_list = getCommentList(open(path + "/" + filename, "r").read())
163                 list_info_dict.update(loadDefineLists(comment_list))
164         self.infos["MODULES"] = module_info_dict
165         self.infos["LISTS"] = list_info_dict
166         self.infos["CONFIGURATIONS"] = configuration_info_dict
167         self.infos["FILES"] = file_dict
168
169     def loadCpuInfos(self):
170         cpuInfos = []
171         for definition in self.findDefinitions(const.CPU_DEFINITION):
172             cpuInfos.append(getInfos(definition))
173         return cpuInfos
174
175     def reloadCpuInfo(self):
176         for cpu_info in self.loadCpuInfos():
177             if cpu_info["CPU_NAME"]:
178                 self.infos["CPU_INFOS"] = cpu_info
179
180     def setInfo(self, key, value):
181         """
182         Store the given value with the name key.
183         """
184         self.infos[key] = value
185     
186     def info(self, key, default=None):
187         """
188         Retrieve the value associated with the name key.
189         """
190         if key in self.infos:
191             return copy.deepcopy(self.infos[key])
192         return default
193
194     def loadSourceTree(self):
195         # Index only the SOURCES_PATH/bertos content
196         bertos_sources_dir = os.path.join(self.info("SOURCES_PATH"), 'bertos')
197         file_dict = {}
198         if os.path.exists(bertos_sources_dir):
199             for element in os.walk(bertos_sources_dir):
200                 for f in element[2]:
201                     file_dict[f] = file_dict.get(f, []) + [element[0]]
202         self.infos["FILE_DICT"] = file_dict
203
204     def searchFiles(self, filename):
205         file_dict = self.infos["FILE_DICT"]
206         return [(filename, dirname) for dirname in file_dict.get(filename, [])]
207
208     def findDefinitions(self, ftype):
209         definitions = self._cached_queries.get(ftype, None)
210         if definitions is not None:
211             return definitions
212         file_dict = self.infos["FILE_DICT"]
213         definitions = []
214         for filename in file_dict:
215             if fnmatch.fnmatch(filename, ftype):
216                 definitions += [(filename, dirname) for dirname in file_dict.get(filename, [])]
217         self._cached_queries[ftype] = definitions
218         return definitions
219
220     def __repr__(self):
221         return repr(self.infos)