Salome HOME
updated copyright message
[modules/kernel.git] / bin / salomeContextUtils.py.in
index 661f2ad904cefad9915ca63e33d20efa7c22a509..fee74ff042e5eb5999d50c619463afb27154e2e7 100644 (file)
@@ -1,6 +1,4 @@
-#! /usr/bin/env python
-
-# Copyright (C) 2013-2016  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2013-2023  CEA, EDF, OPEN CASCADE
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
@@ -40,12 +38,6 @@ def __listDirectory(path):
     cfgFiles = glob.glob(os.path.join(root,'*.cfg'))
     allFiles += cfgFiles
 
-    shFiles = glob.glob(os.path.join(root,'*.sh'))
-    for f in shFiles:
-      no_ext = os.path.splitext(f)[0]
-      if not os.path.isfile(no_ext+".cfg"):
-        allFiles.append(f)
-
   return allFiles
 #
 
@@ -87,103 +79,16 @@ def __getEnvironmentFileNames(args, optionPrefix, checkExistence):
   return configFileNames, args, unexisting
 #
 
-def __validate_pair(ob):
-  try:
-    if not (len(ob) == 2):
-      #print "Unexpected result:", ob
-      raise ValueError
-  except:
-    return False
-  return True
-#
-def __get_environment_from_batch_command(env_cmd, initial=None):
-  """
-  Take a command (either a single command or list of arguments)
-  and return the environment created after running that command.
-  Note that if the command must be a batch file or .cmd file, or the
-  changes to the environment will not be captured.
-
-  If initial is supplied, it is used as the initial environment passed
-  to the child process.
-  """
-  #if not isinstance(env_cmd, (list, tuple)):
-  #    env_cmd = [env_cmd]
-  # construct the command that will alter the environment
-  #env_cmd = subprocess.list2cmdline(env_cmd)
-  # create a tag so we can tell in the output when the proc is done
-  tag = 'Done running command'
-  # construct a command to do accomplish this
-  cmd = '{env_cmd} && echo "{tag}"'.format(**vars())
-
-  # launch the process
-  proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=initial, shell=True)
-  # parse the output sent to stdout
-  lines = proc.stdout
-  # consume whatever output occurs until the tag is reached
-  #consume(itertools.takewhile(lambda l: tag not in l, lines))
-  # define a way to handle each KEY=VALUE line
-  handle_line = lambda l: l.rstrip().split('=',1)
-  # parse key/values into pairs
-  #pairs = map(handle_line, lines)
-  pairs = []
-  cpt = 0
-  while True:
-    line = lines.readline()
-    cpt = cpt+1
-    if tag in line or cpt > 1000:
-      break
-    if line:
-      pairs.append(line.rstrip().split('=',1))
-  # make sure the pairs are valid
-  valid_pairs = filter(__validate_pair, pairs)
-  # construct a dictionary of the pairs
-  result = dict(valid_pairs)
-  # let the process finish
-  proc.communicate()
-  return result
-#
-def __subtract(ref, dic):
-  result = {}
-  for key,val in ref.items():
-    if not dic.has_key(key):
-      result[key] = val
-    else:
-      # compare values types
-      if (type(dic[key]) != type(val)):
-        result[key] = val
-      else:
-        # compare values
-        if isinstance(val, basestring):
-          tolist1 = dic[key].split(os.pathsep)
-          tolist2 = val.split(os.pathsep)
-          diff = list(set(tolist2)-set(tolist1))
-          if diff:
-            result[key] = os.pathsep.join(diff)
-        else:
-          result[key] = val
-
-  return result
-#
-
 def getConfigFileNames(args, checkExistence=False):
   configOptionPrefix = "--config="
   configArgs = [ str(x) for x in args if str(x).startswith(configOptionPrefix) ]
   if len(configArgs) == 0:
-    configFileNames, unexist1 = __getConfigFileNamesDefault(), []
+    configFileNames, unexist = __getConfigFileNamesDefault(), []
   else:
     # get configuration filenames
-    configFileNames, args, unexist1 = __getEnvironmentFileNames(args, configOptionPrefix, checkExistence)
-
-  # get extra environment
-  extraEnvFileNames, args, unexist2 = __getEnvironmentFileNames(args, "--extra_env=", checkExistence)
-  before = __get_environment_from_batch_command("env")
-  after = {}
-  for filename in extraEnvFileNames:
-    after.update(__get_environment_from_batch_command(filename))
-    pass
+    configFileNames, args, unexist = __getEnvironmentFileNames(args, configOptionPrefix, checkExistence)
 
-  extraEnv = __subtract(after,before)
-  return configFileNames, extraEnv, args, unexist1+unexist2
+  return configFileNames, args, unexist
 #
 
 def __getScriptPath(scriptName, searchPathList):
@@ -281,8 +186,8 @@ def getScriptsAndArgs(args=None, searchPathList=None):
         extracted_args = []
         x = elt.split(",")
         # x is ['[file1', 'file2]', 'val1', 'done', '[1', '2', '3]', '[True', 'False]', 'ok']
-        list_begin_indices = [i for i in xrange(len(x)) if x[i].startswith('[')] # [0, 4, 7]
-        list_end_indices = [i for i in xrange(len(x)) if x[i].endswith(']')] # [1, 6, 8]
+        list_begin_indices = [i for i in range(len(x)) if x[i].startswith('[')] # [0, 4, 7]
+        list_end_indices = [i for i in range(len(x)) if x[i].endswith(']')] # [1, 6, 8]
         start = 0
         for lbeg, lend in zip(list_begin_indices,list_end_indices): # [(0, 1), (4, 6), (7, 8)]
           if lbeg > start:
