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