Salome HOME
30a3697146d487234b7305c021d25b05f12b5a2c
[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 def find_command_list(dirPath):
48     ''' Parse files in dirPath that end with .py : it gives commands list
49     
50     :param dirPath str: The directory path where to search the commands
51     :return: cmd_list : the list containing the commands name 
52     :rtype: list
53     '''
54     cmd_list = []
55     for item in os.listdir(dirPath):
56         if item.endswith('.py'):
57             cmd_list.append(item[:-len('.py')])
58     return cmd_list
59
60 # The list of valid salomeTools commands
61 #lCommand = ['config', 'compile', 'prepare']
62 lCommand = find_command_list(cmdsdir)
63
64 # Define all possible option for salomeTools command :  sat <option> <args>
65 parser = src.options.Options()
66 parser.add_option('h', 'help', 'boolean', 'help', _("shows global help or help on a specific command."))
67 parser.add_option('o', 'overwrite', 'list', "overwrite", _("overwrites a configuration parameters."))
68 parser.add_option('g', 'debug', 'boolean', 'debug_mode', _("run salomeTools in debug mode."))
69 parser.add_option('l', 'level', 'int', "output_level", _("change output level (default is 3)."))
70 parser.add_option('s', 'silent', 'boolean', 'silent', _("do not write log or show errors."))
71
72 class Sat(object):
73     '''The main class that stores all the commands of salomeTools
74     '''
75     def __init__(self, opt='', dataDir=None):
76         '''Initialization
77         
78         :param opt str: The sat options 
79         :param: dataDir str : the directory that contain all the external data (like software pyconf and software scripts)
80         '''
81         # Read the salomeTools options (the list of possible options is at the beginning of this file)
82         try:
83             (options, argus) = parser.parse_args(opt.split(' '))
84         except Exception as exc:
85             write_exception(exc)
86             sys.exit(-1)
87
88         # initialization of class attributes       
89         self.__dict__ = dict()
90         self.cfg = None # the config that will be read using pyconf module
91         self.options = options # the options passed to salomeTools
92         self.dataDir = dataDir # default value will be <salomeTools root>/data
93         # set the commands by calling the dedicated function
94         self.__setCommands__(cmdsdir)
95         
96         # if the help option has been called, print help and exit
97         if options.help:
98             try:
99                 self.print_help(argus)
100                 sys.exit(0)
101             except Exception as exc:
102                 write_exception(exc)
103                 sys.exit(1)
104
105     def __getattr__(self, name):
106         ''' overwrite of __getattr__ function in order to display a customized message in case of a wrong call
107         
108         :param name str: The name of the attribute 
109         '''
110         if name in self.__dict__:
111             return self.__dict__[name]
112         else:
113             raise AttributeError(name + _(" is not a valid command"))
114     
115     def __setCommands__(self, dirPath):
116         '''set class attributes corresponding to all commands that are in the dirPath directory
117         
118         :param dirPath str: The directory path containing the commands 
119         '''
120         # loop on the commands name
121         for nameCmd in lCommand:
122             # load the module that has name nameCmd in dirPath
123             (file_, pathname, description) = imp.find_module(nameCmd, [dirPath])
124             module = imp.load_module(nameCmd, file_, pathname, description)
125             
126             def run_command(args='', logger=None):
127                 '''The function that will load the configuration (all pyconf)
128                 and return the function run of the command corresponding to module
129                 
130                 :param args str: The directory path containing the commands 
131                 '''
132                 argv = args.split(" ")
133                 
134                 # if it is provided by the command line, get the application
135                 appliToLoad = None
136                 if argv != [''] and argv[0][0] != "-":
137                     appliToLoad = argv[0].rstrip('*')
138                     argv = argv[1:]
139                 
140                 # read the configuration from all the pyconf files    
141                 cfgManager = config.ConfigManager()
142                 self.cfg = cfgManager.getConfig(dataDir=self.dataDir, application=appliToLoad, options=self.options, command=__nameCmd__)
143                     
144                 # set output level
145                 if self.options.output_level:
146                     self.cfg.USER.output_level = self.options.output_level
147                 if self.cfg.USER.output_level < 1:
148                     self.cfg.USER.output_level = 1
149
150                 # create log file, unless the command is called with a logger as parameter
151                 logger_command = src.logger.Logger(self.cfg, silent_sysstd=self.options.silent)
152                 if logger:
153                     logger_command = logger
154                 
155                 # Execute the run method of the command
156                 res = __module__.run(argv, self, logger_command)
157                 
158                 # put final attributes in xml log file (end time, total time, ...) and write it
159                 logger_command.endWrite()
160                 
161                 return res
162
163             # Make sure that run_command will be redefined at each iteration of the loop
164             globals_up = {}
165             globals_up.update(run_command.__globals__)
166             globals_up.update({'__nameCmd__': nameCmd, '__module__' : module})
167             func = types.FunctionType(run_command.__code__, globals_up, run_command.__name__,run_command.__defaults__, run_command.__closure__)
168
169             # set the attribute corresponding to the command
170             self.__setattr__(nameCmd, func)
171
172     def print_help(self, opt):
173         '''Prints help for a command. Function called when "sat -h <command>"
174         
175         :param argv str: the options passed (to get the command name)
176         '''
177         # if no command as argument (sat -h)
178         if len(opt)==0:
179             print_help()
180             return
181         # get command name
182         command = opt[0]
183         # read the configuration from all the pyconf files    
184         cfgManager = config.ConfigManager()
185         self.cfg = cfgManager.getConfig(dataDir=self.dataDir)
186
187         # Check if this command exists
188         if not hasattr(self, command):
189             raise src.SatException(_("Command '%s' does not exist") % command)
190         
191         # Print salomeTools version
192         print_version()
193         
194         # load the module
195         module = self.get_module(command)
196
197         # print the description of the command that is done in the command file
198         if hasattr( module, "description" ) :
199             print(src.printcolors.printcHeader( _("Description:") ))
200             print(module.description() + '\n')
201
202         # print the description of the command options
203         if hasattr( module, "parser" ) :
204             module.parser.print_help()
205
206     def get_module(self, module):
207         '''Loads a command. Function called only by print_help
208         
209         :param module str: the command to load
210         '''
211         # Check if this command exists
212         if not hasattr(self, module):
213             raise src.SatException(_("Command '%s' does not exist") % module)
214
215         # load the module
216         (file_, pathname, description) = imp.find_module(module, [cmdsdir])
217         module = imp.load_module(module, file_, pathname, description)
218         return module
219  
220 def print_version():
221     '''prints salomeTools version (in src/internal_config/salomeTools.pyconf)
222     '''
223     # read the config 
224     cfgManager = config.ConfigManager()
225     cfg = cfgManager.getConfig()
226     # print the key corresponding to salomeTools version
227     print(src.printcolors.printcHeader( _("Version: ") ) + cfg.INTERNAL.sat_version + '\n')
228
229
230 def print_help():
231     '''prints salomeTools general help
232     
233     :param options str: the options
234     '''
235     print_version()
236     
237     print(src.printcolors.printcHeader( _("Usage: ") ) + "sat [sat_options] <command> [product] [command_options]\n")
238
239     parser.print_help()
240
241     # display all the available commands.
242     print(src.printcolors.printcHeader(_("Available commands are:\n")))
243     for command in lCommand:
244         print(" - %s" % (command))
245         
246     # Explain how to get the help for a specific command
247     print(src.printcolors.printcHeader(_("\nGetting the help for a specific command: ")) + "sat --help <command>\n")
248
249 def write_exception(exc):
250     '''write exception in case of error in a command
251     
252     :param exc exception: the exception to print
253     '''
254     sys.stderr.write("\n***** ")
255     sys.stderr.write(src.printcolors.printcError("salomeTools ERROR:"))
256     sys.stderr.write("\n" + str(exc) + "\n")
257
258 # ###############################
259 # MAIN : terminal command usage #
260 # ###############################
261 if __name__ == "__main__":  
262     # Get the command line using sys.argv
263     cmd_line = " ".join(sys.argv)
264     # Initialize the code that will be returned by the terminal command 
265     code = 0
266     (options, args) = parser.parse_args(sys.argv[1:])
267     
268     # no arguments : print general help
269     if len(args) == 0:
270         print_help()
271         sys.exit(0)
272     
273     # instantiate the salomeTools class with correct options
274     sat = Sat(' '.join(sys.argv[1:]))
275     # the command called
276     command = args[0]
277     # get dynamically the command function to call
278     fun_command = sat.__getattr__(command)
279     # call the command with two cases : mode debug or not
280     if options.debug_mode:
281         # call classically the command and if it fails, show exception and stack (usual python mode)
282         code = fun_command(' '.join(args[1:]))
283     else:
284         # catch exception in order to show less verbose but elegant message
285         try:
286             code = fun_command(' '.join(args[1:]))
287         except Exception as exc:
288             code = 1
289             write_exception(exc)
290     
291     # exit salomeTools with the right code (0 if no errors, else 1)
292     if code is None: code = 0
293     sys.exit(code)
294