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
25 from . import architecture
26 from . import printcolors
29 from . import ElementTree
32 from . import environment
33 from . import fileEnviron
34 from . import compilation
35 from . import test_module
36 from . import template
39 if platform.system() == "Windows" :
46 KNOWNFAILURE_STATUS = "KF"
47 TIMEOUT_STATUS = "TIMEOUT"
49 CONFIG_FILENAME = "sat-config.pyconf"
51 class SatException(Exception):
52 '''rename Exception Class
56 def ensure_path_exists(p):
57 '''Create a path if not existing
59 :param p str: The path.
61 if not os.path.exists(p):
64 def check_config_has_application( config, details = None ):
65 '''check that the config has the key APPLICATION. Else raise an exception.
67 :param config class 'common.pyconf.Config': The config.
69 if 'APPLICATION' not in config:
70 message = _("An APPLICATION is required. Use 'config --list' to get"
71 " the list of available applications.\n")
73 details.append(message)
74 raise SatException( message )
76 def check_config_has_profile( config, details = None ):
77 '''check that the config has the key APPLICATION.profile.
78 Else, raise an exception.
80 :param config class 'common.pyconf.Config': The config.
82 check_config_has_application(config)
83 if 'profile' not in config.APPLICATION:
84 message = _("A profile section is required in your application.\n")
86 details.append(message)
87 raise SatException( message )
89 def config_has_application( config ):
90 return 'APPLICATION' in config
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
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
103 if param_name in config:
104 return config[param_name]
107 def print_info(logger, info):
108 '''Prints the tuples that are in info variable in a formatted way.
110 :param logger Logger: The logging instance to use for the prints.
111 :param info list: The list of tuples to display
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
117 sp = " " * (smax - len(i[0]))
118 printcolors.print_value(logger, sp + i[0], i[1], 2)
119 logger.write("\n", 2)
121 def get_base_path(config):
122 '''Returns the path of the products base.
124 :param config Config: The global Config instance.
125 :return: The path of the products base.
128 if "base" not in config.LOCAL:
129 local_file_path = os.path.join(config.VARS.salometoolsway,
132 msg = _("Please define a base path in the file %s" % local_file_path)
133 raise SatException(msg)
135 base_path = os.path.abspath(config.LOCAL.base)
139 def get_launcher_name(config):
140 '''Returns the name of salome launcher.
142 :param config Config: The global Config instance.
143 :return: The name of salome launcher.
146 check_config_has_application(config)
147 if 'profile' in config.APPLICATION and 'launcher_name' in config.APPLICATION.profile:
148 launcher_name = config.APPLICATION.profile.launcher_name
150 launcher_name = 'salome'
154 def get_log_path(config):
155 '''Returns the path of the logs.
157 :param config Config: The global Config instance.
158 :return: The path of the logs.
161 if "log_dir" not in config.LOCAL:
162 local_file_path = os.path.join(config.VARS.salometoolsway,
165 msg = _("Please define a log_dir in the file %s" % local_file_path)
166 raise SatException(msg)
168 log_dir_path = os.path.abspath(config.LOCAL.log_dir)
172 def get_salome_version(config):
173 if hasattr(config.APPLICATION, 'version_salome'):
174 Version = config.APPLICATION.version_salome
176 KERNEL_info = product.get_product_config(config, "KERNEL")
177 VERSION = os.path.join(
178 KERNEL_info.install_dir,
182 if not os.path.isfile(VERSION):
185 fVERSION = open(VERSION)
186 Version = fVERSION.readline()
189 VersionSalome = int(only_numbers(Version))
192 def only_numbers(str_num):
193 return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
195 def read_config_from_a_file(filePath):
197 cfg_file = pyconf.Config(filePath)
198 except pyconf.ConfigError as e:
199 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
200 { 'file': filePath, 'error': str(e) })
203 def get_tmp_filename(cfg, name):
204 if not os.path.exists(cfg.VARS.tmp_root):
205 os.makedirs(cfg.VARS.tmp_root)
207 return os.path.join(cfg.VARS.tmp_root, name)
210 # Utils class to simplify path manipulations.
212 def __init__(self, path):
213 self.path = str(path)
215 def __add__(self, other):
216 return Path(os.path.join(self.path, str(other)))
219 return Path(os.path.abspath(self.path))
224 def __eq__(self, other):
225 return self.path == other.path
228 return self.islink() or os.path.exists(self.path)
231 return os.path.islink(self.path)
234 return os.path.isdir(self.path)
237 return os.path.isfile(self.path)
240 return [Path(p) for p in os.listdir(self.path)]
243 return Path(os.path.dirname(self.path))
246 return Path(os.path.basename(self.path))
248 def make(self, mode=None):
249 os.makedirs(self.path)
251 os.chmod(self.path, mode)
253 def chmod(self, mode):
254 os.chmod(self.path, mode)
260 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
262 def copy(self, path, smart=False):
263 if not isinstance(path, Path):
266 if os.path.islink(self.path):
267 return self.copylink(path)
268 elif os.path.isdir(self.path):
269 return self.copydir(path, smart)
271 return self.copyfile(path)
273 def smartcopy(self, path):
274 return self.copy(path, True)
278 return os.readlink(self.path)
282 def symlink(self, path):
284 os.symlink(str(path), self.path)
289 def copylink(self, path):
291 os.symlink(os.readlink(self.path), str(path))
296 def copydir(self, dst, smart=False):
306 if smart and (str(name) in [".git", "CVS", ".svn"]):
308 srcname = self + name
310 srcname.copy(dstname, smart)
315 def copyfile(self, path):
317 shutil.copy2(self.path, str(path))
322 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
323 """Find in all the directories in lpath list the file that has the same name
324 as file_name. If it is found, return the full path of the file, else,
326 The additional_dir (optional) is the name of the directory to add to all
329 :param file_name str: The file name to search
330 :param lpath List: The list of directories where to search
331 :param additional_dir str: The name of the additional directory
332 :return: the full path of the file or False if not found
335 for directory in lpath:
336 dir_complete = os.path.join(directory, additional_dir)
337 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
339 l_files = os.listdir(dir_complete)
340 for file_n in l_files:
341 if file_n == file_name:
342 return os.path.join(dir_complete, file_name)
345 def handleRemoveReadonly(func, path, exc):
347 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
348 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
353 def deepcopy_list(input_list):
354 """ Do a deep copy of a list
356 :param input_list List: The list to copy
357 :return: The copy of the list
361 for elem in input_list:
365 def remove_item_from_list(input_list, item):
366 """ Remove all occurences of item from input_list
368 :param input_list List: The list to modify
369 :return: The without any item
373 for elem in input_list:
379 def parse_date(date):
380 """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
382 :param date str: The date to transform
383 :return: The date in the new format
388 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
396 def merge_dicts(*dict_args):
398 Given any number of dicts, shallow copy and merge into a new dict,
399 precedence goes to key value pairs in latter dicts.
402 for dictionary in dict_args:
403 result.update(dictionary)
406 def replace_in_file(filein, strin, strout):
407 '''Replace <strin> by <strout> in file <filein>
409 shutil.move(filein, filein + "_old")
411 filein = filein + "_old"
412 fin = open(filein, "r")
413 fout = open(fileout, "w")
415 fout.write(line.replace(strin, strout))
417 def get_property_in_product_cfg(product_cfg, pprty):
418 if not "properties" in product_cfg:
420 if not pprty in product_cfg.properties:
422 return product_cfg.properties[pprty]