Salome HOME
04a0928a6ef47721820afb78db3f4ffb5ae0c753
[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
35 OK_STATUS = "OK"
36 KO_STATUS = "KO"
37 NA_STATUS = "NA"
38
39 class SatException(Exception):
40     '''rename Exception Class
41     '''
42     pass
43
44 def ensure_path_exists(p):
45     '''Create a path if not existing
46     
47     :param p str: The path.
48     '''
49     if not os.path.exists(p):
50         os.makedirs(p)
51         
52 def check_config_has_application( config, details = None ):
53     '''check that the config has the key APPLICATION. Else raise an exception.
54     
55     :param config class 'common.pyconf.Config': The config.
56     '''
57     if 'APPLICATION' not in config:
58         message = _("An APPLICATION is required. Use 'config --list' to get"
59                     " the list of available applications.\n")
60         if details :
61             details.append(message)
62         raise SatException( message )
63
64 def config_has_application( config ):
65     return 'APPLICATION' in config
66
67 def get_cfg_param(config, param_name, default):
68     '''Search for param_name value in config.
69        If param_name is not in config, then return default,
70        else, return the found value
71        
72     :param config class 'common.pyconf.Config': The config.
73     :param param_name str: the name of the parameter to get the value
74     :param default str: The value to return if param_name is not in config
75     :return: see initial description of the function
76     :rtype: str
77     '''
78     if param_name in config:
79         return config[param_name]
80     return default
81
82 def print_info(logger, info):
83     '''Prints the tuples that are in info variable in a formatted way.
84     
85     :param logger Logger: The logging instance to use for the prints.
86     :param info list: The list of tuples to display
87     '''
88     # find the maximum length of the first value of the tuples in info
89     smax = max(map(lambda l: len(l[0]), info))
90     # Print each item of info with good indentation
91     for i in info:
92         sp = " " * (smax - len(i[0]))
93         printcolors.print_value(logger, sp + i[0], i[1], 2)
94     logger.write("\n", 2)
95
96 def get_base_path(config):
97     '''Returns the path of the product base.
98     
99     :param config Config: The global Config instance.
100     :return: The path of the product base.
101     :rtype: str
102     '''
103     if "base" in config.APPLICATION:
104         base_name = config.APPLICATION.base
105         base_path = config.USER.bases[base_name]
106     else:
107         # default base
108         base_path = config.USER.bases.base
109     return base_path
110
111 ##
112 # Utils class to simplify path manipulations.
113 class Path:
114     def __init__(self, path):
115         self.path = str(path)
116
117     def __add__(self, other):
118         return Path(os.path.join(self.path, str(other)))
119
120     def __abs__(self):
121         return Path(os.path.abspath(self.path))
122
123     def __str__(self):
124         return self.path
125
126     def __eq__(self, other):
127         return self.path == other.path
128
129     def exists(self):
130         return self.islink() or os.path.exists(self.path)
131
132     def islink(self):
133         return os.path.islink(self.path)
134
135     def isdir(self):
136         return os.path.isdir(self.path)
137
138     def list(self):
139         return [Path(p) for p in os.listdir(self.path)]
140
141     def dir(self):
142         return Path(os.path.dirname(self.path))
143
144     def base(self):
145         return Path(os.path.basename(self.path))
146
147     def make(self, mode=None):
148         os.makedirs(self.path)        
149         if mode:
150             os.chmod(self.path, mode)
151         
152     def chmod(self, mode):
153         os.chmod(self.path, mode)
154
155     def rm(self):    
156         if self.islink():
157             os.remove(self.path)
158         else:
159             shutil.rmtree( self.path, onerror = handleRemoveReadonly )
160
161     def copy(self, path, smart=False):
162         if not isinstance(path, Path):
163             path = Path(path)
164
165         if os.path.islink(self.path):
166             return self.copylink(path)
167         elif os.path.isdir(self.path):
168             return self.copydir(path, smart)
169         else:
170             return self.copyfile(path)
171
172     def smartcopy(self, path):
173         return self.copy(path, True)
174
175     def readlink(self):
176         if self.islink():
177             return os.readlink(self.path)
178         else:
179             return False
180
181     def symlink(self, path):
182         try:
183             os.symlink(str(path), self.path)
184             return True
185         except:
186             return False
187
188     def copylink(self, path):
189         try:
190             os.symlink(os.readlink(self.path), str(path))
191             return True
192         except:
193             return False
194
195     def copydir(self, dst, smart=False):
196         try:
197             names = self.list()
198
199             if not dst.exists():
200                 dst.make()
201
202             for name in names:
203                 if name == dst:
204                     continue
205                 if smart and (str(name) in [".git", "CVS", ".svn"]):
206                     continue
207                 srcname = self + name
208                 dstname = dst + name
209                 srcname.copy(dstname, smart)
210             return True
211         except:
212             return False
213
214     def copyfile(self, path):
215         try:
216             shutil.copy2(self.path, str(path))
217             return True
218         except:
219             return False
220
221 def handleRemoveReadonly(func, path, exc):
222     excvalue = exc[1]
223     if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
224         os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
225         func(path)
226     else:
227         raise