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
41 KNOWNFAILURE_STATUS = "KF"
42 TIMEOUT_STATUS = "TIMEOUT"
44 CONFIG_FILENAME = "sat-config.pyconf"
46 class SatException(Exception):
47 '''rename Exception Class
51 def ensure_path_exists(p):
52 '''Create a path if not existing
54 :param p str: The path.
56 if not os.path.exists(p):
59 def check_config_has_application( config, details = None ):
60 '''check that the config has the key APPLICATION. Else raise an exception.
62 :param config class 'common.pyconf.Config': The config.
64 if 'APPLICATION' not in config:
65 message = _("An APPLICATION is required. Use 'config --list' to get"
66 " the list of available applications.\n")
68 details.append(message)
69 raise SatException( message )
71 def check_config_has_profile( config, details = None ):
72 '''check that the config has the key APPLICATION.profile.
73 Else, raise an exception.
75 :param config class 'common.pyconf.Config': The config.
77 check_config_has_application(config)
78 if 'profile' not in config.APPLICATION:
79 message = _("A profile section is required in your application.\n")
81 details.append(message)
82 raise SatException( message )
84 def config_has_application( config ):
85 return 'APPLICATION' in config
87 def get_cfg_param(config, param_name, default):
88 '''Search for param_name value in config.
89 If param_name is not in config, then return default,
90 else, return the found value
92 :param config class 'common.pyconf.Config': The config.
93 :param param_name str: the name of the parameter to get the value
94 :param default str: The value to return if param_name is not in config
95 :return: see initial description of the function
98 if param_name in config:
99 return config[param_name]
102 def print_info(logger, info):
103 '''Prints the tuples that are in info variable in a formatted way.
105 :param logger Logger: The logging instance to use for the prints.
106 :param info list: The list of tuples to display
108 # find the maximum length of the first value of the tuples in info
109 smax = max(map(lambda l: len(l[0]), info))
110 # Print each item of info with good indentation
112 sp = " " * (smax - len(i[0]))
113 printcolors.print_value(logger, sp + i[0], i[1], 2)
114 logger.write("\n", 2)
116 def get_base_path(config):
117 '''Returns the path of the product base.
119 :param config Config: The global Config instance.
120 :return: The path of the product base.
123 if "base" not in config.SITE:
124 site_file_path = os.path.join(config.VARS.salometoolsway,
127 msg = _("Please define a base path in the file %s" % site_file_path)
128 raise SatException(msg)
130 return config.SITE.base
132 def get_salome_version(config):
133 if hasattr(config.APPLICATION, 'version_salome'):
134 Version = config.APPLICATION.version_salome
136 KERNEL_info = product.get_product_config(config, "KERNEL")
137 VERSION = os.path.join(
138 KERNEL_info.install_dir,
142 if not os.path.isfile(VERSION):
145 fVERSION = open(VERSION)
146 Version = fVERSION.readline()
149 VersionSalome = int(only_numbers(Version))
152 def only_numbers(str_num):
153 return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
155 def read_config_from_a_file(filePath):
157 cfg_file = pyconf.Config(filePath)
158 except pyconf.ConfigError as e:
159 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
160 { 'file': filePath, 'error': str(e) })
163 def get_tmp_filename(cfg, name):
164 if not os.path.exists(cfg.VARS.tmp_root):
165 os.makedirs(cfg.VARS.tmp_root)
167 return os.path.join(cfg.VARS.tmp_root, name)
170 # Utils class to simplify path manipulations.
172 def __init__(self, path):
173 self.path = str(path)
175 def __add__(self, other):
176 return Path(os.path.join(self.path, str(other)))
179 return Path(os.path.abspath(self.path))
184 def __eq__(self, other):
185 return self.path == other.path
188 return self.islink() or os.path.exists(self.path)
191 return os.path.islink(self.path)
194 return os.path.isdir(self.path)
197 return os.path.isfile(self.path)
200 return [Path(p) for p in os.listdir(self.path)]
203 return Path(os.path.dirname(self.path))
206 return Path(os.path.basename(self.path))
208 def make(self, mode=None):
209 os.makedirs(self.path)
211 os.chmod(self.path, mode)
213 def chmod(self, mode):
214 os.chmod(self.path, mode)
220 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
222 def copy(self, path, smart=False):
223 if not isinstance(path, Path):
226 if os.path.islink(self.path):
227 return self.copylink(path)
228 elif os.path.isdir(self.path):
229 return self.copydir(path, smart)
231 return self.copyfile(path)
233 def smartcopy(self, path):
234 return self.copy(path, True)
238 return os.readlink(self.path)
242 def symlink(self, path):
244 os.symlink(str(path), self.path)
249 def copylink(self, path):
251 os.symlink(os.readlink(self.path), str(path))
256 def copydir(self, dst, smart=False):
266 if smart and (str(name) in [".git", "CVS", ".svn"]):
268 srcname = self + name
270 srcname.copy(dstname, smart)
275 def copyfile(self, path):
277 shutil.copy2(self.path, str(path))
282 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
283 """Find in all the directories in lpath list the file that has the same name
284 as file_name. If it is found, return the full path of the file, else,
286 The additional_dir (optional) is the name of the directory to add to all
289 :param file_name str: The file name to search
290 :param lpath List: The list of directories where to search
291 :param additional_dir str: The name of the additional directory
292 :return: the full path of the file or False if not found
295 for directory in lpath:
296 dir_complete = os.path.join(directory, additional_dir)
297 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
299 l_files = os.listdir(dir_complete)
300 for file_n in l_files:
301 if file_n == file_name:
302 return os.path.join(dir_complete, file_name)
305 def handleRemoveReadonly(func, path, exc):
307 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
308 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
313 def deepcopy_list(input_list):
314 """ Do a deep copy of a list
316 :param input_list List: The list to copy
317 :return: The copy of the list
321 for elem in input_list:
325 def remove_item_from_list(input_list, item):
326 """ Remove all occurences of item from input_list
328 :param input_list List: The list to modify
329 :return: The without any item
333 for elem in input_list:
339 def parse_date(date):
340 """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
342 :param date str: The date to transform
343 :return: The date in the new format
348 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
356 def merge_dicts(*dict_args):
358 Given any number of dicts, shallow copy and merge into a new dict,
359 precedence goes to key value pairs in latter dicts.
362 for dictionary in dict_args:
363 result.update(dictionary)
366 def replace_in_file(filein, strin, strout):
367 '''Replace <strin> by <strout> in file <filein>
369 shutil.move(filein, filein + "_old")
371 filein = filein + "_old"
372 fin = open(filein, "r")
373 fout = open(fileout, "w")
375 fout.write(line.replace(strin, strout))
377 def get_property_in_product_cfg(product_cfg, pprty):
378 if not "properties" in product_cfg:
380 if not pprty in product_cfg.properties:
382 return product_cfg.properties[pprty]