Salome HOME
45da5ccbfa38eac308f0edccbe3daf764e970080
[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.APPLICATION:
118         base_name = config.APPLICATION.base
119         base_path = config.USER.bases[base_name]
120     else:
121         # default base
122         base_path = config.USER.bases.base
123     return base_path
124
125 def only_numbers(str_num):
126     return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
127
128 def read_config_from_a_file(filePath):
129         try:
130             cfg_file = pyconf.Config(filePath)
131         except pyconf.ConfigError as e:
132             raise SatException(_("Error in configuration file: %(file)s\n  %(error)s") % \
133                 { 'file': filePath, 'error': str(e) })
134         return cfg_file
135
136 def get_tmp_filename(cfg, name):
137     if not os.path.exists(cfg.VARS.tmp_root):
138         os.makedirs(cfg.VARS.tmp_root)
139
140     return os.path.join(cfg.VARS.tmp_root, name)
141
142 ##
143 # Utils class to simplify path manipulations.
144 class Path:
145     def __init__(self, path):
146         self.path = str(path)
147
148     def __add__(self, other):
149         return Path(os.path.join(self.path, str(other)))
150
151     def __abs__(self):
152         return Path(os.path.abspath(self.path))
153
154     def __str__(self):
155         return self.path
156
157     def __eq__(self, other):
158         return self.path == other.path
159
160     def exists(self):
161         return self.islink() or os.path.exists(self.path)
162
163     def islink(self):
164         return os.path.islink(self.path)
165
166     def isdir(self):
167         return os.path.isdir(self.path)
168
169     def list(self):
170         return [Path(p) for p in os.listdir(self.path)]
171
172     def dir(self):
173         return Path(os.path.dirname(self.path))
174
175     def base(self):
176         return Path(os.path.basename(self.path))
177
178     def make(self, mode=None):
179         os.makedirs(self.path)        
180         if mode:
181             os.chmod(self.path, mode)
182         
183     def chmod(self, mode):
184         os.chmod(self.path, mode)
185
186     def rm(self):    
187         if self.islink():
188             os.remove(self.path)
189         else:
190             shutil.rmtree( self.path, onerror = handleRemoveReadonly )
191
192     def copy(self, path, smart=False):
193         if not isinstance(path, Path):
194             path = Path(path)
195
196         if os.path.islink(self.path):
197             return self.copylink(path)
198         elif os.path.isdir(self.path):
199             return self.copydir(path, smart)
200         else:
201             return self.copyfile(path)
202
203     def smartcopy(self, path):
204         return self.copy(path, True)
205
206     def readlink(self):
207         if self.islink():
208             return os.readlink(self.path)
209         else:
210             return False
211
212     def symlink(self, path):
213         try:
214             os.symlink(str(path), self.path)
215             return True
216         except:
217             return False
218
219     def copylink(self, path):
220         try:
221             os.symlink(os.readlink(self.path), str(path))
222             return True
223         except:
224             return False
225
226     def copydir(self, dst, smart=False):
227         try:
228             names = self.list()
229
230             if not dst.exists():
231                 dst.make()
232
233             for name in names:
234                 if name == dst:
235                     continue
236                 if smart and (str(name) in [".git", "CVS", ".svn"]):
237                     continue
238                 srcname = self + name
239                 dstname = dst + name
240                 srcname.copy(dstname, smart)
241             return True
242         except:
243             return False
244
245     def copyfile(self, path):
246         try:
247             shutil.copy2(self.path, str(path))
248             return True
249         except:
250             return False
251
252 def handleRemoveReadonly(func, path, exc):
253     excvalue = exc[1]
254     if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
255         os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
256         func(path)
257     else:
258         raise