Salome HOME
base
[tools/sat.git] / src / __init__.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
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.
9 #
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.
14 #
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
18
19 import os
20 import shutil
21 import errno
22 import stat
23
24 from . import pyconf
25 from . import architecture
26 from . import printcolors
27 from . import options
28 from . import system
29 from . import ElementTree
30 from . import logger
31 from . import product
32 from . import environment
33 from . import fileEnviron
34 from . import compilation
35
36 OK_STATUS = "OK"
37 KO_STATUS = "KO"
38 NA_STATUS = "NA"
39
40 class SatException(Exception):
41     '''rename Exception Class
42     '''
43     pass
44
45 def ensure_path_exists(p):
46     '''Create a path if not existing
47     
48     :param p str: The path.
49     '''
50     if not os.path.exists(p):
51         os.makedirs(p)
52         
53 def check_config_has_application( config, details = None ):
54     '''check that the config has the key APPLICATION. Else raise an exception.
55     
56     :param config class 'common.pyconf.Config': The config.
57     '''
58     if 'APPLICATION' not in config:
59         message = _("An APPLICATION is required. Use 'config --list' to get"
60                     " the list of available applications.\n")
61         if details :
62             details.append(message)
63         raise SatException( message )
64
65 def check_config_has_profile( config, details = None ):
66     '''check that the config has the key APPLICATION.profile.
67        Else, raise an exception.
68     
69     :param config class 'common.pyconf.Config': The config.
70     '''
71     check_config_has_application(config)
72     if 'profile' not in config.APPLICATION:
73         message = _("A profile section is required in your application.\n")
74         if details :
75             details.append(message)
76         raise SatException( message )
77
78 def config_has_application( config ):
79     return 'APPLICATION' in config
80
81 def get_cfg_param(config, param_name, default):
82     '''Search for param_name value in config.
83        If param_name is not in config, then return default,
84        else, return the found value
85        
86     :param config class 'common.pyconf.Config': The config.
87     :param param_name str: the name of the parameter to get the value
88     :param default str: The value to return if param_name is not in config
89     :return: see initial description of the function
90     :rtype: str
91     '''
92     if param_name in config:
93         return config[param_name]
94     return default
95
96 def print_info(logger, info):
97     '''Prints the tuples that are in info variable in a formatted way.
98     
99     :param logger Logger: The logging instance to use for the prints.
100     :param info list: The list of tuples to display
101     '''
102     # find the maximum length of the first value of the tuples in info
103     smax = max(map(lambda l: len(l[0]), info))
104     # Print each item of info with good indentation
105     for i in info:
106         sp = " " * (smax - len(i[0]))
107         printcolors.print_value(logger, sp + i[0], i[1], 2)
108     logger.write("\n", 2)
109
110 def get_base_path(config):
111     '''Returns the path of the product base.
112     
113     :param config Config: The global Config instance.
114     :return: The path of the product base.
115     :rtype: str
116     '''
117     if "base" in config.SITE:
118         base_path = config.SITE.base
119     else:
120         # default base
121         base_path = config.USER.base
122     return base_path
123
124 def only_numbers(str_num):
125     return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
126
127 def read_config_from_a_file(filePath):
128         try:
129             cfg_file = pyconf.Config(filePath)
130         except pyconf.ConfigError as e:
131             raise SatException(_("Error in configuration file: %(file)s\n  %(error)s") % \
132                 { 'file': filePath, 'error': str(e) })
133         return cfg_file
134
135 def get_tmp_filename(cfg, name):
136     if not os.path.exists(cfg.VARS.tmp_root):
137         os.makedirs(cfg.VARS.tmp_root)
138
139     return os.path.join(cfg.VARS.tmp_root, name)
140
141 ##
142 # Utils class to simplify path manipulations.
143 class Path:
144     def __init__(self, path):
145         self.path = str(path)
146
147     def __add__(self, other):
148         return Path(os.path.join(self.path, str(other)))
149
150     def __abs__(self):
151         return Path(os.path.abspath(self.path))
152
153     def __str__(self):
154         return self.path
155
156     def __eq__(self, other):
157         return self.path == other.path
158
159     def exists(self):
160         return self.islink() or os.path.exists(self.path)
161
162     def islink(self):
163         return os.path.islink(self.path)
164
165     def isdir(self):
166         return os.path.isdir(self.path)
167
168     def list(self):
169         return [Path(p) for p in os.listdir(self.path)]
170
171     def dir(self):
172         return Path(os.path.dirname(self.path))
173
174     def base(self):
175         return Path(os.path.basename(self.path))
176
177     def make(self, mode=None):
178         os.makedirs(self.path)        
179         if mode:
180             os.chmod(self.path, mode)
181         
182     def chmod(self, mode):
183         os.chmod(self.path, mode)
184
185     def rm(self):    
186         if self.islink():
187             os.remove(self.path)
188         else:
189             shutil.rmtree( self.path, onerror = handleRemoveReadonly )
190
191     def copy(self, path, smart=False):
192         if not isinstance(path, Path):
193             path = Path(path)
194
195         if os.path.islink(self.path):
196             return self.copylink(path)
197         elif os.path.isdir(self.path):
198             return self.copydir(path, smart)
199         else:
200             return self.copyfile(path)
201
202     def smartcopy(self, path):
203         return self.copy(path, True)
204
205     def readlink(self):
206         if self.islink():
207             return os.readlink(self.path)
208         else:
209             return False
210
211     def symlink(self, path):
212         try:
213             os.symlink(str(path), self.path)
214             return True
215         except:
216             return False
217
218     def copylink(self, path):
219         try:
220             os.symlink(os.readlink(self.path), str(path))
221             return True
222         except:
223             return False
224
225     def copydir(self, dst, smart=False):
226         try:
227             names = self.list()
228
229             if not dst.exists():
230                 dst.make()
231
232             for name in names:
233                 if name == dst:
234                     continue
235                 if smart and (str(name) in [".git", "CVS", ".svn"]):
236                     continue
237                 srcname = self + name
238                 dstname = dst + name
239                 srcname.copy(dstname, smart)
240             return True
241         except:
242             return False
243
244     def copyfile(self, path):
245         try:
246             shutil.copy2(self.path, str(path))
247             return True
248         except:
249             return False
250
251 def find_file_in_lpath(file_name, lpath, additional_dir = ""):
252     """Find in all the directories in lpath list the file that has the same name
253        as file_name. If it is found, return the full path of the file, else,
254        return False. 
255        The additional_dir (optional) is the name of the directory to add to all 
256        paths in lpath.
257     
258     :param file_name str: The file name to search
259     :param lpath List: The list of directories where to search
260     :param additional_dir str: The name of the additional directory
261     :return: the full path of the file or False if not found
262     :rtype: str
263     """
264     for directory in lpath:
265         dir_complete = os.path.join(directory, additional_dir)
266         if not os.path.isdir(directory) or not os.path.isdir(dir_complete):
267             continue
268         l_files = os.listdir(dir_complete)
269         for file_n in l_files:
270             if file_n == file_name:
271                 return os.path.join(dir_complete, file_name)
272     return False
273
274 def handleRemoveReadonly(func, path, exc):
275     excvalue = exc[1]
276     if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
277         os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
278         func(path)
279     else:
280         raise
281
282 def deepcopy_list(input_list):
283     """ Do a deep copy of a list
284     
285     :param input_list List: The list to copy
286     :return: The copy of the list
287     :rtype: List
288     """
289     res = []
290     for elem in input_list:
291         res.append(elem)
292     return res