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