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