Salome HOME
search scripts given as command line args in sys path
[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 def __getScriptPath(scriptName, searchPathList):
86   if searchPathList is None or len(searchPathList) == 0:
87     return None
88
89   for path in searchPathList:
90     fullName = os.path.join(path, scriptName)
91     if os.path.isfile(fullName) or os.path.isfile(fullName+".py"):
92       return fullName
93
94   return None
95 #
96
97 # Return an array of dictionaries {script_name: [list_of_its_args]}
98 def getScriptsAndArgs(args=[], searchPathList=None):
99   if searchPathList is None:
100     searchPathList = sys.path
101
102   # Syntax of args: script.py [args:a1,a2=val,an] ... script.py [args:a1,a2=val,an]
103   scriptArgs = []
104   currentKey = None
105   argsPrefix = "args:"
106   callPython = False
107   currentScript = None
108
109   for i in range(len(args)):
110     elt = args[i]
111
112     if elt.startswith(argsPrefix):
113       if not currentKey or callPython:
114         raise SalomeContextException("args list must follow corresponding script file in command line.")
115       elt = elt.replace(argsPrefix, '')
116       scriptArgs[len(scriptArgs)-1][currentKey] = elt.split(",")
117       currentKey = None
118       callPython = False
119     elif elt.startswith("python"):
120       callPython = True
121     else:
122       if not os.path.isfile(elt) and not os.path.isfile(elt+".py"):
123         eltInSearchPath = __getScriptPath(elt, searchPathList)
124         if eltInSearchPath is None or (not os.path.isfile(eltInSearchPath) and not os.path.isfile(eltInSearchPath+".py")):
125           raise SalomeContextException("Script not found: %s"%elt)
126         elt = eltInSearchPath
127
128       if elt[-4:] != ".hdf":
129         if elt[-3:] == ".py":
130           currentScript = os.path.abspath(elt)
131         elif os.path.isfile(elt+".py"):
132           currentScript = os.path.abspath(elt+".py")
133         else:
134           currentScript = os.path.abspath(elt) # python script not necessary has .py extension
135         pass
136       if currentScript and callPython:
137         currentKey = "@PYTHONBIN@ "+currentScript
138         scriptArgs.append({currentKey:[]})
139         callPython = False
140       elif currentScript:
141         if not os.access(currentScript, os.X_OK):
142           currentKey = "@PYTHONBIN@ "+currentScript
143           scriptArgs.append({currentKey:[]})
144         else:
145           ispython = False
146           try:
147             fn = open(currentScript)
148             for i in xrange(10): # read only 10 first lines
149               ln = fn.readline()
150               if re.search("#!.*python"):
151                 ispython = True
152                 break
153               pass
154             fn.close()
155           except:
156             pass
157           if not ispython and currentScript[-3:] == ".py":
158             currentKey = "@PYTHONBIN@ "+currentScript
159           else:
160             currentKey = currentScript
161             pass
162           scriptArgs.append({currentKey:[]})
163   # end for loop
164   return scriptArgs
165 #
166
167 # Formatting scripts and args as a Bash-like command-line:
168 # script1.py [args] ; script2.py [args] ; ...
169 def formatScriptsAndArgs(scriptArgs=[]):
170     commands = []
171     for sc_dict in scriptArgs:
172       for script, sc_args in sc_dict.items(): # single entry
173         cmd = script
174         if sc_args:
175           cmd = cmd + " " + " ".join(sc_args)
176         commands.append(cmd)
177     sep = " ; "
178     if sys.platform == "win32":
179       sep= " & "
180     command = sep.join(["%s"%x for x in commands])
181     return command
182 #
183
184 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a the folder in which
185 # SALOME will write omniOrb configuration files.
186 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
187 # an exception is raised if check fails. It allows users for choosing a specific folder.
188 # Else the function sets OMNIORB_USER_PATH this way:
189 # - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
190 #   The function does not check USERS folder existence or wrute access. This folder
191 #   must exist ; this is the case if SALOME virtual application has been create using
192 #   appli_gen.py script.
193 # - Else OMNIORB_USER_PATH is set to user home directory.
194 def setOmniOrbUserPath():
195   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
196   if omniorbUserPath:
197     if not os.access(omniorbUserPath, os.W_OK):
198       raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
199     pass
200   else:
201     homePath = os.path.realpath(os.path.expanduser('~'))
202     #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
203     defaultOmniorbUserPath = homePath
204     if os.getenv("APPLI"):
205       defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
206       pass
207     os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
208 #