Salome HOME
add 'context' command
[modules/yacs.git] / bin / salome_utils.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2015  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, or (at your option) any later version.
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     'getLogDir',
43     'getTmpDir',
44     'getHomeDir',
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 (USERNAME on windows)
130     2. if fails, return 'unknown' as default user name
131     """
132     import os, sys
133     if sys.platform == "win32":
134         return os.getenv("USERNAME", "unknown")
135     else:
136         return os.getenv("USER", "unknown")
137 # ---
138
139 def getHostName():
140     """
141     Get host name:
142     1. try socket python module gethostname() function
143     2. if fails, try HOSTNAME environment variable
144     3. if fails, try HOST environment variable
145     4. if fails, return 'unknown' as default host name
146     """
147     import os
148     try:
149         import socket
150         host = socket.gethostname()
151     except:
152         host = None
153         pass
154     if not host: host = os.getenv("HOSTNAME")
155     if not host: host = os.getenv("HOST")
156     if not host: host = "unknown"           # 'unknown' is default host name
157     return host
158
159 # ---
160
161 def getShortHostName():
162     """
163     Get short host name:
164     1. try socket python module gethostname() function
165     2. if fails, try HOSTNAME environment variable
166     3. if fails, try HOST environment variable
167     4. if fails, return 'unknown' as default host name
168     """
169     try:
170         return getHostName().split('.')[0]
171     except:
172         pass
173     return "unknown"           # 'unknown' is default host name
174
175 # ---
176
177 def getAppName():
178     """
179     Get application name:
180     1. try APPNAME environment variable
181     2. if fails, return 'SALOME' as default application name
182     """
183     import os
184     return os.getenv( "APPNAME", "SALOME" ) # 'SALOME' is default user name
185
186 # ---
187
188 def getPortNumber(use_default=True):
189     """
190     Get current naming server port number:
191     1. try NSPORT environment variable
192     1. if fails, try to parse config file defined by OMNIORB_CONFIG environment variable
193     2. if fails, return 2809 as default port number (if use_default is True) or None (id use_default is False)
194     """
195     import os
196     try:
197         return int( os.getenv( "NSPORT" ) )
198     except:
199         pass
200     try:
201         port = int( getPortFromORBcfg() )
202         if port is not None: return port
203     except:
204         pass
205     if use_default: return 2809 # '2809' is default port number
206     return None
207
208 # ---
209
210 def getHomeDir():
211     """
212     Get home directory.
213     """
214     import os
215     return os.path.realpath(os.path.expanduser('~'))
216 # ---
217
218 def getLogDir():
219     """
220     Get directory to be used for the log files.
221     """
222     import os
223     return os.path.join(getTmpDir(), "logs", getUserName())
224 # ---
225
226 def getTmpDir():
227     """
228     Get directory to be used for the temporary files.
229     """
230     import os, tempfile
231     f = tempfile.NamedTemporaryFile()
232     tmpdir = os.path.dirname(f.name)
233     f.close()
234     return tmpdir
235 # ---
236
237 def generateFileName( dir, prefix = None, suffix = None, extension = None,
238                       unique = False, separator = "_", hidden = False, **kwargs ):
239     """
240     Generate file name by sepecified parameters. If necessary, file name
241     can be generated to be unique.
242
243     Parameters:
244     - dir       : directory path
245     - prefix    : file prefix (not added by default)
246     - suffix    : file suffix (not added by default)
247     - extension : file extension (not added by default)
248     - unique    : if this parameter is True, the unique file name is generated:
249     in this case, if the file with the generated name already exists
250     in the <dir> directory, an integer suffix is added to the end of the
251     file name. This parameter is False by default.
252     - separator : separator of the words ('_' by default)
253     - hidden    : if this parameter is True, the file name is prepended by . (dot)
254     symbol. This parameter is False by default.
255
256     Other keyword parameters are:
257     - with_username : 'add user name' flag/option:
258       * boolean value can be passed to determine user name automatically
259       * string value to be used as user name
260     - with_hostname : 'add host name' flag/option:
261       * boolean value can be passed to determine host name automatically
262       * string value to be used as host name
263     - with_port     : 'add port number' flag/option:
264       * boolean value can be passed to determine port number automatically
265       * string value to be used as port number
266     - with_app      : 'add application name' flag/option:
267       * boolean value can be passed to determine application name automatically
268       * string value to be used as application name
269     All <with_...> parameters are optional.
270     """
271     supported = [ 'with_username', 'with_hostname', 'with_port', 'with_app' ]
272     from launchConfigureParser import verbose
273     filename = []
274     # separator
275     if separator is None:
276         separator = ""
277         pass
278     else:
279         separator = str( separator )
280         pass
281     # prefix (if specified)
282     if prefix is not None:
283         filename.append( str( prefix ) )
284         pass
285     # additional keywords
286     ### check unsupported parameters
287     for kw in kwargs:
288         if kw not in supported and verbose():
289             print 'Warning! salome_utilitie.py: generateFileName(): parameter %s is not supported' % kw
290             pass
291         pass
292     ### process supported keywords
293     for kw in supported:
294         if kw not in kwargs: continue
295         ### user name
296         if kw == 'with_username':
297             try:
298                 # auto user name ?
299                 if _try_bool( kwargs[kw] ): filename.append( getUserName() )
300                 pass
301             except:
302                 # user name given as parameter
303                 filename.append( kwargs[kw] )
304                 pass
305             pass
306         ### host name
307         elif kw == 'with_hostname':
308             try:
309                 # auto host name ?
310                 if _try_bool( kwargs[kw] ): filename.append( getShortHostName() )
311                 pass
312             except:
313                 # host name given as parameter
314                 filename.append( kwargs[kw] )
315                 pass
316             pass
317         ### port number
318         elif kw == 'with_port':
319             try:
320                 # auto port number ?
321                 if _try_bool( kwargs[kw] ): filename.append( str( getPortNumber() ) )
322                 pass
323             except:
324                 # port number given as parameter
325                 filename.append( str( kwargs[kw] ) )
326                 pass
327             pass
328         ### application name
329         elif kw == 'with_app':
330             try:
331                 # auto application name ?
332                 if _try_bool( kwargs[kw] ): filename.append( getAppName() )
333                 pass
334             except:
335                 # application name given as parameter
336                 filename.append( kwargs[kw] )
337                 pass
338             pass
339         pass
340     # suffix (if specified)
341     if suffix is not None:
342         filename.append( str( suffix ) )
343         pass
344     # raise an exception if file name is empty
345     if not filename:
346         raise Exception("Empty file name")
347     #
348     if extension is not None and extension.startswith("."): extension = extension[1:]
349     #
350     import os
351     name = separator.join( filename )
352     if hidden: name = "." + name                       # add dot for hidden files
353     if extension: name = name + "." + str( extension ) # add extension if defined
354     name = os.path.join( dir, name )
355     if unique:
356         # create unique file name
357         index = 0
358         while os.path.exists( name ):
359             index = index + 1
360             name = separator.join( filename ) + separator + str( index )
361             if hidden: name = "." + name                       # add dot for hidden files
362             if extension: name = name + "." + str( extension ) # add extension if defined
363             name = os.path.join( dir, name )
364             pass
365         pass
366     return os.path.normpath(name)
367
368 # ---
369
370 def makeTmpDir( path, mode=0777 ):
371     """
372     Make temporary directory with the specified path.
373     If the directory exists then clear its contents.
374
375     Parameters:
376     - path : absolute path to the directory to be created.
377     - mode : access mode
378     """
379     import os
380     if os.path.exists( path ):
381         import sys
382         if sys.platform == "win32":
383             os.system( "rmdir /S /Q " + '"' + path + '"' )
384             os.system( "mkdir " + '"' + path + '"' )
385         else:
386             os.system( "rm -rf " + path + "/*" )
387     else:
388         dirs = path.split("/")
389         shift1 = shift2 = 0
390         if not dirs[0]: shift1 = 1
391         if dirs[-1]: shift2 = 1
392         for i in range(1+shift1,len(dirs)+shift2):
393             p = "/".join(dirs[:i])
394             try:
395                 os.mkdir(p, mode)
396                 os.chmod(p, mode)
397             except:
398                 pass
399
400 # ---
401
402 def uniteFiles( src_file, dest_file ):
403     """
404     Unite contents of the source file with contents of the destination file
405     and put result of the uniting to the destination file.
406     If the destination file does not exist then the source file is simply
407     copied to its path.
408
409     Parameters:
410     - src_file  : absolute path to the source file
411     - dest_file : absolute path to the destination file
412     """
413     import os
414
415     if not os.path.exists( src_file ):
416         return
417         pass
418
419     if os.path.exists( dest_file ):
420         # add a symbol of new line to contents of the destination file (just in case)
421         dest = open( dest_file, 'r' )
422         dest_lines = dest.readlines()
423         dest.close()
424
425         dest_lines.append( "\n" )
426
427         dest = open( dest_file, 'w' )
428         dest.writelines( dest_lines )
429         dest.close()
430
431         import sys
432         if sys.platform == "win32":
433             command = "type " + '"' + src_file + '"' + " >> " + '"' + dest_file + '"'
434         else:
435             command = "cat " + src_file + " >> " + dest_file
436             pass
437         pass
438     else:
439         import sys
440         if sys.platform == "win32":
441             command = "copy " + '"' + src_file + '"' + " " + '"' + dest_file + '"' + " > nul"
442         else:
443             command = "cp " + src_file + " " + dest_file
444             pass
445         pass
446
447     os.system( command )
448
449 # --
450
451 _verbose = None
452
453 def verbose():
454     """
455     Get verbosity level. Default verbosity level is specified via the environment variable
456     SALOME_VERBOSE, e.g.:
457     [bash %] export SALOME_VERBOSE=1
458     The function setVerbose() can be used to change verbosity level explicitly.
459     """
460     global _verbose
461     # verbose has already been called
462     if _verbose is not None:
463         return _verbose
464     # first time
465     try:
466         from os import getenv
467         _verbose = int(getenv('SALOME_VERBOSE'))
468     except:
469         _verbose = 0
470         pass
471     #
472     return _verbose
473 # --
474
475 def setVerbose(level):
476     """
477     Change verbosity level. The function verbose() can be used to get current verbosity level.
478     """
479     global _verbose
480     _verbose = level
481     return
482 # --