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