Salome HOME
Add the config mechanism for the sat bases
[tools/sat.git] / src / __init__.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import shutil
21 import errno
22 import stat
23
24 from . import pyconf
25 from . import architecture
26 from . import printcolors
27 from . import options
28 from . import system
29 from . import ElementTree
30 from . import logger
31 from . import product
32 from . import environment
33 from . import fileEnviron
34 from . import compilation
35 from . import test_module
36
37 OK_STATUS = "OK"
38 KO_STATUS = "KO"
39 NA_STATUS = "NA"
40 KNOWNFAILURE_STATUS = "KF"
41 TIMEOUT_STATUS = "TIMEOUT"
42
43 CONFIG_FILENAME = "sat-config.pyconf"
44
45 class SatException(Exception):
46     '''rename Exception Class
47     '''
48     pass
49
50 def ensure_path_exists(p):
51     '''Create a path if not existing
52     
53     :param p str: The path.
54     '''
55     if not os.path.exists(p):
56         os.makedirs(p)
57         
58 def check_config_has_application( config, details = None ):
59     '''check that the config has the key APPLICATION. Else raise an exception.
60     
61     :param config class 'common.pyconf.Config': The config.
62     '''
63     if 'APPLICATION' not in config:
64         message = _("An APPLICATION is required. Use 'config --list' to get"
65                     " the list of available applications.\n")
66         if details :
67             details.append(message)
68         raise SatException( message )
69
70 def check_config_has_profile( config, details = None ):
71     '''check that the config has the key APPLICATION.profile.
72        Else, raise an exception.
73     
74     :param config class 'common.pyconf.Config': The config.
75     '''
76     check_config_has_application(config)
77     if 'profile' not in config.APPLICATION:
78         message = _("A profile section is required in your application.\n")
79         if details :
80             details.append(message)
81         raise SatException( message )
82
83 def config_has_application( config ):
84     return 'APPLICATION' in config
85
86 def get_cfg_param(config, param_name, default):
87     '''Search for param_name value in config.
88        If param_name is not in config, then return default,
89        else, return the found value
90        
91     :param config class 'common.pyconf.Config': The config.
92     :param param_name str: the name of the parameter to get the value
93     :param default str: The value to return if param_name is not in config
94     :return: see initial description of the function
95     :rtype: str
96     '''
97     if param_name in config:
98         return config[param_name]
99     return default
100
101 def print_info(logger, info):
102     '''Prints the tuples that are in info variable in a formatted way.
103     
104     :param logger Logger: The logging instance to use for the prints.
105     :param info list: The list of tuples to display
106     '''
107     # find the maximum length of the first value of the tuples in info
108     smax = max(map(lambda l: len(l[0]), info))
109     # Print each item of info with good indentation
110     for i in info:
111         sp = " " * (smax - len(i[0]))
112         printcolors.print_value(logger, sp + i[0], i[1], 2)
113     logger.write("\n", 2)
114
115 def get_base_path(config):
116     '''Returns the path of the product base.
117     
118     :param config Config: The global Config instance.
119     :return: The path of the product base.
120     :rtype: str
121     '''
122     if "base" in config.SITE:
123         base_path = config.SITE.base
124     else:
125         # default base
126         base_path = config.USER.base
127     return base_path
128
129 def get_salome_version(config):
130     if hasattr(config.APPLICATION, 'version_salome'):
131         Version = config.APPLICATION.version_salome
132     else:
133         KERNEL_info = product.get_product_config(config, "KERNEL")
134         VERSION = os.path.join(
135                             KERNEL_info.install_dir,
136                             "bin",
137                             "salome",
138                             "VERSION")
139         if not os.path.isfile(VERSION):
140             return None
141             
142         fVERSION = open(VERSION)
143         Version = fVERSION.readline()
144         fVERSION.close()
145         
146     VersionSalome = int(only_numbers(Version))    
147     return VersionSalome
148
149 def only_numbers(str_num):
150     return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
151
152 def read_config_from_a_file(filePath):
153         try:
154             cfg_file = pyconf.Config(filePath)
155         except pyconf.ConfigError as e:
156             raise SatException(_("Error in configuration file: %(file)s\n  %(error)s") % \
157                 { 'file': filePath, 'error': str(e) })
158         return cfg_file
159
160 def get_tmp_filename(cfg, name):
161     if not os.path.exists(cfg.VARS.tmp_root):
162         os.makedirs(cfg.VARS.tmp_root)
163
164     return os.path.join(cfg.VARS.tmp_root, name)
165
166 ##
167 # Utils class to simplify path manipulations.
168 class Path:
169     def __init__(self, path):
170         self.path = str(path)
171
172     def __add__(self, other):
173         return Path(os.path.join(self.path, str(other)))
174
175     def __abs__(self):
176         return Path(os.path.abspath(self.path))
177
178     def __str__(self):
179         return self.path
180
181     def __eq__(self, other):
182         return self.path == other.path
183
184     def exists(self):
185         return self.islink() or os.path.exists(self.path)
186
187     def islink(self):
188         return os.path.islink(self.path)
189
190     def isdir(self):
191         return os.path.isdir(self.path)
192
193     def list(self):
194         return [Path(p) for p in os.listdir(self.path)]
195
196     def dir(self):
197         return Path(os.path.dirname(self.path))
198
199     def base(self):
200         return Path(os.path.basename(self.path))
201
202     def make(self, mode=None):
203         os.makedirs(self.path)        
204         if mode:
205             os.chmod(self.path, mode)
206         
207     def chmod(self, mode):
208         os.chmod(self.path, mode)
209
210     def rm(self):    
211         if self.islink():
212             os.remove(self.path)
213         else:
214             shutil.rmtree( self.path, onerror = handleRemoveReadonly )
215
216     def copy(self, path, smart=False):
217         if not isinstance(path, Path):
218             path = Path(path)
219
220         if os.path.islink(self.path):
221             return self.copylink(path)
222         elif os.path.isdir(self.path):
223             return self.copydir(path, smart)
224         else:
225             return self.copyfile(path)
226
227     def smartcopy(self, path):
228         return self.copy(path, True)
229
230     def readlink(self):
231         if self.islink():
232             return os.readlink(self.path)
233         else:
234             return False
235
236     def symlink(self, path):
237         try:
238             os.symlink(str(path), self.path)
239             return True
240         except:
241             return False
242
243     def copylink(self, path):
244         try:
245             os.symlink(os.readlink(self.path), str(path))
246             return True
247         except:
248             return False
249
250     def copydir(self, dst, smart=False):
251         try:
252             names = self.list()
253
254             if not dst.exists():
255                 dst.make()
256
257             for name in names:
258                 if name == dst:
259                     continue
260                 if smart and (str(name) in [".git", "CVS", ".svn"]):
261                     continue
262                 srcname = self + name
263                 dstname = dst + name
264                 srcname.copy(dstname, smart)
265             return True
266         except:
267             return False
268
269     def copyfile(self, path):
270         try:
271             shutil.copy2(self.path, str(path))
272             return True
273         except:
274             return False
275
276 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
277     """Find in all the directories in lpath list the file that has the same name
278        as file_name. If it is found, return the full path of the file, else,
279        return False. 
280        The additional_dir (optional) is the name of the directory to add to all 
281        paths in lpath.
282     
283     :param file_name str: The file name to search
284     :param lpath List: The list of directories where to search
285     :param additional_dir str: The name of the additional directory
286     :return: the full path of the file or False if not found
287     :rtype: str
288     """
289     for directory in lpath:
290         dir_complete = os.path.join(directory, additional_dir)
291         if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
292             continue
293         l_files = os.listdir(dir_complete)
294         for file_n in l_files:
295             if file_n == file_name:
296                 return os.path.join(dir_complete, file_name)
297     return False
298
299 def handleRemoveReadonly(func, path, exc):
300     excvalue = exc[1]
301     if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
302         os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
303         func(path)
304     else:
305         raise
306
307 def deepcopy_list(input_list):
308     """ Do a deep copy of a list
309     
310     :param input_list List: The list to copy
311     :return: The copy of the list
312     :rtype: List
313     """
314     res = []
315     for elem in input_list:
316         res.append(elem)
317     return res
318
319 def parse_date(date):
320     """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
321     
322     :param date str: The date to transform
323     :return: The date in the new format
324     :rtype: str
325     """
326     if len(date) != 15:
327         return date
328     res = "%s-%s-%s %s:%s:%s" % (date[0:4],
329                                  date[4:6],
330                                  date[6:8],
331                                  date[9:11],
332                                  date[11:13],
333                                  date[13:])
334     return res
335
336 def merge_dicts(*dict_args):
337     '''
338     Given any number of dicts, shallow copy and merge into a new dict,
339     precedence goes to key value pairs in latter dicts.
340     '''
341     result = {}
342     for dictionary in dict_args:
343         result.update(dictionary)
344     return result