4 # This file is part of BeRTOS.
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.
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.
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
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.
29 # Copyright 2008 Develer S.r.l. (http://www.develer.com/)
33 # Author: Lorenzo Berni <duplo@develer.com>
41 import DefineException
43 from LoadException import VersionException, ToolchainException
47 from bertos_utils import (
49 isBertosDir, getTagSet, getInfos, updateConfigurationValues,
50 loadConfigurationInfos, loadDefineLists, loadModuleDefinition,
54 ParseError, SupportedException
57 class BProject(object):
59 Simple class for store and retrieve project informations.
62 def __init__(self, project_file="", info_dict={}):
64 self._cached_queries = {}
66 self.loadBertosProject(project_file, info_dict)
68 #--- Load methods (methods that loads data into project) ------------------#
70 def loadBertosProject(self, project_file, info_dict):
71 project_dir = os.path.dirname(project_file)
72 project_data = pickle.loads(open(project_file, "r").read())
73 # If PROJECT_NAME is not defined it use the directory name as PROJECT_NAME
74 # NOTE: this can throw an Exception if the user has changed the directory containing the project
75 self.infos["PROJECT_NAME"] = project_data.get("PROJECT_NAME", os.path.basename(project_dir))
76 self.infos["PROJECT_PATH"] = os.path.dirname(project_file)
78 # Check for the Wizard version
79 wizard_version = project_data.get("WIZARD_VERSION", 0)
80 if wizard_version < 1:
81 # Ignore the SOURCES_PATH inside the project file for older projects
82 project_data["SOURCES_PATH"] = project_dir
83 self.loadBertosSourceStuff(project_data, info_dict.get("SOURCES_PATH", None))
85 # For those projects that don't have a VERSION file create a dummy one.
86 if not isBertosDir(project_dir):
87 version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
88 open(os.path.join(project_dir, "VERSION"), "w").write(version_file.replace("$version", "").strip())
91 self.loadCpuStuff(project_data)
92 self.loadToolchainStuff(project_data, info_dict.get("TOOLCHAIN", None))
93 self.infos["OUTPUT"] = project_data["OUTPUT"]
94 self.loadModuleData(True)
95 self.setEnabledModules(project_data["ENABLED_MODULES"])
97 def loadBertosSourceStuff(self, project_data, forced_version=None):
98 bertos_source_path = project_data["SOURCES_PATH"]
100 bertos_source_path = forced_version
101 if os.path.exists(bertos_source_path):
102 self.infos["SOURCES_PATH"] = bertos_source_path
104 raise VersionException(self)
106 def loadCpuStuff(self, project_data):
107 cpu_name = project_data["CPU_NAME"]
108 self.infos["CPU_NAME"] = cpu_name
109 cpu_info = self.getCpuInfos()
111 if cpu["CPU_NAME"] == cpu_name:
112 self.infos["CPU_INFOS"] = cpu
114 tag_list = getTagSet(cpu_info)
115 # Create, fill and store the dict with the tags
117 for element in tag_list:
118 tag_dict[element] = False
119 infos = self.info("CPU_INFOS")
121 if tag in infos["CPU_TAGS"] + [infos["CPU_NAME"], infos["TOOLCHAIN"]]:
124 tag_dict[tag] = False
125 self.infos["ALL_CPU_TAGS"] = tag_dict
126 self.infos["SELECTED_FREQ"] = project_data["SELECTED_FREQ"]
128 def loadToolchainStuff(self, project_data, forced_toolchain=None):
129 toolchain = project_data["TOOLCHAIN"]
131 toolchain = forced_toolchain
132 if os.path.exists(toolchain["path"]):
133 self.infos["TOOLCHAIN"] = toolchain
135 raise ToolchainException(self)
137 def loadProjectFromPreset(self, preset):
139 Load a project from a preset.
140 NOTE: this is a stub.
142 self.loadBertosProject(os.path.join(preset, 'project.bertos'), {})
144 def loadProjectPresets(self):
146 Load the default presets (into the const.PREDEFINED_BOARDS_DIR).
148 # NOTE: this method does nothing (for now).
149 preset_path = os.path.join(self.infos["SOURCES_PATH"], const.PREDEFINED_BOARDS_DIR)
151 if os.path.exists(preset_path):
152 preset_tree = self._loadProjectPresetTree(preset_path)
153 self.infos["PRESET_TREE"] = preset_tree
155 def _loadProjectPresetTree(self, path):
157 _tree['info'] = self._loadPresetInfo(os.path.join(path, const.PREDEFINED_BOARD_SPEC_FILE))
158 _tree['info']['filename'] = os.path.basename(path)
159 _tree['info']['path'] = path
160 _tree['children'] = []
161 entries = set(os.listdir(path))
162 for entry in entries:
163 _path = os.path.join(path, entry)
164 if os.path.isdir(_path):
165 sub_entries = set(os.listdir(_path))
166 if const.PREDEFINED_BOARD_SPEC_FILE in sub_entries:
167 _tree['children'].append(self._loadProjectPresetTree(_path))
168 # Add into the info dict the dir type (dir/project)
169 if _tree['children']:
170 _tree['info']['type'] = 'dir'
172 _tree['info']['type'] = 'project'
175 def _loadPresetInfo(self, preset_spec_file):
177 execfile(preset_spec_file, {}, D)
180 def loadModuleData(self, edit=False):
181 module_info_dict = {}
183 configuration_info_dict = {}
185 for filename, path in self.findDefinitions("*.h") + self.findDefinitions("*.c") + self.findDefinitions("*.s") + self.findDefinitions("*.S"):
186 comment_list = getCommentList(open(path + "/" + filename, "r").read())
187 if len(comment_list) > 0:
189 configuration_info = {}
191 to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
192 except ParseError, err:
193 raise DefineException.ModuleDefineException(path, err.line_number, err.line)
194 for module, information in module_dict.items():
195 if "depends" not in information:
196 information["depends"] = ()
197 information["depends"] += (filename.split(".")[0],)
198 information["category"] = os.path.basename(path)
199 if "configuration" in information and len(information["configuration"]):
200 configuration = module_dict[module]["configuration"]
202 configuration_info[configuration] = loadConfigurationInfos(self.infos["SOURCES_PATH"] + "/" + configuration)
203 except ParseError, err:
204 raise DefineException.ConfigurationDefineException(self.infos["SOURCES_PATH"] + "/" + configuration, err.line_number, err.line)
207 path = self.infos["PROJECT_NAME"]
208 directory = self.infos["PROJECT_PATH"]
209 user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
210 configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
211 except ParseError, err:
212 raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
213 module_info_dict.update(module_dict)
214 configuration_info_dict.update(configuration_info)
217 list_dict = loadDefineLists(comment_list[1:])
218 list_info_dict.update(list_dict)
219 except ParseError, err:
220 raise DefineException.EnumDefineException(path, err.line_number, err.line)
221 for tag in self.infos["CPU_INFOS"]["CPU_TAGS"]:
222 for filename, path in self.findDefinitions("*_" + tag + ".h"):
223 comment_list = getCommentList(open(path + "/" + filename, "r").read())
224 list_info_dict.update(loadDefineLists(comment_list))
225 self.infos["MODULES"] = module_info_dict
226 self.infos["LISTS"] = list_info_dict
227 self.infos["CONFIGURATIONS"] = configuration_info_dict
228 self.infos["FILES"] = file_dict
230 def loadSourceTree(self):
232 Index BeRTOS source and load it in memory.
234 # Index only the SOURCES_PATH/bertos content
235 bertos_sources_dir = os.path.join(self.info("SOURCES_PATH"), 'bertos')
237 if os.path.exists(bertos_sources_dir):
238 for element in os.walk(bertos_sources_dir):
240 file_dict[f] = file_dict.get(f, []) + [element[0]]
241 self.infos["FILE_DICT"] = file_dict
243 def reloadCpuInfo(self):
244 for cpu_info in self.getCpuInfos():
245 if cpu_info["CPU_NAME"] == self.infos["CPU_NAME"]:
246 self.infos["CPU_INFOS"] = cpu_info
248 #-------------------------------------------------------------------------#
250 def setInfo(self, key, value):
252 Store the given value with the name key.
254 self.infos[key] = value
256 def info(self, key, default=None):
258 Retrieve the value associated with the name key.
260 if key in self.infos:
261 return copy.deepcopy(self.infos[key])
264 def getCpuInfos(self):
266 for definition in self.findDefinitions(const.CPU_DEFINITION):
267 cpuInfos.append(getInfos(definition))
270 def searchFiles(self, filename):
271 file_dict = self.infos["FILE_DICT"]
272 return [(filename, dirname) for dirname in file_dict.get(filename, [])]
274 def findDefinitions(self, ftype):
275 # Maintain a cache for every scanned SOURCES_PATH
276 definitions_dict = self._cached_queries.get(self.infos["SOURCES_PATH"], {})
277 definitions = definitions_dict.get(ftype, None)
278 if definitions is not None:
280 file_dict = self.infos["FILE_DICT"]
282 for filename in file_dict:
283 if fnmatch.fnmatch(filename, ftype):
284 definitions += [(filename, dirname) for dirname in file_dict.get(filename, [])]
286 # If no cache for the current SOURCES_PATH create an empty one
287 if not definitions_dict:
288 self._cached_queries[self.infos["SOURCES_PATH"]] = {}
289 # Fill the empty cache with the result
290 self._cached_queries[self.infos["SOURCES_PATH"]][ftype] = definitions
293 def setEnabledModules(self, enabled_modules):
294 modules = self.infos["MODULES"]
296 for module, information in modules.items():
297 information["enabled"] = module in enabled_modules
298 if information["enabled"]:
299 for dependency in information["depends"]:
300 if not dependency in modules:
301 files[dependency] = files.get(dependency, 0) + 1
302 self.infos["MODULES"] = modules
303 self.infos["FILES"] = files
306 return repr(self.infos)