Salome HOME
sat generate: improve messages
[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
19 '''This file is the main entry file to salomeTools
20 '''
21
22 # python imports
23 import os
24 import sys
25 import tempfile
26 import imp
27 import types
28 import gettext
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                     continue
154
155             # load the module that has name nameCmd in dirPath
156             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
157             module = imp.load_module(nameCmd, file_, pathname, description)
158             
159             def run_command(args='', batch = False, verbose = -1, logger_add_link = None):
160                 '''The function that will load the configuration (all pyconf)
161                 and return the function run of the command corresponding to module
162                 
163                 :param args str: The directory path containing the commands 
164                 '''
165                 # Make sure the internationalization is available
166                 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
167                 
168                 # Get the arguments in a list and remove the empty elements
169                 argv_0 = args.split(" ")
170                 if argv_0 != ['']:
171                     while "" in argv_0: argv_0.remove("")
172                 
173                 # Format the argv list in order to prevent strings 
174                 # that contain a blank to be separated
175                 argv = []
176                 elem_old = ""
177                 for elem in argv_0:
178                     if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
179                         argv.append(elem)
180                     else:
181                         argv[-1] += " " + elem
182                     elem_old = elem
183                            
184                 # if it is provided by the command line, get the application
185                 appliToLoad = None
186                 if argv != [''] and argv[0][0] != "-":
187                     appliToLoad = argv[0].rstrip('*')
188                     argv = argv[1:]
189    
190                 # read the configuration from all the pyconf files    
191                 cfgManager = config.ConfigManager()
192                 self.cfg = cfgManager.get_config(datadir=self.datadir, 
193                                                  application=appliToLoad, 
194                                                  options=self.options, 
195                                                  command=__nameCmd__)
196                 
197                 # Set the verbose mode if called
198                 if verbose > -1:
199                     verbose_save = self.options.output_verbose_level
200                     self.options.__setattr__("output_verbose_level", verbose)    
201
202                 # Set batch mode if called
203                 if batch:
204                     batch_save = self.options.batch
205                     self.options.__setattr__("batch", True)
206
207                 # set output level
208                 if self.options.output_verbose_level is not None:
209                     self.cfg.USER.output_verbose_level = self.options.output_verbose_level
210                 if self.cfg.USER.output_verbose_level < 1:
211                     self.cfg.USER.output_verbose_level = 0
212                 silent = (self.cfg.USER.output_verbose_level == 0)
213
214                 # create log file
215                 logger_command = src.logger.Logger(self.cfg, 
216                                                    silent_sysstd=silent,
217                                                    all_in_terminal=self.options.all_in_terminal)
218                 
219                 # Check that the path given by the logs_paths_in_file option
220                 # is a file path that can be written
221                 if self.options.logs_paths_in_file:
222                     try:
223                         self.options.logs_paths_in_file = os.path.abspath(
224                                                 self.options.logs_paths_in_file)
225                         dir_file = os.path.dirname(self.options.logs_paths_in_file)
226                         if not os.path.exists(dir_file):
227                             os.makedirs(dir_file)
228                         if os.path.exists(self.options.logs_paths_in_file):
229                             os.remove(self.options.logs_paths_in_file)
230                         file_test = open(self.options.logs_paths_in_file, "w")
231                         file_test.close()
232                     except Exception as e:
233                         msg = _("WARNING: the logs_paths_in_file option will "
234                                 "not be taken into account.\nHere is the error:")
235                         logger_command.write("%s\n%s\n\n" % (src.printcolors.printcWarning(msg), str(e)))
236                         self.options.logs_paths_in_file = None
237                 
238                 try:
239                     res = None
240                     # Execute the hooks (if there is any) 
241                     # and run method of the command
242                     self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
243                     res = __module__.run(argv, self, logger_command)
244                     self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
245                     
246                     # set res if it is not set in the command
247                     if res is None:
248                         res = 0
249                     
250                     # come back in the original batch mode if 
251                     # batch argument was called
252                     if batch:
253                         self.options.__setattr__("batch", batch_save)
254
255                     # come back in the original verbose mode if 
256                     # verbose argument was called                        
257                     if verbose > -1:
258                         self.options.__setattr__("output_verbose_level", 
259                                                  verbose_save)
260                     # put final attributes in xml log file 
261                     # (end time, total time, ...) and write it
262                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
263                                                 os.path.sep +
264                                                 'sat',
265                                                 __nameCmd__, 
266                                                 args])
267                     launchedCommand = launchedCommand.replace('"', "'")
268                     
269                     # Add a link to the parent command      
270                     if logger_add_link is not None:
271                         logger_add_link.add_link(logger_command.logFileName,
272                                                  __nameCmd__,
273                                                  res,
274                                                  launchedCommand)
275                         logger_add_link.l_logFiles += logger_command.l_logFiles
276
277                 finally:
278                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
279                                                 os.path.sep +
280                                                 'sat',
281                                                 __nameCmd__, 
282                                                 args])
283                     launchedCommand = launchedCommand.replace('"', "'")
284                     
285                     # Put the final attributes corresponding to end time and
286                     # Write the file to the hard drive
287                     logger_command.end_write(
288                                         {"launchedCommand" : launchedCommand})
289                     
290                     if res is None:
291                         res = 1
292                     # If the logs_paths_in_file was called, write the result
293                     # and log files in the given file path
294                     if self.options.logs_paths_in_file:
295                         file_res = open(self.options.logs_paths_in_file, "w")
296                         file_res.write(str(res) + "\n")
297                         for i, filepath in enumerate(logger_command.l_logFiles):
298                             file_res.write(filepath)
299                             if i < len(logger_command.l_logFiles):
300                                 file_res.write("\n")
301                 
302                 return res
303
304             # Make sure that run_command will be redefined 
305             # at each iteration of the loop
306             globals_up = {}
307             globals_up.update(run_command.__globals__)
308             globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
309             func = types.FunctionType(run_command.__code__,
310                                       globals_up,
311                                       run_command.__name__,
312                                       run_command.__defaults__,
313                                       run_command.__closure__)
314
315             # set the attribute corresponding to the command
316             self.__setattr__(nameCmd, func)
317
318     def run_hook(self, cmd_name, hook_type, logger):
319         '''Execute a hook file for a given command regarding the fact 
320            it is pre or post
321         
322         :param cmd_name str: The the command on which execute the hook
323         :param hook_type str: pre or post
324         :param logger Logger: the logging instance to use for the prints
325         '''
326         # The hooks must be defined in the application pyconf
327         # So, if there is no application, do not do anything
328         if not src.config_has_application(self.cfg):
329             return
330
331         # The hooks must be defined in the application pyconf in the
332         # APPLICATION section, hook : { command : 'script_path.py'}
333         if "hook" not in self.cfg.APPLICATION \
334                     or cmd_name not in self.cfg.APPLICATION.hook:
335             return
336
337         # Get the hook_script path and verify that it exists
338         hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
339         if not os.path.exists(hook_script_path):
340             raise src.SatException(_("Hook script not found: %s") % 
341                                    hook_script_path)
342         
343         # Try to execute the script, catch the exception if it fails
344         try:
345             # import the module (in the sense of python)
346             pymodule = imp.load_source(cmd_name, hook_script_path)
347             
348             # format a message to be printed at hook execution
349             msg = src.printcolors.printcWarning(_("Run hook script"))
350             msg = "%s: %s\n" % (msg, 
351                                 src.printcolors.printcInfo(hook_script_path))
352             
353             # run the function run_pre_hook if this function is called 
354             # before the command, run_post_hook if it is called after
355             if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
356                 logger.write(msg, 1)
357                 pymodule.run_pre_hook(self.cfg, logger)
358             elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
359                 logger.write(msg, 1)
360                 pymodule.run_post_hook(self.cfg, logger)
361
362         except Exception as exc:
363             msg = _("Unable to run hook script: %s") % hook_script_path
364             msg += "\n" + str(exc)
365             raise src.SatException(msg)
366
367     def print_help(self, opt):
368         '''Prints help for a command. Function called when "sat -h <command>"
369         
370         :param argv str: the options passed (to get the command name)
371         '''
372         # if no command as argument (sat -h)
373         if len(opt)==0:
374             print_help()
375             return
376         # get command name
377         command = opt[0]
378         # read the configuration from all the pyconf files
379         cfgManager = config.ConfigManager()
380         self.cfg = cfgManager.get_config(datadir=self.datadir)
381
382         # Check if this command exists
383         if not hasattr(self, command):
384             raise src.SatException(_("Command '%s' does not exist") % command)
385         
386         # Print salomeTools version
387         print_version()
388         
389         # load the module
390         module = self.get_module(command)
391
392         # print the description of the command that is done in the command file
393         if hasattr( module, "description" ) :
394             print(src.printcolors.printcHeader( _("Description:") ))
395             print(module.description() + '\n')
396
397         # print the description of the command options
398         if hasattr( module, "parser" ) :
399             module.parser.print_help()
400
401     def get_module(self, module):
402         '''Loads a command. Function called only by print_help
403         
404         :param module str: the command to load
405         '''
406         # Check if this command exists
407         if not hasattr(self, module):
408             raise src.SatException(_("Command '%s' does not exist") % module)
409
410         # load the module
411         (file_, pathname, description) = imp.find_module(module, [cmdsdir])
412         module = imp.load_module(module, file_, pathname, description)
413         return module
414  
415 def print_version():
416     '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
417     '''
418     # read the config 
419     cfgManager = config.ConfigManager()
420     cfg = cfgManager.get_config()
421     # print the key corresponding to salomeTools version
422     print(src.printcolors.printcHeader( _("Version: ") ) + 
423           cfg.INTERNAL.sat_version + '\n')
424
425
426 def print_help():
427     '''prints salomeTools general help
428     
429     :param options str: the options
430     '''
431     print_version()
432     
433     print(src.printcolors.printcHeader( _("Usage: ") ) + 
434           "sat [sat_options] <command> [product] [command_options]\n")
435
436     parser.print_help()
437
438     # display all the available commands.
439     print(src.printcolors.printcHeader(_("Available commands are:\n")))
440     for command in lCommand:
441         print(" - %s" % (command))
442         
443     # Explain how to get the help for a specific command
444     print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
445                                     " command: ")) + "sat --help <command>\n")
446
447 def write_exception(exc):
448     '''write exception in case of error in a command
449     
450     :param exc exception: the exception to print
451     '''
452     sys.stderr.write("\n***** ")
453     sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
454     sys.stderr.write("\n" + str(exc) + "\n")
455
456 # ###############################
457 # MAIN : terminal command usage #
458 # ###############################
459 if __name__ == "__main__":  
460     # Initialize the code that will be returned by the terminal command 
461     code = 0
462     (options, args) = parser.parse_args(sys.argv[1:])
463     
464     # no arguments : print general help
465     if len(args) == 0:
466         print_help()
467         sys.exit(0)
468     
469     # instantiate the salomeTools class with correct options
470     sat = Sat(' '.join(sys.argv[1:]))
471     # the command called
472     command = args[0]
473     # get dynamically the command function to call
474     fun_command = sat.__getattr__(command)
475     # call the command with two cases : mode debug or not
476     if options.debug_mode:
477         # call classically the command and if it fails, 
478         # show exception and stack (usual python mode)
479         code = fun_command(' '.join(args[1:]))
480     else:
481         # catch exception in order to show less verbose but elegant message
482         try:
483             code = fun_command(' '.join(args[1:]))
484         except Exception as exc:
485             code = 1
486             write_exception(exc)
487     
488     # exit salomeTools with the right code (0 if no errors, else 1)
489     if code is None: code = 0
490     sys.exit(code)
491