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