3 # Copyright (C) 2010-2013 CEA/DEN
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.
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.
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
21 initial imports and utilities methods for salomeTools
30 from . import architecture
31 from . import printcolors
34 from . import ElementTree
37 from . import environment
38 from . import fileEnviron
39 from . import compilation
40 from . import test_module
41 from . import template
44 if platform.system() == "Windows" :
51 KNOWNFAILURE_STATUS = "KF"
52 TIMEOUT_STATUS = "TIMEOUT"
54 CONFIG_FILENAME = "sat-config.pyconf"
56 class SatException(Exception):
57 """rename Exception Class"""
60 def ensure_path_exists(p):
61 """Create a path if not existing
63 :param p str: The path.
65 if not os.path.exists(p):
68 def check_config_has_application( config, details = None ):
69 """check that the config has the key APPLICATION. Else raise an exception.
71 :param config class 'common.pyconf.Config': The config.
73 if 'APPLICATION' not in config:
74 message = _("An APPLICATION is required. Use 'config --list' to get"
75 " the list of available applications.\n")
77 details.append(message)
78 raise SatException( message )
80 def check_config_has_profile( config, details = None ):
82 check that the config has the key APPLICATION.profile.
83 else, raise an exception.
85 :param config class 'common.pyconf.Config': The config.
87 check_config_has_application(config)
88 if 'profile' not in config.APPLICATION:
89 message = _("A profile section is required in your application.\n")
91 details.append(message)
92 raise SatException( message )
94 def config_has_application( config ):
95 return 'APPLICATION' in config
97 def get_cfg_param(config, param_name, default):
99 eearch for param_name value in config.
100 if param_name is not in config
102 else return the found value
104 :param config class 'common.pyconf.Config': The config.
105 :param param_name str: the name of the parameter to get the value
106 :param default str: The value to return if param_name is not in config
107 :return: see initial description of the function
110 if param_name in config:
111 return config[param_name]
114 def print_info(logger, info):
116 Prints the tuples that are in info variable in a formatted way.
118 :param logger Logger: The logging instance to use for the prints.
119 :param info list: The list of tuples to display
121 # find the maximum length of the first value of the tuples in info
122 smax = max(map(lambda l: len(l[0]), info))
123 # Print each item of info with good indentation
125 sp = " " * (smax - len(i[0]))
126 printcolors.print_value(logger, sp + i[0], i[1], 2)
127 logger.write("\n", 2)
129 def get_base_path(config):
131 Returns the path of the products base.
133 :param config Config: The global Config instance.
134 :return: The path of the products base.
137 if "base" not in config.LOCAL:
138 local_file_path = os.path.join(config.VARS.salometoolsway,
141 msg = _("Please define a base path in the file %s" % local_file_path)
142 raise SatException(msg)
144 base_path = os.path.abspath(config.LOCAL.base)
148 def get_launcher_name(config):
150 Returns the name of salome launcher.
152 :param config Config: The global Config instance.
153 :return: The name of salome launcher.
156 check_config_has_application(config)
157 if 'profile' in config.APPLICATION and 'launcher_name' in config.APPLICATION.profile:
158 launcher_name = config.APPLICATION.profile.launcher_name
160 launcher_name = 'salome'
164 def get_log_path(config):
166 Returns the path of the logs.
168 :param config Config: The global Config instance.
169 :return: The path of the logs.
172 if "log_dir" not in config.LOCAL:
173 local_file_path = os.path.join(config.VARS.salometoolsway,
176 msg = _("Please define a log_dir in the file %s" % local_file_path)
177 raise SatException(msg)
179 log_dir_path = os.path.abspath(config.LOCAL.log_dir)
183 def get_salome_version(config):
184 if hasattr(config.APPLICATION, 'version_salome'):
185 Version = config.APPLICATION.version_salome
187 KERNEL_info = product.get_product_config(config, "KERNEL")
188 VERSION = os.path.join(
189 KERNEL_info.install_dir,
193 if not os.path.isfile(VERSION):
196 fVERSION = open(VERSION)
197 Version = fVERSION.readline()
200 VersionSalome = int(only_numbers(Version))
203 def only_numbers(str_num):
204 return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
206 def read_config_from_a_file(filePath):
208 cfg_file = pyconf.Config(filePath)
209 except pyconf.ConfigError as e:
210 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
211 { 'file': filePath, 'error': str(e) })
214 def get_tmp_filename(cfg, name):
215 if not os.path.exists(cfg.VARS.tmp_root):
216 os.makedirs(cfg.VARS.tmp_root)
218 return os.path.join(cfg.VARS.tmp_root, name)
221 # Utils class to simplify path manipulations.
223 def __init__(self, path):
224 self.path = str(path)
226 def __add__(self, other):
227 return Path(os.path.join(self.path, str(other)))
230 return Path(os.path.abspath(self.path))
235 def __eq__(self, other):
236 return self.path == other.path
239 return self.islink() or os.path.exists(self.path)
242 return os.path.islink(self.path)
245 return os.path.isdir(self.path)
248 return os.path.isfile(self.path)
251 return [Path(p) for p in os.listdir(self.path)]
254 return Path(os.path.dirname(self.path))
257 return Path(os.path.basename(self.path))
259 def make(self, mode=None):
260 os.makedirs(self.path)
262 os.chmod(self.path, mode)
264 def chmod(self, mode):
265 os.chmod(self.path, mode)
271 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
273 def copy(self, path, smart=False):
274 if not isinstance(path, Path):
277 if os.path.islink(self.path):
278 return self.copylink(path)
279 elif os.path.isdir(self.path):
280 return self.copydir(path, smart)
282 return self.copyfile(path)
284 def smartcopy(self, path):
285 return self.copy(path, True)
289 return os.readlink(self.path)
293 def symlink(self, path):
295 os.symlink(str(path), self.path)
300 def copylink(self, path):
302 os.symlink(os.readlink(self.path), str(path))
307 def copydir(self, dst, smart=False):
317 if smart and (str(name) in [".git", "CVS", ".svn"]):
319 srcname = self + name
321 srcname.copy(dstname, smart)
326 def copyfile(self, path):
328 shutil.copy2(self.path, str(path))
333 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
335 Find in all the directories in lpath list the file that has the same name
338 then return the full path of the file
341 The additional_dir (optional) is the name of the directory to add to all
344 :param file_name str: The file name to search
345 :param lpath List: The list of directories where to search
346 :param additional_dir str: The name of the additional directory
347 :return: the full path of the file or False if not found
350 for directory in lpath:
351 dir_complete = os.path.join(directory, additional_dir)
352 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
354 l_files = os.listdir(dir_complete)
355 for file_n in l_files:
356 if file_n == file_name:
357 return os.path.join(dir_complete, file_name)
360 def handleRemoveReadonly(func, path, exc):
362 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
363 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
368 def deepcopy_list(input_list):
370 Do a deep copy of a list
372 :param input_list List: The list to copy
373 :return: The copy of the list
377 for elem in input_list:
381 def remove_item_from_list(input_list, item):
383 Remove all occurences of item from input_list
385 :param input_list List: The list to modify
386 :return: The without any item
390 for elem in input_list:
396 def parse_date(date):
398 Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
400 :param date str: The date to transform
401 :return: The date in the new format
406 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
414 def merge_dicts(*dict_args):
416 Given any number of dicts, shallow copy and merge into a new dict,
417 precedence goes to key value pairs in latter dicts.
420 for dictionary in dict_args:
421 result.update(dictionary)
424 def replace_in_file(filein, strin, strout):
425 """Replace <strin> by <strout> in file <filein>"""
426 shutil.move(filein, filein + "_old")
428 filein = filein + "_old"
429 fin = open(filein, "r")
430 fout = open(fileout, "w")
432 fout.write(line.replace(strin, strout))
434 def get_property_in_product_cfg(product_cfg, pprty):
435 if not "properties" in product_cfg:
437 if not pprty in product_cfg.properties:
439 return product_cfg.properties[pprty]
441 def activate_mesa_property(config):
442 """Add mesa property into application properties
444 :param config Config: The global configuration. It must have an application!
446 # Verify the existence of the file
447 if not 'properties' in config.APPLICATION:
448 config.APPLICATION.addMapping( 'properties', pyconf.Mapping(), None )
449 config.APPLICATION.properties.use_mesa="yes"