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