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