Salome HOME
FSAt package --binaries: substitute also the generated components paths
[tools/sat.git] / salomeTools.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
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.
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 '''This file is the main entry file to salomeTools
19 '''
20
21 # python imports
22 import os
23 import sys
24 import tempfile
25 import imp
26 import types
27 import gettext
28 import traceback
29
30 # salomeTools imports
31 import src
32
33 # get path to salomeTools sources
34 satdir  = os.path.dirname(os.path.realpath(__file__))
35 cmdsdir = os.path.join(satdir, 'commands')
36
37 # Make the src package accessible from all code
38 sys.path.append(satdir)
39 sys.path.append(cmdsdir)
40
41 import config
42
43 # load resources for internationalization
44 #es = gettext.translation('salomeTools', os.path.join(satdir, 'src', 'i18n'))
45 #es.install()
46 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
47
48 # The possible hooks : 
49 # pre is for hooks to be executed before commands
50 # post is for hooks to be executed after commands
51 C_PRE_HOOK = "pre"
52 C_POST_HOOK = "post"
53
54 def find_command_list(dirPath):
55     ''' Parse files in dirPath that end with .py : it gives commands list
56     
57     :param dirPath str: The directory path where to search the commands
58     :return: cmd_list : the list containing the commands name 
59     :rtype: list
60     '''
61     cmd_list = []
62     for item in os.listdir(dirPath):
63         if item.endswith('.py'):
64             cmd_list.append(item[:-len('.py')])
65     return cmd_list
66
67 # The list of valid salomeTools commands
68 #lCommand = ['config', 'compile', 'prepare']
69 lCommand = find_command_list(cmdsdir)
70
71 # Define all possible option for salomeTools command :  sat <option> <args>
72 parser = src.options.Options()
73 parser.add_option('h', 'help', 'boolean', 'help', 
74                   _("shows global help or help on a specific command."))
75 parser.add_option('o', 'overwrite', 'list', "overwrite", 
76                   _("overwrites a configuration parameters."))
77 parser.add_option('g', 'debug', 'boolean', 'debug_mode', 
78                   _("run salomeTools in debug mode."))
79 parser.add_option('v', 'verbose', 'int', "output_verbose_level", 
80                   _("change output verbose level (default is 3)."))
81 parser.add_option('b', 'batch', 'boolean', "batch", 
82                   _("batch mode (no question)."))
83 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal", 
84                   _("All traces in the terminal (for example compilation logs)."))
85 parser.add_option('l', 'logs_paths_in_file', 'string', "logs_paths_in_file", 
86                   _("Put the command result and paths to log files in ."))
87
88 class Sat(object):
89     '''The main class that stores all the commands of salomeTools
90     '''
91     def __init__(self, opt='', datadir=None):
92         '''Initialization
93         
94         :param opt str: The sat options 
95         :param: datadir str : the directory that contain all the external 
96                               data (like software pyconf and software scripts)
97         '''
98         # Read the salomeTools options (the list of possible options is 
99         # at the beginning of this file)
100         try:
101             (options, argus) = parser.parse_args(opt.split(' '))
102         except Exception as exc:
103             write_exception(exc)
104             sys.exit(-1)
105
106         # initialization of class attributes       
107         self.__dict__ = dict()
108         self.cfg = None # the config that will be read using pyconf module
109         self.arguments = opt
110         self.options = options # the options passed to salomeTools
111         self.datadir = datadir # default value will be <salomeTools root>/data
112         # set the commands by calling the dedicated function
113         self._setCommands(cmdsdir)
114         
115         # if the help option has been called, print help and exit
116         if options.help:
117             try:
118                 self.print_help(argus)
119                 sys.exit(0)
120             except Exception as exc:
121                 write_exception(exc)
122                 sys.exit(1)
123
124     def __getattr__(self, name):
125         ''' overwrite of __getattr__ function in order to display 
126             a customized message in case of a wrong call
127         
128         :param name str: The name of the attribute 
129         '''
130         if name in self.__dict__:
131             return self.__dict__[name]
132         else:
133             raise AttributeError(name + _(" is not a valid command"))
134     
135     def _setCommands(self, dirPath):
136         '''set class attributes corresponding to all commands that are 
137            in the dirPath directory
138         
139         :param dirPath str: The directory path containing the commands 
140         '''
141         # loop on the commands name
142         for nameCmd in lCommand:
143             
144             # Exception for the jobs command that requires the paramiko module
145             if nameCmd == "jobs":
146                 try:
147                     saveout = sys.stderr
148                     ff = tempfile.TemporaryFile()
149                     sys.stderr = ff
150                     import paramiko
151                     sys.stderr = saveout
152                 except:
153                     sys.stderr = saveout
154                     continue
155
156             # load the module that has name nameCmd in dirPath
157             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
158             module = imp.load_module(nameCmd, file_, pathname, description)
159             
160             def run_command(args='',
161                             options=None,
162                             batch = False,
163                             verbose = -1,
164                             logger_add_link = None):
165                 '''The function that will load the configuration (all pyconf)
166                 and return the function run of the command corresponding to module
167                 
168                 :param args str: The directory path containing the commands 
169                 '''
170                 # Make sure the internationalization is available
171                 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
172                 
173                 # Get the arguments in a list and remove the empty elements
174                 argv_0 = args.split(" ")
175                 if argv_0 != ['']:
176                     while "" in argv_0: argv_0.remove("")
177                 
178                 # Format the argv list in order to prevent strings 
179                 # that contain a blank to be separated
180                 argv = []
181                 elem_old = ""
182                 for elem in argv_0:
183                     if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
184                         argv.append(elem)
185                     else:
186                         argv[-1] += " " + elem
187                     elem_old = elem
188                            
189                 # if it is provided by the command line, get the application
190                 appliToLoad = None
191                 if argv != [''] and argv[0][0] != "-":
192                     appliToLoad = argv[0].rstrip('*')
193                     argv = argv[1:]
194                 
195                 # Check if the global options of salomeTools have to be changed
196                 if options:
197                     options_save = self.options
198                     self.options = options  
199
200                 # read the configuration from all the pyconf files    
201                 cfgManager = config.ConfigManager()
202                 self.cfg = cfgManager.get_config(datadir=self.datadir, 
203                                                  application=appliToLoad, 
204                                                  options=self.options, 
205                                                  command=__nameCmd__)
206                                
207                 # Set the verbose mode if called
208                 if verbose > -1:
209                     verbose_save = self.options.output_verbose_level
210                     self.options.__setattr__("output_verbose_level", verbose)    
211
212                 # Set batch mode if called
213                 if batch:
214                     batch_save = self.options.batch
215                     self.options.__setattr__("batch", True)
216
217                 # set output level
218                 if self.options.output_verbose_level is not None:
219                     self.cfg.USER.output_verbose_level = self.options.output_verbose_level
220                 if self.cfg.USER.output_verbose_level < 1:
221                     self.cfg.USER.output_verbose_level = 0
222                 silent = (self.cfg.USER.output_verbose_level == 0)
223
224                 # create log file
225                 micro_command = False
226                 if logger_add_link:
227                     micro_command = True
228                 logger_command = src.logger.Logger(self.cfg, 
229                                    silent_sysstd=silent,
230                                    all_in_terminal=self.options.all_in_terminal,
231                                    micro_command=micro_command)
232                 
233                 # Check that the path given by the logs_paths_in_file option
234                 # is a file path that can be written
235                 if self.options.logs_paths_in_file and not micro_command:
236                     try:
237                         self.options.logs_paths_in_file = os.path.abspath(
238                                                 self.options.logs_paths_in_file)
239                         dir_file = os.path.dirname(self.options.logs_paths_in_file)
240                         if not os.path.exists(dir_file):
241                             os.makedirs(dir_file)
242                         if os.path.exists(self.options.logs_paths_in_file):
243                             os.remove(self.options.logs_paths_in_file)
244                         file_test = open(self.options.logs_paths_in_file, "w")
245                         file_test.close()
246                     except Exception as e:
247                         msg = _("WARNING: the logs_paths_in_file option will "
248                                 "not be taken into account.\nHere is the error:")
249                         logger_command.write("%s\n%s\n\n" % (
250                                              src.printcolors.printcWarning(msg),
251                                              str(e)))
252                         self.options.logs_paths_in_file = None
253                 
254                 options_launched = ""
255                 res = None
256                 try:
257                     # Execute the hooks (if there is any) 
258                     # and run method of the command
259                     self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
260                     res = __module__.run(argv, self, logger_command)
261                     self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
262                     if res is None:
263                         res = 0
264                         
265                 except Exception as e:
266                     # Get error
267                     logger_command.write("\n***** ", 1)
268                     logger_command.write(src.printcolors.printcError(
269                                                        "salomeTools ERROR:"), 1)
270                     logger_command.write("\n" + str(e) + "\n\n", 1)
271                     # get stack
272                     __, __, exc_traceback = sys.exc_info()
273                     fp = tempfile.TemporaryFile()
274                     traceback.print_tb(exc_traceback, file=fp)
275                     fp.seek(0)
276                     stack = fp.read()
277                     verbosity = 5
278                     if self.options.debug_mode:
279                         verbosity = 1
280                     logger_command.write("TRACEBACK: %s" % stack.replace('"',"'"),
281                                          verbosity)
282                 finally:
283                     # set res if it is not set in the command
284                     if res is None:
285                         res = 1
286                                             
287                     # come back to the original global options
288                     if options:
289                         options_launched = get_text_from_options(self.options)
290                         self.options = options_save
291                     
292                     # come back in the original batch mode if 
293                     # batch argument was called
294                     if batch:
295                         self.options.__setattr__("batch", batch_save)
296
297                     # come back in the original verbose mode if 
298                     # verbose argument was called                        
299                     if verbose > -1:
300                         self.options.__setattr__("output_verbose_level", 
301                                                  verbose_save)
302                     # put final attributes in xml log file 
303                     # (end time, total time, ...) and write it
304                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
305                                                 os.path.sep +
306                                                 'sat',
307                                                 options_launched,
308                                                 __nameCmd__, 
309                                                 args])
310                     launchedCommand = launchedCommand.replace('"', "'")
311                     
312                     # Add a link to the parent command      
313                     if logger_add_link is not None:
314                         logger_add_link.add_link(logger_command.logFileName,
315                                                  __nameCmd__,
316                                                  res,
317                                                  launchedCommand)
318                         logger_add_link.l_logFiles += logger_command.l_logFiles
319                                             
320                     # Put the final attributes corresponding to end time and
321                     # Write the file to the hard drive
322                     logger_command.end_write(
323                                         {"launchedCommand" : launchedCommand})
324                     
325                     if res != 0:
326                         res = 1
327                     # If the logs_paths_in_file was called, write the result
328                     # and log files in the given file path
329                     if self.options.logs_paths_in_file and not micro_command:
330                         file_res = open(self.options.logs_paths_in_file, "w")
331                         file_res.write(str(res) + "\n")
332                         for i, filepath in enumerate(logger_command.l_logFiles):
333                             file_res.write(filepath)
334                             if i < len(logger_command.l_logFiles):
335                                 file_res.write("\n")
336                                 file_res.flush()
337                 
338                 return res
339
340             # Make sure that run_command will be redefined 
341             # at each iteration of the loop
342             globals_up = {}
343             globals_up.update(run_command.__globals__)
344             globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
345             func = types.FunctionType(run_command.__code__,
346                                       globals_up,
347                                       run_command.__name__,
348                                       run_command.__defaults__,
349                                       run_command.__closure__)
350
351             # set the attribute corresponding to the command
352             self.__setattr__(nameCmd, func)
353
354     def run_hook(self, cmd_name, hook_type, logger):
355         '''Execute a hook file for a given command regarding the fact 
356            it is pre or post
357         
358         :param cmd_name str: The the command on which execute the hook
359         :param hook_type str: pre or post
360         :param logger Logger: the logging instance to use for the prints
361         '''
362         # The hooks must be defined in the application pyconf
363         # So, if there is no application, do not do anything
364         if not src.config_has_application(self.cfg):
365             return
366
367         # The hooks must be defined in the application pyconf in the
368         # APPLICATION section, hook : { command : 'script_path.py'}
369         if "hook" not in self.cfg.APPLICATION \
370                     or cmd_name not in self.cfg.APPLICATION.hook:
371             return
372
373         # Get the hook_script path and verify that it exists
374         hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
375         if not os.path.exists(hook_script_path):
376             raise src.SatException(_("Hook script not found: %s") % 
377                                    hook_script_path)
378         
379         # Try to execute the script, catch the exception if it fails
380         try:
381             # import the module (in the sense of python)
382             pymodule = imp.load_source(cmd_name, hook_script_path)
383             
384             # format a message to be printed at hook execution
385             msg = src.printcolors.printcWarning(_("Run hook script"))
386             msg = "%s: %s\n" % (msg, 
387                                 src.printcolors.printcInfo(hook_script_path))
388             
389             # run the function run_pre_hook if this function is called 
390             # before the command, run_post_hook if it is called after
391             if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
392                 logger.write(msg, 1)
393                 pymodule.run_pre_hook(self.cfg, logger)
394             elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
395                 logger.write(msg, 1)
396                 pymodule.run_post_hook(self.cfg, logger)
397
398         except Exception as exc:
399             msg = _("Unable to run hook script: %s") % hook_script_path
400             msg += "\n" + str(exc)
401             raise src.SatException(msg)
402
403     def print_help(self, opt):
404         '''Prints help for a command. Function called when "sat -h <command>"
405         
406         :param argv str: the options passed (to get the command name)
407         '''
408         # if no command as argument (sat -h)
409         if len(opt)==0:
410             print_help()
411             return
412         # get command name
413         command = opt[0]
414         # read the configuration from all the pyconf files
415         cfgManager = config.ConfigManager()
416         self.cfg = cfgManager.get_config(datadir=self.datadir)
417
418         # Check if this command exists
419         if not hasattr(self, command):
420             raise src.SatException(_("Command '%s' does not exist") % command)
421         
422         # Print salomeTools version
423         print_version()
424         
425         # load the module
426         module = self.get_module(command)
427
428         # print the description of the command that is done in the command file
429         if hasattr( module, "description" ) :
430             print(src.printcolors.printcHeader( _("Description:") ))
431             print(module.description() + '\n')
432
433         # print the description of the command options
434         if hasattr( module, "parser" ) :
435             module.parser.print_help()
436
437     def get_module(self, module):
438         '''Loads a command. Function called only by print_help
439         
440         :param module str: the command to load
441         '''
442         # Check if this command exists
443         if not hasattr(self, module):
444             raise src.SatException(_("Command '%s' does not exist") % module)
445
446         # load the module
447         (file_, pathname, description) = imp.find_module(module, [cmdsdir])
448         module = imp.load_module(module, file_, pathname, description)
449         return module
450
451 def get_text_from_options(options):
452     text_options = ""
453     for attr in dir(options):
454         if attr.startswith("__"):
455             continue
456         if options.__getattr__(attr) != None:
457             option_contain = options.__getattr__(attr)
458             if type(option_contain)==type([]):
459                 option_contain = ",".join(option_contain)
460             if type(option_contain)==type(True):
461                 option_contain = ""
462             text_options+= "--%s %s " % (attr, option_contain)
463     return text_options
464                 
465
466 def print_version():
467     '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
468     '''
469     # read the config 
470     cfgManager = config.ConfigManager()
471     cfg = cfgManager.get_config()
472     # print the key corresponding to salomeTools version
473     print(src.printcolors.printcHeader( _("Version: ") ) + 
474           cfg.INTERNAL.sat_version + '\n')
475
476
477 def print_help():
478     '''prints salomeTools general help
479     
480     :param options str: the options
481     '''
482     print_version()
483     
484     print(src.printcolors.printcHeader( _("Usage: ") ) + 
485           "sat [sat_options] <command> [product] [command_options]\n")
486
487     parser.print_help()
488
489     # display all the available commands.
490     print(src.printcolors.printcHeader(_("Available commands are:\n")))
491     for command in lCommand:
492         print(" - %s" % (command))
493         
494     # Explain how to get the help for a specific command
495     print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
496                                     " command: ")) + "sat --help <command>\n")
497
498 def write_exception(exc):
499     '''write exception in case of error in a command
500     
501     :param exc exception: the exception to print
502     '''
503     sys.stderr.write("\n***** ")
504     sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
505     sys.stderr.write("\n" + str(exc) + "\n")
506
507 # ###############################
508 # MAIN : terminal command usage #
509 # ###############################
510 if __name__ == "__main__":  
511     # Initialize the code that will be returned by the terminal command 
512     code = 0
513     (options, args) = parser.parse_args(sys.argv[1:])
514     
515     # no arguments : print general help
516     if len(args) == 0:
517         print_help()
518         sys.exit(0)
519     
520     # instantiate the salomeTools class with correct options
521     sat = Sat(' '.join(sys.argv[1:]))
522     # the command called
523     command = args[0]
524     # get dynamically the command function to call
525     fun_command = sat.__getattr__(command)
526     # call the command with two cases : mode debug or not
527     if options.debug_mode:
528         # call classically the command and if it fails, 
529         # show exception and stack (usual python mode)
530         code = fun_command(' '.join(args[1:]))
531     else:
532         # catch exception in order to show less verbose but elegant message
533         code = fun_command(' '.join(args[1:]))
534     
535     # exit salomeTools with the right code (0 if no errors, else 1)
536     if code is None: code = 0
537     sys.exit(code)
538