Salome HOME
Improvement of "setenv.py" script - setting of custom enviroment by those modules...
[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     'makeTmpDir',
47     'uniteFiles',
48     ]
49
50 # ---
51
52 def _try_bool( arg ):
53     """
54     Check if specified parameter represents boolean value and returns its value.
55     String values like 'True', 'TRUE', 'YES', 'Yes', 'y', 'NO', 'false', 'n', etc
56     are supported.
57     If <arg> does not represent a boolean, an exception is raised.
58     """
59     import types
60     if type( arg ) == types.BooleanType  :
61         return arg
62     elif type( arg ) == types.StringType  :
63         v = str( arg ).lower()
64         if   v in [ "yes", "y", "true"  ]: return True
65         elif v in [ "no",  "n", "false" ]: return False
66         pass
67     raise Exception("Not boolean value")
68
69 # ---
70
71 def getORBcfgInfo():
72     """
73     Get omniORB current configuration.
74     Returns a list of three values: [ orb_version, host_name, port_number ].
75     
76     The information is retrieved from the omniORB configuration file defined
77     by the OMNIORB_CONFIG environment variable.
78     If omniORB configuration file can not be accessed, a list of three empty
79     strings is returned.
80     """
81     import os, re
82     ret = [ "", "", "" ]
83     try:
84         f = open( os.getenv( "OMNIORB_CONFIG" ) )
85         lines = f.readlines()
86         f.close()
87         regvar = re.compile( "(ORB)?InitRef.*corbaname::(.*):(\d+)\s*$" )
88         for l in lines:
89             try:
90                 m = regvar.match( l )
91                 if m:
92                     if m.group(1) is None:
93                         ret[0] = "4"
94                     else:
95                         ret[0] = "3"
96                         pass
97                     ret[1] = m.group(2)
98                     ret[2] = m.group(3)
99                     break
100                 pass
101             except:
102                 pass
103             pass
104         pass
105     except:
106         pass
107     return ret
108
109 # ---
110
111 def getHostFromORBcfg():
112     """
113     Get current omniORB host.
114     """
115     return getORBcfgInfo()[1]
116 # ---
117
118 def getPortFromORBcfg():
119     """
120     Get current omniORB port.
121     """
122     return getORBcfgInfo()[2]
123
124 # ---
125
126 def getUserName():
127     """
128     Get user name:
129     1. try USER environment variable
130     2. if fails, return 'unknown' as default user name
131     """
132     import os
133     return os.getenv( "USER", "unknown" ) # 'unknown' is default user name
134
135 # ---
136
137 def getHostName():
138     """
139     Get host name:
140     1. try socket python module gethostname() function
141     2. if fails, try HOSTNAME environment variable
142     3. if fails, try HOST environment variable
143     4. if fails, return 'unknown' as default host name
144     """
145     import os
146     try:
147         import socket
148         host = socket.gethostname()
149     except:
150         host = None
151         pass
152     if not host: host = os.getenv("HOSTNAME")
153     if not host: host = os.getenv("HOST")
154     if not host: host = "unknown"           # 'unknown' is default host name
155     return host
156
157 # ---
158
159 def getShortHostName():
160     """
161     Get short host name:
162     1. try socket python module gethostname() function
163     2. if fails, try HOSTNAME environment variable
164     3. if fails, try HOST environment variable
165     4. if fails, return 'unknown' as default host name
166     """
167     try:
168         return getHostName().split('.')[0]
169     except:
170         pass
171     return "unknown"           # 'unknown' is default host name
172     
173 # ---
174
175 def getAppName():
176     """
177     Get application name:
178     1. try APPNAME environment variable
179     2. if fails, return 'SALOME' as default application name
180     """
181     import os
182     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
183
184 # ---
185
186 def getPortNumber():
187     """
188     Get current naming server port number:
189     1. try NSPORT environment variable
190     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
191     2. if fails, return 2809 as default port number
192     """
193     import os
194     try:
195         return int( os.getenv( "NSPORT" ) )
196     except:
197         pass
198     port = getPortFromORBcfg()
199     if port is not None: return port
200     return 2809      # '2809' is default port number
201
202 # ---
203
204 def getTmpDir():
205     """
206     Get directory to be used for the temporary files.
207     """
208     import os, sys
209     if sys.platform == "win32":
210         # for Windows: temporarily using home directory for tmp files;
211         # to be replaced with TEMP environment variable later...
212         dir = os.getenv("HOME")
213     else:
214         # for Linux: use /tmp/logs/{user} folder
215         dir = os.path.join( '/tmp', 'logs', getUserName() )
216         pass
217     return dir
218
219 # ---
220
221 def generateFileName( dir, prefix = None, suffix = None, extension = None,
222                       unique = False, separator = "_", hidden = False, **kwargs ):
223     """
224     Generate file name by sepecified parameters. If necessary, file name
225     can be generated to be unique.
226
227     Parameters:
228     - dir       : directory path
229     - prefix    : file prefix (not added by default)
230     - suffix    : file suffix (not added by default)
231     - extension : file extension (not added by default)
232     - unique    : if this parameter is True, the unique file name is generated:
233     in this case, if the file with the generated name already exists
234     in the <dir> directory, an integer suffix is added to the end of the
235     file name. This parameter is False by default.
236     - separator : separator of the words ('_' by default)
237     - hidden    : if this parameter is True, the file name is prepended by . (dot)
238     symbol. This parameter is False by default.
239
240     Other keyword parameters are:
241     - with_username : 'add user name' flag/option:
242       * boolean value can be passed to determine user name automatically
243       * string value to be used as user name
244     - with_hostname : 'add host name' flag/option:
245       * boolean value can be passed to determine host name automatically
246       * string value to be used as host name
247     - with_port     : 'add port number' flag/option:
248       * boolean value can be passed to determine port number automatically
249       * string value to be used as port number
250     - with_app      : 'add application name' flag/option:
251       * boolean value can be passed to determine application name automatically
252       * string value to be used as application name
253     All <with_...> parameters are optional.
254     """
255     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
256     from launchConfigureParser import verbose
257     filename = []
258     # separator
259     if separator is None:
260         separator = ""
261         pass
262     else:
263         separator = str( separator )
264         pass
265     # prefix (if specified)
266     if prefix is not None:
267         filename.append( str( prefix ) )
268         pass
269     # additional keywords
270     ### check unsupported parameters
271     for kw in kwargs:
272         if kw not in supported and verbose():
273             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
274             pass
275         pass
276     ### process supported keywords
277     for kw in supported:
278         if kw not in kwargs: continue
279         ### user name
280         if kw == 'with_username':
281             try:
282                 # auto user name ?
283                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
284                 pass
285             except:
286                 # user name given as parameter
287                 filename.append( kwargs[kw] )
288                 pass
289             pass
290         ### host name
291         elif kw == 'with_hostname':
292             try:
293                 # auto host name ?
294                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
295                 pass
296             except:
297                 # host name given as parameter
298                 filename.append( kwargs[kw] )
299                 pass
300             pass
301         ### port number
302         elif kw == 'with_port':
303             try:
304                 # auto port number ?
305                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
306                 pass
307             except:
308                 # port number given as parameter
309                 filename.append( str( kwargs[kw] ) )
310                 pass
311             pass
312         ### application name
313         elif kw == 'with_app':
314             try:
315                 # auto application name ?
316                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
317                 pass
318             except:
319                 # application name given as parameter
320                 filename.append( kwargs[kw] )
321                 pass
322             pass
323         pass
324     # suffix (if specified)
325     if suffix is not None:
326         filename.append( str( suffix ) )
327         pass
328     # raise an exception if file name is empty
329     if not filename:
330         raise Exception("Empty file name")
331     #
332     if extension is not None and extension.startswith("."): extension = extension[1:]
333     #
334     import os
335     name = separator.join( filename )
336     if hidden: name = "." + name                       # add dot for hidden files
337     if extension: name = name + "." + str( extension ) # add extension if defined
338     name = os.path.join( dir, name )
339     if unique:
340         # create unique file name
341         index = 0
342         while os.path.exists( name ):
343             index = index + 1
344             name = separator.join( filename ) + separator + str( index )
345             if hidden: name = "." + name                       # add dot for hidden files
346             if extension: name = name + "." + str( extension ) # add extension if defined
347             name = os.path.join( dir, name )
348             pass
349         pass
350     return os.path.normpath(name)
351
352 # ---
353
354 def makeTmpDir( path ):
355     """
356     Make temporary directory with the specified path.
357     If the directory exists then clear its contents.
358
359     Parameters:
360     - path : absolute path to the directory to be created.
361     """
362     import os
363
364     if os.path.exists( path ):
365         os.system( "rm -rf " + path + "/*" )
366         pass
367     else:
368         os.makedirs( path, 0777 )
369         pass
370
371 # ---
372
373 def uniteFiles( src_file, dest_file ):
374     """
375     Unite contents of the source file with contents of the destination file
376     and put result of the uniting to the destination file.
377     If the destination file does not exist then the source file is simply
378     copied to its path.
379
380     Parameters:
381     - src_file  : absolute path to the source file
382     - dest_file : absolute path to the destination file
383     """
384     import os
385
386     if not os.path.exists( src_file ):
387         return
388         pass
389
390     if os.path.exists( dest_file ):
391         # add a symbol of new line to contents of the destination file (just in case)
392         dest = open( dest_file, 'r' )
393         dest_lines = dest.readlines()
394         dest.close()
395
396         dest_lines.append( "\n" )
397
398         dest = open( dest_file, 'w' )
399         dest.writelines( dest_lines )
400         dest.close()
401
402         command = "cat " + src_file + " >> " + dest_file
403         pass
404     else:
405         command = "cp " + src_file + " " + dest_file
406         pass
407
408     os.system( command )