@@ -314,17 +219,18 @@ def getScriptsAndArgs(args=None, searchPathList=None):
       callPython = True
       afterArgs = False
     else:
+      file_extension = os.path.splitext(elt)[-1]
       if not os.path.isfile(elt) and not os.path.isfile(elt+".py"):
         eltInSearchPath = __getScriptPath(elt, searchPathList)
         if eltInSearchPath is None or (not os.path.isfile(eltInSearchPath) and not os.path.isfile(eltInSearchPath+".py")):
-          if elt[-3:] == ".py":
+          if file_extension == ".py":
             raise SalomeContextException("Script not found: %s"%elt)
           scriptArgs.append(ScriptAndArgs(script=elt))
           continue
         elt = eltInSearchPath
 
-      if elt[-4:] != ".hdf":
-        if elt[-3:] == ".py" or isDriver:
+      if file_extension != ".hdf":
+        if file_extension == ".py" or isDriver:
           currentScript = os.path.abspath(elt)
         elif os.path.isfile(elt+".py"):
           currentScript = os.path.abspath(elt+".py")
@@ -337,6 +243,7 @@ def getScriptsAndArgs(args=None, searchPathList=None):
         scriptArgs.append(ScriptAndArgs(script=currentKey))
         callPython = False
       elif currentScript:
+        script_extension = os.path.splitext(currentScript)[-1]
         if isDriver:
           currentKey = currentScript
           scriptArgs.append(ScriptAndArgs(script=currentKey))
@@ -348,16 +255,17 @@ def getScriptsAndArgs(args=None, searchPathList=None):
           ispython = False
           try:
             fn = open(currentScript)
-            for i in xrange(10): # read only 10 first lines
+            for i in range(10): # read only 10 first lines
               ln = fn.readline()
               if re.search("#!.*python"):
                 ispython = True
                 break
               pass
-            fn.close()
-          except:
+          except Exception:
             pass
-          if not ispython and currentScript[-3:] == ".py":
+          finally:
+            fn.close()
+          if not ispython and script_extension == ".py":
             currentKey = "@PYTHONBIN@ "+currentScript
           else:
             currentKey = currentScript
@@ -379,12 +287,18 @@ def getScriptsAndArgs(args=None, searchPathList=None):
 # Formatting scripts and args as a Bash-like command-line:
 # script1.py [args] ; script2.py [args] ; ...
 # scriptArgs is a list of ScriptAndArgs objects; their output parameters are omitted
-def formatScriptsAndArgs(scriptArgs=None):
+def formatScriptsAndArgs(scriptArgs=None, escapeSpaces=False):
     if scriptArgs is None:
       return ""
     commands = []
     for sa_obj in scriptArgs:
       cmd = sa_obj.script
+      if escapeSpaces and cmd:
+        if sys.platform == "win32":
+          cmd = cmd.replace(' ', ' "', 1)
+          cmd = cmd + '"'
+        else:
+          cmd = cmd.replace(' ', '\ ').replace('\ ', ' ', 1)
       if sa_obj.args:
         cmd = " ".join([cmd]+sa_obj.args)
       commands.append(cmd)
@@ -401,9 +315,9 @@ def formatScriptsAndArgs(scriptArgs=None):
 # If OMNIORB_USER_PATH is already set, only checks write access to associated directory ;
 # an exception is raised if check fails. It allows users for choosing a specific folder.
 # Else the function sets OMNIORB_USER_PATH this way:
-# - If APPLI environment variable is set, OMNIORB_USER_PATH is set to ${APPLI}/USERS.
-#   The function does not check USERS folder existence or write access. This folder
-#   must exist ; this is the case if SALOME virtual application has been created using
+# - If APPLI environment variable is set, and if ${APPLI}/USERS points at an existing 
+#   folder with write access, then OMNIORB_USER_PATH is set to ${APPLI}/USERS.
+#   This is the case if SALOME virtual application has been created using
 #   appli_gen.py script.
 # - Else OMNIORB_USER_PATH is set to user home directory.
 def setOmniOrbUserPath():
@@ -413,13 +327,25 @@ def setOmniOrbUserPath():
       raise Exception("Unable to get write access to directory: %s"%omniorbUserPath)
     pass
   else:
-    homePath = os.path.realpath(os.path.expanduser('~'))
-    #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
-    defaultOmniorbUserPath = homePath
-    if os.getenv("APPLI"):
-      defaultOmniorbUserPath = os.path.join(homePath, os.getenv("APPLI"), "USERS")
-      pass
-    os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
+    # Must be in /tmp (or equivalent) to handle application concurrency
+    try:
+      import tempfile
+      temp = tempfile.NamedTemporaryFile()
+      temp_dir = os.path.dirname(temp.name)
+      temp.close()
+      if not os.access(temp_dir, os.W_OK):
+        raise Exception("Unable to get write access to directory: %s"%temp_dir)
+      os.environ["OMNIORB_USER_PATH"] = temp_dir
+    except Exception:
+      homePath = os.path.realpath(os.path.expanduser('~'))
+      #defaultOmniorbUserPath = os.path.join(homePath, ".salomeConfig/USERS")
+      defaultOmniorbUserPath = homePath
+      if os.getenv("APPLI"):
+        appli_users_path=os.path.join(homePath, os.getenv("APPLI"), "USERS")
+        if os.access(appli_users_path, os.W_OK):
+          defaultOmniorbUserPath = appli_users_path
+        pass
+      os.environ["OMNIORB_USER_PATH"] = defaultOmniorbUserPath
 #
 
 def getHostname():