Salome HOME
bug fix for options in job
[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" not in config.SITE:
124         site_file_path = os.path.join(config.VARS.salometoolsway,
125                                       "data",
126                                       "site.pyconf")
127         msg = _("Please define a base path in the file %s" % site_file_path)
128         raise SatException(msg)
129
130     return config.SITE.base
131
132 def get_salome_version(config):
133     if hasattr(config.APPLICATION, 'version_salome'):
134         Version = config.APPLICATION.version_salome
135     else:
136         KERNEL_info = product.get_product_config(config, "KERNEL")
137         VERSION = os.path.join(
138                             KERNEL_info.install_dir,
139                             "bin",
140                             "salome",
141                             "VERSION")
142         if not os.path.isfile(VERSION):
143             return None
144             
145         fVERSION = open(VERSION)
146         Version = fVERSION.readline()
147         fVERSION.close()
148         
149     VersionSalome = int(only_numbers(Version))    
150     return VersionSalome
151
152 def only_numbers(str_num):
153     return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
154
155 def read_config_from_a_file(filePath):
156         try:
157             cfg_file = pyconf.Config(filePath)
158         except pyconf.ConfigError as e:
159             raise SatException(_("Error in configuration file: %(file)s\n  %(error)s") % \
160                 { 'file': filePath, 'error': str(e) })
161         return cfg_file
162
163 def get_tmp_filename(cfg, name):
164     if not os.path.exists(cfg.VARS.tmp_root):
165         os.makedirs(cfg.VARS.tmp_root)
166
167     return os.path.join(cfg.VARS.tmp_root, name)
168
169 ##
170 # Utils class to simplify path manipulations.
171 class Path:
172     def __init__(self, path):
173         self.path = str(path)
174
175     def __add__(self, other):
176         return Path(os.path.join(self.path, str(other)))
177
178     def __abs__(self):
179         return Path(os.path.abspath(self.path))
180
181     def __str__(self):
182         return self.path
183
184     def __eq__(self, other):
185         return self.path == other.path
186
187     def exists(self):
188         return self.islink() or os.path.exists(self.path)
189
190     def islink(self):
191         return os.path.islink(self.path)
192
193     def isdir(self):
194         return os.path.isdir(self.path)
195
196     def isfile(self):
197         return os.path.isfile(self.path)
198
199     def list(self):
200         return [Path(p) for p in os.listdir(self.path)]
201
202     def dir(self):
203         return Path(os.path.dirname(self.path))
204
205     def base(self):
206         return Path(os.path.basename(self.path))
207
208     def make(self, mode=None):
209         os.makedirs(self.path)        
210         if mode:
211             os.chmod(self.path, mode)
212         
213     def chmod(self, mode):
214         os.chmod(self.path, mode)
215
216     def rm(self):    
217         if self.islink():
218             os.remove(self.path)
219         else:
220             shutil.rmtree( self.path, onerror = handleRemoveReadonly )
221
222     def copy(self, path, smart=False):
223         if not isinstance(path, Path):
224             path = Path(path)
225
226         if os.path.islink(self.path):
227             return self.copylink(path)
228         elif os.path.isdir(self.path):
229             return self.copydir(path, smart)
230         else:
231             return self.copyfile(path)
232
233     def smartcopy(self, path):
234         return self.copy(path, True)
235
236     def readlink(self):
237         if self.islink():
238             return os.readlink(self.path)
239         else:
240             return False
241
242     def symlink(self, path):
243         try:
244             os.symlink(str(path), self.path)
245             return True
246         except:
247             return False
248
249     def copylink(self, path):
250         try:
251             os.symlink(os.readlink(self.path), str(path))
252             return True
253         except:
254             return False
255
256     def copydir(self, dst, smart=False):
257         try:
258             names = self.list()
259
260             if not dst.exists():
261                 dst.make()
262
263             for name in names:
264                 if name == dst:
265                     continue
266                 if smart and (str(name) in [".git", "CVS", ".svn"]):
267                     continue
268                 srcname = self + name
269                 dstname = dst + name
270                 srcname.copy(dstname, smart)
271             return True
272         except:
273             return False
274
275     def copyfile(self, path):
276         try:
277             shutil.copy2(self.path, str(path))
278             return True
279         except:
280             return False
281
282 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
283     """Find in all the directories in lpath list the file that has the same name
284        as file_name. If it is found, return the full path of the file, else,
285        return False. 
286        The additional_dir (optional) is the name of the directory to add to all 
287        paths in lpath.
288     
289     :param file_name str: The file name to search
290     :param lpath List: The list of directories where to search
291     :param additional_dir str: The name of the additional directory
292     :return: the full path of the file or False if not found
293     :rtype: str
294     """
295     for directory in lpath:
296         dir_complete = os.path.join(directory, additional_dir)
297         if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
298             continue
299         l_files = os.listdir(dir_complete)
300         for file_n in l_files:
301             if file_n == file_name:
302                 return os.path.join(dir_complete, file_name)
303     return False
304
305 def handleRemoveReadonly(func, path, exc):
306     excvalue = exc[1]
307     if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
308         os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
309         func(path)
310     else:
311         raise
312
313 def deepcopy_list(input_list):
314     """ Do a deep copy of a list
315     
316     :param input_list List: The list to copy
317     :return: The copy of the list
318     :rtype: List
319     """
320     res = []
321     for elem in input_list:
322         res.append(elem)
323     return res
324
325 def remove_item_from_list(input_list, item):
326     """ Remove all occurences of item from input_list
327     
328     :param input_list List: The list to modify
329     :return: The without any item
330     :rtype: List
331     """
332     res = []
333     for elem in input_list:
334         if elem == item:
335             continue
336         res.append(elem)
337     return res
338
339 def parse_date(date):
340     """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
341     
342     :param date str: The date to transform
343     :return: The date in the new format
344     :rtype: str
345     """
346     if len(date) != 15:
347         return date
348     res = "%s-%s-%s %s:%s:%s" % (date[0:4],
349                                  date[4:6],
350                                  date[6:8],
351                                  date[9:11],
352                                  date[11:13],
353                                  date[13:])
354     return res
355
356 def merge_dicts(*dict_args):
357     '''
358     Given any number of dicts, shallow copy and merge into a new dict,
359     precedence goes to key value pairs in latter dicts.
360     '''
361     result = {}
362     for dictionary in dict_args:
363         result.update(dictionary)
364     return result
365
366 def replace_in_file(filein, strin, strout):
367     '''Replace <strin> by <strout> in file <filein>
368     '''
369     shutil.move(filein, filein + "_old")
370     fileout= filein
371     filein = filein + "_old"
372     fin = open(filein, "r")
373     fout = open(fileout, "w")
374     for line in fin:
375         fout.write(line.replace(strin, strout))