Salome HOME
rename salome runner/launcher as salome context
[modules/kernel.git] / bin / salomeContextUtils.py.in
1 #! /usr/bin/env python
2
3 # Copyright (C) 2013-2014  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21
22 import os
23 import sys
24 import glob
25 import subprocess
26 import re
27
28 """
29 Define a specific exception class to manage exceptions related to SalomeContext
30 """
31 class SalomeContextException(Exception):
32   """Report error messages to the user interface of SalomeContext."""
33 #
34
35 def __listDirectory(path):
36   allFiles = []
37   for root, dirs, files in os.walk(path):
38     configFileNames = glob.glob(os.path.join(root,'*.cfg')) + glob.glob(os.path.join(root,'*.sh'))
39     allFiles += configFileNames
40   return allFiles
41 #
42
43 def __getConfigFileNamesDefault():
44   absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
45   if not absoluteAppliPath:
46     return []
47
48   envdDir = absoluteAppliPath + '/env.d'
49   if not os.path.isdir(envdDir):
50     return []
51
52   return __listDirectory(envdDir)
53 #
54
55 def getConfigFileNames(args, checkExistence=False):
56   # special case: configuration files are provided by user
57   # Search for command-line argument(s) --config=file1,file2,..., filen
58   # Search for command-line argument(s) --config=dir1,dir2,..., dirn
59   configOptionPrefix = "--config="
60   configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
61
62   if len(configArgs) == 0:
63     return __getConfigFileNamesDefault(), args, []
64
65   args = [ x for x in args if not x.startswith(configOptionPrefix) ]
66   allLists = [ x.replace(configOptionPrefix, '') for x in configArgs ]
67
68   configFileNames = []
69   unexisting = []
70   for currentList in allLists:
71     elements = currentList.split(',')
72     for elt in elements:
73       elt = os.path.realpath(os.path.expanduser(elt))
74       if os.path.isdir(elt):
75         configFileNames += __listDirectory(elt)
76       else:
77         if checkExistence and not os.path.isfile(elt):
78           unexisting += [elt]
79         else:
80           configFileNames += [elt]
81
82   return configFileNames, args, unexisting
83 #
84
85 # Return an array of dictionaries {script_name: [list_of_its_args]}
86 def getScriptsAndArgs(args=[]):
87   # Syntax of args: script.py [args:a1,a2=val,an] ... script.py [args:a1,a2=val,an]
88   scriptArgs = []
89   currentKey = None
90   argsPrefix = "args:"
91   callPython = False
92   currentScript = None
93
94   for i in range(len(args)):
95     elt = args[i]
96
97     if elt.startswith(argsPrefix):
98       if not currentKey or callPython:
99         raise SalomeContextException("args list must follow corresponding script file in command line.")
100       elt = elt.replace(argsPrefix, '')
101       scriptArgs[len(scriptArgs)-1][currentKey] = elt.split(",")
102       currentKey = None
103       callPython = False
104     elif elt.startswith("python"):
105       callPython = True
106     elif os.path.isfile(elt) or os.path.isfile(elt+".py"):
107       if elt[-4:] != ".hdf":
108         if elt[-3:] == ".py":
109           currentScript = os.path.abspath(elt)
110         elif os.path.isfile(elt+".py"):
111           currentScript = os.path.abspath(elt+".py")
112         else:
113           currentScript = os.path.abspath(elt) # python script not necessary has .py extension
114         pass
115       if currentScript and callPython:
116         currentKey = "@PYTHONBIN@ "+currentScript
117         scriptArgs.append({currentKey:[]})
118         callPython = False
119       elif currentScript:
120         if not os.access(currentScript, os.X_OK):
121           currentKey = "@PYTHONBIN@ "+currentScript
122           scriptArgs.append({currentKey:[]})
123         else:
124           ispython = False
125           try:
126             fn = open(currentScript)
127             for i in xrange(10): # read only 10 first lines
128               ln = fn.readline()
129               if re.search("#!.*python"):
130                 ispython = True
131                 break
132               pass
133             fn.close()
134           except:
135             pass
136           if not ispython and currentScript[-3:] == ".py":
137             currentKey = "@PYTHONBIN@ "+currentScript
138           else:
139             currentKey = currentScript
140             pass
141           scriptArgs.append({currentKey:[]})
142   # end for loop
143   return scriptArgs
144 #
145
146 # Formatting scripts and args as a Bash-like command-line:
147 # script1.py [args] ; script2.py [args] ; ...
148 def formatScriptsAndArgs(scriptArgs=[]):
149     commands = []
150     for sc_dict in scriptArgs:
151       for script, sc_args in sc_dict.items(): # single entry
152         cmd = script
153         if sc_args:
154           cmd = cmd + " " + " ".join(sc_args)
155         commands.append(cmd)
156     sep = " ; "
157     if sys.platform == "win32":
158       sep= " & "
159     command = sep.join(["%s"%x for x in commands])
160     return command
161 #
162
163 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a the folder in which
164 # SALOME will write omniOrb configuration files.
165 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
166 # an exception is raised if check fails. It allows users for choosing a specific folder.
167 # Else the function sets OMNIORB_USER_PATH this way:
168 # - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
169 #   The function does not check USERS folder existence or wrute access. This folder
170 #   must exist ; this is the case if SALOME virtual application has been create using
171 #   appli_gen.py script.
172 # - Else OMNIORB_USER_PATH is set to user home directory.
173 def setOmniOrbUserPath():
174   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
175   if omniorbUserPath:
176     if not os.access(omniorbUserPath, os.W_OK):
177       raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
178     pass
179   else:
180     homePath = os.path.realpath(os.path.expanduser('~'))
181     #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
182     defaultOmniorbUserPath = homePath
183     if os.getenv("APPLI"):
184       defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
185       pass
186     os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
187 #