Salome HOME
be able to prepend an env value from APPLICATION.environ
[tools/sat.git] / salomeTools.py
index 4049ed2436995460ea1e0d14b2a4694afc56945f..4b25cfa68fdd9ae902fd8f5ced8d13bc7c2b624b 100755 (executable)
@@ -22,6 +22,7 @@
 # python imports
 import os
 import sys
+import tempfile
 import imp
 import types
 import gettext
@@ -81,6 +82,8 @@ parser.add_option('b', 'batch', 'boolean', "batch",
                   _("batch mode (no question)."))
 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal", 
                   _("All traces in the terminal (for example compilation logs)."))
+parser.add_option('l', 'logs_paths_in_file', 'string', "logs_paths_in_file", 
+                  _("Put the command result and paths to log files in ."))
 
 class Sat(object):
     '''The main class that stores all the commands of salomeTools
@@ -137,6 +140,19 @@ class Sat(object):
         '''
         # loop on the commands name
         for nameCmd in lCommand:
+            
+            # Exception for the jobs command that requires the paramiko module
+            if nameCmd == "jobs":
+                try:
+                    saveout = sys.stderr
+                    ff = tempfile.TemporaryFile()
+                    sys.stderr = ff
+                    import paramiko
+                    sys.stderr = saveout
+                except:
+                    sys.stderr = saveout
+                    continue
+
             # load the module that has name nameCmd in dirPath
             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
             module = imp.load_module(nameCmd, file_, pathname, description)
@@ -171,7 +187,7 @@ class Sat(object):
                 if argv != [''] and argv[0][0] != "-":
                     appliToLoad = argv[0].rstrip('*')
                     argv = argv[1:]
-                               
+   
                 # read the configuration from all the pyconf files    
                 cfgManager = config.ConfigManager()
                 self.cfg = cfgManager.get_config(datadir=self.datadir, 
@@ -196,16 +212,36 @@ class Sat(object):
                     self.cfg.USER.output_verbose_level = 0
                 silent = (self.cfg.USER.output_verbose_level == 0)
 
-                # create log file, unless the command is called 
-                # with a logger as parameter
+                # create log file
+                micro_command = False
+                if logger_add_link:
+                    micro_command = True
                 logger_command = src.logger.Logger(self.cfg, 
                                                    silent_sysstd=silent,
-                                                   all_in_terminal=self.options.all_in_terminal)
+                                                   all_in_terminal=self.options.all_in_terminal,
+                                                   micro_command=micro_command)
                 
-                if logger_add_link is not None:
-                    logger_add_link.xmlFile.append_node_attrib("Links", attrib={__nameCmd__ : logger_command.logFilePath})
+                # Check that the path given by the logs_paths_in_file option
+                # is a file path that can be written
+                if self.options.logs_paths_in_file:
+                    try:
+                        self.options.logs_paths_in_file = os.path.abspath(
+                                                self.options.logs_paths_in_file)
+                        dir_file = os.path.dirname(self.options.logs_paths_in_file)
+                        if not os.path.exists(dir_file):
+                            os.makedirs(dir_file)
+                        if os.path.exists(self.options.logs_paths_in_file):
+                            os.remove(self.options.logs_paths_in_file)
+                        file_test = open(self.options.logs_paths_in_file, "w")
+                        file_test.close()
+                    except Exception as e:
+                        msg = _("WARNING: the logs_paths_in_file option will "
+                                "not be taken into account.\nHere is the error:")
+                        logger_command.write("%s\n%s\n\n" % (src.printcolors.printcWarning(msg), str(e)))
+                        self.options.logs_paths_in_file = None
                 
                 try:
+                    res = None
                     # Execute the hooks (if there is any) 
                     # and run method of the command
                     self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
@@ -226,8 +262,6 @@ class Sat(object):
                     if verbose > -1:
                         self.options.__setattr__("output_verbose_level", 
                                                  verbose_save)
-                        
-                finally:
                     # put final attributes in xml log file 
                     # (end time, total time, ...) and write it
                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
@@ -235,9 +269,42 @@ class Sat(object):
                                                 'sat',
                                                 __nameCmd__, 
                                                 args])
-                    logger_command.end_write({"launchedCommand" : launchedCommand})
+                    launchedCommand = launchedCommand.replace('"', "'")
+                    
+                    # Add a link to the parent command      
+                    if logger_add_link is not None:
+                        logger_add_link.add_link(logger_command.logFileName,
+                                                 __nameCmd__,
+                                                 res,
+                                                 launchedCommand)
+                        logger_add_link.l_logFiles += logger_command.l_logFiles
+
+                finally:
+                    launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
+                                                os.path.sep +
+                                                'sat',
+                                                __nameCmd__, 
+                                                args])
+                    launchedCommand = launchedCommand.replace('"', "'")
+                    
+                    # Put the final attributes corresponding to end time and
+                    # Write the file to the hard drive
+                    logger_command.end_write(
+                                        {"launchedCommand" : launchedCommand})
+                    
+                    if res != 0:
+                        res = 1
+                    # If the logs_paths_in_file was called, write the result
+                    # and log files in the given file path
+                    if self.options.logs_paths_in_file:
+                        file_res = open(self.options.logs_paths_in_file, "w")
+                        file_res.write(str(res) + "\n")
+                        for i, filepath in enumerate(logger_command.l_logFiles):
+                            file_res.write(filepath)
+                            if i < len(logger_command.l_logFiles):
+                                file_res.write("\n")
                 
-                return res, logger_command.logFilePath
+                return res
 
             # Make sure that run_command will be redefined 
             # at each iteration of the loop
@@ -313,7 +380,7 @@ class Sat(object):
             return
         # get command name
         command = opt[0]
-        # read the configuration from all the pyconf files    
+        # read the configuration from all the pyconf files
         cfgManager = config.ConfigManager()
         self.cfg = cfgManager.get_config(datadir=self.datadir)
 
@@ -414,11 +481,11 @@ if __name__ == "__main__":
     if options.debug_mode:
         # call classically the command and if it fails, 
         # show exception and stack (usual python mode)
-        code, __ = fun_command(' '.join(args[1:]))
+        code = fun_command(' '.join(args[1:]))
     else:
         # catch exception in order to show less verbose but elegant message
         try:
-            code, __ = fun_command(' '.join(args[1:]))
+            code = fun_command(' '.join(args[1:]))
         except Exception as exc:
             code = 1
             write_exception(exc)