Salome HOME
Merge from V5_1_main 14/05/2010
[modules/kernel.git] / bin / salome_utils.py
1 #  -*- coding: iso-8859-1 -*-
2 #  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 #  This library is free software; you can redistribute it and/or
5 #  modify it under the terms of the GNU Lesser General Public
6 #  License as published by the Free Software Foundation; either
7 #  version 2.1 of the License.
8 #
9 #  This library is distributed in the hope that it will be useful,
10 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 #  Lesser General Public License for more details.
13 #
14 #  You should have received a copy of the GNU Lesser General Public
15 #  License along with this library; if not, write to the Free Software
16 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 # ---
22 # File   : salome_utils.py
23 # Author : Vadim SANDLER, Open CASCADE S.A.S. (vadim.sandler@opencascade.com)
24 # ---
25
26 ## @package salome_utils
27 # \brief Set of utility functions used by SALOME python scripts.
28
29 #
30 # Exported functions
31 #
32
33 __all__ = [
34     'getORBcfgInfo',
35     'getHostFromORBcfg',
36     'getPortFromORBcfg',
37     'getUserName',
38     'getHostName',
39     'getShortHostName',
40     'getAppName',
41     'getPortNumber',
42     'getTmpDir',
43     'generateFileName',
44     'makeTmpDir',
45     'uniteFiles',
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(use_default=True):
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 (if use_default is True) or None (id use_default is False)
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     if use_default: return 2809 # '2809' is default port number
199     return None
200
201 # ---
202
203 def getTmpDir():
204     """
205     Get directory to be used for the temporary files.
206     """
207     import os, sys
208     if sys.platform == "win32":
209         # for Windows: temporarily using home directory for tmp files;
210         # to be replaced with TEMP environment variable later...
211         dir = os.getenv("HOME")
212     else:
213         # for Linux: use /tmp/logs/{user} folder
214         dir = os.path.join( '/tmp', 'logs', getUserName() )
215         pass
216     return dir
217
218 # ---
219
220 def generateFileName( dir, prefix = None, suffix = None, extension = None,
221                       unique = False, separator = "_", hidden = False, **kwargs ):
222     """
223     Generate file name by sepecified parameters. If necessary, file name
224     can be generated to be unique.
225
226     Parameters:
227     - dir       : directory path
228     - prefix    : file prefix (not added by default)
229     - suffix    : file suffix (not added by default)
230     - extension : file extension (not added by default)
231     - unique    : if this parameter is True, the unique file name is generated:
232     in this case, if the file with the generated name already exists
233     in the <dir> directory, an integer suffix is added to the end of the
234     file name. This parameter is False by default.
235     - separator : separator of the words ('_' by default)
236     - hidden    : if this parameter is True, the file name is prepended by . (dot)
237     symbol. This parameter is False by default.
238
239     Other keyword parameters are:
240     - with_username : 'add user name' flag/option:
241       * boolean value can be passed to determine user name automatically
242       * string value to be used as user name
243     - with_hostname : 'add host name' flag/option:
244       * boolean value can be passed to determine host name automatically
245       * string value to be used as host name
246     - with_port     : 'add port number' flag/option:
247       * boolean value can be passed to determine port number automatically
248       * string value to be used as port number
249     - with_app      : 'add application name' flag/option:
250       * boolean value can be passed to determine application name automatically
251       * string value to be used as application name
252     All <with_...> parameters are optional.
253     """
254     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
255     from launchConfigureParser import verbose
256     filename = []
257     # separator
258     if separator is None:
259         separator = ""
260         pass
261     else:
262         separator = str( separator )
263         pass
264     # prefix (if specified)
265     if prefix is not None:
266         filename.append( str( prefix ) )
267         pass
268     # additional keywords
269     ### check unsupported parameters
270     for kw in kwargs:
271         if kw not in supported and verbose():
272             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
273             pass
274         pass
275     ### process supported keywords
276     for kw in supported:
277         if kw not in kwargs: continue
278         ### user name
279         if kw == 'with_username':
280             try:
281                 # auto user name ?
282                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
283                 pass
284             except:
285                 # user name given as parameter
286                 filename.append( kwargs[kw] )
287                 pass
288             pass
289         ### host name
290         elif kw == 'with_hostname':
291             try:
292                 # auto host name ?
293                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
294                 pass
295             except:
296                 # host name given as parameter
297                 filename.append( kwargs[kw] )
298                 pass
299             pass
300         ### port number
301         elif kw == 'with_port':
302             try:
303                 # auto port number ?
304                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
305                 pass
306             except:
307                 # port number given as parameter
308                 filename.append( str( kwargs[kw] ) )
309                 pass
310             pass
311         ### application name
312         elif kw == 'with_app':
313             try:
314                 # auto application name ?
315                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
316                 pass
317             except:
318                 # application name given as parameter
319                 filename.append( kwargs[kw] )
320                 pass
321             pass
322         pass
323     # suffix (if specified)
324     if suffix is not None:
325         filename.append( str( suffix ) )
326         pass
327     # raise an exception if file name is empty
328     if not filename:
329         raise Exception("Empty file name")
330     #
331     if extension is not None and extension.startswith("."): extension = extension[1:]
332     #
333     import os
334     name = separator.join( filename )
335     if hidden: name = "." + name                       # add dot for hidden files
336     if extension: name = name + "." + str( extension ) # add extension if defined
337     name = os.path.join( dir, name )
338     if unique:
339         # create unique file name
340         index = 0
341         while os.path.exists( name ):
342             index = index + 1
343             name = separator.join( filename ) + separator + str( index )
344             if hidden: name = "." + name                       # add dot for hidden files
345             if extension: name = name + "." + str( extension ) # add extension if defined
346             name = os.path.join( dir, name )
347             pass
348         pass
349     return os.path.normpath(name)
350
351 # ---
352
353 def makeTmpDir( path, mode=0777 ):
354     """
355     Make temporary directory with the specified path.
356     If the directory exists then clear its contents.
357
358     Parameters:
359     - path : absolute path to the directory to be created.
360     - mode : access mode
361     """
362     import os
363     if os.path.exists( path ):
364         import sys
365         if sys.platform == "win32":
366             os.system( "rmdir /S /Q " + '"' + path + '"' )
367             os.system( "mkdir " + '"' + path + '"' )
368         else:
369             os.system( "rm -rf " + path + "/*" )
370             pass
371         pass
372     else:
373         dirs = path.split("/")
374         shift1 = shift2 = 0
375         if not dirs[0]: shift1 = 1
376         if dirs[-1]: shift2 = 1
377         for i in range(1+shift1,len(dirs)+shift2):
378             p = "/".join(dirs[:i])
379             try:
380                 os.mkdir(p, mode)
381                 os.chmod(p, mode)
382             except:
383                 pass
384             pass
385         pass
386     pass
387
388 # ---
389
390 def uniteFiles( src_file, dest_file ):
391     """
392     Unite contents of the source file with contents of the destination file
393     and put result of the uniting to the destination file.
394     If the destination file does not exist then the source file is simply
395     copied to its path.
396
397     Parameters:
398     - src_file  : absolute path to the source file
399     - dest_file : absolute path to the destination file
400     """
401     import os
402
403     if not os.path.exists( src_file ):
404         return
405         pass
406
407     if os.path.exists( dest_file ):
408         # add a symbol of new line to contents of the destination file (just in case)
409         dest = open( dest_file, 'r' )
410         dest_lines = dest.readlines()
411         dest.close()
412
413         dest_lines.append( "\n" )
414
415         dest = open( dest_file, 'w' )
416         dest.writelines( dest_lines )
417         dest.close()
418
419         import sys
420         if sys.platform == "win32":
421             command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
422         else:
423             command = "cat " + src_file + " >> " + dest_file
424             pass
425         pass
426     else:
427         import sys
428         if sys.platform == "win32":
429             command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
430         else:
431             command = "cp " + src_file + " " + dest_file
432             pass
433         pass
434
435     os.system( command )