Salome HOME
CCAR: documentation update
[modules/kernel.git] / bin / salome_utils.py
1 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 #
6 #  This library is free software; you can redistribute it and/or
7 #  modify it under the terms of the GNU Lesser General Public
8 #  License as published by the Free Software Foundation; either
9 #  version 2.1 of the License.
10 #
11 #  This library is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 #  Lesser General Public License for more details.
15 #
16 #  You should have received a copy of the GNU Lesser General Public
17 #  License along with this library; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #
22 # ---
23 # File   : salome_utils.py
24 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
25 # ---
26 #
27 ## @package salome_utils
28 # \brief Set of utility functions used by SALOME python scripts.
29 #
30 #
31
32 #
33 # Exported functions
34 #
35 __all__ = [
36     'getORBcfgInfo',
37     'getHostFromORBcfg',
38     'getPortFromORBcfg',
39     'getUserName',
40     'getHostName',
41     'getShortHostName',
42     'getAppName',
43     'getPortNumber',
44     'getTmpDir',
45     'generateFileName',
46     ]
47
48 # ---
49
50 def _try_bool( arg ):
51     """
52     Check if specified parameter represents boolean value and returns its value.
53     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
54     are supported.
55     If <arg> does not represent a boolean, an exception is raised.
56     """
57     import types
58     if type( arg ) == types.BooleanType  :
59         return arg
60     elif type( arg ) == types.StringType  :
61         v = str( arg ).lower()
62         if   v in [ "yes", "y", "true"  ]: return True
63         elif v in [ "no",  "n", "false" ]: return False
64         pass
65     raise Exception("Not boolean value")
66
67 # ---
68
69 def getORBcfgInfo():
70     """
71     Get omniORB current configuration.
72     Returns a list of three values: [ orb_version, host_name, port_number ].
73     
74     The information is retrieved from the omniORB configuration file defined
75     by the OMNIORB_CONFIG environment variable.
76     If omniORB configuration file can not be accessed, a list of three empty
77     strings is returned.
78     """
79     import os, re
80     ret = [ "", "", "" ]
81     try:
82         f = open( os.getenv( "OMNIORB_CONFIG" ) )
83         lines = f.readlines()
84         f.close()
85         regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
86         for l in lines:
87             try:
88                 m = regvar.match( l )
89                 if m:
90                     if m.group(1) is None:
91                         ret[0] = "4"
92                     else:
93                         ret[0] = "3"
94                         pass
95                     ret[1] = m.group(2)
96                     ret[2] = m.group(3)
97                     break
98                 pass
99             except:
100                 pass
101             pass
102         pass
103     except:
104         pass
105     return ret
106
107 # ---
108
109 def getHostFromORBcfg():
110     """
111     Get current omniORB host.
112     """
113     return getORBcfgInfo()[1]
114 # ---
115
116 def getPortFromORBcfg():
117     """
118     Get current omniORB port.
119     """
120     return getORBcfgInfo()[2]
121
122 # ---
123
124 def getUserName():
125     """
126     Get user name:
127     1. try USER environment variable
128     2. if fails, return 'unknown' as default user name
129     """
130     import os
131     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
132
133 # ---
134
135 def getHostName():
136     """
137     Get host name:
138     1. try socket python module gethostname() function
139     2. if fails, try HOSTNAME environment variable
140     3. if fails, try HOST environment variable
141     4. if fails, return 'unknown' as default host name
142     """
143     import os
144     try:
145         import socket
146         host = socket.gethostname()
147     except:
148         host = None
149         pass
150     if not host: host = os.getenv("HOSTNAME")
151     if not host: host = os.getenv("HOST")
152     if not host: host = "unknown"           # 'unknown' is default host name
153     return host
154
155 # ---
156
157 def getShortHostName():
158     """
159     Get short host name:
160     1. try socket python module gethostname() function
161     2. if fails, try HOSTNAME environment variable
162     3. if fails, try HOST environment variable
163     4. if fails, return 'unknown' as default host name
164     """
165     try:
166         return getHostName().split('.')[0]
167     except:
168         pass
169     return "unknown"           # 'unknown' is default host name
170     
171 # ---
172
173 def getAppName():
174     """
175     Get application name:
176     1. try APPNAME environment variable
177     2. if fails, return 'SALOME' as default application name
178     """
179     import os
180     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
181
182 # ---
183
184 def getPortNumber():
185     """
186     Get current naming server port number:
187     1. try NSPORT environment variable
188     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
189     2. if fails, return 2809 as default port number
190     """
191     import os
192     try:
193         return int( os.getenv( "NSPORT" ) )
194     except:
195         pass
196     port = getPortFromORBcfg()
197     if port is not None: return port
198     return 2809      # '2809' is default port number
199
200 # ---
201
202 def getTmpDir():
203     """
204     Get directory to be used for the temporary files.
205     """
206     import os, sys
207     if sys.platform == "win32":
208         # for Windows: temporarily using home directory for tmp files;
209         # to be replaced with TEMP environment variable later...
210         dir = os.getenv("HOME")
211     else:
212         # for Linux: use /tmp/logs/{user} folder
213         dir = os.path.join( '/tmp', 'logs', getUserName() )
214         pass
215     return dir
216
217 # ---
218
219 def generateFileName( dir, prefix = None, suffix = None, extension = None,
220                       unique = False, separator = "_", hidden = False, **kwargs ):
221     """
222     Generate file name by sepecified parameters. If necessary, file name
223     can be generated to be unique.
224
225     Parameters:
226     - dir       : directory path
227     - prefix    : file prefix (not added by default)
228     - suffix    : file suffix (not added by default)
229     - extension : file extension (not added by default)
230     - unique    : if this parameter is True, the unique file name is generated:
231     in this case, if the file with the generated name already exists
232     in the <dir> directory, an integer suffix is added to the end of the
233     file name. This parameter is False by default.
234     - separator : separator of the words ('_' by default)
235     - hidden    : if this parameter is True, the file name is prepended by . (dot)
236     symbol. This parameter is False by default.
237
238     Other keyword parameters are:
239     - with_username : 'add user name' flag/option:
240       * boolean value can be passed to determine user name automatically
241       * string value to be used as user name
242     - with_hostname : 'add host name' flag/option:
243       * boolean value can be passed to determine host name automatically
244       * string value to be used as host name
245     - with_port     : 'add port number' flag/option:
246       * boolean value can be passed to determine port number automatically
247       * string value to be used as port number
248     - with_app      : 'add application name' flag/option:
249       * boolean value can be passed to determine application name automatically
250       * string value to be used as application name
251     All <with_...> parameters are optional.
252     """
253     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
254     from launchConfigureParser import verbose
255     filename = []
256     # separator
257     if separator is None:
258         separator = ""
259         pass
260     else:
261         separator = str( separator )
262         pass
263     # prefix (if specified)
264     if prefix is not None:
265         filename.append( str( prefix ) )
266         pass
267     # additional keywords
268     ### check unsupported parameters
269     for kw in kwargs:
270         if kw not in supported and verbose():
271             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
272             pass
273         pass
274     ### process supported keywords
275     for kw in supported:
276         if kw not in kwargs: continue
277         ### user name
278         if kw == 'with_username':
279             try:
280                 # auto user name ?
281                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
282                 pass
283             except:
284                 # user name given as parameter
285                 filename.append( kwargs[kw] )
286                 pass
287             pass
288         ### host name
289         elif kw == 'with_hostname':
290             try:
291                 # auto host name ?
292                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
293                 pass
294             except:
295                 # host name given as parameter
296                 filename.append( kwargs[kw] )
297                 pass
298             pass
299         ### port number
300         elif kw == 'with_port':
301             try:
302                 # auto port number ?
303                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
304                 pass
305             except:
306                 # port number given as parameter
307                 filename.append( str( kwargs[kw] ) )
308                 pass
309             pass
310         ### application name
311         elif kw == 'with_app':
312             try:
313                 # auto application name ?
314                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
315                 pass
316             except:
317                 # application name given as parameter
318                 filename.append( kwargs[kw] )
319                 pass
320             pass
321         pass
322     # suffix (if specified)
323     if suffix is not None:
324         filename.append( str( suffix ) )
325         pass
326     # raise an exception if file name is empty
327     if not filename:
328         raise Exception("Empty file name")
329     #
330     if extension is not None and extension.startswith("."): extension = extension[1:]
331     #
332     import os
333     name = separator.join( filename )
334     if hidden: name = "." + name                       # add dot for hidden files
335     if extension: name = name + "." + str( extension ) # add extension if defined
336     name = os.path.join( dir, name )
337     if unique:
338         # create unique file name
339         index = 0
340         while os.path.exists( name ):
341             index = index + 1
342             name = separator.join( filename ) + separator + str( index )
343             if hidden: name = "." + name                       # add dot for hidden files
344             if extension: name = name + "." + str( extension ) # add extension if defined
345             name = os.path.join( dir, name )
346             pass
347         pass
348     return os.path.normpath(name)