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 product base.
124 :param config Config: The global Config instance.
125 :return: The path of the product base.
128 if "base" not in config.SITE:
129 site_file_path = os.path.join(config.VARS.salometoolsway,
132 msg = _("Please define a base path in the file %s" % site_file_path)
133 raise SatException(msg)
135 return config.SITE.base
137 def get_salome_version(config):
138 if hasattr(config.APPLICATION, 'version_salome'):
139 Version = config.APPLICATION.version_salome
141 KERNEL_info = product.get_product_config(config, "KERNEL")
142 VERSION = os.path.join(
143 KERNEL_info.install_dir,
147 if not os.path.isfile(VERSION):
150 fVERSION = open(VERSION)
151 Version = fVERSION.readline()
154 VersionSalome = int(only_numbers(Version))
157 def only_numbers(str_num):
158 return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
160 def read_config_from_a_file(filePath):
162 cfg_file = pyconf.Config(filePath)
163 except pyconf.ConfigError as e:
164 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
165 { 'file': filePath, 'error': str(e) })
168 def get_tmp_filename(cfg, name):
169 if not os.path.exists(cfg.VARS.tmp_root):
170 os.makedirs(cfg.VARS.tmp_root)
172 return os.path.join(cfg.VARS.tmp_root, name)
175 # Utils class to simplify path manipulations.
177 def __init__(self, path):
178 self.path = str(path)
180 def __add__(self, other):
181 return Path(os.path.join(self.path, str(other)))
184 return Path(os.path.abspath(self.path))
189 def __eq__(self, other):
190 return self.path == other.path
193 return self.islink() or os.path.exists(self.path)
196 return os.path.islink(self.path)
199 return os.path.isdir(self.path)
202 return os.path.isfile(self.path)
205 return [Path(p) for p in os.listdir(self.path)]
208 return Path(os.path.dirname(self.path))
211 return Path(os.path.basename(self.path))
213 def make(self, mode=None):
214 os.makedirs(self.path)
216 os.chmod(self.path, mode)
218 def chmod(self, mode):
219 os.chmod(self.path, mode)
225 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
227 def copy(self, path, smart=False):
228 if not isinstance(path, Path):
231 if os.path.islink(self.path):
232 return self.copylink(path)
233 elif os.path.isdir(self.path):
234 return self.copydir(path, smart)
236 return self.copyfile(path)
238 def smartcopy(self, path):
239 return self.copy(path, True)
243 return os.readlink(self.path)
247 def symlink(self, path):
249 os.symlink(str(path), self.path)
254 def copylink(self, path):
256 os.symlink(os.readlink(self.path), str(path))
261 def copydir(self, dst, smart=False):
271 if smart and (str(name) in [".git", "CVS", ".svn"]):
273 srcname = self + name
275 srcname.copy(dstname, smart)
280 def copyfile(self, path):
282 shutil.copy2(self.path, str(path))
287 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
288 """Find in all the directories in lpath list the file that has the same name
289 as file_name. If it is found, return the full path of the file, else,
291 The additional_dir (optional) is the name of the directory to add to all
294 :param file_name str: The file name to search
295 :param lpath List: The list of directories where to search
296 :param additional_dir str: The name of the additional directory
297 :return: the full path of the file or False if not found
300 for directory in lpath:
301 dir_complete = os.path.join(directory, additional_dir)
302 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
304 l_files = os.listdir(dir_complete)
305 for file_n in l_files:
306 if file_n == file_name:
307 return os.path.join(dir_complete, file_name)
310 def handleRemoveReadonly(func, path, exc):
312 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
313 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
318 def deepcopy_list(input_list):
319 """ Do a deep copy of a list
321 :param input_list List: The list to copy
322 :return: The copy of the list
326 for elem in input_list:
330 def remove_item_from_list(input_list, item):
331 """ Remove all occurences of item from input_list
333 :param input_list List: The list to modify
334 :return: The without any item
338 for elem in input_list:
344 def parse_date(date):
345 """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
347 :param date str: The date to transform
348 :return: The date in the new format
353 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
361 def merge_dicts(*dict_args):
363 Given any number of dicts, shallow copy and merge into a new dict,
364 precedence goes to key value pairs in latter dicts.
367 for dictionary in dict_args:
368 result.update(dictionary)
371 def replace_in_file(filein, strin, strout):
372 '''Replace <strin> by <strout> in file <filein>
374 shutil.move(filein, filein + "_old")
376 filein = filein + "_old"
377 fin = open(filein, "r")
378 fout = open(fileout, "w")
380 fout.write(line.replace(strin, strout))
382 def get_property_in_product_cfg(product_cfg, pprty):
383 if not "properties" in product_cfg:
385 if not pprty in product_cfg.properties:
387 return product_cfg.properties[pprty]