Salome HOME
Revert "Synchronize adm files"
[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     cfgFiles = glob.glob(os.path.join(root,'*.cfg'))
39     allFiles += cfgFiles
40
41     shFiles = glob.glob(os.path.join(root,'*.sh'))
42     for f in shFiles:
43       no_ext = os.path.splitext(f)[0]
44       if not os.path.isfile(no_ext+".cfg"):
45         allFiles.append(f)
46
47   return allFiles
48 #
49
50 def __getConfigFileNamesDefault():
51   absoluteAppliPath = os.getenv('ABSOLUTE_APPLI_PATH','')
52   if not absoluteAppliPath:
53     return []
54
55   envdDir = absoluteAppliPath + '/env.d'
56   if not os.path.isdir(envdDir):
57     return []
58
59   return __listDirectory(envdDir)
60 #
61
62 def getConfigFileNames(args, checkExistence=False):
63   # special case: configuration files are provided by user
64   # Search for command-line argument(s) --config=file1,file2,..., filen
65   # Search for command-line argument(s) --config=dir1,dir2,..., dirn
66   configOptionPrefix = "--config="
67   configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
68
69   if len(configArgs) == 0:
70     return __getConfigFileNamesDefault(), args, []
71
72   args = [ x for x in args if not x.startswith(configOptionPrefix) ]
73   allLists = [ x.replace(configOptionPrefix, '') for x in configArgs ]
74
75   configFileNames = []
76   unexisting = []
77   for currentList in allLists:
78     elements = currentList.split(',')
79     for elt in elements:
80       elt = os.path.realpath(os.path.expanduser(elt))
81       if os.path.isdir(elt):
82         configFileNames += __listDirectory(elt)
83       else:
84         if checkExistence and not os.path.isfile(elt):
85           unexisting += [elt]
86         else:
87           configFileNames += [elt]
88
89   return configFileNames, args, unexisting
90 #
91
92 def __getScriptPath(scriptName, searchPathList):
93   if searchPathList is None or len(searchPathList) == 0:
94     return None
95
96   for path in searchPathList:
97     fullName = os.path.join(path, scriptName)
98     if os.path.isfile(fullName) or os.path.isfile(fullName+".py"):
99       return fullName
100
101   return None
102 #
103
104 # Return an array of dictionaries {script_name: [list_of_its_args]}
105 def getScriptsAndArgs(args=[], searchPathList=None):
106   if searchPathList is None:
107     searchPathList = sys.path
108
109   # Syntax of args: script.py [args:a1,a2=val,an] ... script.py [args:a1,a2=val,an]
110   scriptArgs = []
111   currentKey = None
112   argsPrefix = "args:"
113   callPython = False
114   currentScript = None
115
116   for i in range(len(args)):
117     elt = args[i]
118
119     if elt.startswith(argsPrefix):
120       if not currentKey or callPython:
121         raise SalomeContextException("args list must follow corresponding script file in command line.")
122       elt = elt.replace(argsPrefix, '')
123       scriptArgs[len(scriptArgs)-1][currentKey] = elt.split(",")
124       currentKey = None
125       callPython = False
126     elif elt.startswith("python"):
127       callPython = True
128     else:
129       if not os.path.isfile(elt) and not os.path.isfile(elt+".py"):
130         eltInSearchPath = __getScriptPath(elt, searchPathList)
131         if eltInSearchPath is None or (not os.path.isfile(eltInSearchPath) and not os.path.isfile(eltInSearchPath+".py")):
132           if elt[-3:] == ".py":
133             raise SalomeContextException("Script not found: %s"%elt)
134           continue
135         elt = eltInSearchPath
136
137       if elt[-4:] != ".hdf":
138         if elt[-3:] == ".py":
139           currentScript = os.path.abspath(elt)
140         elif os.path.isfile(elt+".py"):
141           currentScript = os.path.abspath(elt+".py")
142         else:
143           currentScript = os.path.abspath(elt) # python script not necessary has .py extension
144         pass
145       if currentScript and callPython:
146         currentKey = "@PYTHONBIN@ "+currentScript
147         scriptArgs.append({currentKey:[]})
148         callPython = False
149       elif currentScript:
150         if not os.access(currentScript, os.X_OK):
151           currentKey = "@PYTHONBIN@ "+currentScript
152           scriptArgs.append({currentKey:[]})
153         else:
154           ispython = False
155           try:
156             fn = open(currentScript)
157             for i in xrange(10): # read only 10 first lines
158               ln = fn.readline()
159               if re.search("#!.*python"):
160                 ispython = True
161                 break
162               pass
163             fn.close()
164           except:
165             pass
166           if not ispython and currentScript[-3:] == ".py":
167             currentKey = "@PYTHONBIN@ "+currentScript
168           else:
169             currentKey = currentScript
170             pass
171           scriptArgs.append({currentKey:[]})
172   # end for loop
173   return scriptArgs
174 #
175
176 # Formatting scripts and args as a Bash-like command-line:
177 # script1.py [args] ; script2.py [args] ; ...
178 def formatScriptsAndArgs(scriptArgs=[]):
179     commands = []
180     for sc_dict in scriptArgs:
181       for script, sc_args in sc_dict.items(): # single entry
182         cmd = script
183         if sc_args:
184           cmd = cmd + " " + " ".join(sc_args)
185         commands.append(cmd)
186     sep = " ; "
187     if sys.platform == "win32":
188       sep= " & "
189     command = sep.join(["%s"%x for x in commands])
190     return command
191 #
192
193 # Ensure OMNIORB_USER_PATH is defined. This variable refers to a the folder in which
194 # SALOME will write omniOrb configuration files.
195 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
196 # an exception is raised if check fails. It allows users for choosing a specific folder.
197 # Else the function sets OMNIORB_USER_PATH this way:
198 # - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
199 #   The function does not check USERS folder existence or write access. This folder
200 #   must exist ; this is the case if SALOME virtual application has been created using
201 #   appli_gen.py script.
202 # - Else OMNIORB_USER_PATH is set to user home directory.
203 def setOmniOrbUserPath():
204   omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
205   if omniorbUserPath:
206     if not os.access(omniorbUserPath, os.W_OK):
207       raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
208     pass
209   else:
210     homePath = os.path.realpath(os.path.expanduser('~'))
211     #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
212     defaultOmniorbUserPath = homePath
213     if os.getenv("APPLI"):
214       defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
215       pass
216     os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
217 #