Salome HOME
exception raised if given script is not found
[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           if elt[-3:] == ".py":
126             raise SalomeContextException("Script not found: %s"%elt)
127           continue
128         elt = eltInSearchPath
129
130       if elt[-4:] != ".hdf":
131         if elt[-3:] == ".py":
132           currentScript = os.path.abspath(elt)
133         elif os.path.isfile(elt+".py"):
134           currentScript = os.path.abspath(elt+".py")
135         else:
136           currentScript = os.path.abspath(elt) # python script not necessary has .py extension
137         pass
138       if currentScript and callPython:
139         currentKey = "@PYTHONBIN@ "+currentScript
140         scriptArgs.append({currentKey:[]})
141         callPython = False
142       elif currentScript:
143         if not os.access(currentScript, os.X_OK):
144           currentKey = "@PYTHONBIN@ "+currentScript
145           scriptArgs.append({currentKey:[]})
146         else:
147           ispython = False
148           try:
149             fn = open(currentScript)
150             for i in xrange(10): # read only 10 first lines
151               ln = fn.readline()
152               if re.search("#!.*python"):
153                 ispython = True
154                 break
155               pass
156             fn.close()
157           except:
158             pass
159           if not ispython and currentScript[-3:] == ".py":
160             currentKey = "@PYTHONBIN@ "+currentScript
161           else:
162             currentKey = currentScript
163             pass
164           scriptArgs.append({currentKey:[]})
165   # end for loop
166   return scriptArgs
167 #
168
169 # Formatting scripts and args as a Bash-like command-line:
170 # script1.py [args] ; script2.py [args] ; ...
171 def formatScriptsAndArgs(scriptArgs=[]):
172     commands = []
173     for sc_dict in scriptArgs:
174       for script, sc_args in sc_dict.items(): # single entry
175         cmd = script
176         if sc_args:
177           cmd = cmd + " " + " ".join(sc_args)
178         commands.append(cmd)
179     sep = " ; "
180     if sys.platform == "win32":
181       sep= " & "
182     command = sep.join(["%s"%x for x in commands])
183     return command
184 #
185
186 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a the folder in which
187 # SALOME will write omniOrb configuration files.
188 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
189 # an exception is raised if check fails. It allows users for choosing a specific folder.
190 # Else the function sets OMNIORB_USER_PATH this way:
191 # - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
192 #   The function does not check USERS folder existence or wrute access. This folder
193 #   must exist ; this is the case if SALOME virtual application has been create using
194 #   appli_gen.py script.
195 # - Else OMNIORB_USER_PATH is set to user home directory.
196 def setOmniOrbUserPath():
197   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
198   if omniorbUserPath:
199     if not os.access(omniorbUserPath, os.W_OK):
200       raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
201     pass
202   else:
203     homePath = os.path.realpath(os.path.expanduser('~'))
204     #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
205     defaultOmniorbUserPath = homePath
206     if os.getenv("APPLI"):
207       defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
208       pass
209     os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
210 #