Salome HOME
4049ed2436995460ea1e0d14b2a4694afc56945f
[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 imp
26 import types
27 import gettext
28
29 # salomeTools imports
30 import src
31
32 # get path to salomeTools sources
33 satdir  = os.path.dirname(os.path.realpath(__file__))
34 cmdsdir = os.path.join(satdir, 'commands')
35
36 # Make the src package accessible from all code
37 sys.path.append(satdir)
38 sys.path.append(cmdsdir)
39
40 import config
41
42 # load resources for internationalization
43 #es = gettext.translation('salomeTools', os.path.join(satdir, 'src', 'i18n'))
44 #es.install()
45 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
46
47 # The possible hooks : 
48 # pre is for hooks to be executed before commands
49 # post is for hooks to be executed after commands
50 C_PRE_HOOK = "pre"
51 C_POST_HOOK = "post"
52
53 def find_command_list(dirPath):
54     ''' Parse files in dirPath that end with .py : it gives commands list
55     
56     :param dirPath str: The directory path where to search the commands
57     :return: cmd_list : the list containing the commands name 
58     :rtype: list
59     '''
60     cmd_list = []
61     for item in os.listdir(dirPath):
62         if item.endswith('.py'):
63             cmd_list.append(item[:-len('.py')])
64     return cmd_list
65
66 # The list of valid salomeTools commands
67 #lCommand = ['config', 'compile', 'prepare']
68 lCommand = find_command_list(cmdsdir)
69
70 # Define all possible option for salomeTools command :  sat <option> <args>
71 parser = src.options.Options()
72 parser.add_option('h', 'help', 'boolean', 'help', 
73                   _("shows global help or help on a specific command."))
74 parser.add_option('o', 'overwrite', 'list', "overwrite", 
75                   _("overwrites a configuration parameters."))
76 parser.add_option('g', 'debug', 'boolean', 'debug_mode', 
77                   _("run salomeTools in debug mode."))
78 parser.add_option('v', 'verbose', 'int', "output_verbose_level", 
79                   _("change output verbose level (default is 3)."))
80 parser.add_option('b', 'batch', 'boolean', "batch", 
81                   _("batch mode (no question)."))
82 parser.add_option('t', 'all_in_terminal', 'boolean', "all_in_terminal", 
83                   _("All traces in the terminal (for example compilation logs)."))
84
85 class Sat(object):
86     '''The main class that stores all the commands of salomeTools
87     '''
88     def __init__(self, opt='', datadir=None):
89         '''Initialization
90         
91         :param opt str: The sat options 
92         :param: datadir str : the directory that contain all the external 
93                               data (like software pyconf and software scripts)
94         '''
95         # Read the salomeTools options (the list of possible options is 
96         # at the beginning of this file)
97         try:
98             (options, argus) = parser.parse_args(opt.split(' '))
99         except Exception as exc:
100             write_exception(exc)
101             sys.exit(-1)
102
103         # initialization of class attributes       
104         self.__dict__ = dict()
105         self.cfg = None # the config that will be read using pyconf module
106         self.arguments = opt
107         self.options = options # the options passed to salomeTools
108         self.datadir = datadir # default value will be <salomeTools root>/data
109         # set the commands by calling the dedicated function
110         self._setCommands(cmdsdir)
111         
112         # if the help option has been called, print help and exit
113         if options.help:
114             try:
115                 self.print_help(argus)
116                 sys.exit(0)
117             except Exception as exc:
118                 write_exception(exc)
119                 sys.exit(1)
120
121     def __getattr__(self, name):
122         ''' overwrite of __getattr__ function in order to display 
123             a customized message in case of a wrong call
124         
125         :param name str: The name of the attribute 
126         '''
127         if name in self.__dict__:
128             return self.__dict__[name]
129         else:
130             raise AttributeError(name + _(" is not a valid command"))
131     
132     def _setCommands(self, dirPath):
133         '''set class attributes corresponding to all commands that are 
134            in the dirPath directory
135         
136         :param dirPath str: The directory path containing the commands 
137         '''
138         # loop on the commands name
139         for nameCmd in lCommand:
140             # load the module that has name nameCmd in dirPath
141             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
142             module = imp.load_module(nameCmd, file_, pathname, description)
143             
144             def run_command(args='', batch = False, verbose = -1, logger_add_link = None):
145                 '''The function that will load the configuration (all pyconf)
146                 and return the function run of the command corresponding to module
147                 
148                 :param args str: The directory path containing the commands 
149                 '''
150                 # Make sure the internationalization is available
151                 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
152                 
153                 # Get the arguments in a list and remove the empty elements
154                 argv_0 = args.split(" ")
155                 if argv_0 != ['']:
156                     while "" in argv_0: argv_0.remove("")
157                 
158                 # Format the argv list in order to prevent strings 
159                 # that contain a blank to be separated
160                 argv = []
161                 elem_old = ""
162                 for elem in argv_0:
163                     if argv == [] or elem_old.startswith("-") or elem.startswith("-"):
164                         argv.append(elem)
165                     else:
166                         argv[-1] += " " + elem
167                     elem_old = elem
168                            
169                 # if it is provided by the command line, get the application
170                 appliToLoad = None
171                 if argv != [''] and argv[0][0] != "-":
172                     appliToLoad = argv[0].rstrip('*')
173                     argv = argv[1:]
174                                
175                 # read the configuration from all the pyconf files    
176                 cfgManager = config.ConfigManager()
177                 self.cfg = cfgManager.get_config(datadir=self.datadir, 
178                                                  application=appliToLoad, 
179                                                  options=self.options, 
180                                                  command=__nameCmd__)
181                 
182                 # Set the verbose mode if called
183                 if verbose > -1:
184                     verbose_save = self.options.output_verbose_level
185                     self.options.__setattr__("output_verbose_level", verbose)    
186
187                 # Set batch mode if called
188                 if batch:
189                     batch_save = self.options.batch
190                     self.options.__setattr__("batch", True)
191
192                 # set output level
193                 if self.options.output_verbose_level is not None:
194                     self.cfg.USER.output_verbose_level = self.options.output_verbose_level
195                 if self.cfg.USER.output_verbose_level < 1:
196                     self.cfg.USER.output_verbose_level = 0
197                 silent = (self.cfg.USER.output_verbose_level == 0)
198
199                 # create log file, unless the command is called 
200                 # with a logger as parameter
201                 logger_command = src.logger.Logger(self.cfg, 
202                                                    silent_sysstd=silent,
203                                                    all_in_terminal=self.options.all_in_terminal)
204                 
205                 if logger_add_link is not None:
206                     logger_add_link.xmlFile.append_node_attrib("Links", attrib={__nameCmd__ : logger_command.logFilePath})
207                 
208                 try:
209                     # Execute the hooks (if there is any) 
210                     # and run method of the command
211                     self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
212                     res = __module__.run(argv, self, logger_command)
213                     self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
214                     
215                     # set res if it is not set in the command
216                     if res is None:
217                         res = 0
218                     
219                     # come back in the original batch mode if 
220                     # batch argument was called
221                     if batch:
222                         self.options.__setattr__("batch", batch_save)
223
224                     # come back in the original verbose mode if 
225                     # verbose argument was called                        
226                     if verbose > -1:
227                         self.options.__setattr__("output_verbose_level", 
228                                                  verbose_save)
229                         
230                 finally:
231                     # put final attributes in xml log file 
232                     # (end time, total time, ...) and write it
233                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
234                                                 os.path.sep +
235                                                 'sat',
236                                                 __nameCmd__, 
237                                                 args])
238                     logger_command.end_write({"launchedCommand" : launchedCommand})
239                 
240                 return res, logger_command.logFilePath
241
242             # Make sure that run_command will be redefined 
243             # at each iteration of the loop
244             globals_up = {}
245             globals_up.update(run_command.__globals__)
246             globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
247             func = types.FunctionType(run_command.__code__,
248                                       globals_up,
249                                       run_command.__name__,
250                                       run_command.__defaults__,
251                                       run_command.__closure__)
252
253             # set the attribute corresponding to the command
254             self.__setattr__(nameCmd, func)
255
256     def run_hook(self, cmd_name, hook_type, logger):
257         '''Execute a hook file for a given command regarding the fact 
258            it is pre or post
259         
260         :param cmd_name str: The the command on which execute the hook
261         :param hook_type str: pre or post
262         :param logger Logger: the logging instance to use for the prints
263         '''
264         # The hooks must be defined in the application pyconf
265         # So, if there is no application, do not do anything
266         if not src.config_has_application(self.cfg):
267             return
268
269         # The hooks must be defined in the application pyconf in the
270         # APPLICATION section, hook : { command : 'script_path.py'}
271         if "hook" not in self.cfg.APPLICATION \
272                     or cmd_name not in self.cfg.APPLICATION.hook:
273             return
274
275         # Get the hook_script path and verify that it exists
276         hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
277         if not os.path.exists(hook_script_path):
278             raise src.SatException(_("Hook script not found: %s") % 
279                                    hook_script_path)
280         
281         # Try to execute the script, catch the exception if it fails
282         try:
283             # import the module (in the sense of python)
284             pymodule = imp.load_source(cmd_name, hook_script_path)
285             
286             # format a message to be printed at hook execution
287             msg = src.printcolors.printcWarning(_("Run hook script"))
288             msg = "%s: %s\n" % (msg, 
289                                 src.printcolors.printcInfo(hook_script_path))
290             
291             # run the function run_pre_hook if this function is called 
292             # before the command, run_post_hook if it is called after
293             if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
294                 logger.write(msg, 1)
295                 pymodule.run_pre_hook(self.cfg, logger)
296             elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
297                 logger.write(msg, 1)
298                 pymodule.run_post_hook(self.cfg, logger)
299
300         except Exception as exc:
301             msg = _("Unable to run hook script: %s") % hook_script_path
302             msg += "\n" + str(exc)
303             raise src.SatException(msg)
304
305     def print_help(self, opt):
306         '''Prints help for a command. Function called when "sat -h <command>"
307         
308         :param argv str: the options passed (to get the command name)
309         '''
310         # if no command as argument (sat -h)
311         if len(opt)==0:
312             print_help()
313             return
314         # get command name
315         command = opt[0]
316         # read the configuration from all the pyconf files    
317         cfgManager = config.ConfigManager()
318         self.cfg = cfgManager.get_config(datadir=self.datadir)
319
320         # Check if this command exists
321         if not hasattr(self, command):
322             raise src.SatException(_("Command '%s' does not exist") % command)
323         
324         # Print salomeTools version
325         print_version()
326         
327         # load the module
328         module = self.get_module(command)
329
330         # print the description of the command that is done in the command file
331         if hasattr( module, "description" ) :
332             print(src.printcolors.printcHeader( _("Description:") ))
333             print(module.description() + '\n')
334
335         # print the description of the command options
336         if hasattr( module, "parser" ) :
337             module.parser.print_help()
338
339     def get_module(self, module):
340         '''Loads a command. Function called only by print_help
341         
342         :param module str: the command to load
343         '''
344         # Check if this command exists
345         if not hasattr(self, module):
346             raise src.SatException(_("Command '%s' does not exist") % module)
347
348         # load the module
349         (file_, pathname, description) = imp.find_module(module, [cmdsdir])
350         module = imp.load_module(module, file_, pathname, description)
351         return module
352  
353 def print_version():
354     '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
355     '''
356     # read the config 
357     cfgManager = config.ConfigManager()
358     cfg = cfgManager.get_config()
359     # print the key corresponding to salomeTools version
360     print(src.printcolors.printcHeader( _("Version: ") ) + 
361           cfg.INTERNAL.sat_version + '\n')
362
363
364 def print_help():
365     '''prints salomeTools general help
366     
367     :param options str: the options
368     '''
369     print_version()
370     
371     print(src.printcolors.printcHeader( _("Usage: ") ) + 
372           "sat [sat_options] <command> [product] [command_options]\n")
373
374     parser.print_help()
375
376     # display all the available commands.
377     print(src.printcolors.printcHeader(_("Available commands are:\n")))
378     for command in lCommand:
379         print(" - %s" % (command))
380         
381     # Explain how to get the help for a specific command
382     print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
383                                     " command: ")) + "sat --help <command>\n")
384
385 def write_exception(exc):
386     '''write exception in case of error in a command
387     
388     :param exc exception: the exception to print
389     '''
390     sys.stderr.write("\n***** ")
391     sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
392     sys.stderr.write("\n" + str(exc) + "\n")
393
394 # ###############################
395 # MAIN : terminal command usage #
396 # ###############################
397 if __name__ == "__main__":  
398     # Initialize the code that will be returned by the terminal command 
399     code = 0
400     (options, args) = parser.parse_args(sys.argv[1:])
401     
402     # no arguments : print general help
403     if len(args) == 0:
404         print_help()
405         sys.exit(0)
406     
407     # instantiate the salomeTools class with correct options
408     sat = Sat(' '.join(sys.argv[1:]))
409     # the command called
410     command = args[0]
411     # get dynamically the command function to call
412     fun_command = sat.__getattr__(command)
413     # call the command with two cases : mode debug or not
414     if options.debug_mode:
415         # call classically the command and if it fails, 
416         # show exception and stack (usual python mode)
417         code, __ = fun_command(' '.join(args[1:]))
418     else:
419         # catch exception in order to show less verbose but elegant message
420         try:
421             code, __ = fun_command(' '.join(args[1:]))
422         except Exception as exc:
423             code = 1
424             write_exception(exc)
425     
426     # exit salomeTools with the right code (0 if no errors, else 1)
427     if code is None: code = 0
428     sys.exit(code)
429