Change loadModuleData function to be a BProject method.
[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
43 from bertos_utils import (
44                             # Utility functions
45                             isBertosDir, loadCpuInfos, getTagSet, setEnabledModules,
46                             loadConfigurationInfos, loadDefineLists, loadModuleDefinition,
47                             getCommentList, updateConfigurationValues,
48                             
49                             # Custom exceptions
50                             ParseError, SupportedException
51                         )
52
53 class BProject(object):
54     """
55     Simple class for store and retrieve project informations.
56     """
57     
58     def __init__(self, project_file="", info_dict={}):
59         self.infos = {}
60         self._cached_queries = {}
61         if project_file:
62             self.loadBertosProject(project_file, info_dict)
63
64     def loadBertosProject(self, project_file, info_dict):
65         project_dir = os.path.dirname(project_file)
66         project_data = pickle.loads(open(project_file, "r").read())
67         # If PROJECT_NAME is not defined it use the directory name as PROJECT_NAME
68         # NOTE: this can throw an Exception if the user has changed the directory containing the project
69         self.infos["PROJECT_NAME"] = project_data.get("PROJECT_NAME", os.path.basename(project_dir))
70         self.infos["PROJECT_PATH"] = os.path.dirname(project_file)
71         # Check for the Wizard version
72         wizard_version = project_data.get("WIZARD_VERSION", 0)
73         # Ignore the SOURCES_PATH inside the project file
74         project_data["SOURCES_PATH"] = project_dir
75         if "SOURCES_PATH" in info_dict:
76             project_data["SOURCES_PATH"] = info_dict["SOURCES_PATH"]
77         if os.path.exists(project_data["SOURCES_PATH"]):
78             self.infos["SOURCES_PATH"] = project_data["SOURCES_PATH"]
79         else:
80             raise VersionException(self)
81         if not isBertosDir(project_dir):
82             version_file = open(os.path.join(const.DATA_DIR, "vtemplates/VERSION"), "r").read()
83             open(os.path.join(project_dir, "VERSION"), "w").write(version_file.replace("$version", "").strip())
84         self.loadSourceTree()
85         cpu_name = project_data["CPU_NAME"]
86         self.infos["CPU_NAME"] = cpu_name
87         cpu_info = loadCpuInfos(self)
88         for cpu in cpu_info:
89             if cpu["CPU_NAME"] == cpu_name:
90                 self.infos["CPU_INFOS"] = cpu
91                 break
92         tag_list = getTagSet(cpu_info)
93         # Create, fill and store the dict with the tags
94         tag_dict = {}
95         for element in tag_list:
96             tag_dict[element] = False
97         infos = self.info("CPU_INFOS")
98         for tag in tag_dict:
99             if tag in infos["CPU_TAGS"] + [infos["CPU_NAME"], infos["TOOLCHAIN"]]:
100                 tag_dict[tag] = True
101             else:
102                 tag_dict[tag] = False
103         self.infos["ALL_CPU_TAGS"] = tag_dict
104         if "TOOLCHAIN" in info_dict:
105             project_data["TOOLCHAIN"] = info_dict["TOOLCHAIN"]
106         if os.path.exists(project_data["TOOLCHAIN"]["path"]):
107             self.infos["TOOLCHAIN"] = project_data["TOOLCHAIN"]
108         else:
109             raise ToolchainException(self)
110         self.infos["SELECTED_FREQ"] = project_data["SELECTED_FREQ"]
111         self.infos["OUTPUT"] = project_data["OUTPUT"]
112         self.loadModuleData(True)
113         setEnabledModules(self, project_data["ENABLED_MODULES"])
114
115     def loadModuleData(self, edit=False):
116         module_info_dict = {}
117         list_info_dict = {}
118         configuration_info_dict = {}
119         file_dict = {}
120         for filename, path in self.findDefinitions("*.h") + self.findDefinitions("*.c") + self.findDefinitions("*.s") + self.findDefinitions("*.S"):
121             comment_list = getCommentList(open(path + "/" + filename, "r").read())
122             if len(comment_list) > 0:
123                 module_info = {}
124                 configuration_info = {}
125                 try:
126                     to_be_parsed, module_dict = loadModuleDefinition(comment_list[0])
127                 except ParseError, err:
128                     raise DefineException.ModuleDefineException(path, err.line_number, err.line)
129                 for module, information in module_dict.items():
130                     if "depends" not in information:
131                         information["depends"] = ()
132                     information["depends"] += (filename.split(".")[0],)
133                     information["category"] = os.path.basename(path)
134                     if "configuration" in information and len(information["configuration"]):
135                         configuration = module_dict[module]["configuration"]
136                         try:
137                             configuration_info[configuration] = loadConfigurationInfos(self.infos["SOURCES_PATH"] + "/" + configuration)
138                         except ParseError, err:
139                             raise DefineException.ConfigurationDefineException(self.infos["SOURCES_PATH"] + "/" + configuration, err.line_number, err.line)
140                         if edit:
141                             try:
142                                 path = self.infos["PROJECT_NAME"]
143                                 directory = self.infos["PROJECT_PATH"]
144                                 user_configuration = loadConfigurationInfos(directory + "/" + configuration.replace("bertos", path))
145                                 configuration_info[configuration] = updateConfigurationValues(configuration_info[configuration], user_configuration)
146                             except ParseError, err:
147                                 raise DefineException.ConfigurationDefineException(directory + "/" + configuration.replace("bertos", path))
148                 module_info_dict.update(module_dict)
149                 configuration_info_dict.update(configuration_info)
150                 if to_be_parsed:
151                     try:
152                         list_dict = loadDefineLists(comment_list[1:])
153                         list_info_dict.update(list_dict)
154                     except ParseError, err:
155                         raise DefineException.EnumDefineException(path, err.line_number, err.line)
156         for filename, path in self.findDefinitions("*_" + self.infos["CPU_INFOS"]["TOOLCHAIN"] + ".h"):
157             comment_list = getCommentList(open(path + "/" + filename, "r").read())
158             list_info_dict.update(loadDefineLists(comment_list))
159         for tag in self.infos["CPU_INFOS"]["CPU_TAGS"]:
160             for filename, path in self.findDefinitions("*_" + tag + ".h"):
161                 comment_list = getCommentList(open(path + "/" + filename, "r").read())
162                 list_info_dict.update(loadDefineLists(comment_list))
163         self.infos["MODULES"] = module_info_dict
164         self.infos["LISTS"] = list_info_dict
165         self.infos["CONFIGURATIONS"] = configuration_info_dict
166         self.infos["FILES"] = file_dict
167
168
169     def setInfo(self, key, value):
170         """
171         Store the given value with the name key.
172         """
173         self.infos[key] = value
174     
175     def info(self, key, default=None):
176         """
177         Retrieve the value associated with the name key.
178         """
179         if key in self.infos:
180             return copy.deepcopy(self.infos[key])
181         return default
182
183     def loadSourceTree(self):
184         # Index only the SOURCES_PATH/bertos content
185         bertos_sources_dir = os.path.join(self.info("SOURCES_PATH"), 'bertos')
186         file_dict = {}
187         if os.path.exists(bertos_sources_dir):
188             for element in os.walk(bertos_sources_dir):
189                 for f in element[2]:
190                     file_dict[f] = file_dict.get(f, []) + [element[0]]
191         self.infos["FILE_DICT"] = file_dict
192
193     def searchFiles(self, filename):
194         file_dict = self.infos["FILE_DICT"]
195         return [(filename, dirname) for dirname in file_dict.get(filename, [])]
196
197     def findDefinitions(self, ftype):
198         definitions = self._cached_queries.get(ftype, None)
199         if definitions is not None:
200             return definitions
201         file_dict = self.infos["FILE_DICT"]
202         definitions = []
203         for filename in file_dict:
204             if fnmatch.fnmatch(filename, ftype):
205                 definitions += [(filename, dirname) for dirname in file_dict.get(filename, [])]
206         self._cached_queries[ftype] = definitions
207         return definitions
208
209     def __repr__(self):
210         return repr(self.infos)