Salome HOME
fix bug of internationalization
[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('l', 'level', 'int', "output_level", 
79                   _("change output level (default is 3)."))
80 parser.add_option('s', 'silent', 'boolean', 'silent', 
81                   _("do not write log or show errors."))
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):
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                 argv = args.split(" ")
152                 if argv != ['']:
153                     while "" in argv: argv.remove("")
154                 
155                 # if it is provided by the command line, get the application
156                 appliToLoad = None
157                 if argv != [''] and argv[0][0] != "-":
158                     appliToLoad = argv[0].rstrip('*')
159                     argv = argv[1:]
160                 
161                 # read the configuration from all the pyconf files    
162                 cfgManager = config.ConfigManager()
163                 self.cfg = cfgManager.get_config(dataDir=self.dataDir, 
164                                                  application=appliToLoad, 
165                                                  options=self.options, 
166                                                  command=__nameCmd__)
167                     
168                 # set output level
169                 if self.options.output_level:
170                     self.cfg.USER.output_level = self.options.output_level
171                 if self.cfg.USER.output_level < 1:
172                     self.cfg.USER.output_level = 1
173
174                 # create log file, unless the command is called 
175                 # with a logger as parameter
176                 logger_command = src.logger.Logger(self.cfg, 
177                                                    silent_sysstd=self.options.silent)
178                 if logger:
179                     logger_command = logger
180                 
181                 try:
182                     # Execute the hooks (if there is any) 
183                     # and run method of the command
184                     self.run_hook(__nameCmd__, C_PRE_HOOK, logger_command)
185                     res = __module__.run(argv, self, logger_command)
186                     self.run_hook(__nameCmd__, C_POST_HOOK, logger_command)
187                 finally:
188                     # put final attributes in xml log file 
189                     # (end time, total time, ...) and write it
190                     launchedCommand = ' '.join([self.cfg.VARS.salometoolsway +
191                                                 os.path.sep +
192                                                 'sat',
193                                                 self.arguments.split(' ')[0], 
194                                                 args])
195                     logger_command.end_write({"launchedCommand" : launchedCommand})
196                 
197                 return res
198
199             # Make sure that run_command will be redefined 
200             # at each iteration of the loop
201             globals_up = {}
202             globals_up.update(run_command.__globals__)
203             globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
204             func = types.FunctionType(run_command.__code__,
205                                       globals_up,
206                                       run_command.__name__,
207                                       run_command.__defaults__,
208                                       run_command.__closure__)
209
210             # set the attribute corresponding to the command
211             self.__setattr__(nameCmd, func)
212
213     def run_hook(self, cmd_name, hook_type, logger):
214         '''Execute a hook file for a given command regarding the fact 
215            it is pre or post
216         
217         :param cmd_name str: The the command on which execute the hook
218         :param hook_type str: pre or post
219         :param logger Logger: the logging instance to use for the prints
220         '''
221         # The hooks must be defined in the application pyconf
222         # So, if there is no application, do not do anything
223         if not src.config_has_application(self.cfg):
224             return
225
226         # The hooks must be defined in the application pyconf in the
227         # APPLICATION section, hook : { command : 'script_path.py'}
228         if "hook" not in self.cfg.APPLICATION \
229                     or cmd_name not in self.cfg.APPLICATION.hook:
230             return
231
232         # Get the hook_script path and verify that it exists
233         hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
234         if not os.path.exists(hook_script_path):
235             raise src.SatException(_("Hook script not found: %s") % 
236                                    hook_script_path)
237         
238         # Try to execute the script, catch the exception if it fails
239         try:
240             # import the module (in the sense of python)
241             pymodule = imp.load_source(cmd_name, hook_script_path)
242             
243             # format a message to be printed at hook execution
244             msg = src.printcolors.printcWarning(_("Run hook script"))
245             msg = "%s: %s\n" % (msg, 
246                                 src.printcolors.printcInfo(hook_script_path))
247             
248             # run the function run_pre_hook if this function is called 
249             # before the command, run_post_hook if it is called after
250             if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
251                 logger.write(msg, 1)
252                 pymodule.run_pre_hook(self.cfg, logger)
253             elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
254                 logger.write(msg, 1)
255                 pymodule.run_post_hook(self.cfg, logger)
256
257         except Exception as exc:
258             msg = _("Unable to run hook script: %s") % hook_script_path
259             msg += "\n" + str(exc)
260             raise src.SatException(msg)
261
262     def print_help(self, opt):
263         '''Prints help for a command. Function called when "sat -h <command>"
264         
265         :param argv str: the options passed (to get the command name)
266         '''
267         # if no command as argument (sat -h)
268         if len(opt)==0:
269             print_help()
270             return
271         # get command name
272         command = opt[0]
273         # read the configuration from all the pyconf files    
274         cfgManager = config.ConfigManager()
275         self.cfg = cfgManager.get_config(dataDir=self.dataDir)
276
277         # Check if this command exists
278         if not hasattr(self, command):
279             raise src.SatException(_("Command '%s' does not exist") % command)
280         
281         # Print salomeTools version
282         print_version()
283         
284         # load the module
285         module = self.get_module(command)
286
287         # print the description of the command that is done in the command file
288         if hasattr( module, "description" ) :
289             print(src.printcolors.printcHeader( _("Description:") ))
290             print(module.description() + '\n')
291
292         # print the description of the command options
293         if hasattr( module, "parser" ) :
294             module.parser.print_help()
295
296     def get_module(self, module):
297         '''Loads a command. Function called only by print_help
298         
299         :param module str: the command to load
300         '''
301         # Check if this command exists
302         if not hasattr(self, module):
303             raise src.SatException(_("Command '%s' does not exist") % module)
304
305         # load the module
306         (file_, pathname, description) = imp.find_module(module, [cmdsdir])
307         module = imp.load_module(module, file_, pathname, description)
308         return module
309  
310 def print_version():
311     '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
312     '''
313     # read the config 
314     cfgManager = config.ConfigManager()
315     cfg = cfgManager.get_config()
316     # print the key corresponding to salomeTools version
317     print(src.printcolors.printcHeader( _("Version: ") ) + 
318           cfg.INTERNAL.sat_version + '\n')
319
320
321 def print_help():
322     '''prints salomeTools general help
323     
324     :param options str: the options
325     '''
326     print_version()
327     
328     print(src.printcolors.printcHeader( _("Usage: ") ) + 
329           "sat [sat_options] <command> [product] [command_options]\n")
330
331     parser.print_help()
332
333     # display all the available commands.
334     print(src.printcolors.printcHeader(_("Available commands are:\n")))
335     for command in lCommand:
336         print(" - %s" % (command))
337         
338     # Explain how to get the help for a specific command
339     print(src.printcolors.printcHeader(_("\nGetting the help for a specific"
340                                     " command: ")) + "sat --help <command>\n")
341
342 def write_exception(exc):
343     '''write exception in case of error in a command
344     
345     :param exc exception: the exception to print
346     '''
347     sys.stderr.write("\n***** ")
348     sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
349     sys.stderr.write("\n" + str(exc) + "\n")
350
351 # ###############################
352 # MAIN : terminal command usage #
353 # ###############################
354 if __name__ == "__main__":  
355     # Initialize the code that will be returned by the terminal command 
356     code = 0
357     (options, args) = parser.parse_args(sys.argv[1:])
358     
359     # no arguments : print general help
360     if len(args) == 0:
361         print_help()
362         sys.exit(0)
363     
364     # instantiate the salomeTools class with correct options
365     sat = Sat(' '.join(sys.argv[1:]))
366     # the command called
367     command = args[0]
368     # get dynamically the command function to call
369     fun_command = sat.__getattr__(command)
370     # call the command with two cases : mode debug or not
371     if options.debug_mode:
372         # call classically the command and if it fails, 
373         # show exception and stack (usual python mode)
374         code = fun_command(' '.join(args[1:]))
375     else:
376         # catch exception in order to show less verbose but elegant message
377         try:
378             code = fun_command(' '.join(args[1:]))
379         except Exception as exc:
380             code = 1
381             write_exception(exc)
382     
383     # exit salomeTools with the right code (0 if no errors, else 1)
384     if code is None: code = 0
385     sys.exit(code)
386