Salome HOME
add a runSalome.bat for windows
[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(use_default=True):
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 (if use_default is True) or None (id use_default is False)
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     if use_default: return 2809 # '2809' is default port number
201     return None
202
203 # ---
204
205 def getTmpDir():
206     """
207     Get directory to be used for the temporary files.
208     """
209     import os, sys
210     if sys.platform == "win32":
211         # for Windows: temporarily using home directory for tmp files;
212         # to be replaced with TEMP environment variable later...
213         dir = os.getenv("HOME")
214     else:
215         # for Linux: use /tmp/logs/{user} folder
216         dir = os.path.join( '/tmp', 'logs', getUserName() )
217         pass
218     return dir
219
220 # ---
221
222 def generateFileName( dir, prefix = None, suffix = None, extension = None,
223                       unique = False, separator = "_", hidden = False, **kwargs ):
224     """
225     Generate file name by sepecified parameters. If necessary, file name
226     can be generated to be unique.
227
228     Parameters:
229     - dir       : directory path
230     - prefix    : file prefix (not added by default)
231     - suffix    : file suffix (not added by default)
232     - extension : file extension (not added by default)
233     - unique    : if this parameter is True, the unique file name is generated:
234     in this case, if the file with the generated name already exists
235     in the <dir> directory, an integer suffix is added to the end of the
236     file name. This parameter is False by default.
237     - separator : separator of the words ('_' by default)
238     - hidden    : if this parameter is True, the file name is prepended by . (dot)
239     symbol. This parameter is False by default.
240
241     Other keyword parameters are:
242     - with_username : 'add user name' flag/option:
243       * boolean value can be passed to determine user name automatically
244       * string value to be used as user name
245     - with_hostname : 'add host name' flag/option:
246       * boolean value can be passed to determine host name automatically
247       * string value to be used as host name
248     - with_port     : 'add port number' flag/option:
249       * boolean value can be passed to determine port number automatically
250       * string value to be used as port number
251     - with_app      : 'add application name' flag/option:
252       * boolean value can be passed to determine application name automatically
253       * string value to be used as application name
254     All <with_...> parameters are optional.
255     """
256     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
257     from launchConfigureParser import verbose
258     filename = []
259     # separator
260     if separator is None:
261         separator = ""
262         pass
263     else:
264         separator = str( separator )
265         pass
266     # prefix (if specified)
267     if prefix is not None:
268         filename.append( str( prefix ) )
269         pass
270     # additional keywords
271     ### check unsupported parameters
272     for kw in kwargs:
273         if kw not in supported and verbose():
274             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
275             pass
276         pass
277     ### process supported keywords
278     for kw in supported:
279         if kw not in kwargs: continue
280         ### user name
281         if kw == 'with_username':
282             try:
283                 # auto user name ?
284                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
285                 pass
286             except:
287                 # user name given as parameter
288                 filename.append( kwargs[kw] )
289                 pass
290             pass
291         ### host name
292         elif kw == 'with_hostname':
293             try:
294                 # auto host name ?
295                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
296                 pass
297             except:
298                 # host name given as parameter
299                 filename.append( kwargs[kw] )
300                 pass
301             pass
302         ### port number
303         elif kw == 'with_port':
304             try:
305                 # auto port number ?
306                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
307                 pass
308             except:
309                 # port number given as parameter
310                 filename.append( str( kwargs[kw] ) )
311                 pass
312             pass
313         ### application name
314         elif kw == 'with_app':
315             try:
316                 # auto application name ?
317                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
318                 pass
319             except:
320                 # application name given as parameter
321                 filename.append( kwargs[kw] )
322                 pass
323             pass
324         pass
325     # suffix (if specified)
326     if suffix is not None:
327         filename.append( str( suffix ) )
328         pass
329     # raise an exception if file name is empty
330     if not filename:
331         raise Exception("Empty file name")
332     #
333     if extension is not None and extension.startswith("."): extension = extension[1:]
334     #
335     import os
336     name = separator.join( filename )
337     if hidden: name = "." + name                       # add dot for hidden files
338     if extension: name = name + "." + str( extension ) # add extension if defined
339     name = os.path.join( dir, name )
340     if unique:
341         # create unique file name
342         index = 0
343         while os.path.exists( name ):
344             index = index + 1
345             name = separator.join( filename ) + separator + str( index )
346             if hidden: name = "." + name                       # add dot for hidden files
347             if extension: name = name + "." + str( extension ) # add extension if defined
348             name = os.path.join( dir, name )
349             pass
350         pass
351     return os.path.normpath(name)
352
353 # ---
354
355 def makeTmpDir( path, mode=0777 ):
356     """
357     Make temporary directory with the specified path.
358     If the directory exists then clear its contents.
359
360     Parameters:
361     - path : absolute path to the directory to be created.
362     - mode : access mode
363     """
364     import os
365     if os.path.exists( path ):
366         os.system( "rm -rf " + path + "/*" )
367         pass
368     else:
369         dirs = path.split("/")
370         shift1 = shift2 = 0
371         if not dirs[0]: shift1 = 1
372         if dirs[-1]: shift2 = 1
373         for i in range(1+shift1,len(dirs)+shift2):
374             p = "/".join(dirs[:i])
375             try:
376                 os.mkdir(p, mode)
377                 os.chmod(p, mode)
378             except:
379                 pass
380             pass
381         pass
382     pass
383
384 # ---
385
386 def uniteFiles( src_file, dest_file ):
387     """
388     Unite contents of the source file with contents of the destination file
389     and put result of the uniting to the destination file.
390     If the destination file does not exist then the source file is simply
391     copied to its path.
392
393     Parameters:
394     - src_file  : absolute path to the source file
395     - dest_file : absolute path to the destination file
396     """
397     import os
398
399     if not os.path.exists( src_file ):
400         return
401         pass
402
403     if os.path.exists( dest_file ):
404         # add a symbol of new line to contents of the destination file (just in case)
405         dest = open( dest_file, 'r' )
406         dest_lines = dest.readlines()
407         dest.close()
408
409         dest_lines.append( "\n" )
410
411         dest = open( dest_file, 'w' )
412         dest.writelines( dest_lines )
413         dest.close()
414
415         command = "cat " + src_file + " >> " + dest_file
416         pass
417     else:
418         command = "cp " + src_file + " " + dest_file
419         pass
420
421     os.system( command )