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