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 ftplib import FTP
33 from . import architecture
34 from . import printcolors
37 from . import ElementTree
40 from . import environment
41 from . import fileEnviron
42 from . import compilation
43 from . import test_module
44 from . import template
47 if platform.system() == "Windows" :
54 KNOWNFAILURE_STATUS = "KF"
55 TIMEOUT_STATUS = "TIMEOUT"
57 class SatException(Exception):
58 """sat exception class"""
59 def message(self, arg):
60 if sys.version_info[0] >= 3:
61 # message method is not available for python 3.8+
62 return super().msg(arg)
64 return super(SatException,self).message(arg)
66 def ensure_path_exists(p):
67 """Create a path if not existing
69 :param p str: The path.
71 if not os.path.exists(p):
74 def check_config_has_application( config, details = None ):
75 """check that the config has the key APPLICATION. Else raise an exception.
77 :param config class 'common.pyconf.Config': The config.
79 if 'APPLICATION' not in config:
80 message = _("An APPLICATION is required. Use 'config --list' to get the list of available applications.\n")
82 details.append(message)
83 raise SatException( message )
85 def check_config_has_profile( config, details = None ):
87 check that the config has the key APPLICATION.profile.
88 else, raise an exception.
90 :param config class 'common.pyconf.Config': The config.
92 check_config_has_application(config)
93 if 'profile' not in config.APPLICATION:
94 message = _("A profile section is required in your application.\n")
96 details.append(message)
97 raise SatException( message )
99 def appli_test_property(config,property_name, property_value):
100 """Generic function to test if an application has a property set to a value
101 :param config class 'common.pyconf.Config': The config.
102 :param property_name : The name of the property to check
103 :param property_value : The value of the property to test
104 :return: True if the application has the property set to property_value
107 # first check if application has property_value
108 if not ("APPLICATION" in config and
109 "properties" in config.APPLICATION and
110 property_name in config.APPLICATION.properties):
113 # then check to the property is set to property_value
114 eval_expression = 'config.APPLICATION.properties.%s == "%s"' %\
115 (property_name,property_value)
116 result = eval(eval_expression)
120 def config_has_application( config ):
121 return 'APPLICATION' in config
123 def get_cfg_param(config, param_name, default):
125 eearch for param_name value in config.
126 if param_name is not in config
128 else return the found value
130 :param config class 'common.pyconf.Config': The config.
131 :param param_name str: the name of the parameter to get the value
132 :param default str: The value to return if param_name is not in config
133 :return: see initial description of the function
136 if param_name in config:
137 return config[param_name]
140 def strSplitN(aList, nb, skip="\n "):
143 aStr = 'this-is-a-string'
145 split it by every 2nd '-' rather than every '-'
150 strValue += "%15s, " % str(v)
156 strValue = skip + strValue
159 def getProductNames(cfg, wildcards, logger):
160 """get products names using * or ? as wildcards like shell Linux"""
162 if type(wildcards) is list:
167 products = cfg.APPLICATION.products.keys()
168 for wild in wildcards:
170 for prod in products:
171 filtered = fnmatch.filter([prod], wild)
172 # print("filtered", prod, wild, filtered)
173 if len(filtered) > 0:
178 notFound[wild] = None
180 logger.warning("Empty list of products, from %s" % wilds)
181 if len(notFound.keys()) > 0:
182 strProd = strSplitN( sorted(products), 5)
183 logger.warning("products not found: %s\n availables products are:\n%s" % \
184 (sorted(notFound.keys()), strProd) )
188 def print_info(logger, info):
190 Prints the tuples that are in info variable in a formatted way.
192 :param logger Logger: The logging instance to use for the prints.
193 :param info list: The list of tuples to display
195 # find the maximum length of the first value of the tuples in info
196 smax = max(map(lambda l: len(l[0]), info))
197 # Print each item of info with good indentation
199 sp = " " * (smax - len(i[0]))
200 printcolors.print_value(logger, sp + i[0], i[1], 2)
201 logger.write("\n", 2)
203 def get_base_path(config):
205 Returns the path of the products base.
207 :param config Config: The global Config instance.
208 :return: The path of the products base.
211 if "base" not in config.LOCAL:
212 local_file_path = os.path.join(config.VARS.salometoolsway,
215 msg = _("Please define a base path in the file %s" % local_file_path)
216 raise SatException(msg)
218 base_path = os.path.abspath(config.LOCAL.base)
222 def get_launcher_name(config):
224 Returns the name of salome launcher.
226 :param config Config: The global Config instance.
227 :return: The name of salome launcher.
230 check_config_has_application(config)
231 if 'profile' in config.APPLICATION and 'launcher_name' in config.APPLICATION.profile:
232 launcher_name = config.APPLICATION.profile.launcher_name
234 launcher_name = 'salome'
238 def get_launcher_exe(config):
240 Returns the name of exe defined in profile section.
242 :param config Config: The global Config instance.
243 :return: The name of the exe to use in launcher.
246 check_config_has_application(config)
247 if 'profile' in config.APPLICATION and 'exe' in config.APPLICATION.profile:
248 exe_name = config.APPLICATION.profile.exe
255 def get_log_path(config):
257 Returns the path of the logs.
259 :param config Config: The global Config instance.
260 :return: The path of the logs.
263 if "log_dir" not in config.LOCAL:
264 local_file_path = os.path.join(config.VARS.salometoolsway,
267 msg = _("Please define a log_dir in the file %s" % local_file_path)
268 raise SatException(msg)
270 log_dir_path = os.path.abspath(config.LOCAL.log_dir)
274 def get_salometool_version(config):
275 """Return the salomeTool version.
277 :param config Config: The global Config instance.
278 :return: the description of this version of sat in terms of tag and commit
280 return config.LOCAL.tag
283 def get_salome_version(config):
284 import versionMinorMajorPatch as VMMP
286 if hasattr(config.APPLICATION, 'version_salome'):
287 version = VMMP.MinorMajorPatch(config.APPLICATION.version_salome)
289 kernel_info = product.get_product_config(config, "KERNEL")
290 aFile = os.path.join(
291 kernel_info.install_dir,
295 if not os.path.isfile(aFile):
297 with open(aFile) as f:
298 line = f.readline() # example: '[SALOME KERNEL] : 8.4.0'
299 version = VMMP.MinorMajorPatch(line.split(":")[1])
301 res = version.strCompact()
302 # print("get_salome_version %s -> %s" % (version, res))
303 return int(res) # TODO may be future avoid test(s) on integer, use MajorMinorPatch
305 def read_config_from_a_file(filePath):
307 cfg_file = pyconf.Config(filePath)
308 except pyconf.ConfigError as e:
309 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
310 { 'file': filePath, 'error': str(e) })
313 def get_tmp_filename(cfg, name):
314 if not os.path.exists(cfg.VARS.tmp_root):
315 os.makedirs(cfg.VARS.tmp_root)
317 return os.path.join(cfg.VARS.tmp_root, name)
320 # Utils class to simplify path manipulations.
322 def __init__(self, path):
323 self.path = str(path)
325 def __add__(self, other):
326 return Path(os.path.join(self.path, str(other)))
329 return Path(os.path.abspath(self.path))
334 def __eq__(self, other):
335 return self.path == other.path
338 return self.islink() or os.path.exists(self.path)
341 return os.path.islink(self.path)
344 return os.path.isdir(self.path)
347 return os.path.isfile(self.path)
350 return [Path(p) for p in os.listdir(self.path)]
353 return Path(os.path.dirname(self.path))
356 return Path(os.path.basename(self.path))
358 def make(self, mode=None):
359 os.makedirs(self.path)
361 os.chmod(self.path, mode)
363 def chmod(self, mode):
364 os.chmod(self.path, mode)
370 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
372 def copy(self, path, smart=False):
373 if not isinstance(path, Path):
376 if os.path.islink(self.path):
377 return self.copylink(path)
378 elif os.path.isdir(self.path):
379 return self.copydir(path, smart)
381 return self.copyfile(path)
383 def smartcopy(self, path):
384 return self.copy(path, True)
388 return os.readlink(self.path)
392 def symlink(self, path):
394 os.symlink(str(path), self.path)
399 def copylink(self, path):
401 os.symlink(os.readlink(self.path), str(path))
406 def copydir(self, dst, smart=False):
416 if smart and (str(name) in [".git", "CVS", ".svn"]):
418 srcname = self + name
420 srcname.copy(dstname, smart)
425 def copyfile(self, path):
427 shutil.copy2(self.path, str(path))
432 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
434 Find in all the directories in lpath list the file that has the same name
437 then return the full path of the file
440 The additional_dir (optional) is the name of the directory to add to all
443 :param file_name str: The file name to search
444 :param lpath List: The list of directories where to search
445 :param additional_dir str: The name of the additional directory
446 :return: the full path of the file or False if not found
449 for directory in lpath:
450 dir_complete = os.path.join(directory, additional_dir)
451 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
453 l_files = os.listdir(dir_complete)
454 for file_n in l_files:
455 if file_n == file_name:
456 return os.path.join(dir_complete, file_name)
459 def find_file_in_ftppath(file_name, ftppath, installation_dir, logger):
461 Find in all ftp servers in ftppath the file called file_name
462 If it is found then return the destination path of the file
463 (the place where the file was downloaded"
466 :param file_name str: The file name to search
467 :param ftppath, List: The list of ftp servers where to search
468 :param installation_dir str: The name of the installation directory
469 :return: the full path of the file or False if not found
470 :param logger Logger: The logging instance to use for the prints.
474 # make sure installation_dir exists
475 if not os.path.exists(installation_dir):
476 os.makedirs(installation_dir)
478 destination=os.path.join(installation_dir, file_name)
480 # paths in ftppath may contain several paths separated by ":"
481 # we plit them, and push all paths in bigftppath
483 for ipath in ftppath:
484 splpath=ipath.split(":")
487 for ftp_archive in bigftppath:
489 # ftp_archive has the form ftp.xxx.yyy/dir1/dir2/...
490 ftp_archive_split=ftp_archive.split("/")
491 ftp_server=ftp_archive_split[0]
492 ftp = FTP(ftp_server)
493 logger.write(" Connect to ftp server %s\n" % ftp_server, 3)
495 for directory in ftp_archive_split[1:]:
496 logger.write(" Change directory to %s\n" % directory, 3)
499 logger.error("while connecting to ftp server %s\n" % ftp_server)
502 if ftp.size(file_name) > 0:
503 # if file exists and is non empty
504 with open(destination,'wb') as dest_file:
505 ftp.retrbinary("RETR "+file_name, dest_file.write)
506 logger.write(" Archive %s was retrieved and stored in %s\n" % (file_name, destination), 3)
509 logger.error("File not found in ftp_archive %s\n" % ftp_server)
514 def handleRemoveReadonly(func, path, exc):
516 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
517 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
522 def deepcopy_list(input_list):
524 Do a deep copy of a list
526 :param input_list List: The list to copy
527 :return: The copy of the list
531 for elem in input_list:
535 def remove_item_from_list(input_list, item):
537 Remove all occurences of item from input_list
539 :param input_list List: The list to modify
540 :return: The without any item
544 for elem in input_list:
550 def parse_date(date):
552 Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
554 :param date str: The date to transform
555 :return: The date in the new format
560 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
568 def merge_dicts(*dict_args):
570 Given any number of dicts, shallow copy and merge into a new dict,
571 precedence goes to key value pairs in latter dicts.
574 for dictionary in dict_args:
575 result.update(dictionary)
578 def replace_in_file(filein, strin, strout):
579 """Replace <strin> by <strout> in file <filein>"""
580 shutil.move(filein, filein + "_old")
582 filein = filein + "_old"
583 fin = open(filein, "r")
584 fout = open(fileout, "w")
586 fout.write(line.replace(strin, strout))
588 def get_property_in_product_cfg(product_cfg, pprty):
589 if not "properties" in product_cfg:
591 if not pprty in product_cfg.properties:
593 return product_cfg.properties[pprty]
595 def activate_mesa_property(config):
596 """Add mesa property into application properties
598 :param config Config: The global configuration. It must have an application!
600 # Verify the existence of the file
601 if not 'properties' in config.APPLICATION:
602 config.APPLICATION.addMapping( 'properties', pyconf.Mapping(), None )
603 config.APPLICATION.properties.use_mesa="yes"