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
32 from . import architecture
33 from . import printcolors
36 from . import ElementTree
39 from . import environment
40 from . import fileEnviron
41 from . import compilation
42 from . import test_module
43 from . import template
46 if platform.system() == "Windows" :
53 KNOWNFAILURE_STATUS = "KF"
54 TIMEOUT_STATUS = "TIMEOUT"
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 the list of available applications.\n")
76 details.append(message)
77 raise SatException( message )
79 def check_config_has_profile( config, details = None ):
81 check that the config has the key APPLICATION.profile.
82 else, raise an exception.
84 :param config class 'common.pyconf.Config': The config.
86 check_config_has_application(config)
87 if 'profile' not in config.APPLICATION:
88 message = _("A profile section is required in your application.\n")
90 details.append(message)
91 raise SatException( message )
93 def config_has_application( config ):
94 return 'APPLICATION' in config
96 def get_cfg_param(config, param_name, default):
98 eearch for param_name value in config.
99 if param_name is not in config
101 else return the found value
103 :param config class 'common.pyconf.Config': The config.
104 :param param_name str: the name of the parameter to get the value
105 :param default str: The value to return if param_name is not in config
106 :return: see initial description of the function
109 if param_name in config:
110 return config[param_name]
113 def strSplitN(aList, nb, skip="\n "):
116 aStr = 'this-is-a-string'
118 split it by every 2nd '-' rather than every '-'
123 strValue += "%15s, " % str(v)
129 strValue = skip + strValue
132 def getProductNames(cfg, wildcards, logger):
133 """get products names using * or ? as wildcards like shell Linux"""
135 if type(wildcards) is list:
140 products = cfg.APPLICATION.products.keys()
141 for wild in wildcards:
143 for prod in products:
144 filtered = fnmatch.filter([prod], wild)
145 # print("filtered", prod, wild, filtered)
146 if len(filtered) > 0:
151 notFound[wild] = None
153 logger.warning("Empty list of products, from %s" % wilds)
154 if len(notFound.keys()) > 0:
155 strProd = strSplitN( sorted(products), 5)
156 logger.warning("products not found: %s\n availables products are:\n%s" % \
157 (sorted(notFound.keys()), strProd) )
161 def print_info(logger, info):
163 Prints the tuples that are in info variable in a formatted way.
165 :param logger Logger: The logging instance to use for the prints.
166 :param info list: The list of tuples to display
168 # find the maximum length of the first value of the tuples in info
169 smax = max(map(lambda l: len(l[0]), info))
170 # Print each item of info with good indentation
172 sp = " " * (smax - len(i[0]))
173 printcolors.print_value(logger, sp + i[0], i[1], 2)
174 logger.write("\n", 2)
176 def get_base_path(config):
178 Returns the path of the products base.
180 :param config Config: The global Config instance.
181 :return: The path of the products base.
184 if "base" not in config.LOCAL:
185 local_file_path = os.path.join(config.VARS.salometoolsway,
188 msg = _("Please define a base path in the file %s" % local_file_path)
189 raise SatException(msg)
191 base_path = os.path.abspath(config.LOCAL.base)
195 def get_launcher_name(config):
197 Returns the name of salome launcher.
199 :param config Config: The global Config instance.
200 :return: The name of salome launcher.
203 check_config_has_application(config)
204 if 'profile' in config.APPLICATION and 'launcher_name' in config.APPLICATION.profile:
205 launcher_name = config.APPLICATION.profile.launcher_name
207 launcher_name = 'salome'
211 def get_log_path(config):
213 Returns the path of the logs.
215 :param config Config: The global Config instance.
216 :return: The path of the logs.
219 if "log_dir" not in config.LOCAL:
220 local_file_path = os.path.join(config.VARS.salometoolsway,
223 msg = _("Please define a log_dir in the file %s" % local_file_path)
224 raise SatException(msg)
226 log_dir_path = os.path.abspath(config.LOCAL.log_dir)
230 def get_salome_version(config):
231 import versionMinorMajorPatch as VMMP
233 if hasattr(config.APPLICATION, 'version_salome'):
234 version = VMMP.MinorMajorPatch(config.APPLICATION.version_salome)
236 kernel_info = product.get_product_config(config, "KERNEL")
237 aFile = os.path.join(
238 kernel_info.install_dir,
242 if not os.path.isfile(aFile):
244 with open(aFile) as f:
245 line = f.readline() # example: '[SALOME KERNEL] : 8.4.0'
246 version = VMMP.MinorMajorPatch(line.split(":")[1])
248 res = version.strCompact()
249 # print("get_salome_version %s -> %s" % (version, res))
250 return int(res) # TODO may be future avoid test(s) on integer, use MajorMinorPatch
252 def read_config_from_a_file(filePath):
254 cfg_file = pyconf.Config(filePath)
255 except pyconf.ConfigError as e:
256 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
257 { 'file': filePath, 'error': str(e) })
260 def get_tmp_filename(cfg, name):
261 if not os.path.exists(cfg.VARS.tmp_root):
262 os.makedirs(cfg.VARS.tmp_root)
264 return os.path.join(cfg.VARS.tmp_root, name)
267 # Utils class to simplify path manipulations.
269 def __init__(self, path):
270 self.path = str(path)
272 def __add__(self, other):
273 return Path(os.path.join(self.path, str(other)))
276 return Path(os.path.abspath(self.path))
281 def __eq__(self, other):
282 return self.path == other.path
285 return self.islink() or os.path.exists(self.path)
288 return os.path.islink(self.path)
291 return os.path.isdir(self.path)
294 return os.path.isfile(self.path)
297 return [Path(p) for p in os.listdir(self.path)]
300 return Path(os.path.dirname(self.path))
303 return Path(os.path.basename(self.path))
305 def make(self, mode=None):
306 os.makedirs(self.path)
308 os.chmod(self.path, mode)
310 def chmod(self, mode):
311 os.chmod(self.path, mode)
317 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
319 def copy(self, path, smart=False):
320 if not isinstance(path, Path):
323 if os.path.islink(self.path):
324 return self.copylink(path)
325 elif os.path.isdir(self.path):
326 return self.copydir(path, smart)
328 return self.copyfile(path)
330 def smartcopy(self, path):
331 return self.copy(path, True)
335 return os.readlink(self.path)
339 def symlink(self, path):
341 os.symlink(str(path), self.path)
346 def copylink(self, path):
348 os.symlink(os.readlink(self.path), str(path))
353 def copydir(self, dst, smart=False):
363 if smart and (str(name) in [".git", "CVS", ".svn"]):
365 srcname = self + name
367 srcname.copy(dstname, smart)
372 def copyfile(self, path):
374 shutil.copy2(self.path, str(path))
379 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
381 Find in all the directories in lpath list the file that has the same name
384 then return the full path of the file
387 The additional_dir (optional) is the name of the directory to add to all
390 :param file_name str: The file name to search
391 :param lpath List: The list of directories where to search
392 :param additional_dir str: The name of the additional directory
393 :return: the full path of the file or False if not found
396 for directory in lpath:
397 dir_complete = os.path.join(directory, additional_dir)
398 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
400 l_files = os.listdir(dir_complete)
401 for file_n in l_files:
402 if file_n == file_name:
403 return os.path.join(dir_complete, file_name)
406 def handleRemoveReadonly(func, path, exc):
408 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
409 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
414 def deepcopy_list(input_list):
416 Do a deep copy of a list
418 :param input_list List: The list to copy
419 :return: The copy of the list
423 for elem in input_list:
427 def remove_item_from_list(input_list, item):
429 Remove all occurences of item from input_list
431 :param input_list List: The list to modify
432 :return: The without any item
436 for elem in input_list:
442 def parse_date(date):
444 Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
446 :param date str: The date to transform
447 :return: The date in the new format
452 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
460 def merge_dicts(*dict_args):
462 Given any number of dicts, shallow copy and merge into a new dict,
463 precedence goes to key value pairs in latter dicts.
466 for dictionary in dict_args:
467 result.update(dictionary)
470 def replace_in_file(filein, strin, strout):
471 """Replace <strin> by <strout> in file <filein>"""
472 shutil.move(filein, filein + "_old")
474 filein = filein + "_old"
475 fin = open(filein, "r")
476 fout = open(fileout, "w")
478 fout.write(line.replace(strin, strout))
480 def get_property_in_product_cfg(product_cfg, pprty):
481 if not "properties" in product_cfg:
483 if not pprty in product_cfg.properties:
485 return product_cfg.properties[pprty]
487 def activate_mesa_property(config):
488 """Add mesa property into application properties
490 :param config Config: The global configuration. It must have an application!
492 # Verify the existence of the file
493 if not 'properties' in config.APPLICATION:
494 config.APPLICATION.addMapping( 'properties', pyconf.Mapping(), None )
495 config.APPLICATION.properties.use_mesa="yes"