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
40 KNOWNFAILURE_STATUS = "KF"
41 TIMEOUT_STATUS = "TIMEOUT"
43 CONFIG_FILENAME = "sat-config.pyconf"
45 class SatException(Exception):
46 '''rename Exception Class
50 def ensure_path_exists(p):
51 '''Create a path if not existing
53 :param p str: The path.
55 if not os.path.exists(p):
58 def check_config_has_application( config, details = None ):
59 '''check that the config has the key APPLICATION. Else raise an exception.
61 :param config class 'common.pyconf.Config': The config.
63 if 'APPLICATION' not in config:
64 message = _("An APPLICATION is required. Use 'config --list' to get"
65 " the list of available applications.\n")
67 details.append(message)
68 raise SatException( message )
70 def check_config_has_profile( config, details = None ):
71 '''check that the config has the key APPLICATION.profile.
72 Else, raise an exception.
74 :param config class 'common.pyconf.Config': The config.
76 check_config_has_application(config)
77 if 'profile' not in config.APPLICATION:
78 message = _("A profile section is required in your application.\n")
80 details.append(message)
81 raise SatException( message )
83 def config_has_application( config ):
84 return 'APPLICATION' in config
86 def get_cfg_param(config, param_name, default):
87 '''Search for param_name value in config.
88 If param_name is not in config, then return default,
89 else, return the found value
91 :param config class 'common.pyconf.Config': The config.
92 :param param_name str: the name of the parameter to get the value
93 :param default str: The value to return if param_name is not in config
94 :return: see initial description of the function
97 if param_name in config:
98 return config[param_name]
101 def print_info(logger, info):
102 '''Prints the tuples that are in info variable in a formatted way.
104 :param logger Logger: The logging instance to use for the prints.
105 :param info list: The list of tuples to display
107 # find the maximum length of the first value of the tuples in info
108 smax = max(map(lambda l: len(l[0]), info))
109 # Print each item of info with good indentation
111 sp = " " * (smax - len(i[0]))
112 printcolors.print_value(logger, sp + i[0], i[1], 2)
113 logger.write("\n", 2)
115 def get_base_path(config):
116 '''Returns the path of the product base.
118 :param config Config: The global Config instance.
119 :return: The path of the product base.
122 if "base" in config.SITE:
123 base_path = config.SITE.base
126 base_path = config.USER.base
129 def get_salome_version(config):
130 if hasattr(config.APPLICATION, 'version_salome'):
131 Version = config.APPLICATION.version_salome
133 KERNEL_info = product.get_product_config(config, "KERNEL")
134 VERSION = os.path.join(
135 KERNEL_info.install_dir,
139 if not os.path.isfile(VERSION):
142 fVERSION = open(VERSION)
143 Version = fVERSION.readline()
146 VersionSalome = int(only_numbers(Version))
149 def only_numbers(str_num):
150 return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
152 def read_config_from_a_file(filePath):
154 cfg_file = pyconf.Config(filePath)
155 except pyconf.ConfigError as e:
156 raise SatException(_("Error in configuration file: %(file)s\n %(error)s") % \
157 { 'file': filePath, 'error': str(e) })
160 def get_tmp_filename(cfg, name):
161 if not os.path.exists(cfg.VARS.tmp_root):
162 os.makedirs(cfg.VARS.tmp_root)
164 return os.path.join(cfg.VARS.tmp_root, name)
167 # Utils class to simplify path manipulations.
169 def __init__(self, path):
170 self.path = str(path)
172 def __add__(self, other):
173 return Path(os.path.join(self.path, str(other)))
176 return Path(os.path.abspath(self.path))
181 def __eq__(self, other):
182 return self.path == other.path
185 return self.islink() or os.path.exists(self.path)
188 return os.path.islink(self.path)
191 return os.path.isdir(self.path)
194 return [Path(p) for p in os.listdir(self.path)]
197 return Path(os.path.dirname(self.path))
200 return Path(os.path.basename(self.path))
202 def make(self, mode=None):
203 os.makedirs(self.path)
205 os.chmod(self.path, mode)
207 def chmod(self, mode):
208 os.chmod(self.path, mode)
214 shutil.rmtree( self.path, onerror = handleRemoveReadonly )
216 def copy(self, path, smart=False):
217 if not isinstance(path, Path):
220 if os.path.islink(self.path):
221 return self.copylink(path)
222 elif os.path.isdir(self.path):
223 return self.copydir(path, smart)
225 return self.copyfile(path)
227 def smartcopy(self, path):
228 return self.copy(path, True)
232 return os.readlink(self.path)
236 def symlink(self, path):
238 os.symlink(str(path), self.path)
243 def copylink(self, path):
245 os.symlink(os.readlink(self.path), str(path))
250 def copydir(self, dst, smart=False):
260 if smart and (str(name) in [".git", "CVS", ".svn"]):
262 srcname = self + name
264 srcname.copy(dstname, smart)
269 def copyfile(self, path):
271 shutil.copy2(self.path, str(path))
276 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
277 """Find in all the directories in lpath list the file that has the same name
278 as file_name. If it is found, return the full path of the file, else,
280 The additional_dir (optional) is the name of the directory to add to all
283 :param file_name str: The file name to search
284 :param lpath List: The list of directories where to search
285 :param additional_dir str: The name of the additional directory
286 :return: the full path of the file or False if not found
289 for directory in lpath:
290 dir_complete = os.path.join(directory, additional_dir)
291 if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
293 l_files = os.listdir(dir_complete)
294 for file_n in l_files:
295 if file_n == file_name:
296 return os.path.join(dir_complete, file_name)
299 def handleRemoveReadonly(func, path, exc):
301 if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
302 os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
307 def deepcopy_list(input_list):
308 """ Do a deep copy of a list
310 :param input_list List: The list to copy
311 :return: The copy of the list
315 for elem in input_list:
319 def parse_date(date):
320 """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
322 :param date str: The date to transform
323 :return: The date in the new format
328 res = "%s-%s-%s %s:%s:%s" % (date[0:4],
336 def merge_dicts(*dict_args):
338 Given any number of dicts, shallow copy and merge into a new dict,
339 precedence goes to key value pairs in latter dicts.
342 for dictionary in dict_args:
343 result.update(dictionary)
346 def replace_in_file(filein, strin, strout):
347 '''Replace <strin> by <strout> in file <filein>
349 shutil.move(filein, filein + "_old")
351 filein = filein + "_old"
352 fin = open(filein, "r")
353 fout = open(fileout, "w")
355 fout.write(line.replace(strin, strout))